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.

1922 lines
63KB

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