Skip to main content

nibkeep_node/library/
copies.rs

1//! Copies of replicas made elsewhere, which a library's directory holds beside the replica
2//! that is here: brought by a backup, a program that syncs folders, or by hand. A copy is
3//! never opened or written to; what it holds is taken in, as from another replica
4//! (technical design: copies of a replica).
5
6use std::convert::Infallible;
7use std::fs;
8use std::io::Read;
9use std::path::{Path, PathBuf};
10use std::sync::mpsc;
11
12use nibkeep_base::cbor::{self, FromCbor, ToCbor, Value};
13use nibkeep_base::{EntityId, SpaceId};
14use nibkeep_crypto::PassphraseParams;
15use nibkeep_crypto::rand_core::{CryptoRng, TryCryptoRng, TryRng};
16use nibkeep_governance::PairingCode;
17use nibkeep_keys::{KeyFile, NewProtection, Protection, Unlocker};
18use nibkeep_store::{CopiedItem, log_path, take_copied_log};
19use nibkeep_sync::{Holder, Transport, TransportError};
20
21use super::sync::{Joining, Sponsor, Syncing, endpoint_of};
22use super::taking::NewDevice;
23use super::{INFO, KEYS, Library, REPLICAS, new_replica_folder, replica_folders};
24use crate::NodeError;
25use crate::info::{Info, write_file};
26use crate::place::{Drive, declare_drive};
27
28/// The file, in a replica's folder, that records how the copies beside it looked when it
29/// last looked, and whether the person was told that a program syncs the library's folder.
30const SEEN: &str = "copies.cbor";
31
32/// What programs that sync folders leave in the folders they sync, or in their roots, and
33/// whether it is a file: Syncthing's folder, Dropbox's file and folder of its cache, which
34/// its folder of settings in a home folder is not, and ownCloud's file; Nextcloud's journal
35/// is `.sync_*.db`.
36const MARKS: &[(&str, bool)] = &[
37	(".stfolder", false),
38	(".dropbox", true),
39	(".dropbox.cache", false),
40	(".owncloudsync.log", true),
41];
42
43/// A copy of a replica made elsewhere, in a library's directory.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub struct ReplicaCopy {
46	/// Its folder, which is read and never written.
47	pub folder: PathBuf,
48	/// The replica it is a copy of, and its device, as its library file says, if it reads.
49	pub replica: Option<(EntityId, EntityId)>,
50}
51
52impl ReplicaCopy {
53	/// How the copy's keys are protected, and its secrets', if it has any: whether a
54	/// passphrase opens them, or a keystore entry, which only the computer that made it
55	/// holds, unless its keyring came with the copy.
56	///
57	/// # Errors
58	///
59	/// Returns [`NodeError::NewerFormats`] if a later version of NibKeep changed the copy,
60	/// and an error if its key file does not read.
61	pub fn protections(&self) -> Result<(Protection, Option<Protection>), NodeError> {
62		crate::engines::check(&self.folder)?;
63		let key_file = KeyFile::read(&self.folder.join(KEYS))?;
64		Ok((
65			key_file.replica_protection().clone(),
66			key_file.secrets_protection().cloned(),
67		))
68	}
69}
70
71/// What taking in copies brought.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
73pub struct TakenIn {
74	/// The copies read.
75	pub copies: usize,
76	/// The changes, keys and blobs that were new to this replica.
77	pub items: usize,
78}
79
80impl Library {
81	/// The copies that a library's directory holds: the folders of replicas that are not
82	/// here, also those that a program may still be bringing in, but the one that a recovery
83	/// in place replaces, until it is set aside.
84	#[must_use]
85	pub fn copies_in(directory: &Path) -> Vec<ReplicaCopy> {
86		let here = Self::replica_folder(directory).ok();
87		let replaced = here.as_deref().and_then(super::recovering::replaced_by);
88		// Sorted by folder, as the folders are.
89		replica_folders(directory)
90			.unwrap_or_default()
91			.into_iter()
92			.map(|(folder, _)| folder)
93			.filter(|folder| Some(folder) != here.as_ref() && Some(folder) != replaced.as_ref())
94			.map(|folder| ReplicaCopy {
95				replica: Info::read(&folder.join(INFO))
96					.ok()
97					.map(|info| (info.replica, info.device)),
98				folder,
99			})
100			.collect()
101	}
102
103	/// The copies beside this replica in its library's directory.
104	#[must_use]
105	pub fn copies(&self) -> Vec<ReplicaCopy> {
106		self.directory
107			.parent()
108			.and_then(Path::parent)
109			.map_or_default(Self::copies_in)
110	}
111
112	/// Adds this computer as a device of its own, in a new replica beside the copy in `copy`
113	/// in the library's directory `directory`, with the copy's own keys, which `unlocker`
114	/// opens: for
115	/// when no other device of the person's can add it, as after a library restored from the
116	/// backup of the only one. The copy is opened in a private copy of its own, with its
117	/// keys in a key file of that copy's, and nothing of the copy or its keystore entries is
118	/// written to. It adds the new replica as pairing does, in this process; the new replica
119	/// takes in what the copy holds, and with `secrets`, which open the copy's secrets and
120	/// protect them here, the secrets too, as [`Library::take_secrets_from_copy`] does; then
121	/// it revokes the replicas of the copy's device, whose keys a thief of that device may
122	/// hold. A device of the person's that turns up later does not know the new one, and is
123	/// added anew.
124	///
125	/// # Errors
126	///
127	/// Returns [`NodeError::Exists`] if a replica is here already, an error of the keys if
128	/// `unlocker` does not open the copy's, [`NodeError::AiAgentMayNot`] if the copy is an AI
129	/// agent's, [`NodeError::NewerFormats`] if a later version of NibKeep changed the copy,
130	/// and an error if the copy does not read, or the new replica cannot be made.
131	pub fn add_from_copy(
132		directory: &Path,
133		(copy, unlocker): (&Path, &Unlocker<'_>),
134		joining: Joining,
135		protection: &NewProtection<'_>,
136		secrets: Option<(&Unlocker<'_>, &NewProtection<'_>)>,
137		now: &dyn Fn() -> u64,
138		rng: &mut impl CryptoRng,
139	) -> Result<Self, NodeError> {
140		match Self::replica_folder(directory) {
141			Err(NodeError::NoLibrary | NodeError::Copied) => {}
142			_ => return Err(NodeError::Exists),
143		}
144		// A copy that a later version changed is read by none of its files.
145		crate::engines::check(copy)?;
146		// The secrets' unlocker is tried first, so that a mistyped passphrase leaves nothing
147		// made.
148		if let Some((unlocker, _)) = secrets {
149			KeyFile::read(&copy.join(KEYS))?.unlock_secrets(unlocker)?;
150		}
151		// Before the private copy is made there, as a program that syncs the folder would take
152		// it to the cloud.
153		Self::check_place(directory)?;
154		// The private copy is of this computer's, beside the replicas, where the folders of
155		// replicas that are being made are too.
156		let replicas = directory.join(REPLICAS);
157		fs::create_dir_all(&replicas).map_err(NodeError::file(&replicas))?;
158		let private = private_folder(&replicas, "private", rng)?;
159		let added = (|| {
160			let mut sponsor = open_privately(copy, unlocker, &private, now, rng)?;
161			sponsor.check_not_ai_agent("add devices")?;
162			let old = sponsor.info.device;
163			// The new device takes the spaces that the copy holds, and asks before it takes a
164			// space given to it later if the copy did.
165			let device = sponsor.as_new_device()?;
166			let mut library = pair_in_process(
167				&mut sponsor,
168				directory,
169				(joining, &device),
170				protection,
171				now,
172				rng,
173			)?;
174			// Then the spaces settle between the two, as they do after every pairing, before
175			// the copy goes.
176			if let Err(error) = spaces_in_process(&mut sponsor, &mut library, now, rng) {
177				library.remove_unsynced();
178				return Err(error);
179			}
180			drop(sponsor);
181			// The new device is known only to the private copy, which goes: if what follows
182			// fails, it goes too, and the person can begin again.
183			let finished = (|| {
184				library.take_in_from(copy, now)?;
185				// Before the copy's device is revoked, whose secrets would be lost with it.
186				if let Some((unlocker, protection)) = secrets {
187					library.take_secrets_from_copy(copy, unlocker, protection, now(), rng)?;
188				}
189				let revoking: Vec<EntityId> = library
190					.replicas()?
191					.into_iter()
192					.filter(|replica| {
193						!replica.this && !replica.revoked && replica.device == Some(old)
194					})
195					.map(|replica| replica.id)
196					.collect();
197				if !revoking.is_empty() {
198					library.revoke(&revoking, now(), rng)?;
199				}
200				Ok::<(), NodeError>(())
201			})();
202			match finished {
203				Ok(()) => Ok(library),
204				Err(error) => {
205					library.remove_unsynced();
206					Err(error)
207				}
208			}
209		})();
210		let _ = fs::remove_dir_all(&private);
211		added
212	}
213
214	/// Takes in what the copy in `copy` holds and this replica lacks, as
215	/// [`Library::take_in_copies`] does.
216	///
217	/// # Errors
218	///
219	/// As [`Library::take_in_copies`].
220	pub fn take_in_from(
221		&mut self,
222		copy: &Path,
223		now: &dyn Fn() -> u64,
224	) -> Result<TakenIn, NodeError> {
225		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
226		self.take_in(&[copy.to_owned()], &spaces, As::ThisReplica, now)
227	}
228
229	/// Takes in what the replica in `folder`, of a lost device, holds of `spaces` and this
230	/// replica lacks, as [`Library::take_in_copies`] does, but taking each change as from its
231	/// author, as a backup's are, so that what a replica that the space ended made after that
232	/// is left out. Returns how many changes, keys and blobs were new.
233	///
234	/// # Errors
235	///
236	/// As [`Library::take_in_copies`].
237	pub(crate) fn take_in_lost_replica(
238		&mut self,
239		folder: &Path,
240		spaces: &[SpaceId],
241		now: &dyn Fn() -> u64,
242	) -> Result<usize, NodeError> {
243		Ok(self
244			.take_in(&[folder.to_owned()], spaces, As::Authors, now)?
245			.items)
246	}
247
248	/// Adds a new replica of this library in `directory`, which `joining` asks for, as
249	/// pairing does, but in this process and without a network: pairing, then the new
250	/// replica's first sync, which brings it the personal space. `now` is the new replica's
251	/// wall clock; this one makes its changes at the time pairing starts. Benchmarks time a
252	/// first sync with it.
253	///
254	/// # Errors
255	///
256	/// Returns an error if this replica cannot sponsor one, `directory` holds a library
257	/// already, or the first sync fails, in which case the new replica is removed.
258	pub fn pair_in_process(
259		&mut self,
260		directory: &Path,
261		joining: Joining,
262		protection: &NewProtection<'_>,
263		now: &dyn Fn() -> u64,
264		rng: &mut impl CryptoRng,
265	) -> Result<Self, NodeError> {
266		pair_in_process(
267			self,
268			directory,
269			(joining, &NewDevice::computer()),
270			protection,
271			now,
272			rng,
273		)
274	}
275
276	/// What a device made from this replica, a copy's, is to take: the spaces that it holds,
277	/// but those whose drop it stated, and, as it says, the spaces given to it later or not. A
278	/// space that it was dropping, and still holds, it takes, as its blobs whose copies
279	/// elsewhere were not proven yet may be only in the copy.
280	fn as_new_device(&self) -> Result<NewDevice, NodeError> {
281		let mut spaces = Vec::new();
282		for space in self.spaces() {
283			if space != self.info.personal && self.holds_here(space)? {
284				spaces.push(space);
285			}
286		}
287		let device = if self.takes_new_spaces()? {
288			NewDevice::computer()
289		} else {
290			NewDevice::phone()
291		};
292		Ok(device.with_spaces(spaces))
293	}
294
295	/// Takes in what the copies beside this replica hold and it lacks, in the spaces that it
296	/// holds: changes, the keys of statements and blobs, and sealed blobs, as a sync takes
297	/// in what another replica sends, checking each. The copies' keys are not needed, and
298	/// nothing of them is written to. `now` is the wall clock, read as each change comes in.
299	///
300	/// # Errors
301	///
302	/// Returns an error if what is taken in cannot be saved. A copy whose log does not read,
303	/// or that a later version of NibKeep changed, is passed over.
304	pub fn take_in_copies(&mut self, now: &dyn Fn() -> u64) -> Result<TakenIn, NodeError> {
305		let copies: Vec<PathBuf> = self.copies().into_iter().map(|copy| copy.folder).collect();
306		let spaces: Vec<SpaceId> = self.spaces.keys().copied().collect();
307		self.take_in(&copies, &spaces, As::ThisReplica, now)
308	}
309
310	/// Takes in what `copies` hold of `spaces`, each change taken as `taken_as` says.
311	fn take_in(
312		&mut self,
313		copies: &[PathBuf],
314		spaces: &[SpaceId],
315		taken_as: As,
316		now: &dyn Fn() -> u64,
317	) -> Result<TakenIn, NodeError> {
318		let mut taken = TakenIn::default();
319		// Private copies of the copies' logs go in this replica's own folder, never where
320		// another user of the computer could have made a folder of the name first.
321		let own = self.directory.clone();
322		remove_private_folders(&own, "taking-in");
323		let mut rng = Derived::seeded(&own, now());
324		let mut syncing = Syncing::new(self, now);
325		for copy in copies {
326			// A copy of a later version, or whose engines file does not read, gives nothing.
327			if crate::engines::check(copy).is_err() {
328				continue;
329			}
330			let mut read = false;
331			for &space in spaces {
332				let log = log_path(copy, space);
333				if !log.exists() {
334					continue;
335				}
336				let private = private_folder(&own, "taking-in", &mut rng)?;
337				let took = take_copied_log(&log, &private, &mut |item| {
338					let new = take(&mut syncing, space, item, taken_as).map_err(Taking::Here)?;
339					taken.items += usize::from(new);
340					Ok::<(), Taking>(())
341				});
342				let _ = fs::remove_dir_all(&private);
343				match took {
344					Ok(()) => read = true,
345					// A copy whose log does not read, as one damaged or not a log at all,
346					// gives nothing, and the others are still read.
347					Err(Taking::Copy) => {}
348					// What this replica cannot save is an error of its own.
349					Err(Taking::Here(error)) => return Err(error),
350				}
351				syncing.finish_space(space)?;
352			}
353			taken.copies += usize::from(read);
354		}
355		Ok(taken)
356	}
357}
358
359impl Library {
360	/// Whether a program that syncs folders syncs this library's folder, as the marks it
361	/// leaves in the folder or above it show, or as the copies beside this replica do, when
362	/// their files changed since this replica last looked: only the first time that it is
363	/// found, so that the person is told once. NibKeep syncs on its own, and such a program
364	/// puts every replica's key file on every computer and with its provider.
365	///
366	/// # Errors
367	///
368	/// Returns an error if what this replica saw cannot be saved.
369	pub fn told_of_syncing(&self) -> Result<bool, NodeError> {
370		let path = self.directory.join(SEEN);
371		let before = Seen::read(&path);
372		if before.told {
373			return Ok(false);
374		}
375		let now = Seen {
376			told: before.told,
377			copies: self
378				.copies()
379				.iter()
380				.filter_map(|copy| {
381					let name = copy.folder.file_name()?.to_string_lossy().into_owned();
382					Some((name, look(&copy.folder)))
383				})
384				.collect(),
385		};
386		let changed = now.copies.iter().any(|(name, looks)| {
387			before
388				.copies
389				.iter()
390				.any(|(was, looked)| was == name && looked != looks)
391		});
392		let marked = self.directory.ancestors().any(|folder| {
393			MARKS.iter().any(|(mark, file)| {
394				fs::metadata(folder.join(mark)).is_ok_and(|found| found.is_file() == *file)
395			}) || fs::read_dir(folder)
396				.into_iter()
397				.flatten()
398				.flatten()
399				.any(|entry| {
400					let name = entry.file_name().to_string_lossy().into_owned();
401					name.starts_with(".sync_")
402						&& Path::new(&name)
403							.extension()
404							.is_some_and(|extension| extension.eq_ignore_ascii_case("db"))
405				})
406		});
407		let tell = !now.told && (changed || marked);
408		let seen = Seen {
409			told: now.told || tell,
410			..now
411		};
412		if seen != before {
413			write_file(&path, &cbor::to_vec(&seen))?;
414		}
415		Ok(tell)
416	}
417}
418
419/// How the copies beside a replica looked, and whether the person was told that a program
420/// syncs the folder. In CBOR, `[1, told, [[name, looks], …]]`.
421#[derive(Clone, Debug, Default, PartialEq, Eq)]
422struct Seen {
423	told: bool,
424	copies: Vec<(String, [u8; 32])>,
425}
426
427impl Seen {
428	/// What a replica saw before, or nothing if it saw nothing, or what it saw does not read.
429	fn read(path: &Path) -> Self {
430		fs::read(path)
431			.ok()
432			.and_then(|bytes| cbor::from_slice(&bytes).ok())
433			.unwrap_or_default()
434	}
435}
436
437impl ToCbor for Seen {
438	fn to_cbor(&self) -> Value {
439		Value::Array(vec![
440			1u8.to_cbor(),
441			Value::Bool(self.told),
442			Value::Array(
443				self.copies
444					.iter()
445					.map(|(name, looks)| {
446						Value::Array(vec![name.to_cbor(), Value::Bytes(looks.to_vec())])
447					})
448					.collect(),
449			),
450		])
451	}
452}
453
454impl FromCbor for Seen {
455	fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
456		const EXPECTED: &str = "what copies looked like: [1, told, [[name, looks], …]]";
457		let Value::Array(items) = value else {
458			return Err(cbor::Error::Expected(EXPECTED));
459		};
460		let [suite, told, copies] = items.as_slice() else {
461			return Err(cbor::Error::Expected(EXPECTED));
462		};
463		if u8::from_cbor(suite) != Ok(1) {
464			return Err(cbor::Error::Expected(EXPECTED));
465		}
466		let Value::Array(copies) = copies else {
467			return Err(cbor::Error::Expected(EXPECTED));
468		};
469		let copies = copies
470			.iter()
471			.map(|copy| match copy {
472				Value::Array(pair) => match pair.as_slice() {
473					[name, Value::Bytes(looks)] => Ok((
474						String::from_cbor(name)?,
475						<[u8; 32]>::try_from(looks.as_slice())
476							.map_err(|_| cbor::Error::Expected(EXPECTED))?,
477					)),
478					_ => Err(cbor::Error::Expected(EXPECTED)),
479				},
480				_ => Err(cbor::Error::Expected(EXPECTED)),
481			})
482			.collect::<Result<_, _>>()?;
483		Ok(Self {
484			told: bool::from_cbor(told)?,
485			copies,
486		})
487	}
488}
489
490/// How a copy looks: a hash of the sizes and times of its files but its blobs and those it
491/// was writing, which a program that syncs it changes as the replica it copies writes.
492fn look(folder: &Path) -> [u8; 32] {
493	let mut hasher = blake3::Hasher::new();
494	let mut files = Vec::new();
495	gather(folder, folder, &mut files);
496	files.sort();
497	for (path, size, written) in files {
498		hasher.update(path.as_bytes());
499		hasher.update(&size.to_le_bytes());
500		hasher.update(&written.to_le_bytes());
501	}
502	*hasher.finalize().as_bytes()
503}
504
505/// The files in a copy's folder but its blobs and those it was writing, with their sizes and
506/// when they were written.
507fn gather(root: &Path, folder: &Path, files: &mut Vec<(String, u64, u128)>) {
508	for entry in fs::read_dir(folder).into_iter().flatten().flatten() {
509		let path = entry.path();
510		match entry.file_type() {
511			Ok(kind) if kind.is_dir() => {
512				if entry.file_name() != "blobs" && entry.file_name() != "tmp" {
513					gather(root, &path, files);
514				}
515			}
516			Ok(_) => {
517				let Ok(metadata) = entry.metadata() else {
518					continue;
519				};
520				let written = metadata
521					.modified()
522					.ok()
523					.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
524					.map_or(0, |since| since.as_nanos());
525				let name = path
526					.strip_prefix(root)
527					.unwrap_or(&path)
528					.to_string_lossy()
529					.into_owned();
530				files.push((name, metadata.len(), written));
531			}
532			Err(_) => {}
533		}
534	}
535}
536
537/// Opens a copy of a replica in `private`, a folder of the caller's own: its keys, which
538/// `unlocker` opens, in a key file of that folder's, under a passphrase drawn anew, its
539/// library file, and private copies of its logs, checked first as what another computer
540/// wrote. The copy itself is only read.
541fn open_privately(
542	copy: &Path,
543	unlocker: &Unlocker<'_>,
544	private: &Path,
545	now: &dyn Fn() -> u64,
546	rng: &mut impl CryptoRng,
547) -> Result<Library, NodeError> {
548	let key_file = KeyFile::read(&copy.join(KEYS))?;
549	let replica = key_file.replica(&key_file.unlock_replica(unlocker)?)?;
550	let info = Info::read(&copy.join(INFO))?;
551	fs::create_dir_all(private).map_err(NodeError::file(private))?;
552	// The private folder is placed by its path, as the copy's folder is not here.
553	declare_drive(private, Drive::default(), None);
554	let directory = private.join("library");
555	let folder = new_replica_folder(&directory, now(), rng)?;
556	let mut passphrase = [0u8; 32];
557	rng.fill_bytes(&mut passphrase);
558	let passphrase = super::hex(&passphrase);
559	let params =
560		PassphraseParams::new(64, 1, 1).map_err(|error| NodeError::Damaged(error.to_string()))?;
561	let (mut private_keys, compartment) = KeyFile::create(
562		&replica,
563		&NewProtection::Passphrase(&passphrase, params),
564		rng,
565	)?;
566	private_keys.write(&folder.join(KEYS))?;
567	info.write(&folder.join(INFO))?;
568	// Its spaces start empty, and take in what the copy's hold, checked as what another
569	// replica sends: the copy's logs, which another computer may have written, are never
570	// opened as logs of this computer's.
571	let mut library = Library::open_spaces(&folder, private_keys, compartment, true)?;
572	library.take_in_from(copy, now)?;
573	library.finish_opening()?;
574	Ok(library)
575}
576
577/// Adds a new replica, which `joining` asks for, in `directory`, as `sponsor` pairs with it,
578/// in this process, through two pipes in memory: pairing, then the new replica's first sync.
579fn pair_in_process(
580	sponsor: &mut Library,
581	directory: &Path,
582	(joining, device): (Joining, &NewDevice),
583	protection: &NewProtection<'_>,
584	now: &dyn Fn() -> u64,
585	rng: &mut impl CryptoRng,
586) -> Result<Library, NodeError> {
587	let code = PairingCode::generate(rng);
588	let (sponsor_end, joiner_end) = (sponsor.endpoint(), endpoint_of(&joining.endpoint_secret()));
589	let (mut pairing, mut joining_end) = pipes(rng, sponsor_end, joiner_end);
590	let (mut answering, mut syncing_end) = pipes(rng, sponsor_end, joiner_end);
591	let mut sponsor_rng = Derived::from(rng);
592	// The sponsor's side makes its changes at the time the pairing starts.
593	let started = now();
594	let sponsor_now = move || started;
595	let sponsor_code = code.clone();
596	std::thread::scope(|scope| {
597		let sponsored = scope.spawn(move || -> Result<(), NodeError> {
598			nibkeep_sync::sponsor(
599				&mut pairing,
600				&mut Sponsor::new(sponsor, &sponsor_now).for_device(device.clone()),
601				&sponsor_code,
602				&mut sponsor_rng,
603			)?;
604			nibkeep_sync::respond(&mut answering, &mut Syncing::new(sponsor, &sponsor_now))?;
605			Ok(())
606		});
607		let joined = (|| {
608			let grant = nibkeep_sync::join(&mut joining_end, &joining.request(), &code, rng)?;
609			let mut library = joining.make(directory, &grant, protection, rng)?;
610			let listings = library.pairing_listings(&grant);
611			let synced = nibkeep_sync::joined(&mut joining_end, grant.clone(), listings)
612				.map_err(NodeError::from)
613				.and_then(|_| {
614					let mut syncing = Syncing::new(&mut library, now).trusting(grant.sponsor);
615					nibkeep_sync::initiate(&mut syncing_end, &mut syncing).map_err(NodeError::from)
616				});
617			match synced {
618				Ok(_) => {
619					// It takes the spaces given to it as it paired, then says, as the person
620					// chose, whether it takes those given to it later, as a pairing over the
621					// network does.
622					let _ = library.settle_keys(now(), rng);
623					let _ = library.take_paired_spaces(now(), rng);
624					if grant.asks_first {
625						let _ = library.set_takes_new_spaces(false, now(), rng);
626					}
627					Ok(library)
628				}
629				Err(error) => {
630					library.remove_unsynced();
631					Err(error)
632				}
633			}
634		})();
635		// So that the sponsor's side ends, if this side stopped early.
636		drop((joining_end, syncing_end));
637		let sponsored = sponsored
638			.join()
639			.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
640		let library = joined?;
641		sponsored?;
642		Ok(library)
643	})
644}
645
646/// Settles the user's spaces between the private copy and the new replica that it paired,
647/// syncing them in this process: the copy gives the new replica its spaces, the new one asks
648/// to be listed in them, and the copy lists it, so that it can take in the copy's logs of
649/// every space before the copy's device is revoked.
650fn spaces_in_process(
651	sponsor: &mut Library,
652	library: &mut Library,
653	now: &dyn Fn() -> u64,
654	rng: &mut impl CryptoRng,
655) -> Result<(), NodeError> {
656	// What fails to settle leaves the spaces it concerns to the next sync, as pairing does;
657	// only a failed sync stops it.
658	for _ in 0..3 {
659		let _ = sponsor.settle_spaces(now(), rng);
660		sync_in_process(library, sponsor, now, rng)?;
661		let _ = library.settle_keys(now(), rng);
662		sync_in_process(library, sponsor, now, rng)?;
663	}
664	Ok(())
665}
666
667/// Syncs two libraries open in this process: `first` connects to `second`.
668fn sync_in_process(
669	first: &mut Library,
670	second: &mut Library,
671	now: &dyn Fn() -> u64,
672	rng: &mut impl CryptoRng,
673) -> Result<(), NodeError> {
674	let (mut connecting, mut answering) = pipes(rng, first.endpoint(), second.endpoint());
675	// Both sides at one time, as the closure is not shared between threads.
676	let at = now();
677	let answering_now = move || at;
678	std::thread::scope(|scope| {
679		let answered = scope.spawn(move || {
680			let synced =
681				nibkeep_sync::respond(&mut answering, &mut Syncing::new(second, &answering_now));
682			drop(answering);
683			synced
684		});
685		let synced = nibkeep_sync::initiate(&mut connecting, &mut Syncing::new(first, now));
686		drop(connecting);
687		let answered = answered
688			.join()
689			.unwrap_or_else(|panic| std::panic::resume_unwind(panic));
690		synced?;
691		answered?;
692		Ok(())
693	})
694}
695
696/// One end of a pipe in memory, between two sides in one process.
697struct Pipe {
698	to: mpsc::Sender<Vec<u8>>,
699	from: mpsc::Receiver<Vec<u8>>,
700	/// A message taken from `from` to tell whether one had arrived, and not yet received.
701	early: Option<Result<Vec<u8>, TransportError>>,
702	binding: [u8; 32],
703	own: [u8; 32],
704	peer: [u8; 32],
705}
706
707/// The two ends of a pipe in memory, with a binding drawn anew: the first end is `first`'s,
708/// and the second `second`'s.
709fn pipes(rng: &mut impl CryptoRng, first: [u8; 32], second: [u8; 32]) -> (Pipe, Pipe) {
710	let mut binding = [0u8; 32];
711	rng.fill_bytes(&mut binding);
712	let (to_second, from_first) = mpsc::channel();
713	let (to_first, from_second) = mpsc::channel();
714	(
715		Pipe {
716			to: to_second,
717			from: from_second,
718			early: None,
719			binding,
720			own: first,
721			peer: second,
722		},
723		Pipe {
724			to: to_first,
725			from: from_first,
726			early: None,
727			binding,
728			own: second,
729			peer: first,
730		},
731	)
732}
733
734impl Transport for Pipe {
735	fn send(&mut self, message: &[u8]) -> Result<(), TransportError> {
736		self.to
737			.send(message.to_vec())
738			.map_err(|_| TransportError("the other side ended".to_owned()))
739	}
740
741	fn receive(&mut self) -> Result<Vec<u8>, TransportError> {
742		self.early.take().unwrap_or_else(|| {
743			self.from
744				.recv()
745				.map_err(|_| TransportError("the other side ended".to_owned()))
746		})
747	}
748
749	fn has_message(&mut self) -> bool {
750		if self.early.is_none() {
751			self.early = match self.from.try_recv() {
752				Ok(message) => Some(Ok(message)),
753				Err(mpsc::TryRecvError::Empty) => None,
754				Err(mpsc::TryRecvError::Disconnected) => {
755					Some(Err(TransportError("the other side ended".to_owned())))
756				}
757			};
758		}
759		self.early.is_some()
760	}
761
762	fn binding(&self) -> [u8; 32] {
763		self.binding
764	}
765
766	fn own_endpoint(&self) -> [u8; 32] {
767		self.own
768	}
769
770	fn peer_endpoint(&self) -> [u8; 32] {
771		self.peer
772	}
773}
774
775/// Random numbers for a second side in one process: BLAKE3's extendable output, keyed
776/// with 32 bytes of the caller's generator.
777struct Derived(blake3::OutputReader);
778
779impl Derived {
780	/// Random enough for the names of private folders, where no caller's generator is at
781	/// hand: a hash of the folder, the time, the process and the clock's nanoseconds. The
782	/// names need only be new, as the folder they go in is this replica's own.
783	fn seeded(folder: &Path, now: u64) -> Self {
784		let mut hasher = blake3::Hasher::new();
785		hasher.update(b"nibkeep 2026-10 private folders");
786		hasher.update(folder.as_os_str().as_encoded_bytes());
787		hasher.update(&now.to_le_bytes());
788		hasher.update(&std::process::id().to_le_bytes());
789		let unique = std::time::SystemTime::now()
790			.duration_since(std::time::UNIX_EPOCH)
791			.map_or(0, |since| since.as_nanos());
792		hasher.update(&unique.to_le_bytes());
793		Self(hasher.finalize_xof())
794	}
795
796	fn from(rng: &mut impl CryptoRng) -> Self {
797		let mut seed = [0u8; 32];
798		rng.fill_bytes(&mut seed);
799		Self(
800			blake3::Hasher::new_keyed(&seed)
801				.update(b"nibkeep 2026-10 second side")
802				.finalize_xof(),
803		)
804	}
805}
806
807impl TryRng for Derived {
808	type Error = Infallible;
809
810	fn try_next_u32(&mut self) -> Result<u32, Infallible> {
811		let mut bytes = [0; 4];
812		self.0.fill(&mut bytes);
813		Ok(u32::from_le_bytes(bytes))
814	}
815
816	fn try_next_u64(&mut self) -> Result<u64, Infallible> {
817		let mut bytes = [0; 8];
818		self.0.fill(&mut bytes);
819		Ok(u64::from_le_bytes(bytes))
820	}
821
822	fn try_fill_bytes(&mut self, destination: &mut [u8]) -> Result<(), Infallible> {
823		self.0.fill(destination);
824		Ok(())
825	}
826}
827
828impl TryCryptoRng for Derived {}
829
830/// Whom a change taken in from a copy is taken as from.
831#[derive(Clone, Copy)]
832enum As {
833	/// This replica, of whose device the copy is: the space ends it only if it ends this one
834	/// too.
835	ThisReplica,
836	/// Its author, as a backup's changes are: what a replica that the space ended made after
837	/// that is left out.
838	Authors,
839}
840
841/// Why taking in a copy's log stopped: the copy's log did not read, which passes the copy
842/// over, or what it held could not be saved here, which is an error.
843enum Taking {
844	Copy,
845	Here(NodeError),
846}
847
848impl From<nibkeep_store::StoreError> for Taking {
849	fn from(_: nibkeep_store::StoreError) -> Self {
850		Self::Copy
851	}
852}
853
854/// Makes a new folder of this process's own in `parent`, under a name that starts with a dot
855/// and is drawn at random, which only its owner reaches: for private copies of copies.
856fn private_folder(
857	parent: &Path,
858	what: &str,
859	rng: &mut impl CryptoRng,
860) -> Result<PathBuf, NodeError> {
861	let mut name = [0u8; 8];
862	rng.fill_bytes(&mut name);
863	let folder = parent.join(format!(".{what}-{}", super::hex(&name)));
864	#[cfg(unix)]
865	let builder = {
866		let mut builder = fs::DirBuilder::new();
867		std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
868		builder
869	};
870	#[cfg(not(unix))]
871	let builder = fs::DirBuilder::new();
872	builder.create(&folder).map_err(NodeError::file(&folder))?;
873	Ok(folder)
874}
875
876/// Removes the private folders that a crash left in a replica's own folder.
877fn remove_private_folders(own: &Path, what: &str) {
878	let prefix = format!(".{what}-");
879	for entry in fs::read_dir(own).into_iter().flatten().flatten() {
880		if entry.file_name().to_string_lossy().starts_with(&prefix) {
881			let _ = fs::remove_dir_all(entry.path());
882		}
883	}
884}
885
886/// Takes in one item of a copy, as a sync takes in what another replica sends, a change as
887/// from whom `taken_as` says; whether it was new.
888fn take(
889	syncing: &mut Syncing<'_>,
890	space: SpaceId,
891	item: CopiedItem,
892	taken_as: As,
893) -> Result<bool, NodeError> {
894	match item {
895		// A copy is of this device: what it holds is taken as from this replica, which the
896		// space ends only if it ends this one too; a lost device's, as from their authors.
897		CopiedItem::Change(parcel) => {
898			let from = match taken_as {
899				As::ThisReplica => syncing.verifying_key(),
900				As::Authors => *parcel.change.author(),
901			};
902			syncing.receive_change(space, &from, *parcel)
903		}
904		CopiedItem::RecordKey(statement, key) => syncing.receive_record_key(space, statement, key),
905		CopiedItem::BlobKey(sealed, key) => syncing.receive_blob_key(space, sealed, key),
906		CopiedItem::Blob(sealed, path) => {
907			// Read from the copy's file, and checked against its sealed hash as it is
908			// written here: never linked to the copy's.
909			let Ok(file) = fs::File::open(&path) else {
910				return Ok(false);
911			};
912			let size = file.metadata().map_or(0, |metadata| metadata.len());
913			let mut bytes: Box<dyn Read> = Box::new(file);
914			syncing.receive_blob(space, sealed, size, &mut bytes)
915		}
916	}
917}