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.

1108 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 },
  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. /* end of header */
  292. if (line[0] == '\0') {
  293. s->end_header = 1;
  294. return 0;
  295. }
  296. p = line;
  297. if (line_count == 0) {
  298. while (!av_isspace(*p) && *p != '\0')
  299. p++;
  300. while (av_isspace(*p))
  301. p++;
  302. s->http_code = strtol(p, &end, 10);
  303. av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
  304. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  305. * don't abort until all headers have been parsed. */
  306. if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
  307. || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  308. (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  309. end += strspn(end, SPACE_CHARS);
  310. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
  311. s->http_code, end);
  312. return -1;
  313. }
  314. } else {
  315. while (*p != '\0' && *p != ':')
  316. p++;
  317. if (*p != ':')
  318. return 1;
  319. *p = '\0';
  320. tag = line;
  321. p++;
  322. while (av_isspace(*p))
  323. p++;
  324. if (!av_strcasecmp(tag, "Location")) {
  325. char redirected_location[MAX_URL_SIZE];
  326. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  327. s->location, p);
  328. av_strlcpy(s->location, redirected_location, sizeof(s->location));
  329. *new_location = 1;
  330. } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
  331. s->filesize = strtoll(p, NULL, 10);
  332. } else if (!av_strcasecmp (tag, "Content-Range")) {
  333. /* "bytes $from-$to/$document_size" */
  334. const char *slash;
  335. if (!strncmp (p, "bytes ", 6)) {
  336. p += 6;
  337. s->off = strtoll(p, NULL, 10);
  338. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  339. s->filesize = strtoll(slash+1, NULL, 10);
  340. }
  341. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  342. h->is_streamed = 0; /* we _can_ in fact seek */
  343. } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
  344. h->is_streamed = 0;
  345. } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
  346. s->filesize = -1;
  347. s->chunksize = 0;
  348. } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
  349. ff_http_auth_handle_header(&s->auth_state, tag, p);
  350. } else if (!av_strcasecmp (tag, "Authentication-Info")) {
  351. ff_http_auth_handle_header(&s->auth_state, tag, p);
  352. } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
  353. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  354. } else if (!av_strcasecmp (tag, "Connection")) {
  355. if (!strcmp(p, "close"))
  356. s->willclose = 1;
  357. } else if (!av_strcasecmp (tag, "Server")) {
  358. if (!av_strcasecmp (p, "AkamaiGHost")) {
  359. s->is_akamai = 1;
  360. } else if (!av_strncasecmp (p, "MediaGateway", 12)) {
  361. s->is_mediagateway = 1;
  362. }
  363. } else if (!av_strcasecmp (tag, "Content-Type")) {
  364. av_free(s->mime_type); s->mime_type = av_strdup(p);
  365. } else if (!av_strcasecmp (tag, "Set-Cookie")) {
  366. if (!s->cookies) {
  367. if (!(s->cookies = av_strdup(p)))
  368. return AVERROR(ENOMEM);
  369. } else {
  370. char *tmp = s->cookies;
  371. size_t str_size = strlen(tmp) + strlen(p) + 2;
  372. if (!(s->cookies = av_malloc(str_size))) {
  373. s->cookies = tmp;
  374. return AVERROR(ENOMEM);
  375. }
  376. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  377. av_free(tmp);
  378. }
  379. } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
  380. s->icy_metaint = strtoll(p, NULL, 10);
  381. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  382. // Concat all Icy- header lines
  383. char *buf = av_asprintf("%s%s: %s\n",
  384. s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
  385. if (!buf)
  386. return AVERROR(ENOMEM);
  387. av_freep(&s->icy_metadata_headers);
  388. s->icy_metadata_headers = buf;
  389. } else if (!av_strcasecmp (tag, "Content-Encoding")) {
  390. if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
  391. #if CONFIG_ZLIB
  392. s->compressed = 1;
  393. inflateEnd(&s->inflate_stream);
  394. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  395. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  396. s->inflate_stream.msg);
  397. return AVERROR(ENOSYS);
  398. }
  399. if (zlibCompileFlags() & (1 << 17)) {
  400. av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
  401. return AVERROR(ENOSYS);
  402. }
  403. #else
  404. av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
  405. return AVERROR(ENOSYS);
  406. #endif
  407. } else if (!av_strncasecmp(p, "identity", 8)) {
  408. // The normal, no-encoding case (although servers shouldn't include
  409. // the header at all if this is the case).
  410. } else {
  411. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  412. }
  413. }
  414. }
  415. return 1;
  416. }
  417. /**
  418. * Create a string containing cookie values for use as a HTTP cookie header
  419. * field value for a particular path and domain from the cookie values stored in
  420. * the HTTP protocol context. The cookie string is stored in *cookies.
  421. *
  422. * @return a negative value if an error condition occurred, 0 otherwise
  423. */
  424. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  425. const char *domain)
  426. {
  427. // cookie strings will look like Set-Cookie header field values. Multiple
  428. // Set-Cookie fields will result in multiple values delimited by a newline
  429. int ret = 0;
  430. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  431. if (!set_cookies) return AVERROR(EINVAL);
  432. *cookies = NULL;
  433. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  434. int domain_offset = 0;
  435. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  436. set_cookies = NULL;
  437. while ((param = av_strtok(cookie, "; ", &next_param))) {
  438. cookie = NULL;
  439. if (!av_strncasecmp("path=", param, 5)) {
  440. av_free(cpath);
  441. cpath = av_strdup(&param[5]);
  442. } else if (!av_strncasecmp("domain=", param, 7)) {
  443. av_free(cdomain);
  444. cdomain = av_strdup(&param[7]);
  445. } else if (!av_strncasecmp("secure", param, 6) ||
  446. !av_strncasecmp("comment", param, 7) ||
  447. !av_strncasecmp("max-age", param, 7) ||
  448. !av_strncasecmp("version", param, 7)) {
  449. // ignore Comment, Max-Age, Secure and Version
  450. } else {
  451. av_free(cvalue);
  452. cvalue = av_strdup(param);
  453. }
  454. }
  455. if (!cdomain)
  456. cdomain = av_strdup(domain);
  457. // ensure all of the necessary values are valid
  458. if (!cdomain || !cpath || !cvalue) {
  459. av_log(s, AV_LOG_WARNING,
  460. "Invalid cookie found, no value, path or domain specified\n");
  461. goto done_cookie;
  462. }
  463. // check if the request path matches the cookie path
  464. if (av_strncasecmp(path, cpath, strlen(cpath)))
  465. goto done_cookie;
  466. // the domain should be at least the size of our cookie domain
  467. domain_offset = strlen(domain) - strlen(cdomain);
  468. if (domain_offset < 0)
  469. goto done_cookie;
  470. // match the cookie domain
  471. if (av_strcasecmp(&domain[domain_offset], cdomain))
  472. goto done_cookie;
  473. // cookie parameters match, so copy the value
  474. if (!*cookies) {
  475. if (!(*cookies = av_strdup(cvalue))) {
  476. ret = AVERROR(ENOMEM);
  477. goto done_cookie;
  478. }
  479. } else {
  480. char *tmp = *cookies;
  481. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  482. if (!(*cookies = av_malloc(str_size))) {
  483. ret = AVERROR(ENOMEM);
  484. goto done_cookie;
  485. }
  486. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  487. av_free(tmp);
  488. }
  489. done_cookie:
  490. av_free(cdomain);
  491. av_free(cpath);
  492. av_free(cvalue);
  493. if (ret < 0) {
  494. if (*cookies) av_freep(cookies);
  495. av_free(cset_cookies);
  496. return ret;
  497. }
  498. }
  499. av_free(cset_cookies);
  500. return 0;
  501. }
  502. static inline int has_header(const char *str, const char *header)
  503. {
  504. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  505. if (!str)
  506. return 0;
  507. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  508. }
  509. static int http_read_header(URLContext *h, int *new_location)
  510. {
  511. HTTPContext *s = h->priv_data;
  512. char line[MAX_URL_SIZE];
  513. int err = 0;
  514. s->chunksize = -1;
  515. for (;;) {
  516. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  517. return err;
  518. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  519. err = process_line(h, line, s->line_count, new_location);
  520. if (err < 0)
  521. return err;
  522. if (err == 0)
  523. break;
  524. s->line_count++;
  525. }
  526. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  527. h->is_streamed = 1; /* we can in fact _not_ seek */
  528. return err;
  529. }
  530. static int http_connect(URLContext *h, const char *path, const char *local_path,
  531. const char *hoststr, const char *auth,
  532. const char *proxyauth, int *new_location)
  533. {
  534. HTTPContext *s = h->priv_data;
  535. int post, err;
  536. char headers[4096] = "";
  537. char *authstr = NULL, *proxyauthstr = NULL;
  538. int64_t off = s->off;
  539. int len = 0;
  540. const char *method;
  541. int send_expect_100 = 0;
  542. /* send http header */
  543. post = h->flags & AVIO_FLAG_WRITE;
  544. if (s->post_data) {
  545. /* force POST method and disable chunked encoding when
  546. * custom HTTP post data is set */
  547. post = 1;
  548. s->chunked_post = 0;
  549. }
  550. method = post ? "POST" : "GET";
  551. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  552. method);
  553. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  554. local_path, method);
  555. if (post && !s->post_data) {
  556. send_expect_100 = s->send_expect_100;
  557. /* The user has supplied authentication but we don't know the auth type,
  558. * send Expect: 100-continue to get the 401 response including the
  559. * WWW-Authenticate header, or an 100 continue if no auth actually
  560. * is needed. */
  561. if (auth && *auth &&
  562. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  563. s->http_code != 401)
  564. send_expect_100 = 1;
  565. }
  566. /* set default headers if needed */
  567. if (!has_header(s->headers, "\r\nUser-Agent: "))
  568. len += av_strlcatf(headers + len, sizeof(headers) - len,
  569. "User-Agent: %s\r\n", s->user_agent);
  570. if (!has_header(s->headers, "\r\nAccept: "))
  571. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  572. sizeof(headers) - len);
  573. // Note: we send this on purpose even when s->off is 0 when we're probing,
  574. // since it allows us to detect more reliably if a (non-conforming)
  575. // server supports seeking by analysing the reply headers.
  576. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
  577. len += av_strlcatf(headers + len, sizeof(headers) - len,
  578. "Range: bytes=%"PRId64"-\r\n", s->off);
  579. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  580. len += av_strlcatf(headers + len, sizeof(headers) - len,
  581. "Expect: 100-continue\r\n");
  582. if (!has_header(s->headers, "\r\nConnection: ")) {
  583. if (s->multiple_requests) {
  584. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  585. sizeof(headers) - len);
  586. } else {
  587. len += av_strlcpy(headers + len, "Connection: close\r\n",
  588. sizeof(headers) - len);
  589. }
  590. }
  591. if (!has_header(s->headers, "\r\nHost: "))
  592. len += av_strlcatf(headers + len, sizeof(headers) - len,
  593. "Host: %s\r\n", hoststr);
  594. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  595. len += av_strlcatf(headers + len, sizeof(headers) - len,
  596. "Content-Length: %d\r\n", s->post_datalen);
  597. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  598. len += av_strlcatf(headers + len, sizeof(headers) - len,
  599. "Content-Type: %s\r\n", s->content_type);
  600. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  601. char *cookies = NULL;
  602. if (!get_cookies(s, &cookies, path, hoststr)) {
  603. len += av_strlcatf(headers + len, sizeof(headers) - len,
  604. "Cookie: %s\r\n", cookies);
  605. av_free(cookies);
  606. }
  607. }
  608. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  609. len += av_strlcatf(headers + len, sizeof(headers) - len,
  610. "Icy-MetaData: %d\r\n", 1);
  611. }
  612. /* now add in custom headers */
  613. if (s->headers)
  614. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  615. snprintf(s->buffer, sizeof(s->buffer),
  616. "%s %s HTTP/1.1\r\n"
  617. "%s"
  618. "%s"
  619. "%s"
  620. "%s%s"
  621. "\r\n",
  622. method,
  623. path,
  624. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  625. headers,
  626. authstr ? authstr : "",
  627. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  628. av_freep(&authstr);
  629. av_freep(&proxyauthstr);
  630. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  631. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  632. return err;
  633. if (s->post_data)
  634. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  635. return err;
  636. /* init input buffer */
  637. s->buf_ptr = s->buffer;
  638. s->buf_end = s->buffer;
  639. s->line_count = 0;
  640. s->off = 0;
  641. s->icy_data_read = 0;
  642. s->filesize = -1;
  643. s->willclose = 0;
  644. s->end_chunked_post = 0;
  645. s->end_header = 0;
  646. if (post && !s->post_data && !send_expect_100) {
  647. /* Pretend that it did work. We didn't read any header yet, since
  648. * we've still to send the POST data, but the code calling this
  649. * function will check http_code after we return. */
  650. s->http_code = 200;
  651. return 0;
  652. }
  653. /* wait for header */
  654. err = http_read_header(h, new_location);
  655. if (err < 0)
  656. return err;
  657. return (off == s->off) ? 0 : -1;
  658. }
  659. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  660. {
  661. HTTPContext *s = h->priv_data;
  662. int len;
  663. /* read bytes from input buffer first */
  664. len = s->buf_end - s->buf_ptr;
  665. if (len > 0) {
  666. if (len > size)
  667. len = size;
  668. memcpy(buf, s->buf_ptr, len);
  669. s->buf_ptr += len;
  670. } else {
  671. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  672. return AVERROR_EOF;
  673. len = ffurl_read(s->hd, buf, size);
  674. }
  675. if (len > 0) {
  676. s->off += len;
  677. s->icy_data_read += len;
  678. if (s->chunksize > 0)
  679. s->chunksize -= len;
  680. }
  681. return len;
  682. }
  683. #if CONFIG_ZLIB
  684. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  685. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  686. {
  687. HTTPContext *s = h->priv_data;
  688. int ret;
  689. if (!s->inflate_buffer) {
  690. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  691. if (!s->inflate_buffer)
  692. return AVERROR(ENOMEM);
  693. }
  694. if (s->inflate_stream.avail_in == 0) {
  695. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  696. if (read <= 0)
  697. return read;
  698. s->inflate_stream.next_in = s->inflate_buffer;
  699. s->inflate_stream.avail_in = read;
  700. }
  701. s->inflate_stream.avail_out = size;
  702. s->inflate_stream.next_out = buf;
  703. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  704. if (ret != Z_OK && ret != Z_STREAM_END)
  705. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  706. return size - s->inflate_stream.avail_out;
  707. }
  708. #endif
  709. static int http_read(URLContext *h, uint8_t *buf, int size)
  710. {
  711. HTTPContext *s = h->priv_data;
  712. int err, new_location;
  713. if (!s->hd)
  714. return AVERROR_EOF;
  715. if (s->end_chunked_post && !s->end_header) {
  716. err = http_read_header(h, &new_location);
  717. if (err < 0)
  718. return err;
  719. }
  720. if (s->chunksize >= 0) {
  721. if (!s->chunksize) {
  722. char line[32];
  723. for(;;) {
  724. do {
  725. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  726. return err;
  727. } while (!*line); /* skip CR LF from last chunk */
  728. s->chunksize = strtoll(line, NULL, 16);
  729. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  730. if (!s->chunksize)
  731. return 0;
  732. break;
  733. }
  734. }
  735. size = FFMIN(size, s->chunksize);
  736. }
  737. if (s->icy_metaint > 0) {
  738. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  739. if (!remaining) {
  740. // The metadata packet is variable sized. It has a 1 byte header
  741. // which sets the length of the packet (divided by 16). If it's 0,
  742. // the metadata doesn't change. After the packet, icy_metaint bytes
  743. // of normal data follow.
  744. int ch = http_getc(s);
  745. if (ch < 0)
  746. return ch;
  747. if (ch > 0) {
  748. char data[255 * 16 + 1];
  749. int n;
  750. int ret;
  751. ch *= 16;
  752. for (n = 0; n < ch; n++)
  753. data[n] = http_getc(s);
  754. data[ch + 1] = 0;
  755. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  756. return ret;
  757. }
  758. s->icy_data_read = 0;
  759. remaining = s->icy_metaint;
  760. }
  761. size = FFMIN(size, remaining);
  762. }
  763. #if CONFIG_ZLIB
  764. if (s->compressed)
  765. return http_buf_read_compressed(h, buf, size);
  766. #endif
  767. return http_buf_read(h, buf, size);
  768. }
  769. /* used only when posting data */
  770. static int http_write(URLContext *h, const uint8_t *buf, int size)
  771. {
  772. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  773. int ret;
  774. char crlf[] = "\r\n";
  775. HTTPContext *s = h->priv_data;
  776. if (!s->chunked_post) {
  777. /* non-chunked data is sent without any special encoding */
  778. return ffurl_write(s->hd, buf, size);
  779. }
  780. /* silently ignore zero-size data since chunk encoding that would
  781. * signal EOF */
  782. if (size > 0) {
  783. /* upload data using chunked encoding */
  784. snprintf(temp, sizeof(temp), "%x\r\n", size);
  785. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  786. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  787. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  788. return ret;
  789. }
  790. return size;
  791. }
  792. static int http_shutdown(URLContext *h, int flags)
  793. {
  794. int ret = 0;
  795. char footer[] = "0\r\n\r\n";
  796. HTTPContext *s = h->priv_data;
  797. /* signal end of chunked encoding if used */
  798. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  799. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  800. ret = ret > 0 ? 0 : ret;
  801. s->end_chunked_post = 1;
  802. }
  803. return ret;
  804. }
  805. static int http_close(URLContext *h)
  806. {
  807. int ret = 0;
  808. HTTPContext *s = h->priv_data;
  809. #if CONFIG_ZLIB
  810. inflateEnd(&s->inflate_stream);
  811. av_freep(&s->inflate_buffer);
  812. #endif
  813. if (!s->end_chunked_post) {
  814. /* Close the write direction by sending the end of chunked encoding. */
  815. ret = http_shutdown(h, h->flags);
  816. }
  817. if (s->hd)
  818. ffurl_closep(&s->hd);
  819. av_dict_free(&s->chained_options);
  820. return ret;
  821. }
  822. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  823. {
  824. HTTPContext *s = h->priv_data;
  825. URLContext *old_hd = s->hd;
  826. int64_t old_off = s->off;
  827. uint8_t old_buf[BUFFER_SIZE];
  828. int old_buf_size;
  829. AVDictionary *options = NULL;
  830. if (whence == AVSEEK_SIZE)
  831. return s->filesize;
  832. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  833. return -1;
  834. /* we save the old context in case the seek fails */
  835. old_buf_size = s->buf_end - s->buf_ptr;
  836. memcpy(old_buf, s->buf_ptr, old_buf_size);
  837. s->hd = NULL;
  838. if (whence == SEEK_CUR)
  839. off += s->off;
  840. else if (whence == SEEK_END)
  841. off += s->filesize;
  842. s->off = off;
  843. /* if it fails, continue on old connection */
  844. av_dict_copy(&options, s->chained_options, 0);
  845. if (http_open_cnx(h, &options) < 0) {
  846. av_dict_free(&options);
  847. memcpy(s->buffer, old_buf, old_buf_size);
  848. s->buf_ptr = s->buffer;
  849. s->buf_end = s->buffer + old_buf_size;
  850. s->hd = old_hd;
  851. s->off = old_off;
  852. return -1;
  853. }
  854. av_dict_free(&options);
  855. ffurl_close(old_hd);
  856. return off;
  857. }
  858. static int
  859. http_get_file_handle(URLContext *h)
  860. {
  861. HTTPContext *s = h->priv_data;
  862. return ffurl_get_file_handle(s->hd);
  863. }
  864. #if CONFIG_HTTP_PROTOCOL
  865. URLProtocol ff_http_protocol = {
  866. .name = "http",
  867. .url_open2 = http_open,
  868. .url_read = http_read,
  869. .url_write = http_write,
  870. .url_seek = http_seek,
  871. .url_close = http_close,
  872. .url_get_file_handle = http_get_file_handle,
  873. .url_shutdown = http_shutdown,
  874. .priv_data_size = sizeof(HTTPContext),
  875. .priv_data_class = &http_context_class,
  876. .flags = URL_PROTOCOL_FLAG_NETWORK,
  877. };
  878. #endif
  879. #if CONFIG_HTTPS_PROTOCOL
  880. URLProtocol ff_https_protocol = {
  881. .name = "https",
  882. .url_open2 = http_open,
  883. .url_read = http_read,
  884. .url_write = http_write,
  885. .url_seek = http_seek,
  886. .url_close = http_close,
  887. .url_get_file_handle = http_get_file_handle,
  888. .url_shutdown = http_shutdown,
  889. .priv_data_size = sizeof(HTTPContext),
  890. .priv_data_class = &https_context_class,
  891. .flags = URL_PROTOCOL_FLAG_NETWORK,
  892. };
  893. #endif
  894. #if CONFIG_HTTPPROXY_PROTOCOL
  895. static int http_proxy_close(URLContext *h)
  896. {
  897. HTTPContext *s = h->priv_data;
  898. if (s->hd)
  899. ffurl_closep(&s->hd);
  900. return 0;
  901. }
  902. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  903. {
  904. HTTPContext *s = h->priv_data;
  905. char hostname[1024], hoststr[1024];
  906. char auth[1024], pathbuf[1024], *path;
  907. char lower_url[100];
  908. int port, ret = 0, attempts = 0;
  909. HTTPAuthType cur_auth_type;
  910. char *authstr;
  911. int new_loc;
  912. if( s->seekable == 1 )
  913. h->is_streamed = 0;
  914. else
  915. h->is_streamed = 1;
  916. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  917. pathbuf, sizeof(pathbuf), uri);
  918. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  919. path = pathbuf;
  920. if (*path == '/')
  921. path++;
  922. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  923. NULL);
  924. redo:
  925. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  926. &h->interrupt_callback, NULL);
  927. if (ret < 0)
  928. return ret;
  929. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  930. path, "CONNECT");
  931. snprintf(s->buffer, sizeof(s->buffer),
  932. "CONNECT %s HTTP/1.1\r\n"
  933. "Host: %s\r\n"
  934. "Connection: close\r\n"
  935. "%s%s"
  936. "\r\n",
  937. path,
  938. hoststr,
  939. authstr ? "Proxy-" : "", authstr ? authstr : "");
  940. av_freep(&authstr);
  941. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  942. goto fail;
  943. s->buf_ptr = s->buffer;
  944. s->buf_end = s->buffer;
  945. s->line_count = 0;
  946. s->filesize = -1;
  947. cur_auth_type = s->proxy_auth_state.auth_type;
  948. /* Note: This uses buffering, potentially reading more than the
  949. * HTTP header. If tunneling a protocol where the server starts
  950. * the conversation, we might buffer part of that here, too.
  951. * Reading that requires using the proper ffurl_read() function
  952. * on this URLContext, not using the fd directly (as the tls
  953. * protocol does). This shouldn't be an issue for tls though,
  954. * since the client starts the conversation there, so there
  955. * is no extra data that we might buffer up here.
  956. */
  957. ret = http_read_header(h, &new_loc);
  958. if (ret < 0)
  959. goto fail;
  960. attempts++;
  961. if (s->http_code == 407 &&
  962. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  963. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  964. ffurl_closep(&s->hd);
  965. goto redo;
  966. }
  967. if (s->http_code < 400)
  968. return 0;
  969. ret = AVERROR(EIO);
  970. fail:
  971. http_proxy_close(h);
  972. return ret;
  973. }
  974. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  975. {
  976. HTTPContext *s = h->priv_data;
  977. return ffurl_write(s->hd, buf, size);
  978. }
  979. URLProtocol ff_httpproxy_protocol = {
  980. .name = "httpproxy",
  981. .url_open = http_proxy_open,
  982. .url_read = http_buf_read,
  983. .url_write = http_proxy_write,
  984. .url_close = http_proxy_close,
  985. .url_get_file_handle = http_get_file_handle,
  986. .priv_data_size = sizeof(HTTPContext),
  987. .flags = URL_PROTOCOL_FLAG_NETWORK,
  988. };
  989. #endif