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.

1075 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\n",
  381. s->inflate_stream.msg);
  382. return AVERROR(ENOSYS);
  383. }
  384. if (zlibCompileFlags() & (1 << 17)) {
  385. av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
  386. return AVERROR(ENOSYS);
  387. }
  388. #else
  389. av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
  390. return AVERROR(ENOSYS);
  391. #endif
  392. } else if (!av_strncasecmp(p, "identity", 8)) {
  393. // The normal, no-encoding case (although servers shouldn't include
  394. // the header at all if this is the case).
  395. } else {
  396. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  397. return AVERROR(ENOSYS);
  398. }
  399. }
  400. }
  401. return 1;
  402. }
  403. /**
  404. * Create a string containing cookie values for use as a HTTP cookie header
  405. * field value for a particular path and domain from the cookie values stored in
  406. * the HTTP protocol context. The cookie string is stored in *cookies.
  407. *
  408. * @return a negative value if an error condition occurred, 0 otherwise
  409. */
  410. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  411. const char *domain)
  412. {
  413. // cookie strings will look like Set-Cookie header field values. Multiple
  414. // Set-Cookie fields will result in multiple values delimited by a newline
  415. int ret = 0;
  416. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  417. if (!set_cookies) return AVERROR(EINVAL);
  418. *cookies = NULL;
  419. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  420. int domain_offset = 0;
  421. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  422. set_cookies = NULL;
  423. while ((param = av_strtok(cookie, "; ", &next_param))) {
  424. cookie = NULL;
  425. if (!av_strncasecmp("path=", param, 5)) {
  426. av_free(cpath);
  427. cpath = av_strdup(&param[5]);
  428. } else if (!av_strncasecmp("domain=", param, 7)) {
  429. av_free(cdomain);
  430. cdomain = av_strdup(&param[7]);
  431. } else if (!av_strncasecmp("secure", param, 6) ||
  432. !av_strncasecmp("comment", param, 7) ||
  433. !av_strncasecmp("max-age", param, 7) ||
  434. !av_strncasecmp("version", param, 7)) {
  435. // ignore Comment, Max-Age, Secure and Version
  436. } else {
  437. av_free(cvalue);
  438. cvalue = av_strdup(param);
  439. }
  440. }
  441. if (!cdomain)
  442. cdomain = av_strdup(domain);
  443. // ensure all of the necessary values are valid
  444. if (!cdomain || !cpath || !cvalue) {
  445. av_log(s, AV_LOG_WARNING,
  446. "Invalid cookie found, no value, path or domain specified\n");
  447. goto done_cookie;
  448. }
  449. // check if the request path matches the cookie path
  450. if (av_strncasecmp(path, cpath, strlen(cpath)))
  451. goto done_cookie;
  452. // the domain should be at least the size of our cookie domain
  453. domain_offset = strlen(domain) - strlen(cdomain);
  454. if (domain_offset < 0)
  455. goto done_cookie;
  456. // match the cookie domain
  457. if (av_strcasecmp(&domain[domain_offset], cdomain))
  458. goto done_cookie;
  459. // cookie parameters match, so copy the value
  460. if (!*cookies) {
  461. if (!(*cookies = av_strdup(cvalue))) {
  462. ret = AVERROR(ENOMEM);
  463. goto done_cookie;
  464. }
  465. } else {
  466. char *tmp = *cookies;
  467. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  468. if (!(*cookies = av_malloc(str_size))) {
  469. ret = AVERROR(ENOMEM);
  470. goto done_cookie;
  471. }
  472. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  473. av_free(tmp);
  474. }
  475. done_cookie:
  476. av_free(cdomain);
  477. av_free(cpath);
  478. av_free(cvalue);
  479. if (ret < 0) {
  480. if (*cookies) av_freep(cookies);
  481. av_free(cset_cookies);
  482. return ret;
  483. }
  484. }
  485. av_free(cset_cookies);
  486. return 0;
  487. }
  488. static inline int has_header(const char *str, const char *header)
  489. {
  490. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  491. if (!str)
  492. return 0;
  493. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  494. }
  495. static int http_read_header(URLContext *h, int *new_location)
  496. {
  497. HTTPContext *s = h->priv_data;
  498. char line[MAX_URL_SIZE];
  499. int err = 0;
  500. s->chunksize = -1;
  501. for (;;) {
  502. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  503. return err;
  504. av_dlog(NULL, "header='%s'\n", line);
  505. err = process_line(h, line, s->line_count, new_location);
  506. if (err < 0)
  507. return err;
  508. if (err == 0)
  509. break;
  510. s->line_count++;
  511. }
  512. return err;
  513. }
  514. static int http_connect(URLContext *h, const char *path, const char *local_path,
  515. const char *hoststr, const char *auth,
  516. const char *proxyauth, int *new_location)
  517. {
  518. HTTPContext *s = h->priv_data;
  519. int post, err;
  520. char headers[4096] = "";
  521. char *authstr = NULL, *proxyauthstr = NULL;
  522. int64_t off = s->off;
  523. int len = 0;
  524. const char *method;
  525. /* send http header */
  526. post = h->flags & AVIO_FLAG_WRITE;
  527. if (s->post_data) {
  528. /* force POST method and disable chunked encoding when
  529. * custom HTTP post data is set */
  530. post = 1;
  531. s->chunked_post = 0;
  532. }
  533. method = post ? "POST" : "GET";
  534. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  535. method);
  536. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  537. local_path, method);
  538. /* set default headers if needed */
  539. if (!has_header(s->headers, "\r\nUser-Agent: "))
  540. len += av_strlcatf(headers + len, sizeof(headers) - len,
  541. "User-Agent: %s\r\n", s->user_agent);
  542. if (!has_header(s->headers, "\r\nAccept: "))
  543. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  544. sizeof(headers) - len);
  545. // Note: we send this on purpose even when s->off is 0 when we're probing,
  546. // since it allows us to detect more reliably if a (non-conforming)
  547. // server supports seeking by analysing the reply headers.
  548. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
  549. len += av_strlcatf(headers + len, sizeof(headers) - len,
  550. "Range: bytes=%"PRId64"-\r\n", s->off);
  551. if (!has_header(s->headers, "\r\nConnection: ")) {
  552. if (s->multiple_requests) {
  553. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  554. sizeof(headers) - len);
  555. } else {
  556. len += av_strlcpy(headers + len, "Connection: close\r\n",
  557. sizeof(headers) - len);
  558. }
  559. }
  560. if (!has_header(s->headers, "\r\nHost: "))
  561. len += av_strlcatf(headers + len, sizeof(headers) - len,
  562. "Host: %s\r\n", hoststr);
  563. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  564. len += av_strlcatf(headers + len, sizeof(headers) - len,
  565. "Content-Length: %d\r\n", s->post_datalen);
  566. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  567. len += av_strlcatf(headers + len, sizeof(headers) - len,
  568. "Content-Type: %s\r\n", s->content_type);
  569. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  570. char *cookies = NULL;
  571. if (!get_cookies(s, &cookies, path, hoststr)) {
  572. len += av_strlcatf(headers + len, sizeof(headers) - len,
  573. "Cookie: %s\r\n", cookies);
  574. av_free(cookies);
  575. }
  576. }
  577. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  578. len += av_strlcatf(headers + len, sizeof(headers) - len,
  579. "Icy-MetaData: %d\r\n", 1);
  580. }
  581. /* now add in custom headers */
  582. if (s->headers)
  583. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  584. snprintf(s->buffer, sizeof(s->buffer),
  585. "%s %s HTTP/1.1\r\n"
  586. "%s"
  587. "%s"
  588. "%s"
  589. "%s%s"
  590. "\r\n",
  591. method,
  592. path,
  593. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  594. headers,
  595. authstr ? authstr : "",
  596. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  597. av_freep(&authstr);
  598. av_freep(&proxyauthstr);
  599. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  600. return err;
  601. if (s->post_data)
  602. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  603. return err;
  604. /* init input buffer */
  605. s->buf_ptr = s->buffer;
  606. s->buf_end = s->buffer;
  607. s->line_count = 0;
  608. s->off = 0;
  609. s->icy_data_read = 0;
  610. s->filesize = -1;
  611. s->willclose = 0;
  612. s->end_chunked_post = 0;
  613. s->end_header = 0;
  614. if (post && !s->post_data) {
  615. /* Pretend that it did work. We didn't read any header yet, since
  616. * we've still to send the POST data, but the code calling this
  617. * function will check http_code after we return. */
  618. s->http_code = 200;
  619. return 0;
  620. }
  621. /* wait for header */
  622. err = http_read_header(h, new_location);
  623. if (err < 0)
  624. return err;
  625. return (off == s->off) ? 0 : -1;
  626. }
  627. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  628. {
  629. HTTPContext *s = h->priv_data;
  630. int len;
  631. /* read bytes from input buffer first */
  632. len = s->buf_end - s->buf_ptr;
  633. if (len > 0) {
  634. if (len > size)
  635. len = size;
  636. memcpy(buf, s->buf_ptr, len);
  637. s->buf_ptr += len;
  638. } else {
  639. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  640. return AVERROR_EOF;
  641. len = ffurl_read(s->hd, buf, size);
  642. }
  643. if (len > 0) {
  644. s->off += len;
  645. s->icy_data_read += len;
  646. if (s->chunksize > 0)
  647. s->chunksize -= len;
  648. }
  649. return len;
  650. }
  651. #if CONFIG_ZLIB
  652. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  653. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  654. {
  655. HTTPContext *s = h->priv_data;
  656. int ret;
  657. if (!s->inflate_buffer) {
  658. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  659. if (!s->inflate_buffer)
  660. return AVERROR(ENOMEM);
  661. }
  662. if (s->inflate_stream.avail_in == 0) {
  663. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  664. if (read <= 0)
  665. return read;
  666. s->inflate_stream.next_in = s->inflate_buffer;
  667. s->inflate_stream.avail_in = read;
  668. }
  669. s->inflate_stream.avail_out = size;
  670. s->inflate_stream.next_out = buf;
  671. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  672. if (ret != Z_OK && ret != Z_STREAM_END)
  673. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  674. return size - s->inflate_stream.avail_out;
  675. }
  676. #endif
  677. static int http_read(URLContext *h, uint8_t *buf, int size)
  678. {
  679. HTTPContext *s = h->priv_data;
  680. int err, new_location;
  681. if (!s->hd)
  682. return AVERROR_EOF;
  683. if (s->end_chunked_post && !s->end_header) {
  684. err = http_read_header(h, &new_location);
  685. if (err < 0)
  686. return err;
  687. }
  688. if (s->chunksize >= 0) {
  689. if (!s->chunksize) {
  690. char line[32];
  691. for(;;) {
  692. do {
  693. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  694. return err;
  695. } while (!*line); /* skip CR LF from last chunk */
  696. s->chunksize = strtoll(line, NULL, 16);
  697. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  698. if (!s->chunksize)
  699. return 0;
  700. break;
  701. }
  702. }
  703. size = FFMIN(size, s->chunksize);
  704. }
  705. if (s->icy_metaint > 0) {
  706. int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
  707. if (!remaining) {
  708. // The metadata packet is variable sized. It has a 1 byte header
  709. // which sets the length of the packet (divided by 16). If it's 0,
  710. // the metadata doesn't change. After the packet, icy_metaint bytes
  711. // of normal data follow.
  712. int ch = http_getc(s);
  713. if (ch < 0)
  714. return ch;
  715. if (ch > 0) {
  716. char data[255 * 16 + 1];
  717. int n;
  718. int ret;
  719. ch *= 16;
  720. for (n = 0; n < ch; n++)
  721. data[n] = http_getc(s);
  722. data[ch + 1] = 0;
  723. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  724. return ret;
  725. }
  726. s->icy_data_read = 0;
  727. remaining = s->icy_metaint;
  728. }
  729. size = FFMIN(size, remaining);
  730. }
  731. #if CONFIG_ZLIB
  732. if (s->compressed)
  733. return http_buf_read_compressed(h, buf, size);
  734. #endif
  735. return http_buf_read(h, buf, size);
  736. }
  737. /* used only when posting data */
  738. static int http_write(URLContext *h, const uint8_t *buf, int size)
  739. {
  740. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  741. int ret;
  742. char crlf[] = "\r\n";
  743. HTTPContext *s = h->priv_data;
  744. if (!s->chunked_post) {
  745. /* non-chunked data is sent without any special encoding */
  746. return ffurl_write(s->hd, buf, size);
  747. }
  748. /* silently ignore zero-size data since chunk encoding that would
  749. * signal EOF */
  750. if (size > 0) {
  751. /* upload data using chunked encoding */
  752. snprintf(temp, sizeof(temp), "%x\r\n", size);
  753. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  754. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  755. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  756. return ret;
  757. }
  758. return size;
  759. }
  760. static int http_shutdown(URLContext *h, int flags)
  761. {
  762. int ret = 0;
  763. char footer[] = "0\r\n\r\n";
  764. HTTPContext *s = h->priv_data;
  765. /* signal end of chunked encoding if used */
  766. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  767. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  768. ret = ret > 0 ? 0 : ret;
  769. s->end_chunked_post = 1;
  770. }
  771. return ret;
  772. }
  773. static int http_close(URLContext *h)
  774. {
  775. int ret = 0;
  776. HTTPContext *s = h->priv_data;
  777. #if CONFIG_ZLIB
  778. inflateEnd(&s->inflate_stream);
  779. av_freep(&s->inflate_buffer);
  780. #endif
  781. if (!s->end_chunked_post) {
  782. /* Close the write direction by sending the end of chunked encoding. */
  783. ret = http_shutdown(h, h->flags);
  784. }
  785. if (s->hd)
  786. ffurl_closep(&s->hd);
  787. return ret;
  788. }
  789. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  790. {
  791. HTTPContext *s = h->priv_data;
  792. URLContext *old_hd = s->hd;
  793. int64_t old_off = s->off;
  794. uint8_t old_buf[BUFFER_SIZE];
  795. int old_buf_size;
  796. if (whence == AVSEEK_SIZE)
  797. return s->filesize;
  798. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  799. return -1;
  800. /* we save the old context in case the seek fails */
  801. old_buf_size = s->buf_end - s->buf_ptr;
  802. memcpy(old_buf, s->buf_ptr, old_buf_size);
  803. s->hd = NULL;
  804. if (whence == SEEK_CUR)
  805. off += s->off;
  806. else if (whence == SEEK_END)
  807. off += s->filesize;
  808. s->off = off;
  809. /* if it fails, continue on old connection */
  810. if (http_open_cnx(h) < 0) {
  811. memcpy(s->buffer, old_buf, old_buf_size);
  812. s->buf_ptr = s->buffer;
  813. s->buf_end = s->buffer + old_buf_size;
  814. s->hd = old_hd;
  815. s->off = old_off;
  816. return -1;
  817. }
  818. ffurl_close(old_hd);
  819. return off;
  820. }
  821. static int
  822. http_get_file_handle(URLContext *h)
  823. {
  824. HTTPContext *s = h->priv_data;
  825. return ffurl_get_file_handle(s->hd);
  826. }
  827. #if CONFIG_HTTP_PROTOCOL
  828. URLProtocol ff_http_protocol = {
  829. .name = "http",
  830. .url_open = http_open,
  831. .url_read = http_read,
  832. .url_write = http_write,
  833. .url_seek = http_seek,
  834. .url_close = http_close,
  835. .url_get_file_handle = http_get_file_handle,
  836. .url_shutdown = http_shutdown,
  837. .priv_data_size = sizeof(HTTPContext),
  838. .priv_data_class = &http_context_class,
  839. .flags = URL_PROTOCOL_FLAG_NETWORK,
  840. };
  841. #endif
  842. #if CONFIG_HTTPS_PROTOCOL
  843. URLProtocol ff_https_protocol = {
  844. .name = "https",
  845. .url_open = http_open,
  846. .url_read = http_read,
  847. .url_write = http_write,
  848. .url_seek = http_seek,
  849. .url_close = http_close,
  850. .url_get_file_handle = http_get_file_handle,
  851. .url_shutdown = http_shutdown,
  852. .priv_data_size = sizeof(HTTPContext),
  853. .priv_data_class = &https_context_class,
  854. .flags = URL_PROTOCOL_FLAG_NETWORK,
  855. };
  856. #endif
  857. #if CONFIG_HTTPPROXY_PROTOCOL
  858. static int http_proxy_close(URLContext *h)
  859. {
  860. HTTPContext *s = h->priv_data;
  861. if (s->hd)
  862. ffurl_closep(&s->hd);
  863. return 0;
  864. }
  865. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  866. {
  867. HTTPContext *s = h->priv_data;
  868. char hostname[1024], hoststr[1024];
  869. char auth[1024], pathbuf[1024], *path;
  870. char lower_url[100];
  871. int port, ret = 0, attempts = 0;
  872. HTTPAuthType cur_auth_type;
  873. char *authstr;
  874. int new_loc;
  875. AVDictionary *opts = NULL;
  876. char opts_format[20];
  877. if( s->seekable == 1 )
  878. h->is_streamed = 0;
  879. else
  880. h->is_streamed = 1;
  881. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  882. pathbuf, sizeof(pathbuf), uri);
  883. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  884. path = pathbuf;
  885. if (*path == '/')
  886. path++;
  887. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  888. NULL);
  889. redo:
  890. if (s->rw_timeout != -1) {
  891. snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
  892. av_dict_set(&opts, "timeout", opts_format, 0);
  893. } /* if option is not given, don't pass it and let tcp use its own default */
  894. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  895. &h->interrupt_callback, &opts);
  896. av_dict_free(&opts);
  897. if (ret < 0)
  898. return ret;
  899. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  900. path, "CONNECT");
  901. snprintf(s->buffer, sizeof(s->buffer),
  902. "CONNECT %s HTTP/1.1\r\n"
  903. "Host: %s\r\n"
  904. "Connection: close\r\n"
  905. "%s%s"
  906. "\r\n",
  907. path,
  908. hoststr,
  909. authstr ? "Proxy-" : "", authstr ? authstr : "");
  910. av_freep(&authstr);
  911. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  912. goto fail;
  913. s->buf_ptr = s->buffer;
  914. s->buf_end = s->buffer;
  915. s->line_count = 0;
  916. s->filesize = -1;
  917. cur_auth_type = s->proxy_auth_state.auth_type;
  918. /* Note: This uses buffering, potentially reading more than the
  919. * HTTP header. If tunneling a protocol where the server starts
  920. * the conversation, we might buffer part of that here, too.
  921. * Reading that requires using the proper ffurl_read() function
  922. * on this URLContext, not using the fd directly (as the tls
  923. * protocol does). This shouldn't be an issue for tls though,
  924. * since the client starts the conversation there, so there
  925. * is no extra data that we might buffer up here.
  926. */
  927. ret = http_read_header(h, &new_loc);
  928. if (ret < 0)
  929. goto fail;
  930. attempts++;
  931. if (s->http_code == 407 &&
  932. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  933. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  934. ffurl_closep(&s->hd);
  935. goto redo;
  936. }
  937. if (s->http_code < 400)
  938. return 0;
  939. ret = AVERROR(EIO);
  940. fail:
  941. http_proxy_close(h);
  942. return ret;
  943. }
  944. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  945. {
  946. HTTPContext *s = h->priv_data;
  947. return ffurl_write(s->hd, buf, size);
  948. }
  949. URLProtocol ff_httpproxy_protocol = {
  950. .name = "httpproxy",
  951. .url_open = http_proxy_open,
  952. .url_read = http_buf_read,
  953. .url_write = http_proxy_write,
  954. .url_close = http_proxy_close,
  955. .url_get_file_handle = http_get_file_handle,
  956. .priv_data_size = sizeof(HTTPContext),
  957. .flags = URL_PROTOCOL_FLAG_NETWORK,
  958. };
  959. #endif