diff --git a/.cargo/config.toml b/.cargo/config.toml index 4c0fbdc..05ed9b0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,3 +1,4 @@ [env] # in development (i.e. when running through Cargo), store state in project directory CREDDY_DATA_DIR = { value = "data", relative = true } +CREDDY_RUNTIME_DIR = { value = "data", relative = true } diff --git a/Cargo.lock b/Cargo.lock index 7363d6f..301c3ec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1445,12 +1445,14 @@ dependencies = [ "hyper-util", "include_dir", "jiff", + "rustix", "serde", "serde_json", + "smol", + "smol-hyper", "tempfile", "testresult", "thiserror 2.0.21", - "tokio", "uuid", ] @@ -7040,6 +7042,19 @@ dependencies = [ "futures-lite", ] +[[package]] +name = "smol-hyper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7428a49d323867702cd12b97b08a6b0104f39ec13b49117911f101271321bc1a" +dependencies = [ + "async-executor", + "async-io", + "futures-io", + "hyper", + "pin-project-lite", +] + [[package]] name = "smol_str" version = "0.3.7" diff --git a/Cargo.toml b/Cargo.toml index b9efe91..e7fe22e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,11 +21,13 @@ hyper = { version = "1.12.0", features = ["server", "http1"] } hyper-util = { version = "0.1.21", features = ["tokio"] } include_dir = "0.7.4" jiff = { version = "1.0.1", features = ["serde"] } +rustix = { version = "1.1.6", features = ["net"] } serde = "1.0.229" serde_json = "1.0.154" +smol = "2.0.2" +smol-hyper = "0.1.1" testresult = "0.4.2" thiserror = "2.0.21" -tokio = { version = "1.54.1", features = ["rt-multi-thread", "net"] } uuid = { version = "1.29.3", features = ["v4", "serde"] } [dev-dependencies] diff --git a/src/app.rs b/src/app.rs index a65ae29..84f5943 100644 --- a/src/app.rs +++ b/src/app.rs @@ -7,6 +7,7 @@ use gpui_omarchy::ActiveTheme; use crate::config::AppConfig; use crate::screens::{CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen}; use crate::session::AppSession; +use crate::srv; pub struct CreddyApp {} @@ -44,7 +45,12 @@ impl Render for CreddyApp { /// Install the globals and open the main window. Tests call this too, so they get the same wiring. pub fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle { + // todo: `SetupError` global, that gets populated if any of the fallible setup fails so we can display it in the UI gpui_omarchy::init(cx); + + srv::start_creddy_server(&config.creddy_server_addr(), cx.to_async()) + .expect("Failed to start server, we will add proper error handling for this later"); + cx.set_global(config); cx.set_global(session); cx.set_global(Screen::Home); diff --git a/src/config.rs b/src/config.rs index 7cf9c00..2245ba5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -42,7 +42,7 @@ impl PublicConfig { } } -/// Config that can be stored in the encrypted db +/// Config that should be stored in the encrypted db #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct PrivateConfig { @@ -60,6 +60,7 @@ impl Default for PrivateConfig { #[derive(Debug, Clone)] pub struct AppConfig { pub data_dir: PathBuf, + pub runtime_dir: PathBuf, pub db_salt: [u8; 32], pub rehide_ms: u64, } @@ -67,31 +68,35 @@ pub struct AppConfig { impl AppConfig { /// Load config from disk, using defaults for non-public values. pub fn load() -> Result { - let data_dir = AppConfig::resolve_data_dir( - env::var_os("CREDDY_DATA_DIR"), - dirs::data_dir(), - )?; + let data_dir = env::var_os("CREDDY_DATA_DIR") + .map(PathBuf::from) + .or_else(|| dirs::data_dir().map(|d| d.join("creddy"))) + .ok_or(CreddyError::DirNotFound)?; - AppConfig::load_from(data_dir) + let runtime_dir = env::var_os("CREDDY_RUNTIME_DIR") + .map(PathBuf::from) + .or_else(|| dirs::runtime_dir()) + .ok_or(CreddyError::DirNotFound)?; + + AppConfig::load_from(data_dir, runtime_dir) } - pub fn load_from(data_dir: PathBuf) -> Result { + pub fn load_from(data_dir: PathBuf, runtime_dir: PathBuf) -> Result { let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?; let private_config = PrivateConfig::default(); - Ok(AppConfig::from_parts(data_dir, public_config, private_config)) - } - - fn resolve_data_dir(creddy_data_dir: Option, platform_data_dir: Option) -> Result { - creddy_data_dir - .map(PathBuf::from) - .or_else(|| platform_data_dir.map(|d| d.join("creddy"))) - .ok_or(CreddyError::DataDirNotFound) + Ok(AppConfig::from_parts(data_dir, runtime_dir, public_config, private_config)) } /// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither) - fn from_parts(data_dir: PathBuf, public: PublicConfig, private: PrivateConfig) -> AppConfig { + fn from_parts( + data_dir: PathBuf, + runtime_dir: PathBuf, + public: PublicConfig, + private: PrivateConfig + ) -> AppConfig { AppConfig { data_dir, + runtime_dir, db_salt: public.db_salt, rehide_ms: private.rehide_ms, } @@ -109,6 +114,10 @@ impl AppConfig { self.data_dir.join("creddy.duckdb") } + pub fn creddy_server_addr(&self) -> PathBuf { + self.runtime_dir.join("creddy-server.sock") + } + pub fn public_config(&self) -> PublicConfig { PublicConfig { db_salt: self.db_salt, @@ -128,6 +137,7 @@ impl Default for AppConfig { // remaining defaults when constructing otherwise, and data_dir is // always specified otherwise AppConfig::from_parts( + PathBuf::from(""), PathBuf::from(""), PublicConfig::default(), PrivateConfig::default(), @@ -174,7 +184,8 @@ mod tests { #[test] fn test_config_load_not_present() -> TestResult { let data_dir = tempfile::tempdir()?; - let config = AppConfig::load_from(data_dir.path().to_path_buf())?; + let data_dir_path = data_dir.path().to_path_buf(); + let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?; assert!(config.data_dir == data_dir.path()); assert!(config.db_salt.len() == 32); Ok(()) @@ -183,38 +194,18 @@ mod tests { #[test] fn test_config_load_present() -> TestResult { let data_dir = tempfile::tempdir()?; + let data_dir_path = data_dir.path().to_path_buf(); let p = data_dir.path().join("public_config.json"); let public = PublicConfig::default(); // uses a random db salt let f = File::create(&p)?; serde_json::to_writer(f, &public)?; - let config = AppConfig::load_from(data_dir.path().to_path_buf())?; + let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?; assert!(config.data_dir == data_dir.path()); assert!(config.db_salt == public.db_salt); Ok(()) } - #[test] - fn test_resolve_data_dir_override() -> TestResult { - let data_dir = AppConfig::resolve_data_dir( - Some(OsString::from("/tmp/creddy")), - None, - )?; - assert!(data_dir == PathBuf::from("/tmp/creddy")); - Ok(()) - } - - #[test] - fn test_resolve_data_dir_default() -> TestResult { - let data_dir = AppConfig::resolve_data_dir( - None, - Some(PathBuf::from("/tmp")), - )?; - - assert!(data_dir == PathBuf::from("/tmp/creddy")); - Ok(()) - } - #[test] fn test_config_paths() { let mut config = AppConfig::default(); @@ -224,6 +215,14 @@ mod tests { assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json")); } + #[test] + fn test_server_addr() { + let mut config = AppConfig::default(); + config.runtime_dir = PathBuf::from("/tmp/creddy"); + + assert_eq!(config.creddy_server_addr(), PathBuf::from("/tmp/creddy/creddy-server.sock")); + } + #[test] fn test_public_config_from_app_config() { let mut config = AppConfig::default(); diff --git a/src/db/config.rs b/src/db/config.rs index a86ced2..6e0d9dc 100644 --- a/src/db/config.rs +++ b/src/db/config.rs @@ -44,7 +44,7 @@ mod tests { } #[test] - fn test_load_priate_config() -> TestResult { + fn test_load_private_config() -> TestResult { let (db, _data_dir) = test_db()?; let private_config = PrivateConfig::default(); db.save_private_config(&private_config)?; diff --git a/src/error.rs b/src/error.rs index e419696..56e4d5b 100644 --- a/src/error.rs +++ b/src/error.rs @@ -5,7 +5,7 @@ use thiserror::Error; #[derive(Error, Debug)] pub enum CreddyError { #[error("Couldn't determine location for app state")] - DataDirNotFound, + DirNotFound, #[error("Invalid path: {0:?}")] InvalidPath(OsString), @@ -30,4 +30,7 @@ pub enum CreddyError { #[error("Invalid JSON: {0}")] InvalidJSON(#[from] serde_json::Error), + + #[error("Failed to bind socket: {0}")] + SocketBind(String), } diff --git a/src/main.rs b/src/main.rs index 86c7911..9411585 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,6 +15,7 @@ mod tests; use config::AppConfig; use session::AppSession; + fn main() { // todo: replace this with proper error handling let app_config = AppConfig::load().expect("failed to load config"); diff --git a/src/srv/creddy_server.rs b/src/srv/creddy_server.rs new file mode 100644 index 0000000..e02c940 --- /dev/null +++ b/src/srv/creddy_server.rs @@ -0,0 +1,69 @@ +use crate::error::CreddyError; +use gpui_kit::AsyncApp; +use http_body_util::Full; +use hyper::{Request, Response, StatusCode}; +use hyper::body::{Incoming, Bytes}; +use hyper::service::service_fn; +use hyper::server::conn::http1; +use smol::Timer; +use smol::net::unix::{UnixListener, UnixStream}; +use smol_hyper::rt::FuturesIo; +use rustix::net::sockopt::socket_peercred; +use rustix::process::Pid; +use std::convert::Infallible; +use std::fs; +use std::io; +use std::path::Path; +use std::time::Duration; + + +pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> { + if path.exists() { + fs::remove_file(path)?; + } + let listener = UnixListener::bind(path) + .map_err(|_| CreddyError::SocketBind(path.to_string_lossy().into()))?; + + app.spawn(async move |app| { + loop { + let (stream, pid) = match accept(&listener).await { + Ok((stream, pid)) => (stream, pid), + Err(e) => { + eprintln!("Error accepting connection: {e}"); + Timer::after(Duration::from_millis(100)).await; + continue; + } + }; + + app.spawn(async move |app| { + let adapter = FuturesIo::new(stream); + let service = service_fn(|req| handle(req, pid, app.clone())); + let conn = http1::Builder::new().serve_connection(adapter, service); + if let Err(e) = conn.await { + eprintln!("Error serving connection: {e}") + } + }).detach(); + } + }).detach(); + + Ok(()) +} + + +async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> { + let (stream, _) = listener.accept().await?; + // pid() never returns None on Linux + let pid = socket_peercred(&stream)?.pid; + Ok((stream, pid)) +} + + +async fn handle(req: Request, pid: Pid, app: AsyncApp) -> Result>, Infallible> { + Ok(Response::new(Full::new(Bytes::from("hello world")))) +} + +fn text(status: StatusCode, body: &'static str) -> Response> { + let mut response = Response::new(Full::new(Bytes::from(body))); + *response.status_mut() = status; + response +} diff --git a/src/srv/mod.rs b/src/srv/mod.rs new file mode 100644 index 0000000..ddee22e --- /dev/null +++ b/src/srv/mod.rs @@ -0,0 +1,3 @@ +mod creddy_server; + +pub use creddy_server::start_creddy_server; diff --git a/src/tests/mod.rs b/src/tests/mod.rs index a835e3f..1acab24 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -22,7 +22,8 @@ pub struct TestEnv { impl TestEnv { pub fn new() -> Result { let dir = tempfile::tempdir()?; - let config = AppConfig::load_from(dir.path().to_path_buf())?; + let path = dir.path().to_path_buf(); + let config = AppConfig::load_from(path.clone(), path)?; Ok(TestEnv { _dir: dir, config }) } @@ -33,7 +34,13 @@ impl TestEnv { /// Start the app against the test environment, as `main` would. fn open_app(env: &TestEnv, cx: &mut TestAppContext) -> AnyWindowHandle { - let window = cx.update(|cx| launch(cx, env.config.clone(), AppSession::load(&env.config))); + let window = cx.update(|cx| { + launch( + cx, + env.config.clone(), + AppSession::load(&env.config), + ) + }); // first frame, so that elements exist to be found cx.update_window(window.into(), |_, window, cx| window.render_frame(cx)).unwrap(); window.into()