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.

1128 lines
38KB

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