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.

1099 lines
35KB

  1. /*
  2. * HTTP protocol for avconv client
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav 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. * Libav 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 Libav; 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 avconv 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. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  48. int64_t chunksize;
  49. int64_t off, end_off, filesize;
  50. char *location;
  51. HTTPAuthState auth_state;
  52. HTTPAuthState proxy_auth_state;
  53. char *headers;
  54. char *mime_type;
  55. char *user_agent;
  56. char *content_type;
  57. /* Set if the server correctly handles Connection: close and will close
  58. * the connection after feeding us the content. */
  59. int willclose;
  60. int chunked_post;
  61. /* A flag which indicates if the end of chunked encoding has been sent. */
  62. int end_chunked_post;
  63. /* A flag which indicates we have finished to read POST reply. */
  64. int end_header;
  65. /* A flag which indicates if we use persistent connections. */
  66. int multiple_requests;
  67. uint8_t *post_data;
  68. int post_datalen;
  69. int icy;
  70. /* how much data was read since the last ICY metadata packet */
  71. int icy_data_read;
  72. /* after how many bytes of read data a new metadata packet will be found */
  73. int icy_metaint;
  74. char *icy_metadata_headers;
  75. char *icy_metadata_packet;
  76. #if CONFIG_ZLIB
  77. int compressed;
  78. z_stream inflate_stream;
  79. uint8_t *inflate_buffer;
  80. #endif
  81. AVDictionary *chained_options;
  82. int send_expect_100;
  83. char *method;
  84. } HTTPContext;
  85. #define OFFSET(x) offsetof(HTTPContext, x)
  86. #define D AV_OPT_FLAG_DECODING_PARAM
  87. #define E AV_OPT_FLAG_ENCODING_PARAM
  88. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  89. static const AVOption options[] = {
  90. {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
  91. {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  92. {"content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  93. {"user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
  94. {"user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
  95. {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
  96. {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
  97. {"mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  98. {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
  99. {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  100. {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  101. {"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" },
  102. {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
  103. {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
  104. {"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 },
  105. {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
  106. {"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
  107. {"end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
  108. {"method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E, },
  109. {NULL}
  110. };
  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_close(s->hd);
  181. s->hd = NULL;
  182. goto redo;
  183. } else
  184. goto fail;
  185. }
  186. if (s->http_code == 407) {
  187. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  188. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  189. ffurl_close(s->hd);
  190. s->hd = NULL;
  191. goto redo;
  192. } else
  193. goto fail;
  194. }
  195. if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
  196. && location_changed == 1) {
  197. /* url moved, get next */
  198. ffurl_close(s->hd);
  199. s->hd = NULL;
  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_close(s->hd);
  213. s->hd = NULL;
  214. return AVERROR(EIO);
  215. }
  216. int ff_http_do_new_request(URLContext *h, const char *uri)
  217. {
  218. HTTPContext *s = h->priv_data;
  219. AVDictionary *options = NULL;
  220. int ret;
  221. s->off = 0;
  222. s->icy_data_read = 0;
  223. av_free(s->location);
  224. s->location = av_strdup(uri);
  225. if (!s->location)
  226. return AVERROR(ENOMEM);
  227. av_dict_copy(&options, s->chained_options, 0);
  228. ret = http_open_cnx(h, &options);
  229. av_dict_free(&options);
  230. return ret;
  231. }
  232. static int http_open(URLContext *h, const char *uri, int flags,
  233. AVDictionary **options)
  234. {
  235. HTTPContext *s = h->priv_data;
  236. int ret;
  237. h->is_streamed = 1;
  238. s->filesize = -1;
  239. s->location = av_strdup(uri);
  240. if (!s->location)
  241. return AVERROR(ENOMEM);
  242. if (options)
  243. av_dict_copy(&s->chained_options, *options, 0);
  244. if (s->headers) {
  245. int len = strlen(s->headers);
  246. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  247. av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
  248. }
  249. ret = http_open_cnx(h, options);
  250. if (ret < 0)
  251. av_dict_free(&s->chained_options);
  252. return ret;
  253. }
  254. static int http_getc(HTTPContext *s)
  255. {
  256. int len;
  257. if (s->buf_ptr >= s->buf_end) {
  258. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  259. if (len < 0) {
  260. return len;
  261. } else if (len == 0) {
  262. return AVERROR_EOF;
  263. } else {
  264. s->buf_ptr = s->buffer;
  265. s->buf_end = s->buffer + len;
  266. }
  267. }
  268. return *s->buf_ptr++;
  269. }
  270. static int http_get_line(HTTPContext *s, char *line, int line_size)
  271. {
  272. int ch;
  273. char *q;
  274. q = line;
  275. for(;;) {
  276. ch = http_getc(s);
  277. if (ch < 0)
  278. return ch;
  279. if (ch == '\n') {
  280. /* process line */
  281. if (q > line && q[-1] == '\r')
  282. q--;
  283. *q = '\0';
  284. return 0;
  285. } else {
  286. if ((q - line) < line_size - 1)
  287. *q++ = ch;
  288. }
  289. }
  290. }
  291. static int check_http_code(URLContext *h, int http_code, const char *end)
  292. {
  293. HTTPContext *s = h->priv_data;
  294. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  295. * don't abort until all headers have been parsed. */
  296. if (http_code >= 400 && http_code < 600 &&
  297. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  298. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  299. end += strspn(end, SPACE_CHARS);
  300. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  301. return AVERROR(EIO);
  302. }
  303. return 0;
  304. }
  305. static int parse_location(HTTPContext *s, const char *p)
  306. {
  307. char redirected_location[MAX_URL_SIZE], *new_loc;
  308. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  309. s->location, p);
  310. new_loc = av_strdup(redirected_location);
  311. if (!new_loc)
  312. return AVERROR(ENOMEM);
  313. av_free(s->location);
  314. s->location = new_loc;
  315. return 0;
  316. }
  317. /* "bytes $from-$to/$document_size" */
  318. static void parse_content_range(URLContext *h, const char *p)
  319. {
  320. HTTPContext *s = h->priv_data;
  321. const char *slash;
  322. if (!strncmp(p, "bytes ", 6)) {
  323. p += 6;
  324. s->off = strtoll(p, NULL, 10);
  325. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  326. s->filesize = strtoll(slash+1, NULL, 10);
  327. }
  328. h->is_streamed = 0; /* we _can_ in fact seek */
  329. }
  330. static int parse_content_encoding(URLContext *h, const char *p)
  331. {
  332. HTTPContext *s = h->priv_data;
  333. if (!av_strncasecmp(p, "gzip", 4) ||
  334. !av_strncasecmp(p, "deflate", 7)) {
  335. #if CONFIG_ZLIB
  336. s->compressed = 1;
  337. inflateEnd(&s->inflate_stream);
  338. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  339. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  340. s->inflate_stream.msg);
  341. return AVERROR(ENOSYS);
  342. }
  343. if (zlibCompileFlags() & (1 << 17)) {
  344. av_log(h, AV_LOG_WARNING,
  345. "Your zlib was compiled without gzip support.\n");
  346. return AVERROR(ENOSYS);
  347. }
  348. #else
  349. av_log(h, AV_LOG_WARNING,
  350. "Compressed (%s) content, need zlib with gzip support\n", p);
  351. return AVERROR(ENOSYS);
  352. #endif
  353. } else if (!av_strncasecmp(p, "identity", 8)) {
  354. // The normal, no-encoding case (although servers shouldn't include
  355. // the header at all if this is the case).
  356. } else {
  357. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  358. return AVERROR(ENOSYS);
  359. }
  360. return 0;
  361. }
  362. // Concat all Icy- header lines
  363. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  364. {
  365. int len = 4 + strlen(p) + strlen(tag);
  366. int is_first = !s->icy_metadata_headers;
  367. int ret;
  368. if (s->icy_metadata_headers)
  369. len += strlen(s->icy_metadata_headers);
  370. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  371. return ret;
  372. if (is_first)
  373. *s->icy_metadata_headers = '\0';
  374. av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
  375. return 0;
  376. }
  377. static int process_line(URLContext *h, char *line, int line_count,
  378. int *new_location)
  379. {
  380. HTTPContext *s = h->priv_data;
  381. char *tag, *p, *end;
  382. int ret;
  383. /* end of header */
  384. if (line[0] == '\0') {
  385. s->end_header = 1;
  386. return 0;
  387. }
  388. p = line;
  389. if (line_count == 0) {
  390. while (!av_isspace(*p) && *p != '\0')
  391. p++;
  392. while (av_isspace(*p))
  393. p++;
  394. s->http_code = strtol(p, &end, 10);
  395. av_dlog(NULL, "http_code=%d\n", s->http_code);
  396. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  397. return ret;
  398. } else {
  399. while (*p != '\0' && *p != ':')
  400. p++;
  401. if (*p != ':')
  402. return 1;
  403. *p = '\0';
  404. tag = line;
  405. p++;
  406. while (av_isspace(*p))
  407. p++;
  408. if (!av_strcasecmp(tag, "Location")) {
  409. if ((ret = parse_location(s, p)) < 0)
  410. return ret;
  411. *new_location = 1;
  412. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  413. s->filesize = strtoll(p, NULL, 10);
  414. } else if (!av_strcasecmp(tag, "Content-Range")) {
  415. parse_content_range(h, p);
  416. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  417. !strncmp(p, "bytes", 5)) {
  418. h->is_streamed = 0;
  419. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  420. !av_strncasecmp(p, "chunked", 7)) {
  421. s->filesize = -1;
  422. s->chunksize = 0;
  423. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  424. ff_http_auth_handle_header(&s->auth_state, tag, p);
  425. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  426. ff_http_auth_handle_header(&s->auth_state, tag, p);
  427. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  428. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  429. } else if (!av_strcasecmp(tag, "Connection")) {
  430. if (!strcmp(p, "close"))
  431. s->willclose = 1;
  432. } else if (!av_strcasecmp (tag, "Content-Type")) {
  433. av_free(s->mime_type);
  434. s->mime_type = av_strdup(p);
  435. } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
  436. s->icy_metaint = strtoll(p, NULL, 10);
  437. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  438. if ((ret = parse_icy(s, tag, p)) < 0)
  439. return ret;
  440. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  441. if ((ret = parse_content_encoding(h, p)) < 0)
  442. return ret;
  443. }
  444. }
  445. return 1;
  446. }
  447. static inline int has_header(const char *str, const char *header)
  448. {
  449. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  450. if (!str)
  451. return 0;
  452. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  453. }
  454. static int http_read_header(URLContext *h, int *new_location)
  455. {
  456. HTTPContext *s = h->priv_data;
  457. char line[MAX_URL_SIZE];
  458. int err = 0;
  459. s->chunksize = -1;
  460. for (;;) {
  461. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  462. return err;
  463. av_dlog(NULL, "header='%s'\n", line);
  464. err = process_line(h, line, s->line_count, new_location);
  465. if (err < 0)
  466. return err;
  467. if (err == 0)
  468. break;
  469. s->line_count++;
  470. }
  471. return err;
  472. }
  473. static int http_connect(URLContext *h, const char *path, const char *local_path,
  474. const char *hoststr, const char *auth,
  475. const char *proxyauth, int *new_location)
  476. {
  477. HTTPContext *s = h->priv_data;
  478. int post, err;
  479. char headers[HTTP_HEADERS_SIZE] = "";
  480. char *authstr = NULL, *proxyauthstr = NULL;
  481. int64_t off = s->off;
  482. int len = 0;
  483. const char *method;
  484. int send_expect_100 = 0;
  485. /* send http header */
  486. post = h->flags & AVIO_FLAG_WRITE;
  487. if (s->post_data) {
  488. /* force POST method and disable chunked encoding when
  489. * custom HTTP post data is set */
  490. post = 1;
  491. s->chunked_post = 0;
  492. }
  493. if (s->method)
  494. method = s->method;
  495. else
  496. method = post ? "POST" : "GET";
  497. authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
  498. method);
  499. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  500. local_path, method);
  501. if (post && !s->post_data) {
  502. send_expect_100 = s->send_expect_100;
  503. /* The user has supplied authentication but we don't know the auth type,
  504. * send Expect: 100-continue to get the 401 response including the
  505. * WWW-Authenticate header, or an 100 continue if no auth actually
  506. * is needed. */
  507. if (auth && *auth &&
  508. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  509. s->http_code != 401)
  510. send_expect_100 = 1;
  511. }
  512. /* set default headers if needed */
  513. if (!has_header(s->headers, "\r\nUser-Agent: "))
  514. len += av_strlcatf(headers + len, sizeof(headers) - len,
  515. "User-Agent: %s\r\n", s->user_agent);
  516. if (!has_header(s->headers, "\r\nAccept: "))
  517. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  518. sizeof(headers) - len);
  519. // Note: we send this on purpose even when s->off is 0 when we're probing,
  520. // since it allows us to detect more reliably if a (non-conforming)
  521. // server supports seeking by analysing the reply headers.
  522. if (!has_header(s->headers, "\r\nRange: ") && !post) {
  523. len += av_strlcatf(headers + len, sizeof(headers) - len,
  524. "Range: bytes=%"PRId64"-", s->off);
  525. if (s->end_off)
  526. len += av_strlcatf(headers + len, sizeof(headers) - len,
  527. "%"PRId64, s->end_off - 1);
  528. len += av_strlcpy(headers + len, "\r\n",
  529. sizeof(headers) - len);
  530. }
  531. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  532. len += av_strlcatf(headers + len, sizeof(headers) - len,
  533. "Expect: 100-continue\r\n");
  534. if (!has_header(s->headers, "\r\nConnection: ")) {
  535. if (s->multiple_requests) {
  536. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  537. sizeof(headers) - len);
  538. } else {
  539. len += av_strlcpy(headers + len, "Connection: close\r\n",
  540. sizeof(headers) - len);
  541. }
  542. }
  543. if (!has_header(s->headers, "\r\nHost: "))
  544. len += av_strlcatf(headers + len, sizeof(headers) - len,
  545. "Host: %s\r\n", hoststr);
  546. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  547. len += av_strlcatf(headers + len, sizeof(headers) - len,
  548. "Content-Length: %d\r\n", s->post_datalen);
  549. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  550. len += av_strlcatf(headers + len, sizeof(headers) - len,
  551. "Content-Type: %s\r\n", s->content_type);
  552. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
  553. len += av_strlcatf(headers + len, sizeof(headers) - len,
  554. "Icy-MetaData: %d\r\n", 1);
  555. }
  556. /* now add in custom headers */
  557. if (s->headers)
  558. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  559. snprintf(s->buffer, sizeof(s->buffer),
  560. "%s %s HTTP/1.1\r\n"
  561. "%s"
  562. "%s"
  563. "%s"
  564. "%s%s"
  565. "\r\n",
  566. method,
  567. path,
  568. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  569. headers,
  570. authstr ? authstr : "",
  571. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  572. av_freep(&authstr);
  573. av_freep(&proxyauthstr);
  574. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  575. return err;
  576. if (s->post_data)
  577. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  578. return err;
  579. /* init input buffer */
  580. s->buf_ptr = s->buffer;
  581. s->buf_end = s->buffer;
  582. s->line_count = 0;
  583. s->off = 0;
  584. s->icy_data_read = 0;
  585. s->filesize = -1;
  586. s->willclose = 0;
  587. s->end_chunked_post = 0;
  588. s->end_header = 0;
  589. if (post && !s->post_data && !send_expect_100) {
  590. /* Pretend that it did work. We didn't read any header yet, since
  591. * we've still to send the POST data, but the code calling this
  592. * function will check http_code after we return. */
  593. s->http_code = 200;
  594. return 0;
  595. }
  596. /* wait for header */
  597. err = http_read_header(h, new_location);
  598. if (err < 0)
  599. return err;
  600. return (off == s->off) ? 0 : -1;
  601. }
  602. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  603. {
  604. HTTPContext *s = h->priv_data;
  605. int len;
  606. /* read bytes from input buffer first */
  607. len = s->buf_end - s->buf_ptr;
  608. if (len > 0) {
  609. if (len > size)
  610. len = size;
  611. memcpy(buf, s->buf_ptr, len);
  612. s->buf_ptr += len;
  613. } else {
  614. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  615. return AVERROR_EOF;
  616. len = ffurl_read(s->hd, buf, size);
  617. }
  618. if (len > 0) {
  619. s->off += len;
  620. if (s->chunksize > 0)
  621. s->chunksize -= len;
  622. }
  623. return len;
  624. }
  625. #if CONFIG_ZLIB
  626. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  627. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  628. {
  629. HTTPContext *s = h->priv_data;
  630. int ret;
  631. if (!s->inflate_buffer) {
  632. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  633. if (!s->inflate_buffer)
  634. return AVERROR(ENOMEM);
  635. }
  636. if (s->inflate_stream.avail_in == 0) {
  637. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  638. if (read <= 0)
  639. return read;
  640. s->inflate_stream.next_in = s->inflate_buffer;
  641. s->inflate_stream.avail_in = read;
  642. }
  643. s->inflate_stream.avail_out = size;
  644. s->inflate_stream.next_out = buf;
  645. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  646. if (ret != Z_OK && ret != Z_STREAM_END)
  647. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  648. return size - s->inflate_stream.avail_out;
  649. }
  650. #endif
  651. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  652. {
  653. HTTPContext *s = h->priv_data;
  654. int err, new_location;
  655. if (!s->hd)
  656. return AVERROR_EOF;
  657. if (s->end_chunked_post && !s->end_header) {
  658. err = http_read_header(h, &new_location);
  659. if (err < 0)
  660. return err;
  661. }
  662. if (s->chunksize >= 0) {
  663. if (!s->chunksize) {
  664. char line[32];
  665. for(;;) {
  666. do {
  667. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  668. return err;
  669. } while (!*line); /* skip CR LF from last chunk */
  670. s->chunksize = strtoll(line, NULL, 16);
  671. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  672. if (!s->chunksize)
  673. return 0;
  674. break;
  675. }
  676. }
  677. size = FFMIN(size, s->chunksize);
  678. }
  679. #if CONFIG_ZLIB
  680. if (s->compressed)
  681. return http_buf_read_compressed(h, buf, size);
  682. #endif
  683. return http_buf_read(h, buf, size);
  684. }
  685. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  686. {
  687. int pos = 0;
  688. while (pos < size) {
  689. int len = http_read_stream(h, buf + pos, size - pos);
  690. if (len < 0)
  691. return len;
  692. pos += len;
  693. }
  694. return pos;
  695. }
  696. static int store_icy(URLContext *h, int size)
  697. {
  698. HTTPContext *s = h->priv_data;
  699. /* until next metadata packet */
  700. int remaining = s->icy_metaint - s->icy_data_read;
  701. if (remaining < 0)
  702. return AVERROR_INVALIDDATA;
  703. if (!remaining) {
  704. // The metadata packet is variable sized. It has a 1 byte header
  705. // which sets the length of the packet (divided by 16). If it's 0,
  706. // the metadata doesn't change. After the packet, icy_metaint bytes
  707. // of normal data follow.
  708. uint8_t ch;
  709. int len = http_read_stream_all(h, &ch, 1);
  710. if (len < 0)
  711. return len;
  712. if (ch > 0) {
  713. char data[255 * 16 + 1];
  714. int ret;
  715. len = ch * 16;
  716. ret = http_read_stream_all(h, data, len);
  717. if (ret < 0)
  718. return ret;
  719. data[len + 1] = 0;
  720. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  721. return ret;
  722. }
  723. s->icy_data_read = 0;
  724. remaining = s->icy_metaint;
  725. }
  726. return FFMIN(size, remaining);
  727. }
  728. static int http_read(URLContext *h, uint8_t *buf, int size)
  729. {
  730. HTTPContext *s = h->priv_data;
  731. if (s->icy_metaint > 0) {
  732. size = store_icy(h, size);
  733. if (size < 0)
  734. return size;
  735. }
  736. size = http_read_stream(h, buf, size);
  737. if (size > 0)
  738. s->icy_data_read += size;
  739. return 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_close(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, ret;
  801. AVDictionary *options = NULL;
  802. if (whence == AVSEEK_SIZE)
  803. return s->filesize;
  804. else if ((whence == SEEK_CUR && off == 0) ||
  805. (whence == SEEK_SET && off == s->off))
  806. return s->off;
  807. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  808. return AVERROR(ENOSYS);
  809. /* we save the old context in case the seek fails */
  810. old_buf_size = s->buf_end - s->buf_ptr;
  811. memcpy(old_buf, s->buf_ptr, old_buf_size);
  812. s->hd = NULL;
  813. if (whence == SEEK_CUR)
  814. off += s->off;
  815. else if (whence == SEEK_END)
  816. off += s->filesize;
  817. s->off = off;
  818. /* if it fails, continue on old connection */
  819. av_dict_copy(&options, s->chained_options, 0);
  820. if ((ret = http_open_cnx(h, &options)) < 0) {
  821. av_dict_free(&options);
  822. memcpy(s->buffer, old_buf, old_buf_size);
  823. s->buf_ptr = s->buffer;
  824. s->buf_end = s->buffer + old_buf_size;
  825. s->hd = old_hd;
  826. s->off = old_off;
  827. return ret;
  828. }
  829. av_dict_free(&options);
  830. ffurl_close(old_hd);
  831. return off;
  832. }
  833. static int
  834. http_get_file_handle(URLContext *h)
  835. {
  836. HTTPContext *s = h->priv_data;
  837. return ffurl_get_file_handle(s->hd);
  838. }
  839. #define HTTP_CLASS(flavor)\
  840. static const AVClass flavor ## _context_class = {\
  841. .class_name = #flavor,\
  842. .item_name = av_default_item_name,\
  843. .option = options,\
  844. .version = LIBAVUTIL_VERSION_INT,\
  845. }
  846. #if CONFIG_HTTP_PROTOCOL
  847. HTTP_CLASS(http);
  848. URLProtocol ff_http_protocol = {
  849. .name = "http",
  850. .url_open2 = http_open,
  851. .url_read = http_read,
  852. .url_write = http_write,
  853. .url_seek = http_seek,
  854. .url_close = http_close,
  855. .url_get_file_handle = http_get_file_handle,
  856. .url_shutdown = http_shutdown,
  857. .priv_data_size = sizeof(HTTPContext),
  858. .priv_data_class = &http_context_class,
  859. .flags = URL_PROTOCOL_FLAG_NETWORK,
  860. };
  861. #endif
  862. #if CONFIG_HTTPS_PROTOCOL
  863. HTTP_CLASS(https);
  864. URLProtocol ff_https_protocol = {
  865. .name = "https",
  866. .url_open2 = http_open,
  867. .url_read = http_read,
  868. .url_write = http_write,
  869. .url_seek = http_seek,
  870. .url_close = http_close,
  871. .url_get_file_handle = http_get_file_handle,
  872. .url_shutdown = http_shutdown,
  873. .priv_data_size = sizeof(HTTPContext),
  874. .priv_data_class = &https_context_class,
  875. .flags = URL_PROTOCOL_FLAG_NETWORK,
  876. };
  877. #endif
  878. #if CONFIG_HTTPPROXY_PROTOCOL
  879. static int http_proxy_close(URLContext *h)
  880. {
  881. HTTPContext *s = h->priv_data;
  882. if (s->hd)
  883. ffurl_close(s->hd);
  884. return 0;
  885. }
  886. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  887. {
  888. HTTPContext *s = h->priv_data;
  889. char hostname[1024], hoststr[1024];
  890. char auth[1024], pathbuf[1024], *path;
  891. char lower_url[100];
  892. int port, ret = 0, attempts = 0;
  893. HTTPAuthType cur_auth_type;
  894. char *authstr;
  895. int new_loc;
  896. h->is_streamed = 1;
  897. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  898. pathbuf, sizeof(pathbuf), uri);
  899. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  900. path = pathbuf;
  901. if (*path == '/')
  902. path++;
  903. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  904. NULL);
  905. redo:
  906. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  907. &h->interrupt_callback, NULL);
  908. if (ret < 0)
  909. return ret;
  910. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  911. path, "CONNECT");
  912. snprintf(s->buffer, sizeof(s->buffer),
  913. "CONNECT %s HTTP/1.1\r\n"
  914. "Host: %s\r\n"
  915. "Connection: close\r\n"
  916. "%s%s"
  917. "\r\n",
  918. path,
  919. hoststr,
  920. authstr ? "Proxy-" : "", authstr ? authstr : "");
  921. av_freep(&authstr);
  922. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  923. goto fail;
  924. s->buf_ptr = s->buffer;
  925. s->buf_end = s->buffer;
  926. s->line_count = 0;
  927. s->filesize = -1;
  928. cur_auth_type = s->proxy_auth_state.auth_type;
  929. /* Note: This uses buffering, potentially reading more than the
  930. * HTTP header. If tunneling a protocol where the server starts
  931. * the conversation, we might buffer part of that here, too.
  932. * Reading that requires using the proper ffurl_read() function
  933. * on this URLContext, not using the fd directly (as the tls
  934. * protocol does). This shouldn't be an issue for tls though,
  935. * since the client starts the conversation there, so there
  936. * is no extra data that we might buffer up here.
  937. */
  938. ret = http_read_header(h, &new_loc);
  939. if (ret < 0)
  940. goto fail;
  941. attempts++;
  942. if (s->http_code == 407 &&
  943. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  944. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  945. ffurl_close(s->hd);
  946. s->hd = NULL;
  947. goto redo;
  948. }
  949. if (s->http_code < 400)
  950. return 0;
  951. ret = AVERROR(EIO);
  952. fail:
  953. http_proxy_close(h);
  954. return ret;
  955. }
  956. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  957. {
  958. HTTPContext *s = h->priv_data;
  959. return ffurl_write(s->hd, buf, size);
  960. }
  961. URLProtocol ff_httpproxy_protocol = {
  962. .name = "httpproxy",
  963. .url_open = http_proxy_open,
  964. .url_read = http_buf_read,
  965. .url_write = http_proxy_write,
  966. .url_close = http_proxy_close,
  967. .url_get_file_handle = http_get_file_handle,
  968. .priv_data_size = sizeof(HTTPContext),
  969. .flags = URL_PROTOCOL_FLAG_NETWORK,
  970. };
  971. #endif