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.

1107 lines
37KB

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