Skip to main content

nibkeep_node/
at_login.rs

1//! Syncing from login ([technical design](../../../docs/Technical-design.md#106-syncing-from-login)):
2//! `nibkeep-sync`, a program without a window that starts when the person logs in, holds the
3//! sync role of the libraries they chose, as an app holds it while unlocked. Every NibKeep
4//! program reads and writes the list of those libraries alike, in the person's folder of
5//! settings; the service follows it, and writes beside it what it does for each.
6
7use std::collections::BTreeMap;
8use std::fs::{self, File, OpenOptions, TryLockError};
9use std::io::{self, Read};
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14use std::thread::JoinHandle;
15use std::time::{Duration, Instant};
16
17use nibkeep_base::EntityId;
18use nibkeep_crypto::rand_core::CryptoRng;
19use nibkeep_keys::{KeysError, Protection, Unlocker};
20use serde_json::{Value as Json, json};
21
22pub mod app;
23
24use crate::info::write_file;
25use crate::{Background, BackgroundOptions, Closed, Library, NodeError};
26
27/// The list of libraries that the service syncs from login, and the copy that serves them.
28const LIST: &str = "sync-at-login";
29
30/// The file that a program locks while it changes the list.
31const LIST_LOCK: &str = "sync-at-login.lock";
32
33/// The file that the running service locks.
34const RUNNING: &str = "sync-at-login.running";
35
36/// What the service does for each library.
37const STATUS: &str = "sync-at-login.status";
38
39pub use crate::engines::ENGINE_VERSION;
40
41/// What the service names itself in a replica's records, and the name of its program.
42pub const SERVICE_PROGRAM: &str = "nibkeep-sync";
43
44/// How long a look at whether the service runs may hold its lock, which the service then
45/// waits out.
46const LOOKING: Duration = Duration::from_millis(50);
47
48/// How long a copy of `nibkeep-sync` may take to tell its version.
49const VERSION_WAIT: Duration = Duration::from_secs(5);
50
51/// How often a library's thread looks at what its holder does.
52const STEP: Duration = Duration::from_millis(100);
53
54/// How long a library's thread waits at most before it tries again to serve a library that
55/// it could not.
56const LONGEST_WAIT: Duration = Duration::from_mins(1);
57
58/// This computer's folder within NibKeep's folder of state for the person, where the list
59/// and the files beside it are: in `~/.local/state/nibkeep` on Linux (or
60/// `$XDG_STATE_HOME/nibkeep`), `%LOCALAPPDATA%\NibKeep` on Windows, which no roaming profile
61/// carries, and `~/Library/Application Support/NibKeep` on macOS. It is named by a hash of
62/// the computer's ID, so that a program that syncs the home folder between computers makes
63/// no two of them write the same file. Or the folder that `NIBKEEP_STATE` names, as tests
64/// name one. `None` where there is no home folder.
65#[cfg(not(any(target_os = "android", target_os = "ios")))]
66#[must_use]
67pub fn settings_folder() -> Option<PathBuf> {
68	if let Some(named) = std::env::var_os("NIBKEEP_STATE").filter(|named| !named.is_empty()) {
69		return Some(PathBuf::from(named));
70	}
71	let base = directories::BaseDirs::new()?;
72	let nibkeep = if cfg!(any(windows, target_vendor = "apple")) {
73		base.data_local_dir().join("NibKeep")
74	} else {
75		base.state_dir()?.join("nibkeep")
76	};
77	Some(nibkeep.join(computer_name()))
78}
79
80/// The name of this computer's folder of state, and of its login entry: the first 8 bytes,
81/// in hexadecimal, of a hash of the computer's ID, or `computer` where there is none.
82#[cfg(not(any(target_os = "android", target_os = "ios")))]
83fn computer_name() -> String {
84	use std::fmt::Write as _;
85	/// The context of the hash that names this computer's folder.
86	const COMPUTER_CONTEXT: &str = "nibkeep 2026-11 computer's folder of state";
87	crate::place::computer_id().map_or_else(
88		|| "computer".to_owned(),
89		|id| {
90			let hash = blake3::derive_key(COMPUTER_CONTEXT, &id);
91			hash[..8].iter().fold(String::new(), |mut hex, byte| {
92				let _ = write!(hex, "{byte:02x}");
93				hex
94			})
95		},
96	)
97}
98
99/// A library that the service syncs from login.
100#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct Served {
102	/// The ID of this computer's replica of it, which the replica that is here in its
103	/// directory must have: a list that a program syncing dotfolders brought from another
104	/// computer names replicas that are not here.
105	pub replica: EntityId,
106	/// The library's directory, as [`Library::open`] takes it.
107	pub directory: PathBuf,
108}
109
110/// The list of libraries to sync from login, and the copy of `nibkeep-sync` that serves
111/// them.
112#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct AtLogin {
114	/// The copy of `nibkeep-sync` that serves them, which the login entry starts.
115	pub program: Option<PathBuf>,
116	/// The libraries.
117	pub libraries: Vec<Served>,
118}
119
120impl AtLogin {
121	/// Reads the list in the folder of settings: empty if there is none.
122	///
123	/// # Errors
124	///
125	/// Returns an error if the list cannot be read, or does not read as a list.
126	pub fn read(settings: &Path) -> Result<Self, NodeError> {
127		let path = settings.join(LIST);
128		match fs::read(&path) {
129			Ok(bytes) => Self::parse(&bytes).ok_or_else(|| {
130				NodeError::Damaged(format!("{} is not a list of libraries", path.display()))
131			}),
132			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
133			Err(error) => Err(NodeError::file(&path)(error)),
134		}
135	}
136
137	/// Changes the list as `change` does, and writes it if it changed: while holding the
138	/// lock on `sync-at-login.lock`, so that two programs never undo each other's changes.
139	/// Returns what `change` returns.
140	///
141	/// # Errors
142	///
143	/// Returns an error if the list cannot be read, locked or written, or names a path that
144	/// is not Unicode.
145	pub fn edit<T>(settings: &Path, change: impl FnOnce(&mut Self) -> T) -> Result<T, NodeError> {
146		Self::edit_and(settings, change, |_, _| ()).map(|(changed, ())| changed)
147	}
148
149	/// Changes the list as [`AtLogin::edit`] does, and once it is written, runs `then` on
150	/// it and on what `change` returned, still holding the lock: as for the login entry,
151	/// which changes with the list, and never before the list is written. Returns what both
152	/// return.
153	fn edit_and<T, U>(
154		settings: &Path,
155		change: impl FnOnce(&mut Self) -> T,
156		then: impl FnOnce(&Self, &T) -> U,
157	) -> Result<(T, U), NodeError> {
158		fs::create_dir_all(settings).map_err(NodeError::file(settings))?;
159		let path = settings.join(LIST_LOCK);
160		let lock = open_lock(&path)?;
161		lock.lock().map_err(NodeError::file(&path))?;
162		let mut list = Self::read(settings)?;
163		let before = list.clone();
164		let changed = change(&mut list);
165		if list != before {
166			write_file(&settings.join(LIST), &list.to_bytes()?)?;
167		}
168		let then = then(&list, &changed);
169		Ok((changed, then))
170	}
171
172	/// Adds a library, in place of any with its directory or replica.
173	pub fn add(&mut self, served: Served) {
174		self.libraries.retain(|listed| {
175			listed.replica != served.replica && listed.directory != served.directory
176		});
177		self.libraries.push(served);
178	}
179
180	/// Removes the library in `directory`: whether the list had it.
181	pub fn remove(&mut self, directory: &Path) -> bool {
182		let before = self.libraries.len();
183		self.libraries
184			.retain(|listed| listed.directory != directory);
185		self.libraries.len() != before
186	}
187
188	/// Removes the library whose replica on this computer is `replica`: whether the list had
189	/// it.
190	pub fn remove_replica(&mut self, replica: EntityId) -> bool {
191		let before = self.libraries.len();
192		self.libraries.retain(|listed| listed.replica != replica);
193		self.libraries.len() != before
194	}
195
196	/// The library in `directory`, if the list has it.
197	#[must_use]
198	pub fn find(&self, directory: &Path) -> Option<&Served> {
199		self.libraries
200			.iter()
201			.find(|listed| listed.directory == directory)
202	}
203
204	fn parse(bytes: &[u8]) -> Option<Self> {
205		let json: Json = serde_json::from_slice(bytes).ok()?;
206		let program = match &json["program"] {
207			Json::Null => None,
208			program => Some(PathBuf::from(program.as_str()?)),
209		};
210		let libraries = json["libraries"]
211			.as_array()?
212			.iter()
213			.map(parse_served)
214			.collect::<Option<_>>()?;
215		Some(Self { program, libraries })
216	}
217
218	fn to_bytes(&self) -> Result<Vec<u8>, NodeError> {
219		let program = self.program.as_deref().map(unicode).transpose()?;
220		let libraries = self
221			.libraries
222			.iter()
223			.map(served_json)
224			.collect::<Result<Vec<_>, _>>()?;
225		let json = json!({"program": program, "libraries": libraries});
226		Ok(serde_json::to_vec_pretty(&json).unwrap_or_default())
227	}
228}
229
230fn parse_served(json: &Json) -> Option<Served> {
231	Some(Served {
232		replica: json["replica"].as_str()?.parse().ok()?,
233		directory: PathBuf::from(json["directory"].as_str()?),
234	})
235}
236
237fn served_json(served: &Served) -> Result<Json, NodeError> {
238	Ok(json!({
239		"replica": served.replica.to_string(),
240		"directory": unicode(&served.directory)?,
241	}))
242}
243
244fn unicode(path: &Path) -> Result<&str, NodeError> {
245	path.to_str()
246		.ok_or_else(|| NodeError::NotUnicode(path.to_owned()))
247}
248
249/// What the service does for a library.
250#[derive(Clone, Debug, PartialEq, Eq)]
251pub enum Serving {
252	/// It is opening the library, and has not said more yet.
253	Starting,
254	/// It holds the library's sync role, and syncs it.
255	Syncing,
256	/// Another program holds the role, which it takes as soon as that one lets go.
257	Waiting,
258	/// The keystore's entry of the library's key is locked, as a Secret Service is after an
259	/// automatic login, until the person unlocks it.
260	WaitingForKeyring,
261	/// No replica with the listed ID is here in the directory: the folder is gone, holds
262	/// another library, or a copy of another computer's replica.
263	NotHere,
264	/// The library's keys are not in the keystore: a passphrase protects them, or the
265	/// keystore has no key for them.
266	NoKey,
267	/// It failed, as this says; it tries again a while later.
268	Failed(String),
269}
270
271impl Serving {
272	/// How the status file names it.
273	#[must_use]
274	pub fn word(&self) -> &'static str {
275		match self {
276			Self::Starting => "starting",
277			Self::Syncing => "syncing",
278			Self::Waiting => "waiting",
279			Self::WaitingForKeyring => "waiting for the keyring",
280			Self::NotHere => "not here",
281			Self::NoKey => "no key",
282			Self::Failed(_) => "failed",
283		}
284	}
285
286	/// Why it failed, if it did.
287	#[must_use]
288	pub fn error(&self) -> Option<&str> {
289		match self {
290			Self::Failed(error) => Some(error),
291			_ => None,
292		}
293	}
294
295	fn from_word(word: &str, error: Option<&str>) -> Option<Self> {
296		Some(match word {
297			"starting" => Self::Starting,
298			"syncing" => Self::Syncing,
299			"waiting" => Self::Waiting,
300			"waiting for the keyring" => Self::WaitingForKeyring,
301			"not here" => Self::NotHere,
302			"no key" => Self::NoKey,
303			"failed" => Self::Failed(error?.to_owned()),
304			_ => return None,
305		})
306	}
307}
308
309/// What the service does for each library it serves, which it writes beside the list.
310#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct ServiceStatus {
312	/// The engine's version of the copy that runs.
313	pub version: String,
314	/// Each library, and what the service does for it.
315	pub libraries: Vec<(Served, Serving)>,
316}
317
318impl ServiceStatus {
319	/// Reads what the service last wrote: `None` if it wrote nothing, as when none runs.
320	///
321	/// # Errors
322	///
323	/// Returns an error if the file cannot be read, or does not read as a status.
324	pub fn read(settings: &Path) -> Result<Option<Self>, NodeError> {
325		let path = settings.join(STATUS);
326		match fs::read(&path) {
327			Ok(bytes) => Self::parse(&bytes)
328				.map(Some)
329				.ok_or_else(|| NodeError::Damaged(format!("{} is not a status", path.display()))),
330			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
331			Err(error) => Err(NodeError::file(&path)(error)),
332		}
333	}
334
335	/// What it does for the library in `directory`, if it serves it.
336	#[must_use]
337	pub fn of(&self, directory: &Path) -> Option<&Serving> {
338		self.libraries
339			.iter()
340			.find(|(served, _)| served.directory == directory)
341			.map(|(_, serving)| serving)
342	}
343
344	fn parse(bytes: &[u8]) -> Option<Self> {
345		let json: Json = serde_json::from_slice(bytes).ok()?;
346		let libraries = json["libraries"]
347			.as_array()?
348			.iter()
349			.map(|library| {
350				let serving =
351					Serving::from_word(library["state"].as_str()?, library["error"].as_str())?;
352				Some((parse_served(library)?, serving))
353			})
354			.collect::<Option<_>>()?;
355		Some(Self {
356			version: json["version"].as_str()?.to_owned(),
357			libraries,
358		})
359	}
360
361	fn write(&self, settings: &Path) -> Result<(), NodeError> {
362		let mut libraries = Vec::new();
363		for (served, serving) in &self.libraries {
364			let mut library = served_json(served)?;
365			library["state"] = json!(serving.word());
366			if let Some(error) = serving.error() {
367				library["error"] = json!(error);
368			}
369			libraries.push(library);
370		}
371		let json = json!({"version": self.version, "libraries": libraries});
372		write_file(
373			&settings.join(STATUS),
374			&serde_json::to_vec_pretty(&json).unwrap_or_default(),
375		)
376	}
377}
378
379/// Whether a copy of `nibkeep-sync` runs for the person: whether one holds the lock on
380/// `sync-at-login.running`, which this takes for a moment to tell.
381///
382/// # Errors
383///
384/// Returns an error if the lock's file cannot be opened or locked.
385pub fn service_running(settings: &Path) -> Result<bool, NodeError> {
386	let path = settings.join(RUNNING);
387	if !path.exists() {
388		return Ok(false);
389	}
390	let file = open_lock(&path)?;
391	Ok(!try_alone(&file, &path)?)
392}
393
394/// The engine's version that a copy of `nibkeep-sync` tells, or `None` if it tells none
395/// within a few seconds, as one that is gone.
396#[must_use]
397pub fn service_version(program: &Path) -> Option<String> {
398	let mut child = Command::new(program)
399		.arg("--version")
400		.stdin(Stdio::null())
401		.stdout(Stdio::piped())
402		.stderr(Stdio::null())
403		.spawn()
404		.ok()?;
405	let started = Instant::now();
406	loop {
407		match child.try_wait() {
408			Ok(Some(status)) if status.success() => break,
409			Ok(None) if started.elapsed() < VERSION_WAIT => std::thread::sleep(STEP),
410			_ => {
411				let _ = child.kill();
412				let _ = child.wait();
413				return None;
414			}
415		}
416	}
417	let mut told = String::new();
418	child.stdout?.read_to_string(&mut told).ok()?;
419	let version = told.trim().strip_prefix(SERVICE_PROGRAM)?.trim();
420	(!version.is_empty()).then(|| version.to_owned())
421}
422
423/// Whether version `a` is newer than `b`, comparing their numbers in turn.
424#[must_use]
425pub fn newer(a: &str, b: &str) -> bool {
426	let numbers = |version: &str| -> Vec<u64> {
427		version
428			.split(['.', '-', '+'])
429			.map_while(|part| part.parse().ok())
430			.collect()
431	};
432	numbers(a) > numbers(b)
433}
434
435/// Names `own`, this program's copy of `nibkeep-sync`, in the list, where the list names
436/// none, or one that is gone, as after its app was removed, or one older than `own`, as
437/// `version_of` tells of each; and points the login entry at it, if there is one, leaving it
438/// off if the person turned it off: whether it named it. A copy of the same version stays,
439/// so that two programs do not take it from each other, and so does one that does not tell
440/// its version in time, as one that a scanner of viruses holds up.
441///
442/// # Errors
443///
444/// Returns the errors of [`AtLogin::edit`], and of [`LoginEntry::point`] once the list is
445/// written.
446pub fn name_own_copy(
447	settings: &Path,
448	own: &Path,
449	version_of: &VersionOf<'_>,
450	entry: Option<&LoginEntry>,
451) -> Result<bool, NodeError> {
452	let ((named, _), pointed) = AtLogin::edit_and(
453		settings,
454		|list| name_in(list, own, version_of),
455		|_, (named, program)| match entry {
456			Some(entry) if *named => entry.point(program).map(|_| ()),
457			_ => Ok(()),
458		},
459	)?;
460	pointed?;
461	Ok(named)
462}
463
464/// Names `own` in `list`, as [`name_own_copy`] says: whether it did, and the copy that the
465/// list names then.
466fn name_in(list: &mut AtLogin, own: &Path, version_of: &VersionOf<'_>) -> (bool, PathBuf) {
467	let replace = match list.program.as_deref() {
468		None => true,
469		Some(listed) if same_file(listed, own) => false,
470		Some(listed) if !listed.is_file() => true,
471		Some(listed) => match (version_of(own), version_of(listed)) {
472			(Some(own), Some(listed)) => newer(&own, &listed),
473			_ => false,
474		},
475	};
476	let program = match &list.program {
477		Some(listed) if !replace => listed.clone(),
478		_ => own.to_owned(),
479	};
480	list.program = Some(program.clone());
481	(replace, program)
482}
483
484/// Starts a copy of `nibkeep-sync`, apart from this program, so that it runs on when this
485/// one ends.
486///
487/// # Errors
488///
489/// Returns an error if it cannot be started.
490pub fn start_service(program: &Path) -> Result<(), NodeError> {
491	let mut command = Command::new(program);
492	command
493		.stdin(Stdio::null())
494		.stdout(Stdio::null())
495		.stderr(Stdio::null());
496	#[cfg(unix)]
497	{
498		use std::os::unix::process::CommandExt;
499		// Apart from the terminal's group, so that its Ctrl-C does not end it.
500		command.process_group(0);
501	}
502	#[cfg(windows)]
503	{
504		use std::os::windows::process::CommandExt;
505		const DETACHED_PROCESS: u32 = 0x0000_0008;
506		const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
507		command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
508	}
509	let mut child = command.spawn().map_err(NodeError::file(program))?;
510	// Reaped when it ends, if this program, as an app, runs that long.
511	std::thread::spawn(move || {
512		let _ = child.wait();
513	});
514	Ok(())
515}
516
517/// What tells the engine's version of a copy of `nibkeep-sync`, as [`service_version`] does.
518pub type VersionOf<'a> = dyn Fn(&Path) -> Option<String> + 'a;
519
520/// What became of the login entry.
521#[derive(Clone, Debug, PartialEq, Eq)]
522pub enum EntryOutcome {
523	/// The platform has none, as macOS has none yet, or tests keep away from it.
524	NoEntry,
525	/// It starts this program at login.
526	On(PathBuf),
527	/// It would start this program, but the person turned it off.
528	Off(PathBuf),
529	/// It could not be made, as this says.
530	Failed(String),
531}
532
533impl EntryOutcome {
534	/// In a word, as programs show it: `on`, `off` or `failed`; `None` where there is no
535	/// entry.
536	#[must_use]
537	pub fn word(&self) -> Option<&'static str> {
538		match self {
539			Self::NoEntry => None,
540			Self::On(_) => Some("on"),
541			Self::Off(_) => Some("off"),
542			Self::Failed(_) => Some("failed"),
543		}
544	}
545
546	/// Why it could not be made, if it could not.
547	#[must_use]
548	pub fn error(&self) -> Option<&str> {
549		match self {
550			Self::Failed(error) => Some(error),
551			_ => None,
552		}
553	}
554}
555
556/// What turning syncing from login on did.
557#[derive(Clone, Debug, PartialEq, Eq)]
558pub struct TurnedOn {
559	/// The copy of `nibkeep-sync` to start, if any: the one listed, unless one runs; or the
560	/// program's own, just named, which waits for the one that runs to read the list and end.
561	pub start: Option<PathBuf>,
562	/// What became of the login entry.
563	pub entry: EntryOutcome,
564}
565
566/// Turns syncing from login on for a library: adds it to the list; names `own`, this
567/// program's copy of `nibkeep-sync`, if it is newer than the one listed, as `version_of`
568/// tells; and, once the list is written, makes the login entry start the listed copy,
569/// leaving it off if the person turned it off. The entry changes while the list is locked,
570/// so that turning another library off meanwhile never removes it. A login entry that
571/// cannot be made leaves the library on the list, and is told.
572///
573/// # Errors
574///
575/// Returns [`NodeError::NotInKeystore`] if a passphrase protects the library's keys, as
576/// nobody is there to type it at login, and the errors of [`AtLogin::edit`].
577pub fn turn_on(
578	settings: &Path,
579	served: Served,
580	(own, version_of): (&Path, &VersionOf<'_>),
581	entry: Option<&LoginEntry>,
582) -> Result<TurnedOn, NodeError> {
583	if !matches!(
584		Library::protection(&served.directory)?,
585		Protection::Keystore { .. }
586	) {
587		return Err(NodeError::NotInKeystore);
588	}
589	let ((named, program), entry) = AtLogin::edit_and(
590		settings,
591		|list| {
592			list.add(served);
593			name_in(list, own, version_of)
594		},
595		|_, (_, program)| match entry {
596			None => EntryOutcome::NoEntry,
597			Some(entry) => match entry.make(program) {
598				Ok(EntryState::On(program)) => EntryOutcome::On(program),
599				Ok(EntryState::Off(program)) => EntryOutcome::Off(program),
600				Ok(EntryState::Missing) => {
601					EntryOutcome::Failed("it does not read back as written".to_owned())
602				}
603				Err(error) => EntryOutcome::Failed(error.to_string()),
604			},
605		},
606	)?;
607	let start = named || !service_running(settings)?;
608	Ok(TurnedOn {
609		start: start.then_some(program),
610		entry,
611	})
612}
613
614/// What turning syncing from login off did.
615#[derive(Clone, Debug, PartialEq, Eq)]
616pub struct TurnedOff {
617	/// Whether the list had the library.
618	pub removed: bool,
619	/// Why the login entry could not be removed, with the last library, if it could not.
620	pub entry_failed: Option<String>,
621}
622
623/// Turns syncing from login off for the library in `directory`, or, if the list has none
624/// there, for `replica`, as after the library's folder was moved. The service lets go of
625/// its role once it reads the list, and ends if it was the last. Once the list, written,
626/// holds no library, the login entry goes too, while the list is locked; so a later turning
627/// off removes an entry left by one that failed to. Where there is no list, nothing is
628/// written, and the entry is left alone.
629///
630/// # Errors
631///
632/// Returns the errors of [`AtLogin::edit`].
633pub fn turn_off(
634	settings: &Path,
635	(directory, replica): (&Path, Option<EntityId>),
636	entry: Option<&LoginEntry>,
637) -> Result<TurnedOff, NodeError> {
638	if !settings.join(LIST).exists() {
639		return Ok(TurnedOff {
640			removed: false,
641			entry_failed: None,
642		});
643	}
644	let (removed, entry_failed) = AtLogin::edit_and(
645		settings,
646		|list| {
647			list.remove(directory) || replica.is_some_and(|replica| list.remove_replica(replica))
648		},
649		|list, _| match entry {
650			Some(entry) if list.libraries.is_empty() => {
651				entry.remove().err().map(|error| error.to_string())
652			}
653			_ => None,
654		},
655	)?;
656	Ok(TurnedOff {
657		removed,
658		entry_failed,
659	})
660}
661
662/// What syncing from login does for a library, as a program shows it.
663#[derive(Clone, Debug, PartialEq, Eq)]
664pub struct AtLoginStatus {
665	/// Whether the list has the library.
666	pub on: bool,
667	/// What the copy that runs does for it, or `None` where none runs.
668	pub serving: Option<Serving>,
669	/// What the login entry says, where the platform has one, or why it cannot be read.
670	pub entry: Option<Result<EntryState, String>>,
671	/// The copy of `nibkeep-sync` that the list names, which the entry should start.
672	pub listed: Option<PathBuf>,
673}
674
675impl AtLoginStatus {
676	/// Whether the entry starts another program than the copy that the list names, or one
677	/// that is gone.
678	#[must_use]
679	pub fn entry_stale(&self) -> bool {
680		match &self.entry {
681			Some(Ok(EntryState::On(program) | EntryState::Off(program))) => {
682				self.listed.as_ref() != Some(program) || !program.is_file()
683			}
684			_ => false,
685		}
686	}
687
688	/// What the login entry says, in a word, as programs show it: `off` where the person
689	/// turned it off, whatever it starts; `missing`; `stale` where it starts another program
690	/// than the copy that the list names; `on`; `unreadable`; `None` where there is none.
691	#[must_use]
692	pub fn entry_word(&self) -> Option<&'static str> {
693		Some(match &self.entry {
694			None => return None,
695			Some(Err(_)) => "unreadable",
696			Some(Ok(EntryState::Off(_))) => "off",
697			Some(Ok(EntryState::Missing)) => "missing",
698			Some(Ok(EntryState::On(_))) if self.entry_stale() => "stale",
699			Some(Ok(EntryState::On(_))) => "on",
700		})
701	}
702}
703
704/// What syncing from login does for the library in `directory`, or the one whose replica
705/// here is `replica`, as after its folder was named another way: as far as it can be read,
706/// for a program to show; a list that cannot be read counts as one without it. Of a library
707/// that is off, nothing more is read.
708#[must_use]
709pub fn status(
710	settings: &Path,
711	(directory, replica): (&Path, Option<EntityId>),
712	entry: Option<&LoginEntry>,
713) -> AtLoginStatus {
714	let list = AtLogin::read(settings).unwrap_or_default();
715	let listed = list.find(directory).cloned().or_else(|| {
716		let replica = replica?;
717		list.libraries
718			.iter()
719			.find(|listed| listed.replica == replica)
720			.cloned()
721	});
722	let Some(listed) = listed else {
723		return AtLoginStatus {
724			on: false,
725			serving: None,
726			entry: None,
727			listed: list.program,
728		};
729	};
730	let serving = service_running(settings).unwrap_or(false).then(|| {
731		ServiceStatus::read(settings)
732			.ok()
733			.flatten()
734			.and_then(|status| status.of(&listed.directory).cloned())
735			.unwrap_or(Serving::Starting)
736	});
737	AtLoginStatus {
738		on: true,
739		serving,
740		entry: entry.map(|entry| entry.state().map_err(|error| error.to_string())),
741		listed: list.program,
742	}
743}
744
745/// What an app does as it starts, where the list holds libraries and the login entry is on,
746/// or the platform has none: names `own`, its copy of `nibkeep-sync`, if the listed one is
747/// gone or older, pointing the login entry along; and returns the copy to start, if any: its
748/// own, just named, which waits for the one that runs to end, or the listed one, where none
749/// runs, as after a crash. Where the person turned the entry off, or removed it, it does
750/// nothing, so that the copy that runs, as one that turning on started, goes on.
751///
752/// # Errors
753///
754/// Returns the errors of [`name_own_copy`].
755pub fn app_started(
756	settings: &Path,
757	own: &Path,
758	version_of: &VersionOf<'_>,
759	entry: Option<&LoginEntry>,
760) -> Result<Option<PathBuf>, NodeError> {
761	if !settings.join(LIST).exists() || AtLogin::read(settings)?.libraries.is_empty() {
762		return Ok(None);
763	}
764	if let Some(entry) = entry
765		&& !matches!(entry.state()?, EntryState::On(_))
766	{
767		return Ok(None);
768	}
769	let named = name_own_copy(settings, own, version_of, entry)?;
770	let start = named || !service_running(settings)?;
771	Ok(AtLogin::read(settings)?.program.filter(|_| start))
772}
773
774/// Whether the keystore holds its entry of a service and an account locked.
775pub type KeyringLocked = dyn Fn(&str, &str) -> bool + Send + Sync;
776
777/// How the service runs.
778#[derive(Clone)]
779pub struct ServiceOptions {
780	/// Its own program, which the list must name for it to run.
781	pub program: PathBuf,
782	/// How it holds each library's role, as an app holds it.
783	pub background: BackgroundOptions,
784	/// Whether the keystore holds its entry of a service and an account locked, as a
785	/// Secret Service does until the person unlocks it: asked without a prompt.
786	pub locked: Arc<KeyringLocked>,
787	/// How often it looks at the list, and again at a library that it cannot serve yet.
788	pub look: Duration,
789	/// The login entry, which it removes with the last library, as it does when it takes
790	/// off the list a library that a passphrase protects.
791	pub entry: Option<LoginEntry>,
792}
793
794impl ServiceOptions {
795	/// For `program`, holding each role as `background` says, with a keystore that is never
796	/// locked, looking every two seconds.
797	#[must_use]
798	pub fn new(program: PathBuf, background: BackgroundOptions) -> Self {
799		Self {
800			program,
801			background,
802			locked: Arc::new(|_, _| false),
803			look: Duration::from_secs(2),
804			entry: None,
805		}
806	}
807}
808
809/// Why the service ended.
810#[derive(Clone, Copy, Debug, PartialEq, Eq)]
811pub enum ServiceEnded {
812	/// It was stopped, as when the session ends.
813	Stopped,
814	/// The list holds no library.
815	Empty,
816	/// The list names another copy of `nibkeep-sync`.
817	NamesAnother,
818}
819
820/// Runs the service: takes the lock on `sync-at-login.running`, or waits for the copy that
821/// holds it while the list names this one; then holds the sync role of each library on the
822/// list, each on a thread of its own, following the list as it changes, and writes what it
823/// does for each, until stopped, or the list is empty or names another copy. `now` is the
824/// wall clock, and `rng` makes randomness for each thread.
825///
826/// # Errors
827///
828/// Returns an error if the folder of settings, or the lock in it, cannot be made.
829pub fn serve_at_login<R: CryptoRng + Send + 'static>(
830	settings: &Path,
831	options: &ServiceOptions,
832	now: impl Fn() -> u64 + Send + Sync + 'static,
833	rng: impl Fn() -> R + Send + Sync + 'static,
834	stop: &AtomicBool,
835) -> Result<ServiceEnded, NodeError> {
836	fs::create_dir_all(settings).map_err(NodeError::file(settings))?;
837	let path = settings.join(RUNNING);
838	let shared = Shared {
839		settings: settings.to_owned(),
840		options: options.clone(),
841		now: Arc::new(now),
842		rng: Arc::new(rng),
843	};
844	loop {
845		let running = open_lock(&path)?;
846		loop {
847			if take_alone(&running, &path)? {
848				break;
849			}
850			if !names(&AtLogin::read(settings)?, &options.program) {
851				return Ok(ServiceEnded::NamesAnother);
852			}
853			if pause(options.look, stop) {
854				return Ok(ServiceEnded::Stopped);
855			}
856		}
857		let (ended, workers) = serve(&shared, stop);
858		// Each lets go of its role once the syncs under way end, all at once; and the lock
859		// goes first, so that a copy started meanwhile takes each role as it is let go.
860		for worker in workers.values() {
861			worker.stop.store(true, Ordering::SeqCst);
862		}
863		let _ = fs::remove_file(settings.join(STATUS));
864		drop(running);
865		drop(workers);
866		// A program that added a library while this one ended found it running, and started
867		// none: so it serves again, unless another copy runs by now.
868		let again = ended == ServiceEnded::Empty
869			&& AtLogin::read(settings)
870				.is_ok_and(|list| !list.libraries.is_empty() && names(&list, &options.program))
871			&& !service_running(settings)?;
872		if !again {
873			return Ok(ended);
874		}
875	}
876}
877
878/// Serves the listed libraries, as [`serve_at_login`] says, holding the lock on
879/// `sync-at-login.running`: until stopped, or the list is empty or names another copy.
880/// Returns why, and the libraries' threads, still running.
881fn serve<R: CryptoRng + Send + 'static>(
882	shared: &Shared<R>,
883	stop: &AtomicBool,
884) -> (ServiceEnded, BTreeMap<PathBuf, Worker>) {
885	let (settings, options) = (shared.settings.as_path(), &shared.options);
886	let mut workers: BTreeMap<PathBuf, Worker> = BTreeMap::new();
887	let mut written = None;
888	let mut list = AtLogin::default();
889	let ended = loop {
890		if stop.load(Ordering::SeqCst) {
891			break ServiceEnded::Stopped;
892		}
893		// A list that does not read for a moment, as one written by hand, leaves things as
894		// they were.
895		if let Ok(read) = AtLogin::read(settings) {
896			list = read;
897		}
898		if !names(&list, &options.program) {
899			break ServiceEnded::NamesAnother;
900		}
901		if list.libraries.is_empty() {
902			break ServiceEnded::Empty;
903		}
904		workers.retain(|directory, worker| {
905			list.find(directory)
906				.is_some_and(|listed| listed.replica == worker.served.replica)
907		});
908		for served in &list.libraries {
909			if !workers.contains_key(&served.directory) {
910				let worker = Worker::start(served.clone(), shared);
911				workers.insert(served.directory.clone(), worker);
912			}
913		}
914		let status = ServiceStatus {
915			version: ENGINE_VERSION.to_owned(),
916			libraries: list
917				.libraries
918				.iter()
919				.filter_map(|served| {
920					let worker = workers.get(&served.directory)?;
921					Some((served.clone(), locked(&worker.serving).clone()))
922				})
923				.collect(),
924		};
925		if written.as_ref() != Some(&status) && status.write(settings).is_ok() {
926			written = Some(status);
927		}
928		if pause(options.look.min(Duration::from_secs(1)), stop) {
929			break ServiceEnded::Stopped;
930		}
931	};
932	(ended, workers)
933}
934
935/// The wall clock, shared by the threads.
936type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
937
938/// What makes randomness for each thread, shared by the threads.
939type Randomness<R> = Arc<dyn Fn() -> R + Send + Sync>;
940
941/// What every library's thread shares.
942struct Shared<R> {
943	/// The folder of the list.
944	settings: PathBuf,
945	options: ServiceOptions,
946	now: Clock,
947	rng: Randomness<R>,
948}
949
950/// A thread that serves one library: opens it once it can, and holds its role in the
951/// background, until stopped or dropped.
952struct Worker {
953	served: Served,
954	stop: Arc<AtomicBool>,
955	serving: Arc<Mutex<Serving>>,
956	thread: Option<JoinHandle<()>>,
957}
958
959impl Worker {
960	fn start<R: CryptoRng + Send + 'static>(served: Served, shared: &Shared<R>) -> Self {
961		let stop = Arc::new(AtomicBool::new(false));
962		let serving = Arc::new(Mutex::new(Serving::Starting));
963		let thread = {
964			let (served, stop, serving) = (served.clone(), Arc::clone(&stop), Arc::clone(&serving));
965			let (settings, options) = (shared.settings.clone(), shared.options.clone());
966			let (now, rng) = (Arc::clone(&shared.now), Arc::clone(&shared.rng));
967			std::thread::spawn(move || {
968				let context = (settings.as_path(), &options);
969				serve_library(&served, context, (&now, &rng), &stop, &serving);
970			})
971		};
972		Self {
973			served,
974			stop,
975			serving,
976			thread: Some(thread),
977		}
978	}
979}
980
981impl Drop for Worker {
982	/// Stops it, and waits until it let go of the role.
983	fn drop(&mut self) {
984		self.stop.store(true, Ordering::SeqCst);
985		if let Some(thread) = self.thread.take() {
986			let _ = thread.join();
987		}
988	}
989}
990
991/// The thread of a [`Worker`]. Where it cannot serve the library, it tries again, at
992/// first after `look`, then less and less often, but for a locked keyring, which the person
993/// may unlock any time; and it turns syncing from login off for a library that a passphrase
994/// protects now, as nobody is there to type it.
995fn serve_library<R: CryptoRng + Send + 'static>(
996	served: &Served,
997	(settings, options): (&Path, &ServiceOptions),
998	(now, rng): (&Clock, &Randomness<R>),
999	stop: &AtomicBool,
1000	serving: &Mutex<Serving>,
1001) {
1002	let mut wait = options.look;
1003	let again = |wait: &mut Duration| {
1004		let stopped = pause(*wait, stop);
1005		*wait = (*wait * 2).min(LONGEST_WAIT);
1006		stopped
1007	};
1008	while !stop.load(Ordering::SeqCst) {
1009		let closed = match prepare(served, options.locked.as_ref()) {
1010			Ok(closed) => closed,
1011			Err(Cannot::Serve(Serving::WaitingForKeyring)) => {
1012				*locked(serving) = Serving::WaitingForKeyring;
1013				if pause(options.look, stop) {
1014					return;
1015				}
1016				continue;
1017			}
1018			Err(Cannot::Serve(cannot)) => {
1019				*locked(serving) = cannot;
1020				if again(&mut wait) {
1021					return;
1022				}
1023				continue;
1024			}
1025			Err(Cannot::Passphrase) => {
1026				*locked(serving) = Serving::NoKey;
1027				let _ = turn_off(settings, (&served.directory, None), options.entry.as_ref());
1028				if again(&mut wait) {
1029					return;
1030				}
1031				continue;
1032			}
1033		};
1034		let background = {
1035			let (now, rng) = (Arc::clone(now), Arc::clone(rng));
1036			Background::start(
1037				closed,
1038				options.background.clone(),
1039				move || now(),
1040				move || rng(),
1041			)
1042		};
1043		// Until stopped, or the holder ends, as after another program protected the library
1044		// anew, when the library is opened again with its new key.
1045		let mut held = false;
1046		loop {
1047			let state = background.state();
1048			held |= state.holding;
1049			*locked(serving) = match (state.holding, state.failed) {
1050				(true, _) => Serving::Syncing,
1051				(false, Some(failed)) => Serving::Failed(failed),
1052				(false, None) => Serving::Waiting,
1053			};
1054			if stop.load(Ordering::SeqCst) || background.ended() {
1055				break;
1056			}
1057			std::thread::sleep(STEP);
1058		}
1059		background.wait();
1060		if held {
1061			wait = options.look;
1062		}
1063		if again(&mut wait) {
1064			return;
1065		}
1066	}
1067}
1068
1069/// Why the service cannot serve a library now.
1070enum Cannot {
1071	/// As this says.
1072	Serve(Serving),
1073	/// A passphrase protects the library's keys.
1074	Passphrase,
1075}
1076
1077/// Opens the listed library with its key from the keystore, and closes it, without its
1078/// secrets; or says why it cannot.
1079fn prepare(served: &Served, keyring_locked: &KeyringLocked) -> Result<Closed, Cannot> {
1080	let failed = |error: NodeError| {
1081		Cannot::Serve(match error {
1082			NodeError::NoLibrary | NodeError::Copied | NodeError::SeveralHere(_) => {
1083				Serving::NotHere
1084			}
1085			NodeError::Keys(KeysError::Keystore(keyring_core::Error::NoEntry)) => Serving::NoKey,
1086			error => Serving::Failed(error.to_string()),
1087		})
1088	};
1089	let Protection::Keystore { service, account } =
1090		Library::protection(&served.directory).map_err(failed)?
1091	else {
1092		return Err(Cannot::Passphrase);
1093	};
1094	if keyring_locked(&service, &account) {
1095		return Err(Cannot::Serve(Serving::WaitingForKeyring));
1096	}
1097	let library = Library::open(&served.directory, &Unlocker::Keystore).map_err(failed)?;
1098	let here = library
1099		.replicas()
1100		.map_err(failed)?
1101		.into_iter()
1102		.find(|replica| replica.this)
1103		.map(|replica| replica.id);
1104	if here != Some(served.replica) {
1105		return Err(Cannot::Serve(Serving::NotHere));
1106	}
1107	// Without the secrets, which syncing never needs.
1108	Ok(library.close().without_secrets())
1109}
1110
1111/// Whether the list names `program`.
1112fn names(list: &AtLogin, program: &Path) -> bool {
1113	list.program
1114		.as_deref()
1115		.is_some_and(|listed| same_file(listed, program))
1116}
1117
1118/// Whether two paths name one file: the same path, or the same once resolved.
1119fn same_file(a: &Path, b: &Path) -> bool {
1120	a == b
1121		|| matches!(
1122			(fs::canonicalize(a), fs::canonicalize(b)),
1123			(Ok(a), Ok(b)) if a == b
1124		)
1125}
1126
1127/// Waits for `wait`, or less if stopped: whether it was stopped.
1128fn pause(wait: Duration, stop: &AtomicBool) -> bool {
1129	let paused = Instant::now();
1130	while paused.elapsed() < wait {
1131		if stop.load(Ordering::SeqCst) {
1132			return true;
1133		}
1134		std::thread::sleep(STEP.min(wait));
1135	}
1136	stop.load(Ordering::SeqCst)
1137}
1138
1139fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
1140	mutex.lock().unwrap_or_else(PoisonError::into_inner)
1141}
1142
1143fn open_lock(path: &Path) -> Result<File, NodeError> {
1144	OpenOptions::new()
1145		.read(true)
1146		.write(true)
1147		.create(true)
1148		.truncate(false)
1149		.open(path)
1150		.map_err(NodeError::file(path))
1151}
1152
1153/// Takes the lock on a file alone, unless another holds it: whether it did.
1154fn try_alone(file: &File, path: &Path) -> Result<bool, NodeError> {
1155	match file.try_lock() {
1156		Ok(()) => Ok(true),
1157		Err(TryLockError::WouldBlock) => Ok(false),
1158		Err(TryLockError::Error(error)) => Err(NodeError::file(path)(error)),
1159	}
1160}
1161
1162/// Takes the lock on a file alone, trying for a while, as another program may hold it for
1163/// a moment only to see whether the service runs: whether it did.
1164fn take_alone(file: &File, path: &Path) -> Result<bool, NodeError> {
1165	let tried = Instant::now();
1166	loop {
1167		if try_alone(file, path)? {
1168			return Ok(true);
1169		}
1170		if tried.elapsed() >= LOOKING {
1171			return Ok(false);
1172		}
1173		std::thread::sleep(Duration::from_millis(5));
1174	}
1175}
1176
1177/// The name of the login entry, as the system's startup settings show it.
1178const ENTRY_NAME: &str = "NibKeep Sync";
1179
1180/// The login entry that starts `nibkeep-sync` when the person logs in: the platform's own,
1181/// where the person finds the programs that start with their session. Each computer has one
1182/// of its own, named as its folder of state is, so that a program that syncs dotfolders, or
1183/// a roaming profile, never makes one computer's turning off remove another's.
1184#[derive(Clone, Debug)]
1185pub struct LoginEntry {
1186	place: EntryPlace,
1187}
1188
1189#[derive(Clone, Debug)]
1190enum EntryPlace {
1191	/// An XDG autostart entry: its file.
1192	Autostart(PathBuf),
1193	/// A value of a Run key in the person's registry, named as it says; and the key in which
1194	/// Windows keeps whether the person turned it off.
1195	#[cfg(windows)]
1196	Run {
1197		key: String,
1198		approved: String,
1199		name: String,
1200	},
1201}
1202
1203/// What the login entry says.
1204#[derive(Clone, Debug, PartialEq, Eq)]
1205pub enum EntryState {
1206	/// There is none, or none that reads as one.
1207	Missing,
1208	/// It starts this program at login.
1209	On(PathBuf),
1210	/// It would start this program, but the person turned it off in the system's startup
1211	/// settings.
1212	Off(PathBuf),
1213}
1214
1215impl LoginEntry {
1216	/// This computer's login entry: on Windows, the value `NibKeep Sync` with the
1217	/// computer's name after it, of the Run key in the person's registry. None where tests
1218	/// keep away from it.
1219	#[cfg(windows)]
1220	#[must_use]
1221	pub fn platform() -> Option<Self> {
1222		if kept_away() {
1223			return None;
1224		}
1225		Some(Self::run_key(
1226			r"Software\Microsoft\Windows\CurrentVersion\Run",
1227			r"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run",
1228			&format!("{ENTRY_NAME} {}", computer_name()),
1229		))
1230	}
1231
1232	/// This computer's login entry: on Linux and the like, the autostart entry
1233	/// `~/.config/autostart/nibkeep-sync-COMPUTER.desktop`, or in `$XDG_CONFIG_HOME/autostart`.
1234	/// None where tests keep away from it.
1235	#[cfg(all(
1236		unix,
1237		not(any(target_os = "macos", target_os = "ios", target_os = "android"))
1238	))]
1239	#[must_use]
1240	pub fn platform() -> Option<Self> {
1241		if kept_away() {
1242			return None;
1243		}
1244		directories::BaseDirs::new().map(|base| {
1245			let file = format!("{SERVICE_PROGRAM}-{}.desktop", computer_name());
1246			Self::autostart(base.config_dir().join("autostart").join(file))
1247		})
1248	}
1249
1250	/// This computer's login entry: none on macOS, where the login item comes with the apps,
1251	/// nor on phones.
1252	#[cfg(not(any(
1253		windows,
1254		all(
1255			unix,
1256			not(any(target_os = "macos", target_os = "ios", target_os = "android"))
1257		)
1258	)))]
1259	#[must_use]
1260	pub fn platform() -> Option<Self> {
1261		None
1262	}
1263
1264	/// An XDG autostart entry in `file`, as tests make one.
1265	#[must_use]
1266	pub fn autostart(file: PathBuf) -> Self {
1267		Self {
1268			place: EntryPlace::Autostart(file),
1269		}
1270	}
1271
1272	/// A value named `name` of the Run key `key` in the person's registry, whose being
1273	/// turned off Windows keeps in the key `approved`, as tests make one.
1274	#[cfg(windows)]
1275	#[must_use]
1276	pub fn run_key(key: &str, approved: &str, name: &str) -> Self {
1277		Self {
1278			place: EntryPlace::Run {
1279				key: key.to_owned(),
1280				approved: approved.to_owned(),
1281				name: name.to_owned(),
1282			},
1283		}
1284	}
1285
1286	/// What it says now.
1287	///
1288	/// # Errors
1289	///
1290	/// Returns an error if it cannot be read.
1291	pub fn state(&self) -> Result<EntryState, NodeError> {
1292		match &self.place {
1293			EntryPlace::Autostart(file) => Ok(autostart::state(autostart::read(file)?.as_deref())),
1294			#[cfg(windows)]
1295			EntryPlace::Run {
1296				key,
1297				approved,
1298				name,
1299			} => run::state(key, approved, name),
1300		}
1301	}
1302
1303	/// Makes it start `program`: a new one, on, where there is none; otherwise the one
1304	/// there, starting `program` instead, and still off if the person turned it off. Writes
1305	/// nothing where it starts `program` already. Returns what it says then.
1306	///
1307	/// # Errors
1308	///
1309	/// Returns an error if it cannot be read or written.
1310	pub fn make(&self, program: &Path) -> Result<EntryState, NodeError> {
1311		self.write(program, true)
1312	}
1313
1314	/// Makes it start `program` instead, as [`LoginEntry::make`] does, if there is one: what
1315	/// it says then. A program that names a newer copy does this, and never makes an entry
1316	/// that the person removed.
1317	///
1318	/// # Errors
1319	///
1320	/// Returns an error if it cannot be read or written.
1321	pub fn point(&self, program: &Path) -> Result<EntryState, NodeError> {
1322		self.write(program, false)
1323	}
1324
1325	/// Removes it, with the record that the person turned it off, so that one made later
1326	/// starts on.
1327	///
1328	/// # Errors
1329	///
1330	/// Returns an error if it cannot be removed.
1331	pub fn remove(&self) -> Result<(), NodeError> {
1332		match &self.place {
1333			EntryPlace::Autostart(file) => match fs::remove_file(file) {
1334				Err(error) if error.kind() != io::ErrorKind::NotFound => {
1335					Err(NodeError::file(file)(error))
1336				}
1337				_ => Ok(()),
1338			},
1339			#[cfg(windows)]
1340			EntryPlace::Run {
1341				key,
1342				approved,
1343				name,
1344			} => run::remove(key, approved, name),
1345		}
1346	}
1347
1348	/// Makes it start `program`, a new one only where `new` allows: what it says then.
1349	fn write(&self, program: &Path, new: bool) -> Result<EntryState, NodeError> {
1350		match &self.place {
1351			EntryPlace::Autostart(file) => {
1352				let text = autostart::read(file)?;
1353				let written = match (autostart::state(text.as_deref()), &text) {
1354					(EntryState::On(listed) | EntryState::Off(listed), _) if listed == program => {
1355						return Ok(autostart::state(text.as_deref()));
1356					}
1357					(EntryState::Missing, _) if !new => return Ok(EntryState::Missing),
1358					(EntryState::Missing, _) | (_, None) => autostart::new(program),
1359					(_, Some(text)) => autostart::pointed(text, program),
1360				};
1361				// Through a link, as a program that manages dotfiles makes, to its file.
1362				let target = fs::canonicalize(file).unwrap_or_else(|_| file.clone());
1363				if let Some(folder) = target.parent() {
1364					fs::create_dir_all(folder).map_err(NodeError::file(folder))?;
1365				}
1366				write_file(&target, written.as_bytes())?;
1367				Ok(autostart::state(Some(&written)))
1368			}
1369			#[cfg(windows)]
1370			EntryPlace::Run {
1371				key,
1372				approved,
1373				name,
1374			} => {
1375				let state = run::state(key, approved, name)?;
1376				match &state {
1377					EntryState::On(listed) | EntryState::Off(listed) if listed == program => {
1378						return Ok(state);
1379					}
1380					EntryState::Missing if !new => return Ok(state),
1381					_ => {}
1382				}
1383				let anew = state == EntryState::Missing;
1384				run::write((key, approved, name), program, anew)?;
1385				run::state(key, approved, name)
1386			}
1387		}
1388	}
1389}
1390
1391/// Whether tests keep away from the person's login entry: where `NIBKEEP_NO_LOGIN_ENTRY`
1392/// says so, or `NIBKEEP_STATE` names another folder of state, whose list the entry would not
1393/// serve.
1394#[cfg(any(
1395	windows,
1396	all(
1397		unix,
1398		not(any(target_os = "macos", target_os = "ios", target_os = "android"))
1399	)
1400))]
1401fn kept_away() -> bool {
1402	["NIBKEEP_NO_LOGIN_ENTRY", "NIBKEEP_STATE"]
1403		.iter()
1404		.any(|name| std::env::var_os(name).is_some_and(|value| !value.is_empty()))
1405}
1406
1407mod autostart {
1408	//! XDG autostart entries, as the Desktop Entry Specification has them.
1409
1410	use std::fs;
1411	use std::io;
1412	use std::path::{Path, PathBuf};
1413
1414	use super::{ENTRY_NAME, EntryState};
1415	use crate::NodeError;
1416
1417	/// The entry's text, if there is a file.
1418	pub(super) fn read(file: &Path) -> Result<Option<String>, NodeError> {
1419		match fs::read(file) {
1420			Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())),
1421			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
1422			Err(error) => Err(NodeError::file(file)(error)),
1423		}
1424	}
1425
1426	/// A new entry that starts `program`, on.
1427	pub(super) fn new(program: &Path) -> String {
1428		format!(
1429			"[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",
1430			exec(program)
1431		)
1432	}
1433
1434	/// The lines of an entry, each with whether it is in the group `[Desktop Entry]`, after
1435	/// any byte-order mark.
1436	fn lines(text: &str) -> impl Iterator<Item = (bool, &str)> {
1437		let text = text.strip_prefix('\u{feff}').unwrap_or(text);
1438		let mut group = None;
1439		text.lines().map(move |line| {
1440			if line.starts_with('[') {
1441				group = Some(line.trim());
1442			}
1443			(
1444				group == Some("[Desktop Entry]") && !line.starts_with('['),
1445				line,
1446			)
1447		})
1448	}
1449
1450	/// The entry `text`, starting `program` instead, and nothing else changed: its `Exec`
1451	/// replaced, or added after the group's header if it has none.
1452	pub(super) fn pointed(text: &str, program: &Path) -> String {
1453		let exec = format!("Exec={}\n", exec(program));
1454		let has_exec = lines(text).any(|(entry, line)| entry && key(line) == Some("Exec"));
1455		let mut pointed = String::new();
1456		for (entry, line) in lines(text) {
1457			if entry && key(line) == Some("Exec") {
1458				pointed.push_str(&exec);
1459				continue;
1460			}
1461			pointed.push_str(line);
1462			pointed.push('\n');
1463			if !has_exec && line.trim() == "[Desktop Entry]" {
1464				pointed.push_str(&exec);
1465			}
1466		}
1467		pointed
1468	}
1469
1470	/// What the entry says: missing if there is no file, or no group `[Desktop Entry]`; off
1471	/// if it is hidden, as the specification has an entry deleted, or GNOME's flag turns it
1472	/// off. One whose `Exec` does not read starts nothing that it names.
1473	pub(super) fn state(text: Option<&str>) -> EntryState {
1474		let Some(text) = text else {
1475			return EntryState::Missing;
1476		};
1477		let header = lines(text).any(|(_, line)| line.trim() == "[Desktop Entry]");
1478		let (mut program, mut off) = (PathBuf::new(), false);
1479		for (_, line) in lines(text).filter(|(entry, _)| *entry) {
1480			let value = line.split_once('=').map_or("", |(_, value)| value.trim());
1481			match key(line) {
1482				Some("Exec") => program = parse_exec(value).unwrap_or_default(),
1483				Some("Hidden") => off |= value == "true",
1484				Some("X-GNOME-Autostart-enabled") => off |= value == "false",
1485				_ => {}
1486			}
1487		}
1488		match (header, off) {
1489			(false, _) => EntryState::Missing,
1490			(true, false) => EntryState::On(program),
1491			(true, true) => EntryState::Off(program),
1492		}
1493	}
1494
1495	/// The key of a line `key=value`.
1496	fn key(line: &str) -> Option<&str> {
1497		line.split_once('=').map(|(key, _)| key.trim())
1498	}
1499
1500	/// `program` as the value of `Exec`: quoted, with the characters that quotes reserve
1501	/// escaped, then with the backslashes of a string value escaped, and `%` doubled, as
1502	/// field codes take it.
1503	fn exec(program: &Path) -> String {
1504		let mut quoted = String::from("\"");
1505		for character in program.to_string_lossy().chars() {
1506			if matches!(character, '"' | '`' | '$' | '\\') {
1507				quoted.push('\\');
1508			}
1509			quoted.push(character);
1510		}
1511		quoted.push('"');
1512		quoted.replace('\\', "\\\\").replace('%', "%%")
1513	}
1514
1515	/// The program of an `Exec` value: its first argument.
1516	fn parse_exec(value: &str) -> Option<PathBuf> {
1517		let mut unescaped = String::new();
1518		let mut characters = value.chars();
1519		while let Some(character) = characters.next() {
1520			match (character, characters.clone().next()) {
1521				('\\', Some('\\')) => {
1522					unescaped.push('\\');
1523					characters.next();
1524				}
1525				('\\', Some('s')) => {
1526					unescaped.push(' ');
1527					characters.next();
1528				}
1529				('%', Some('%')) => {
1530					unescaped.push('%');
1531					characters.next();
1532				}
1533				_ => unescaped.push(character),
1534			}
1535		}
1536		let mut program = String::new();
1537		let mut characters = unescaped.chars();
1538		if unescaped.starts_with('"') {
1539			characters.next();
1540			while let Some(character) = characters.next() {
1541				match character {
1542					'\\' => program.push(characters.next()?),
1543					'"' => break,
1544					_ => program.push(character),
1545				}
1546			}
1547		} else {
1548			unescaped.split(' ').next()?.clone_into(&mut program);
1549		}
1550		(!program.is_empty()).then(|| PathBuf::from(program))
1551	}
1552}
1553
1554#[cfg(windows)]
1555mod run {
1556	//! A value of a Run key in the person's registry.
1557
1558	use std::io;
1559	use std::path::{Path, PathBuf};
1560
1561	use winreg::RegKey;
1562	use winreg::enums::HKEY_CURRENT_USER;
1563
1564	use super::EntryState;
1565	use crate::NodeError;
1566
1567	fn failed(key: &str) -> impl FnOnce(io::Error) -> NodeError {
1568		let key = key.to_owned();
1569		move |error| NodeError::file(Path::new(&format!(r"HKCU\{key}")))(error)
1570	}
1571
1572	pub(super) fn state(key: &str, approved: &str, name: &str) -> Result<EntryState, NodeError> {
1573		let user = RegKey::predef(HKEY_CURRENT_USER);
1574		let value: String = match user.open_subkey(key).and_then(|run| run.get_value(name)) {
1575			Ok(value) => value,
1576			Err(error) if error.kind() == io::ErrorKind::NotFound => {
1577				return Ok(EntryState::Missing);
1578			}
1579			Err(error) => return Err(failed(key)(error)),
1580		};
1581		let program = PathBuf::from(value.trim().trim_matches('"'));
1582		// Windows marks an entry turned off with an odd first byte.
1583		let off = user
1584			.open_subkey(approved)
1585			.and_then(|approved| approved.get_raw_value(name))
1586			.is_ok_and(|value| value.bytes.first().is_some_and(|first| first & 1 == 1));
1587		Ok(if off {
1588			EntryState::Off(program)
1589		} else {
1590			EntryState::On(program)
1591		})
1592	}
1593
1594	/// Writes the value; made `anew`, without Windows' record of an earlier one turned off,
1595	/// so that it starts on.
1596	pub(super) fn write(
1597		(key, approved, name): (&str, &str, &str),
1598		program: &Path,
1599		anew: bool,
1600	) -> Result<(), NodeError> {
1601		if anew {
1602			let removed = RegKey::predef(HKEY_CURRENT_USER)
1603				.open_subkey_with_flags(approved, winreg::enums::KEY_SET_VALUE)
1604				.and_then(|opened| opened.delete_value(name));
1605			if let Err(error) = removed
1606				&& error.kind() != io::ErrorKind::NotFound
1607			{
1608				return Err(failed(approved)(error));
1609			}
1610		}
1611		let (run, _) = RegKey::predef(HKEY_CURRENT_USER)
1612			.create_subkey(key)
1613			.map_err(failed(key))?;
1614		run.set_value(name, &format!("\"{}\"", program.display()))
1615			.map_err(failed(key))
1616	}
1617
1618	pub(super) fn remove(key: &str, approved: &str, name: &str) -> Result<(), NodeError> {
1619		let user = RegKey::predef(HKEY_CURRENT_USER);
1620		for key in [key, approved] {
1621			let removed = user
1622				.open_subkey_with_flags(key, winreg::enums::KEY_SET_VALUE)
1623				.and_then(|opened| opened.delete_value(name));
1624			match removed {
1625				Err(error) if error.kind() != io::ErrorKind::NotFound => {
1626					return Err(failed(key)(error));
1627				}
1628				_ => {}
1629			}
1630		}
1631		Ok(())
1632	}
1633}
1634
1635/// Windows' firewall: the rule that lets other replicas reach any of NibKeep's programs on
1636/// private networks, by port.
1637#[cfg(windows)]
1638pub mod firewall {
1639	use std::process::{Command, Stdio};
1640
1641	/// The rule's name.
1642	pub const RULE: &str = "NibKeep";
1643
1644	/// Whether the rule is there as NibKeep makes it: on, letting in, over UDP, with its
1645	/// ports, on private networks among others.
1646	#[must_use]
1647	pub fn has_rule() -> bool {
1648		powershell(
1649			"$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 }",
1650		)
1651	}
1652
1653	/// Adds the rule, in place of any of its name, asking Windows for the administrator's
1654	/// consent: whether it is there then, as it is not when the person refused. The rule:
1655	/// UDP ports 53300 to 53309 for syncing, and 5353 for multicast DNS, by which replicas
1656	/// find each other, into any program, on private networks.
1657	#[must_use]
1658	pub fn add_rule() -> bool {
1659		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";
1660		let _ = powershell(&format!(
1661			"Start-Process -FilePath cmd -ArgumentList '{commands}' -Verb RunAs -Wait -WindowStyle Hidden"
1662		));
1663		has_rule()
1664	}
1665
1666	/// Runs a script of PowerShell, with no console window, as from an app: whether it
1667	/// succeeded.
1668	fn powershell(script: &str) -> bool {
1669		use std::os::windows::process::CommandExt;
1670		const CREATE_NO_WINDOW: u32 = 0x0800_0000;
1671		Command::new("powershell")
1672			.creation_flags(CREATE_NO_WINDOW)
1673			.args(["-NoProfile", "-NonInteractive", "-Command", script])
1674			.stdin(Stdio::null())
1675			.stdout(Stdio::null())
1676			.stderr(Stdio::null())
1677			.status()
1678			.is_ok_and(|status| status.success())
1679	}
1680}