1use 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
27const LIST: &str = "sync-at-login";
29
30const LIST_LOCK: &str = "sync-at-login.lock";
32
33const RUNNING: &str = "sync-at-login.running";
35
36const STATUS: &str = "sync-at-login.status";
38
39pub use crate::engines::ENGINE_VERSION;
40
41pub const SERVICE_PROGRAM: &str = "nibkeep-sync";
43
44const LOOKING: Duration = Duration::from_millis(50);
47
48const VERSION_WAIT: Duration = Duration::from_secs(5);
50
51const STEP: Duration = Duration::from_millis(100);
53
54const LONGEST_WAIT: Duration = Duration::from_mins(1);
57
58#[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#[cfg(not(any(target_os = "android", target_os = "ios")))]
83fn computer_name() -> String {
84 use std::fmt::Write as _;
85 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#[derive(Clone, Debug, PartialEq, Eq)]
101pub struct Served {
102 pub replica: EntityId,
106 pub directory: PathBuf,
108}
109
110#[derive(Clone, Debug, Default, PartialEq, Eq)]
113pub struct AtLogin {
114 pub program: Option<PathBuf>,
116 pub libraries: Vec<Served>,
118}
119
120impl AtLogin {
121 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 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 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 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 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 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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
251pub enum Serving {
252 Starting,
254 Syncing,
256 Waiting,
258 WaitingForKeyring,
261 NotHere,
264 NoKey,
267 Failed(String),
269}
270
271impl Serving {
272 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct ServiceStatus {
312 pub version: String,
314 pub libraries: Vec<(Served, Serving)>,
316}
317
318impl ServiceStatus {
319 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 #[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
379pub 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#[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#[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
435pub 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
464fn 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
484pub 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 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 std::thread::spawn(move || {
512 let _ = child.wait();
513 });
514 Ok(())
515}
516
517pub type VersionOf<'a> = dyn Fn(&Path) -> Option<String> + 'a;
519
520#[derive(Clone, Debug, PartialEq, Eq)]
522pub enum EntryOutcome {
523 NoEntry,
525 On(PathBuf),
527 Off(PathBuf),
529 Failed(String),
531}
532
533impl EntryOutcome {
534 #[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 #[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#[derive(Clone, Debug, PartialEq, Eq)]
558pub struct TurnedOn {
559 pub start: Option<PathBuf>,
562 pub entry: EntryOutcome,
564}
565
566pub 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#[derive(Clone, Debug, PartialEq, Eq)]
616pub struct TurnedOff {
617 pub removed: bool,
619 pub entry_failed: Option<String>,
621}
622
623pub 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#[derive(Clone, Debug, PartialEq, Eq)]
664pub struct AtLoginStatus {
665 pub on: bool,
667 pub serving: Option<Serving>,
669 pub entry: Option<Result<EntryState, String>>,
671 pub listed: Option<PathBuf>,
673}
674
675impl AtLoginStatus {
676 #[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 #[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#[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
745pub 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
774pub type KeyringLocked = dyn Fn(&str, &str) -> bool + Send + Sync;
776
777#[derive(Clone)]
779pub struct ServiceOptions {
780 pub program: PathBuf,
782 pub background: BackgroundOptions,
784 pub locked: Arc<KeyringLocked>,
787 pub look: Duration,
789 pub entry: Option<LoginEntry>,
792}
793
794impl ServiceOptions {
795 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
811pub enum ServiceEnded {
812 Stopped,
814 Empty,
816 NamesAnother,
818}
819
820pub 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 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 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
878fn 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 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
935type Clock = Arc<dyn Fn() -> u64 + Send + Sync>;
937
938type Randomness<R> = Arc<dyn Fn() -> R + Send + Sync>;
940
941struct Shared<R> {
943 settings: PathBuf,
945 options: ServiceOptions,
946 now: Clock,
947 rng: Randomness<R>,
948}
949
950struct 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 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
991fn 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 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
1069enum Cannot {
1071 Serve(Serving),
1073 Passphrase,
1075}
1076
1077fn 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 Ok(library.close().without_secrets())
1109}
1110
1111fn names(list: &AtLogin, program: &Path) -> bool {
1113 list.program
1114 .as_deref()
1115 .is_some_and(|listed| same_file(listed, program))
1116}
1117
1118fn 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
1127fn 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
1153fn 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
1162fn 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
1177const ENTRY_NAME: &str = "NibKeep Sync";
1179
1180#[derive(Clone, Debug)]
1185pub struct LoginEntry {
1186 place: EntryPlace,
1187}
1188
1189#[derive(Clone, Debug)]
1190enum EntryPlace {
1191 Autostart(PathBuf),
1193 #[cfg(windows)]
1196 Run {
1197 key: String,
1198 approved: String,
1199 name: String,
1200 },
1201}
1202
1203#[derive(Clone, Debug, PartialEq, Eq)]
1205pub enum EntryState {
1206 Missing,
1208 On(PathBuf),
1210 Off(PathBuf),
1213}
1214
1215impl LoginEntry {
1216 #[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 #[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 #[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 #[must_use]
1266 pub fn autostart(file: PathBuf) -> Self {
1267 Self {
1268 place: EntryPlace::Autostart(file),
1269 }
1270 }
1271
1272 #[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 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 pub fn make(&self, program: &Path) -> Result<EntryState, NodeError> {
1311 self.write(program, true)
1312 }
1313
1314 pub fn point(&self, program: &Path) -> Result<EntryState, NodeError> {
1322 self.write(program, false)
1323 }
1324
1325 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 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 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#[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 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 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 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 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 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 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 fn key(line: &str) -> Option<&str> {
1497 line.split_once('=').map(|(key, _)| key.trim())
1498 }
1499
1500 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 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 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 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 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#[cfg(windows)]
1638pub mod firewall {
1639 use std::process::{Command, Stdio};
1640
1641 pub const RULE: &str = "NibKeep";
1643
1644 #[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 #[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 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}