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.

1303 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 {
  523. // ignore unknown attributes
  524. }
  525. }
  526. if (!cdomain)
  527. cdomain = av_strdup(domain);
  528. // ensure all of the necessary values are valid
  529. if (!cdomain || !cpath || !cvalue) {
  530. av_log(s, AV_LOG_WARNING,
  531. "Invalid cookie found, no value, path or domain specified\n");
  532. goto done_cookie;
  533. }
  534. // check if the request path matches the cookie path
  535. if (av_strncasecmp(path, cpath, strlen(cpath)))
  536. goto done_cookie;
  537. // the domain should be at least the size of our cookie domain
  538. domain_offset = strlen(domain) - strlen(cdomain);
  539. if (domain_offset < 0)
  540. goto done_cookie;
  541. // match the cookie domain
  542. if (av_strcasecmp(&domain[domain_offset], cdomain))
  543. goto done_cookie;
  544. // cookie parameters match, so copy the value
  545. if (!*cookies) {
  546. if (!(*cookies = av_strdup(cvalue))) {
  547. ret = AVERROR(ENOMEM);
  548. goto done_cookie;
  549. }
  550. } else {
  551. char *tmp = *cookies;
  552. size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
  553. if (!(*cookies = av_malloc(str_size))) {
  554. ret = AVERROR(ENOMEM);
  555. goto done_cookie;
  556. }
  557. snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
  558. av_free(tmp);
  559. }
  560. done_cookie:
  561. av_free(cdomain);
  562. av_free(cpath);
  563. av_free(cvalue);
  564. if (ret < 0) {
  565. if (*cookies) av_freep(cookies);
  566. av_free(cset_cookies);
  567. return ret;
  568. }
  569. }
  570. av_free(cset_cookies);
  571. return 0;
  572. }
  573. static inline int has_header(const char *str, const char *header)
  574. {
  575. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  576. if (!str)
  577. return 0;
  578. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  579. }
  580. static int http_read_header(URLContext *h, int *new_location)
  581. {
  582. HTTPContext *s = h->priv_data;
  583. char line[MAX_URL_SIZE];
  584. int err = 0;
  585. s->chunksize = -1;
  586. for (;;) {
  587. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  588. return err;
  589. av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
  590. err = process_line(h, line, s->line_count, new_location);
  591. if (err < 0)
  592. return err;
  593. if (err == 0)
  594. break;
  595. s->line_count++;
  596. }
  597. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  598. h->is_streamed = 1; /* we can in fact _not_ seek */
  599. return err;
  600. }
  601. static int http_connect(URLContext *h, const char *path, const char *local_path,
  602. const char *hoststr, const char *auth,
  603. const char *proxyauth, int *new_location)
  604. {
  605. HTTPContext *s = h->priv_data;
  606. int post, err;
  607. char headers[HTTP_HEADERS_SIZE] = "";
  608. char *authstr = NULL, *proxyauthstr = NULL;
  609. int64_t off = s->off;
  610. int len = 0;
  611. const char *method;
  612. int send_expect_100 = 0;
  613. int ret;
  614. /* send http header */
  615. post = h->flags & AVIO_FLAG_WRITE;
  616. if (s->post_data) {
  617. /* force POST method and disable chunked encoding when
  618. * custom HTTP post data is set */
  619. post = 1;
  620. s->chunked_post = 0;
  621. }
  622. if (s->method)
  623. method = s->method;
  624. else
  625. method = post ? "POST" : "GET";
  626. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  627. local_path, method);
  628. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  629. local_path, method);
  630. if (post && !s->post_data) {
  631. send_expect_100 = s->send_expect_100;
  632. /* The user has supplied authentication but we don't know the auth type,
  633. * send Expect: 100-continue to get the 401 response including the
  634. * WWW-Authenticate header, or an 100 continue if no auth actually
  635. * is needed. */
  636. if (auth && *auth &&
  637. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  638. s->http_code != 401)
  639. send_expect_100 = 1;
  640. }
  641. /* set default headers if needed */
  642. if (!has_header(s->headers, "\r\nUser-Agent: "))
  643. len += av_strlcatf(headers + len, sizeof(headers) - len,
  644. "User-Agent: %s\r\n", s->user_agent);
  645. if (!has_header(s->headers, "\r\nAccept: "))
  646. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  647. sizeof(headers) - len);
  648. // Note: we send this on purpose even when s->off is 0 when we're probing,
  649. // since it allows us to detect more reliably if a (non-conforming)
  650. // server supports seeking by analysing the reply headers.
  651. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  652. len += av_strlcatf(headers + len, sizeof(headers) - len,
  653. "Range: bytes=%"PRId64"-", s->off);
  654. if (s->end_off)
  655. len += av_strlcatf(headers + len, sizeof(headers) - len,
  656. "%"PRId64, s->end_off - 1);
  657. len += av_strlcpy(headers + len, "\r\n",
  658. sizeof(headers) - len);
  659. }
  660. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  661. len += av_strlcatf(headers + len, sizeof(headers) - len,
  662. "Expect: 100-continue\r\n");
  663. if (!has_header(s->headers, "\r\nConnection: ")) {
  664. if (s->multiple_requests)
  665. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  666. sizeof(headers) - len);
  667. else
  668. len += av_strlcpy(headers + len, "Connection: close\r\n",
  669. sizeof(headers) - len);
  670. }
  671. if (!has_header(s->headers, "\r\nHost: "))
  672. len += av_strlcatf(headers + len, sizeof(headers) - len,
  673. "Host: %s\r\n", hoststr);
  674. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  675. len += av_strlcatf(headers + len, sizeof(headers) - len,
  676. "Content-Length: %d\r\n", s->post_datalen);
  677. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  678. len += av_strlcatf(headers + len, sizeof(headers) - len,
  679. "Content-Type: %s\r\n", s->content_type);
  680. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  681. char *cookies = NULL;
  682. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  683. len += av_strlcatf(headers + len, sizeof(headers) - len,
  684. "Cookie: %s\r\n", cookies);
  685. av_free(cookies);
  686. }
  687. }
  688. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  689. len += av_strlcatf(headers + len, sizeof(headers) - len,
  690. "Icy-MetaData: %d\r\n", 1);
  691. /* now add in custom headers */
  692. if (s->headers)
  693. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  694. ret = snprintf(s->buffer, sizeof(s->buffer),
  695. "%s %s HTTP/1.1\r\n"
  696. "%s"
  697. "%s"
  698. "%s"
  699. "%s%s"
  700. "\r\n",
  701. method,
  702. path,
  703. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  704. headers,
  705. authstr ? authstr : "",
  706. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  707. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  708. if (strlen(headers) + 1 == sizeof(headers) ||
  709. ret >= sizeof(s->buffer)) {
  710. av_log(h, AV_LOG_ERROR, "overlong headers\n");
  711. err = AVERROR(EINVAL);
  712. goto done;
  713. }
  714. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  715. goto done;
  716. if (s->post_data)
  717. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  718. goto done;
  719. /* init input buffer */
  720. s->buf_ptr = s->buffer;
  721. s->buf_end = s->buffer;
  722. s->line_count = 0;
  723. s->off = 0;
  724. s->icy_data_read = 0;
  725. s->filesize = -1;
  726. s->willclose = 0;
  727. s->end_chunked_post = 0;
  728. s->end_header = 0;
  729. if (post && !s->post_data && !send_expect_100) {
  730. /* Pretend that it did work. We didn't read any header yet, since
  731. * we've still to send the POST data, but the code calling this
  732. * function will check http_code after we return. */
  733. s->http_code = 200;
  734. err = 0;
  735. goto done;
  736. }
  737. /* wait for header */
  738. err = http_read_header(h, new_location);
  739. if (err < 0)
  740. goto done;
  741. err = (off == s->off) ? 0 : -1;
  742. done:
  743. av_freep(&authstr);
  744. av_freep(&proxyauthstr);
  745. return err;
  746. }
  747. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  748. {
  749. HTTPContext *s = h->priv_data;
  750. int len;
  751. /* read bytes from input buffer first */
  752. len = s->buf_end - s->buf_ptr;
  753. if (len > 0) {
  754. if (len > size)
  755. len = size;
  756. memcpy(buf, s->buf_ptr, len);
  757. s->buf_ptr += len;
  758. } else {
  759. if ((!s->willclose || s->chunksize < 0) &&
  760. s->filesize >= 0 && s->off >= s->filesize)
  761. return AVERROR_EOF;
  762. len = ffurl_read(s->hd, buf, size);
  763. }
  764. if (len > 0) {
  765. s->off += len;
  766. if (s->chunksize > 0)
  767. s->chunksize -= len;
  768. }
  769. return len;
  770. }
  771. #if CONFIG_ZLIB
  772. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  773. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  774. {
  775. HTTPContext *s = h->priv_data;
  776. int ret;
  777. if (!s->inflate_buffer) {
  778. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  779. if (!s->inflate_buffer)
  780. return AVERROR(ENOMEM);
  781. }
  782. if (s->inflate_stream.avail_in == 0) {
  783. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  784. if (read <= 0)
  785. return read;
  786. s->inflate_stream.next_in = s->inflate_buffer;
  787. s->inflate_stream.avail_in = read;
  788. }
  789. s->inflate_stream.avail_out = size;
  790. s->inflate_stream.next_out = buf;
  791. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  792. if (ret != Z_OK && ret != Z_STREAM_END)
  793. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  794. ret, s->inflate_stream.msg);
  795. return size - s->inflate_stream.avail_out;
  796. }
  797. #endif /* CONFIG_ZLIB */
  798. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  799. {
  800. HTTPContext *s = h->priv_data;
  801. int err, new_location;
  802. if (!s->hd)
  803. return AVERROR_EOF;
  804. if (s->end_chunked_post && !s->end_header) {
  805. err = http_read_header(h, &new_location);
  806. if (err < 0)
  807. return err;
  808. }
  809. if (s->chunksize >= 0) {
  810. if (!s->chunksize) {
  811. char line[32];
  812. do {
  813. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  814. return err;
  815. } while (!*line); /* skip CR LF from last chunk */
  816. s->chunksize = strtoll(line, NULL, 16);
  817. av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
  818. s->chunksize);
  819. if (!s->chunksize)
  820. return 0;
  821. }
  822. size = FFMIN(size, s->chunksize);
  823. }
  824. #if CONFIG_ZLIB
  825. if (s->compressed)
  826. return http_buf_read_compressed(h, buf, size);
  827. #endif /* CONFIG_ZLIB */
  828. return http_buf_read(h, buf, size);
  829. }
  830. // Like http_read_stream(), but no short reads.
  831. // Assumes partial reads are an error.
  832. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  833. {
  834. int pos = 0;
  835. while (pos < size) {
  836. int len = http_read_stream(h, buf + pos, size - pos);
  837. if (len < 0)
  838. return len;
  839. pos += len;
  840. }
  841. return pos;
  842. }
  843. static void update_metadata(HTTPContext *s, char *data)
  844. {
  845. char *key;
  846. char *val;
  847. char *end;
  848. char *next = data;
  849. while (*next) {
  850. key = next;
  851. val = strstr(key, "='");
  852. if (!val)
  853. break;
  854. end = strstr(val, "';");
  855. if (!end)
  856. break;
  857. *val = '\0';
  858. *end = '\0';
  859. val += 2;
  860. av_dict_set(&s->metadata, key, val, 0);
  861. next = end + 2;
  862. }
  863. }
  864. static int store_icy(URLContext *h, int size)
  865. {
  866. HTTPContext *s = h->priv_data;
  867. /* until next metadata packet */
  868. int remaining = s->icy_metaint - s->icy_data_read;
  869. if (remaining < 0)
  870. return AVERROR_INVALIDDATA;
  871. if (!remaining) {
  872. /* The metadata packet is variable sized. It has a 1 byte header
  873. * which sets the length of the packet (divided by 16). If it's 0,
  874. * the metadata doesn't change. After the packet, icy_metaint bytes
  875. * of normal data follows. */
  876. uint8_t ch;
  877. int len = http_read_stream_all(h, &ch, 1);
  878. if (len < 0)
  879. return len;
  880. if (ch > 0) {
  881. char data[255 * 16 + 1];
  882. int ret;
  883. len = ch * 16;
  884. ret = http_read_stream_all(h, data, len);
  885. if (ret < 0)
  886. return ret;
  887. data[len + 1] = 0;
  888. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  889. return ret;
  890. update_metadata(s, data);
  891. }
  892. s->icy_data_read = 0;
  893. remaining = s->icy_metaint;
  894. }
  895. return FFMIN(size, remaining);
  896. }
  897. static int http_read(URLContext *h, uint8_t *buf, int size)
  898. {
  899. HTTPContext *s = h->priv_data;
  900. if (s->icy_metaint > 0) {
  901. size = store_icy(h, size);
  902. if (size < 0)
  903. return size;
  904. }
  905. size = http_read_stream(h, buf, size);
  906. if (size > 0)
  907. s->icy_data_read += size;
  908. return size;
  909. }
  910. /* used only when posting data */
  911. static int http_write(URLContext *h, const uint8_t *buf, int size)
  912. {
  913. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  914. int ret;
  915. char crlf[] = "\r\n";
  916. HTTPContext *s = h->priv_data;
  917. if (!s->chunked_post) {
  918. /* non-chunked data is sent without any special encoding */
  919. return ffurl_write(s->hd, buf, size);
  920. }
  921. /* silently ignore zero-size data since chunk encoding that would
  922. * signal EOF */
  923. if (size > 0) {
  924. /* upload data using chunked encoding */
  925. snprintf(temp, sizeof(temp), "%x\r\n", size);
  926. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  927. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  928. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  929. return ret;
  930. }
  931. return size;
  932. }
  933. static int http_shutdown(URLContext *h, int flags)
  934. {
  935. int ret = 0;
  936. char footer[] = "0\r\n\r\n";
  937. HTTPContext *s = h->priv_data;
  938. /* signal end of chunked encoding if used */
  939. if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
  940. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  941. ret = ret > 0 ? 0 : ret;
  942. s->end_chunked_post = 1;
  943. }
  944. return ret;
  945. }
  946. static int http_close(URLContext *h)
  947. {
  948. int ret = 0;
  949. HTTPContext *s = h->priv_data;
  950. #if CONFIG_ZLIB
  951. inflateEnd(&s->inflate_stream);
  952. av_freep(&s->inflate_buffer);
  953. #endif /* CONFIG_ZLIB */
  954. if (!s->end_chunked_post)
  955. /* Close the write direction by sending the end of chunked encoding. */
  956. ret = http_shutdown(h, h->flags);
  957. if (s->hd)
  958. ffurl_closep(&s->hd);
  959. av_dict_free(&s->chained_options);
  960. return ret;
  961. }
  962. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  963. {
  964. HTTPContext *s = h->priv_data;
  965. URLContext *old_hd = s->hd;
  966. int64_t old_off = s->off;
  967. uint8_t old_buf[BUFFER_SIZE];
  968. int old_buf_size, ret;
  969. AVDictionary *options = NULL;
  970. if (whence == AVSEEK_SIZE)
  971. return s->filesize;
  972. else if ((whence == SEEK_CUR && off == 0) ||
  973. (whence == SEEK_SET && off == s->off))
  974. return s->off;
  975. else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
  976. return AVERROR(ENOSYS);
  977. if (whence == SEEK_CUR)
  978. off += s->off;
  979. else if (whence == SEEK_END)
  980. off += s->filesize;
  981. else if (whence != SEEK_SET)
  982. return AVERROR(EINVAL);
  983. if (off < 0)
  984. return AVERROR(EINVAL);
  985. s->off = off;
  986. /* we save the old context in case the seek fails */
  987. old_buf_size = s->buf_end - s->buf_ptr;
  988. memcpy(old_buf, s->buf_ptr, old_buf_size);
  989. s->hd = NULL;
  990. /* if it fails, continue on old connection */
  991. av_dict_copy(&options, s->chained_options, 0);
  992. if ((ret = http_open_cnx(h, &options)) < 0) {
  993. av_dict_free(&options);
  994. memcpy(s->buffer, old_buf, old_buf_size);
  995. s->buf_ptr = s->buffer;
  996. s->buf_end = s->buffer + old_buf_size;
  997. s->hd = old_hd;
  998. s->off = old_off;
  999. return ret;
  1000. }
  1001. av_dict_free(&options);
  1002. ffurl_close(old_hd);
  1003. return off;
  1004. }
  1005. static int http_get_file_handle(URLContext *h)
  1006. {
  1007. HTTPContext *s = h->priv_data;
  1008. return ffurl_get_file_handle(s->hd);
  1009. }
  1010. #define HTTP_CLASS(flavor) \
  1011. static const AVClass flavor ## _context_class = { \
  1012. .class_name = # flavor, \
  1013. .item_name = av_default_item_name, \
  1014. .option = options, \
  1015. .version = LIBAVUTIL_VERSION_INT, \
  1016. }
  1017. #if CONFIG_HTTP_PROTOCOL
  1018. HTTP_CLASS(http);
  1019. URLProtocol ff_http_protocol = {
  1020. .name = "http",
  1021. .url_open2 = http_open,
  1022. .url_read = http_read,
  1023. .url_write = http_write,
  1024. .url_seek = http_seek,
  1025. .url_close = http_close,
  1026. .url_get_file_handle = http_get_file_handle,
  1027. .url_shutdown = http_shutdown,
  1028. .priv_data_size = sizeof(HTTPContext),
  1029. .priv_data_class = &http_context_class,
  1030. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1031. };
  1032. #endif /* CONFIG_HTTP_PROTOCOL */
  1033. #if CONFIG_HTTPS_PROTOCOL
  1034. HTTP_CLASS(https);
  1035. URLProtocol ff_https_protocol = {
  1036. .name = "https",
  1037. .url_open2 = http_open,
  1038. .url_read = http_read,
  1039. .url_write = http_write,
  1040. .url_seek = http_seek,
  1041. .url_close = http_close,
  1042. .url_get_file_handle = http_get_file_handle,
  1043. .url_shutdown = http_shutdown,
  1044. .priv_data_size = sizeof(HTTPContext),
  1045. .priv_data_class = &https_context_class,
  1046. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1047. };
  1048. #endif /* CONFIG_HTTPS_PROTOCOL */
  1049. #if CONFIG_HTTPPROXY_PROTOCOL
  1050. static int http_proxy_close(URLContext *h)
  1051. {
  1052. HTTPContext *s = h->priv_data;
  1053. if (s->hd)
  1054. ffurl_closep(&s->hd);
  1055. return 0;
  1056. }
  1057. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1058. {
  1059. HTTPContext *s = h->priv_data;
  1060. char hostname[1024], hoststr[1024];
  1061. char auth[1024], pathbuf[1024], *path;
  1062. char lower_url[100];
  1063. int port, ret = 0, attempts = 0;
  1064. HTTPAuthType cur_auth_type;
  1065. char *authstr;
  1066. int new_loc;
  1067. if( s->seekable == 1 )
  1068. h->is_streamed = 0;
  1069. else
  1070. h->is_streamed = 1;
  1071. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1072. pathbuf, sizeof(pathbuf), uri);
  1073. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1074. path = pathbuf;
  1075. if (*path == '/')
  1076. path++;
  1077. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1078. NULL);
  1079. redo:
  1080. ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1081. &h->interrupt_callback, NULL);
  1082. if (ret < 0)
  1083. return ret;
  1084. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1085. path, "CONNECT");
  1086. snprintf(s->buffer, sizeof(s->buffer),
  1087. "CONNECT %s HTTP/1.1\r\n"
  1088. "Host: %s\r\n"
  1089. "Connection: close\r\n"
  1090. "%s%s"
  1091. "\r\n",
  1092. path,
  1093. hoststr,
  1094. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1095. av_freep(&authstr);
  1096. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1097. goto fail;
  1098. s->buf_ptr = s->buffer;
  1099. s->buf_end = s->buffer;
  1100. s->line_count = 0;
  1101. s->filesize = -1;
  1102. cur_auth_type = s->proxy_auth_state.auth_type;
  1103. /* Note: This uses buffering, potentially reading more than the
  1104. * HTTP header. If tunneling a protocol where the server starts
  1105. * the conversation, we might buffer part of that here, too.
  1106. * Reading that requires using the proper ffurl_read() function
  1107. * on this URLContext, not using the fd directly (as the tls
  1108. * protocol does). This shouldn't be an issue for tls though,
  1109. * since the client starts the conversation there, so there
  1110. * is no extra data that we might buffer up here.
  1111. */
  1112. ret = http_read_header(h, &new_loc);
  1113. if (ret < 0)
  1114. goto fail;
  1115. attempts++;
  1116. if (s->http_code == 407 &&
  1117. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1118. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1119. ffurl_closep(&s->hd);
  1120. goto redo;
  1121. }
  1122. if (s->http_code < 400)
  1123. return 0;
  1124. ret = AVERROR(EIO);
  1125. fail:
  1126. http_proxy_close(h);
  1127. return ret;
  1128. }
  1129. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1130. {
  1131. HTTPContext *s = h->priv_data;
  1132. return ffurl_write(s->hd, buf, size);
  1133. }
  1134. URLProtocol ff_httpproxy_protocol = {
  1135. .name = "httpproxy",
  1136. .url_open = http_proxy_open,
  1137. .url_read = http_buf_read,
  1138. .url_write = http_proxy_write,
  1139. .url_close = http_proxy_close,
  1140. .url_get_file_handle = http_get_file_handle,
  1141. .priv_data_size = sizeof(HTTPContext),
  1142. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1143. };
  1144. #endif /* CONFIG_HTTPPROXY_PROTOCOL */