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.

1876 lines
62KB

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