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.

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