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.

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