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.

1839 lines
61KB

  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/avassert.h"
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/opt.h"
  28. #include "libavutil/time.h"
  29. #include "libavutil/parseutils.h"
  30. #include "avformat.h"
  31. #include "http.h"
  32. #include "httpauth.h"
  33. #include "internal.h"
  34. #include "network.h"
  35. #include "os_support.h"
  36. #include "url.h"
  37. /* XXX: POST protocol is not completely implemented because ffmpeg uses
  38. * only a subset of it. */
  39. /* The IO buffer size is unrelated to the max URL size in itself, but needs
  40. * to be large enough to fit the full request headers (including long
  41. * path names). */
  42. #define BUFFER_SIZE MAX_URL_SIZE
  43. #define MAX_REDIRECTS 8
  44. #define HTTP_SINGLE 1
  45. #define HTTP_MUTLI 2
  46. #define MAX_EXPIRY 19
  47. #define WHITESPACES " \n\t\r"
  48. typedef enum {
  49. LOWER_PROTO,
  50. READ_HEADERS,
  51. WRITE_REPLY_HEADERS,
  52. FINISH
  53. }HandshakeState;
  54. typedef struct HTTPContext {
  55. const AVClass *class;
  56. URLContext *hd;
  57. unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
  58. int line_count;
  59. int http_code;
  60. /* Used if "Transfer-Encoding: chunked" otherwise -1. */
  61. uint64_t chunksize;
  62. int chunkend;
  63. uint64_t off, end_off, filesize;
  64. char *location;
  65. HTTPAuthState auth_state;
  66. HTTPAuthState proxy_auth_state;
  67. char *http_proxy;
  68. char *headers;
  69. char *mime_type;
  70. char *user_agent;
  71. #if FF_API_HTTP_USER_AGENT
  72. char *user_agent_deprecated;
  73. #endif
  74. char *content_type;
  75. /* Set if the server correctly handles Connection: close and will close
  76. * the connection after feeding us the content. */
  77. int willclose;
  78. int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
  79. int chunked_post;
  80. /* A flag which indicates if the end of chunked encoding has been sent. */
  81. int end_chunked_post;
  82. /* A flag which indicates we have finished to read POST reply. */
  83. int end_header;
  84. /* A flag which indicates if we use persistent connections. */
  85. int multiple_requests;
  86. uint8_t *post_data;
  87. int post_datalen;
  88. int is_akamai;
  89. int is_mediagateway;
  90. char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
  91. /* A dictionary containing cookies keyed by cookie name */
  92. AVDictionary *cookie_dict;
  93. int icy;
  94. /* how much data was read since the last ICY metadata packet */
  95. uint64_t icy_data_read;
  96. /* after how many bytes of read data a new metadata packet will be found */
  97. uint64_t icy_metaint;
  98. char *icy_metadata_headers;
  99. char *icy_metadata_packet;
  100. AVDictionary *metadata;
  101. #if CONFIG_ZLIB
  102. int compressed;
  103. z_stream inflate_stream;
  104. uint8_t *inflate_buffer;
  105. #endif /* CONFIG_ZLIB */
  106. AVDictionary *chained_options;
  107. int send_expect_100;
  108. char *method;
  109. int reconnect;
  110. int reconnect_at_eof;
  111. int reconnect_streamed;
  112. int reconnect_delay;
  113. int reconnect_delay_max;
  114. int listen;
  115. char *resource;
  116. int reply_code;
  117. int is_multi_client;
  118. HandshakeState handshake_step;
  119. int is_connected_server;
  120. } HTTPContext;
  121. #define OFFSET(x) offsetof(HTTPContext, x)
  122. #define D AV_OPT_FLAG_DECODING_PARAM
  123. #define E AV_OPT_FLAG_ENCODING_PARAM
  124. #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
  125. static const AVOption options[] = {
  126. { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
  127. { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
  128. { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
  129. { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
  130. { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
  131. { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  132. #if FF_API_HTTP_USER_AGENT
  133. { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
  134. #endif
  135. { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
  136. { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
  137. { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  138. { "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, { .str = NULL }, 0, 0, D },
  139. { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
  140. { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
  141. { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
  142. { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
  143. { "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"},
  144. { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
  145. { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
  146. { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
  147. { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
  148. { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
  149. { "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 },
  150. { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
  151. { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
  152. { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
  153. { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
  154. { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
  155. { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
  156. { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
  157. { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
  158. { NULL }
  159. };
  160. static int http_connect(URLContext *h, const char *path, const char *local_path,
  161. const char *hoststr, const char *auth,
  162. const char *proxyauth, int *new_location);
  163. static int http_read_header(URLContext *h, int *new_location);
  164. static int http_shutdown(URLContext *h, int flags);
  165. void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
  166. {
  167. memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
  168. &((HTTPContext *)src->priv_data)->auth_state,
  169. sizeof(HTTPAuthState));
  170. memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
  171. &((HTTPContext *)src->priv_data)->proxy_auth_state,
  172. sizeof(HTTPAuthState));
  173. }
  174. static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
  175. {
  176. const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
  177. char hostname[1024], hoststr[1024], proto[10];
  178. char auth[1024], proxyauth[1024] = "";
  179. char path1[MAX_URL_SIZE];
  180. char buf[1024], urlbuf[MAX_URL_SIZE];
  181. int port, use_proxy, err, location_changed = 0;
  182. HTTPContext *s = h->priv_data;
  183. av_url_split(proto, sizeof(proto), auth, sizeof(auth),
  184. hostname, sizeof(hostname), &port,
  185. path1, sizeof(path1), s->location);
  186. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  187. proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
  188. use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
  189. proxy_path && av_strstart(proxy_path, "http://", NULL);
  190. if (!strcmp(proto, "https")) {
  191. lower_proto = "tls";
  192. use_proxy = 0;
  193. if (port < 0)
  194. port = 443;
  195. }
  196. if (port < 0)
  197. port = 80;
  198. if (path1[0] == '\0')
  199. path = "/";
  200. else
  201. path = path1;
  202. local_path = path;
  203. if (use_proxy) {
  204. /* Reassemble the request URL without auth string - we don't
  205. * want to leak the auth to the proxy. */
  206. ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
  207. path1);
  208. path = urlbuf;
  209. av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
  210. hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
  211. }
  212. ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
  213. if (!s->hd) {
  214. err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
  215. &h->interrupt_callback, options,
  216. h->protocol_whitelist, h->protocol_blacklist, h);
  217. if (err < 0)
  218. return err;
  219. }
  220. err = http_connect(h, path, local_path, hoststr,
  221. auth, proxyauth, &location_changed);
  222. if (err < 0)
  223. return err;
  224. return location_changed;
  225. }
  226. /* return non zero if error */
  227. static int http_open_cnx(URLContext *h, AVDictionary **options)
  228. {
  229. HTTPAuthType cur_auth_type, cur_proxy_auth_type;
  230. HTTPContext *s = h->priv_data;
  231. int location_changed, attempts = 0, redirects = 0;
  232. redo:
  233. av_dict_copy(options, s->chained_options, 0);
  234. cur_auth_type = s->auth_state.auth_type;
  235. cur_proxy_auth_type = s->auth_state.auth_type;
  236. location_changed = http_open_cnx_internal(h, options);
  237. if (location_changed < 0)
  238. goto fail;
  239. attempts++;
  240. if (s->http_code == 401) {
  241. if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
  242. s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  243. ffurl_closep(&s->hd);
  244. goto redo;
  245. } else
  246. goto fail;
  247. }
  248. if (s->http_code == 407) {
  249. if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  250. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
  251. ffurl_closep(&s->hd);
  252. goto redo;
  253. } else
  254. goto fail;
  255. }
  256. if ((s->http_code == 301 || s->http_code == 302 ||
  257. s->http_code == 303 || s->http_code == 307) &&
  258. location_changed == 1) {
  259. /* url moved, get next */
  260. ffurl_closep(&s->hd);
  261. if (redirects++ >= MAX_REDIRECTS)
  262. return AVERROR(EIO);
  263. /* Restart the authentication process with the new target, which
  264. * might use a different auth mechanism. */
  265. memset(&s->auth_state, 0, sizeof(s->auth_state));
  266. attempts = 0;
  267. location_changed = 0;
  268. goto redo;
  269. }
  270. return 0;
  271. fail:
  272. if (s->hd)
  273. ffurl_closep(&s->hd);
  274. if (location_changed < 0)
  275. return location_changed;
  276. return ff_http_averror(s->http_code, AVERROR(EIO));
  277. }
  278. int ff_http_do_new_request(URLContext *h, const char *uri)
  279. {
  280. HTTPContext *s = h->priv_data;
  281. AVDictionary *options = NULL;
  282. int ret;
  283. char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
  284. int port1, port2;
  285. av_url_split(proto1, sizeof(proto1), NULL, 0,
  286. hostname1, sizeof(hostname1), &port1,
  287. NULL, 0, s->location);
  288. av_url_split(proto2, sizeof(proto2), NULL, 0,
  289. hostname2, sizeof(hostname2), &port2,
  290. NULL, 0, uri);
  291. if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
  292. av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
  293. hostname1, port1,
  294. hostname2, port2
  295. );
  296. return AVERROR(EINVAL);
  297. }
  298. ret = http_shutdown(h, h->flags);
  299. if (ret < 0)
  300. return ret;
  301. s->end_chunked_post = 0;
  302. s->chunkend = 0;
  303. s->off = 0;
  304. s->icy_data_read = 0;
  305. av_free(s->location);
  306. s->location = av_strdup(uri);
  307. if (!s->location)
  308. return AVERROR(ENOMEM);
  309. ret = http_open_cnx(h, &options);
  310. av_dict_free(&options);
  311. return ret;
  312. }
  313. int ff_http_averror(int status_code, int default_averror)
  314. {
  315. switch (status_code) {
  316. case 400: return AVERROR_HTTP_BAD_REQUEST;
  317. case 401: return AVERROR_HTTP_UNAUTHORIZED;
  318. case 403: return AVERROR_HTTP_FORBIDDEN;
  319. case 404: return AVERROR_HTTP_NOT_FOUND;
  320. default: break;
  321. }
  322. if (status_code >= 400 && status_code <= 499)
  323. return AVERROR_HTTP_OTHER_4XX;
  324. else if (status_code >= 500)
  325. return AVERROR_HTTP_SERVER_ERROR;
  326. else
  327. return default_averror;
  328. }
  329. static int http_write_reply(URLContext* h, int status_code)
  330. {
  331. int ret, body = 0, reply_code, message_len;
  332. const char *reply_text, *content_type;
  333. HTTPContext *s = h->priv_data;
  334. char message[BUFFER_SIZE];
  335. content_type = "text/plain";
  336. if (status_code < 0)
  337. body = 1;
  338. switch (status_code) {
  339. case AVERROR_HTTP_BAD_REQUEST:
  340. case 400:
  341. reply_code = 400;
  342. reply_text = "Bad Request";
  343. break;
  344. case AVERROR_HTTP_FORBIDDEN:
  345. case 403:
  346. reply_code = 403;
  347. reply_text = "Forbidden";
  348. break;
  349. case AVERROR_HTTP_NOT_FOUND:
  350. case 404:
  351. reply_code = 404;
  352. reply_text = "Not Found";
  353. break;
  354. case 200:
  355. reply_code = 200;
  356. reply_text = "OK";
  357. content_type = s->content_type ? s->content_type : "application/octet-stream";
  358. break;
  359. case AVERROR_HTTP_SERVER_ERROR:
  360. case 500:
  361. reply_code = 500;
  362. reply_text = "Internal server error";
  363. break;
  364. default:
  365. return AVERROR(EINVAL);
  366. }
  367. if (body) {
  368. s->chunked_post = 0;
  369. message_len = snprintf(message, sizeof(message),
  370. "HTTP/1.1 %03d %s\r\n"
  371. "Content-Type: %s\r\n"
  372. "Content-Length: %"SIZE_SPECIFIER"\r\n"
  373. "%s"
  374. "\r\n"
  375. "%03d %s\r\n",
  376. reply_code,
  377. reply_text,
  378. content_type,
  379. strlen(reply_text) + 6, // 3 digit status code + space + \r\n
  380. s->headers ? s->headers : "",
  381. reply_code,
  382. reply_text);
  383. } else {
  384. s->chunked_post = 1;
  385. message_len = snprintf(message, sizeof(message),
  386. "HTTP/1.1 %03d %s\r\n"
  387. "Content-Type: %s\r\n"
  388. "Transfer-Encoding: chunked\r\n"
  389. "%s"
  390. "\r\n",
  391. reply_code,
  392. reply_text,
  393. content_type,
  394. s->headers ? s->headers : "");
  395. }
  396. av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
  397. if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
  398. return ret;
  399. return 0;
  400. }
  401. static void handle_http_errors(URLContext *h, int error)
  402. {
  403. av_assert0(error < 0);
  404. http_write_reply(h, error);
  405. }
  406. static int http_handshake(URLContext *c)
  407. {
  408. int ret, err, new_location;
  409. HTTPContext *ch = c->priv_data;
  410. URLContext *cl = ch->hd;
  411. switch (ch->handshake_step) {
  412. case LOWER_PROTO:
  413. av_log(c, AV_LOG_TRACE, "Lower protocol\n");
  414. if ((ret = ffurl_handshake(cl)) > 0)
  415. return 2 + ret;
  416. if (ret < 0)
  417. return ret;
  418. ch->handshake_step = READ_HEADERS;
  419. ch->is_connected_server = 1;
  420. return 2;
  421. case READ_HEADERS:
  422. av_log(c, AV_LOG_TRACE, "Read headers\n");
  423. if ((err = http_read_header(c, &new_location)) < 0) {
  424. handle_http_errors(c, err);
  425. return err;
  426. }
  427. ch->handshake_step = WRITE_REPLY_HEADERS;
  428. return 1;
  429. case WRITE_REPLY_HEADERS:
  430. av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
  431. if ((err = http_write_reply(c, ch->reply_code)) < 0)
  432. return err;
  433. ch->handshake_step = FINISH;
  434. return 1;
  435. case FINISH:
  436. return 0;
  437. }
  438. // this should never be reached.
  439. return AVERROR(EINVAL);
  440. }
  441. static int http_listen(URLContext *h, const char *uri, int flags,
  442. AVDictionary **options) {
  443. HTTPContext *s = h->priv_data;
  444. int ret;
  445. char hostname[1024], proto[10];
  446. char lower_url[100];
  447. const char *lower_proto = "tcp";
  448. int port;
  449. av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
  450. NULL, 0, uri);
  451. if (!strcmp(proto, "https"))
  452. lower_proto = "tls";
  453. ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
  454. NULL);
  455. if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
  456. goto fail;
  457. if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  458. &h->interrupt_callback, options,
  459. h->protocol_whitelist, h->protocol_blacklist, h
  460. )) < 0)
  461. goto fail;
  462. s->handshake_step = LOWER_PROTO;
  463. if (s->listen == HTTP_SINGLE) { /* single client */
  464. s->reply_code = 200;
  465. while ((ret = http_handshake(h)) > 0);
  466. }
  467. fail:
  468. av_dict_free(&s->chained_options);
  469. return ret;
  470. }
  471. static int http_open(URLContext *h, const char *uri, int flags,
  472. AVDictionary **options)
  473. {
  474. HTTPContext *s = h->priv_data;
  475. int ret;
  476. if( s->seekable == 1 )
  477. h->is_streamed = 0;
  478. else
  479. h->is_streamed = 1;
  480. s->filesize = UINT64_MAX;
  481. s->location = av_strdup(uri);
  482. if (!s->location)
  483. return AVERROR(ENOMEM);
  484. if (options)
  485. av_dict_copy(&s->chained_options, *options, 0);
  486. if (s->headers) {
  487. int len = strlen(s->headers);
  488. if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
  489. av_log(h, AV_LOG_WARNING,
  490. "No trailing CRLF found in HTTP header.\n");
  491. ret = av_reallocp(&s->headers, len + 3);
  492. if (ret < 0)
  493. return ret;
  494. s->headers[len] = '\r';
  495. s->headers[len + 1] = '\n';
  496. s->headers[len + 2] = '\0';
  497. }
  498. }
  499. if (s->listen) {
  500. return http_listen(h, uri, flags, options);
  501. }
  502. ret = http_open_cnx(h, options);
  503. if (ret < 0)
  504. av_dict_free(&s->chained_options);
  505. return ret;
  506. }
  507. static int http_accept(URLContext *s, URLContext **c)
  508. {
  509. int ret;
  510. HTTPContext *sc = s->priv_data;
  511. HTTPContext *cc;
  512. URLContext *sl = sc->hd;
  513. URLContext *cl = NULL;
  514. av_assert0(sc->listen);
  515. if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
  516. goto fail;
  517. cc = (*c)->priv_data;
  518. if ((ret = ffurl_accept(sl, &cl)) < 0)
  519. goto fail;
  520. cc->hd = cl;
  521. cc->is_multi_client = 1;
  522. fail:
  523. return ret;
  524. }
  525. static int http_getc(HTTPContext *s)
  526. {
  527. int len;
  528. if (s->buf_ptr >= s->buf_end) {
  529. len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
  530. if (len < 0) {
  531. return len;
  532. } else if (len == 0) {
  533. return AVERROR_EOF;
  534. } else {
  535. s->buf_ptr = s->buffer;
  536. s->buf_end = s->buffer + len;
  537. }
  538. }
  539. return *s->buf_ptr++;
  540. }
  541. static int http_get_line(HTTPContext *s, char *line, int line_size)
  542. {
  543. int ch;
  544. char *q;
  545. q = line;
  546. for (;;) {
  547. ch = http_getc(s);
  548. if (ch < 0)
  549. return ch;
  550. if (ch == '\n') {
  551. /* process line */
  552. if (q > line && q[-1] == '\r')
  553. q--;
  554. *q = '\0';
  555. return 0;
  556. } else {
  557. if ((q - line) < line_size - 1)
  558. *q++ = ch;
  559. }
  560. }
  561. }
  562. static int check_http_code(URLContext *h, int http_code, const char *end)
  563. {
  564. HTTPContext *s = h->priv_data;
  565. /* error codes are 4xx and 5xx, but regard 401 as a success, so we
  566. * don't abort until all headers have been parsed. */
  567. if (http_code >= 400 && http_code < 600 &&
  568. (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
  569. (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
  570. end += strspn(end, SPACE_CHARS);
  571. av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
  572. return ff_http_averror(http_code, AVERROR(EIO));
  573. }
  574. return 0;
  575. }
  576. static int parse_location(HTTPContext *s, const char *p)
  577. {
  578. char redirected_location[MAX_URL_SIZE], *new_loc;
  579. ff_make_absolute_url(redirected_location, sizeof(redirected_location),
  580. s->location, p);
  581. new_loc = av_strdup(redirected_location);
  582. if (!new_loc)
  583. return AVERROR(ENOMEM);
  584. av_free(s->location);
  585. s->location = new_loc;
  586. return 0;
  587. }
  588. /* "bytes $from-$to/$document_size" */
  589. static void parse_content_range(URLContext *h, const char *p)
  590. {
  591. HTTPContext *s = h->priv_data;
  592. const char *slash;
  593. if (!strncmp(p, "bytes ", 6)) {
  594. p += 6;
  595. s->off = strtoull(p, NULL, 10);
  596. if ((slash = strchr(p, '/')) && strlen(slash) > 0)
  597. s->filesize = strtoull(slash + 1, NULL, 10);
  598. }
  599. if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
  600. h->is_streamed = 0; /* we _can_ in fact seek */
  601. }
  602. static int parse_content_encoding(URLContext *h, const char *p)
  603. {
  604. if (!av_strncasecmp(p, "gzip", 4) ||
  605. !av_strncasecmp(p, "deflate", 7)) {
  606. #if CONFIG_ZLIB
  607. HTTPContext *s = h->priv_data;
  608. s->compressed = 1;
  609. inflateEnd(&s->inflate_stream);
  610. if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
  611. av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
  612. s->inflate_stream.msg);
  613. return AVERROR(ENOSYS);
  614. }
  615. if (zlibCompileFlags() & (1 << 17)) {
  616. av_log(h, AV_LOG_WARNING,
  617. "Your zlib was compiled without gzip support.\n");
  618. return AVERROR(ENOSYS);
  619. }
  620. #else
  621. av_log(h, AV_LOG_WARNING,
  622. "Compressed (%s) content, need zlib with gzip support\n", p);
  623. return AVERROR(ENOSYS);
  624. #endif /* CONFIG_ZLIB */
  625. } else if (!av_strncasecmp(p, "identity", 8)) {
  626. // The normal, no-encoding case (although servers shouldn't include
  627. // the header at all if this is the case).
  628. } else {
  629. av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
  630. }
  631. return 0;
  632. }
  633. // Concat all Icy- header lines
  634. static int parse_icy(HTTPContext *s, const char *tag, const char *p)
  635. {
  636. int len = 4 + strlen(p) + strlen(tag);
  637. int is_first = !s->icy_metadata_headers;
  638. int ret;
  639. av_dict_set(&s->metadata, tag, p, 0);
  640. if (s->icy_metadata_headers)
  641. len += strlen(s->icy_metadata_headers);
  642. if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
  643. return ret;
  644. if (is_first)
  645. *s->icy_metadata_headers = '\0';
  646. av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
  647. return 0;
  648. }
  649. static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
  650. {
  651. char exp_buf[MAX_EXPIRY];
  652. int i, j, exp_buf_len = MAX_EXPIRY-1;
  653. char *expiry;
  654. // strip off any punctuation or whitespace
  655. for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
  656. if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
  657. (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
  658. (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
  659. exp_buf[j] = exp_str[i];
  660. j++;
  661. }
  662. }
  663. exp_buf[j] = '\0';
  664. expiry = exp_buf;
  665. // move the string beyond the day of week
  666. while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
  667. expiry++;
  668. return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
  669. }
  670. static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
  671. {
  672. char *param, *next_param, *cstr, *back;
  673. if (!(cstr = av_strdup(set_cookie)))
  674. return AVERROR(EINVAL);
  675. // strip any trailing whitespace
  676. back = &cstr[strlen(cstr)-1];
  677. while (strchr(WHITESPACES, *back)) {
  678. *back='\0';
  679. back--;
  680. }
  681. next_param = cstr;
  682. while ((param = av_strtok(next_param, ";", &next_param))) {
  683. char *name, *value;
  684. param += strspn(param, WHITESPACES);
  685. if ((name = av_strtok(param, "=", &value))) {
  686. if (av_dict_set(dict, name, value, 0) < 0) {
  687. av_free(cstr);
  688. return -1;
  689. }
  690. }
  691. }
  692. av_free(cstr);
  693. return 0;
  694. }
  695. static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
  696. {
  697. AVDictionary *new_params = NULL;
  698. AVDictionaryEntry *e, *cookie_entry;
  699. char *eql, *name;
  700. // ensure the cookie is parsable
  701. if (parse_set_cookie(p, &new_params))
  702. return -1;
  703. // if there is no cookie value there is nothing to parse
  704. cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
  705. if (!cookie_entry || !cookie_entry->value) {
  706. av_dict_free(&new_params);
  707. return -1;
  708. }
  709. // ensure the cookie is not expired or older than an existing value
  710. if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
  711. struct tm new_tm = {0};
  712. if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
  713. AVDictionaryEntry *e2;
  714. // if the cookie has already expired ignore it
  715. if (av_timegm(&new_tm) < av_gettime() / 1000000) {
  716. av_dict_free(&new_params);
  717. return -1;
  718. }
  719. // only replace an older cookie with the same name
  720. e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
  721. if (e2 && e2->value) {
  722. AVDictionary *old_params = NULL;
  723. if (!parse_set_cookie(p, &old_params)) {
  724. e2 = av_dict_get(old_params, "expires", NULL, 0);
  725. if (e2 && e2->value) {
  726. struct tm old_tm = {0};
  727. if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
  728. if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
  729. av_dict_free(&new_params);
  730. av_dict_free(&old_params);
  731. return -1;
  732. }
  733. }
  734. }
  735. }
  736. av_dict_free(&old_params);
  737. }
  738. }
  739. }
  740. // duplicate the cookie name (dict will dupe the value)
  741. if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
  742. if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
  743. // add the cookie to the dictionary
  744. av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
  745. return 0;
  746. }
  747. static int cookie_string(AVDictionary *dict, char **cookies)
  748. {
  749. AVDictionaryEntry *e = NULL;
  750. int len = 1;
  751. // determine how much memory is needed for the cookies string
  752. while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
  753. len += strlen(e->key) + strlen(e->value) + 1;
  754. // reallocate the cookies
  755. e = NULL;
  756. if (*cookies) av_free(*cookies);
  757. *cookies = av_malloc(len);
  758. if (!*cookies) return AVERROR(ENOMEM);
  759. *cookies[0] = '\0';
  760. // write out the cookies
  761. while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
  762. av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
  763. return 0;
  764. }
  765. static int process_line(URLContext *h, char *line, int line_count,
  766. int *new_location)
  767. {
  768. HTTPContext *s = h->priv_data;
  769. const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
  770. char *tag, *p, *end, *method, *resource, *version;
  771. int ret;
  772. /* end of header */
  773. if (line[0] == '\0') {
  774. s->end_header = 1;
  775. return 0;
  776. }
  777. p = line;
  778. if (line_count == 0) {
  779. if (s->is_connected_server) {
  780. // HTTP method
  781. method = p;
  782. while (*p && !av_isspace(*p))
  783. p++;
  784. *(p++) = '\0';
  785. av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
  786. if (s->method) {
  787. if (av_strcasecmp(s->method, method)) {
  788. av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
  789. s->method, method);
  790. return ff_http_averror(400, AVERROR(EIO));
  791. }
  792. } else {
  793. // use autodetected HTTP method to expect
  794. av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
  795. if (av_strcasecmp(auto_method, method)) {
  796. av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
  797. "(%s autodetected %s received)\n", auto_method, method);
  798. return ff_http_averror(400, AVERROR(EIO));
  799. }
  800. if (!(s->method = av_strdup(method)))
  801. return AVERROR(ENOMEM);
  802. }
  803. // HTTP resource
  804. while (av_isspace(*p))
  805. p++;
  806. resource = p;
  807. while (!av_isspace(*p))
  808. p++;
  809. *(p++) = '\0';
  810. av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
  811. if (!(s->resource = av_strdup(resource)))
  812. return AVERROR(ENOMEM);
  813. // HTTP version
  814. while (av_isspace(*p))
  815. p++;
  816. version = p;
  817. while (*p && !av_isspace(*p))
  818. p++;
  819. *p = '\0';
  820. if (av_strncasecmp(version, "HTTP/", 5)) {
  821. av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
  822. return ff_http_averror(400, AVERROR(EIO));
  823. }
  824. av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
  825. } else {
  826. while (!av_isspace(*p) && *p != '\0')
  827. p++;
  828. while (av_isspace(*p))
  829. p++;
  830. s->http_code = strtol(p, &end, 10);
  831. av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
  832. if ((ret = check_http_code(h, s->http_code, end)) < 0)
  833. return ret;
  834. }
  835. } else {
  836. while (*p != '\0' && *p != ':')
  837. p++;
  838. if (*p != ':')
  839. return 1;
  840. *p = '\0';
  841. tag = line;
  842. p++;
  843. while (av_isspace(*p))
  844. p++;
  845. if (!av_strcasecmp(tag, "Location")) {
  846. if ((ret = parse_location(s, p)) < 0)
  847. return ret;
  848. *new_location = 1;
  849. } else if (!av_strcasecmp(tag, "Content-Length") &&
  850. s->filesize == UINT64_MAX) {
  851. s->filesize = strtoull(p, NULL, 10);
  852. } else if (!av_strcasecmp(tag, "Content-Range")) {
  853. parse_content_range(h, p);
  854. } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
  855. !strncmp(p, "bytes", 5) &&
  856. s->seekable == -1) {
  857. h->is_streamed = 0;
  858. } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
  859. !av_strncasecmp(p, "chunked", 7)) {
  860. s->filesize = UINT64_MAX;
  861. s->chunksize = 0;
  862. } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
  863. ff_http_auth_handle_header(&s->auth_state, tag, p);
  864. } else if (!av_strcasecmp(tag, "Authentication-Info")) {
  865. ff_http_auth_handle_header(&s->auth_state, tag, p);
  866. } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
  867. ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
  868. } else if (!av_strcasecmp(tag, "Connection")) {
  869. if (!strcmp(p, "close"))
  870. s->willclose = 1;
  871. } else if (!av_strcasecmp(tag, "Server")) {
  872. if (!av_strcasecmp(p, "AkamaiGHost")) {
  873. s->is_akamai = 1;
  874. } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
  875. s->is_mediagateway = 1;
  876. }
  877. } else if (!av_strcasecmp(tag, "Content-Type")) {
  878. av_free(s->mime_type);
  879. s->mime_type = av_strdup(p);
  880. } else if (!av_strcasecmp(tag, "Set-Cookie")) {
  881. if (parse_cookie(s, p, &s->cookie_dict))
  882. av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
  883. } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
  884. s->icy_metaint = strtoull(p, NULL, 10);
  885. } else if (!av_strncasecmp(tag, "Icy-", 4)) {
  886. if ((ret = parse_icy(s, tag, p)) < 0)
  887. return ret;
  888. } else if (!av_strcasecmp(tag, "Content-Encoding")) {
  889. if ((ret = parse_content_encoding(h, p)) < 0)
  890. return ret;
  891. }
  892. }
  893. return 1;
  894. }
  895. /**
  896. * Create a string containing cookie values for use as a HTTP cookie header
  897. * field value for a particular path and domain from the cookie values stored in
  898. * the HTTP protocol context. The cookie string is stored in *cookies.
  899. *
  900. * @return a negative value if an error condition occurred, 0 otherwise
  901. */
  902. static int get_cookies(HTTPContext *s, char **cookies, const char *path,
  903. const char *domain)
  904. {
  905. // cookie strings will look like Set-Cookie header field values. Multiple
  906. // Set-Cookie fields will result in multiple values delimited by a newline
  907. int ret = 0;
  908. char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
  909. if (!set_cookies) return AVERROR(EINVAL);
  910. // destroy any cookies in the dictionary.
  911. av_dict_free(&s->cookie_dict);
  912. *cookies = NULL;
  913. while ((cookie = av_strtok(next, "\n", &next))) {
  914. AVDictionary *cookie_params = NULL;
  915. AVDictionaryEntry *cookie_entry, *e;
  916. // store the cookie in a dict in case it is updated in the response
  917. if (parse_cookie(s, cookie, &s->cookie_dict))
  918. av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
  919. // continue on to the next cookie if this one cannot be parsed
  920. if (parse_set_cookie(cookie, &cookie_params))
  921. continue;
  922. // if the cookie has no value, skip it
  923. cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
  924. if (!cookie_entry || !cookie_entry->value) {
  925. av_dict_free(&cookie_params);
  926. continue;
  927. }
  928. // if the cookie has expired, don't add it
  929. if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
  930. struct tm tm_buf = {0};
  931. if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
  932. if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
  933. av_dict_free(&cookie_params);
  934. continue;
  935. }
  936. }
  937. }
  938. // if no domain in the cookie assume it appied to this request
  939. if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
  940. // find the offset comparison is on the min domain (b.com, not a.b.com)
  941. int domain_offset = strlen(domain) - strlen(e->value);
  942. if (domain_offset < 0) {
  943. av_dict_free(&cookie_params);
  944. continue;
  945. }
  946. // match the cookie domain
  947. if (av_strcasecmp(&domain[domain_offset], e->value)) {
  948. av_dict_free(&cookie_params);
  949. continue;
  950. }
  951. }
  952. // ensure this cookie matches the path
  953. e = av_dict_get(cookie_params, "path", NULL, 0);
  954. if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
  955. av_dict_free(&cookie_params);
  956. continue;
  957. }
  958. // cookie parameters match, so copy the value
  959. if (!*cookies) {
  960. if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
  961. ret = AVERROR(ENOMEM);
  962. break;
  963. }
  964. } else {
  965. char *tmp = *cookies;
  966. size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
  967. if (!(*cookies = av_malloc(str_size))) {
  968. ret = AVERROR(ENOMEM);
  969. av_free(tmp);
  970. break;
  971. }
  972. snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
  973. av_free(tmp);
  974. }
  975. }
  976. av_free(set_cookies);
  977. return ret;
  978. }
  979. static inline int has_header(const char *str, const char *header)
  980. {
  981. /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
  982. if (!str)
  983. return 0;
  984. return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
  985. }
  986. static int http_read_header(URLContext *h, int *new_location)
  987. {
  988. HTTPContext *s = h->priv_data;
  989. char line[MAX_URL_SIZE];
  990. int err = 0;
  991. s->chunksize = UINT64_MAX;
  992. for (;;) {
  993. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  994. return err;
  995. av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
  996. err = process_line(h, line, s->line_count, new_location);
  997. if (err < 0)
  998. return err;
  999. if (err == 0)
  1000. break;
  1001. s->line_count++;
  1002. }
  1003. if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
  1004. h->is_streamed = 1; /* we can in fact _not_ seek */
  1005. // add any new cookies into the existing cookie string
  1006. cookie_string(s->cookie_dict, &s->cookies);
  1007. av_dict_free(&s->cookie_dict);
  1008. return err;
  1009. }
  1010. static int http_connect(URLContext *h, const char *path, const char *local_path,
  1011. const char *hoststr, const char *auth,
  1012. const char *proxyauth, int *new_location)
  1013. {
  1014. HTTPContext *s = h->priv_data;
  1015. int post, err;
  1016. char headers[HTTP_HEADERS_SIZE] = "";
  1017. char *authstr = NULL, *proxyauthstr = NULL;
  1018. uint64_t off = s->off;
  1019. int len = 0;
  1020. const char *method;
  1021. int send_expect_100 = 0;
  1022. int ret;
  1023. /* send http header */
  1024. post = h->flags & AVIO_FLAG_WRITE;
  1025. if (s->post_data) {
  1026. /* force POST method and disable chunked encoding when
  1027. * custom HTTP post data is set */
  1028. post = 1;
  1029. s->chunked_post = 0;
  1030. }
  1031. if (s->method)
  1032. method = s->method;
  1033. else
  1034. method = post ? "POST" : "GET";
  1035. authstr = ff_http_auth_create_response(&s->auth_state, auth,
  1036. local_path, method);
  1037. proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
  1038. local_path, method);
  1039. if (post && !s->post_data) {
  1040. send_expect_100 = s->send_expect_100;
  1041. /* The user has supplied authentication but we don't know the auth type,
  1042. * send Expect: 100-continue to get the 401 response including the
  1043. * WWW-Authenticate header, or an 100 continue if no auth actually
  1044. * is needed. */
  1045. if (auth && *auth &&
  1046. s->auth_state.auth_type == HTTP_AUTH_NONE &&
  1047. s->http_code != 401)
  1048. send_expect_100 = 1;
  1049. }
  1050. #if FF_API_HTTP_USER_AGENT
  1051. if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
  1052. av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
  1053. s->user_agent = av_strdup(s->user_agent_deprecated);
  1054. }
  1055. #endif
  1056. /* set default headers if needed */
  1057. if (!has_header(s->headers, "\r\nUser-Agent: "))
  1058. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1059. "User-Agent: %s\r\n", s->user_agent);
  1060. if (!has_header(s->headers, "\r\nAccept: "))
  1061. len += av_strlcpy(headers + len, "Accept: */*\r\n",
  1062. sizeof(headers) - len);
  1063. // Note: we send this on purpose even when s->off is 0 when we're probing,
  1064. // since it allows us to detect more reliably if a (non-conforming)
  1065. // server supports seeking by analysing the reply headers.
  1066. if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
  1067. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1068. "Range: bytes=%"PRIu64"-", s->off);
  1069. if (s->end_off)
  1070. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1071. "%"PRId64, s->end_off - 1);
  1072. len += av_strlcpy(headers + len, "\r\n",
  1073. sizeof(headers) - len);
  1074. }
  1075. if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
  1076. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1077. "Expect: 100-continue\r\n");
  1078. if (!has_header(s->headers, "\r\nConnection: ")) {
  1079. if (s->multiple_requests)
  1080. len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
  1081. sizeof(headers) - len);
  1082. else
  1083. len += av_strlcpy(headers + len, "Connection: close\r\n",
  1084. sizeof(headers) - len);
  1085. }
  1086. if (!has_header(s->headers, "\r\nHost: "))
  1087. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1088. "Host: %s\r\n", hoststr);
  1089. if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
  1090. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1091. "Content-Length: %d\r\n", s->post_datalen);
  1092. if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
  1093. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1094. "Content-Type: %s\r\n", s->content_type);
  1095. if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
  1096. char *cookies = NULL;
  1097. if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
  1098. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1099. "Cookie: %s\r\n", cookies);
  1100. av_free(cookies);
  1101. }
  1102. }
  1103. if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
  1104. len += av_strlcatf(headers + len, sizeof(headers) - len,
  1105. "Icy-MetaData: %d\r\n", 1);
  1106. /* now add in custom headers */
  1107. if (s->headers)
  1108. av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
  1109. ret = snprintf(s->buffer, sizeof(s->buffer),
  1110. "%s %s HTTP/1.1\r\n"
  1111. "%s"
  1112. "%s"
  1113. "%s"
  1114. "%s%s"
  1115. "\r\n",
  1116. method,
  1117. path,
  1118. post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
  1119. headers,
  1120. authstr ? authstr : "",
  1121. proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
  1122. av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
  1123. if (strlen(headers) + 1 == sizeof(headers) ||
  1124. ret >= sizeof(s->buffer)) {
  1125. av_log(h, AV_LOG_ERROR, "overlong headers\n");
  1126. err = AVERROR(EINVAL);
  1127. goto done;
  1128. }
  1129. if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1130. goto done;
  1131. if (s->post_data)
  1132. if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
  1133. goto done;
  1134. /* init input buffer */
  1135. s->buf_ptr = s->buffer;
  1136. s->buf_end = s->buffer;
  1137. s->line_count = 0;
  1138. s->off = 0;
  1139. s->icy_data_read = 0;
  1140. s->filesize = UINT64_MAX;
  1141. s->willclose = 0;
  1142. s->end_chunked_post = 0;
  1143. s->end_header = 0;
  1144. #if CONFIG_ZLIB
  1145. s->compressed = 0;
  1146. #endif
  1147. if (post && !s->post_data && !send_expect_100) {
  1148. /* Pretend that it did work. We didn't read any header yet, since
  1149. * we've still to send the POST data, but the code calling this
  1150. * function will check http_code after we return. */
  1151. s->http_code = 200;
  1152. err = 0;
  1153. goto done;
  1154. }
  1155. /* wait for header */
  1156. err = http_read_header(h, new_location);
  1157. if (err < 0)
  1158. goto done;
  1159. if (*new_location)
  1160. s->off = off;
  1161. err = (off == s->off) ? 0 : -1;
  1162. done:
  1163. av_freep(&authstr);
  1164. av_freep(&proxyauthstr);
  1165. return err;
  1166. }
  1167. static int http_buf_read(URLContext *h, uint8_t *buf, int size)
  1168. {
  1169. HTTPContext *s = h->priv_data;
  1170. int len;
  1171. if (s->chunksize != UINT64_MAX) {
  1172. if (s->chunkend) {
  1173. return AVERROR_EOF;
  1174. }
  1175. if (!s->chunksize) {
  1176. char line[32];
  1177. int err;
  1178. do {
  1179. if ((err = http_get_line(s, line, sizeof(line))) < 0)
  1180. return err;
  1181. } while (!*line); /* skip CR LF from last chunk */
  1182. s->chunksize = strtoull(line, NULL, 16);
  1183. av_log(h, AV_LOG_TRACE,
  1184. "Chunked encoding data size: %"PRIu64"\n",
  1185. s->chunksize);
  1186. if (!s->chunksize && s->multiple_requests) {
  1187. http_get_line(s, line, sizeof(line)); // read empty chunk
  1188. s->chunkend = 1;
  1189. return 0;
  1190. }
  1191. else if (!s->chunksize) {
  1192. av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
  1193. ffurl_closep(&s->hd);
  1194. return 0;
  1195. }
  1196. else if (s->chunksize == UINT64_MAX) {
  1197. av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
  1198. s->chunksize);
  1199. return AVERROR(EINVAL);
  1200. }
  1201. }
  1202. size = FFMIN(size, s->chunksize);
  1203. }
  1204. /* read bytes from input buffer first */
  1205. len = s->buf_end - s->buf_ptr;
  1206. if (len > 0) {
  1207. if (len > size)
  1208. len = size;
  1209. memcpy(buf, s->buf_ptr, len);
  1210. s->buf_ptr += len;
  1211. } else {
  1212. uint64_t target_end = s->end_off ? s->end_off : s->filesize;
  1213. if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
  1214. return AVERROR_EOF;
  1215. len = ffurl_read(s->hd, buf, size);
  1216. if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
  1217. av_log(h, AV_LOG_ERROR,
  1218. "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
  1219. s->off, target_end
  1220. );
  1221. return AVERROR(EIO);
  1222. }
  1223. }
  1224. if (len > 0) {
  1225. s->off += len;
  1226. if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
  1227. av_assert0(s->chunksize >= len);
  1228. s->chunksize -= len;
  1229. }
  1230. }
  1231. return len;
  1232. }
  1233. #if CONFIG_ZLIB
  1234. #define DECOMPRESS_BUF_SIZE (256 * 1024)
  1235. static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
  1236. {
  1237. HTTPContext *s = h->priv_data;
  1238. int ret;
  1239. if (!s->inflate_buffer) {
  1240. s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
  1241. if (!s->inflate_buffer)
  1242. return AVERROR(ENOMEM);
  1243. }
  1244. if (s->inflate_stream.avail_in == 0) {
  1245. int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
  1246. if (read <= 0)
  1247. return read;
  1248. s->inflate_stream.next_in = s->inflate_buffer;
  1249. s->inflate_stream.avail_in = read;
  1250. }
  1251. s->inflate_stream.avail_out = size;
  1252. s->inflate_stream.next_out = buf;
  1253. ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
  1254. if (ret != Z_OK && ret != Z_STREAM_END)
  1255. av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
  1256. ret, s->inflate_stream.msg);
  1257. return size - s->inflate_stream.avail_out;
  1258. }
  1259. #endif /* CONFIG_ZLIB */
  1260. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
  1261. static int http_read_stream(URLContext *h, uint8_t *buf, int size)
  1262. {
  1263. HTTPContext *s = h->priv_data;
  1264. int err, new_location, read_ret;
  1265. int64_t seek_ret;
  1266. if (!s->hd)
  1267. return AVERROR_EOF;
  1268. if (s->end_chunked_post && !s->end_header) {
  1269. err = http_read_header(h, &new_location);
  1270. if (err < 0)
  1271. return err;
  1272. }
  1273. #if CONFIG_ZLIB
  1274. if (s->compressed)
  1275. return http_buf_read_compressed(h, buf, size);
  1276. #endif /* CONFIG_ZLIB */
  1277. read_ret = http_buf_read(h, buf, size);
  1278. if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
  1279. || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
  1280. uint64_t target = h->is_streamed ? 0 : s->off;
  1281. if (s->reconnect_delay > s->reconnect_delay_max)
  1282. return AVERROR(EIO);
  1283. av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
  1284. av_usleep(1000U*1000*s->reconnect_delay);
  1285. s->reconnect_delay = 1 + 2*s->reconnect_delay;
  1286. seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
  1287. if (seek_ret != target) {
  1288. av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
  1289. return read_ret;
  1290. }
  1291. read_ret = http_buf_read(h, buf, size);
  1292. } else
  1293. s->reconnect_delay = 0;
  1294. return read_ret;
  1295. }
  1296. // Like http_read_stream(), but no short reads.
  1297. // Assumes partial reads are an error.
  1298. static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
  1299. {
  1300. int pos = 0;
  1301. while (pos < size) {
  1302. int len = http_read_stream(h, buf + pos, size - pos);
  1303. if (len < 0)
  1304. return len;
  1305. pos += len;
  1306. }
  1307. return pos;
  1308. }
  1309. static void update_metadata(HTTPContext *s, char *data)
  1310. {
  1311. char *key;
  1312. char *val;
  1313. char *end;
  1314. char *next = data;
  1315. while (*next) {
  1316. key = next;
  1317. val = strstr(key, "='");
  1318. if (!val)
  1319. break;
  1320. end = strstr(val, "';");
  1321. if (!end)
  1322. break;
  1323. *val = '\0';
  1324. *end = '\0';
  1325. val += 2;
  1326. av_dict_set(&s->metadata, key, val, 0);
  1327. next = end + 2;
  1328. }
  1329. }
  1330. static int store_icy(URLContext *h, int size)
  1331. {
  1332. HTTPContext *s = h->priv_data;
  1333. /* until next metadata packet */
  1334. uint64_t remaining;
  1335. if (s->icy_metaint < s->icy_data_read)
  1336. return AVERROR_INVALIDDATA;
  1337. remaining = s->icy_metaint - s->icy_data_read;
  1338. if (!remaining) {
  1339. /* The metadata packet is variable sized. It has a 1 byte header
  1340. * which sets the length of the packet (divided by 16). If it's 0,
  1341. * the metadata doesn't change. After the packet, icy_metaint bytes
  1342. * of normal data follows. */
  1343. uint8_t ch;
  1344. int len = http_read_stream_all(h, &ch, 1);
  1345. if (len < 0)
  1346. return len;
  1347. if (ch > 0) {
  1348. char data[255 * 16 + 1];
  1349. int ret;
  1350. len = ch * 16;
  1351. ret = http_read_stream_all(h, data, len);
  1352. if (ret < 0)
  1353. return ret;
  1354. data[len + 1] = 0;
  1355. if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
  1356. return ret;
  1357. update_metadata(s, data);
  1358. }
  1359. s->icy_data_read = 0;
  1360. remaining = s->icy_metaint;
  1361. }
  1362. return FFMIN(size, remaining);
  1363. }
  1364. static int http_read(URLContext *h, uint8_t *buf, int size)
  1365. {
  1366. HTTPContext *s = h->priv_data;
  1367. if (s->icy_metaint > 0) {
  1368. size = store_icy(h, size);
  1369. if (size < 0)
  1370. return size;
  1371. }
  1372. size = http_read_stream(h, buf, size);
  1373. if (size > 0)
  1374. s->icy_data_read += size;
  1375. return size;
  1376. }
  1377. /* used only when posting data */
  1378. static int http_write(URLContext *h, const uint8_t *buf, int size)
  1379. {
  1380. char temp[11] = ""; /* 32-bit hex + CRLF + nul */
  1381. int ret;
  1382. char crlf[] = "\r\n";
  1383. HTTPContext *s = h->priv_data;
  1384. if (!s->chunked_post) {
  1385. /* non-chunked data is sent without any special encoding */
  1386. return ffurl_write(s->hd, buf, size);
  1387. }
  1388. /* silently ignore zero-size data since chunk encoding that would
  1389. * signal EOF */
  1390. if (size > 0) {
  1391. /* upload data using chunked encoding */
  1392. snprintf(temp, sizeof(temp), "%x\r\n", size);
  1393. if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
  1394. (ret = ffurl_write(s->hd, buf, size)) < 0 ||
  1395. (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
  1396. return ret;
  1397. }
  1398. return size;
  1399. }
  1400. static int http_shutdown(URLContext *h, int flags)
  1401. {
  1402. int ret = 0;
  1403. char footer[] = "0\r\n\r\n";
  1404. HTTPContext *s = h->priv_data;
  1405. /* signal end of chunked encoding if used */
  1406. if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
  1407. ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
  1408. ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
  1409. ret = ret > 0 ? 0 : ret;
  1410. s->end_chunked_post = 1;
  1411. }
  1412. return ret;
  1413. }
  1414. static int http_close(URLContext *h)
  1415. {
  1416. int ret = 0;
  1417. HTTPContext *s = h->priv_data;
  1418. #if CONFIG_ZLIB
  1419. inflateEnd(&s->inflate_stream);
  1420. av_freep(&s->inflate_buffer);
  1421. #endif /* CONFIG_ZLIB */
  1422. if (!s->end_chunked_post)
  1423. /* Close the write direction by sending the end of chunked encoding. */
  1424. ret = http_shutdown(h, h->flags);
  1425. if (s->hd)
  1426. ffurl_closep(&s->hd);
  1427. av_dict_free(&s->chained_options);
  1428. return ret;
  1429. }
  1430. static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
  1431. {
  1432. HTTPContext *s = h->priv_data;
  1433. URLContext *old_hd = s->hd;
  1434. uint64_t old_off = s->off;
  1435. uint8_t old_buf[BUFFER_SIZE];
  1436. int old_buf_size, ret;
  1437. AVDictionary *options = NULL;
  1438. if (whence == AVSEEK_SIZE)
  1439. return s->filesize;
  1440. else if (!force_reconnect &&
  1441. ((whence == SEEK_CUR && off == 0) ||
  1442. (whence == SEEK_SET && off == s->off)))
  1443. return s->off;
  1444. else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
  1445. return AVERROR(ENOSYS);
  1446. if (whence == SEEK_CUR)
  1447. off += s->off;
  1448. else if (whence == SEEK_END)
  1449. off += s->filesize;
  1450. else if (whence != SEEK_SET)
  1451. return AVERROR(EINVAL);
  1452. if (off < 0)
  1453. return AVERROR(EINVAL);
  1454. s->off = off;
  1455. if (s->off && h->is_streamed)
  1456. return AVERROR(ENOSYS);
  1457. /* we save the old context in case the seek fails */
  1458. old_buf_size = s->buf_end - s->buf_ptr;
  1459. memcpy(old_buf, s->buf_ptr, old_buf_size);
  1460. s->hd = NULL;
  1461. /* if it fails, continue on old connection */
  1462. if ((ret = http_open_cnx(h, &options)) < 0) {
  1463. av_dict_free(&options);
  1464. memcpy(s->buffer, old_buf, old_buf_size);
  1465. s->buf_ptr = s->buffer;
  1466. s->buf_end = s->buffer + old_buf_size;
  1467. s->hd = old_hd;
  1468. s->off = old_off;
  1469. return ret;
  1470. }
  1471. av_dict_free(&options);
  1472. ffurl_close(old_hd);
  1473. return off;
  1474. }
  1475. static int64_t http_seek(URLContext *h, int64_t off, int whence)
  1476. {
  1477. return http_seek_internal(h, off, whence, 0);
  1478. }
  1479. static int http_get_file_handle(URLContext *h)
  1480. {
  1481. HTTPContext *s = h->priv_data;
  1482. return ffurl_get_file_handle(s->hd);
  1483. }
  1484. static int http_get_short_seek(URLContext *h)
  1485. {
  1486. HTTPContext *s = h->priv_data;
  1487. return ffurl_get_short_seek(s->hd);
  1488. }
  1489. #define HTTP_CLASS(flavor) \
  1490. static const AVClass flavor ## _context_class = { \
  1491. .class_name = # flavor, \
  1492. .item_name = av_default_item_name, \
  1493. .option = options, \
  1494. .version = LIBAVUTIL_VERSION_INT, \
  1495. }
  1496. #if CONFIG_HTTP_PROTOCOL
  1497. HTTP_CLASS(http);
  1498. const URLProtocol ff_http_protocol = {
  1499. .name = "http",
  1500. .url_open2 = http_open,
  1501. .url_accept = http_accept,
  1502. .url_handshake = http_handshake,
  1503. .url_read = http_read,
  1504. .url_write = http_write,
  1505. .url_seek = http_seek,
  1506. .url_close = http_close,
  1507. .url_get_file_handle = http_get_file_handle,
  1508. .url_get_short_seek = http_get_short_seek,
  1509. .url_shutdown = http_shutdown,
  1510. .priv_data_size = sizeof(HTTPContext),
  1511. .priv_data_class = &http_context_class,
  1512. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1513. .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
  1514. };
  1515. #endif /* CONFIG_HTTP_PROTOCOL */
  1516. #if CONFIG_HTTPS_PROTOCOL
  1517. HTTP_CLASS(https);
  1518. const URLProtocol ff_https_protocol = {
  1519. .name = "https",
  1520. .url_open2 = http_open,
  1521. .url_read = http_read,
  1522. .url_write = http_write,
  1523. .url_seek = http_seek,
  1524. .url_close = http_close,
  1525. .url_get_file_handle = http_get_file_handle,
  1526. .url_get_short_seek = http_get_short_seek,
  1527. .url_shutdown = http_shutdown,
  1528. .priv_data_size = sizeof(HTTPContext),
  1529. .priv_data_class = &https_context_class,
  1530. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1531. .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
  1532. };
  1533. #endif /* CONFIG_HTTPS_PROTOCOL */
  1534. #if CONFIG_HTTPPROXY_PROTOCOL
  1535. static int http_proxy_close(URLContext *h)
  1536. {
  1537. HTTPContext *s = h->priv_data;
  1538. if (s->hd)
  1539. ffurl_closep(&s->hd);
  1540. return 0;
  1541. }
  1542. static int http_proxy_open(URLContext *h, const char *uri, int flags)
  1543. {
  1544. HTTPContext *s = h->priv_data;
  1545. char hostname[1024], hoststr[1024];
  1546. char auth[1024], pathbuf[1024], *path;
  1547. char lower_url[100];
  1548. int port, ret = 0, attempts = 0;
  1549. HTTPAuthType cur_auth_type;
  1550. char *authstr;
  1551. int new_loc;
  1552. if( s->seekable == 1 )
  1553. h->is_streamed = 0;
  1554. else
  1555. h->is_streamed = 1;
  1556. av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
  1557. pathbuf, sizeof(pathbuf), uri);
  1558. ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
  1559. path = pathbuf;
  1560. if (*path == '/')
  1561. path++;
  1562. ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
  1563. NULL);
  1564. redo:
  1565. ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
  1566. &h->interrupt_callback, NULL,
  1567. h->protocol_whitelist, h->protocol_blacklist, h);
  1568. if (ret < 0)
  1569. return ret;
  1570. authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
  1571. path, "CONNECT");
  1572. snprintf(s->buffer, sizeof(s->buffer),
  1573. "CONNECT %s HTTP/1.1\r\n"
  1574. "Host: %s\r\n"
  1575. "Connection: close\r\n"
  1576. "%s%s"
  1577. "\r\n",
  1578. path,
  1579. hoststr,
  1580. authstr ? "Proxy-" : "", authstr ? authstr : "");
  1581. av_freep(&authstr);
  1582. if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
  1583. goto fail;
  1584. s->buf_ptr = s->buffer;
  1585. s->buf_end = s->buffer;
  1586. s->line_count = 0;
  1587. s->filesize = UINT64_MAX;
  1588. cur_auth_type = s->proxy_auth_state.auth_type;
  1589. /* Note: This uses buffering, potentially reading more than the
  1590. * HTTP header. If tunneling a protocol where the server starts
  1591. * the conversation, we might buffer part of that here, too.
  1592. * Reading that requires using the proper ffurl_read() function
  1593. * on this URLContext, not using the fd directly (as the tls
  1594. * protocol does). This shouldn't be an issue for tls though,
  1595. * since the client starts the conversation there, so there
  1596. * is no extra data that we might buffer up here.
  1597. */
  1598. ret = http_read_header(h, &new_loc);
  1599. if (ret < 0)
  1600. goto fail;
  1601. attempts++;
  1602. if (s->http_code == 407 &&
  1603. (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
  1604. s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
  1605. ffurl_closep(&s->hd);
  1606. goto redo;
  1607. }
  1608. if (s->http_code < 400)
  1609. return 0;
  1610. ret = ff_http_averror(s->http_code, AVERROR(EIO));
  1611. fail:
  1612. http_proxy_close(h);
  1613. return ret;
  1614. }
  1615. static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
  1616. {
  1617. HTTPContext *s = h->priv_data;
  1618. return ffurl_write(s->hd, buf, size);
  1619. }
  1620. const URLProtocol ff_httpproxy_protocol = {
  1621. .name = "httpproxy",
  1622. .url_open = http_proxy_open,
  1623. .url_read = http_buf_read,
  1624. .url_write = http_proxy_write,
  1625. .url_close = http_proxy_close,
  1626. .url_get_file_handle = http_get_file_handle,
  1627. .priv_data_size = sizeof(HTTPContext),
  1628. .flags = URL_PROTOCOL_FLAG_NETWORK,
  1629. };
  1630. #endif /* CONFIG_HTTPPROXY_PROTOCOL */