Skip to main content

vector_core/i2p/
sam.rs

1//! A minimal SAMv3 client for a router the user already runs. It speaks five commands and
2//! nothing else: transient STREAM sessions that never publish a LeaseSet or build a zero-hop
3//! tunnel, outbound stream connects, name lookups and a liveness probe. No line it sends can
4//! make the router accept a connection or carry someone else's traffic.
5
6use std::net::Ipv4Addr;
7use std::time::Duration;
8
9use tokio::io::{AsyncReadExt, AsyncWriteExt};
10use tokio::net::TcpStream;
11use zeroize::Zeroizing;
12
13/// SAM is cleartext, so it never leaves the loopback interface.
14pub const SAM_HOST: Ipv4Addr = Ipv4Addr::LOCALHOST;
15
16const TCP_CONNECT: Duration = Duration::from_secs(5);
17const HELLO_REPLY: Duration = Duration::from_secs(5);
18pub(crate) const SESSION_CAP: Duration = Duration::from_secs(120);
19pub(crate) const STREAM_CAP: Duration = Duration::from_secs(90);
20const LOOKUP_CAP: Duration = Duration::from_secs(30);
21const OWN_ADDRESS_CAP: Duration = Duration::from_secs(10);
22const PROBE_CAP: Duration = Duration::from_secs(10);
23const MAX_LINE: usize = 4096;
24/// The SESSION STATUS reply carries the transient private key.
25const MAX_SESSION_LINE: usize = 16 * 1024;
26
27/// Options every session is created with. Zero-hop tunnels off in both directions; the LeaseSet
28/// is never published, so nothing can reach this destination unasked.
29pub(crate) const SESSION_OPTIONS: &str = "SIGNATURE_TYPE=7 i2cp.leaseSetEncType=6,4 i2cp.dontPublishLeaseSet=true \
30inbound.length=3 inbound.quantity=3 outbound.length=3 outbound.quantity=3 inbound.allowZeroHop=false outbound.allowZeroHop=false";
31
32#[derive(Clone)]
33pub struct SamAuth {
34    pub user: String,
35    pub password: Zeroizing<String>,
36}
37
38impl SamAuth {
39    pub fn new(user: &str, password: &str) -> Self {
40        SamAuth { user: user.to_string(), password: Zeroizing::new(password.to_string()) }
41    }
42}
43
44impl PartialEq for SamAuth {
45    fn eq(&self, other: &Self) -> bool {
46        self.user == other.user && self.password.as_str() == other.password.as_str()
47    }
48}
49
50impl std::fmt::Debug for SamAuth {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("SamAuth").field("user", &self.user).finish_non_exhaustive()
53    }
54}
55
56#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
57pub struct SamVersion {
58    pub major: u8,
59    pub minor: u8,
60}
61
62impl SamVersion {
63    pub const MIN: SamVersion = SamVersion { major: 3, minor: 2 };
64
65    fn parse(v: &str) -> Option<SamVersion> {
66        let (a, b) = v.split_once('.')?;
67        Some(SamVersion { major: a.parse().ok()?, minor: b.split('.').next()?.parse().ok()? })
68    }
69}
70
71impl std::fmt::Display for SamVersion {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        write!(f, "{}.{}", self.major, self.minor)
74    }
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub enum HelloError {
79    /// Nothing answered on the port (refused, reset, or closed before a reply).
80    Refused,
81    Timeout,
82    /// Something took the connection and never replied: a web console or proxy, most often.
83    Silent,
84    /// Something answered, but not a SAM bridge.
85    NotSam,
86    /// The router can't speak 3.2 or newer; the version it named, when it named one.
87    NoVersion(String),
88    AuthRequired,
89    AuthFailed,
90}
91
92#[derive(Clone, Debug, PartialEq, Eq)]
93pub enum StreamFail {
94    RouterDown,
95    SessionGone,
96    /// The router answered oddly (`I2P_ERROR`, a garbled line, EOF): the session may be gone.
97    SessionSuspect(String),
98    Unreachable(String),
99    BadKey,
100    Timeout,
101}
102
103#[derive(Clone, Debug, PartialEq, Eq)]
104pub enum Liveness {
105    Alive,
106    Gone,
107    RouterDown,
108    Inconclusive(String),
109}
110
111// ── Lines ────────────────────────────────────────────────────────────────────
112
113#[derive(Debug)]
114pub(crate) enum LineError {
115    Eof,
116    TooLong,
117    Io(std::io::Error),
118}
119
120/// One reply line, read a byte at a time so nothing after the `\n` is consumed: on a stream
121/// socket every later byte belongs to the stream.
122pub(crate) async fn read_line(s: &mut TcpStream, max: usize) -> Result<Zeroizing<String>, LineError> {
123    // Sized for the longest line up front: a growing buffer would leave copies of a session's
124    // private key behind in freed memory, outside the zeroized one.
125    let mut buf = Zeroizing::new(Vec::with_capacity(max));
126    let mut b = [0u8; 1];
127    loop {
128        match s.read(&mut b).await {
129            Ok(0) => return Err(LineError::Eof),
130            Ok(_) => {
131                if b[0] == b'\n' {
132                    break;
133                }
134                if buf.len() >= max {
135                    return Err(LineError::TooLong);
136                }
137                buf.push(b[0]);
138            }
139            Err(e) => return Err(LineError::Io(e)),
140        }
141    }
142    if buf.last() == Some(&b'\r') {
143        buf.pop();
144    }
145    Ok(Zeroizing::new(String::from_utf8_lossy(&buf).into_owned()))
146}
147
148/// A reply split into its two command words and its `KEY=VALUE` pairs. Values may be quoted.
149#[derive(Debug, Default)]
150pub(crate) struct Reply {
151    pub topic: String,
152    pub kind: String,
153    pub args: Vec<(String, String)>,
154}
155
156impl Reply {
157    pub fn get(&self, key: &str) -> Option<&str> {
158        self.args.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str())
159    }
160
161    pub fn result(&self) -> &str {
162        self.get("RESULT").unwrap_or("")
163    }
164
165    /// The router's own words for a failure, short and printable.
166    pub fn detail(&self) -> String {
167        let raw = self.get("MESSAGE").filter(|m| !m.is_empty()).unwrap_or_else(|| self.result());
168        let clean: String = raw.chars().filter(|c| !c.is_control()).take(120).collect();
169        if clean.is_empty() {
170            "no reason given".into()
171        } else {
172            clean
173        }
174    }
175}
176
177pub(crate) fn parse(line: &str) -> Reply {
178    let mut tokens = Vec::new();
179    let mut cur = String::new();
180    let mut quoted = false;
181    for c in line.chars() {
182        match c {
183            '"' => quoted = !quoted,
184            ' ' if !quoted => {
185                if !cur.is_empty() {
186                    tokens.push(std::mem::take(&mut cur));
187                }
188            }
189            _ => cur.push(c),
190        }
191    }
192    if !cur.is_empty() {
193        tokens.push(cur);
194    }
195    let mut it = tokens.into_iter();
196    let topic = it.next().unwrap_or_default();
197    let kind = it.next().unwrap_or_default();
198    let args = it.filter_map(|t| t.split_once('=').map(|(k, v)| (k.to_string(), v.to_string()))).collect();
199    Reply { topic, kind, args }
200}
201
202/// A SESSION STATUS reply, cut before its `DESTINATION` (the private key) so the key is never
203/// copied out of the zeroized line.
204fn parse_session_reply(line: &str) -> Reply {
205    match line.find(" DESTINATION=") {
206        Some(i) => parse(&line[..i]),
207        None => parse(line),
208    }
209}
210
211async fn send_line(s: &mut TcpStream, line: &str) -> std::io::Result<()> {
212    let mut out = Zeroizing::new(String::with_capacity(line.len() + 1));
213    out.push_str(line);
214    out.push('\n');
215    s.write_all(out.as_bytes()).await
216}
217
218fn random_hex(bytes: usize) -> String {
219    use rand::RngCore;
220    let mut b = vec![0u8; bytes];
221    rand::rngs::OsRng.fill_bytes(&mut b);
222    crate::simd::hex::bytes_to_hex_string(&b)
223}
224
225/// A fresh session nickname: 128 random bits, nothing that names the app or the account.
226pub fn new_nick() -> String {
227    random_hex(16)
228}
229
230// ── HELLO ────────────────────────────────────────────────────────────────────
231
232/// Built in one allocation of its exact size, so the password is never copied into a buffer that
233/// is freed without being zeroized.
234fn hello_line(auth: Option<&SamAuth>) -> Zeroizing<String> {
235    const BASE: &str = "HELLO VERSION MIN=3.2 MAX=3.3";
236    let Some(a) = auth else { return Zeroizing::new(BASE.to_string()) };
237    let parts = [BASE, " USER=", a.user.as_str(), " PASSWORD=", a.password.as_str()];
238    let mut line = Zeroizing::new(String::with_capacity(parts.iter().map(|p| p.len()).sum()));
239    for p in parts {
240        line.push_str(p);
241    }
242    line
243}
244
245/// Open a SAM socket and agree on 3.2 or newer.
246pub async fn hello(port: u16, auth: Option<&SamAuth>) -> Result<(TcpStream, SamVersion), HelloError> {
247    let mut s = match tokio::time::timeout(TCP_CONNECT, TcpStream::connect((SAM_HOST, port))).await {
248        Err(_) => return Err(HelloError::Timeout),
249        Ok(Err(_)) => return Err(HelloError::Refused),
250        Ok(Ok(s)) => s,
251    };
252    let _ = s.set_nodelay(true);
253    let line = hello_line(auth);
254    if send_line(&mut s, &line).await.is_err() {
255        return Err(HelloError::Refused);
256    }
257    let reply = match tokio::time::timeout(HELLO_REPLY, read_line(&mut s, MAX_LINE)).await {
258        Err(_) => return Err(HelloError::Silent),
259        Ok(Err(LineError::TooLong)) => return Err(HelloError::NotSam),
260        Ok(Err(_)) => return Err(HelloError::Refused),
261        Ok(Ok(l)) => parse(&l),
262    };
263    if reply.topic != "HELLO" || reply.kind != "REPLY" {
264        return Err(HelloError::NotSam);
265    }
266    match reply.result() {
267        "OK" => {
268            let named = reply.get("VERSION").unwrap_or("").to_string();
269            match SamVersion::parse(&named) {
270                Some(v) if v >= SamVersion::MIN => Ok((s, v)),
271                _ => Err(HelloError::NoVersion(named)),
272            }
273        }
274        "NOVERSION" => Err(HelloError::NoVersion(String::new())),
275        "I2P_ERROR" if auth.is_some() => Err(HelloError::AuthFailed),
276        "I2P_ERROR" => Err(HelloError::AuthRequired),
277        _ => Err(HelloError::NotSam),
278    }
279}
280
281// ── Sessions ─────────────────────────────────────────────────────────────────
282
283/// A session's control socket. Dropping it ends the session: the router tears a session down
284/// within half a second of its control socket closing.
285pub struct ControlSocket {
286    stream: TcpStream,
287    buf: Vec<u8>,
288    address: Option<String>,
289}
290
291/// What the router said on a session's control socket.
292#[derive(Debug, PartialEq, Eq)]
293pub enum ControlEvent {
294    /// The socket closed: the session is gone.
295    Closed(String),
296    /// The router pinged; answer with [`ControlSocket::pong`].
297    Ping(String),
298    Other,
299}
300
301impl ControlSocket {
302    /// The session's own `.b32.i2p` address, when the router told us.
303    pub fn address(&self) -> Option<&str> {
304        self.address.as_deref()
305    }
306
307    /// Wait for the router to say something. Cancel-safe: a partial line stays buffered.
308    pub async fn next_event(&mut self) -> ControlEvent {
309        loop {
310            if let Some(i) = self.buf.iter().position(|b| *b == b'\n') {
311                let line: Vec<u8> = self.buf.drain(..=i).collect();
312                let text = String::from_utf8_lossy(&line).trim().to_string();
313                return match text.strip_prefix("PING") {
314                    Some(rest) if rest.is_empty() || rest.starts_with(' ') => ControlEvent::Ping(rest.trim().to_string()),
315                    _ => ControlEvent::Other,
316                };
317            }
318            if self.buf.len() > MAX_LINE {
319                self.buf.clear();
320            }
321            let mut chunk = [0u8; 256];
322            match self.stream.read(&mut chunk).await {
323                Ok(0) => return ControlEvent::Closed("the router closed the session".into()),
324                Ok(n) => self.buf.extend_from_slice(&chunk[..n]),
325                Err(e) => return ControlEvent::Closed(e.to_string()),
326            }
327        }
328    }
329
330    /// Answer a router's PING. Vector never sends one of its own.
331    pub async fn pong(&mut self, text: &str) -> std::io::Result<()> {
332        let line = if text.is_empty() { "PONG".to_string() } else { format!("PONG {text}") };
333        send_line(&mut self.stream, &line).await
334    }
335}
336
337/// Create a transient STREAM session named `nick` on its own control socket.
338pub async fn create_session(port: u16, auth: Option<&SamAuth>, nick: &str) -> Result<ControlSocket, String> {
339    let (mut s, _) = hello(port, auth).await.map_err(|e| hello_text(&e, port))?;
340    let line = format!("SESSION CREATE STYLE=STREAM ID={nick} DESTINATION=TRANSIENT {SESSION_OPTIONS}");
341    send_line(&mut s, &line).await.map_err(|e| e.to_string())?;
342    let reply = match tokio::time::timeout(SESSION_CAP, read_line(&mut s, MAX_SESSION_LINE)).await {
343        Err(_) => return Err("timed out".into()),
344        Ok(Err(LineError::Eof)) => return Err("the router closed the connection".into()),
345        Ok(Err(LineError::TooLong)) => return Err("an unreadable reply".into()),
346        Ok(Err(LineError::Io(e))) => return Err(e.to_string()),
347        Ok(Ok(l)) => parse_session_reply(&l),
348    };
349    if reply.topic != "SESSION" || reply.kind != "STATUS" {
350        return Err("an unreadable reply".into());
351    }
352    match reply.result() {
353        "OK" => {
354            let address = own_address(&mut s).await;
355            Ok(ControlSocket { stream: s, buf: Vec::new(), address })
356        }
357        _ => Err(reply.detail()),
358    }
359}
360
361/// The session's public address, asked of the router rather than derived from the private key
362/// its SESSION STATUS carried. Best effort: a router that won't say leaves the session usable.
363async fn own_address(s: &mut TcpStream) -> Option<String> {
364    send_line(s, "NAMING LOOKUP NAME=ME").await.ok()?;
365    let read = async {
366        loop {
367            let line = read_line(s, MAX_SESSION_LINE).await.ok()?;
368            if let Some(rest) = line.strip_prefix("PING") {
369                send_line(s, &format!("PONG{rest}")).await.ok()?;
370                continue;
371            }
372            let reply = parse(&line);
373            if reply.topic == "NAMING" && reply.kind == "REPLY" {
374                return match reply.result() {
375                    "OK" => reply.get("VALUE").and_then(b32_of),
376                    _ => None,
377                };
378            }
379        }
380    };
381    tokio::time::timeout(OWN_ADDRESS_CAP, read).await.ok().flatten()
382}
383
384/// `xxxx.b32.i2p` for a destination in I2P's base64 (`-` and `~` stand for `+` and `/`).
385pub fn b32_of(destination: &str) -> Option<String> {
386    use sha2::Digest;
387    let standard: String = destination.chars().map(|c| match c { '-' => '+', '~' => '/', c => c }).collect();
388    let bytes = crate::simd::base64::STANDARD.decode_to_vec(standard.as_bytes()).ok()?;
389    // 256-byte encryption key, 128-byte signing key, 3-byte certificate header.
390    if bytes.len() < 387 {
391        return None;
392    }
393    Some(format!("{}.b32.i2p", base32_lower(&sha2::Sha256::digest(&bytes))))
394}
395
396fn base32_lower(bytes: &[u8]) -> String {
397    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
398    let mut out = String::with_capacity(bytes.len().div_ceil(5) * 8);
399    let (mut acc, mut bits) = (0u32, 0u32);
400    for &b in bytes {
401        acc = (acc << 8) | b as u32;
402        bits += 8;
403        while bits >= 5 {
404            bits -= 5;
405            out.push(ALPHABET[((acc >> bits) & 31) as usize] as char);
406        }
407    }
408    if bits > 0 {
409        out.push(ALPHABET[((acc << (5 - bits)) & 31) as usize] as char);
410    }
411    out
412}
413
414/// A short reason for a failed HELLO, for logs and session errors.
415pub fn hello_text(e: &HelloError, port: u16) -> String {
416    match e {
417        HelloError::Refused | HelloError::Timeout => format!("no router answered on port {port}"),
418        HelloError::Silent => format!("no SAM reply on port {port}"),
419        HelloError::NotSam => "not a SAM bridge".into(),
420        HelloError::NoVersion(_) => "SAM too old".into(),
421        HelloError::AuthRequired => "SAM credentials required".into(),
422        HelloError::AuthFailed => "SAM credentials refused".into(),
423    }
424}
425
426fn stream_fail(reply: &Reply) -> StreamFail {
427    match reply.result() {
428        "INVALID_ID" => StreamFail::SessionGone,
429        "CANT_REACH_PEER" | "PEER_NOT_FOUND" => StreamFail::Unreachable(reply.detail()),
430        "TIMEOUT" => StreamFail::Timeout,
431        "INVALID_KEY" => StreamFail::BadKey,
432        _ => StreamFail::SessionSuspect(reply.detail()),
433    }
434}
435
436async fn hello_for_stream(port: u16, auth: Option<&SamAuth>) -> Result<TcpStream, StreamFail> {
437    match hello(port, auth).await {
438        Ok((s, _)) => Ok(s),
439        Err(HelloError::Refused) => Err(StreamFail::RouterDown),
440        Err(e) => Err(StreamFail::SessionSuspect(hello_text(&e, port))),
441    }
442}
443
444async fn read_reply(s: &mut TcpStream, cap: Duration) -> Result<Reply, StreamFail> {
445    match tokio::time::timeout(cap, read_line(s, MAX_LINE)).await {
446        Err(_) => Err(StreamFail::Timeout),
447        Ok(Err(LineError::Eof)) => Err(StreamFail::SessionSuspect("the router closed the connection".into())),
448        Ok(Err(LineError::TooLong)) => Err(StreamFail::SessionSuspect("an unreadable reply".into())),
449        Ok(Err(LineError::Io(e))) => Err(StreamFail::SessionSuspect(e.to_string())),
450        Ok(Ok(l)) => Ok(parse(&l)),
451    }
452}
453
454/// Open a stream from session `nick` to `dest` (a `.b32.i2p` address or a base64 destination)
455/// on `to_port`. The returned socket IS the stream.
456pub async fn connect(port: u16, auth: Option<&SamAuth>, nick: &str, dest: &str, to_port: u16) -> Result<TcpStream, StreamFail> {
457    let mut s = hello_for_stream(port, auth).await?;
458    let line = format!("STREAM CONNECT ID={nick} DESTINATION={dest} SILENT=false TO_PORT={to_port}");
459    send_line(&mut s, &line).await.map_err(|e| StreamFail::SessionSuspect(e.to_string()))?;
460    let reply = read_reply(&mut s, STREAM_CAP).await?;
461    if reply.topic != "STREAM" || reply.kind != "STATUS" {
462        return Err(StreamFail::SessionSuspect("an unreadable reply".into()));
463    }
464    match reply.result() {
465        "OK" => Ok(s),
466        _ => Err(stream_fail(&reply)),
467    }
468}
469
470/// Resolve a name (or a b32 a router wants as base64) through the router's address book.
471pub async fn lookup(port: u16, auth: Option<&SamAuth>, name: &str) -> Result<String, StreamFail> {
472    let mut s = hello_for_stream(port, auth).await?;
473    send_line(&mut s, &format!("NAMING LOOKUP NAME={name}")).await.map_err(|e| StreamFail::SessionSuspect(e.to_string()))?;
474    let reply = read_reply(&mut s, LOOKUP_CAP).await?;
475    if reply.topic != "NAMING" || reply.kind != "REPLY" {
476        return Err(StreamFail::SessionSuspect("an unreadable reply".into()));
477    }
478    match reply.result() {
479        "OK" => match reply.get("VALUE") {
480            Some(v) if !v.is_empty() && v.bytes().all(|b| b.is_ascii_alphanumeric() || b"-~=".contains(&b)) => Ok(v.to_string()),
481            _ => Err(StreamFail::SessionSuspect("an unreadable reply".into())),
482        },
483        "KEY_NOT_FOUND" | "INVALID_KEY" => Err(StreamFail::BadKey),
484        _ => Err(StreamFail::SessionSuspect(reply.detail())),
485    }
486}
487
488/// Is session `nick` alive? A connect to a destination that can't exist answers at once,
489/// without any network traffic: `INVALID_KEY` for a live session, `INVALID_ID` for a gone one.
490pub async fn liveness(port: u16, auth: Option<&SamAuth>, nick: &str) -> Liveness {
491    let mut s = match hello(port, auth).await {
492        Ok((s, _)) => s,
493        Err(HelloError::Refused) => return Liveness::RouterDown,
494        Err(e) => return Liveness::Inconclusive(hello_text(&e, port)),
495    };
496    let line = format!("STREAM CONNECT ID={nick} DESTINATION={} SILENT=false", random_hex(8));
497    if let Err(e) = send_line(&mut s, &line).await {
498        return Liveness::Inconclusive(e.to_string());
499    }
500    match read_reply(&mut s, PROBE_CAP).await {
501        Ok(r) if r.topic == "STREAM" && r.kind == "STATUS" => match r.result() {
502            "INVALID_KEY" => Liveness::Alive,
503            "INVALID_ID" => Liveness::Gone,
504            other => Liveness::Inconclusive(format!("liveness answered {other}")),
505        },
506        Ok(_) => Liveness::Inconclusive("an unreadable reply".into()),
507        Err(e) => Liveness::Inconclusive(format!("{e:?}")),
508    }
509}
510
511/// What the router test in Settings reports: a HELLO, no session.
512#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
513pub struct RouterTest {
514    pub ok: bool,
515    pub version: Option<String>,
516    pub text: String,
517}
518
519pub async fn test_router(port: u16, auth: Option<&SamAuth>) -> RouterTest {
520    match hello(port, auth).await {
521        Ok((_, v)) => RouterTest { ok: true, version: Some(v.to_string()), text: format!("Found a router. SAM {v}.") },
522        Err(e) => {
523            let version = match &e {
524                HelloError::NoVersion(v) if !v.is_empty() => Some(v.clone()),
525                _ => None,
526            };
527            RouterTest { ok: false, version, text: test_text(&e) }
528        }
529    }
530}
531
532fn test_text(e: &HelloError) -> String {
533    match e {
534        HelloError::Refused | HelloError::Timeout => "No router answered on this port.".into(),
535        // A SAM bridge answers HELLO at once; silence is another service on the wrong port.
536        HelloError::Silent | HelloError::NotSam => "This port isn't a SAM bridge.".into(),
537        HelloError::NoVersion(v) => too_old_text(v),
538        HelloError::AuthRequired => "Your router asks for a SAM username and password.".into(),
539        HelloError::AuthFailed => "Your router turned down the SAM username or password.".into(),
540    }
541}
542
543/// A router that named its version says which; one that only answered NOVERSION can't.
544pub(crate) fn too_old_text(v: &str) -> String {
545    if v.is_empty() {
546        "Your router's SAM is too old. Vector needs 3.2 or newer.".into()
547    } else {
548        format!("Your router speaks SAM {v}. Vector needs 3.2 or newer.")
549    }
550}