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.

956 lines
30KB

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