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.

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