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.

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