You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1169 lines
39KB

  1. /*
  2. * HTTP protocol for ffmpeg client
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "avformat.h"
  23. #include "internal.h"
  24. #include "network.h"
  25. #include "http.h"
  26. #include "os_support.h"
  27. #include "httpauth.h"
  28. #include "url.h"
  29. #include "libavutil/opt.h"
  30. #if CONFIG_ZLIB
  31. #include <zlib.h>
  32. #endif
  33. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  34. only a subset of it. */
  35. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  36. * to be large enough to fit the full request headers (including long
  37. * path names).
  38. */
  39. #define BUFFER_SIZE MAX_URL_SIZE
  40. #define MAX_REDIRECTS 8
  41. typedef struct {
  42. const AVClass *class;
  43. URLContext *hd;
  44. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  45. int line_count;
  46. int http_code;
  47. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  48. int64_t chunksize;
  49. char *content_type;
  50. char *user_agent;
  51. int64_t off, filesize, req_end_offset;
  52. int icy_data_read; ///< how much data was read since last ICY metadata packet
  53. int icy_metaint; ///< after how many bytes of read data a new metadata packet will be found
  54. char *location;
  55. HTTPAuthState auth_state;
  56. HTTPAuthState proxy_auth_state;
  57. char *headers;
  58. /* Set if the server correctly handles Connection: close and will close
  59. * the connection after feeding us the content. */
  60. int willclose;
  61. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  62. int chunked_post;
  63. /* A flag which indicates if the end of chunked encoding has been sent. */
  64. int end_chunked_post;
  65. /* A flag which indicates we have finished to read POST reply. */
  66. int end_header;
  67. /* A flag which indicates if we use persistent connections. */
  68. int multiple_requests;
  69. uint8_t *post_data;
  70. int post_datalen;
  71. int is_akamai;
  72. int is_mediagateway;
  73. char *mime_type;
  74. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  75. int icy;
  76. char *icy_metadata_headers;
  77. char *icy_metadata_packet;
  78. #if CONFIG_ZLIB
  79. int compressed;
  80. z_stream inflate_stream;
  81. uint8_t *inflate_buffer;
  82. #endif
  83. AVDictionary *chained_options;
  84. int send_expect_100;
  85. } HTTPContext;
  86. #define OFFSET(x) offsetof(HTTPContext, x)
  87. #define D AV_OPT_FLAG_DECODING_PARAM
  88. #define E AV_OPT_FLAG_ENCODING_PARAM
  89. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  90. static const AVOption options[] = {
  91. {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
  92. {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  93. {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  94. {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  95. {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
  96. {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
  97. {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
  98. {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  99. {"cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, {0}, 0, 0, D },
  100. {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
  101. {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  102. {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
  103. {"auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, {.i64 = HTTP_AUTH_NONE}, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D|E, "auth_type" },
  104. {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
  105. {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
  106. {"send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
  107. {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  108. {"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
  109. {"end_offset", "try to limit the request to bytes preceding this offset", OFFSET(req_end_offset), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
  110. {NULL}
  111. };
  112. #define HTTP_CLASS(flavor)\
  113. static const AVClass flavor ## _context_class = {\
  114. .class_name = #flavor,\
  115. .item_name = av_default_item_name,\
  116. .option = options,\
  117. .version = LIBAVUTIL_VERSION_INT,\
  118. }
  119. HTTP_CLASS(http);
  120. HTTP_CLASS(https);
  121. static int http_connect(URLContext *h, const char *path, const char *local_path,
  122. const char *hoststr, const char *auth,
  123. const char *proxyauth, int *new_location);
  124. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  125. {
  126. memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
  127. &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
  128. memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
  129. &((HTTPContext*)src->priv_data)->proxy_auth_state,
  130. sizeof(HTTPAuthState));
  131. }
  132. /* return non zero if error */
  133. static int http_open_cnx(URLContext *h, AVDictionary **options)
  134. {
  135. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  136. char hostname[1024], hoststr[1024], proto[10];
  137. char auth[1024], proxyauth[1024] = "";
  138. char path1[MAX_URL_SIZE];
  139. char buf[1024], urlbuf[MAX_URL_SIZE];
  140. int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
  141. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  142. HTTPContext *s = h->priv_data;
  143. /* fill the dest addr */
  144. redo:
  145. /* needed in any case to build the host string */
  146. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  147. hostname, sizeof(hostname), &port,
  148. path1, sizeof(path1), s->location);
  149. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  150. proxy_path = getenv("http_proxy");
  151. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  152. proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
  153. if (!strcmp(proto, "https")) {
  154. lower_proto = "tls";
  155. use_proxy = 0;
  156. if (port < 0)
  157. port = 443;
  158. }
  159. if (port < 0)
  160. port = 80;
  161. if (path1[0] == '\0')
  162. path = "/";
  163. else
  164. path = path1;
  165. local_path = path;
  166. if (use_proxy) {
  167. /* Reassemble the request URL without auth string - we don't
  168. * want to leak the auth to the proxy. */
  169. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  170. path1);
  171. path = urlbuf;
  172. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  173. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  174. }
  175. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  176. if (!s->hd) {
  177. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  178. &h->interrupt_callback, options);
  179. if (err < 0)
  180. goto fail;
  181. }
  182. cur_auth_type = s->auth_state.auth_type;
  183. cur_proxy_auth_type = s->auth_state.auth_type;
  184. if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
  185. goto fail;
  186. attempts++;
  187. if (s->http_code == 401) {
  188. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  189. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  190. ffurl_closep(&s->hd);
  191. goto redo;
  192. } else
  193. goto fail;
  194. }
  195. if (s->http_code == 407) {
  196. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  197. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  198. ffurl_closep(&s->hd);
  199. goto redo;
  200. } else
  201. goto fail;
  202. }
  203. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  204. && location_changed == 1) {
  205. /* url moved, get next */
  206. ffurl_closep(&s->hd);
  207. if (redirects++ >= MAX_REDIRECTS)
  208. return AVERROR(EIO);
  209. /* Restart the authentication process with the new target, which
  210. * might use a different auth mechanism. */
  211. memset(&s->auth_state, 0, sizeof(s->auth_state));
  212. attempts = 0;
  213. location_changed = 0;
  214. goto redo;
  215. }
  216. return 0;
  217. fail:
  218. if (s->hd)
  219. ffurl_closep(&s->hd);
  220. return AVERROR(EIO);
  221. }
  222. int ff_http_do_new_request(URLContext *h, const char *uri)
  223. {
  224. HTTPContext *s = h->priv_data;
  225. AVDictionary *options = NULL;
  226. int ret;
  227. s->off = 0;
  228. s->icy_data_read = 0;
  229. av_free(s->location);
  230. s->location = av_strdup(uri);
  231. if (!s->location)
  232. return AVERROR(ENOMEM);
  233. av_dict_copy(&options, s->chained_options, 0);
  234. ret = http_open_cnx(h, &options);
  235. av_dict_free(&options);
  236. return ret;
  237. }
  238. static int http_open(URLContext *h, const char *uri, int flags,
  239. AVDictionary **options)
  240. {
  241. HTTPContext *s = h->priv_data;
  242. int ret;
  243. if( s->seekable == 1 )
  244. h->is_streamed = 0;
  245. else
  246. h->is_streamed = 1;
  247. s->filesize = -1;
  248. s->location = av_strdup(uri);
  249. if (!s->location)
  250. return AVERROR(ENOMEM);
  251. if (options)
  252. av_dict_copy(&s->chained_options, *options, 0);
  253. if (s->headers) {
  254. int len = strlen(s->headers);
  255. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  256. av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
  257. }
  258. ret = http_open_cnx(h, options);
  259. if (ret < 0)
  260. av_dict_free(&s->chained_options);
  261. return ret;
  262. }
  263. static int http_getc(HTTPContext *s)
  264. {
  265. int len;
  266. if (s->buf_ptr >= s->buf_end) {
  267. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  268. if (len < 0) {
  269. return len;
  270. } else if (len == 0) {
  271. return AVERROR_EOF;
  272. } else {
  273. s->buf_ptr = s->buffer;
  274. s->buf_end = s->buffer + len;
  275. }
  276. }
  277. return *s->buf_ptr++;
  278. }
  279. static int http_get_line(HTTPContext *s, char *line, int line_size)
  280. {
  281. int ch;
  282. char *q;
  283. q = line;
  284. for(;;) {
  285. ch = http_getc(s);
  286. if (ch < 0)
  287. return ch;
  288. if (ch == '\n') {
  289. /* process line */
  290. if (q > line && q[-1] == '\r')
  291. q--;
  292. *q = '\0';
  293. return 0;
  294. } else {
  295. if ((q - line) < line_size - 1)
  296. *q++ = ch;
  297. }
  298. }
  299. }
  300. static int process_line(URLContext *h, char *line, int line_count,
  301. int *new_location)
  302. {
  303. HTTPContext *s = h->priv_data;
  304. char *tag, *p, *end;
  305. /* end of header */
  306. if (line[0] == '\0') {
  307. s->end_header = 1;
  308. return 0;
  309. }
  310. p = line;
  311. if (line_count == 0) {
  312. while (!av_isspace(*p) && *p != '\0')
  313. p++;
  314. while (av_isspace(*p))
  315. p++;
  316. s->http_code = strtol(p, &end, 10);
  317. av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
  318. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  319. * don't abort until all headers have been parsed. */
  320. if (s->http_code >= 400 && s->http_code < 600 &&
  321. (s->http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  322. (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  323. end += strspn(end, SPACE_CHARS);
  324. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", s->http_code, end);
  325. return AVERROR(EIO);
  326. }
  327. } else {
  328. while (*p != '\0' && *p != ':')
  329. p++;
  330. if (*p != ':')
  331. return 1;
  332. *p = '\0';
  333. tag = line;
  334. p++;
  335. while (av_isspace(*p))
  336. p++;
  337. if (!av_strcasecmp(tag, "Location")) {
  338. char redirected_location[MAX_URL_SIZE], *new_loc;
  339. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  340. s->location, p);
  341. new_loc = av_strdup(redirected_location);
  342. if (!new_loc)
  343. return AVERROR(ENOMEM);
  344. av_free(s->location);
  345. s->location = new_loc;
  346. *new_location = 1;
  347. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  348. s->filesize = strtoll(p, NULL, 10);
  349. } else if (!av_strcasecmp(tag, "Content-Range")) {
  350. /* "bytes $from-$to/$document_size" */
  351. const char *slash;
  352. if (!strncmp(p, "bytes ", 6)) {
  353. p += 6;
  354. s->off = strtoll(p, NULL, 10);
  355. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  356. s->filesize = strtoll(slash+1, NULL, 10);
  357. }
  358. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  359. h->is_streamed = 0; /* we _can_ in fact seek */
  360. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  361. !strncmp(p, "bytes", 5) &&
  362. s->seekable == -1) {
  363. h->is_streamed = 0;
  364. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  365. !av_strncasecmp(p, "chunked", 7)) {
  366. s->filesize = -1;
  367. s->chunksize = 0;
  368. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  369. ff_http_auth_handle_header(&s->auth_state, tag, p);
  370. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  371. ff_http_auth_handle_header(&s->auth_state, tag, p);
  372. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  373. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  374. } else if (!av_strcasecmp(tag, "Connection")) {
  375. if (!strcmp(p, "close"))
  376. s->willclose = 1;
  377. } else if (!av_strcasecmp (tag, "Server")) {
  378. if (!av_strcasecmp (p, "AkamaiGHost")) {
  379. s->is_akamai = 1;
  380. } else if (!av_strncasecmp (p, "MediaGateway", 12)) {
  381. s->is_mediagateway = 1;
  382. }
  383. } else if (!av_strcasecmp (tag, "Content-Type")) {
  384. av_free(s->mime_type); s->mime_type = av_strdup(p);
  385. } else if (!av_strcasecmp (tag, "Set-Cookie")) {
  386. if (!s->cookies) {
  387. if (!(s->cookies = av_strdup(p)))
  388. return AVERROR(ENOMEM);
  389. } else {
  390. char *tmp = s->cookies;
  391. size_t str_size = strlen(tmp) + strlen(p) + 2;
  392. if (!(s->cookies = av_malloc(str_size))) {
  393. s->cookies = tmp;
  394. return AVERROR(ENOMEM);
  395. }
  396. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  397. av_free(tmp);
  398. }
  399. } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
  400. s->icy_metaint = strtoll(p, NULL, 10);
  401. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  402. // Concat all Icy- header lines
  403. char *buf = av_asprintf("%s%s: %s\n",
  404. s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
  405. if (!buf)
  406. return AVERROR(ENOMEM);
  407. av_freep(&s->icy_metadata_headers);
  408. s->icy_metadata_headers = buf;
  409. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  410. if (!av_strncasecmp(p, "gzip", 4) ||
  411. !av_strncasecmp(p, "deflate", 7)) {
  412. #if CONFIG_ZLIB
  413. s->compressed = 1;
  414. inflateEnd(&s->inflate_stream);
  415. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  416. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  417. s->inflate_stream.msg);
  418. return AVERROR(ENOSYS);
  419. }
  420. if (zlibCompileFlags() & (1 << 17)) {
  421. av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
  422. return AVERROR(ENOSYS);
  423. }
  424. #else
  425. av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
  426. return AVERROR(ENOSYS);
  427. #endif
  428. } else if (!av_strncasecmp(p, "identity", 8)) {
  429. // The normal, no-encoding case (although servers shouldn't include
  430. // the header at all if this is the case).
  431. } else {
  432. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  433. }
  434. }
  435. }
  436. return 1;
  437. }
  438. /**
  439. * Create a string containing cookie values for use as a HTTP cookie header
  440. * field value for a particular path and domain from the cookie values stored in
  441. * the HTTP protocol context. The cookie string is stored in *cookies.
  442. *
  443. * @return a negative value if an error condition occurred, 0 otherwise
  444. */
  445. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  446. const char *domain)
  447. {
  448. // cookie strings will look like Set-Cookie header field values. Multiple
  449. // Set-Cookie fields will result in multiple values delimited by a newline
  450. int ret = 0;
  451. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  452. if (!set_cookies) return AVERROR(EINVAL);
  453. *cookies = NULL;
  454. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  455. int domain_offset = 0;
  456. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  457. set_cookies = NULL;
  458. while ((param = av_strtok(cookie, "; ", &next_param))) {
  459. cookie = NULL;
  460. if (!av_strncasecmp("path=", param, 5)) {
  461. av_free(cpath);
  462. cpath = av_strdup(&param[5]);
  463. } else if (!av_strncasecmp("domain=", param, 7)) {
  464. // if the cookie specifies a sub-domain, skip the leading dot thereby
  465. // supporting URLs that point to sub-domains and the master domain
  466. int leading_dot = (param[7] == '.');
  467. av_free(cdomain);
  468. cdomain = av_strdup(&param[7+leading_dot]);
  469. } else if (!av_strncasecmp("secure", param, 6) ||
  470. !av_strncasecmp("comment", param, 7) ||
  471. !av_strncasecmp("max-age", param, 7) ||
  472. !av_strncasecmp("version", param, 7)) {
  473. // ignore Comment, Max-Age, Secure and Version
  474. } else {
  475. av_free(cvalue);
  476. cvalue = av_strdup(param);
  477. }
  478. }
  479. if (!cdomain)
  480. cdomain = av_strdup(domain);
  481. // ensure all of the necessary values are valid
  482. if (!cdomain || !cpath || !cvalue) {
  483. av_log(s, AV_LOG_WARNING,
  484. "Invalid cookie found, no value, path or domain specified\n");
  485. goto done_cookie;
  486. }
  487. // check if the request path matches the cookie path
  488. if (av_strncasecmp(path, cpath, strlen(cpath)))
  489. goto done_cookie;
  490. // the domain should be at least the size of our cookie domain
  491. domain_offset = strlen(domain) - strlen(cdomain);
  492. if (domain_offset < 0)
  493. goto done_cookie;
  494. // match the cookie domain
  495. if (av_strcasecmp(&domain[domain_offset], cdomain))
  496. goto done_cookie;
  497. // cookie parameters match, so copy the value
  498. if (!*cookies) {
  499. if (!(*cookies = av_strdup(cvalue))) {
  500. ret = AVERROR(ENOMEM);
  501. goto done_cookie;
  502. }
  503. } else {
  504. char *tmp = *cookies;
  505. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  506. if (!(*cookies = av_malloc(str_size))) {
  507. ret = AVERROR(ENOMEM);
  508. goto done_cookie;
  509. }
  510. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  511. av_free(tmp);
  512. }
  513. done_cookie:
  514. av_free(cdomain);
  515. av_free(cpath);
  516. av_free(cvalue);
  517. if (ret < 0) {
  518. if (*cookies) av_freep(cookies);
  519. av_free(cset_cookies);
  520. return ret;
  521. }
  522. }
  523. av_free(cset_cookies);
  524. return 0;
  525. }
  526. static inline int has_header(const char *str, const char *header)
  527. {
  528. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  529. if (!str)
  530. return 0;
  531. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  532. }
  533. static int http_read_header(URLContext *h, int *new_location)
  534. {
  535. HTTPContext *s = h->priv_data;
  536. char line[MAX_URL_SIZE];
  537. int err = 0;
  538. s->chunksize = -1;
  539. for (;;) {
  540. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  541. return err;
  542. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  543. err = process_line(h, line, s->line_count, new_location);
  544. if (err < 0)
  545. return err;
  546. if (err == 0)
  547. break;
  548. s->line_count++;
  549. }
  550. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  551. h->is_streamed = 1; /* we can in fact _not_ seek */
  552. return err;
  553. }
  554. static int http_connect(URLContext *h, const char *path, const char *local_path,
  555. const char *hoststr, const char *auth,
  556. const char *proxyauth, int *new_location)
  557. {
  558. HTTPContext *s = h->priv_data;
  559. int post, err;
  560. char headers[4096] = "";
  561. char *authstr = NULL, *proxyauthstr = NULL;
  562. int64_t off = s->off;
  563. int len = 0;
  564. const char *method;
  565. int send_expect_100 = 0;
  566. /* send http header */
  567. post = h->flags & AVIO_FLAG_WRITE;
  568. if (s->post_data) {
  569. /* force POST method and disable chunked encoding when
  570. * custom HTTP post data is set */
  571. post = 1;
  572. s->chunked_post = 0;
  573. }
  574. method = post ? "POST" : "GET";
  575. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  576. method);
  577. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  578. local_path, method);
  579. if (post && !s->post_data) {
  580. send_expect_100 = s->send_expect_100;
  581. /* The user has supplied authentication but we don't know the auth type,
  582. * send Expect: 100-continue to get the 401 response including the
  583. * WWW-Authenticate header, or an 100 continue if no auth actually
  584. * is needed. */
  585. if (auth && *auth &&
  586. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  587. s->http_code != 401)
  588. send_expect_100 = 1;
  589. }
  590. /* set default headers if needed */
  591. if (!has_header(s->headers, "\r\nUser-Agent: "))
  592. len += av_strlcatf(headers + len, sizeof(headers) - len,
  593. "User-Agent: %s\r\n", s->user_agent);
  594. if (!has_header(s->headers, "\r\nAccept: "))
  595. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  596. sizeof(headers) - len);
  597. // Note: we send this on purpose even when s->off is 0 when we're probing,
  598. // since it allows us to detect more reliably if a (non-conforming)
  599. // server supports seeking by analysing the reply headers.
  600. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->req_end_offset || s->seekable == -1)) {
  601. len += av_strlcatf(headers + len, sizeof(headers) - len,
  602. "Range: bytes=%"PRId64"-", s->off);
  603. if (s->req_end_offset)
  604. len += av_strlcatf(headers + len, sizeof(headers) - len,
  605. "%"PRId64, s->req_end_offset - 1);
  606. len += av_strlcpy(headers + len, "\r\n",
  607. sizeof(headers) - len);
  608. }
  609. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  610. len += av_strlcatf(headers + len, sizeof(headers) - len,
  611. "Expect: 100-continue\r\n");
  612. if (!has_header(s->headers, "\r\nConnection: ")) {
  613. if (s->multiple_requests) {
  614. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  615. sizeof(headers) - len);
  616. } else {
  617. len += av_strlcpy(headers + len, "Connection: close\r\n",
  618. sizeof(headers) - len);
  619. }
  620. }
  621. if (!has_header(s->headers, "\r\nHost: "))
  622. len += av_strlcatf(headers + len, sizeof(headers) - len,
  623. "Host: %s\r\n", hoststr);
  624. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  625. len += av_strlcatf(headers + len, sizeof(headers) - len,
  626. "Content-Length: %d\r\n", s->post_datalen);
  627. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  628. len += av_strlcatf(headers + len, sizeof(headers) - len,
  629. "Content-Type: %s\r\n", s->content_type);
  630. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  631. char *cookies = NULL;
  632. if (!get_cookies(s, &cookies, path, hoststr)) {
  633. len += av_strlcatf(headers + len, sizeof(headers) - len,
  634. "Cookie: %s\r\n", cookies);
  635. av_free(cookies);
  636. }
  637. }
  638. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  639. len += av_strlcatf(headers + len, sizeof(headers) - len,
  640. "Icy-MetaData: %d\r\n", 1);
  641. }
  642. /* now add in custom headers */
  643. if (s->headers)
  644. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  645. snprintf(s->buffer, sizeof(s->buffer),
  646. "%s %s HTTP/1.1\r\n"
  647. "%s"
  648. "%s"
  649. "%s"
  650. "%s%s"
  651. "\r\n",
  652. method,
  653. path,
  654. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  655. headers,
  656. authstr ? authstr : "",
  657. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  658. av_freep(&authstr);
  659. av_freep(&proxyauthstr);
  660. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  661. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  662. return err;
  663. if (s->post_data)
  664. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  665. return err;
  666. /* init input buffer */
  667. s->buf_ptr = s->buffer;
  668. s->buf_end = s->buffer;
  669. s->line_count = 0;
  670. s->off = 0;
  671. s->icy_data_read = 0;
  672. s->filesize = -1;
  673. s->willclose = 0;
  674. s->end_chunked_post = 0;
  675. s->end_header = 0;
  676. if (post && !s->post_data && !send_expect_100) {
  677. /* Pretend that it did work. We didn't read any header yet, since
  678. * we've still to send the POST data, but the code calling this
  679. * function will check http_code after we return. */
  680. s->http_code = 200;
  681. return 0;
  682. }
  683. /* wait for header */
  684. err = http_read_header(h, new_location);
  685. if (err < 0)
  686. return err;
  687. return (off == s->off) ? 0 : -1;
  688. }
  689. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  690. {
  691. HTTPContext *s = h->priv_data;
  692. int len;
  693. /* read bytes from input buffer first */
  694. len = s->buf_end - s->buf_ptr;
  695. if (len > 0) {
  696. if (len > size)
  697. len = size;
  698. memcpy(buf, s->buf_ptr, len);
  699. s->buf_ptr += len;
  700. } else {
  701. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  702. return AVERROR_EOF;
  703. len = ffurl_read(s->hd, buf, size);
  704. }
  705. if (len > 0) {
  706. s->off += len;
  707. if (s->chunksize > 0)
  708. s->chunksize -= len;
  709. }
  710. return len;
  711. }
  712. #if CONFIG_ZLIB
  713. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  714. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  715. {
  716. HTTPContext *s = h->priv_data;
  717. int ret;
  718. if (!s->inflate_buffer) {
  719. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  720. if (!s->inflate_buffer)
  721. return AVERROR(ENOMEM);
  722. }
  723. if (s->inflate_stream.avail_in == 0) {
  724. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  725. if (read <= 0)
  726. return read;
  727. s->inflate_stream.next_in = s->inflate_buffer;
  728. s->inflate_stream.avail_in = read;
  729. }
  730. s->inflate_stream.avail_out = size;
  731. s->inflate_stream.next_out = buf;
  732. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  733. if (ret != Z_OK && ret != Z_STREAM_END)
  734. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  735. return size - s->inflate_stream.avail_out;
  736. }
  737. #endif
  738. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  739. {
  740. HTTPContext *s = h->priv_data;
  741. int err, new_location;
  742. if (!s->hd)
  743. return AVERROR_EOF;
  744. if (s->end_chunked_post && !s->end_header) {
  745. err = http_read_header(h, &new_location);
  746. if (err < 0)
  747. return err;
  748. }
  749. if (s->chunksize >= 0) {
  750. if (!s->chunksize) {
  751. char line[32];
  752. for(;;) {
  753. do {
  754. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  755. return err;
  756. } while (!*line); /* skip CR LF from last chunk */
  757. s->chunksize = strtoll(line, NULL, 16);
  758. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  759. if (!s->chunksize)
  760. return 0;
  761. break;
  762. }
  763. }
  764. size = FFMIN(size, s->chunksize);
  765. }
  766. #if CONFIG_ZLIB
  767. if (s->compressed)
  768. return http_buf_read_compressed(h, buf, size);
  769. #endif
  770. return http_buf_read(h, buf, size);
  771. }
  772. // Like http_read_stream(), but no short reads.
  773. // Assumes partial reads are an error.
  774. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  775. {
  776. int pos = 0;
  777. while (pos < size) {
  778. int len = http_read_stream(h, buf + pos, size - pos);
  779. if (len < 0)
  780. return len;
  781. pos += len;
  782. }
  783. return pos;
  784. }
  785. static int http_read(URLContext *h, uint8_t *buf, int size)
  786. {
  787. HTTPContext *s = h->priv_data;
  788. if (s->icy_metaint > 0) {
  789. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  790. if (!remaining) {
  791. // The metadata packet is variable sized. It has a 1 byte header
  792. // which sets the length of the packet (divided by 16). If it's 0,
  793. // the metadata doesn't change. After the packet, icy_metaint bytes
  794. // of normal data follow.
  795. uint8_t ch;
  796. int len = http_read_stream_all(h, &ch, 1);
  797. if (len < 1)
  798. return len;
  799. if (ch > 0) {
  800. char data[255 * 16 + 1];
  801. int ret;
  802. len = ch * 16;
  803. ret = http_read_stream_all(h, data, len);
  804. if (ret < len)
  805. return ret;
  806. data[len + 1] = 0;
  807. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  808. return ret;
  809. }
  810. s->icy_data_read = 0;
  811. remaining = s->icy_metaint;
  812. }
  813. size = FFMIN(size, remaining);
  814. }
  815. size = http_read_stream(h, buf, size);
  816. if (size > 0)
  817. s->icy_data_read += size;
  818. return size;
  819. }
  820. /* used only when posting data */
  821. static int http_write(URLContext *h, const uint8_t *buf, int size)
  822. {
  823. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  824. int ret;
  825. char crlf[] = "\r\n";
  826. HTTPContext *s = h->priv_data;
  827. if (!s->chunked_post) {
  828. /* non-chunked data is sent without any special encoding */
  829. return ffurl_write(s->hd, buf, size);
  830. }
  831. /* silently ignore zero-size data since chunk encoding that would
  832. * signal EOF */
  833. if (size > 0) {
  834. /* upload data using chunked encoding */
  835. snprintf(temp, sizeof(temp), "%x\r\n", size);
  836. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  837. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  838. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  839. return ret;
  840. }
  841. return size;
  842. }
  843. static int http_shutdown(URLContext *h, int flags)
  844. {
  845. int ret = 0;
  846. char footer[] = "0\r\n\r\n";
  847. HTTPContext *s = h->priv_data;
  848. /* signal end of chunked encoding if used */
  849. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  850. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  851. ret = ret > 0 ? 0 : ret;
  852. s->end_chunked_post = 1;
  853. }
  854. return ret;
  855. }
  856. static int http_close(URLContext *h)
  857. {
  858. int ret = 0;
  859. HTTPContext *s = h->priv_data;
  860. #if CONFIG_ZLIB
  861. inflateEnd(&s->inflate_stream);
  862. av_freep(&s->inflate_buffer);
  863. #endif
  864. if (!s->end_chunked_post) {
  865. /* Close the write direction by sending the end of chunked encoding. */
  866. ret = http_shutdown(h, h->flags);
  867. }
  868. if (s->hd)
  869. ffurl_closep(&s->hd);
  870. av_dict_free(&s->chained_options);
  871. return ret;
  872. }
  873. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  874. {
  875. HTTPContext *s = h->priv_data;
  876. URLContext *old_hd = s->hd;
  877. int64_t old_off = s->off;
  878. uint8_t old_buf[BUFFER_SIZE];
  879. int old_buf_size, ret;
  880. AVDictionary *options = NULL;
  881. if (whence == AVSEEK_SIZE)
  882. return s->filesize;
  883. else if ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))
  884. return s->off;
  885. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  886. return AVERROR(ENOSYS);
  887. if (whence == SEEK_CUR)
  888. off += s->off;
  889. else if (whence == SEEK_END)
  890. off += s->filesize;
  891. else if (whence != SEEK_SET)
  892. return AVERROR(EINVAL);
  893. if (off < 0)
  894. return AVERROR(EINVAL);
  895. s->off = off;
  896. /* we save the old context in case the seek fails */
  897. old_buf_size = s->buf_end - s->buf_ptr;
  898. memcpy(old_buf, s->buf_ptr, old_buf_size);
  899. s->hd = NULL;
  900. /* if it fails, continue on old connection */
  901. av_dict_copy(&options, s->chained_options, 0);
  902. if ((ret = http_open_cnx(h, &options)) < 0) {
  903. av_dict_free(&options);
  904. memcpy(s->buffer, old_buf, old_buf_size);
  905. s->buf_ptr = s->buffer;
  906. s->buf_end = s->buffer + old_buf_size;
  907. s->hd = old_hd;
  908. s->off = old_off;
  909. return ret;
  910. }
  911. av_dict_free(&options);
  912. ffurl_close(old_hd);
  913. return off;
  914. }
  915. static int
  916. http_get_file_handle(URLContext *h)
  917. {
  918. HTTPContext *s = h->priv_data;
  919. return ffurl_get_file_handle(s->hd);
  920. }
  921. #if CONFIG_HTTP_PROTOCOL
  922. URLProtocol ff_http_protocol = {
  923. .name = "http",
  924. .url_open2 = http_open,
  925. .url_read = http_read,
  926. .url_write = http_write,
  927. .url_seek = http_seek,
  928. .url_close = http_close,
  929. .url_get_file_handle = http_get_file_handle,
  930. .url_shutdown = http_shutdown,
  931. .priv_data_size = sizeof(HTTPContext),
  932. .priv_data_class = &http_context_class,
  933. .flags = URL_PROTOCOL_FLAG_NETWORK,
  934. };
  935. #endif
  936. #if CONFIG_HTTPS_PROTOCOL
  937. URLProtocol ff_https_protocol = {
  938. .name = "https",
  939. .url_open2 = http_open,
  940. .url_read = http_read,
  941. .url_write = http_write,
  942. .url_seek = http_seek,
  943. .url_close = http_close,
  944. .url_get_file_handle = http_get_file_handle,
  945. .url_shutdown = http_shutdown,
  946. .priv_data_size = sizeof(HTTPContext),
  947. .priv_data_class = &https_context_class,
  948. .flags = URL_PROTOCOL_FLAG_NETWORK,
  949. };
  950. #endif
  951. #if CONFIG_HTTPPROXY_PROTOCOL
  952. static int http_proxy_close(URLContext *h)
  953. {
  954. HTTPContext *s = h->priv_data;
  955. if (s->hd)
  956. ffurl_closep(&s->hd);
  957. return 0;
  958. }
  959. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  960. {
  961. HTTPContext *s = h->priv_data;
  962. char hostname[1024], hoststr[1024];
  963. char auth[1024], pathbuf[1024], *path;
  964. char lower_url[100];
  965. int port, ret = 0, attempts = 0;
  966. HTTPAuthType cur_auth_type;
  967. char *authstr;
  968. int new_loc;
  969. if( s->seekable == 1 )
  970. h->is_streamed = 0;
  971. else
  972. h->is_streamed = 1;
  973. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  974. pathbuf, sizeof(pathbuf), uri);
  975. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  976. path = pathbuf;
  977. if (*path == '/')
  978. path++;
  979. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  980. NULL);
  981. redo:
  982. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  983. &h->interrupt_callback, NULL);
  984. if (ret < 0)
  985. return ret;
  986. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  987. path, "CONNECT");
  988. snprintf(s->buffer, sizeof(s->buffer),
  989. "CONNECT %s HTTP/1.1\r\n"
  990. "Host: %s\r\n"
  991. "Connection: close\r\n"
  992. "%s%s"
  993. "\r\n",
  994. path,
  995. hoststr,
  996. authstr ? "Proxy-" : "", authstr ? authstr : "");
  997. av_freep(&authstr);
  998. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  999. goto fail;
  1000. s->buf_ptr = s->buffer;
  1001. s->buf_end = s->buffer;
  1002. s->line_count = 0;
  1003. s->filesize = -1;
  1004. cur_auth_type = s->proxy_auth_state.auth_type;
  1005. /* Note: This uses buffering, potentially reading more than the
  1006. * HTTP header. If tunneling a protocol where the server starts
  1007. * the conversation, we might buffer part of that here, too.
  1008. * Reading that requires using the proper ffurl_read() function
  1009. * on this URLContext, not using the fd directly (as the tls
  1010. * protocol does). This shouldn't be an issue for tls though,
  1011. * since the client starts the conversation there, so there
  1012. * is no extra data that we might buffer up here.
  1013. */
  1014. ret = http_read_header(h, &new_loc);
  1015. if (ret < 0)
  1016. goto fail;
  1017. attempts++;
  1018. if (s->http_code == 407 &&
  1019. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1020. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1021. ffurl_closep(&s->hd);
  1022. goto redo;
  1023. }
  1024. if (s->http_code < 400)
  1025. return 0;
  1026. ret = AVERROR(EIO);
  1027. fail:
  1028. http_proxy_close(h);
  1029. return ret;
  1030. }
  1031. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1032. {
  1033. HTTPContext *s = h->priv_data;
  1034. return ffurl_write(s->hd, buf, size);
  1035. }
  1036. URLProtocol ff_httpproxy_protocol = {
  1037. .name = "httpproxy",
  1038. .url_open = http_proxy_open,
  1039. .url_read = http_buf_read,
  1040. .url_write = http_proxy_write,
  1041. .url_close = http_proxy_close,
  1042. .url_get_file_handle = http_get_file_handle,
  1043. .priv_data_size = sizeof(HTTPContext),
  1044. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1045. };
  1046. #endif