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.

1928 lines
64KB

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