Skip to main content

lb_rs/model/
core_config.rs

1use std::env;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{get_code_commit, get_code_version};
6
7#[derive(Debug, Serialize, Deserialize, Clone, Copy, PartialEq, Eq, Default)]
8pub enum ClientType {
9    Cli,
10    Ui,
11    #[default]
12    Unknown,
13}
14
15impl ClientType {
16    pub fn as_str(self) -> &'static str {
17        match self {
18            ClientType::Cli => "cli",
19            ClientType::Ui => "ui",
20            ClientType::Unknown => "unknown",
21        }
22    }
23}
24
25#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
26pub struct Config {
27    /// Identifies the client in startup logs and `lockbook-<client_name>.log`.
28    #[serde(default)]
29    pub client_name: String,
30
31    /// Optional build identity of a client compiled separately from Rust.
32    #[serde(default)]
33    pub build_info: Option<String>,
34
35    #[serde(default)]
36    pub os_version: Option<String>,
37
38    #[serde(default = "default_lb_version")]
39    pub lb_version: String,
40
41    #[serde(default = "default_lb_commit")]
42    pub lb_commit: Option<String>,
43
44    /// Where should lockbook store data, including logs?
45    pub writeable_path: String,
46
47    /// Should lb do background work like keep search indexes up to date?
48    pub background_work: bool,
49
50    /// Should we log at all?
51    pub logs: bool,
52
53    /// Should logs be printed to stdout?
54    pub stdout_logs: bool,
55
56    /// Should logs be colored?
57    pub colored_logs: bool,
58
59    #[serde(default)]
60    pub client_type: ClientType,
61
62    /// Should dev accounts exit when a db lock is held past its budget? Set per platform: a host
63    /// turns it on where it enforces the frame budget. lb-rs can't derive it, since
64    /// [ClientType::Ui] doesn't mean the host has a frame budget.
65    #[serde(default)]
66    pub lock_budget: bool,
67
68    #[serde(default)]
69    pub read_only: bool,
70
71    /// Should listings, recents, pending shares and search include attachments folders and their
72    /// contents? The apps leave them out; the CLI and the Files app show them. The recipient of an
73    /// individually shared note never sees its attachments folder listed, whatever this is set to.
74    #[serde(default)]
75    pub list_attachments: bool,
76
77    /// Seeds the ids and keys of new files and accounts, so a test that takes the same steps
78    /// replays them; None draws from the OS. Seeded keys are guessable, so only test builds have
79    /// it and no saved config sets one.
80    #[cfg(feature = "test-seed")]
81    #[serde(skip)]
82    pub seed: Option<u64>,
83}
84
85impl Default for Config {
86    fn default() -> Self {
87        Self {
88            client_name: String::new(),
89            build_info: None,
90            os_version: None,
91            lb_version: default_lb_version(),
92            lb_commit: default_lb_commit(),
93            writeable_path: String::new(),
94            background_work: false,
95            logs: false,
96            stdout_logs: false,
97            colored_logs: false,
98            client_type: ClientType::Unknown,
99            lock_budget: false,
100            read_only: false,
101            list_attachments: false,
102            #[cfg(feature = "test-seed")]
103            seed: None,
104        }
105    }
106}
107
108fn default_lb_version() -> String {
109    get_code_version().to_owned()
110}
111
112fn default_lb_commit() -> Option<String> {
113    get_code_commit().map(str::to_owned)
114}
115
116impl Config {
117    /// Configures lockbook for CLI use with no stdout logs or background work. `writeable_path_subfolder` is generally
118    /// a hardcoded client name like `"cli"`.
119    pub fn cli_config(writeable_path_subfolder: &str) -> Config {
120        Config {
121            client_name: writeable_path_subfolder.to_owned(),
122            os_version: host_os_version(),
123            writeable_path: Self::writeable_path(writeable_path_subfolder),
124            logs: true,
125            colored_logs: true,
126            client_type: ClientType::Cli,
127            list_attachments: true,
128            ..Default::default()
129        }
130    }
131
132    /// Configures lockbook for UI use with stdout logs and background work. `writeable_path_subfolder` is generally
133    /// a hardcoded client name like `"macos"`.
134    pub fn ui_config(writeable_path_subfolder: &str) -> Config {
135        Config {
136            client_name: writeable_path_subfolder.to_owned(),
137            os_version: host_os_version(),
138            writeable_path: Self::writeable_path(writeable_path_subfolder),
139            background_work: true,
140            logs: true,
141            stdout_logs: true,
142            colored_logs: true,
143            client_type: ClientType::Ui,
144            ..Default::default()
145        }
146    }
147
148    /// Produces a full writable path for lockbook to use based on environment variables and platform. Useful for
149    /// initializing the Config struct.
150    pub fn writeable_path(writeable_path_subfolder: &str) -> String {
151        if let Ok(specified_path) = env::var("LOCKBOOK_PATH") {
152            return specified_path;
153        }
154
155        // `env::home_dir` is `HOME` then `getpwuid_r` on unix, and `USERPROFILE` then `GetUserProfileDirectory` on
156        // windows. It notably never consults `HOME` on windows: we used to fall back to `HOMEPATH`, which omits the
157        // drive letter (`\Users\parth`), so the data directory silently followed whichever drive the process happened
158        // to be running from.
159        let Some(home) = env::home_dir() else {
160            panic!("no location for lockbook to initialize");
161        };
162
163        home.join(".lockbook")
164            .join(writeable_path_subfolder)
165            .to_string_lossy()
166            .into_owned()
167    }
168}
169
170// todo: we added background work as a flag to speed up test execution in debug mode
171// turn background work back to true in test_utils to see the slow test
172// the slow test primarily does a large amount of allocations due to ownership model
173// of treelike. In a universe where these operations could be expressed as iterators
174// we would be able to vastly cut down on allocations and eliminate this complexity
175//
176// another nice aspect of background work is that it is a workaround for CLI's lack
177// of graceful shutdown. Ideally, both of these situations will be handled differently.
178
179#[cfg(any(target_os = "macos", target_os = "ios"))]
180pub fn host_os_version() -> Option<String> {
181    let mut buf = [0u8; 64];
182    let mut len = buf.len();
183    let res = unsafe {
184        libc::sysctlbyname(
185            c"kern.osproductversion".as_ptr(),
186            buf.as_mut_ptr().cast(),
187            &mut len,
188            std::ptr::null_mut(),
189            0,
190        )
191    };
192    if res != 0 {
193        return None;
194    }
195    let version = std::ffi::CStr::from_bytes_until_nul(&buf[..len])
196        .ok()?
197        .to_str()
198        .ok()?;
199    let os = if cfg!(target_os = "ios") { "iOS" } else { "macOS" };
200    Some(format!("{os} {version}"))
201}
202
203#[cfg(target_os = "linux")]
204pub fn host_os_version() -> Option<String> {
205    let release = std::fs::read_to_string("/etc/os-release")
206        .or_else(|_| std::fs::read_to_string("/usr/lib/os-release"))
207        .ok()?;
208    release
209        .lines()
210        .find_map(|line| line.strip_prefix("PRETTY_NAME="))
211        .map(|name| name.trim_matches('"').to_owned())
212}
213
214#[cfg(windows)]
215pub fn host_os_version() -> Option<String> {
216    use windows_sys::Wdk::System::SystemServices::RtlGetVersion;
217    use windows_sys::Win32::System::SystemInformation::OSVERSIONINFOW;
218
219    let mut info: OSVERSIONINFOW = unsafe { std::mem::zeroed() };
220    info.dwOSVersionInfoSize = std::mem::size_of::<OSVERSIONINFOW>() as u32;
221    if unsafe { RtlGetVersion(&mut info) } != 0 {
222        return None;
223    }
224    Some(format!("Windows {}.{}.{}", info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber))
225}
226
227#[cfg(target_os = "android")]
228pub fn host_os_version() -> Option<String> {
229    fn property(name: &std::ffi::CStr) -> Option<String> {
230        let mut buf = [0u8; libc::PROP_VALUE_MAX as usize];
231        let len = unsafe { libc::__system_property_get(name.as_ptr(), buf.as_mut_ptr().cast()) };
232        if len <= 0 {
233            return None;
234        }
235        String::from_utf8(buf[..len as usize].to_vec()).ok()
236    }
237    let release = property(c"ro.build.version.release")?;
238    match property(c"ro.build.version.sdk") {
239        Some(sdk) => Some(format!("Android {release} (SDK {sdk})")),
240        None => Some(format!("Android {release}")),
241    }
242}
243
244#[cfg(not(any(
245    target_os = "macos",
246    target_os = "ios",
247    target_os = "linux",
248    target_os = "android",
249    windows
250)))]
251pub fn host_os_version() -> Option<String> {
252    None
253}