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.

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