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.

863 lines
27KB

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