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.

1067 lines
33KB

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