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.

1131 lines
39KB

  1. /*
  2. * HTTP protocol for ffmpeg client
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/avstring.h"
  22. #include "avformat.h"
  23. #include "internal.h"
  24. #include "network.h"
  25. #include "http.h"
  26. #include "os_support.h"
  27. #include "httpauth.h"
  28. #include "url.h"
  29. #include "libavutil/opt.h"
  30. #if CONFIG_ZLIB
  31. #include <zlib.h>
  32. #endif
  33. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  34. only a subset of it. */
  35. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  36. * to be large enough to fit the full request headers (including long
  37. * path names).
  38. */
  39. #define BUFFER_SIZE MAX_URL_SIZE
  40. #define MAX_REDIRECTS 8
  41. typedef struct {
  42. const AVClass *class;
  43. URLContext *hd;
  44. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  45. int line_count;
  46. int http_code;
  47. 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. // if the cookie specifies a sub-domain, skip the leading dot thereby
  456. // supporting URLs that point to sub-domains and the master domain
  457. int leading_dot = (param[7] == '.');
  458. av_free(cdomain);
  459. cdomain = av_strdup(&param[7+leading_dot]);
  460. } else if (!av_strncasecmp("secure", param, 6) ||
  461. !av_strncasecmp("comment", param, 7) ||
  462. !av_strncasecmp("max-age", param, 7) ||
  463. !av_strncasecmp("version", param, 7)) {
  464. // ignore Comment, Max-Age, Secure and Version
  465. } else {
  466. av_free(cvalue);
  467. cvalue = av_strdup(param);
  468. }
  469. }
  470. if (!cdomain)
  471. cdomain = av_strdup(domain);
  472. // ensure all of the necessary values are valid
  473. if (!cdomain || !cpath || !cvalue) {
  474. av_log(s, AV_LOG_WARNING,
  475. "Invalid cookie found, no value, path or domain specified\n");
  476. goto done_cookie;
  477. }
  478. // check if the request path matches the cookie path
  479. if (av_strncasecmp(path, cpath, strlen(cpath)))
  480. goto done_cookie;
  481. // the domain should be at least the size of our cookie domain
  482. domain_offset = strlen(domain) - strlen(cdomain);
  483. if (domain_offset < 0)
  484. goto done_cookie;
  485. // match the cookie domain
  486. if (av_strcasecmp(&domain[domain_offset], cdomain))
  487. goto done_cookie;
  488. // cookie parameters match, so copy the value
  489. if (!*cookies) {
  490. if (!(*cookies = av_strdup(cvalue))) {
  491. ret = AVERROR(ENOMEM);
  492. goto done_cookie;
  493. }
  494. } else {
  495. char *tmp = *cookies;
  496. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  497. if (!(*cookies = av_malloc(str_size))) {
  498. ret = AVERROR(ENOMEM);
  499. goto done_cookie;
  500. }
  501. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  502. av_free(tmp);
  503. }
  504. done_cookie:
  505. av_free(cdomain);
  506. av_free(cpath);
  507. av_free(cvalue);
  508. if (ret < 0) {
  509. if (*cookies) av_freep(cookies);
  510. av_free(cset_cookies);
  511. return ret;
  512. }
  513. }
  514. av_free(cset_cookies);
  515. return 0;
  516. }
  517. static inline int has_header(const char *str, const char *header)
  518. {
  519. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  520. if (!str)
  521. return 0;
  522. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  523. }
  524. static int http_read_header(URLContext *h, int *new_location)
  525. {
  526. HTTPContext *s = h->priv_data;
  527. char line[MAX_URL_SIZE];
  528. int err = 0;
  529. s->chunksize = -1;
  530. for (;;) {
  531. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  532. return err;
  533. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  534. err = process_line(h, line, s->line_count, new_location);
  535. if (err < 0)
  536. return err;
  537. if (err == 0)
  538. break;
  539. s->line_count++;
  540. }
  541. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  542. h->is_streamed = 1; /* we can in fact _not_ seek */
  543. return err;
  544. }
  545. static int http_connect(URLContext *h, const char *path, const char *local_path,
  546. const char *hoststr, const char *auth,
  547. const char *proxyauth, int *new_location)
  548. {
  549. HTTPContext *s = h->priv_data;
  550. int post, err;
  551. char headers[4096] = "";
  552. char *authstr = NULL, *proxyauthstr = NULL;
  553. int64_t off = s->off;
  554. int len = 0;
  555. const char *method;
  556. int send_expect_100 = 0;
  557. /* send http header */
  558. post = h->flags & AVIO_FLAG_WRITE;
  559. if (s->post_data) {
  560. /* force POST method and disable chunked encoding when
  561. * custom HTTP post data is set */
  562. post = 1;
  563. s->chunked_post = 0;
  564. }
  565. method = post ? "POST" : "GET";
  566. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  567. method);
  568. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  569. local_path, method);
  570. if (post && !s->post_data) {
  571. send_expect_100 = s->send_expect_100;
  572. /* The user has supplied authentication but we don't know the auth type,
  573. * send Expect: 100-continue to get the 401 response including the
  574. * WWW-Authenticate header, or an 100 continue if no auth actually
  575. * is needed. */
  576. if (auth && *auth &&
  577. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  578. s->http_code != 401)
  579. send_expect_100 = 1;
  580. }
  581. /* set default headers if needed */
  582. if (!has_header(s->headers, "\r\nUser-Agent: "))
  583. len += av_strlcatf(headers + len, sizeof(headers) - len,
  584. "User-Agent: %s\r\n", s->user_agent);
  585. if (!has_header(s->headers, "\r\nAccept: "))
  586. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  587. sizeof(headers) - len);
  588. // Note: we send this on purpose even when s->off is 0 when we're probing,
  589. // since it allows us to detect more reliably if a (non-conforming)
  590. // server supports seeking by analysing the reply headers.
  591. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->req_end_offset || s->seekable == -1)) {
  592. len += av_strlcatf(headers + len, sizeof(headers) - len,
  593. "Range: bytes=%"PRId64"-", s->off);
  594. if (s->req_end_offset)
  595. len += av_strlcatf(headers + len, sizeof(headers) - len,
  596. "%"PRId64, s->req_end_offset - 1);
  597. len += av_strlcpy(headers + len, "\r\n",
  598. sizeof(headers) - len);
  599. }
  600. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  601. len += av_strlcatf(headers + len, sizeof(headers) - len,
  602. "Expect: 100-continue\r\n");
  603. if (!has_header(s->headers, "\r\nConnection: ")) {
  604. if (s->multiple_requests) {
  605. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  606. sizeof(headers) - len);
  607. } else {
  608. len += av_strlcpy(headers + len, "Connection: close\r\n",
  609. sizeof(headers) - len);
  610. }
  611. }
  612. if (!has_header(s->headers, "\r\nHost: "))
  613. len += av_strlcatf(headers + len, sizeof(headers) - len,
  614. "Host: %s\r\n", hoststr);
  615. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  616. len += av_strlcatf(headers + len, sizeof(headers) - len,
  617. "Content-Length: %d\r\n", s->post_datalen);
  618. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  619. len += av_strlcatf(headers + len, sizeof(headers) - len,
  620. "Content-Type: %s\r\n", s->content_type);
  621. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  622. char *cookies = NULL;
  623. if (!get_cookies(s, &cookies, path, hoststr)) {
  624. len += av_strlcatf(headers + len, sizeof(headers) - len,
  625. "Cookie: %s\r\n", cookies);
  626. av_free(cookies);
  627. }
  628. }
  629. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  630. len += av_strlcatf(headers + len, sizeof(headers) - len,
  631. "Icy-MetaData: %d\r\n", 1);
  632. }
  633. /* now add in custom headers */
  634. if (s->headers)
  635. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  636. snprintf(s->buffer, sizeof(s->buffer),
  637. "%s %s HTTP/1.1\r\n"
  638. "%s"
  639. "%s"
  640. "%s"
  641. "%s%s"
  642. "\r\n",
  643. method,
  644. path,
  645. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  646. headers,
  647. authstr ? authstr : "",
  648. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  649. av_freep(&authstr);
  650. av_freep(&proxyauthstr);
  651. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  652. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  653. return err;
  654. if (s->post_data)
  655. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  656. return err;
  657. /* init input buffer */
  658. s->buf_ptr = s->buffer;
  659. s->buf_end = s->buffer;
  660. s->line_count = 0;
  661. s->off = 0;
  662. s->icy_data_read = 0;
  663. s->filesize = -1;
  664. s->willclose = 0;
  665. s->end_chunked_post = 0;
  666. s->end_header = 0;
  667. if (post && !s->post_data && !send_expect_100) {
  668. /* Pretend that it did work. We didn't read any header yet, since
  669. * we've still to send the POST data, but the code calling this
  670. * function will check http_code after we return. */
  671. s->http_code = 200;
  672. return 0;
  673. }
  674. /* wait for header */
  675. err = http_read_header(h, new_location);
  676. if (err < 0)
  677. return err;
  678. return (off == s->off) ? 0 : -1;
  679. }
  680. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  681. {
  682. HTTPContext *s = h->priv_data;
  683. int len;
  684. /* read bytes from input buffer first */
  685. len = s->buf_end - s->buf_ptr;
  686. if (len > 0) {
  687. if (len > size)
  688. len = size;
  689. memcpy(buf, s->buf_ptr, len);
  690. s->buf_ptr += len;
  691. } else {
  692. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  693. return AVERROR_EOF;
  694. len = ffurl_read(s->hd, buf, size);
  695. }
  696. if (len > 0) {
  697. s->off += len;
  698. s->icy_data_read += len;
  699. if (s->chunksize > 0)
  700. s->chunksize -= len;
  701. }
  702. return len;
  703. }
  704. #if CONFIG_ZLIB
  705. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  706. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  707. {
  708. HTTPContext *s = h->priv_data;
  709. int ret;
  710. if (!s->inflate_buffer) {
  711. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  712. if (!s->inflate_buffer)
  713. return AVERROR(ENOMEM);
  714. }
  715. if (s->inflate_stream.avail_in == 0) {
  716. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  717. if (read <= 0)
  718. return read;
  719. s->inflate_stream.next_in = s->inflate_buffer;
  720. s->inflate_stream.avail_in = read;
  721. }
  722. s->inflate_stream.avail_out = size;
  723. s->inflate_stream.next_out = buf;
  724. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  725. if (ret != Z_OK && ret != Z_STREAM_END)
  726. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  727. return size - s->inflate_stream.avail_out;
  728. }
  729. #endif
  730. static int http_read(URLContext *h, uint8_t *buf, int size)
  731. {
  732. HTTPContext *s = h->priv_data;
  733. int err, new_location;
  734. if (!s->hd)
  735. return AVERROR_EOF;
  736. if (s->end_chunked_post && !s->end_header) {
  737. err = http_read_header(h, &new_location);
  738. if (err < 0)
  739. return err;
  740. }
  741. if (s->chunksize >= 0) {
  742. if (!s->chunksize) {
  743. char line[32];
  744. for(;;) {
  745. do {
  746. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  747. return err;
  748. } while (!*line); /* skip CR LF from last chunk */
  749. s->chunksize = strtoll(line, NULL, 16);
  750. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  751. if (!s->chunksize)
  752. return 0;
  753. break;
  754. }
  755. }
  756. size = FFMIN(size, s->chunksize);
  757. }
  758. if (s->icy_metaint > 0) {
  759. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  760. if (!remaining) {
  761. // The metadata packet is variable sized. It has a 1 byte header
  762. // which sets the length of the packet (divided by 16). If it's 0,
  763. // the metadata doesn't change. After the packet, icy_metaint bytes
  764. // of normal data follow.
  765. int ch = http_getc(s);
  766. if (ch < 0)
  767. return ch;
  768. if (ch > 0) {
  769. char data[255 * 16 + 1];
  770. int n;
  771. int ret;
  772. ch *= 16;
  773. for (n = 0; n < ch; n++)
  774. data[n] = http_getc(s);
  775. data[ch + 1] = 0;
  776. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  777. return ret;
  778. }
  779. s->icy_data_read = 0;
  780. remaining = s->icy_metaint;
  781. }
  782. size = FFMIN(size, remaining);
  783. }
  784. #if CONFIG_ZLIB
  785. if (s->compressed)
  786. return http_buf_read_compressed(h, buf, size);
  787. #endif
  788. return http_buf_read(h, buf, size);
  789. }
  790. /* used only when posting data */
  791. static int http_write(URLContext *h, const uint8_t *buf, int size)
  792. {
  793. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  794. int ret;
  795. char crlf[] = "\r\n";
  796. HTTPContext *s = h->priv_data;
  797. if (!s->chunked_post) {
  798. /* non-chunked data is sent without any special encoding */
  799. return ffurl_write(s->hd, buf, size);
  800. }
  801. /* silently ignore zero-size data since chunk encoding that would
  802. * signal EOF */
  803. if (size > 0) {
  804. /* upload data using chunked encoding */
  805. snprintf(temp, sizeof(temp), "%x\r\n", size);
  806. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  807. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  808. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  809. return ret;
  810. }
  811. return size;
  812. }
  813. static int http_shutdown(URLContext *h, int flags)
  814. {
  815. int ret = 0;
  816. char footer[] = "0\r\n\r\n";
  817. HTTPContext *s = h->priv_data;
  818. /* signal end of chunked encoding if used */
  819. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  820. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  821. ret = ret > 0 ? 0 : ret;
  822. s->end_chunked_post = 1;
  823. }
  824. return ret;
  825. }
  826. static int http_close(URLContext *h)
  827. {
  828. int ret = 0;
  829. HTTPContext *s = h->priv_data;
  830. #if CONFIG_ZLIB
  831. inflateEnd(&s->inflate_stream);
  832. av_freep(&s->inflate_buffer);
  833. #endif
  834. if (!s->end_chunked_post) {
  835. /* Close the write direction by sending the end of chunked encoding. */
  836. ret = http_shutdown(h, h->flags);
  837. }
  838. if (s->hd)
  839. ffurl_closep(&s->hd);
  840. av_dict_free(&s->chained_options);
  841. return ret;
  842. }
  843. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  844. {
  845. HTTPContext *s = h->priv_data;
  846. URLContext *old_hd = s->hd;
  847. int64_t old_off = s->off;
  848. uint8_t old_buf[BUFFER_SIZE];
  849. int old_buf_size;
  850. AVDictionary *options = NULL;
  851. if (whence == AVSEEK_SIZE)
  852. return s->filesize;
  853. else if ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))
  854. return s->off;
  855. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  856. return -1;
  857. /* we save the old context in case the seek fails */
  858. old_buf_size = s->buf_end - s->buf_ptr;
  859. memcpy(old_buf, s->buf_ptr, old_buf_size);
  860. s->hd = NULL;
  861. if (whence == SEEK_CUR)
  862. off += s->off;
  863. else if (whence == SEEK_END)
  864. off += s->filesize;
  865. s->off = off;
  866. /* if it fails, continue on old connection */
  867. av_dict_copy(&options, s->chained_options, 0);
  868. if (http_open_cnx(h, &options) < 0) {
  869. av_dict_free(&options);
  870. memcpy(s->buffer, old_buf, old_buf_size);
  871. s->buf_ptr = s->buffer;
  872. s->buf_end = s->buffer + old_buf_size;
  873. s->hd = old_hd;
  874. s->off = old_off;
  875. return -1;
  876. }
  877. av_dict_free(&options);
  878. ffurl_close(old_hd);
  879. return off;
  880. }
  881. static int
  882. http_get_file_handle(URLContext *h)
  883. {
  884. HTTPContext *s = h->priv_data;
  885. return ffurl_get_file_handle(s->hd);
  886. }
  887. #if CONFIG_HTTP_PROTOCOL
  888. URLProtocol ff_http_protocol = {
  889. .name = "http",
  890. .url_open2 = http_open,
  891. .url_read = http_read,
  892. .url_write = http_write,
  893. .url_seek = http_seek,
  894. .url_close = http_close,
  895. .url_get_file_handle = http_get_file_handle,
  896. .url_shutdown = http_shutdown,
  897. .priv_data_size = sizeof(HTTPContext),
  898. .priv_data_class = &http_context_class,
  899. .flags = URL_PROTOCOL_FLAG_NETWORK,
  900. };
  901. #endif
  902. #if CONFIG_HTTPS_PROTOCOL
  903. URLProtocol ff_https_protocol = {
  904. .name = "https",
  905. .url_open2 = http_open,
  906. .url_read = http_read,
  907. .url_write = http_write,
  908. .url_seek = http_seek,
  909. .url_close = http_close,
  910. .url_get_file_handle = http_get_file_handle,
  911. .url_shutdown = http_shutdown,
  912. .priv_data_size = sizeof(HTTPContext),
  913. .priv_data_class = &https_context_class,
  914. .flags = URL_PROTOCOL_FLAG_NETWORK,
  915. };
  916. #endif
  917. #if CONFIG_HTTPPROXY_PROTOCOL
  918. static int http_proxy_close(URLContext *h)
  919. {
  920. HTTPContext *s = h->priv_data;
  921. if (s->hd)
  922. ffurl_closep(&s->hd);
  923. return 0;
  924. }
  925. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  926. {
  927. HTTPContext *s = h->priv_data;
  928. char hostname[1024], hoststr[1024];
  929. char auth[1024], pathbuf[1024], *path;
  930. char lower_url[100];
  931. int port, ret = 0, attempts = 0;
  932. HTTPAuthType cur_auth_type;
  933. char *authstr;
  934. int new_loc;
  935. if( s->seekable == 1 )
  936. h->is_streamed = 0;
  937. else
  938. h->is_streamed = 1;
  939. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  940. pathbuf, sizeof(pathbuf), uri);
  941. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  942. path = pathbuf;
  943. if (*path == '/')
  944. path++;
  945. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  946. NULL);
  947. redo:
  948. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  949. &h->interrupt_callback, NULL);
  950. if (ret < 0)
  951. return ret;
  952. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  953. path, "CONNECT");
  954. snprintf(s->buffer, sizeof(s->buffer),
  955. "CONNECT %s HTTP/1.1\r\n"
  956. "Host: %s\r\n"
  957. "Connection: close\r\n"
  958. "%s%s"
  959. "\r\n",
  960. path,
  961. hoststr,
  962. authstr ? "Proxy-" : "", authstr ? authstr : "");
  963. av_freep(&authstr);
  964. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  965. goto fail;
  966. s->buf_ptr = s->buffer;
  967. s->buf_end = s->buffer;
  968. s->line_count = 0;
  969. s->filesize = -1;
  970. cur_auth_type = s->proxy_auth_state.auth_type;
  971. /* Note: This uses buffering, potentially reading more than the
  972. * HTTP header. If tunneling a protocol where the server starts
  973. * the conversation, we might buffer part of that here, too.
  974. * Reading that requires using the proper ffurl_read() function
  975. * on this URLContext, not using the fd directly (as the tls
  976. * protocol does). This shouldn't be an issue for tls though,
  977. * since the client starts the conversation there, so there
  978. * is no extra data that we might buffer up here.
  979. */
  980. ret = http_read_header(h, &new_loc);
  981. if (ret < 0)
  982. goto fail;
  983. attempts++;
  984. if (s->http_code == 407 &&
  985. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  986. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  987. ffurl_closep(&s->hd);
  988. goto redo;
  989. }
  990. if (s->http_code < 400)
  991. return 0;
  992. ret = AVERROR(EIO);
  993. fail:
  994. http_proxy_close(h);
  995. return ret;
  996. }
  997. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  998. {
  999. HTTPContext *s = h->priv_data;
  1000. return ffurl_write(s->hd, buf, size);
  1001. }
  1002. URLProtocol ff_httpproxy_protocol = {
  1003. .name = "httpproxy",
  1004. .url_open = http_proxy_open,
  1005. .url_read = http_buf_read,
  1006. .url_write = http_proxy_write,
  1007. .url_close = http_proxy_close,
  1008. .url_get_file_handle = http_get_file_handle,
  1009. .priv_data_size = sizeof(HTTPContext),
  1010. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1011. };
  1012. #endif