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.

1232 lines
40KB

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