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.

1097 lines
37KB

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