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.

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