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.

1105 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 "config.h"
  22. #if CONFIG_ZLIB
  23. #include <zlib.h>
  24. #endif /* CONFIG_ZLIB */
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/opt.h"
  27. #include "avformat.h"
  28. #include "http.h"
  29. #include "httpauth.h"
  30. #include "internal.h"
  31. #include "network.h"
  32. #include "os_support.h"
  33. #include "url.h"
  34. /* XXX: POST protocol is not completely implemented because avconv uses
  35. * only a subset of it. */
  36. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  37. * to be large enough to fit the full request headers (including long
  38. * path names). */
  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 /* CONFIG_ZLIB */
  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,
  118. sizeof(HTTPAuthState));
  119. memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
  120. &((HTTPContext *)src->priv_data)->proxy_auth_state,
  121. sizeof(HTTPAuthState));
  122. }
  123. /* return non zero if error */
  124. static int http_open_cnx(URLContext *h, AVDictionary **options)
  125. {
  126. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  127. char hostname[1024], hoststr[1024], proto[10];
  128. char auth[1024], proxyauth[1024] = "";
  129. char path1[MAX_URL_SIZE];
  130. char buf[1024], urlbuf[MAX_URL_SIZE];
  131. int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
  132. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  133. HTTPContext *s = h->priv_data;
  134. /* fill the dest addr */
  135. redo:
  136. /* needed in any case to build the host string */
  137. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  138. hostname, sizeof(hostname), &port,
  139. path1, sizeof(path1), s->location);
  140. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  141. proxy_path = getenv("http_proxy");
  142. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  143. proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
  144. if (!strcmp(proto, "https")) {
  145. lower_proto = "tls";
  146. use_proxy = 0;
  147. if (port < 0)
  148. port = 443;
  149. }
  150. if (port < 0)
  151. port = 80;
  152. if (path1[0] == '\0')
  153. path = "/";
  154. else
  155. path = path1;
  156. local_path = path;
  157. if (use_proxy) {
  158. /* Reassemble the request URL without auth string - we don't
  159. * want to leak the auth to the proxy. */
  160. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  161. path1);
  162. path = urlbuf;
  163. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  164. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  165. }
  166. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  167. if (!s->hd) {
  168. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  169. &h->interrupt_callback, options);
  170. if (err < 0)
  171. goto fail;
  172. }
  173. cur_auth_type = s->auth_state.auth_type;
  174. cur_proxy_auth_type = s->auth_state.auth_type;
  175. if (http_connect(h, path, local_path, hoststr,
  176. auth, proxyauth, &location_changed) < 0)
  177. goto fail;
  178. attempts++;
  179. if (s->http_code == 401) {
  180. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  181. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  182. ffurl_close(s->hd);
  183. s->hd = NULL;
  184. goto redo;
  185. } else
  186. goto fail;
  187. }
  188. if (s->http_code == 407) {
  189. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  190. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  191. ffurl_close(s->hd);
  192. s->hd = NULL;
  193. goto redo;
  194. } else
  195. goto fail;
  196. }
  197. if ((s->http_code == 301 || s->http_code == 302 ||
  198. s->http_code == 303 || s->http_code == 307) &&
  199. location_changed == 1) {
  200. /* url moved, get next */
  201. ffurl_close(s->hd);
  202. s->hd = NULL;
  203. if (redirects++ >= MAX_REDIRECTS)
  204. return AVERROR(EIO);
  205. /* Restart the authentication process with the new target, which
  206. * might use a different auth mechanism. */
  207. memset(&s->auth_state, 0, sizeof(s->auth_state));
  208. attempts = 0;
  209. location_changed = 0;
  210. goto redo;
  211. }
  212. return 0;
  213. fail:
  214. if (s->hd)
  215. ffurl_close(s->hd);
  216. s->hd = NULL;
  217. return AVERROR(EIO);
  218. }
  219. int ff_http_do_new_request(URLContext *h, const char *uri)
  220. {
  221. HTTPContext *s = h->priv_data;
  222. AVDictionary *options = NULL;
  223. int ret;
  224. s->off = 0;
  225. s->icy_data_read = 0;
  226. av_free(s->location);
  227. s->location = av_strdup(uri);
  228. if (!s->location)
  229. return AVERROR(ENOMEM);
  230. av_dict_copy(&options, s->chained_options, 0);
  231. ret = http_open_cnx(h, &options);
  232. av_dict_free(&options);
  233. return ret;
  234. }
  235. static int http_open(URLContext *h, const char *uri, int flags,
  236. AVDictionary **options)
  237. {
  238. HTTPContext *s = h->priv_data;
  239. int ret;
  240. h->is_streamed = 1;
  241. s->filesize = -1;
  242. s->location = av_strdup(uri);
  243. if (!s->location)
  244. return AVERROR(ENOMEM);
  245. if (options)
  246. av_dict_copy(&s->chained_options, *options, 0);
  247. if (s->headers) {
  248. int len = strlen(s->headers);
  249. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  250. av_log(h, AV_LOG_WARNING,
  251. "No trailing CRLF found in HTTP header.\n");
  252. }
  253. ret = http_open_cnx(h, options);
  254. if (ret < 0)
  255. av_dict_free(&s->chained_options);
  256. return ret;
  257. }
  258. static int http_getc(HTTPContext *s)
  259. {
  260. int len;
  261. if (s->buf_ptr >= s->buf_end) {
  262. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  263. if (len < 0) {
  264. return len;
  265. } else if (len == 0) {
  266. return AVERROR_EOF;
  267. } else {
  268. s->buf_ptr = s->buffer;
  269. s->buf_end = s->buffer + len;
  270. }
  271. }
  272. return *s->buf_ptr++;
  273. }
  274. static int http_get_line(HTTPContext *s, char *line, int line_size)
  275. {
  276. int ch;
  277. char *q;
  278. q = line;
  279. for (;;) {
  280. ch = http_getc(s);
  281. if (ch < 0)
  282. return ch;
  283. if (ch == '\n') {
  284. /* process line */
  285. if (q > line && q[-1] == '\r')
  286. q--;
  287. *q = '\0';
  288. return 0;
  289. } else {
  290. if ((q - line) < line_size - 1)
  291. *q++ = ch;
  292. }
  293. }
  294. }
  295. static int check_http_code(URLContext *h, int http_code, const char *end)
  296. {
  297. HTTPContext *s = h->priv_data;
  298. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  299. * don't abort until all headers have been parsed. */
  300. if (http_code >= 400 && http_code < 600 &&
  301. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  302. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  303. end += strspn(end, SPACE_CHARS);
  304. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  305. return AVERROR(EIO);
  306. }
  307. return 0;
  308. }
  309. static int parse_location(HTTPContext *s, const char *p)
  310. {
  311. char redirected_location[MAX_URL_SIZE], *new_loc;
  312. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  313. s->location, p);
  314. new_loc = av_strdup(redirected_location);
  315. if (!new_loc)
  316. return AVERROR(ENOMEM);
  317. av_free(s->location);
  318. s->location = new_loc;
  319. return 0;
  320. }
  321. /* "bytes $from-$to/$document_size" */
  322. static void parse_content_range(URLContext *h, const char *p)
  323. {
  324. HTTPContext *s = h->priv_data;
  325. const char *slash;
  326. if (!strncmp(p, "bytes ", 6)) {
  327. p += 6;
  328. s->off = strtoll(p, NULL, 10);
  329. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  330. s->filesize = strtoll(slash + 1, NULL, 10);
  331. }
  332. h->is_streamed = 0; /* we _can_ in fact seek */
  333. }
  334. static int parse_content_encoding(URLContext *h, const char *p)
  335. {
  336. HTTPContext *s = h->priv_data;
  337. if (!av_strncasecmp(p, "gzip", 4) ||
  338. !av_strncasecmp(p, "deflate", 7)) {
  339. #if CONFIG_ZLIB
  340. s->compressed = 1;
  341. inflateEnd(&s->inflate_stream);
  342. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  343. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  344. s->inflate_stream.msg);
  345. return AVERROR(ENOSYS);
  346. }
  347. if (zlibCompileFlags() & (1 << 17)) {
  348. av_log(h, AV_LOG_WARNING,
  349. "Your zlib was compiled without gzip support.\n");
  350. return AVERROR(ENOSYS);
  351. }
  352. #else
  353. av_log(h, AV_LOG_WARNING,
  354. "Compressed (%s) content, need zlib with gzip support\n", p);
  355. return AVERROR(ENOSYS);
  356. #endif /* CONFIG_ZLIB */
  357. } else if (!av_strncasecmp(p, "identity", 8)) {
  358. // The normal, no-encoding case (although servers shouldn't include
  359. // the header at all if this is the case).
  360. } else {
  361. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  362. return AVERROR(ENOSYS);
  363. }
  364. return 0;
  365. }
  366. // Concat all Icy- header lines
  367. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  368. {
  369. int len = 4 + strlen(p) + strlen(tag);
  370. int is_first = !s->icy_metadata_headers;
  371. int ret;
  372. if (s->icy_metadata_headers)
  373. len += strlen(s->icy_metadata_headers);
  374. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  375. return ret;
  376. if (is_first)
  377. *s->icy_metadata_headers = '\0';
  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[HTTP_HEADERS_SIZE] = "";
  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. if (s->method)
  498. method = s->method;
  499. else
  500. method = post ? "POST" : "GET";
  501. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  502. local_path, 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. if (!has_header(s->headers, "\r\nHost: "))
  547. len += av_strlcatf(headers + len, sizeof(headers) - len,
  548. "Host: %s\r\n", hoststr);
  549. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  550. len += av_strlcatf(headers + len, sizeof(headers) - len,
  551. "Content-Length: %d\r\n", s->post_datalen);
  552. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  553. len += av_strlcatf(headers + len, sizeof(headers) - len,
  554. "Content-Type: %s\r\n", s->content_type);
  555. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  556. len += av_strlcatf(headers + len, sizeof(headers) - len,
  557. "Icy-MetaData: %d\r\n", 1);
  558. /* now add in custom headers */
  559. if (s->headers)
  560. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  561. snprintf(s->buffer, sizeof(s->buffer),
  562. "%s %s HTTP/1.1\r\n"
  563. "%s"
  564. "%s"
  565. "%s"
  566. "%s%s"
  567. "\r\n",
  568. method,
  569. path,
  570. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  571. headers,
  572. authstr ? authstr : "",
  573. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  574. av_freep(&authstr);
  575. av_freep(&proxyauthstr);
  576. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  577. return err;
  578. if (s->post_data)
  579. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  580. return err;
  581. /* init input buffer */
  582. s->buf_ptr = s->buffer;
  583. s->buf_end = s->buffer;
  584. s->line_count = 0;
  585. s->off = 0;
  586. s->icy_data_read = 0;
  587. s->filesize = -1;
  588. s->willclose = 0;
  589. s->end_chunked_post = 0;
  590. s->end_header = 0;
  591. if (post && !s->post_data && !send_expect_100) {
  592. /* Pretend that it did work. We didn't read any header yet, since
  593. * we've still to send the POST data, but the code calling this
  594. * function will check http_code after we return. */
  595. s->http_code = 200;
  596. return 0;
  597. }
  598. /* wait for header */
  599. err = http_read_header(h, new_location);
  600. if (err < 0)
  601. return err;
  602. return (off == s->off) ? 0 : -1;
  603. }
  604. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  605. {
  606. HTTPContext *s = h->priv_data;
  607. int len;
  608. /* read bytes from input buffer first */
  609. len = s->buf_end - s->buf_ptr;
  610. if (len > 0) {
  611. if (len > size)
  612. len = size;
  613. memcpy(buf, s->buf_ptr, len);
  614. s->buf_ptr += len;
  615. } else {
  616. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  617. return AVERROR_EOF;
  618. len = ffurl_read(s->hd, buf, size);
  619. }
  620. if (len > 0) {
  621. s->off += len;
  622. if (s->chunksize > 0)
  623. s->chunksize -= len;
  624. }
  625. return len;
  626. }
  627. #if CONFIG_ZLIB
  628. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  629. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  630. {
  631. HTTPContext *s = h->priv_data;
  632. int ret;
  633. if (!s->inflate_buffer) {
  634. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  635. if (!s->inflate_buffer)
  636. return AVERROR(ENOMEM);
  637. }
  638. if (s->inflate_stream.avail_in == 0) {
  639. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  640. if (read <= 0)
  641. return read;
  642. s->inflate_stream.next_in = s->inflate_buffer;
  643. s->inflate_stream.avail_in = read;
  644. }
  645. s->inflate_stream.avail_out = size;
  646. s->inflate_stream.next_out = buf;
  647. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  648. if (ret != Z_OK && ret != Z_STREAM_END)
  649. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  650. ret, s->inflate_stream.msg);
  651. return size - s->inflate_stream.avail_out;
  652. }
  653. #endif /* CONFIG_ZLIB */
  654. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  655. {
  656. HTTPContext *s = h->priv_data;
  657. int err, new_location;
  658. if (!s->hd)
  659. return AVERROR_EOF;
  660. if (s->end_chunked_post && !s->end_header) {
  661. err = http_read_header(h, &new_location);
  662. if (err < 0)
  663. return err;
  664. }
  665. if (s->chunksize >= 0) {
  666. if (!s->chunksize) {
  667. char line[32];
  668. for (;;) {
  669. do {
  670. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  671. return err;
  672. } while (!*line); /* skip CR LF from last chunk */
  673. s->chunksize = strtoll(line, NULL, 16);
  674. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
  675. 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 /* CONFIG_ZLIB */
  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 follows. */
  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 /* CONFIG_ZLIB */
  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. if (s->hd)
  793. ffurl_close(s->hd);
  794. av_dict_free(&s->chained_options);
  795. return ret;
  796. }
  797. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  798. {
  799. HTTPContext *s = h->priv_data;
  800. URLContext *old_hd = s->hd;
  801. int64_t old_off = s->off;
  802. uint8_t old_buf[BUFFER_SIZE];
  803. int old_buf_size, ret;
  804. AVDictionary *options = NULL;
  805. if (whence == AVSEEK_SIZE)
  806. return s->filesize;
  807. else if ((whence == SEEK_CUR && off == 0) ||
  808. (whence == SEEK_SET && off == s->off))
  809. return s->off;
  810. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  811. return AVERROR(ENOSYS);
  812. /* we save the old context in case the seek fails */
  813. old_buf_size = s->buf_end - s->buf_ptr;
  814. memcpy(old_buf, s->buf_ptr, old_buf_size);
  815. s->hd = NULL;
  816. if (whence == SEEK_CUR)
  817. off += s->off;
  818. else if (whence == SEEK_END)
  819. off += s->filesize;
  820. s->off = off;
  821. /* if it fails, continue on old connection */
  822. av_dict_copy(&options, s->chained_options, 0);
  823. if ((ret = http_open_cnx(h, &options)) < 0) {
  824. av_dict_free(&options);
  825. memcpy(s->buffer, old_buf, old_buf_size);
  826. s->buf_ptr = s->buffer;
  827. s->buf_end = s->buffer + old_buf_size;
  828. s->hd = old_hd;
  829. s->off = old_off;
  830. return ret;
  831. }
  832. av_dict_free(&options);
  833. ffurl_close(old_hd);
  834. return off;
  835. }
  836. static int http_get_file_handle(URLContext *h)
  837. {
  838. HTTPContext *s = h->priv_data;
  839. return ffurl_get_file_handle(s->hd);
  840. }
  841. #define HTTP_CLASS(flavor) \
  842. static const AVClass flavor ## _context_class = { \
  843. .class_name = # flavor, \
  844. .item_name = av_default_item_name, \
  845. .option = options, \
  846. .version = LIBAVUTIL_VERSION_INT, \
  847. }
  848. #if CONFIG_HTTP_PROTOCOL
  849. HTTP_CLASS(http);
  850. URLProtocol ff_http_protocol = {
  851. .name = "http",
  852. .url_open2 = http_open,
  853. .url_read = http_read,
  854. .url_write = http_write,
  855. .url_seek = http_seek,
  856. .url_close = http_close,
  857. .url_get_file_handle = http_get_file_handle,
  858. .url_shutdown = http_shutdown,
  859. .priv_data_size = sizeof(HTTPContext),
  860. .priv_data_class = &http_context_class,
  861. .flags = URL_PROTOCOL_FLAG_NETWORK,
  862. };
  863. #endif /* CONFIG_HTTP_PROTOCOL */
  864. #if CONFIG_HTTPS_PROTOCOL
  865. HTTP_CLASS(https);
  866. URLProtocol ff_https_protocol = {
  867. .name = "https",
  868. .url_open2 = http_open,
  869. .url_read = http_read,
  870. .url_write = http_write,
  871. .url_seek = http_seek,
  872. .url_close = http_close,
  873. .url_get_file_handle = http_get_file_handle,
  874. .url_shutdown = http_shutdown,
  875. .priv_data_size = sizeof(HTTPContext),
  876. .priv_data_class = &https_context_class,
  877. .flags = URL_PROTOCOL_FLAG_NETWORK,
  878. };
  879. #endif /* CONFIG_HTTPS_PROTOCOL */
  880. #if CONFIG_HTTPPROXY_PROTOCOL
  881. static int http_proxy_close(URLContext *h)
  882. {
  883. HTTPContext *s = h->priv_data;
  884. if (s->hd)
  885. ffurl_close(s->hd);
  886. return 0;
  887. }
  888. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  889. {
  890. HTTPContext *s = h->priv_data;
  891. char hostname[1024], hoststr[1024];
  892. char auth[1024], pathbuf[1024], *path;
  893. char lower_url[100];
  894. int port, ret = 0, attempts = 0;
  895. HTTPAuthType cur_auth_type;
  896. char *authstr;
  897. int new_loc;
  898. h->is_streamed = 1;
  899. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  900. pathbuf, sizeof(pathbuf), uri);
  901. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  902. path = pathbuf;
  903. if (*path == '/')
  904. path++;
  905. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  906. NULL);
  907. redo:
  908. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  909. &h->interrupt_callback, NULL);
  910. if (ret < 0)
  911. return ret;
  912. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  913. path, "CONNECT");
  914. snprintf(s->buffer, sizeof(s->buffer),
  915. "CONNECT %s HTTP/1.1\r\n"
  916. "Host: %s\r\n"
  917. "Connection: close\r\n"
  918. "%s%s"
  919. "\r\n",
  920. path,
  921. hoststr,
  922. authstr ? "Proxy-" : "", authstr ? authstr : "");
  923. av_freep(&authstr);
  924. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  925. goto fail;
  926. s->buf_ptr = s->buffer;
  927. s->buf_end = s->buffer;
  928. s->line_count = 0;
  929. s->filesize = -1;
  930. cur_auth_type = s->proxy_auth_state.auth_type;
  931. /* Note: This uses buffering, potentially reading more than the
  932. * HTTP header. If tunneling a protocol where the server starts
  933. * the conversation, we might buffer part of that here, too.
  934. * Reading that requires using the proper ffurl_read() function
  935. * on this URLContext, not using the fd directly (as the tls
  936. * protocol does). This shouldn't be an issue for tls though,
  937. * since the client starts the conversation there, so there
  938. * is no extra data that we might buffer up here.
  939. */
  940. ret = http_read_header(h, &new_loc);
  941. if (ret < 0)
  942. goto fail;
  943. attempts++;
  944. if (s->http_code == 407 &&
  945. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  946. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  947. ffurl_close(s->hd);
  948. s->hd = NULL;
  949. goto redo;
  950. }
  951. if (s->http_code < 400)
  952. return 0;
  953. ret = AVERROR(EIO);
  954. fail:
  955. http_proxy_close(h);
  956. return ret;
  957. }
  958. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  959. {
  960. HTTPContext *s = h->priv_data;
  961. return ffurl_write(s->hd, buf, size);
  962. }
  963. URLProtocol ff_httpproxy_protocol = {
  964. .name = "httpproxy",
  965. .url_open = http_proxy_open,
  966. .url_read = http_buf_read,
  967. .url_write = http_proxy_write,
  968. .url_close = http_proxy_close,
  969. .url_get_file_handle = http_get_file_handle,
  970. .priv_data_size = sizeof(HTTPContext),
  971. .flags = URL_PROTOCOL_FLAG_NETWORK,
  972. };
  973. #endif /* CONFIG_HTTPPROXY_PROTOCOL */