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.

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