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.

1299 lines
42KB

  1. /*
  2. * HTTP protocol for ffmpeg client
  3. * Copyright (c) 2000, 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #if CONFIG_ZLIB
  23. #include <zlib.h>
  24. #endif /* CONFIG_ZLIB */
  25. #include "libavutil/avstring.h"
  26. #include "libavutil/opt.h"
  27. #include "avformat.h"
  28. #include "http.h"
  29. #include "httpauth.h"
  30. #include "internal.h"
  31. #include "network.h"
  32. #include "os_support.h"
  33. #include "url.h"
  34. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  35. * only a subset of it. */
  36. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  37. * to be large enough to fit the full request headers (including long
  38. * path names). */
  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. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  48. int64_t chunksize;
  49. int64_t off, end_off, filesize;
  50. char *location;
  51. HTTPAuthState auth_state;
  52. HTTPAuthState proxy_auth_state;
  53. char *headers;
  54. char *mime_type;
  55. char *user_agent;
  56. char *content_type;
  57. /* Set if the server correctly handles Connection: close and will close
  58. * the connection after feeding us the content. */
  59. int willclose;
  60. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  61. int chunked_post;
  62. /* A flag which indicates if the end of chunked encoding has been sent. */
  63. int end_chunked_post;
  64. /* A flag which indicates we have finished to read POST reply. */
  65. int end_header;
  66. /* A flag which indicates if we use persistent connections. */
  67. int multiple_requests;
  68. uint8_t *post_data;
  69. int post_datalen;
  70. int is_akamai;
  71. int is_mediagateway;
  72. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  73. int icy;
  74. /* how much data was read since the last ICY metadata packet */
  75. int icy_data_read;
  76. /* after how many bytes of read data a new metadata packet will be found */
  77. int icy_metaint;
  78. char *icy_metadata_headers;
  79. char *icy_metadata_packet;
  80. AVDictionary *metadata;
  81. #if CONFIG_ZLIB
  82. int compressed;
  83. z_stream inflate_stream;
  84. uint8_t *inflate_buffer;
  85. #endif /* CONFIG_ZLIB */
  86. AVDictionary *chained_options;
  87. int send_expect_100;
  88. char *method;
  89. } HTTPContext;
  90. #define OFFSET(x) offsetof(HTTPContext, x)
  91. #define D AV_OPT_FLAG_DECODING_PARAM
  92. #define E AV_OPT_FLAG_ENCODING_PARAM
  93. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  94. static const AVOption options[] = {
  95. { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
  96. { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
  97. { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  98. { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  99. { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  100. { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  101. { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
  102. { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
  103. { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  104. { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D },
  105. { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
  106. { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  107. { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
  108. { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  109. { "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"},
  110. { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
  111. { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
  112. { "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 },
  113. { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
  114. { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  115. { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  116. { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
  117. { NULL }
  118. };
  119. static int http_connect(URLContext *h, const char *path, const char *local_path,
  120. const char *hoststr, const char *auth,
  121. const char *proxyauth, int *new_location);
  122. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  123. {
  124. memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
  125. &((HTTPContext *)src->priv_data)->auth_state,
  126. sizeof(HTTPAuthState));
  127. memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
  128. &((HTTPContext *)src->priv_data)->proxy_auth_state,
  129. sizeof(HTTPAuthState));
  130. }
  131. static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
  132. {
  133. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  134. char hostname[1024], hoststr[1024], proto[10];
  135. char auth[1024], proxyauth[1024] = "";
  136. char path1[MAX_URL_SIZE];
  137. char buf[1024], urlbuf[MAX_URL_SIZE];
  138. int port, use_proxy, err, location_changed = 0;
  139. HTTPContext *s = h->priv_data;
  140. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  141. hostname, sizeof(hostname), &port,
  142. path1, sizeof(path1), s->location);
  143. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  144. proxy_path = getenv("http_proxy");
  145. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  146. proxy_path && av_strstart(proxy_path, "http://", NULL);
  147. if (!strcmp(proto, "https")) {
  148. lower_proto = "tls";
  149. use_proxy = 0;
  150. if (port < 0)
  151. port = 443;
  152. }
  153. if (port < 0)
  154. port = 80;
  155. if (path1[0] == '\0')
  156. path = "/";
  157. else
  158. path = path1;
  159. local_path = path;
  160. if (use_proxy) {
  161. /* Reassemble the request URL without auth string - we don't
  162. * want to leak the auth to the proxy. */
  163. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  164. path1);
  165. path = urlbuf;
  166. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  167. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  168. }
  169. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  170. if (!s->hd) {
  171. err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  172. &h->interrupt_callback, options);
  173. if (err < 0)
  174. return err;
  175. }
  176. err = http_connect(h, path, local_path, hoststr,
  177. auth, proxyauth, &location_changed);
  178. if (err < 0)
  179. return err;
  180. return location_changed;
  181. }
  182. /* return non zero if error */
  183. static int http_open_cnx(URLContext *h, AVDictionary **options)
  184. {
  185. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  186. HTTPContext *s = h->priv_data;
  187. int location_changed, attempts = 0, redirects = 0;
  188. redo:
  189. cur_auth_type = s->auth_state.auth_type;
  190. cur_proxy_auth_type = s->auth_state.auth_type;
  191. location_changed = http_open_cnx_internal(h, options);
  192. if (location_changed < 0)
  193. goto fail;
  194. attempts++;
  195. if (s->http_code == 401) {
  196. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  197. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  198. ffurl_closep(&s->hd);
  199. goto redo;
  200. } else
  201. goto fail;
  202. }
  203. if (s->http_code == 407) {
  204. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  205. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  206. ffurl_closep(&s->hd);
  207. goto redo;
  208. } else
  209. goto fail;
  210. }
  211. if ((s->http_code == 301 || s->http_code == 302 ||
  212. s->http_code == 303 || s->http_code == 307) &&
  213. location_changed == 1) {
  214. /* url moved, get next */
  215. ffurl_closep(&s->hd);
  216. if (redirects++ >= MAX_REDIRECTS)
  217. return AVERROR(EIO);
  218. /* Restart the authentication process with the new target, which
  219. * might use a different auth mechanism. */
  220. memset(&s->auth_state, 0, sizeof(s->auth_state));
  221. attempts = 0;
  222. location_changed = 0;
  223. goto redo;
  224. }
  225. return 0;
  226. fail:
  227. if (s->hd)
  228. ffurl_closep(&s->hd);
  229. return AVERROR(EIO);
  230. }
  231. int ff_http_do_new_request(URLContext *h, const char *uri)
  232. {
  233. HTTPContext *s = h->priv_data;
  234. AVDictionary *options = NULL;
  235. int ret;
  236. s->off = 0;
  237. s->icy_data_read = 0;
  238. av_free(s->location);
  239. s->location = av_strdup(uri);
  240. if (!s->location)
  241. return AVERROR(ENOMEM);
  242. av_dict_copy(&options, s->chained_options, 0);
  243. ret = http_open_cnx(h, &options);
  244. av_dict_free(&options);
  245. return ret;
  246. }
  247. static int http_open(URLContext *h, const char *uri, int flags,
  248. AVDictionary **options)
  249. {
  250. HTTPContext *s = h->priv_data;
  251. int ret;
  252. if( s->seekable == 1 )
  253. h->is_streamed = 0;
  254. else
  255. h->is_streamed = 1;
  256. s->filesize = -1;
  257. s->location = av_strdup(uri);
  258. if (!s->location)
  259. return AVERROR(ENOMEM);
  260. if (options)
  261. av_dict_copy(&s->chained_options, *options, 0);
  262. if (s->headers) {
  263. int len = strlen(s->headers);
  264. if (len < 2 || strcmp("\r\n", s->headers + len - 2))
  265. av_log(h, AV_LOG_WARNING,
  266. "No trailing CRLF found in HTTP header.\n");
  267. }
  268. ret = http_open_cnx(h, options);
  269. if (ret < 0)
  270. av_dict_free(&s->chained_options);
  271. return ret;
  272. }
  273. static int http_getc(HTTPContext *s)
  274. {
  275. int len;
  276. if (s->buf_ptr >= s->buf_end) {
  277. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  278. if (len < 0) {
  279. return len;
  280. } else if (len == 0) {
  281. return AVERROR_EOF;
  282. } else {
  283. s->buf_ptr = s->buffer;
  284. s->buf_end = s->buffer + len;
  285. }
  286. }
  287. return *s->buf_ptr++;
  288. }
  289. static int http_get_line(HTTPContext *s, char *line, int line_size)
  290. {
  291. int ch;
  292. char *q;
  293. q = line;
  294. for (;;) {
  295. ch = http_getc(s);
  296. if (ch < 0)
  297. return ch;
  298. if (ch == '\n') {
  299. /* process line */
  300. if (q > line && q[-1] == '\r')
  301. q--;
  302. *q = '\0';
  303. return 0;
  304. } else {
  305. if ((q - line) < line_size - 1)
  306. *q++ = ch;
  307. }
  308. }
  309. }
  310. static int check_http_code(URLContext *h, int http_code, const char *end)
  311. {
  312. HTTPContext *s = h->priv_data;
  313. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  314. * don't abort until all headers have been parsed. */
  315. if (http_code >= 400 && http_code < 600 &&
  316. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  317. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  318. end += strspn(end, SPACE_CHARS);
  319. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  320. return AVERROR(EIO);
  321. }
  322. return 0;
  323. }
  324. static int parse_location(HTTPContext *s, const char *p)
  325. {
  326. char redirected_location[MAX_URL_SIZE], *new_loc;
  327. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  328. s->location, p);
  329. new_loc = av_strdup(redirected_location);
  330. if (!new_loc)
  331. return AVERROR(ENOMEM);
  332. av_free(s->location);
  333. s->location = new_loc;
  334. return 0;
  335. }
  336. /* "bytes $from-$to/$document_size" */
  337. static void parse_content_range(URLContext *h, const char *p)
  338. {
  339. HTTPContext *s = h->priv_data;
  340. const char *slash;
  341. if (!strncmp(p, "bytes ", 6)) {
  342. p += 6;
  343. s->off = strtoll(p, NULL, 10);
  344. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  345. s->filesize = strtoll(slash + 1, NULL, 10);
  346. }
  347. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  348. h->is_streamed = 0; /* we _can_ in fact seek */
  349. }
  350. static int parse_content_encoding(URLContext *h, const char *p)
  351. {
  352. if (!av_strncasecmp(p, "gzip", 4) ||
  353. !av_strncasecmp(p, "deflate", 7)) {
  354. #if CONFIG_ZLIB
  355. HTTPContext *s = h->priv_data;
  356. s->compressed = 1;
  357. inflateEnd(&s->inflate_stream);
  358. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  359. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  360. s->inflate_stream.msg);
  361. return AVERROR(ENOSYS);
  362. }
  363. if (zlibCompileFlags() & (1 << 17)) {
  364. av_log(h, AV_LOG_WARNING,
  365. "Your zlib was compiled without gzip support.\n");
  366. return AVERROR(ENOSYS);
  367. }
  368. #else
  369. av_log(h, AV_LOG_WARNING,
  370. "Compressed (%s) content, need zlib with gzip support\n", p);
  371. return AVERROR(ENOSYS);
  372. #endif /* CONFIG_ZLIB */
  373. } else if (!av_strncasecmp(p, "identity", 8)) {
  374. // The normal, no-encoding case (although servers shouldn't include
  375. // the header at all if this is the case).
  376. } else {
  377. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  378. }
  379. return 0;
  380. }
  381. // Concat all Icy- header lines
  382. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  383. {
  384. int len = 4 + strlen(p) + strlen(tag);
  385. int is_first = !s->icy_metadata_headers;
  386. int ret;
  387. av_dict_set(&s->metadata, tag, p, 0);
  388. if (s->icy_metadata_headers)
  389. len += strlen(s->icy_metadata_headers);
  390. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  391. return ret;
  392. if (is_first)
  393. *s->icy_metadata_headers = '\0';
  394. av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
  395. return 0;
  396. }
  397. static int process_line(URLContext *h, char *line, int line_count,
  398. int *new_location)
  399. {
  400. HTTPContext *s = h->priv_data;
  401. char *tag, *p, *end;
  402. int ret;
  403. /* end of header */
  404. if (line[0] == '\0') {
  405. s->end_header = 1;
  406. return 0;
  407. }
  408. p = line;
  409. if (line_count == 0) {
  410. while (!av_isspace(*p) && *p != '\0')
  411. p++;
  412. while (av_isspace(*p))
  413. p++;
  414. s->http_code = strtol(p, &end, 10);
  415. av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
  416. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  417. return ret;
  418. } else {
  419. while (*p != '\0' && *p != ':')
  420. p++;
  421. if (*p != ':')
  422. return 1;
  423. *p = '\0';
  424. tag = line;
  425. p++;
  426. while (av_isspace(*p))
  427. p++;
  428. if (!av_strcasecmp(tag, "Location")) {
  429. if ((ret = parse_location(s, p)) < 0)
  430. return ret;
  431. *new_location = 1;
  432. } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
  433. s->filesize = strtoll(p, NULL, 10);
  434. } else if (!av_strcasecmp(tag, "Content-Range")) {
  435. parse_content_range(h, p);
  436. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  437. !strncmp(p, "bytes", 5) &&
  438. s->seekable == -1) {
  439. h->is_streamed = 0;
  440. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  441. !av_strncasecmp(p, "chunked", 7)) {
  442. s->filesize = -1;
  443. s->chunksize = 0;
  444. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  445. ff_http_auth_handle_header(&s->auth_state, tag, p);
  446. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  447. ff_http_auth_handle_header(&s->auth_state, tag, p);
  448. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  449. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  450. } else if (!av_strcasecmp(tag, "Connection")) {
  451. if (!strcmp(p, "close"))
  452. s->willclose = 1;
  453. } else if (!av_strcasecmp(tag, "Server")) {
  454. if (!av_strcasecmp(p, "AkamaiGHost")) {
  455. s->is_akamai = 1;
  456. } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
  457. s->is_mediagateway = 1;
  458. }
  459. } else if (!av_strcasecmp(tag, "Content-Type")) {
  460. av_free(s->mime_type);
  461. s->mime_type = av_strdup(p);
  462. } else if (!av_strcasecmp(tag, "Set-Cookie")) {
  463. if (!s->cookies) {
  464. if (!(s->cookies = av_strdup(p)))
  465. return AVERROR(ENOMEM);
  466. } else {
  467. char *tmp = s->cookies;
  468. size_t str_size = strlen(tmp) + strlen(p) + 2;
  469. if (!(s->cookies = av_malloc(str_size))) {
  470. s->cookies = tmp;
  471. return AVERROR(ENOMEM);
  472. }
  473. snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
  474. av_free(tmp);
  475. }
  476. } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
  477. s->icy_metaint = strtoll(p, NULL, 10);
  478. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  479. if ((ret = parse_icy(s, tag, p)) < 0)
  480. return ret;
  481. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  482. if ((ret = parse_content_encoding(h, p)) < 0)
  483. return ret;
  484. }
  485. }
  486. return 1;
  487. }
  488. /**
  489. * Create a string containing cookie values for use as a HTTP cookie header
  490. * field value for a particular path and domain from the cookie values stored in
  491. * the HTTP protocol context. The cookie string is stored in *cookies.
  492. *
  493. * @return a negative value if an error condition occurred, 0 otherwise
  494. */
  495. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  496. const char *domain)
  497. {
  498. // cookie strings will look like Set-Cookie header field values. Multiple
  499. // Set-Cookie fields will result in multiple values delimited by a newline
  500. int ret = 0;
  501. char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
  502. if (!set_cookies) return AVERROR(EINVAL);
  503. *cookies = NULL;
  504. while ((cookie = av_strtok(set_cookies, "\n", &next))) {
  505. int domain_offset = 0;
  506. char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
  507. set_cookies = NULL;
  508. while ((param = av_strtok(cookie, "; ", &next_param))) {
  509. if (cookie) {
  510. // first key-value pair is the actual cookie value
  511. cvalue = av_strdup(param);
  512. cookie = NULL;
  513. } else if (!av_strncasecmp("path=", param, 5)) {
  514. av_free(cpath);
  515. cpath = av_strdup(&param[5]);
  516. } else if (!av_strncasecmp("domain=", param, 7)) {
  517. // if the cookie specifies a sub-domain, skip the leading dot thereby
  518. // supporting URLs that point to sub-domains and the master domain
  519. int leading_dot = (param[7] == '.');
  520. av_free(cdomain);
  521. cdomain = av_strdup(&param[7+leading_dot]);
  522. } else if (!av_strncasecmp("secure", param, 6) ||
  523. !av_strncasecmp("comment", param, 7) ||
  524. !av_strncasecmp("max-age", param, 7) ||
  525. !av_strncasecmp("version", param, 7)) {
  526. // ignore Comment, Max-Age, Secure and Version
  527. } else {
  528. // ignore unknown attributes
  529. }
  530. }
  531. if (!cdomain)
  532. cdomain = av_strdup(domain);
  533. // ensure all of the necessary values are valid
  534. if (!cdomain || !cpath || !cvalue) {
  535. av_log(s, AV_LOG_WARNING,
  536. "Invalid cookie found, no value, path or domain specified\n");
  537. goto done_cookie;
  538. }
  539. // check if the request path matches the cookie path
  540. if (av_strncasecmp(path, cpath, strlen(cpath)))
  541. goto done_cookie;
  542. // the domain should be at least the size of our cookie domain
  543. domain_offset = strlen(domain) - strlen(cdomain);
  544. if (domain_offset < 0)
  545. goto done_cookie;
  546. // match the cookie domain
  547. if (av_strcasecmp(&domain[domain_offset], cdomain))
  548. goto done_cookie;
  549. // cookie parameters match, so copy the value
  550. if (!*cookies) {
  551. if (!(*cookies = av_strdup(cvalue))) {
  552. ret = AVERROR(ENOMEM);
  553. goto done_cookie;
  554. }
  555. } else {
  556. char *tmp = *cookies;
  557. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  558. if (!(*cookies = av_malloc(str_size))) {
  559. ret = AVERROR(ENOMEM);
  560. goto done_cookie;
  561. }
  562. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  563. av_free(tmp);
  564. }
  565. done_cookie:
  566. av_free(cdomain);
  567. av_free(cpath);
  568. av_free(cvalue);
  569. if (ret < 0) {
  570. if (*cookies) av_freep(cookies);
  571. av_free(cset_cookies);
  572. return ret;
  573. }
  574. }
  575. av_free(cset_cookies);
  576. return 0;
  577. }
  578. static inline int has_header(const char *str, const char *header)
  579. {
  580. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  581. if (!str)
  582. return 0;
  583. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  584. }
  585. static int http_read_header(URLContext *h, int *new_location)
  586. {
  587. HTTPContext *s = h->priv_data;
  588. char line[MAX_URL_SIZE];
  589. int err = 0;
  590. s->chunksize = -1;
  591. for (;;) {
  592. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  593. return err;
  594. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  595. err = process_line(h, line, s->line_count, new_location);
  596. if (err < 0)
  597. return err;
  598. if (err == 0)
  599. break;
  600. s->line_count++;
  601. }
  602. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  603. h->is_streamed = 1; /* we can in fact _not_ seek */
  604. return err;
  605. }
  606. static int http_connect(URLContext *h, const char *path, const char *local_path,
  607. const char *hoststr, const char *auth,
  608. const char *proxyauth, int *new_location)
  609. {
  610. HTTPContext *s = h->priv_data;
  611. int post, err;
  612. char headers[HTTP_HEADERS_SIZE] = "";
  613. char *authstr = NULL, *proxyauthstr = NULL;
  614. int64_t off = s->off;
  615. int len = 0;
  616. const char *method;
  617. int send_expect_100 = 0;
  618. /* send http header */
  619. post = h->flags & AVIO_FLAG_WRITE;
  620. if (s->post_data) {
  621. /* force POST method and disable chunked encoding when
  622. * custom HTTP post data is set */
  623. post = 1;
  624. s->chunked_post = 0;
  625. }
  626. if (s->method)
  627. method = s->method;
  628. else
  629. method = post ? "POST" : "GET";
  630. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  631. local_path, method);
  632. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  633. local_path, method);
  634. if (post && !s->post_data) {
  635. send_expect_100 = s->send_expect_100;
  636. /* The user has supplied authentication but we don't know the auth type,
  637. * send Expect: 100-continue to get the 401 response including the
  638. * WWW-Authenticate header, or an 100 continue if no auth actually
  639. * is needed. */
  640. if (auth && *auth &&
  641. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  642. s->http_code != 401)
  643. send_expect_100 = 1;
  644. }
  645. /* set default headers if needed */
  646. if (!has_header(s->headers, "\r\nUser-Agent: "))
  647. len += av_strlcatf(headers + len, sizeof(headers) - len,
  648. "User-Agent: %s\r\n", s->user_agent);
  649. if (!has_header(s->headers, "\r\nAccept: "))
  650. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  651. sizeof(headers) - len);
  652. // Note: we send this on purpose even when s->off is 0 when we're probing,
  653. // since it allows us to detect more reliably if a (non-conforming)
  654. // server supports seeking by analysing the reply headers.
  655. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  656. len += av_strlcatf(headers + len, sizeof(headers) - len,
  657. "Range: bytes=%"PRId64"-", s->off);
  658. if (s->end_off)
  659. len += av_strlcatf(headers + len, sizeof(headers) - len,
  660. "%"PRId64, s->end_off - 1);
  661. len += av_strlcpy(headers + len, "\r\n",
  662. sizeof(headers) - len);
  663. }
  664. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  665. len += av_strlcatf(headers + len, sizeof(headers) - len,
  666. "Expect: 100-continue\r\n");
  667. if (!has_header(s->headers, "\r\nConnection: ")) {
  668. if (s->multiple_requests)
  669. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  670. sizeof(headers) - len);
  671. else
  672. len += av_strlcpy(headers + len, "Connection: close\r\n",
  673. sizeof(headers) - len);
  674. }
  675. if (!has_header(s->headers, "\r\nHost: "))
  676. len += av_strlcatf(headers + len, sizeof(headers) - len,
  677. "Host: %s\r\n", hoststr);
  678. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  679. len += av_strlcatf(headers + len, sizeof(headers) - len,
  680. "Content-Length: %d\r\n", s->post_datalen);
  681. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  682. len += av_strlcatf(headers + len, sizeof(headers) - len,
  683. "Content-Type: %s\r\n", s->content_type);
  684. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  685. char *cookies = NULL;
  686. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  687. len += av_strlcatf(headers + len, sizeof(headers) - len,
  688. "Cookie: %s\r\n", cookies);
  689. av_free(cookies);
  690. }
  691. }
  692. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  693. len += av_strlcatf(headers + len, sizeof(headers) - len,
  694. "Icy-MetaData: %d\r\n", 1);
  695. /* now add in custom headers */
  696. if (s->headers)
  697. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  698. snprintf(s->buffer, sizeof(s->buffer),
  699. "%s %s HTTP/1.1\r\n"
  700. "%s"
  701. "%s"
  702. "%s"
  703. "%s%s"
  704. "\r\n",
  705. method,
  706. path,
  707. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  708. headers,
  709. authstr ? authstr : "",
  710. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  711. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  712. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  713. goto done;
  714. if (s->post_data)
  715. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  716. goto done;
  717. /* init input buffer */
  718. s->buf_ptr = s->buffer;
  719. s->buf_end = s->buffer;
  720. s->line_count = 0;
  721. s->off = 0;
  722. s->icy_data_read = 0;
  723. s->filesize = -1;
  724. s->willclose = 0;
  725. s->end_chunked_post = 0;
  726. s->end_header = 0;
  727. if (post && !s->post_data && !send_expect_100) {
  728. /* Pretend that it did work. We didn't read any header yet, since
  729. * we've still to send the POST data, but the code calling this
  730. * function will check http_code after we return. */
  731. s->http_code = 200;
  732. err = 0;
  733. goto done;
  734. }
  735. /* wait for header */
  736. err = http_read_header(h, new_location);
  737. if (err < 0)
  738. goto done;
  739. err = (off == s->off) ? 0 : -1;
  740. done:
  741. av_freep(&authstr);
  742. av_freep(&proxyauthstr);
  743. return err;
  744. }
  745. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  746. {
  747. HTTPContext *s = h->priv_data;
  748. int len;
  749. /* read bytes from input buffer first */
  750. len = s->buf_end - s->buf_ptr;
  751. if (len > 0) {
  752. if (len > size)
  753. len = size;
  754. memcpy(buf, s->buf_ptr, len);
  755. s->buf_ptr += len;
  756. } else {
  757. if ((!s->willclose || s->chunksize < 0) &&
  758. s->filesize >= 0 && s->off >= s->filesize)
  759. return AVERROR_EOF;
  760. len = ffurl_read(s->hd, buf, size);
  761. }
  762. if (len > 0) {
  763. s->off += len;
  764. if (s->chunksize > 0)
  765. s->chunksize -= len;
  766. }
  767. return len;
  768. }
  769. #if CONFIG_ZLIB
  770. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  771. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  772. {
  773. HTTPContext *s = h->priv_data;
  774. int ret;
  775. if (!s->inflate_buffer) {
  776. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  777. if (!s->inflate_buffer)
  778. return AVERROR(ENOMEM);
  779. }
  780. if (s->inflate_stream.avail_in == 0) {
  781. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  782. if (read <= 0)
  783. return read;
  784. s->inflate_stream.next_in = s->inflate_buffer;
  785. s->inflate_stream.avail_in = read;
  786. }
  787. s->inflate_stream.avail_out = size;
  788. s->inflate_stream.next_out = buf;
  789. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  790. if (ret != Z_OK && ret != Z_STREAM_END)
  791. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  792. ret, s->inflate_stream.msg);
  793. return size - s->inflate_stream.avail_out;
  794. }
  795. #endif /* CONFIG_ZLIB */
  796. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  797. {
  798. HTTPContext *s = h->priv_data;
  799. int err, new_location;
  800. if (!s->hd)
  801. return AVERROR_EOF;
  802. if (s->end_chunked_post && !s->end_header) {
  803. err = http_read_header(h, &new_location);
  804. if (err < 0)
  805. return err;
  806. }
  807. if (s->chunksize >= 0) {
  808. if (!s->chunksize) {
  809. char line[32];
  810. do {
  811. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  812. return err;
  813. } while (!*line); /* skip CR LF from last chunk */
  814. s->chunksize = strtoll(line, NULL, 16);
  815. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
  816. s->chunksize);
  817. if (!s->chunksize)
  818. return 0;
  819. }
  820. size = FFMIN(size, s->chunksize);
  821. }
  822. #if CONFIG_ZLIB
  823. if (s->compressed)
  824. return http_buf_read_compressed(h, buf, size);
  825. #endif /* CONFIG_ZLIB */
  826. return http_buf_read(h, buf, size);
  827. }
  828. // Like http_read_stream(), but no short reads.
  829. // Assumes partial reads are an error.
  830. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  831. {
  832. int pos = 0;
  833. while (pos < size) {
  834. int len = http_read_stream(h, buf + pos, size - pos);
  835. if (len < 0)
  836. return len;
  837. pos += len;
  838. }
  839. return pos;
  840. }
  841. static void update_metadata(HTTPContext *s, char *data)
  842. {
  843. char *key;
  844. char *val;
  845. char *end;
  846. char *next = data;
  847. while (*next) {
  848. key = next;
  849. val = strstr(key, "='");
  850. if (!val)
  851. break;
  852. end = strstr(val, "';");
  853. if (!end)
  854. break;
  855. *val = '\0';
  856. *end = '\0';
  857. val += 2;
  858. av_dict_set(&s->metadata, key, val, 0);
  859. next = end + 2;
  860. }
  861. }
  862. static int store_icy(URLContext *h, int size)
  863. {
  864. HTTPContext *s = h->priv_data;
  865. /* until next metadata packet */
  866. int remaining = s->icy_metaint - s->icy_data_read;
  867. if (remaining < 0)
  868. return AVERROR_INVALIDDATA;
  869. if (!remaining) {
  870. /* The metadata packet is variable sized. It has a 1 byte header
  871. * which sets the length of the packet (divided by 16). If it's 0,
  872. * the metadata doesn't change. After the packet, icy_metaint bytes
  873. * of normal data follows. */
  874. uint8_t ch;
  875. int len = http_read_stream_all(h, &ch, 1);
  876. if (len < 0)
  877. return len;
  878. if (ch > 0) {
  879. char data[255 * 16 + 1];
  880. int ret;
  881. len = ch * 16;
  882. ret = http_read_stream_all(h, data, len);
  883. if (ret < 0)
  884. return ret;
  885. data[len + 1] = 0;
  886. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  887. return ret;
  888. update_metadata(s, data);
  889. }
  890. s->icy_data_read = 0;
  891. remaining = s->icy_metaint;
  892. }
  893. return FFMIN(size, remaining);
  894. }
  895. static int http_read(URLContext *h, uint8_t *buf, int size)
  896. {
  897. HTTPContext *s = h->priv_data;
  898. if (s->icy_metaint > 0) {
  899. size = store_icy(h, size);
  900. if (size < 0)
  901. return size;
  902. }
  903. size = http_read_stream(h, buf, size);
  904. if (size > 0)
  905. s->icy_data_read += size;
  906. return size;
  907. }
  908. /* used only when posting data */
  909. static int http_write(URLContext *h, const uint8_t *buf, int size)
  910. {
  911. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  912. int ret;
  913. char crlf[] = "\r\n";
  914. HTTPContext *s = h->priv_data;
  915. if (!s->chunked_post) {
  916. /* non-chunked data is sent without any special encoding */
  917. return ffurl_write(s->hd, buf, size);
  918. }
  919. /* silently ignore zero-size data since chunk encoding that would
  920. * signal EOF */
  921. if (size > 0) {
  922. /* upload data using chunked encoding */
  923. snprintf(temp, sizeof(temp), "%x\r\n", size);
  924. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  925. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  926. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  927. return ret;
  928. }
  929. return size;
  930. }
  931. static int http_shutdown(URLContext *h, int flags)
  932. {
  933. int ret = 0;
  934. char footer[] = "0\r\n\r\n";
  935. HTTPContext *s = h->priv_data;
  936. /* signal end of chunked encoding if used */
  937. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  938. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  939. ret = ret > 0 ? 0 : ret;
  940. s->end_chunked_post = 1;
  941. }
  942. return ret;
  943. }
  944. static int http_close(URLContext *h)
  945. {
  946. int ret = 0;
  947. HTTPContext *s = h->priv_data;
  948. #if CONFIG_ZLIB
  949. inflateEnd(&s->inflate_stream);
  950. av_freep(&s->inflate_buffer);
  951. #endif /* CONFIG_ZLIB */
  952. if (!s->end_chunked_post)
  953. /* Close the write direction by sending the end of chunked encoding. */
  954. ret = http_shutdown(h, h->flags);
  955. if (s->hd)
  956. ffurl_closep(&s->hd);
  957. av_dict_free(&s->chained_options);
  958. return ret;
  959. }
  960. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  961. {
  962. HTTPContext *s = h->priv_data;
  963. URLContext *old_hd = s->hd;
  964. int64_t old_off = s->off;
  965. uint8_t old_buf[BUFFER_SIZE];
  966. int old_buf_size, ret;
  967. AVDictionary *options = NULL;
  968. if (whence == AVSEEK_SIZE)
  969. return s->filesize;
  970. else if ((whence == SEEK_CUR && off == 0) ||
  971. (whence == SEEK_SET && off == s->off))
  972. return s->off;
  973. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  974. return AVERROR(ENOSYS);
  975. if (whence == SEEK_CUR)
  976. off += s->off;
  977. else if (whence == SEEK_END)
  978. off += s->filesize;
  979. else if (whence != SEEK_SET)
  980. return AVERROR(EINVAL);
  981. if (off < 0)
  982. return AVERROR(EINVAL);
  983. s->off = off;
  984. /* we save the old context in case the seek fails */
  985. old_buf_size = s->buf_end - s->buf_ptr;
  986. memcpy(old_buf, s->buf_ptr, old_buf_size);
  987. s->hd = NULL;
  988. /* if it fails, continue on old connection */
  989. av_dict_copy(&options, s->chained_options, 0);
  990. if ((ret = http_open_cnx(h, &options)) < 0) {
  991. av_dict_free(&options);
  992. memcpy(s->buffer, old_buf, old_buf_size);
  993. s->buf_ptr = s->buffer;
  994. s->buf_end = s->buffer + old_buf_size;
  995. s->hd = old_hd;
  996. s->off = old_off;
  997. return ret;
  998. }
  999. av_dict_free(&options);
  1000. ffurl_close(old_hd);
  1001. return off;
  1002. }
  1003. static int http_get_file_handle(URLContext *h)
  1004. {
  1005. HTTPContext *s = h->priv_data;
  1006. return ffurl_get_file_handle(s->hd);
  1007. }
  1008. #define HTTP_CLASS(flavor) \
  1009. static const AVClass flavor ## _context_class = { \
  1010. .class_name = # flavor, \
  1011. .item_name = av_default_item_name, \
  1012. .option = options, \
  1013. .version = LIBAVUTIL_VERSION_INT, \
  1014. }
  1015. #if CONFIG_HTTP_PROTOCOL
  1016. HTTP_CLASS(http);
  1017. URLProtocol ff_http_protocol = {
  1018. .name = "http",
  1019. .url_open2 = http_open,
  1020. .url_read = http_read,
  1021. .url_write = http_write,
  1022. .url_seek = http_seek,
  1023. .url_close = http_close,
  1024. .url_get_file_handle = http_get_file_handle,
  1025. .url_shutdown = http_shutdown,
  1026. .priv_data_size = sizeof(HTTPContext),
  1027. .priv_data_class = &http_context_class,
  1028. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1029. };
  1030. #endif /* CONFIG_HTTP_PROTOCOL */
  1031. #if CONFIG_HTTPS_PROTOCOL
  1032. HTTP_CLASS(https);
  1033. URLProtocol ff_https_protocol = {
  1034. .name = "https",
  1035. .url_open2 = http_open,
  1036. .url_read = http_read,
  1037. .url_write = http_write,
  1038. .url_seek = http_seek,
  1039. .url_close = http_close,
  1040. .url_get_file_handle = http_get_file_handle,
  1041. .url_shutdown = http_shutdown,
  1042. .priv_data_size = sizeof(HTTPContext),
  1043. .priv_data_class = &https_context_class,
  1044. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1045. };
  1046. #endif /* CONFIG_HTTPS_PROTOCOL */
  1047. #if CONFIG_HTTPPROXY_PROTOCOL
  1048. static int http_proxy_close(URLContext *h)
  1049. {
  1050. HTTPContext *s = h->priv_data;
  1051. if (s->hd)
  1052. ffurl_closep(&s->hd);
  1053. return 0;
  1054. }
  1055. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1056. {
  1057. HTTPContext *s = h->priv_data;
  1058. char hostname[1024], hoststr[1024];
  1059. char auth[1024], pathbuf[1024], *path;
  1060. char lower_url[100];
  1061. int port, ret = 0, attempts = 0;
  1062. HTTPAuthType cur_auth_type;
  1063. char *authstr;
  1064. int new_loc;
  1065. if( s->seekable == 1 )
  1066. h->is_streamed = 0;
  1067. else
  1068. h->is_streamed = 1;
  1069. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1070. pathbuf, sizeof(pathbuf), uri);
  1071. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1072. path = pathbuf;
  1073. if (*path == '/')
  1074. path++;
  1075. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1076. NULL);
  1077. redo:
  1078. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1079. &h->interrupt_callback, NULL);
  1080. if (ret < 0)
  1081. return ret;
  1082. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1083. path, "CONNECT");
  1084. snprintf(s->buffer, sizeof(s->buffer),
  1085. "CONNECT %s HTTP/1.1\r\n"
  1086. "Host: %s\r\n"
  1087. "Connection: close\r\n"
  1088. "%s%s"
  1089. "\r\n",
  1090. path,
  1091. hoststr,
  1092. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1093. av_freep(&authstr);
  1094. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1095. goto fail;
  1096. s->buf_ptr = s->buffer;
  1097. s->buf_end = s->buffer;
  1098. s->line_count = 0;
  1099. s->filesize = -1;
  1100. cur_auth_type = s->proxy_auth_state.auth_type;
  1101. /* Note: This uses buffering, potentially reading more than the
  1102. * HTTP header. If tunneling a protocol where the server starts
  1103. * the conversation, we might buffer part of that here, too.
  1104. * Reading that requires using the proper ffurl_read() function
  1105. * on this URLContext, not using the fd directly (as the tls
  1106. * protocol does). This shouldn't be an issue for tls though,
  1107. * since the client starts the conversation there, so there
  1108. * is no extra data that we might buffer up here.
  1109. */
  1110. ret = http_read_header(h, &new_loc);
  1111. if (ret < 0)
  1112. goto fail;
  1113. attempts++;
  1114. if (s->http_code == 407 &&
  1115. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1116. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1117. ffurl_closep(&s->hd);
  1118. goto redo;
  1119. }
  1120. if (s->http_code < 400)
  1121. return 0;
  1122. ret = AVERROR(EIO);
  1123. fail:
  1124. http_proxy_close(h);
  1125. return ret;
  1126. }
  1127. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1128. {
  1129. HTTPContext *s = h->priv_data;
  1130. return ffurl_write(s->hd, buf, size);
  1131. }
  1132. URLProtocol ff_httpproxy_protocol = {
  1133. .name = "httpproxy",
  1134. .url_open = http_proxy_open,
  1135. .url_read = http_buf_read,
  1136. .url_write = http_proxy_write,
  1137. .url_close = http_proxy_close,
  1138. .url_get_file_handle = http_get_file_handle,
  1139. .priv_data_size = sizeof(HTTPContext),
  1140. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1141. };
  1142. #endif /* CONFIG_HTTPPROXY_PROTOCOL */