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.

2007 lines
66KB

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