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.

900 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 && s->auth_state.auth_type == HTTP_AUTH_NONE &&
  419. s->http_code != 401)
  420. send_expect_100 = 1;
  421. }
  422. /* set default headers if needed */
  423. if (!has_header(s->headers, "\r\nUser-Agent: "))
  424. len += av_strlcatf(headers + len, sizeof(headers) - len,
  425. "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
  426. if (!has_header(s->headers, "\r\nAccept: "))
  427. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  428. sizeof(headers) - len);
  429. if (!has_header(s->headers, "\r\nRange: ") && !post)
  430. len += av_strlcatf(headers + len, sizeof(headers) - len,
  431. "Range: bytes=%"PRId64"-\r\n", s->off);
  432. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  433. len += av_strlcatf(headers + len, sizeof(headers) - len,
  434. "Expect: 100-continue\r\n");
  435. if (!has_header(s->headers, "\r\nConnection: ")) {
  436. if (s->multiple_requests) {
  437. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  438. sizeof(headers) - len);
  439. } else {
  440. len += av_strlcpy(headers + len, "Connection: close\r\n",
  441. sizeof(headers) - len);
  442. }
  443. }
  444. if (!has_header(s->headers, "\r\nHost: "))
  445. len += av_strlcatf(headers + len, sizeof(headers) - len,
  446. "Host: %s\r\n", hoststr);
  447. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  448. len += av_strlcatf(headers + len, sizeof(headers) - len,
  449. "Content-Length: %d\r\n", s->post_datalen);
  450. /* now add in custom headers */
  451. if (s->headers)
  452. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  453. snprintf(s->buffer, sizeof(s->buffer),
  454. "%s %s HTTP/1.1\r\n"
  455. "%s"
  456. "%s"
  457. "%s"
  458. "%s%s"
  459. "\r\n",
  460. method,
  461. path,
  462. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  463. headers,
  464. authstr ? authstr : "",
  465. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  466. av_freep(&authstr);
  467. av_freep(&proxyauthstr);
  468. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  469. return err;
  470. if (s->post_data)
  471. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  472. return err;
  473. /* init input buffer */
  474. s->buf_ptr = s->buffer;
  475. s->buf_end = s->buffer;
  476. s->line_count = 0;
  477. s->off = 0;
  478. s->filesize = -1;
  479. s->willclose = 0;
  480. s->end_chunked_post = 0;
  481. s->end_header = 0;
  482. if (post && !s->post_data && !send_expect_100) {
  483. /* Pretend that it did work. We didn't read any header yet, since
  484. * we've still to send the POST data, but the code calling this
  485. * function will check http_code after we return. */
  486. s->http_code = 200;
  487. return 0;
  488. }
  489. /* wait for header */
  490. err = http_read_header(h, new_location);
  491. if (err < 0)
  492. return err;
  493. return (off == s->off) ? 0 : -1;
  494. }
  495. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  496. {
  497. HTTPContext *s = h->priv_data;
  498. int len;
  499. /* read bytes from input buffer first */
  500. len = s->buf_end - s->buf_ptr;
  501. if (len > 0) {
  502. if (len > size)
  503. len = size;
  504. memcpy(buf, s->buf_ptr, len);
  505. s->buf_ptr += len;
  506. } else {
  507. if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
  508. return AVERROR_EOF;
  509. len = ffurl_read(s->hd, buf, size);
  510. }
  511. if (len > 0) {
  512. s->off += len;
  513. if (s->chunksize > 0)
  514. s->chunksize -= len;
  515. }
  516. return len;
  517. }
  518. #if CONFIG_ZLIB
  519. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  520. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  521. {
  522. HTTPContext *s = h->priv_data;
  523. int ret;
  524. if (!s->inflate_buffer) {
  525. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  526. if (!s->inflate_buffer)
  527. return AVERROR(ENOMEM);
  528. }
  529. if (s->inflate_stream.avail_in == 0) {
  530. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  531. if (read <= 0)
  532. return read;
  533. s->inflate_stream.next_in = s->inflate_buffer;
  534. s->inflate_stream.avail_in = read;
  535. }
  536. s->inflate_stream.avail_out = size;
  537. s->inflate_stream.next_out = buf;
  538. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  539. if (ret != Z_OK && ret != Z_STREAM_END)
  540. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
  541. return size - s->inflate_stream.avail_out;
  542. }
  543. #endif
  544. static int http_read(URLContext *h, uint8_t *buf, int size)
  545. {
  546. HTTPContext *s = h->priv_data;
  547. int err, new_location;
  548. if (!s->hd)
  549. return AVERROR_EOF;
  550. if (s->end_chunked_post && !s->end_header) {
  551. err = http_read_header(h, &new_location);
  552. if (err < 0)
  553. return err;
  554. }
  555. if (s->chunksize >= 0) {
  556. if (!s->chunksize) {
  557. char line[32];
  558. for(;;) {
  559. do {
  560. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  561. return err;
  562. } while (!*line); /* skip CR LF from last chunk */
  563. s->chunksize = strtoll(line, NULL, 16);
  564. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
  565. if (!s->chunksize)
  566. return 0;
  567. break;
  568. }
  569. }
  570. size = FFMIN(size, s->chunksize);
  571. }
  572. #if CONFIG_ZLIB
  573. if (s->compressed)
  574. return http_buf_read_compressed(h, buf, size);
  575. #endif
  576. return http_buf_read(h, buf, size);
  577. }
  578. /* used only when posting data */
  579. static int http_write(URLContext *h, const uint8_t *buf, int size)
  580. {
  581. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  582. int ret;
  583. char crlf[] = "\r\n";
  584. HTTPContext *s = h->priv_data;
  585. if (!s->chunked_post) {
  586. /* non-chunked data is sent without any special encoding */
  587. return ffurl_write(s->hd, buf, size);
  588. }
  589. /* silently ignore zero-size data since chunk encoding that would
  590. * signal EOF */
  591. if (size > 0) {
  592. /* upload data using chunked encoding */
  593. snprintf(temp, sizeof(temp), "%x\r\n", size);
  594. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  595. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  596. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  597. return ret;
  598. }
  599. return size;
  600. }
  601. static int http_shutdown(URLContext *h, int flags)
  602. {
  603. int ret = 0;
  604. char footer[] = "0\r\n\r\n";
  605. HTTPContext *s = h->priv_data;
  606. /* signal end of chunked encoding if used */
  607. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  608. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  609. ret = ret > 0 ? 0 : ret;
  610. s->end_chunked_post = 1;
  611. }
  612. return ret;
  613. }
  614. static int http_close(URLContext *h)
  615. {
  616. int ret = 0;
  617. HTTPContext *s = h->priv_data;
  618. #if CONFIG_ZLIB
  619. inflateEnd(&s->inflate_stream);
  620. av_freep(&s->inflate_buffer);
  621. #endif
  622. if (!s->end_chunked_post) {
  623. /* Close the write direction by sending the end of chunked encoding. */
  624. ret = http_shutdown(h, h->flags);
  625. }
  626. if (s->hd)
  627. ffurl_close(s->hd);
  628. av_dict_free(&s->chained_options);
  629. return ret;
  630. }
  631. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  632. {
  633. HTTPContext *s = h->priv_data;
  634. URLContext *old_hd = s->hd;
  635. int64_t old_off = s->off;
  636. uint8_t old_buf[BUFFER_SIZE];
  637. int old_buf_size;
  638. AVDictionary *options = NULL;
  639. if (whence == AVSEEK_SIZE)
  640. return s->filesize;
  641. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  642. return -1;
  643. /* we save the old context in case the seek fails */
  644. old_buf_size = s->buf_end - s->buf_ptr;
  645. memcpy(old_buf, s->buf_ptr, old_buf_size);
  646. s->hd = NULL;
  647. if (whence == SEEK_CUR)
  648. off += s->off;
  649. else if (whence == SEEK_END)
  650. off += s->filesize;
  651. s->off = off;
  652. /* if it fails, continue on old connection */
  653. av_dict_copy(&options, s->chained_options, 0);
  654. if (http_open_cnx(h, &options) < 0) {
  655. av_dict_free(&options);
  656. memcpy(s->buffer, old_buf, old_buf_size);
  657. s->buf_ptr = s->buffer;
  658. s->buf_end = s->buffer + old_buf_size;
  659. s->hd = old_hd;
  660. s->off = old_off;
  661. return -1;
  662. }
  663. av_dict_free(&options);
  664. ffurl_close(old_hd);
  665. return off;
  666. }
  667. static int
  668. http_get_file_handle(URLContext *h)
  669. {
  670. HTTPContext *s = h->priv_data;
  671. return ffurl_get_file_handle(s->hd);
  672. }
  673. #if CONFIG_HTTP_PROTOCOL
  674. URLProtocol ff_http_protocol = {
  675. .name = "http",
  676. .url_open2 = http_open,
  677. .url_read = http_read,
  678. .url_write = http_write,
  679. .url_seek = http_seek,
  680. .url_close = http_close,
  681. .url_get_file_handle = http_get_file_handle,
  682. .url_shutdown = http_shutdown,
  683. .priv_data_size = sizeof(HTTPContext),
  684. .priv_data_class = &http_context_class,
  685. .flags = URL_PROTOCOL_FLAG_NETWORK,
  686. };
  687. #endif
  688. #if CONFIG_HTTPS_PROTOCOL
  689. URLProtocol ff_https_protocol = {
  690. .name = "https",
  691. .url_open2 = http_open,
  692. .url_read = http_read,
  693. .url_write = http_write,
  694. .url_seek = http_seek,
  695. .url_close = http_close,
  696. .url_get_file_handle = http_get_file_handle,
  697. .url_shutdown = http_shutdown,
  698. .priv_data_size = sizeof(HTTPContext),
  699. .priv_data_class = &https_context_class,
  700. .flags = URL_PROTOCOL_FLAG_NETWORK,
  701. };
  702. #endif
  703. #if CONFIG_HTTPPROXY_PROTOCOL
  704. static int http_proxy_close(URLContext *h)
  705. {
  706. HTTPContext *s = h->priv_data;
  707. if (s->hd)
  708. ffurl_close(s->hd);
  709. return 0;
  710. }
  711. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  712. {
  713. HTTPContext *s = h->priv_data;
  714. char hostname[1024], hoststr[1024];
  715. char auth[1024], pathbuf[1024], *path;
  716. char lower_url[100];
  717. int port, ret = 0, attempts = 0;
  718. HTTPAuthType cur_auth_type;
  719. char *authstr;
  720. int new_loc;
  721. h->is_streamed = 1;
  722. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  723. pathbuf, sizeof(pathbuf), uri);
  724. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  725. path = pathbuf;
  726. if (*path == '/')
  727. path++;
  728. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  729. NULL);
  730. redo:
  731. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  732. &h->interrupt_callback, NULL);
  733. if (ret < 0)
  734. return ret;
  735. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  736. path, "CONNECT");
  737. snprintf(s->buffer, sizeof(s->buffer),
  738. "CONNECT %s HTTP/1.1\r\n"
  739. "Host: %s\r\n"
  740. "Connection: close\r\n"
  741. "%s%s"
  742. "\r\n",
  743. path,
  744. hoststr,
  745. authstr ? "Proxy-" : "", authstr ? authstr : "");
  746. av_freep(&authstr);
  747. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  748. goto fail;
  749. s->buf_ptr = s->buffer;
  750. s->buf_end = s->buffer;
  751. s->line_count = 0;
  752. s->filesize = -1;
  753. cur_auth_type = s->proxy_auth_state.auth_type;
  754. /* Note: This uses buffering, potentially reading more than the
  755. * HTTP header. If tunneling a protocol where the server starts
  756. * the conversation, we might buffer part of that here, too.
  757. * Reading that requires using the proper ffurl_read() function
  758. * on this URLContext, not using the fd directly (as the tls
  759. * protocol does). This shouldn't be an issue for tls though,
  760. * since the client starts the conversation there, so there
  761. * is no extra data that we might buffer up here.
  762. */
  763. ret = http_read_header(h, &new_loc);
  764. if (ret < 0)
  765. goto fail;
  766. attempts++;
  767. if (s->http_code == 407 &&
  768. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  769. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  770. ffurl_close(s->hd);
  771. s->hd = NULL;
  772. goto redo;
  773. }
  774. if (s->http_code < 400)
  775. return 0;
  776. ret = AVERROR(EIO);
  777. fail:
  778. http_proxy_close(h);
  779. return ret;
  780. }
  781. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  782. {
  783. HTTPContext *s = h->priv_data;
  784. return ffurl_write(s->hd, buf, size);
  785. }
  786. URLProtocol ff_httpproxy_protocol = {
  787. .name = "httpproxy",
  788. .url_open = http_proxy_open,
  789. .url_read = http_buf_read,
  790. .url_write = http_proxy_write,
  791. .url_close = http_proxy_close,
  792. .url_get_file_handle = http_get_file_handle,
  793. .priv_data_size = sizeof(HTTPContext),
  794. .flags = URL_PROTOCOL_FLAG_NETWORK,
  795. };
  796. #endif