Skip to main content

vector_core/
net.rs

1//! Network utilities — SSRF protection, HTTP client helpers.
2
3use url::Url;
4
5/// Reject URLs that resolve to private/loopback/link-local addresses (SSRF protection).
6pub 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; } // Unique local
46    if segments[0] & 0xffc0 == 0xfe80 { return true; } // Link-local
47    false
48}
49
50/// The exact `reqwest` these clients are built from.
51///
52/// Re-exported because call sites name its types (headers, bodies, methods): a consumer that
53/// names its own `reqwest` version gets a different type with the same name.
54pub use reqwest;
55
56pub use crate::transport::Lane;
57
58/// How long a transfer may go without moving a byte before it is given up on.
59///
60/// This is the only time limit a large transfer has. A total deadline caps the
61/// file size a slow link can ever move (300 s at 1 Mbit/s is 36 MB), so
62/// uploads and downloads are bounded by progress instead: any rate at all
63/// keeps them alive, and only a dead connection is abandoned.
64///
65/// Two minutes rather than one because TCP's own retransmit backoff on a
66/// lossy long-haul path reaches that between attempts: a shorter window
67/// abandons a connection the kernel is still recovering. Servers we run keep
68/// their gap timers above this, so the client is the one that gives up and
69/// can say why, instead of meeting a socket the proxy already closed.
70pub const TRANSFER_STALL: std::time::Duration = std::time::Duration::from_secs(120);
71
72/// [`TRANSFER_STALL`] for the transport in use.
73pub fn transfer_stall() -> std::time::Duration {
74    crate::transport::budget(crate::transport::Op::TransferStall, TRANSFER_STALL)
75}
76
77/// What every request calls itself. Set once by the app with its own
78/// version; until then, this crate's. Magnitude serves link previews to
79/// Vector only, and judges that by this header, so it has to be present on
80/// every request and has to start with `Vector/`. One string for every
81/// user is also the least identifying choice: over Tor, a client that looks
82/// like every other Vector looks like nothing in particular.
83static USER_AGENT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
84
85/// Name the app's version in the user agent. Call once at startup; a second
86/// call is ignored.
87pub 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
98/// An HTTP budget (a request total, a read) for the transport in use: a circuit to a fresh
99/// host alone can take 45 s. Clearnet passes through.
100pub fn tor_http_timeout(clearnet: std::time::Duration) -> std::time::Duration {
101    crate::transport::budget(crate::transport::Op::HttpTotal, clearnet)
102}
103
104// ============================================================================
105// HttpClient: egress decided per request
106// ============================================================================
107//
108// A client is a descriptor (owner, lane, options), never a connection pool: `Req::send` asks
109// the transport where this request may go, then runs it on the pooled reqwest client for that
110// decision. A client taken before a network switch can therefore never send on the old egress,
111// and a body in flight aborts when the network changes.
112
113#[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    /// Never direct: a fetch decided while an anonymity network was chosen, that the user must
119    /// never make from this device's own address.
120    no_direct: bool,
121}
122
123#[derive(Clone, Debug)]
124pub struct HttpClient {
125    owner: u64,
126    lane: Lane,
127    opts: ClientOptions,
128}
129
130/// A client with the given total timeout, for content anyone can name.
131///
132/// Every fetch goes through the transport's decision for its own host: direct only while the
133/// account is on Clearnet, through the bridge on an anonymity network, and refused in process
134/// while that network is not up. Clippy forbids building a reqwest client anywhere else.
135pub fn build_http_client(timeout: std::time::Duration) -> Result<HttpClient, String> {
136    build_http_client_for(Lane::Shared, Some(timeout), None, true)
137}
138
139/// Like `build_http_client`, with the total timeout optional and
140/// redirect-following switchable.
141///
142/// `timeout` is a deadline on the whole request; `None` for large transfers,
143/// which are bounded by progress instead (see [`TRANSFER_STALL`]).
144///
145/// `read_timeout` resets on every byte of the response *body*. Before the
146/// headers arrive it is a single deadline from the start of the request that
147/// nothing resets — including bytes of a request body going out — so it must
148/// stay `None` on an upload whose body may take longer than it.
149///
150/// Blossom PUT uses `follow_redirects = false`: a 3xx mid-upload would
151/// re-issue as GET and drop the body, so the 3xx surfaces as the real status.
152pub 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
160/// A client for `lane`: `Account` for requests that identify as the user (signed uploads).
161pub 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
176/// A 30 s client for frequent small fetches (image cache, wallet polling).
177pub 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/// The pool key: one reqwest client per decision, so no pooled connection outlives its epoch.
186#[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
199/// Drop every pooled client: the next request builds one for the current egress.
200pub fn forget_clients() {
201    if let Ok(mut g) = POOLS.lock() {
202        *g = None;
203    }
204}
205
206/// Kept for callers that rebuilt the shared client on a Tor flip; clients are per request now.
207pub fn rebuild_shared_http_client() -> Result<(), String> {
208    forget_clients();
209    Ok(())
210}
211
212/// Only builds requests: `Req::send` executes on the client the current egress gives.
213fn 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/// Ring with the webpki roots, offering h2 before HTTP/1.1, with a session store of its own.
219///
220/// Built per pooled client, never cloned from a shared one: a clone shares the session store,
221/// and a resumed ticket would tie this account and lane to another's requests to that server.
222#[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    /// The session this client was built under.
272    pub fn owner(&self) -> u64 {
273        self.owner
274    }
275
276    /// The same client speaking for `lane`: a request carrying the user's signed authorization
277    /// identifies them, so it rides the Account lane.
278    pub fn with_lane(&self, lane: Lane) -> HttpClient {
279        HttpClient { lane, ..self.clone() }
280    }
281
282    /// The same client, refusing to go direct: for a fetch that was only allowed because the
283    /// account was on an anonymity network, so a switch to Clearnet meanwhile fails it.
284    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        // Kept connections: idle ones stay a while so a burst of small
294        // fetches to one host (an edge, a Blossom server) rides one or a
295        // few connections, and HTTP/2 multiplexes on them where offered.
296        .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        // Magnitude's preview endpoint refuses a caller that does not say it is Vector.
302        .user_agent(user_agent())
303        // Bounded connect: a black-holed host (SYN swallowed, never refused) must
304        // fail in seconds instead of silently consuming the whole request budget.
305        .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        // Validate EVERY redirect hop, not just the initial URL: a public host answering
316        // `302 Location: http://169.254.169.254/…` would otherwise walk past the SSRF check,
317        // and one naming another network's host must not reach a resolver.
318        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
346/// The pooled client for this decision, built and cached unless the epoch moved meanwhile.
347fn 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/// Hosts this page reaches at another address: `(host, base)`, the host matching itself and its
373/// subdomains. Vector Web served from an onion reaches Magnitude at its onion, since Tor Browser
374/// sends `Origin: null` from an onion page to the clearnet and Magnitude admits browsers by Origin.
375#[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/// `url` at its alias, keeping the path and query; `None` when its host has none.
392#[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
404/// A request being built. Forwards the builder methods call sites use.
405pub 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    /// The browser's own cache stays out of it (Vector Web).
453    #[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    /// Ask the transport where this request may go, then run it there. A refusal opens no
460    /// socket and resolves nothing; a network change while it runs abandons it.
461    #[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        // A decision raced by a switch is taken again, at most three times; past that the
471        // request runs on the last one and fails closed against its stale epoch.
472        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        // After the decision: the transport judges the host asked for, and the alias is an
488        // address only this page's browser reaches (an onion, from a page served on one).
489        #[cfg(target_arch = "wasm32")]
490        apply_host_alias(req.url_mut());
491        // The change is polled first: a switch that lands before the first poll must stop the
492        // request before it resolves or dials anything.
493        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/// A response body as a stream; `Send` natively, where the browser's isn't.
505#[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
510/// A response whose body reads stop when the network it came over changes.
511pub 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    /// The transport refused before any socket opened.
614    Refused(crate::transport::ConnectError),
615    /// The network this request was on changed under it.
616    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    /// reqwest's text, unless the transport recorded why it refused this host just now.
626    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            // Under Tor an arti failure keeps reqwest's own text, as it always read.
631            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    /// The network will come back: a switch, or the chosen kind still connecting. A policy
664    /// refusal won't.
665    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    /// A refusal by the transport's rules (I2P-Only, another network's name), which no retry fixes.
674    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
698/// Upload bodies: ends the stream with an error when the epoch or live session changes.
699pub 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
711/// Hold a transfer that hit a network change until the network is back, then let it resume.
712/// Policy refusals and other failures return at once with their text.
713pub 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
720/// Find the byte index where a bracket/paren group opened at `start` closes,
721/// tracking nesting depth and honoring backslash escapes — markdown balances
722/// both, so a naive first-closer scan desyncs on `[[claim]](evil)` or
723/// `[claim\]](evil)` and lets the claim reach the URL scan. All compared
724/// bytes are ASCII, so the returned index is char-boundary-safe.
725fn 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
746/// Rewrite markdown links so a preview-URL scan sees only real DESTINATIONS:
747/// `[text](href)` keeps the href and drops the display text — a URL claimed in
748/// the text must never win the OG preview over where the link actually goes —
749/// `[text](<href>)` drops entirely (angle brackets are the no-preview syntax),
750/// and `[text][ref]` drops the label (its destination is a definition scanned
751/// on its own elsewhere in the text). Images (`![alt](url)`) render as literal
752/// text in chat, so they pass through untouched.
753pub 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            // Inline link: drop the label, contribute the destination.
766            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            // Reference link: drop the label; the `[ref]: url` definition line
782            // carries the real destination and gets scanned as plain text.
783            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    // ========================================================================
806    // strip_md_link_claims — preview scan must see destinations, not claims
807    // ========================================================================
808
809    #[test]
810    fn md_link_claim_text_dropped_href_kept() {
811        // The spoof shape: claimed URL first in raw text, real destination second.
812        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 = "![shot](https://host.io/img.png)";
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    // ========================================================================
879    // Valid public URLs — should pass
880    // ========================================================================
881
882    #[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    // ========================================================================
913    // Loopback addresses — should be rejected
914    // ========================================================================
915
916    #[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    // ========================================================================
935    // Private IP ranges — should be rejected
936    // ========================================================================
937
938    #[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    // ========================================================================
963    // Special addresses — should be rejected
964    // ========================================================================
965
966    #[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    // ========================================================================
997    // IPv6 addresses — should be rejected
998    // ========================================================================
999
1000    #[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    // ========================================================================
1037    // Domain name restrictions
1038    // ========================================================================
1039
1040    #[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    // ========================================================================
1053    // Scheme restrictions
1054    // ========================================================================
1055
1056    #[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    // ========================================================================
1083    // Missing / invalid URL
1084    // ========================================================================
1085
1086    #[test]
1087    fn no_host_rejected() {
1088        // http:// with no host is actually an invalid URL for the url crate
1089        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    // ========================================================================
1107    // Edge cases
1108    // ========================================================================
1109
1110    #[test]
1111    fn cgn_100_63_not_rejected() {
1112        // 100.63.x.x is NOT in the CGN range (100.64-100.127)
1113        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        // 100.128.x.x is NOT in the CGN range
1120        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        // 172.15.x.x is NOT private (private is 172.16-172.31)
1127        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        // 172.32.x.x is NOT private
1134        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
1139// ============================================================================
1140// Egress: where a request actually goes
1141// ============================================================================
1142
1143/// Where a request for `url` really goes, and what it carries: the proxy's
1144/// address with a signed authorization when the privacy setting routes it
1145/// through Magnitude, or the URL itself.
1146pub struct Egress {
1147    pub url: String,
1148    pub auth: Option<reqwest::header::HeaderValue>,
1149}
1150
1151impl Egress {
1152    /// Whether the request leaves through a proxy rather than to the host.
1153    pub fn proxied(&self) -> bool {
1154        self.auth.is_some() || crate::proxy::proxy_server_of(&self.url).is_some()
1155    }
1156}
1157
1158/// Resolve the destination for `url`. Every outbound fetch of somebody else's
1159/// content asks here first, so the setting has exactly one place to act.
1160pub 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
1173/// A request for `url` on `client`, already pointed at the right place and
1174/// carrying the proxy authorization when there is one.
1175pub 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
1183/// The HTTP status the SOURCE gives for `url`: 2xx means it serves, 404/410
1184/// means it is gone. `None` means nothing definitive could be learned (the
1185/// host, or the proxy, was unreachable). Through the proxy a HEAD carries no
1186/// body, so one byte is asked for instead and the source's status read from
1187/// the proxy's answer; direct, a HEAD is tried first and a one-byte GET when
1188/// the host refuses HEAD.
1189pub 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
1214// ============================================================================
1215// Remote File Size
1216// ============================================================================
1217
1218/// Get the size of a remote file via HEAD request or Range fallback.
1219/// Returns None if the URL is private, unreachable, or size can't be determined.
1220pub 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    // Method 1: HEAD request
1225    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    // Method 2: Range request fallback
1234    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/// Lift the open-file ceiling to what the OS allows.
1260///
1261/// A relay pool authenticates every plane on its own socket and the SQLite pool
1262/// holds dozens of handles, so a busy session idles near 200 descriptors. macOS
1263/// launches GUI apps with a soft limit of 256; past it every socket, file and
1264/// child process fails, and the first system UI to lazily load a resource
1265/// bundle traps the process. Returns the new soft limit, `None` if unchanged.
1266#[allow(clippy::unnecessary_cast)] // rlim_t is u32 on 32-bit Android
1267pub fn raise_fd_limit() -> Option<u64> {
1268    #[cfg(not(unix))]
1269    {
1270        None
1271    }
1272    #[cfg(unix)]
1273    {
1274        // macOS refuses a soft limit above OPEN_MAX (sys/syslimits.h) even under
1275        // an unlimited hard limit; Linux refuses one above nr_open.
1276        #[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        // SAFETY: plain libc calls on a stack struct we own.
1283        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    /// Magnitude refuses a preview request whose agent does not start with
1354    /// `Vector/`; this is the string every request will carry.
1355    #[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        // Either the app's version or, if another test set it first, that
1360        // one: in both cases still Vector's.
1361        assert!(user_agent().starts_with("Vector/"), "{}", user_agent());
1362    }
1363}