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.

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