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.

914 lines
29KB

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