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.

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