Skip to main content

vector_core/transport/
prefs.rs

1//! The account's network choice and routing settings. One source of truth: the session's
2//! [`SessionPrefs`]; instances never hold a copy.
3//!
4//! Nothing outside this file reads or writes the legacy Tor row: it is a projection kept so an
5//! older build of the same schema stays fail closed.
6
7use std::collections::HashMap;
8use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};
9use std::sync::{Arc, Mutex, RwLock};
10
11use super::aliases::{AliasEntry, AliasTable};
12use super::{Kind, KindConfig};
13
14pub const KEY_TRANSPORT: &str = "transport";
15pub const KEY_LEGACY_TOR: &str = "tor_enabled";
16pub const KEY_ALIASES: &str = "transport_aliases";
17pub const KEY_MULTI_CIRCUIT: &str = "tor_multi_circuit";
18pub const KEY_I2P_CONFIG: &str = "transport_cfg_i2p";
19
20/// `transport_cfg_{kind}`: one JSON row per kind.
21pub fn config_key(kind: Kind) -> String {
22    format!("transport_cfg_{}", kind.as_str())
23}
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum StoredKind {
27    Absent,
28    Kind(Kind),
29    Unparseable(String),
30    ReadError(String),
31}
32
33pub struct StoredPrefs {
34    pub kind: StoredKind,
35    pub multi_circuit: bool,
36    pub configs: HashMap<Kind, KindConfig>,
37    pub aliases: Vec<AliasEntry>,
38}
39
40fn row(conn: &rusqlite::Connection, key: &str) -> Result<Option<String>, String> {
41    match conn.query_row("SELECT value FROM settings WHERE key = ?1", [key], |r| r.get::<_, String>(0)) {
42        Ok(v) => Ok(Some(v)),
43        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
44        Err(e) => Err(e.to_string()),
45    }
46}
47
48/// The strictest reading wins, so a round trip through an older build can only raise.
49pub fn resolve(transport: Option<&str>, legacy_tor: Option<&str>) -> StoredKind {
50    let tor_on = matches!(legacy_tor, Some("1") | Some("true"));
51    match transport {
52        Some(v) => match Kind::parse(v) {
53            Some(Kind::Clearnet) if tor_on => StoredKind::Kind(Kind::Tor),
54            Some(k) => StoredKind::Kind(k),
55            None => StoredKind::Unparseable(v.to_string()),
56        },
57        None if tor_on => StoredKind::Kind(Kind::Tor),
58        None if legacy_tor.is_some() => StoredKind::Kind(Kind::Clearnet),
59        None => StoredKind::Absent,
60    }
61}
62
63pub fn read_stored(conn: &rusqlite::Connection) -> StoredPrefs {
64    let kind = match (row(conn, KEY_TRANSPORT), row(conn, KEY_LEGACY_TOR)) {
65        (Ok(t), Ok(l)) => resolve(t.as_deref(), l.as_deref()),
66        (Err(e), _) | (_, Err(e)) => StoredKind::ReadError(e),
67    };
68    let multi_circuit = !matches!(row(conn, KEY_MULTI_CIRCUIT), Ok(Some(ref v)) if v == "0" || v == "false");
69    let configs = Kind::ALL
70        .into_iter()
71        .map(|k| match row(conn, &config_key(k)) {
72            Ok(json) => {
73                let json = json.map(zeroize::Zeroizing::new);
74                (k, super::kinds::decode(k, json.as_deref().map(String::as_str)))
75            }
76            Err(e) => {
77                crate::log_warn!("[Transport] could not read the {} settings: {e}", k.label());
78                (k, super::kinds::decode_unreadable(k))
79            }
80        })
81        .collect();
82    let aliases = AliasTable::parse(row(conn, KEY_ALIASES).ok().flatten().as_deref()).entries();
83    StoredPrefs { kind, multi_circuit, configs, aliases }
84}
85
86struct PrefsKey;
87
88pub struct SessionPrefs {
89    /// 0 Unknown, else `Kind::code`.
90    kind: AtomicU8,
91    configs: RwLock<HashMap<Kind, KindConfig>>,
92    aliases: RwLock<Arc<AliasTable>>,
93    consent: Mutex<Option<Kind>>,
94    config_seq: AtomicU64,
95    /// The database these settings were loaded from. Loading it again only raises: a choice
96    /// whose save failed stays in force until Vector restarts, as the user was told.
97    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
98    hydrated_from: Mutex<Option<std::path::PathBuf>>,
99}
100
101impl Default for SessionPrefs {
102    fn default() -> Self {
103        let kind = if super::is_strict() && !cfg!(target_arch = "wasm32") { 0 } else { Kind::Clearnet.code() };
104        SessionPrefs {
105            kind: AtomicU8::new(kind),
106            configs: RwLock::new(HashMap::new()),
107            aliases: RwLock::new(Arc::new(AliasTable::default())),
108            consent: Mutex::new(None),
109            config_seq: AtomicU64::new(0),
110            hydrated_from: Mutex::new(None),
111        }
112    }
113}
114
115impl SessionPrefs {
116    pub fn kind(&self) -> Option<Kind> {
117        Kind::from_code(self.kind.load(Ordering::Acquire))
118    }
119
120    pub fn config(&self, kind: Kind) -> KindConfig {
121        if let Some(c) = self.configs.read().unwrap_or_else(|e| e.into_inner()).get(&kind) {
122            return c.clone();
123        }
124        super::kinds::decode(kind, None)
125    }
126
127    pub fn aliases(&self) -> Arc<AliasTable> {
128        self.aliases.read().unwrap_or_else(|e| e.into_inner()).clone()
129    }
130
131    pub fn config_seq(&self) -> u64 {
132        self.config_seq.load(Ordering::Acquire)
133    }
134
135    pub(crate) fn set_aliases(&self, table: Arc<AliasTable>) {
136        *self.aliases.write().unwrap_or_else(|e| e.into_inner()) = table;
137        self.config_seq.fetch_add(1, Ordering::AcqRel);
138    }
139
140    pub(crate) fn set_config_value(&self, kind: Kind, cfg: KindConfig) {
141        self.configs.write().unwrap_or_else(|e| e.into_inner()).insert(kind, cfg);
142        self.config_seq.fetch_add(1, Ordering::AcqRel);
143    }
144
145    pub(crate) fn consent(&self) -> Option<Kind> {
146        *self.consent.lock().unwrap_or_else(|e| e.into_inner())
147    }
148
149    pub(crate) fn set_consent(&self, k: Option<Kind>) {
150        *self.consent.lock().unwrap_or_else(|e| e.into_inner()) = k;
151    }
152}
153
154/// Insert the entry before the session is shared, so a rebound clone of the session's map holds
155/// the same `Arc` instead of growing its own.
156pub fn attach(session: &Arc<crate::db::Session>) {
157    let _ = of(session);
158}
159
160pub fn of(session: &Arc<crate::db::Session>) -> Arc<SessionPrefs> {
161    session.scoped::<PrefsKey, SessionPrefs>()
162}
163
164struct ConfigWrites;
165
166/// Held across a kind config's read, persist and install, so two writers of the same session
167/// (a settings change, the welcome screen's commit retry, a reload) never drop each other's change.
168pub(crate) fn config_write_lock() -> Arc<Mutex<()>> {
169    config_write_lock_of(&crate::db::current_session())
170}
171
172fn config_write_lock_of(session: &Arc<crate::db::Session>) -> Arc<Mutex<()>> {
173    session.scoped::<ConfigWrites, Mutex<()>>()
174}
175
176/// The live session's settings: unbound callers (relay tasks, the bridge) act for it.
177pub fn live() -> Arc<SessionPrefs> {
178    of(&crate::db::live_session())
179}
180
181/// The settings of the session this work belongs to.
182pub fn current() -> Arc<SessionPrefs> {
183    of(&crate::db::current_session())
184}
185
186/// Change `session`'s kind. A live session's change moves the epoch; a kind change also drops
187/// its realtime consent.
188pub(crate) fn set_kind(session: &Arc<crate::db::Session>, kind: Option<Kind>) {
189    let p = of(session);
190    let code = kind.map_or(0, Kind::code);
191    let prev = p.kind.swap(code, Ordering::AcqRel);
192    if prev == code {
193        return;
194    }
195    if Kind::from_code(prev) != kind {
196        p.set_consent(None);
197    }
198    if session.is_live() {
199        super::bump_epoch();
200        super::host::notify(super::host::TransportEvent::Changed);
201    }
202}
203
204/// The live session's config for `kind`, parsed once.
205pub fn config(kind: Kind) -> KindConfig {
206    live().config(kind)
207}
208
209/// Install `cfg` into the session this work belongs to, the same one `persist_config` writes.
210pub fn set_config(kind: Kind, cfg: KindConfig) {
211    let session = crate::db::current_session();
212    of(&session).set_config_value(kind, cfg);
213    if session.is_live() {
214        super::bump_policy_gen();
215        super::host::notify(super::host::TransportEvent::Changed);
216    }
217}
218
219/// Load the account's settings into THIS session (never resolved through the task binding: the
220/// caller is installing it). A read error leaves the session Unknown.
221pub fn hydrate(session: &Arc<crate::db::Session>, db_path: &std::path::Path) {
222    #[cfg(target_arch = "wasm32")]
223    {
224        let _ = db_path;
225        set_kind(session, Some(Kind::Clearnet));
226    }
227    #[cfg(not(target_arch = "wasm32"))]
228    {
229        let stored = match crate::db::connect_at(db_path) {
230            Ok(conn) => read_stored(&conn),
231            Err(e) => StoredPrefs {
232                kind: StoredKind::ReadError(e),
233                multi_circuit: true,
234                configs: Kind::ALL.into_iter().map(|k| (k, super::kinds::decode_unreadable(k))).collect(),
235                aliases: Vec::new(),
236            },
237        };
238        let p = of(session);
239        let mut from = p.hydrated_from.lock().unwrap_or_else(|e| e.into_inner());
240        if from.as_deref() == Some(db_path) {
241            reapply_stored(session, stored);
242        } else {
243            apply_stored(session, stored);
244            *from = Some(db_path.to_path_buf());
245        }
246    }
247}
248
249#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
250pub(crate) fn apply_stored(session: &Arc<crate::db::Session>, stored: StoredPrefs) {
251    #[cfg(feature = "tor")]
252    crate::tor::set_multi_circuit(stored.multi_circuit);
253    let p = of(session);
254    {
255        let lock = config_write_lock_of(session);
256        let _write = lock.lock().unwrap_or_else(|e| e.into_inner());
257        *p.configs.write().unwrap_or_else(|e| e.into_inner()) = stored.configs;
258    }
259    p.set_aliases(Arc::new(AliasTable::from_entries(stored.aliases)));
260    if let StoredKind::ReadError(e) = &stored.kind {
261        crate::log_warn!("[Transport] could not read the network preference: {e}");
262    }
263    set_kind(session, super::prelogin::effective(&stored.kind));
264}
265
266/// The same account's settings loaded again into a session that already holds them: what the
267/// session holds wins, unless the row is stricter. Every change saves before it loosens, so only
268/// a tightening whose save failed can differ, and it stays.
269#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
270fn reapply_stored(session: &Arc<crate::db::Session>, stored: StoredPrefs) {
271    let p = of(session);
272    {
273        let lock = config_write_lock_of(session);
274        let _write = lock.lock().unwrap_or_else(|e| e.into_inner());
275        let mut configs = p.configs.write().unwrap_or_else(|e| e.into_inner());
276        for (k, row) in stored.configs {
277            let next = match configs.get(&k) {
278                Some(held) => super::kinds::stricter(k, held, &row),
279                None => row,
280            };
281            configs.insert(k, next);
282        }
283    }
284    p.config_seq.fetch_add(1, Ordering::AcqRel);
285    set_kind(session, stricter_kind(p.kind(), super::prelogin::effective(&stored.kind)));
286}
287
288/// Unknown over any kind, any anonymity kind over Clearnet; between two anonymity kinds the
289/// session's own, the user's latest choice.
290pub(crate) fn stricter_kind(held: Option<Kind>, stored: Option<Kind>) -> Option<Kind> {
291    match (held, stored) {
292        (_, None) => None,
293        (None, s) => s,
294        (Some(Kind::Clearnet), s) => s,
295        (Some(h), Some(_)) => Some(h),
296    }
297}
298
299/// The stored kind of the session this work belongs to.
300pub fn stored_kind() -> StoredKind {
301    match crate::db::get_db_connection_guard_static() {
302        Ok(conn) => read_stored(&conn).kind,
303        Err(e) => StoredKind::ReadError(e),
304    }
305}
306
307/// `transport` and its legacy projection, in one transaction.
308pub fn persist_kind(kind: Kind) -> Result<(), String> {
309    let mut conn = crate::db::get_write_connection_guard_static()?;
310    persist_kind_on(&mut conn, kind)
311}
312
313pub fn persist_kind_on(conn: &mut rusqlite::Connection, kind: Kind) -> Result<(), String> {
314    let tx = conn
315        .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
316        .map_err(|e| format!("Failed to save the network choice: {e}"))?;
317    let legacy = if kind == Kind::Clearnet { "0" } else { "1" };
318    for (k, v) in [(KEY_TRANSPORT, kind.as_str()), (KEY_LEGACY_TOR, legacy)] {
319        tx.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", rusqlite::params![k, v])
320            .map_err(|e| format!("Failed to save the network choice: {e}"))?;
321    }
322    tx.commit().map_err(|e| format!("Failed to save the network choice: {e}"))
323}
324
325pub fn persist_config(kind: Kind, json: &str) -> Result<(), String> {
326    persist_setting(&config_key(kind), json)
327}
328
329/// Borrowed straight into the statement: a row that can hold a secret is never copied here.
330pub(crate) fn persist_setting(key: &str, value: &str) -> Result<(), String> {
331    let conn = crate::db::get_write_connection_guard_static()?;
332    conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?1, ?2)", rusqlite::params![key, value])
333        .map_err(|e| format!("Failed to set setting: {e}"))?;
334    Ok(())
335}
336
337/// JSON written once into a buffer of its exact size, so no reallocation leaves a copy of a
338/// secret behind, and zeroized when dropped.
339pub fn secret_json<T: serde::Serialize + ?Sized>(v: &T) -> zeroize::Zeroizing<String> {
340    struct Count(usize);
341    impl std::io::Write for Count {
342        fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
343            self.0 += b.len();
344            Ok(b.len())
345        }
346        fn flush(&mut self) -> std::io::Result<()> {
347            Ok(())
348        }
349    }
350    let mut count = Count(0);
351    if serde_json::to_writer(&mut count, v).is_err() {
352        return zeroize::Zeroizing::new("{}".into());
353    }
354    let mut buf = Vec::with_capacity(count.0);
355    if serde_json::to_writer(&mut buf, v).is_err() {
356        zeroize::Zeroize::zeroize(&mut buf);
357        return zeroize::Zeroizing::new("{}".into());
358    }
359    // serde_json writes UTF-8 only.
360    zeroize::Zeroizing::new(String::from_utf8(buf).unwrap_or_default())
361}
362
363/// Wipe every string in a JSON value that may have held a secret before it is dropped.
364pub fn scrub_json(v: &mut serde_json::Value) {
365    match v {
366        serde_json::Value::String(s) => zeroize::Zeroize::zeroize(s),
367        serde_json::Value::Array(a) => a.iter_mut().for_each(scrub_json),
368        serde_json::Value::Object(o) => o.values_mut().for_each(scrub_json),
369        _ => {}
370    }
371}
372
373/// Every settings key this module owns: the generic settings commands never touch them.
374pub const PROTECTED_KEYS: &[&str] = &[KEY_TRANSPORT, KEY_LEGACY_TOR, KEY_I2P_CONFIG, KEY_ALIASES];