Skip to main content

nibkeep_node/at_login/
app.rs

1//! What an app does with syncing from login ([technical design](../../../../docs/Technical-design.md#106-syncing-from-login)):
2//! the switch, which has the copy of `nibkeep-sync` that the app ships beside its program sync
3//! a library whenever the person is logged in; and what the app does as it starts. Only on
4//! computers.
5//!
6//! Tests keep apps from the person's list and login entry: with `NIBKEEP_NO_KEYSTORE`, as
7//! they run the apps, there is none, and once a test has named a place of its own, or none,
8//! the process keeps to it.
9
10use std::path::PathBuf;
11use std::sync::{Mutex, PoisonError};
12
13use nibkeep_base::EntityId;
14
15use super::{
16	AtLoginStatus, EntryOutcome, LoginEntry, Served, TurnedOff, service_version, start_service,
17};
18use crate::NodeError;
19
20/// Where syncing from login keeps its list and login entry, and the app's own copy of
21/// `nibkeep-sync`.
22#[derive(Clone)]
23struct Place {
24	settings: PathBuf,
25	entry: Option<LoginEntry>,
26	own: Option<PathBuf>,
27	/// Whether the app starts copies: a test's place says what it would start instead.
28	starts: bool,
29}
30
31/// Which place an app uses.
32#[derive(Clone)]
33enum Chosen {
34	/// The person's.
35	Persons,
36	/// A test's.
37	Tests(Place),
38	/// None, as a test chose.
39	Nowhere,
40}
41
42/// The place that an app uses: the person's, until a test chooses.
43static CHOSEN: Mutex<Chosen> = Mutex::new(Chosen::Persons);
44
45/// For tests, which keep away from the person's: puts the list in the folder `folder`, the
46/// login entry, if any, in the autostart file `entry`, and takes `program` for the app's own
47/// copy, which it then never starts. Without a folder, the app has no syncing from login.
48pub fn set_test_place(folder: Option<PathBuf>, entry: Option<PathBuf>, program: Option<PathBuf>) {
49	let chosen = folder.map_or(Chosen::Nowhere, |settings| {
50		Chosen::Tests(Place {
51			settings,
52			entry: entry.map(LoginEntry::autostart),
53			own: program,
54			starts: false,
55		})
56	});
57	*CHOSEN.lock().unwrap_or_else(PoisonError::into_inner) = chosen;
58}
59
60/// Whether tests keep the program from the computer's keystore, as `NIBKEEP_NO_KEYSTORE`
61/// says: an app, `nib` or `nibkeep-sync`. They keep an app from the person's syncing from
62/// login too.
63#[must_use]
64pub fn kept_away() -> bool {
65	std::env::var_os("NIBKEEP_NO_KEYSTORE").is_some_and(|off| !off.is_empty())
66}
67
68/// Where syncing from login is: a test's, or the person's; none on phones, nor where tests
69/// keep the app away.
70fn place() -> Option<Place> {
71	match CHOSEN
72		.lock()
73		.unwrap_or_else(PoisonError::into_inner)
74		.clone()
75	{
76		Chosen::Tests(place) => return Some(place),
77		Chosen::Nowhere => return None,
78		Chosen::Persons => {}
79	}
80	if kept_away() {
81		return None;
82	}
83	#[cfg(not(any(target_os = "android", target_os = "ios")))]
84	return Some(Place {
85		settings: super::settings_folder()?,
86		entry: LoginEntry::platform(),
87		own: own_copy(),
88		starts: true,
89	});
90	#[cfg(any(target_os = "android", target_os = "ios"))]
91	None
92}
93
94/// The app's own copy of `nibkeep-sync`, beside its program, if it ships one.
95#[cfg(not(any(target_os = "android", target_os = "ios")))]
96fn own_copy() -> Option<PathBuf> {
97	let name = format!("{}{}", super::SERVICE_PROGRAM, std::env::consts::EXE_SUFFIX);
98	let copy = std::env::current_exe().ok()?.with_file_name(name);
99	copy.is_file().then_some(copy)
100}
101
102/// Starts a copy of `nibkeep-sync`, unless the place is a test's: the copy started, or that
103/// would be.
104fn start(place: &Place, program: Option<PathBuf>) -> Result<Option<PathBuf>, NodeError> {
105	if let Some(program) = &program
106		&& place.starts
107	{
108		start_service(program)?;
109	}
110	Ok(program)
111}
112
113/// Whether the app can turn syncing from login on here: on a computer where it ships
114/// `nibkeep-sync`.
115#[must_use]
116pub fn available() -> bool {
117	place().is_some_and(|place| place.own.is_some())
118}
119
120/// What the app does as it starts, as [`super::app_started`] says: the copy of
121/// `nibkeep-sync` that it started, if any.
122///
123/// # Errors
124///
125/// Returns the errors of [`super::app_started`] and [`start_service`].
126pub fn started() -> Result<Option<PathBuf>, NodeError> {
127	let Some(place) = place() else {
128		return Ok(None);
129	};
130	let Some(own) = &place.own else {
131		return Ok(None);
132	};
133	let program = super::app_started(&place.settings, own, &service_version, place.entry.as_ref())?;
134	start(&place, program)
135}
136
137/// What syncing from login does for the library in `directory`, whose replica here is
138/// `replica`: `None` where the app cannot turn it on here.
139#[must_use]
140pub fn status(directory: &std::path::Path, replica: Option<EntityId>) -> Option<AtLoginStatus> {
141	let place = place().filter(|place| place.own.is_some())?;
142	Some(super::status(
143		&place.settings,
144		(directory, replica),
145		place.entry.as_ref(),
146	))
147}
148
149/// What turning syncing from login on did, for an app.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct AppTurnedOn {
152	/// What became of the login entry.
153	pub entry: EntryOutcome,
154	/// What became of Windows' firewall: `opened`, or `refused`; elsewhere, or where its rule
155	/// is there, `None`.
156	pub firewall: Option<&'static str>,
157	/// The copy of `nibkeep-sync` that it started, or that a test's place would.
158	pub started: Option<PathBuf>,
159}
160
161/// Turns syncing from login on, as [`super::turn_on`] does with the app's own copy; lets the
162/// other devices through Windows' firewall, asking for the administrator's consent, before it
163/// starts the copy that should run, so that Windows does not ask about that one, whose
164/// refusal would block it. `None` where the app cannot turn it on here. It may wait for
165/// copies to tell their versions, and for the person's consent: never while the app holds its
166/// library.
167///
168/// # Errors
169///
170/// Returns the errors of [`super::turn_on`] and [`start_service`].
171pub fn turn_on(served: Served) -> Result<Option<AppTurnedOn>, NodeError> {
172	let Some(place) = place() else {
173		return Ok(None);
174	};
175	let Some(own) = &place.own else {
176		return Ok(None);
177	};
178	let turned_on = super::turn_on(
179		&place.settings,
180		served,
181		(own, &service_version),
182		place.entry.as_ref(),
183	)?;
184	let firewall = if place.starts { firewall() } else { None };
185	let started = start(&place, turned_on.start)?;
186	Ok(Some(AppTurnedOn {
187		entry: turned_on.entry,
188		firewall,
189		started,
190	}))
191}
192
193/// Lets the other devices through Windows' firewall, unless its rule is there: `opened`, or
194/// `refused`; elsewhere, nothing to do.
195fn firewall() -> Option<&'static str> {
196	#[cfg(windows)]
197	{
198		use super::firewall;
199		if firewall::has_rule() {
200			None
201		} else if firewall::add_rule() {
202			Some("opened")
203		} else {
204			Some("refused")
205		}
206	}
207	#[cfg(not(windows))]
208	None
209}
210
211/// Turns syncing from login off for the library in `directory`, or its replica here, as
212/// [`super::turn_off`] does: nothing where the app has no syncing from login.
213///
214/// # Errors
215///
216/// Returns the errors of [`super::turn_off`].
217pub fn turn_off(
218	directory: &std::path::Path,
219	replica: Option<EntityId>,
220) -> Result<TurnedOff, NodeError> {
221	let Some(place) = place() else {
222		return Ok(TurnedOff {
223			removed: false,
224			entry_failed: None,
225		});
226	};
227	super::turn_off(&place.settings, (directory, replica), place.entry.as_ref())
228}