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.

1080 lines
36KB

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