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.

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