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.

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