use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};
use nibkeep_base::EntityId;
use nibkeep_crypto::rand_core::CryptoRng;
use nibkeep_keys::{KeysError, Protection, Unlocker};
use serde_json::{Value as Json, json};
pub mod app;
use crate::info::write_file;
use crate::{Background, BackgroundOptions, Closed, Library, NodeError};
const LIST: &str = "sync-at-login";
const LIST_LOCK: &str = "sync-at-login.lock";
const RUNNING: &str = "sync-at-login.running";
const STATUS: &str = "sync-at-login.status";
pub use crate::engines::ENGINE_VERSION;
pub const SERVICE_PROGRAM: &str = "nibkeep-sync";
const LOOKING: Duration = Duration::from_millis(50);
const VERSION_WAIT: Duration = Duration::from_secs(5);
const STEP: Duration = Duration::from_millis(100);
const LONGEST_WAIT: Duration = Duration::from_mins(1);
#[cfg(not(any(target_os = "android", target_os = "ios")))]
#[must_use]
pub fn settings_folder() -> Option<PathBuf> {
if let Some(named) = std::env::var_os("NIBKEEP_STATE").filter(|named| !named.is_empty()) {
return Some(PathBuf::from(named));
}
let base = directories::BaseDirs::new()?;
let nibkeep = if cfg!(any(windows, target_vendor = "apple")) {
base.data_local_dir().join("NibKeep")
} else {
base.state_dir()?.join("nibkeep")
};
Some(nibkeep.join(computer_name()))
}
#[cfg(not(any(target_os = "android", target_os = "ios")))]
fn computer_name() -> String {
use std::fmt::Write as _;
const COMPUTER_CONTEXT: &str = "nibkeep 2026-11 computer's folder of state";
crate::place::computer_id().map_or_else(
|| "computer".to_owned(),
|id| {
let hash = blake3::derive_key(COMPUTER_CONTEXT, &id);
hash[..8].iter().fold(String::new(), |mut hex, byte| {
let _ = write!(hex, "{byte:02x}");
hex
})
},
)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Served {
pub replica: EntityId,
pub directory: PathBuf,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct AtLogin {
pub program: Option<PathBuf>,
pub libraries: Vec<Served>,
}
impl AtLogin {
pub fn read(settings: &Path) -> Result<Self, NodeError> {
let path = settings.join(LIST);
match fs::read(&path) {
Ok(bytes) => Self::parse(&bytes).ok_or_else(|| {
NodeError::Damaged(format!("{} is not a list of libraries", path.display()))
}),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
Err(error) => Err(NodeError::file(&path)(error)),
}
}
pub fn edit<T>(settings: &Path, change: impl FnOnce(&mut Self) -> T) -> Result<T, NodeError> {
Self::edit_and(settings, change, |_, _| ()).map(|(changed, ())| changed)
}
fn edit_and<T, U>(
settings: &Path,
change: impl FnOnce(&mut Self) -> T,
then: impl FnOnce(&Self, &T) -> U,
) -> Result<(T, U), NodeError> {
fs::create_dir_all(settings).map_err(NodeError::file(settings))?;
let path = settings.join(LIST_LOCK);
let lock = open_lock(&path)?;
lock.lock().map_err(NodeError::file(&path))?;
let mut list = Self::read(settings)?;
let before = list.clone();
let changed = change(&mut list);
if list != before {
write_file(&settings.join(LIST), &list.to_bytes()?)?;
}
let then = then(&list, &changed);
Ok((changed, then))
}
pub fn add(&mut self, served: Served) {
self.libraries.retain(|listed| {
listed.replica != served.replica && listed.directory != served.directory
});
self.libraries.push(served);
}
pub fn remove(&mut self, directory: &Path) -> bool {
let before = self.libraries.len();
self.libraries
.retain(|listed| listed.directory != directory);
self.libraries.len() != before
}
pub fn remove_replica(&mut self, replica: EntityId) -> bool {
let before = self.libraries.len();
self.libraries.retain(|listed| listed.replica != replica);
self.libraries.len() != before
}
#[must_use]
pub fn find(&self, directory: &Path) -> Option<&Served> {
self.libraries
.iter()
.find(|listed| listed.directory == directory)
}
fn parse(bytes: &[u8]) -> Option<Self> {
let json: Json = serde_json::from_slice(bytes).ok()?;
let program = match &json["program"] {
Json::Null => None,
program => Some(PathBuf::from(program.as_str()?)),
};
let libraries = json["libraries"]
.as_array()?
.iter()
.map(parse_served)
.collect::<Option<_>>()?;
Some(Self { program, libraries })
}
fn to_bytes(&self) -> Result<Vec<u8>, NodeError> {
let program = self.program.as_deref().map(unicode).transpose()?;
let libraries = self
.libraries
.iter()
.map(served_json)
.collect::<Result<Vec<_>, _>>()?;
let json = json!({"program": program, "libraries": libraries});
Ok(serde_json::to_vec_pretty(&json).unwrap_or_default())
}
}
fn parse_served(json: &Json) -> Option<Served> {
Some(Served {
replica: json["replica"].as_str()?.parse().ok()?,
directory: PathBuf::from(json["directory"].as_str()?),
})
}
fn served_json(served: &Served) -> Result<Json, NodeError> {
Ok(json!({
"replica": served.replica.to_string(),
"directory": unicode(&served.directory)?,
}))
}
fn unicode(path: &Path) -> Result<&str, NodeError> {
path.to_str()
.ok_or_else(|| NodeError::NotUnicode(path.to_owned()))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Serving {
Starting,
Syncing,
Waiting,
WaitingForKeyring,
NotHere,
NoKey,
Failed(String),
}
impl Serving {
#[must_use]
pub fn word(&self) -> &'static str {
match self {
Self::Starting => "starting",
Self::Syncing => "syncing",
Self::Waiting => "waiting",
Self::WaitingForKeyring => "waiting for the keyring",
Self::NotHere => "not here",
Self::NoKey => "no key",
Self::Failed(_) => "failed",
}
}
#[must_use]
pub fn error(&self) -> Option<&str> {
match self {
Self::Failed(error) => Some(error),
_ => None,
}
}
fn from_word(word: &str, error: Option<&str>) -> Option<Self> {
Some(match word {
"starting" => Self::Starting,
"syncing" => Self::Syncing,
"waiting" => Self::Waiting,
"waiting for the keyring" => Self::WaitingForKeyring,
"not here" => Self::NotHere,
"no key" => Self::NoKey,
"failed" => Self::Failed(error?.to_owned()),
_ => return None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServiceStatus {
pub version: String,
pub libraries: Vec<(Served, Serving)>,
}
impl ServiceStatus {
pub fn read(settings: &Path) -> Result<Option<Self>, NodeError> {
let path = settings.join(STATUS);
match fs::read(&path) {
Ok(bytes) => Self::parse(&bytes)
.map(Some)
.ok_or_else(|| NodeError::Damaged(format!("{} is not a status", path.display()))),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(NodeError::file(&path)(error)),
}
}
#[must_use]
pub fn of(&self, directory: &Path) -> Option<&Serving> {
self.libraries
.iter()
.find(|(served, _)| served.directory == directory)
.map(|(_, serving)| serving)
}
fn parse(bytes: &[u8]) -> Option<Self> {
let json: Json = serde_json::from_slice(bytes).ok()?;
let libraries = json["libraries"]
.as_array()?
.iter()
.map(|library| {
let serving =
Serving::from_word(library["state"].as_str()?, library["error"].as_str())?;
Some((parse_served(library)?, serving))
})
.collect::<Option<_>>()?;
Some(Self {
version: json["version"].as_str()?.to_owned(),
libraries,
})
}
fn write(&self, settings: &Path) -> Result<(), NodeError> {
let mut libraries = Vec::new();
for (served, serving) in &self.libraries {
let mut library = served_json(served)?;
library["state"] = json!(serving.word());
if let Some(error) = serving.error() {
library["error"] = json!(error);
}
libraries.push(library);
}
let json = json!({"version": self.version, "libraries": libraries});
write_file(
&settings.join(STATUS),
&serde_json::to_vec_pretty(&json).unwrap_or_default(),
)
}
}
pub fn service_running(settings: &Path) -> Result<bool, NodeError> {
let path = settings.join(RUNNING);
if !path.exists() {
return Ok(false);
}
let file = open_lock(&path)?;
Ok(!try_alone(&file, &path)?)
}
#[must_use]
pub fn service_version(program: &Path) -> Option<String> {
let mut child = Command::new(program)
.arg("--version")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let started = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => break,
Ok(None) if started.elapsed() < VERSION_WAIT => std::thread::sleep(STEP),
_ => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
let mut told = String::new();
child.stdout?.read_to_string(&mut told).ok()?;
let version = told.trim().strip_prefix(SERVICE_PROGRAM)?.trim();
(!version.is_empty()).then(|| version.to_owned())
}
#[must_use]
pub fn newer(a: &str, b: &str) -> bool {
let numbers = |version: &str| -> Vec<u64> {
version
.split(['.', '-', '+'])
.map_while(|part| part.parse().ok())
.collect()
};
numbers(a) > numbers(b)
}
pub fn name_own_copy(
settings: &Path,
own: &Path,
version_of: &VersionOf<'_>,
entry: Option<&LoginEntry>,
) -> Result<bool, NodeError> {
let ((named, _), pointed) = AtLogin::edit_and(
settings,
|list| name_in(list, own, version_of),
|_, (named, program)| match entry {
Some(entry) if *named => entry.point(program).map(|_| ()),
_ => Ok(()),
},
)?;
pointed?;
Ok(named)
}
fn name_in(list: &mut AtLogin, own: &Path, version_of: &VersionOf<'_>) -> (bool, PathBuf) {
let replace = match list.program.as_deref() {
None => true,
Some(listed) if same_file(listed, own) => false,
Some(listed) if !listed.is_file() => true,
Some(listed) => match (version_of(own), version_of(listed)) {
(Some(own), Some(listed)) => newer(&own, &listed),
_ => false,
},
};
let program = match &list.program {
Some(listed) if !replace => listed.clone(),
_ => own.to_owned(),
};
list.program = Some(program.clone());
(replace, program)
}
pub fn start_service(program: &Path) -> Result<(), NodeError> {
let mut command = Command::new(program);
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
command.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}
let mut child = command.spawn().map_err(NodeError::file(program))?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}
pub type VersionOf<'a> = dyn Fn(&Path) -> Option<String> + 'a;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EntryOutcome {
NoEntry,
On(PathBuf),
Off(PathBuf),
Failed(String),
}
impl EntryOutcome {
#[must_use]
pub fn word(&self) -> Option<&'static str> {
match self {
Self::NoEntry => None,
Self::On(_) => Some("on"),
Self::Off(_) => Some("off"),
Self::Failed(_) => Some("failed"),
}
}
#[must_use]
pub fn error(&self) -> Option<&str> {
match self {
Self::Failed(error) => Some(error),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TurnedOn {
pub start: Option<PathBuf>,
pub entry: EntryOutcome,
}
pub fn turn_on(
settings: &Path,
served: Served,
(own, version_of): (&Path, &VersionOf<'_>),
entry: Option<&LoginEntry>,
) -> Result<TurnedOn, NodeError> {
if !matches!(
Library::protection(&served.directory)?,
Protection::Keystore { .. }
) {
return Err(NodeError::NotInKeystore);
}
let ((named, program), entry) = AtLogin::edit_and(
settings,
|list| {
list.add(served);
name_in(list, own, version_of)
},
|_, (_, program)| match entry {
None => EntryOutcome::NoEntry,
Some(entry) => match entry.make(program) {
Ok(EntryState::On(program)) => EntryOutcome::On(program),
Ok(EntryState::Off(program)) => EntryOutcome::Off(program),
Ok(EntryState::Missing) => {
EntryOutcome::Failed("it does not read back as written".to_owned())
}
Err(error) => EntryOutcome::Failed(error.to_string()),
},
},
)?;
let start = named || !service_running(settings)?;
Ok(TurnedOn {
start: start.then_some(program),
entry,
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TurnedOff {
pub removed: bool,
pub entry_failed: Option<String>,
}
pub fn turn_off(
settings: &Path,
(directory, replica): (&Path, Option<EntityId>),
entry: Option<&LoginEntry>,
) -> Result<TurnedOff, NodeError> {
if !settings.join(LIST).exists() {
return Ok(TurnedOff {
removed: false,
entry_failed: None,
});
}
let (removed, entry_failed) = AtLogin::edit_and(
settings,
|list| {
list.remove(directory) || replica.is_some_and(|replica| list.remove_replica(replica))
},
|list, _| match entry {
Some(entry) if list.libraries.is_empty() => {
entry.remove().err().map(|error| error.to_string())
}
_ => None,
},
)?;
Ok(TurnedOff {
removed,
entry_failed,
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AtLoginStatus {
pub on: bool,
pub serving: Option<Serving>,
pub entry: Option<Result<EntryState, String>>,
pub listed: Option<PathBuf>,
}
impl AtLoginStatus {
#[must_use]
pub fn entry_stale(&self) -> bool {
match &self.entry {
Some(Ok(EntryState::On(program) | EntryState::Off(program))) => {
self.listed.as_ref() != Some(program) || !program.is_file()
}
_ => false,
}
}
#[must_use]
pub fn entry_word(&self) -> Option<&'static str> {
Some(match &self.entry {
None => return None,
Some(Err(_)) => "unreadable",
Some(Ok(EntryState::Off(_))) => "off",
Some(Ok(EntryState::Missing)) => "missing",
Some(Ok(EntryState::On(_))) if self.entry_stale() => "stale",
Some(Ok(EntryState::On(_))) => "on",
})
}
}
#[must_use]
pub fn status(
settings: &Path,
(directory, replica): (&Path, Option<EntityId>),
entry: Option<&LoginEntry>,
) -> AtLoginStatus {
let list = AtLogin::read(settings).unwrap_or_default();
let listed = list.find(directory).cloned().or_else(|| {
let replica = replica?;
list.libraries
.iter()
.find(|listed| listed.replica == replica)
.cloned()
});
let Some(listed) = listed else {
return AtLoginStatus {
on: false,
serving: None,
entry: None,
listed: list.program,
};
};
let serving = service_running(settings).unwrap_or(false).then(|| {
ServiceStatus::read(settings)
.ok()
.flatten()
.and_then(|status| status.of(&listed.directory).cloned())
.unwrap_or(Serving::Starting)
});
AtLoginStatus {
on: true,
serving,
entry: entry.map(|entry| entry.state().map_err(|error| error.to_string())),
listed: list.program,
}
}
pub fn app_started(
settings: &Path,
own: &Path,
version_of: &VersionOf<'_>,
entry: Option<&LoginEntry>,
) -> Result<Option<PathBuf>, NodeError> {
if !settings.join(LIST).exists() || AtLogin::read(settings)?.libraries.is_empty() {
return Ok(None);
}
if let Some(entry) = entry
&& !matches!(entry.state()?, EntryState::On(_))
{
return Ok(None);
}
let named = name_own_copy(settings, own, version_of, entry)?;
let start = named || !service_running(settings)?;
Ok(AtLogin::read(settings)?.program.filter(|_| start))
}
pub type KeyringLocked = dyn Fn(&str, &str) -> bool + Send + Sync;
#[derive(Clone)]
pub struct ServiceOptions {
pub program: PathBuf,
pub background: BackgroundOptions,
pub locked: Arc<KeyringLocked>,
pub look: Duration,
pub entry: Option<LoginEntry>,
}
impl ServiceOptions {
#[must_use]
pub fn new(program: PathBuf, background: BackgroundOptions) -> Self {
Self {
program,
background,
locked: Arc::new(|_, _| false),
look: Duration::from_secs(2),
entry: None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ServiceEnded {
Stopped,
Empty,
NamesAnother,
}
pub fn serve_at_login<R: CryptoRng + Send + 'static>(
settings: &Path,
options: &ServiceOptions,
now: impl Fn() -> u64 + Send + Sync + 'static,
rng: impl Fn() -> R + Send + Sync + 'static,
stop: &AtomicBool,
) -> Result<ServiceEnded, NodeError> {
fs::create_dir_all(settings).map_err(NodeError::file(settings))?;
let path = settings.join(RUNNING);
let shared = Shared {
settings: settings.to_owned(),
options: options.clone(),
now: Arc::new(now),
rng: Arc::new(rng),
};
loop {
let running = open_lock(&path)?;
loop {
if take_alone(&running, &path)? {
break;
}
if !names(&AtLogin::read(settings)?, &options.program) {
return Ok(ServiceEnded::NamesAnother);
}
if pause(options.look, stop) {
return Ok(ServiceEnded::Stopped);
}
}
let (ended, workers) = serve(&shared, stop);
for worker in workers.values() {
worker.stop.store(true, Ordering::SeqCst);
}
let _ = fs::remove_file(settings.join(STATUS));
drop(running);
drop(workers);
let again = ended == ServiceEnded::Empty
&& AtLogin::read(settings)
.is_ok_and(|list| !list.libraries.is_empty() && names(&list, &options.program))
&& !service_running(settings)?;
if !again {
return Ok(ended);
}
}
}
fn serve<R: CryptoRng + Send + 'static>(
shared: &Shared<R>,
stop: &AtomicBool,
) -> (ServiceEnded, BTreeMap<PathBuf, Worker>) {
let (settings, options) = (shared.settings.as_path(), &shared.options);
let mut workers: BTreeMap<PathBuf, Worker> = BTreeMap::new();
let mut written = None;
let mut list = AtLogin::default();
let ended = loop {
if stop.load(Ordering::SeqCst) {
break ServiceEnded::Stopped;
}
if let Ok(read) = AtLogin::read(settings) {
list = read;
}
if !names(&list, &options.program) {
break ServiceEnded::NamesAnother;
}
if list.libraries.is_empty() {
break ServiceEnded::Empty;
}
workers.retain(|directory, worker| {
list.find(directory)
.is_some_and(|listed| listed.replica == worker.served.replica)
});
for served in &list.libraries {
if !workers.contains_key(&served.directory) {
let worker = Worker::start(served.clone(), shared);
workers.insert(served.directory.clone(), worker);
}
}
let status = ServiceStatus {
version: ENGINE_VERSION.to_owned(),
libraries: list
.libraries
.iter()
.filter_map(|served| {
let worker = workers.get(&served.directory)?;
Some((served.clone(), locked(&worker.serving).clone()))
})
.collect(),
};
if written.as_ref() != Some(&status) && status.write(settings).is_ok() {
written = Some(status);
}
if pause(options.look.min(Duration::from_secs(1)), stop) {
break ServiceEnded::Stopped;
}
};
(ended, workers)
}
type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
type Randomness<R> = Arc<dyn Fn() -> R + Send + Sync>;
struct Shared<R> {
settings: PathBuf,
options: ServiceOptions,
now: Clock,
rng: Randomness<R>,
}
struct Worker {
served: Served,
stop: Arc<AtomicBool>,
serving: Arc<Mutex<Serving>>,
thread: Option<JoinHandle<()>>,
}
impl Worker {
fn start<R: CryptoRng + Send + 'static>(served: Served, shared: &Shared<R>) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let serving = Arc::new(Mutex::new(Serving::Starting));
let thread = {
let (served, stop, serving) = (served.clone(), Arc::clone(&stop), Arc::clone(&serving));
let (settings, options) = (shared.settings.clone(), shared.options.clone());
let (now, rng) = (Arc::clone(&shared.now), Arc::clone(&shared.rng));
std::thread::spawn(move || {
let context = (settings.as_path(), &options);
serve_library(&served, context, (&now, &rng), &stop, &serving);
})
};
Self {
served,
stop,
serving,
thread: Some(thread),
}
}
}
impl Drop for Worker {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
fn serve_library<R: CryptoRng + Send + 'static>(
served: &Served,
(settings, options): (&Path, &ServiceOptions),
(now, rng): (&Clock, &Randomness<R>),
stop: &AtomicBool,
serving: &Mutex<Serving>,
) {
let mut wait = options.look;
let again = |wait: &mut Duration| {
let stopped = pause(*wait, stop);
*wait = (*wait * 2).min(LONGEST_WAIT);
stopped
};
while !stop.load(Ordering::SeqCst) {
let closed = match prepare(served, options.locked.as_ref()) {
Ok(closed) => closed,
Err(Cannot::Serve(Serving::WaitingForKeyring)) => {
*locked(serving) = Serving::WaitingForKeyring;
if pause(options.look, stop) {
return;
}
continue;
}
Err(Cannot::Serve(cannot)) => {
*locked(serving) = cannot;
if again(&mut wait) {
return;
}
continue;
}
Err(Cannot::Passphrase) => {
*locked(serving) = Serving::NoKey;
let _ = turn_off(settings, (&served.directory, None), options.entry.as_ref());
if again(&mut wait) {
return;
}
continue;
}
};
let background = {
let (now, rng) = (Arc::clone(now), Arc::clone(rng));
Background::start(
closed,
options.background.clone(),
move || now(),
move || rng(),
)
};
let mut held = false;
loop {
let state = background.state();
held |= state.holding;
*locked(serving) = match (state.holding, state.failed) {
(true, _) => Serving::Syncing,
(false, Some(failed)) => Serving::Failed(failed),
(false, None) => Serving::Waiting,
};
if stop.load(Ordering::SeqCst) || background.ended() {
break;
}
std::thread::sleep(STEP);
}
background.wait();
if held {
wait = options.look;
}
if again(&mut wait) {
return;
}
}
}
enum Cannot {
Serve(Serving),
Passphrase,
}
fn prepare(served: &Served, keyring_locked: &KeyringLocked) -> Result<Closed, Cannot> {
let failed = |error: NodeError| {
Cannot::Serve(match error {
NodeError::NoLibrary | NodeError::Copied | NodeError::SeveralHere(_) => {
Serving::NotHere
}
NodeError::Keys(KeysError::Keystore(keyring_core::Error::NoEntry)) => Serving::NoKey,
error => Serving::Failed(error.to_string()),
})
};
let Protection::Keystore { service, account } =
Library::protection(&served.directory).map_err(failed)?
else {
return Err(Cannot::Passphrase);
};
if keyring_locked(&service, &account) {
return Err(Cannot::Serve(Serving::WaitingForKeyring));
}
let library = Library::open(&served.directory, &Unlocker::Keystore).map_err(failed)?;
let here = library
.replicas()
.map_err(failed)?
.into_iter()
.find(|replica| replica.this)
.map(|replica| replica.id);
if here != Some(served.replica) {
return Err(Cannot::Serve(Serving::NotHere));
}
Ok(library.close().without_secrets())
}
fn names(list: &AtLogin, program: &Path) -> bool {
list.program
.as_deref()
.is_some_and(|listed| same_file(listed, program))
}
fn same_file(a: &Path, b: &Path) -> bool {
a == b
|| matches!(
(fs::canonicalize(a), fs::canonicalize(b)),
(Ok(a), Ok(b)) if a == b
)
}
fn pause(wait: Duration, stop: &AtomicBool) -> bool {
let paused = Instant::now();
while paused.elapsed() < wait {
if stop.load(Ordering::SeqCst) {
return true;
}
std::thread::sleep(STEP.min(wait));
}
stop.load(Ordering::SeqCst)
}
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
fn open_lock(path: &Path) -> Result<File, NodeError> {
OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(path)
.map_err(NodeError::file(path))
}
fn try_alone(file: &File, path: &Path) -> Result<bool, NodeError> {
match file.try_lock() {
Ok(()) => Ok(true),
Err(TryLockError::WouldBlock) => Ok(false),
Err(TryLockError::Error(error)) => Err(NodeError::file(path)(error)),
}
}
fn take_alone(file: &File, path: &Path) -> Result<bool, NodeError> {
let tried = Instant::now();
loop {
if try_alone(file, path)? {
return Ok(true);
}
if tried.elapsed() >= LOOKING {
return Ok(false);
}
std::thread::sleep(Duration::from_millis(5));
}
}
const ENTRY_NAME: &str = "NibKeep Sync";
#[derive(Clone, Debug)]
pub struct LoginEntry {
place: EntryPlace,
}
#[derive(Clone, Debug)]
enum EntryPlace {
Autostart(PathBuf),
#[cfg(windows)]
Run {
key: String,
approved: String,
name: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum EntryState {
Missing,
On(PathBuf),
Off(PathBuf),
}
impl LoginEntry {
#[cfg(windows)]
#[must_use]
pub fn platform() -> Option<Self> {
if kept_away() {
return None;
}
Some(Self::run_key(
r"Software\Microsoft\Windows\CurrentVersion\Run",
r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run",
&format!("{ENTRY_NAME} {}", computer_name()),
))
}
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
))]
#[must_use]
pub fn platform() -> Option<Self> {
if kept_away() {
return None;
}
directories::BaseDirs::new().map(|base| {
let file = format!("{SERVICE_PROGRAM}-{}.desktop", computer_name());
Self::autostart(base.config_dir().join("autostart").join(file))
})
}
#[cfg(not(any(
windows,
all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
)
)))]
#[must_use]
pub fn platform() -> Option<Self> {
None
}
#[must_use]
pub fn autostart(file: PathBuf) -> Self {
Self {
place: EntryPlace::Autostart(file),
}
}
#[cfg(windows)]
#[must_use]
pub fn run_key(key: &str, approved: &str, name: &str) -> Self {
Self {
place: EntryPlace::Run {
key: key.to_owned(),
approved: approved.to_owned(),
name: name.to_owned(),
},
}
}
pub fn state(&self) -> Result<EntryState, NodeError> {
match &self.place {
EntryPlace::Autostart(file) => Ok(autostart::state(autostart::read(file)?.as_deref())),
#[cfg(windows)]
EntryPlace::Run {
key,
approved,
name,
} => run::state(key, approved, name),
}
}
pub fn make(&self, program: &Path) -> Result<EntryState, NodeError> {
self.write(program, true)
}
pub fn point(&self, program: &Path) -> Result<EntryState, NodeError> {
self.write(program, false)
}
pub fn remove(&self) -> Result<(), NodeError> {
match &self.place {
EntryPlace::Autostart(file) => match fs::remove_file(file) {
Err(error) if error.kind() != io::ErrorKind::NotFound => {
Err(NodeError::file(file)(error))
}
_ => Ok(()),
},
#[cfg(windows)]
EntryPlace::Run {
key,
approved,
name,
} => run::remove(key, approved, name),
}
}
fn write(&self, program: &Path, new: bool) -> Result<EntryState, NodeError> {
match &self.place {
EntryPlace::Autostart(file) => {
let text = autostart::read(file)?;
let written = match (autostart::state(text.as_deref()), &text) {
(EntryState::On(listed) | EntryState::Off(listed), _) if listed == program => {
return Ok(autostart::state(text.as_deref()));
}
(EntryState::Missing, _) if !new => return Ok(EntryState::Missing),
(EntryState::Missing, _) | (_, None) => autostart::new(program),
(_, Some(text)) => autostart::pointed(text, program),
};
let target = fs::canonicalize(file).unwrap_or_else(|_| file.clone());
if let Some(folder) = target.parent() {
fs::create_dir_all(folder).map_err(NodeError::file(folder))?;
}
write_file(&target, written.as_bytes())?;
Ok(autostart::state(Some(&written)))
}
#[cfg(windows)]
EntryPlace::Run {
key,
approved,
name,
} => {
let state = run::state(key, approved, name)?;
match &state {
EntryState::On(listed) | EntryState::Off(listed) if listed == program => {
return Ok(state);
}
EntryState::Missing if !new => return Ok(state),
_ => {}
}
let anew = state == EntryState::Missing;
run::write((key, approved, name), program, anew)?;
run::state(key, approved, name)
}
}
}
}
#[cfg(any(
windows,
all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "android"))
)
))]
fn kept_away() -> bool {
["NIBKEEP_NO_LOGIN_ENTRY", "NIBKEEP_STATE"]
.iter()
.any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
}
mod autostart {
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::{ENTRY_NAME, EntryState};
use crate::NodeError;
pub(super) fn read(file: &Path) -> Result<Option<String>, NodeError> {
match fs::read(file) {
Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(NodeError::file(file)(error)),
}
}
pub(super) fn new(program: &Path) -> String {
format!(
"[Desktop Entry]\nType=Application\nName={ENTRY_NAME}\nComment=Syncs your NibKeep libraries with your other devices while you are logged in\nExec={}\nTerminal=false\nX-GNOME-Autostart-enabled=true\n",
exec(program)
)
}
fn lines(text: &str) -> impl Iterator<Item = (bool, &str)> {
let text = text.strip_prefix('\u{feff}').unwrap_or(text);
let mut group = None;
text.lines().map(move |line| {
if line.starts_with('[') {
group = Some(line.trim());
}
(
group == Some("[Desktop Entry]") && !line.starts_with('['),
line,
)
})
}
pub(super) fn pointed(text: &str, program: &Path) -> String {
let exec = format!("Exec={}\n", exec(program));
let has_exec = lines(text).any(|(entry, line)| entry && key(line) == Some("Exec"));
let mut pointed = String::new();
for (entry, line) in lines(text) {
if entry && key(line) == Some("Exec") {
pointed.push_str(&exec);
continue;
}
pointed.push_str(line);
pointed.push('\n');
if !has_exec && line.trim() == "[Desktop Entry]" {
pointed.push_str(&exec);
}
}
pointed
}
pub(super) fn state(text: Option<&str>) -> EntryState {
let Some(text) = text else {
return EntryState::Missing;
};
let header = lines(text).any(|(_, line)| line.trim() == "[Desktop Entry]");
let (mut program, mut off) = (PathBuf::new(), false);
for (_, line) in lines(text).filter(|(entry, _)| *entry) {
let value = line.split_once('=').map_or("", |(_, value)| value.trim());
match key(line) {
Some("Exec") => program = parse_exec(value).unwrap_or_default(),
Some("Hidden") => off |= value == "true",
Some("X-GNOME-Autostart-enabled") => off |= value == "false",
_ => {}
}
}
match (header, off) {
(false, _) => EntryState::Missing,
(true, false) => EntryState::On(program),
(true, true) => EntryState::Off(program),
}
}
fn key(line: &str) -> Option<&str> {
line.split_once('=').map(|(key, _)| key.trim())
}
fn exec(program: &Path) -> String {
let mut quoted = String::from("\"");
for character in program.to_string_lossy().chars() {
if matches!(character, '"' | '`' | '$' | '\\') {
quoted.push('\\');
}
quoted.push(character);
}
quoted.push('"');
quoted.replace('\\', "\\\\").replace('%', "%%")
}
fn parse_exec(value: &str) -> Option<PathBuf> {
let mut unescaped = String::new();
let mut characters = value.chars();
while let Some(character) = characters.next() {
match (character, characters.clone().next()) {
('\\', Some('\\')) => {
unescaped.push('\\');
characters.next();
}
('\\', Some('s')) => {
unescaped.push(' ');
characters.next();
}
('%', Some('%')) => {
unescaped.push('%');
characters.next();
}
_ => unescaped.push(character),
}
}
let mut program = String::new();
let mut characters = unescaped.chars();
if unescaped.starts_with('"') {
characters.next();
while let Some(character) = characters.next() {
match character {
'\\' => program.push(characters.next()?),
'"' => break,
_ => program.push(character),
}
}
} else {
unescaped.split(' ').next()?.clone_into(&mut program);
}
(!program.is_empty()).then(|| PathBuf::from(program))
}
}
#[cfg(windows)]
mod run {
use std::io;
use std::path::{Path, PathBuf};
use winreg::RegKey;
use winreg::enums::HKEY_CURRENT_USER;
use super::EntryState;
use crate::NodeError;
fn failed(key: &str) -> impl FnOnce(io::Error) -> NodeError {
let key = key.to_owned();
move |error| NodeError::file(Path::new(&format!(r"HKCU\{key}")))(error)
}
pub(super) fn state(key: &str, approved: &str, name: &str) -> Result<EntryState, NodeError> {
let user = RegKey::predef(HKEY_CURRENT_USER);
let value: String = match user.open_subkey(key).and_then(|run| run.get_value(name)) {
Ok(value) => value,
Err(error) if error.kind() == io::ErrorKind::NotFound => {
return Ok(EntryState::Missing);
}
Err(error) => return Err(failed(key)(error)),
};
let program = PathBuf::from(value.trim().trim_matches('"'));
let off = user
.open_subkey(approved)
.and_then(|approved| approved.get_raw_value(name))
.is_ok_and(|value| value.bytes.first().is_some_and(|first| first & 1 == 1));
Ok(if off {
EntryState::Off(program)
} else {
EntryState::On(program)
})
}
pub(super) fn write(
(key, approved, name): (&str, &str, &str),
program: &Path,
anew: bool,
) -> Result<(), NodeError> {
if anew {
let removed = RegKey::predef(HKEY_CURRENT_USER)
.open_subkey_with_flags(approved, winreg::enums::KEY_SET_VALUE)
.and_then(|opened| opened.delete_value(name));
if let Err(error) = removed
&& error.kind() != io::ErrorKind::NotFound
{
return Err(failed(approved)(error));
}
}
let (run, _) = RegKey::predef(HKEY_CURRENT_USER)
.create_subkey(key)
.map_err(failed(key))?;
run.set_value(name, &format!("\"{}\"", program.display()))
.map_err(failed(key))
}
pub(super) fn remove(key: &str, approved: &str, name: &str) -> Result<(), NodeError> {
let user = RegKey::predef(HKEY_CURRENT_USER);
for key in [key, approved] {
let removed = user
.open_subkey_with_flags(key, winreg::enums::KEY_SET_VALUE)
.and_then(|opened| opened.delete_value(name));
match removed {
Err(error) if error.kind() != io::ErrorKind::NotFound => {
return Err(failed(key)(error));
}
_ => {}
}
}
Ok(())
}
}
#[cfg(windows)]
pub mod firewall {
use std::process::{Command, Stdio};
pub const RULE: &str = "NibKeep";
#[must_use]
pub fn has_rule() -> bool {
powershell(
"$rules = @(Get-NetFirewallRule -DisplayName NibKeep -ErrorAction SilentlyContinue | Where-Object { $_.Enabled -eq 'True' -and $_.Action -eq 'Allow' -and $_.Direction -eq 'Inbound' -and \"$($_.Profile)\" -match 'Private|Any' } | Where-Object { $filter = $_ | Get-NetFirewallPortFilter; $ports = @($filter.LocalPort); ($filter.Protocol -eq 'UDP') -and ($ports -contains '5353') -and ($ports -contains '53300-53309') }); if ($rules.Count -gt 0) { exit 0 } else { exit 1 }",
)
}
#[must_use]
pub fn add_rule() -> bool {
let commands = "/c netsh advfirewall firewall delete rule name=NibKeep & netsh advfirewall firewall add rule name=NibKeep dir=in action=allow protocol=UDP localport=53300-53309,5353 profile=private";
let _ = powershell(&format!(
"Start-Process -FilePath cmd -ArgumentList '{commands}' -Verb RunAs -Wait -WindowStyle Hidden"
));
has_rule()
}
fn powershell(script: &str) -> bool {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
Command::new("powershell")
.creation_flags(CREATE_NO_WINDOW)
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.is_ok_and(|status| status.success())
}
}