diff --git a/src/daemon.rs b/src/daemon.rs index 9492f04..df477e5 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -1,9 +1,9 @@ use std::{ - env, io, + env, io, mem, ops::Deref, os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd}, sync::{ - LazyLock, + Arc, LazyLock, atomic::{AtomicUsize, Ordering}, }, time::Duration, @@ -19,6 +19,7 @@ use serde::{Deserialize, Serialize}; use serde_json::StreamDeserializer; use crate::{ + SourceFile, SourceLine, daemon_tokfd::{FdInfo, FdKind}, prelude::*, }; @@ -66,6 +67,17 @@ impl ConvenientAttrPath { let boxed = iter.map(|s| Box::from(s)); Self::Split(Box::from_iter(boxed)) } + + pub fn to_nix_decl(&self) -> Box { + use ConvenientAttrPath::*; + match self { + Dotted(s) => s.clone(), + Split(path) => { + // FIXME: quote if necessary + path.join(".").into_boxed_str() + }, + } + } } impl<'i> FromIterator<&'i str> for ConvenientAttrPath { @@ -89,6 +101,7 @@ impl FromIterator> for ConvenientAttrPath { #[derive(Debug, Clone, PartialEq)] #[derive(serde::Deserialize, serde::Serialize)] #[serde(tag = "action", content = "args", rename_all = "snake_case")] +// FIXME: rename to not confuse with the clap argument type. pub enum DaemonCmd { Append { name: ConvenientAttrPath, @@ -112,6 +125,7 @@ fn next_token() -> Token { #[derive(Debug)] pub struct Daemon { + config_path: Arc, fd: OwnedFdWithFlags, path: Option>, @@ -197,6 +211,8 @@ impl Daemon { IoError::last_os_error().raw_os_error(), Some(Errno::BADF.raw_os_error()), ); + + self.tokfd.remove2(&fd).unwrap_or_else(|| todo!()); } fn fd_for_token(&self, token: Token) -> Option { @@ -215,7 +231,12 @@ impl Daemon { } impl Daemon { - pub fn new(fd: OwnedFd, kind: FdKind, name: Option>) -> Self { + pub fn new( + config_path: Arc, + fd: OwnedFd, + kind: FdKind, + name: Option>, + ) -> Self { let mut fd_info: IdOrdMap = Default::default(); // Supposedly, the only possible ways this can fail are EMFILE, ENFILE, and ENOMEM. @@ -240,6 +261,7 @@ impl Daemon { }; Self { + config_path, fd, path, poller, @@ -250,7 +272,7 @@ impl Daemon { } } - pub fn from_unix_socket_path(path: &Path) -> Result { + pub fn from_unix_socket_path(config_path: Arc, path: &Path) -> Result { // We unconditionally unlink() `path` before binding, but completely ignore the result. let _ = rustix::fs::unlink(path); let listener = UnixListener::bind(path) @@ -260,13 +282,18 @@ impl Daemon { rustix::net::sockopt::set_socket_keepalive(&listener_owned_fd, true).unwrap(); let path: Box = path.to_path_buf().into_boxed_path().into_boxed_os_str(); - Ok(Self::new(listener_owned_fd, FdKind::Socket, Some(path))) + Ok(Self::new( + config_path, + listener_owned_fd, + FdKind::Socket, + Some(path), + )) } - pub fn open_default_socket() -> Result { + pub fn open_default_socket(config_path: Arc) -> Result { use IoErrorKind::*; let preferred = USER_SOCKET_DIR.join("dynix.sock").into_boxed_path(); - let constructed = match Self::from_unix_socket_path(&preferred) { + let constructed = match Self::from_unix_socket_path(config_path.clone(), &preferred) { Ok(v) => v, Err(e) if e.kind() == Unsupported => { // @@ -279,7 +306,7 @@ impl Daemon { ); let fallback = TMPDIR.join("dynix.sock").into_boxed_path(); - Self::from_unix_socket_path(&fallback).tap_err(|e| { + Self::from_unix_socket_path(config_path, &fallback).tap_err(|e| { error!( "failed binding AF_UNIX socket at {}: {e}", fallback.display(), @@ -294,14 +321,14 @@ impl Daemon { /// This panics if stdin cannot be opened. /// /// If you want to handle that error, use [`Daemon::from_raw_parts()`]. - pub fn from_stdin() -> Self { + pub fn from_stdin(config_path: Arc) -> Self { let stdin = io::stdin(); let fd = stdin .as_fd() .try_clone_to_owned() .expect("dynix daemon could not open stdin; try a Unix socket?"); - Self::new(fd, FdKind::File, None) + Self::new(config_path, fd, FdKind::File, None) } //pub unsafe fn from_raw_parts(fd: OwnedFd) -> Self { @@ -325,8 +352,11 @@ impl Daemon { let _count = rustix::io::read(fd, spare_capacity(&mut self.cmd_buffer)) .tap_err(|e| error!("read() on daemon fd {fd:?} failed: {e}"))?; + // So that the loop doesn't borrow from `self`. + let mut cmd_buffer = mem::take(&mut self.cmd_buffer); + // The buffer might have existing data from the last read. - let deserializer = serde_json::Deserializer::from_slice(&self.cmd_buffer); + let deserializer = serde_json::Deserializer::from_slice(&cmd_buffer); let stream: StreamDeserializer<_, DaemonCmd> = deserializer.into_iter(); for cmd in stream { let cmd = match cmd { @@ -334,12 +364,14 @@ impl Daemon { Err(e) if e.is_eof() => { self.next_timeout = Some(Duration::from_secs(4)); warn!("Didn't get a valid daemon command; giving the other side 4 seconds..."); + let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer); return Ok(()); }, Err(e) => { warn!("error deserializing command: {e}"); - debug!("command buffer was: {:?}", self.cmd_buffer.as_bstr()); - self.cmd_buffer.clear(); + debug!("command buffer was: {:?}", cmd_buffer.as_bstr()); + cmd_buffer.clear(); + let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer); // Don't propagate the error unless we have too many. self.fd_error_push(fd.as_raw_fd(), e.into()).tap_err(|e| { error!("Accumulated too many errors for daemon fd {fd:?}: {e}") @@ -350,9 +382,51 @@ impl Daemon { debug!("got cmd: {cmd:?}"); let _ = rustix::io::write(fd, b""); info!("dispatching command"); + self.dispatch_cmd(cmd).unwrap_or_else(|e| todo!("{e}")); } - self.cmd_buffer.clear(); + cmd_buffer.clear(); + let _ = mem::replace(&mut self.cmd_buffer, cmd_buffer); + + Ok(()) + } + + fn dispatch_cmd(&mut self, cmd: DaemonCmd) -> Result<(), IoError> { + let (name, value) = match cmd { + DaemonCmd::Append { name, value } => (name, value), + }; + let mut opts = File::options(); + opts.read(true) + .write(true) + .create(false) + .custom_flags(libc::O_CLOEXEC); + let source_file = SourceFile::open_from(self.config_path.clone(), opts)?; + let pri = crate::get_where(source_file.clone()).unwrap_or_else(|e| todo!("{e}")); + let new_pri = pri - 1; + //let new_pri_line = + // crate::get_next_prio_line(source_file.clone(), Arc::from(name), Arc::from(value)); + // Get next priority line. + let source_lines = source_file.lines()?; + let penultimate = source_lines.get(source_lines.len() - 2); + // FIXME: don't rely on whitespace lol + debug_assert_eq!(penultimate.map(SourceLine::text).as_deref(), Some(" ];")); + let penultimate = penultimate.unwrap(); + let new_generation = 0 - new_pri; + let new_line = SourceLine { + line: penultimate.line, + path: source_file.path(), + text: Arc::from(format!( + " {} = lib.mkOverride ({}) ({}); # DYNIX GENERATION {}", + name.to_nix_decl(), + new_pri, + value, + new_generation, + )), + }; + + drop(source_lines); + + crate::write_next_prio(source_file, new_line).unwrap_or_else(|e| todo!("{e}")); Ok(()) } diff --git a/src/lib.rs b/src/lib.rs index 426fc44..40f983b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -35,6 +35,8 @@ pub(crate) mod prelude { pub use bstr::ByteSlice; + pub use itertools::Itertools; + pub use rustix::io::Errno; pub use tap::{Pipe, Tap, TapFallible, TapOptional}; @@ -133,17 +135,27 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr } //#[tracing::instrument(level = "debug")] -pub fn do_daemon(_args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { +pub fn do_daemon(args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { + let config_file = Path::new(&args.file); + let config_file: PathBuf = if config_file.is_relative() && !config_file.starts_with("./") { + iter::once(OsStr::new("./")) + .chain(config_file.iter()) + .collect() + } else { + config_file.to_path_buf() + }; + let config_file: Arc = Arc::from(config_file); + // FIXME: make configurable? let _ = rustix::process::umask(Mode::from_bits_retain(0o600).complement()); let mut daemon = match daemon_args { - DaemonCmd { stdin: true, .. } => Daemon::from_stdin(), - DaemonCmd { socket: None, .. } => Daemon::open_default_socket()?, + DaemonCmd { stdin: true, .. } => Daemon::from_stdin(config_file), + DaemonCmd { socket: None, .. } => Daemon::open_default_socket(config_file)?, DaemonCmd { socket: Some(socket), .. - } => Daemon::from_unix_socket_path(&socket)?, + } => Daemon::from_unix_socket_path(config_file, &socket)?, }; daemon.enter_loop().unwrap();