1use url::Url;
4
5pub fn validate_url_not_private(url_str: &str) -> Result<(), &'static str> {
7 let parsed = Url::parse(url_str).map_err(|_| "Invalid URL")?;
8
9 match parsed.scheme() {
10 "http" | "https" => {}
11 _ => return Err("Only HTTP(S) URLs are allowed"),
12 }
13
14 match parsed.host() {
15 Some(url::Host::Ipv4(ip)) => {
16 let o = ip.octets();
17 if ip.is_loopback() || ip.is_private() || ip.is_link_local()
18 || ip.is_broadcast() || ip.is_unspecified()
19 || (o[0] == 100 && o[1] >= 64 && o[1] <= 127)
20 {
21 return Err("Private/internal IP addresses are not allowed");
22 }
23 }
24 Some(url::Host::Ipv6(ip)) => {
25 if ip.is_loopback() || ip.is_unspecified() || is_ipv6_private(&ip) {
26 return Err("Private/internal IP addresses are not allowed");
27 }
28 }
29 Some(url::Host::Domain(domain)) => {
30 if domain == "localhost" || domain.ends_with(".local") || domain.ends_with(".internal") {
31 return Err("Local hostnames are not allowed");
32 }
33 }
34 None => return Err("URL has no host"),
35 }
36
37 Ok(())
38}
39
40fn is_ipv6_private(ip: &std::net::Ipv6Addr) -> bool {
41 if let Some(ipv4) = ip.to_ipv4_mapped() {
42 return ipv4.is_loopback() || ipv4.is_private() || ipv4.is_link_local();
43 }
44 let segments = ip.segments();
45 if segments[0] & 0xfe00 == 0xfc00 { return true; } if segments[0] & 0xffc0 == 0xfe80 { return true; } false
48}
49
50pub use reqwest;
55
56pub use crate::transport::Lane;
57
58pub const TRANSFER_STALL: std::time::Duration = std::time::Duration::from_secs(120);
71
72pub fn transfer_stall() -> std::time::Duration {
74 crate::transport::budget(crate::transport::Op::TransferStall, TRANSFER_STALL)
75}
76
77static USER_AGENT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
84
85pub fn set_app_version(version: &str) {
88 let _ = USER_AGENT.set(format!("Vector/{version}"));
89}
90
91pub fn user_agent() -> String {
92 USER_AGENT
93 .get()
94 .cloned()
95 .unwrap_or_else(|| format!("Vector/{}", env!("CARGO_PKG_VERSION")))
96}
97
98pub fn tor_http_timeout(clearnet: std::time::Duration) -> std::time::Duration {
101 crate::transport::budget(crate::transport::Op::HttpTotal, clearnet)
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114struct ClientOptions {
115 timeout: Option<std::time::Duration>,
116 read_timeout: Option<std::time::Duration>,
117 follow_redirects: bool,
118 no_direct: bool,
121}
122
123#[derive(Clone, Debug)]
124pub struct HttpClient {
125 owner: u64,
126 lane: Lane,
127 opts: ClientOptions,
128}
129
130pub fn build_http_client(timeout: std::time::Duration) -> Result<HttpClient, String> {
136 build_http_client_for(Lane::Shared, Some(timeout), None, true)
137}
138
139pub fn build_http_client_with_options(
153 timeout: Option<std::time::Duration>,
154 read_timeout: Option<std::time::Duration>,
155 follow_redirects: bool,
156) -> Result<HttpClient, String> {
157 build_http_client_for(Lane::Shared, timeout, read_timeout, follow_redirects)
158}
159
160pub fn build_http_client_for(
162 lane: Lane,
163 timeout: Option<std::time::Duration>,
164 read_timeout: Option<std::time::Duration>,
165 follow_redirects: bool,
166) -> Result<HttpClient, String> {
167 Ok(HttpClient {
168 owner: crate::db::current_session_id(),
169 lane,
170 opts: ClientOptions { timeout, read_timeout, follow_redirects, no_direct: false },
171 })
172}
173
174const DEFAULT_SHARED_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
175
176pub fn shared_http_client() -> std::sync::Arc<HttpClient> {
178 std::sync::Arc::new(HttpClient {
179 owner: crate::db::current_session_id(),
180 lane: Lane::Shared,
181 opts: ClientOptions { timeout: Some(DEFAULT_SHARED_TIMEOUT), read_timeout: None, follow_redirects: true, no_direct: false },
182 })
183}
184
185#[derive(Clone, Copy, PartialEq, Eq, Hash)]
187struct PoolKey {
188 epoch: u64,
189 owner: u64,
190 lane: Lane,
191 opts: ClientOptions,
192 direct: bool,
193}
194
195type Pools = std::collections::HashMap<PoolKey, reqwest::Client>;
196
197static POOLS: std::sync::Mutex<Option<Pools>> = std::sync::Mutex::new(None);
198
199pub fn forget_clients() {
201 if let Ok(mut g) = POOLS.lock() {
202 *g = None;
203 }
204}
205
206pub fn rebuild_shared_http_client() -> Result<(), String> {
208 forget_clients();
209 Ok(())
210}
211
212fn template() -> &'static reqwest::Client {
214 static T: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
215 T.get_or_init(|| client_builder().build().expect("a plain reqwest client always builds"))
216}
217
218#[cfg(not(target_arch = "wasm32"))]
223fn tls_config() -> rustls::ClientConfig {
224 let roots = rustls::RootCertStore { roots: webpki_roots::TLS_SERVER_ROOTS.to_vec() };
225 let mut cfg = rustls::ClientConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::ring::default_provider()))
226 .with_safe_default_protocol_versions()
227 .expect("ring supports TLS 1.2 and 1.3")
228 .with_root_certificates(roots)
229 .with_no_client_auth();
230 cfg.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
231 cfg
232}
233
234#[allow(clippy::disallowed_methods)]
235fn client_builder() -> reqwest::ClientBuilder {
236 #[cfg(not(target_arch = "wasm32"))]
237 return reqwest::Client::builder().tls_backend_preconfigured(tls_config());
238 #[cfg(target_arch = "wasm32")]
239 return reqwest::Client::builder();
240}
241
242impl HttpClient {
243 pub fn request<U: reqwest::IntoUrl>(&self, method: reqwest::Method, url: U) -> Req {
244 Req { rb: template().request(method, url), client: self.clone() }
245 }
246
247 pub fn get<U: reqwest::IntoUrl>(&self, url: U) -> Req {
248 self.request(reqwest::Method::GET, url)
249 }
250
251 pub fn post<U: reqwest::IntoUrl>(&self, url: U) -> Req {
252 self.request(reqwest::Method::POST, url)
253 }
254
255 pub fn put<U: reqwest::IntoUrl>(&self, url: U) -> Req {
256 self.request(reqwest::Method::PUT, url)
257 }
258
259 pub fn head<U: reqwest::IntoUrl>(&self, url: U) -> Req {
260 self.request(reqwest::Method::HEAD, url)
261 }
262
263 pub fn delete<U: reqwest::IntoUrl>(&self, url: U) -> Req {
264 self.request(reqwest::Method::DELETE, url)
265 }
266
267 pub fn lane(&self) -> Lane {
268 self.lane
269 }
270
271 pub fn owner(&self) -> u64 {
273 self.owner
274 }
275
276 pub fn with_lane(&self, lane: Lane) -> HttpClient {
279 HttpClient { lane, ..self.clone() }
280 }
281
282 pub fn without_direct(&self) -> HttpClient {
285 HttpClient { opts: ClientOptions { no_direct: true, ..self.opts }, ..self.clone() }
286 }
287}
288
289#[cfg(not(target_arch = "wasm32"))]
290fn build_pooled(opts: ClientOptions, proxy: Option<String>) -> Result<reqwest::Client, String> {
291 use crate::transport::{budget, Op};
292 let mut builder = client_builder()
293 .pool_max_idle_per_host(8)
297 .pool_idle_timeout(std::time::Duration::from_secs(90))
298 .tcp_keepalive(std::time::Duration::from_secs(30))
299 .http2_keep_alive_interval(std::time::Duration::from_secs(30))
300 .http2_keep_alive_while_idle(true)
301 .user_agent(user_agent())
303 .connect_timeout(budget(Op::HttpConnect, std::time::Duration::from_secs(15)));
306 if let Some(t) = opts.timeout {
307 builder = builder.timeout(budget(Op::HttpTotal, t));
308 }
309 if let Some(rt) = opts.read_timeout {
310 builder = builder.read_timeout(budget(Op::HttpRead, rt));
311 }
312 if !opts.follow_redirects {
313 builder = builder.redirect(reqwest::redirect::Policy::none());
314 } else {
315 builder = builder.redirect(reqwest::redirect::Policy::custom(|attempt| {
319 if attempt.previous().len() >= 10 {
320 return attempt.error("too many redirects");
321 }
322 if let Some(dest) = attempt.url().host_str().and_then(crate::transport::Dest::parse) {
323 let kind = crate::transport::preference().unwrap_or(crate::transport::Kind::Clearnet);
324 if let Some(r) = crate::transport::route::pre_route(kind, &dest) {
325 return attempt.error(r.text());
326 }
327 }
328 match validate_url_not_private(attempt.url().as_str()) {
329 Ok(()) => attempt.follow(),
330 Err(e) => attempt.error(e),
331 }
332 }));
333 }
334 if let Some(url) = proxy {
335 let proxy = reqwest::Proxy::all(url).map_err(|_| "Vector couldn't open its local proxy.".to_string())?;
336 builder = builder.proxy(proxy);
337 }
338 builder.build().map_err(|e| format!("Failed to build HTTP client: {}", e))
339}
340
341#[cfg(target_arch = "wasm32")]
342fn build_pooled(_opts: ClientOptions, _proxy: Option<String>) -> Result<reqwest::Client, String> {
343 client_builder().build().map_err(|e| format!("HTTP client build failed: {e}"))
344}
345
346fn pooled(desc: &HttpClient, epoch: u64, egress: &crate::transport::Egress) -> Result<reqwest::Client, HttpError> {
348 let key = PoolKey {
349 epoch,
350 owner: desc.owner,
351 lane: desc.lane,
352 opts: desc.opts,
353 direct: matches!(egress, crate::transport::Egress::Direct),
354 };
355 if let Some(c) = POOLS.lock().ok().and_then(|g| g.as_ref().and_then(|m| m.get(&key).cloned())) {
356 return Ok(c);
357 }
358 let proxy = match egress {
359 #[cfg(not(target_arch = "wasm32"))]
360 crate::transport::Egress::Proxy(t) => Some(crate::transport::bridge::proxy_url(t).map_err(HttpError::Refused)?),
361 _ => None,
362 };
363 let client = build_pooled(desc.opts, proxy).map_err(|e| HttpError::Refused(crate::transport::ConnectError::Bridge(e)))?;
364 if crate::transport::epoch() == epoch {
365 if let Ok(mut g) = POOLS.lock() {
366 g.get_or_insert_with(Default::default).entry(key).or_insert_with(|| client.clone());
367 }
368 }
369 Ok(client)
370}
371
372#[cfg(target_arch = "wasm32")]
376static HOST_ALIASES: std::sync::OnceLock<Vec<(String, reqwest::Url)>> = std::sync::OnceLock::new();
377
378#[cfg(target_arch = "wasm32")]
379pub fn set_host_aliases(aliases: &[(&str, &str)]) {
380 let parsed = aliases.iter().filter_map(|(host, base)| Some((host.to_string(), reqwest::Url::parse(base).ok()?))).collect();
381 let _ = HOST_ALIASES.set(parsed);
382}
383
384#[cfg(target_arch = "wasm32")]
385fn apply_host_alias(url: &mut reqwest::Url) {
386 if let Some(next) = HOST_ALIASES.get().and_then(|aliases| aliased(url, aliases)) {
387 *url = next;
388 }
389}
390
391#[cfg(any(target_arch = "wasm32", test))]
393fn aliased(url: &reqwest::Url, aliases: &[(String, reqwest::Url)]) -> Option<reqwest::Url> {
394 let host = url.host_str()?;
395 let (_, base) = aliases
396 .iter()
397 .find(|(alias, _)| host == alias || host.strip_suffix(alias.as_str()).is_some_and(|sub| sub.ends_with('.')))?;
398 let mut next = base.clone();
399 next.set_path(url.path());
400 next.set_query(url.query());
401 Some(next)
402}
403
404pub struct Req {
406 rb: reqwest::RequestBuilder,
407 client: HttpClient,
408}
409
410impl Req {
411 pub fn header<K, V>(mut self, key: K, value: V) -> Self
412 where
413 reqwest::header::HeaderName: TryFrom<K>,
414 <reqwest::header::HeaderName as TryFrom<K>>::Error: Into<http::Error>,
415 reqwest::header::HeaderValue: TryFrom<V>,
416 <reqwest::header::HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
417 {
418 self.rb = self.rb.header(key, value);
419 self
420 }
421
422 pub fn headers(mut self, headers: reqwest::header::HeaderMap) -> Self {
423 self.rb = self.rb.headers(headers);
424 self
425 }
426
427 pub fn body<T: Into<reqwest::Body>>(mut self, body: T) -> Self {
428 self.rb = self.rb.body(body);
429 self
430 }
431
432 pub fn json<T: serde::Serialize + ?Sized>(mut self, json: &T) -> Self {
433 self.rb = self.rb.json(json);
434 self
435 }
436
437 pub fn bearer_auth<T: std::fmt::Display>(mut self, token: T) -> Self {
438 self.rb = self.rb.bearer_auth(token);
439 self
440 }
441
442 pub fn basic_auth<U: std::fmt::Display, P: std::fmt::Display>(mut self, user: U, password: Option<P>) -> Self {
443 self.rb = self.rb.basic_auth(user, password);
444 self
445 }
446
447 pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
448 self.rb = self.rb.timeout(timeout);
449 self
450 }
451
452 #[cfg(target_arch = "wasm32")]
454 pub fn fetch_cache_no_store(mut self) -> Self {
455 self.rb = self.rb.fetch_cache_no_store();
456 self
457 }
458
459 #[allow(clippy::disallowed_methods)]
462 pub async fn send(self) -> Result<Resp, HttpError> {
463 let (_, req) = self.rb.build_split();
464 #[allow(unused_mut)]
465 let mut req = req.map_err(HttpError::from_reqwest)?;
466 let host = req.url().host_str().unwrap_or_default().to_string();
467 let port = req.url().port_or_known_default().unwrap_or(443);
468 let desc = self.client;
469 let (mut epoch, mut client) = (0, None);
470 for _ in 0..3 {
473 epoch = crate::transport::epoch();
474 let egress = crate::transport::egress(desc.owner, desc.lane, &host, port);
475 if let crate::transport::Egress::Refuse(e) = egress {
476 return Err(HttpError::Refused(e));
477 }
478 if desc.opts.no_direct && egress == crate::transport::Egress::Direct {
479 return Err(HttpError::Refused(crate::transport::ConnectError::Stale));
480 }
481 client = Some(pooled(&desc, epoch, &egress)?);
482 if crate::transport::epoch() == epoch {
483 break;
484 }
485 }
486 let client = client.expect("the loop ran");
487 #[cfg(target_arch = "wasm32")]
490 apply_host_alias(req.url_mut());
491 let changed = crate::transport::changed(epoch);
494 let run = client.execute(req);
495 futures_util::pin_mut!(changed, run);
496 match futures_util::future::select(changed, run).await {
497 futures_util::future::Either::Left(_) => Err(HttpError::NetworkChanged),
498 futures_util::future::Either::Right((Ok(inner), _)) => Ok(Resp { inner, epoch, owner: desc.owner }),
499 futures_util::future::Either::Right((Err(e), _)) => Err(HttpError::from_reqwest_for(e, &host)),
500 }
501 }
502}
503
504#[cfg(not(target_arch = "wasm32"))]
506pub type BodyStream = std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<bytes::Bytes, HttpError>> + Send>>;
507#[cfg(target_arch = "wasm32")]
508pub type BodyStream = std::pin::Pin<Box<dyn futures_util::Stream<Item = Result<bytes::Bytes, HttpError>>>>;
509
510pub struct Resp {
512 inner: reqwest::Response,
513 epoch: u64,
514 owner: u64,
515}
516
517impl Resp {
518 pub fn status(&self) -> reqwest::StatusCode {
519 self.inner.status()
520 }
521
522 pub fn headers(&self) -> &reqwest::header::HeaderMap {
523 self.inner.headers()
524 }
525
526 pub fn content_length(&self) -> Option<u64> {
527 self.inner.content_length()
528 }
529
530 pub fn url(&self) -> &reqwest::Url {
531 self.inner.url()
532 }
533
534 pub fn error_for_status(self) -> Result<Resp, HttpError> {
535 let (epoch, owner) = (self.epoch, self.owner);
536 self.inner.error_for_status().map(|inner| Resp { inner, epoch, owner }).map_err(HttpError::from_reqwest)
537 }
538
539 fn still_current(&self) -> bool {
540 crate::transport::epoch() == self.epoch && crate::db::live_session_id() == self.owner
541 }
542
543 #[cfg(not(target_arch = "wasm32"))]
544 #[allow(clippy::disallowed_methods)]
545 pub async fn chunk(&mut self) -> Result<Option<bytes::Bytes>, HttpError> {
546 if !self.still_current() {
547 return Err(HttpError::NetworkChanged);
548 }
549 let changed = crate::transport::changed(self.epoch);
550 let read = self.inner.chunk();
551 futures_util::pin_mut!(read, changed);
552 match futures_util::future::select(read, changed).await {
553 futures_util::future::Either::Left((r, _)) => r.map_err(HttpError::from_reqwest),
554 futures_util::future::Either::Right(_) => Err(HttpError::NetworkChanged),
555 }
556 }
557
558 #[allow(clippy::disallowed_methods)]
559 pub fn bytes_stream(self) -> BodyStream {
560 use futures_util::StreamExt;
561 let (epoch, owner) = (self.epoch, self.owner);
562 let inner = Box::pin(self.inner.bytes_stream());
563 Box::pin(futures_util::stream::unfold((inner, false), move |(mut inner, done)| async move {
564 if done {
565 return None;
566 }
567 if crate::transport::epoch() != epoch || crate::db::live_session_id() != owner {
568 return Some((Err(HttpError::NetworkChanged), (inner, true)));
569 }
570 let changed = crate::transport::changed(epoch);
571 futures_util::pin_mut!(changed);
572 match futures_util::future::select(inner.next(), changed).await {
573 futures_util::future::Either::Left((Some(item), _)) => Some((item.map_err(HttpError::from_reqwest), (inner, false))),
574 futures_util::future::Either::Left((None, _)) => None,
575 futures_util::future::Either::Right(_) => Some((Err(HttpError::NetworkChanged), (inner, true))),
576 }
577 }))
578 }
579
580 async fn whole<T, F: std::future::Future<Output = Result<T, reqwest::Error>>>(epoch: u64, read: F) -> Result<T, HttpError> {
581 let changed = crate::transport::changed(epoch);
582 futures_util::pin_mut!(read, changed);
583 match futures_util::future::select(read, changed).await {
584 futures_util::future::Either::Left((r, _)) => r.map_err(HttpError::from_reqwest),
585 futures_util::future::Either::Right(_) => Err(HttpError::NetworkChanged),
586 }
587 }
588
589 pub async fn bytes(self) -> Result<bytes::Bytes, HttpError> {
590 if !self.still_current() {
591 return Err(HttpError::NetworkChanged);
592 }
593 Self::whole(self.epoch, self.inner.bytes()).await
594 }
595
596 pub async fn text(self) -> Result<String, HttpError> {
597 if !self.still_current() {
598 return Err(HttpError::NetworkChanged);
599 }
600 Self::whole(self.epoch, self.inner.text()).await
601 }
602
603 pub async fn json<T: serde::de::DeserializeOwned>(self) -> Result<T, HttpError> {
604 if !self.still_current() {
605 return Err(HttpError::NetworkChanged);
606 }
607 Self::whole(self.epoch, self.inner.json::<T>()).await
608 }
609}
610
611#[derive(Debug)]
612pub enum HttpError {
613 Refused(crate::transport::ConnectError),
615 NetworkChanged,
617 Http { err: reqwest::Error, text: String },
618}
619
620impl HttpError {
621 fn from_reqwest(err: reqwest::Error) -> Self {
622 HttpError::Http { text: err.to_string(), err }
623 }
624
625 fn from_reqwest_for(err: reqwest::Error, host: &str) -> Self {
627 let recorded = crate::transport::host::active().and_then(|a| {
628 let (at, e) = a.last_failure(host)?;
629 let fresh = at.elapsed() < std::time::Duration::from_secs(30);
630 let keep_reqwest = a.kind == crate::transport::Kind::Tor && matches!(e, crate::transport::ConnectError::Unreachable(_));
632 (fresh && !keep_reqwest).then(|| e.text())
633 });
634 HttpError::Http { text: recorded.unwrap_or_else(|| err.to_string()), err }
635 }
636
637 pub fn is_timeout(&self) -> bool {
638 matches!(self, HttpError::Http { err, .. } if err.is_timeout())
639 }
640
641 pub fn is_connect(&self) -> bool {
642 #[cfg(not(target_arch = "wasm32"))]
643 {
644 matches!(self, HttpError::Http { err, .. } if err.is_connect())
645 }
646 #[cfg(target_arch = "wasm32")]
647 {
648 false
649 }
650 }
651
652 pub fn is_request(&self) -> bool {
653 matches!(self, HttpError::Http { err, .. } if err.is_request())
654 }
655
656 pub fn status(&self) -> Option<reqwest::StatusCode> {
657 match self {
658 HttpError::Http { err, .. } => err.status(),
659 _ => None,
660 }
661 }
662
663 pub fn is_transient(&self) -> bool {
666 match self {
667 HttpError::NetworkChanged => true,
668 HttpError::Refused(e) => e.is_transient(),
669 HttpError::Http { .. } => false,
670 }
671 }
672
673 pub fn is_policy_refusal(&self) -> bool {
675 matches!(self, HttpError::Refused(crate::transport::ConnectError::Refused(_)))
676 }
677}
678
679impl std::fmt::Display for HttpError {
680 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
681 match self {
682 HttpError::Refused(e) => f.write_str(&e.text()),
683 HttpError::NetworkChanged => f.write_str("The network changed."),
684 HttpError::Http { text, .. } => f.write_str(text),
685 }
686 }
687}
688
689impl std::error::Error for HttpError {
690 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
691 match self {
692 HttpError::Http { err, .. } => Some(err),
693 _ => None,
694 }
695 }
696}
697
698pub fn guard_body<S, E>(
700 body: S,
701 epoch: u64,
702 owner: u64,
703) -> impl futures_util::Stream<Item = Result<bytes::Bytes, std::io::Error>> + Send + 'static
704where
705 S: futures_util::Stream<Item = Result<bytes::Bytes, E>> + Send + 'static,
706 E: std::fmt::Display + Send + 'static,
707{
708 crate::transport::guard::guard_body(body, epoch, owner)
709}
710
711pub async fn wait_after(e: &HttpError) -> Result<(), String> {
714 if !e.is_transient() {
715 return Err(e.to_string());
716 }
717 crate::transport::wait_ready(crate::transport::budget(crate::transport::Op::Startup, std::time::Duration::ZERO)).await
718}
719
720fn md_group_close(bytes: &[u8], start: usize, open: u8, close: u8) -> Option<usize> {
726 let mut depth = 1usize;
727 let mut escaped = false;
728 let mut j = start;
729 loop {
730 match bytes.get(j).copied() {
731 None => return None,
732 Some(b'\\') if !escaped => escaped = true,
733 Some(b) if b == open && !escaped => depth += 1,
734 Some(b) if b == close && !escaped => {
735 depth -= 1;
736 if depth == 0 {
737 return Some(j);
738 }
739 }
740 _ => escaped = false,
741 }
742 j += 1;
743 }
744}
745
746pub fn strip_md_link_claims(text: &str) -> String {
754 let bytes = text.as_bytes();
755 let mut out = String::with_capacity(text.len());
756 let mut last = 0;
757 let mut i = 0;
758 while i < bytes.len() {
759 if bytes[i] != b'[' || (i > 0 && bytes[i - 1] == b'!') {
760 i += 1;
761 continue;
762 }
763 let Some(close) = md_group_close(bytes, i + 1, b'[', b']') else { break };
764 match bytes.get(close + 1).copied() {
765 Some(b'(') => {
767 let Some(paren) = md_group_close(bytes, close + 2, b'(', b')') else {
768 i = close + 1;
769 continue;
770 };
771 out.push_str(&text[last..i]);
772 let href = text[close + 2..paren].trim();
773 if !(href.starts_with('<') && href.ends_with('>')) {
774 out.push(' ');
775 out.push_str(href);
776 out.push(' ');
777 }
778 i = paren + 1;
779 last = i;
780 }
781 Some(b'[') => {
784 let Some(ref_close) = md_group_close(bytes, close + 2, b'[', b']') else {
785 i = close + 1;
786 continue;
787 };
788 out.push_str(&text[last..i]);
789 i = ref_close + 1;
790 last = i;
791 }
792 _ => {
793 i = close + 1;
794 }
795 }
796 }
797 out.push_str(&text[last..]);
798 out
799}
800
801#[cfg(test)]
802mod tests {
803 use super::*;
804
805 #[test]
810 fn md_link_claim_text_dropped_href_kept() {
811 let out = strip_md_link_claims("[https://your-bank.com](https://evil.io)");
813 assert!(!out.contains("your-bank.com"), "claimed text must not reach the scan: {out}");
814 assert!(out.contains("https://evil.io"), "real destination must reach the scan: {out}");
815 }
816
817 #[test]
818 fn md_no_preview_link_dropped_entirely() {
819 let out = strip_md_link_claims("see [docs](<https://vector.app/docs>) ok");
820 assert!(!out.contains("vector.app"), "no-preview href must not reach the scan: {out}");
821 assert!(out.contains("see ") && out.contains(" ok"));
822 }
823
824 #[test]
825 fn md_image_passes_through() {
826 let text = "";
827 assert_eq!(strip_md_link_claims(text), text);
828 }
829
830 #[test]
831 fn plain_text_and_bare_urls_untouched() {
832 let text = "check https://vector.app and [also] (spaced) brackets";
833 assert_eq!(strip_md_link_claims(text), text);
834 }
835
836 #[test]
837 fn multiple_links_keep_document_order() {
838 let out = strip_md_link_claims("[a](https://one.io) mid [b](https://two.io)");
839 let one = out.find("https://one.io").expect("first href kept");
840 let two = out.find("https://two.io").expect("second href kept");
841 assert!(one < two);
842 }
843
844 #[test]
845 fn nested_bracket_label_still_drops_claim() {
846 let out = strip_md_link_claims("[[https://trusted.com]](https://evil.io)");
847 assert!(!out.contains("trusted.com"), "nested-bracket claim must not reach the scan: {out}");
848 assert!(out.contains("https://evil.io"));
849 }
850
851 #[test]
852 fn escaped_bracket_label_still_drops_claim() {
853 let out = strip_md_link_claims(r"[https://trusted.com\]](https://evil.io)");
854 assert!(!out.contains("trusted.com"), "escaped-bracket claim must not reach the scan: {out}");
855 assert!(out.contains("https://evil.io"));
856 }
857
858 #[test]
859 fn paren_path_href_survives_whole() {
860 let out = strip_md_link_claims("[wiki](https://en.wikipedia.org/wiki/Foo_(bar))");
861 assert!(out.contains("https://en.wikipedia.org/wiki/Foo_(bar)"), "balanced-paren href kept intact: {out}");
862 }
863
864 #[test]
865 fn reference_link_label_dropped_definition_scanned() {
866 let out = strip_md_link_claims("[https://trusted.com][1]\n[1]: https://evil.io");
867 assert!(!out.contains("trusted.com"), "reflink claim must not reach the scan: {out}");
868 assert!(out.contains("https://evil.io"), "definition URL stays scannable: {out}");
869 }
870
871 #[test]
872 fn multibyte_label_no_panic() {
873 let out = strip_md_link_claims("[🔒 sécurisé — café](https://evil.io) 日本語");
874 assert!(out.contains("https://evil.io"));
875 assert!(out.contains("日本語"));
876 }
877
878 #[test]
883 fn valid_public_https_url_passes() {
884 assert!(validate_url_not_private("https://example.com/path").is_ok(),
885 "https://example.com should be allowed");
886 }
887
888 #[test]
889 fn valid_public_http_url_passes() {
890 assert!(validate_url_not_private("http://example.com").is_ok(),
891 "http://example.com should be allowed");
892 }
893
894 #[test]
895 fn valid_public_ip_8888_passes() {
896 assert!(validate_url_not_private("https://8.8.8.8/dns").is_ok(),
897 "8.8.8.8 (Google DNS) is a public IP and should be allowed");
898 }
899
900 #[test]
901 fn valid_public_ip_1111_passes() {
902 assert!(validate_url_not_private("https://1.1.1.1").is_ok(),
903 "1.1.1.1 (Cloudflare DNS) is a public IP and should be allowed");
904 }
905
906 #[test]
907 fn valid_url_with_port_passes() {
908 assert!(validate_url_not_private("https://example.com:8080/api").is_ok(),
909 "URL with port on public domain should be allowed");
910 }
911
912 #[test]
917 fn localhost_rejected() {
918 let result = validate_url_not_private("http://localhost/secret");
919 assert!(result.is_err(), "localhost should be rejected");
920 }
921
922 #[test]
923 fn ip_127_0_0_1_rejected() {
924 let result = validate_url_not_private("http://127.0.0.1/admin");
925 assert!(result.is_err(), "127.0.0.1 (loopback) should be rejected");
926 }
927
928 #[test]
929 fn ip_127_255_255_255_rejected() {
930 let result = validate_url_not_private("http://127.255.255.255");
931 assert!(result.is_err(), "127.255.255.255 (loopback range) should be rejected");
932 }
933
934 #[test]
939 fn private_class_a_10_rejected() {
940 let result = validate_url_not_private("http://10.0.0.1/internal");
941 assert!(result.is_err(), "10.0.0.1 (private class A) should be rejected");
942 }
943
944 #[test]
945 fn private_class_b_172_16_rejected() {
946 let result = validate_url_not_private("http://172.16.0.1/internal");
947 assert!(result.is_err(), "172.16.0.1 (private class B) should be rejected");
948 }
949
950 #[test]
951 fn private_class_b_172_31_rejected() {
952 let result = validate_url_not_private("http://172.31.255.255");
953 assert!(result.is_err(), "172.31.255.255 (private class B upper bound) should be rejected");
954 }
955
956 #[test]
957 fn private_class_c_192_168_rejected() {
958 let result = validate_url_not_private("http://192.168.1.1/router");
959 assert!(result.is_err(), "192.168.1.1 (private class C) should be rejected");
960 }
961
962 #[test]
967 fn link_local_169_254_rejected() {
968 let result = validate_url_not_private("http://169.254.1.1");
969 assert!(result.is_err(), "169.254.1.1 (link-local) should be rejected");
970 }
971
972 #[test]
973 fn cgn_100_64_rejected() {
974 let result = validate_url_not_private("http://100.64.0.1");
975 assert!(result.is_err(), "100.64.0.1 (CGN / shared address space) should be rejected");
976 }
977
978 #[test]
979 fn cgn_100_127_rejected() {
980 let result = validate_url_not_private("http://100.127.255.255");
981 assert!(result.is_err(), "100.127.255.255 (CGN upper bound) should be rejected");
982 }
983
984 #[test]
985 fn broadcast_255_rejected() {
986 let result = validate_url_not_private("http://255.255.255.255");
987 assert!(result.is_err(), "255.255.255.255 (broadcast) should be rejected");
988 }
989
990 #[test]
991 fn unspecified_0_0_0_0_rejected() {
992 let result = validate_url_not_private("http://0.0.0.0");
993 assert!(result.is_err(), "0.0.0.0 (unspecified) should be rejected");
994 }
995
996 #[test]
1001 fn ipv6_loopback_rejected() {
1002 let result = validate_url_not_private("http://[::1]/secret");
1003 assert!(result.is_err(), "::1 (IPv6 loopback) should be rejected");
1004 }
1005
1006 #[test]
1007 fn ipv6_unique_local_fc00_rejected() {
1008 let result = validate_url_not_private("http://[fc00::1]");
1009 assert!(result.is_err(), "fc00::1 (IPv6 unique-local) should be rejected");
1010 }
1011
1012 #[test]
1013 fn ipv6_unique_local_fd00_rejected() {
1014 let result = validate_url_not_private("http://[fd00::1]");
1015 assert!(result.is_err(), "fd00::1 (IPv6 unique-local) should be rejected");
1016 }
1017
1018 #[test]
1019 fn ipv6_link_local_fe80_rejected() {
1020 let result = validate_url_not_private("http://[fe80::1]");
1021 assert!(result.is_err(), "fe80::1 (IPv6 link-local) should be rejected");
1022 }
1023
1024 #[test]
1025 fn ipv4_mapped_ipv6_loopback_rejected() {
1026 let result = validate_url_not_private("http://[::ffff:127.0.0.1]");
1027 assert!(result.is_err(), "::ffff:127.0.0.1 (IPv4-mapped loopback) should be rejected");
1028 }
1029
1030 #[test]
1031 fn ipv4_mapped_ipv6_private_rejected() {
1032 let result = validate_url_not_private("http://[::ffff:192.168.1.1]");
1033 assert!(result.is_err(), "::ffff:192.168.1.1 (IPv4-mapped private) should be rejected");
1034 }
1035
1036 #[test]
1041 fn dot_local_domain_rejected() {
1042 let result = validate_url_not_private("http://mydevice.local/api");
1043 assert!(result.is_err(), ".local domain should be rejected");
1044 }
1045
1046 #[test]
1047 fn dot_internal_domain_rejected() {
1048 let result = validate_url_not_private("http://service.internal/health");
1049 assert!(result.is_err(), ".internal domain should be rejected");
1050 }
1051
1052 #[test]
1057 fn ftp_scheme_rejected() {
1058 let result = validate_url_not_private("ftp://example.com/file.txt");
1059 assert!(result.is_err(), "ftp:// scheme should be rejected");
1060 assert_eq!(result.unwrap_err(), "Only HTTP(S) URLs are allowed");
1061 }
1062
1063 #[test]
1064 fn file_scheme_rejected() {
1065 let result = validate_url_not_private("file:///etc/passwd");
1066 assert!(result.is_err(), "file:// scheme should be rejected");
1067 assert_eq!(result.unwrap_err(), "Only HTTP(S) URLs are allowed");
1068 }
1069
1070 #[test]
1071 fn javascript_scheme_rejected() {
1072 let result = validate_url_not_private("javascript:alert(1)");
1073 assert!(result.is_err(), "javascript: scheme should be rejected");
1074 }
1075
1076 #[test]
1077 fn data_scheme_rejected() {
1078 let result = validate_url_not_private("data:text/html,<h1>hi</h1>");
1079 assert!(result.is_err(), "data: scheme should be rejected");
1080 }
1081
1082 #[test]
1087 fn no_host_rejected() {
1088 let result = validate_url_not_private("http://");
1090 assert!(result.is_err(), "URL with no host should be rejected");
1091 }
1092
1093 #[test]
1094 fn invalid_url_rejected() {
1095 let result = validate_url_not_private("not a url at all");
1096 assert!(result.is_err(), "invalid URL string should be rejected");
1097 assert_eq!(result.unwrap_err(), "Invalid URL");
1098 }
1099
1100 #[test]
1101 fn empty_string_rejected() {
1102 let result = validate_url_not_private("");
1103 assert!(result.is_err(), "empty string should be rejected");
1104 }
1105
1106 #[test]
1111 fn cgn_100_63_not_rejected() {
1112 assert!(validate_url_not_private("http://100.63.255.255").is_ok(),
1114 "100.63.255.255 is outside CGN range and should be allowed");
1115 }
1116
1117 #[test]
1118 fn cgn_100_128_not_rejected() {
1119 assert!(validate_url_not_private("http://100.128.0.1").is_ok(),
1121 "100.128.0.1 is outside CGN range and should be allowed");
1122 }
1123
1124 #[test]
1125 fn private_172_15_not_rejected() {
1126 assert!(validate_url_not_private("http://172.15.255.255").is_ok(),
1128 "172.15.255.255 is outside private class B range and should be allowed");
1129 }
1130
1131 #[test]
1132 fn private_172_32_not_rejected() {
1133 assert!(validate_url_not_private("http://172.32.0.1").is_ok(),
1135 "172.32.0.1 is outside private class B range and should be allowed");
1136 }
1137}
1138
1139pub struct Egress {
1147 pub url: String,
1148 pub auth: Option<reqwest::header::HeaderValue>,
1149}
1150
1151impl Egress {
1152 pub fn proxied(&self) -> bool {
1154 self.auth.is_some() || crate::proxy::proxy_server_of(&self.url).is_some()
1155 }
1156}
1157
1158pub async fn egress(url: &str) -> Egress {
1161 match crate::proxy::proxied(url).await {
1162 Some(via) => {
1163 let auth = match crate::proxy::proxy_server_of(&via) {
1164 Some(server) => crate::proxy::proxy_authorization(&server).await,
1165 None => None,
1166 };
1167 Egress { url: via, auth }
1168 }
1169 None => Egress { url: url.to_string(), auth: None },
1170 }
1171}
1172
1173pub async fn proxied_request(client: &HttpClient, method: reqwest::Method, url: &str) -> Req {
1176 let e = egress(url).await;
1177 match e.auth {
1178 Some(v) => client.with_lane(Lane::Account).request(method, &e.url).header(reqwest::header::AUTHORIZATION, v),
1179 None => client.request(method, &e.url),
1180 }
1181}
1182
1183pub async fn remote_status(url: &str, timeout: std::time::Duration) -> Option<u16> {
1190 let e = egress(url).await;
1191 let client = build_http_client(timeout).ok()?;
1192 let client = if e.auth.is_some() { client.with_lane(Lane::Account) } else { client };
1193 let with = |req: Req| match &e.auth {
1194 Some(v) => req.header(reqwest::header::AUTHORIZATION, v.clone()),
1195 None => req,
1196 };
1197 if e.proxied() {
1198 let resp = with(client.get(&e.url)).header(reqwest::header::RANGE, "bytes=0-0").send().await.ok()?;
1199 if resp.status().is_success() {
1200 return Some(200);
1201 }
1202 let body: serde_json::Value = resp.json().await.ok()?;
1203 return body.get("source_status").and_then(|v| v.as_u64()).map(|v| v as u16);
1204 }
1205 let head = with(client.head(&e.url)).send().await.ok()?;
1206 let status = head.status();
1207 if status == reqwest::StatusCode::METHOD_NOT_ALLOWED || status == reqwest::StatusCode::NOT_IMPLEMENTED {
1208 let r = with(client.get(&e.url)).header(reqwest::header::RANGE, "bytes=0-0").send().await.ok()?;
1209 return Some(r.status().as_u16());
1210 }
1211 Some(status.as_u16())
1212}
1213
1214pub async fn get_remote_file_size(url: &str) -> Option<u64> {
1221 validate_url_not_private(url).ok()?;
1222 let client = build_http_client(std::time::Duration::from_secs(8)).ok()?;
1223
1224 if let Ok(head_res) = proxied_request(&client, reqwest::Method::HEAD, url).await.send().await {
1226 if let Some(length) = head_res.content_length() {
1227 if length > 0 {
1228 return Some(length);
1229 }
1230 }
1231 }
1232
1233 if let Ok(partial_res) = proxied_request(&client, reqwest::Method::GET, url)
1235 .await
1236 .header("Range", "bytes=0-1")
1237 .send()
1238 .await
1239 {
1240 if let Some(content_range) = partial_res.headers().get("content-range") {
1241 if let Ok(range_str) = content_range.to_str() {
1242 if let Some(size_part) = range_str.split('/').nth(1) {
1243 if let Ok(size) = size_part.parse::<u64>() {
1244 return Some(size);
1245 }
1246 }
1247 }
1248 }
1249 if let Some(length) = partial_res.content_length() {
1250 if length > 100 {
1251 return Some(length);
1252 }
1253 }
1254 }
1255
1256 None
1257}
1258
1259#[allow(clippy::unnecessary_cast)] pub fn raise_fd_limit() -> Option<u64> {
1268 #[cfg(not(unix))]
1269 {
1270 None
1271 }
1272 #[cfg(unix)]
1273 {
1274 #[cfg(target_os = "macos")]
1277 const CEILING: libc::rlim_t = 10240;
1278 #[cfg(not(target_os = "macos"))]
1279 const CEILING: libc::rlim_t = 1 << 20;
1280
1281 let mut lim = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
1282 if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut lim) } != 0 {
1284 return None;
1285 }
1286 let target = lim.rlim_max.min(CEILING);
1287 if target <= lim.rlim_cur {
1288 return None;
1289 }
1290 lim.rlim_cur = target;
1291 if unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &lim) } != 0 {
1292 return None;
1293 }
1294 Some(target as u64)
1295 }
1296}
1297
1298#[cfg(all(test, unix))]
1299mod fd_limit_tests {
1300 #[test]
1301 fn soft_limit_reaches_the_ceiling_and_is_never_lowered() {
1302 let mut before = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
1303 assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) }, 0);
1304
1305 super::raise_fd_limit();
1306
1307 let mut after = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
1308 assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut after) }, 0);
1309 #[cfg(target_os = "macos")]
1310 let ceiling: libc::rlim_t = 10240;
1311 #[cfg(not(target_os = "macos"))]
1312 let ceiling: libc::rlim_t = 1 << 20;
1313 assert!(after.rlim_cur >= before.rlim_cur);
1314 assert!(after.rlim_cur >= after.rlim_max.min(ceiling));
1315 }
1316}
1317
1318#[cfg(test)]
1319mod alias_tests {
1320 use super::aliased;
1321
1322 #[test]
1323 fn a_host_and_its_subdomains_reach_the_alias_and_nothing_else_does() {
1324 let onion = reqwest::Url::parse("http://abc.onion").unwrap();
1325 let aliases = [("magnitude.vectorapp.io".to_string(), onion.clone()), ("magnitude.jskitty.com".to_string(), onion)];
1326 let at = |u: &str| aliased(&reqwest::Url::parse(u).unwrap(), &aliases).map(|u| u.to_string());
1327 assert_eq!(at("https://magnitude.vectorapp.io/ab.png").as_deref(), Some("http://abc.onion/ab.png"));
1328 assert_eq!(at("https://us.magnitude.jskitty.com/proxy?url=x%2Fy").as_deref(), Some("http://abc.onion/proxy?url=x%2Fy"));
1329 assert_eq!(at("https://evilmagnitude.vectorapp.io/ab.png"), None);
1330 assert_eq!(at("https://magnitude.vectorapp.io.evil.com/ab.png"), None);
1331 assert_eq!(at("https://blossom.primal.net/ab.png"), None);
1332 }
1333}
1334
1335#[cfg(all(test, not(target_arch = "wasm32")))]
1336mod tls_tests {
1337 use super::*;
1338
1339 #[test]
1340 fn clients_build_on_ring_with_h2_offered_first() {
1341 let cfg = tls_config();
1342 assert_eq!(cfg.alpn_protocols, [b"h2".to_vec(), b"http/1.1".to_vec()]);
1343 let opts = ClientOptions { timeout: None, read_timeout: None, follow_redirects: true, no_direct: false };
1344 build_pooled(opts, None).expect("a pooled client builds");
1345 template();
1346 }
1347}
1348
1349#[cfg(test)]
1350mod user_agent_tests {
1351 use super::*;
1352
1353 #[test]
1356 fn the_client_names_itself_as_vector() {
1357 assert!(user_agent().starts_with("Vector/"), "{}", user_agent());
1358 set_app_version("9.9.9-test");
1359 assert!(user_agent().starts_with("Vector/"), "{}", user_agent());
1362 }
1363}