git clone https://garage44.eu/jeroen/pinnacle.git.. /programs/src/bin/sync.rs
//! The sync service: keeps the vault's files in step with the person's
//! other devices (`docs/backup-and-sync.md`), in the background, with no
//! window. A system program, `system-sync`, so installed apps cannot reach
//! it; it runs once the vault is open.
//!
//! Every ten seconds it looks at what changed in the vault, hashing only
//! files whose size or time changed (`pinnacle_sync::Index`). With each of
//! the person's own devices (`pinnacle_ui::p2p::OWN`) it syncs every 30 s,
//! and a few seconds after a change here; the logic is `pinnacle_sync`'s,
//! carried over a p2p stream (`pinnacle_ui::p2p::SYNC`). A device that
//! syncs with this one reaches it through its p2p service, which says
//! first which device it is. Settings asks it for a backup to the disk
//! labelled `backup`, or a restore from one (`pinnacle_ui::p2p::backup`).
//!
//! Kept in the vault, and not in step themselves:
//! - `data:/sync/index`: what each file hashed to;
//! - `data:/sync/base/<device>`: what this device and that one last agreed
//! on, kept by the one of the two with the lower key, which decides;
//! - `data:/sync/last/<device>`: when the last sync with it ended, and how
//! (`<seconds since 1970> <copied> <merged> <conflicts> <failed>`), for Settings.
#![no_std]
#![no_main]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_rt::{Channel, Received, fs, println};
use pinnacle_sync::{Files, Index, Sync, backup};
use pinnacle_ui::p2p::{self as protocol, Key};
const SCAN_MS: u64 = 10_000;
/// With each own device at least this often.
const EVERY_MS: u64 = 30_000;
/// After a change here, this soon.
const CHANGED_MS: u64 = 3000;
/// A sync that hears nothing for this long is given up.
const QUIET_MS: u64 = 120_000;
/// Waiting for the p2p service, and for the vault.
const WAIT_MS: u64 = 2000;
fn hex(key: &Key) -> String {
key[..16].iter().map(|b| alloc::format!("{b:02x}")).collect()
}
fn data(path: &str) -> String {
alloc::format!("data:{path}")
}
/// The vault, as `pinnacle_sync` reads and writes it.
struct Vault;
impl Files for Vault {
fn read(&mut self, path: &str) -> Option<Vec<u8>> {
fs::read(&data(path))
}
fn write(&mut self, path: &str, bytes: &[u8]) -> bool {
// Its folders first, from the top.
let mut at = 0;
while let Some(i) = path[at + 1..].find('/') {
at += i + 1;
fs::create_dir(&data(&path[..at]));
}
fs::write(&data(path), bytes)
}
fn remove(&mut self, path: &str) -> bool {
fs::remove(&data(path))
}
}
/// Every file in the vault below `dir` (a vault path ending in `/`): path,
/// size, time of change.
fn walk(dir: &str, out: &mut Vec<(String, u64, u64)>) {
for name in fs::list(&data(dir)).unwrap_or_default() {
let path = alloc::format!("{dir}{name}");
if name.ends_with('/') {
if path != "/sync/" {
walk(&path, out);
}
} else if let Some(stat) = fs::stat(&data(&path)) {
out.push((path, stat.size, stat.modified));
}
}
}
/// Seconds since 1970 from the board's clock, else since the start.
fn now_s() -> u64 {
match pinnacle_rt::clock() {
0 => pinnacle_rt::time() / 1000,
s => s,
}
}
/// A sync with one device, running.
struct Run {
device: Key,
channel: Channel,
sync: Sync,
heard: u64,
/// Whether this device opened it.
opened: bool,
}
/// What this device knows of each own device: when a sync with it was
/// last tried, and the manifest's generation it ended at.
struct Known {
device: Key,
tried: Option<u64>,
synced_at: Option<u64>,
}
struct Service {
me: Key,
name: String,
index: Index,
manifest: Vec<pinnacle_sync::Entry>,
/// Bumped at every scan that found a change.
generation: u64,
runs: Vec<Run>,
known: Vec<Known>,
}
impl Service {
fn scan(&mut self) {
let mut stats = Vec::new();
walk("/", &mut stats);
let manifest = self.index.refresh(&stats, now_s(), &mut |p| fs::read(&data(p)));
if manifest != self.manifest {
self.manifest = manifest;
self.generation += 1;
fs::create_dir("data:/sync");
fs::write("data:/sync/index", &self.index.to_bytes());
}
}
fn base(&self, device: &Key) -> Vec<pinnacle_sync::Agreed> {
fs::read(&alloc::format!("data:/sync/base/{}", hex(device)))
.map(|b| pinnacle_sync::base_from_bytes(&b))
.unwrap_or_default()
}
fn start(&mut self, device: Key, channel: Channel, opened: bool, now: u64) {
let decides = self.me < device;
let base = if decides { self.base(&device) } else { Vec::new() };
let mut run = Run {
device,
channel,
sync: Sync::new(decides, &self.name, self.manifest.clone(), base),
heard: now,
opened,
};
pump(&mut run);
self.runs.push(run);
if let Some(k) = self.known.iter_mut().find(|k| k.device == device) {
k.tried = Some(now);
}
}
/// Opens a sync with each own device that is due one.
fn due(&mut self, now: u64) {
let own = protocol::own_devices();
self.known.retain(|k| own.contains(&k.device));
for device in own {
if !self.known.iter().any(|k| k.device == device) {
self.known.push(Known {
device,
tried: None,
synced_at: None,
});
}
if self.runs.iter().any(|r| r.device == device) {
continue;
}
let k = self.known.iter().find(|k| k.device == device).unwrap();
let changed = k.synced_at != Some(self.generation);
let wait = if changed { CHANGED_MS } else { EVERY_MS };
if k.tried.is_some_and(|t| now - t < wait) {
continue;
}
if let Some(channel) = protocol::sync_with(&device) {
self.start(device, channel, true, now);
}
}
}
/// A connection from another device's sync, through the p2p service,
/// whose first message said which device it is.
fn incoming(&mut self, device: Key, channel: Channel, now: u64) {
if !protocol::own_devices().contains(&device) {
return;
}
if let Some(i) = self.runs.iter().position(|r| r.device == device) {
// Both opened at once: the one the deciding device opened stays.
let theirs_wins = !(self.me < device);
if !(theirs_wins && self.runs[i].opened) {
return;
}
self.runs.remove(i);
}
self.start(device, channel, false, now);
}
/// A run is over: its outcome kept, the p2p service told of contacts
/// that changed.
fn finish(&mut self, i: usize) {
let run = self.runs.remove(i);
let Some(o) = run.sync.outcome() else {
println!("sync: with {} cut off", run.sync.other());
return;
};
let device = hex(&run.device);
fs::create_dir("data:/sync/base");
fs::create_dir("data:/sync/last");
if let Some(base) = &o.base {
fs::write(
&alloc::format!("data:/sync/base/{device}"),
&pinnacle_sync::base_to_bytes(base),
);
}
let last = alloc::format!(
"{} {} {} {} {}",
now_s(),
o.copied,
o.merged,
o.conflicts,
o.failed
);
fs::write(&alloc::format!("data:/sync/last/{device}"), last.as_bytes());
if o.changed.iter().any(|p| p.starts_with("/p2p/")) {
protocol::reload();
}
println!(
"sync: in step with {}: {} copied, {} merged, {} kept twice, {} failed",
run.sync.other(),
o.copied,
o.merged,
o.conflicts,
o.failed
);
for path in o.changed.iter().take(20) {
println!("sync: changed {path}");
}
// What it wrote is seen at the next scan; it need not sync again
// for that alone.
let changed_here = !o.changed.is_empty();
if changed_here {
self.scan();
}
let generation = self.generation;
if let Some(k) = self.known.iter_mut().find(|k| k.device == run.device) {
k.synced_at = Some(generation);
}
}
}
/// Where this device's backup is on the backup disk.
fn backup_dir(me: &Key) -> String {
alloc::format!("{}:/pinnacle/{}", protocol::BACKUP_DISK, hex(me))
}
fn random<const N: usize>() -> [u8; N] {
let mut b = [0u8; N];
pinnacle_rt::random(&mut b);
b
}
impl Service {
/// Backs the vault up to the backup disk, sealed under `password`
/// (`pinnacle_sync::backup`): the files it holds and those written now.
/// A password that does not open the backup's key starts it afresh.
fn backup(&mut self, password: &str) -> Option<(u32, u32)> {
fs::disk(protocol::BACKUP_DISK)?;
self.scan();
let dir = backup_dir(&self.me);
fs::create_dir(&alloc::format!("{}:/pinnacle", protocol::BACKUP_DISK));
fs::create_dir(&dir);
fs::create_dir(&alloc::format!("{dir}/blobs"));
let key_path = alloc::format!("{dir}/key");
let key = match fs::read(&key_path).and_then(|k| backup::open_key(password, &k)) {
Some(key) => key,
None => {
let key = random::<32>();
let sealed = backup::seal_key(password, random(), backup::ROUNDS, &key);
if !fs::write(&key_path, &sealed) {
return None;
}
key
}
};
let present = fs::list(&alloc::format!("{dir}/blobs")).unwrap_or_default();
let (write, stale) = backup::backup_plan(&key, &self.manifest, &present);
let mut written = 0;
for e in write {
let Some(data) = fs::read(&data(&e.path)) else {
continue;
};
if pinnacle_sync::hash(&data) != e.hash {
// Changed since the scan: the next backup takes it.
continue;
}
let blob = alloc::format!("{dir}/blobs/{}", backup::blob_name(&key, &e.hash));
if fs::write(&blob, &backup::seal_blob(&key, &data)) {
written += 1;
}
}
let index = backup::index_of(&self.manifest);
if !fs::write(
&alloc::format!("{dir}/index"),
&backup::seal_index(&key, random(), &index),
) {
return None;
}
for name in stale {
fs::remove(&alloc::format!("{dir}/blobs/{name}"));
}
let files = index.len() as u32;
fs::write(
protocol::BACKUP_LAST,
alloc::format!("{} {files} {written}", now_s()).as_bytes(),
);
println!("sync: backed up {files} files, {written} written");
Some((files, written))
}
/// Puts back what a backup on the backup disk holds, the first whose key
/// `password` opens: every file this vault does not hold as it is
/// there. The files it put back, and of them those written.
fn restore(&mut self, password: &str) -> Option<(u32, u32)> {
let root = alloc::format!("{}:/pinnacle", protocol::BACKUP_DISK);
let (dir, key) = fs::list(&root)?.into_iter().find_map(|name| {
let dir = alloc::format!("{root}/{}", name.trim_end_matches('/'));
let key = backup::open_key(password, &fs::read(&alloc::format!("{dir}/key"))?)?;
Some((dir, key))
})?;
let index = backup::open_index(&key, &fs::read(&alloc::format!("{dir}/index"))?)?;
self.scan();
let mut written = 0;
let mut changed_p2p = false;
for a in backup::restore_plan(&index, &self.manifest) {
let blob = fs::read(&alloc::format!(
"{dir}/blobs/{}",
backup::blob_name(&key, &a.hash)
));
let Some(data) = blob.and_then(|b| backup::open_blob(&key, &a.hash, &b)) else {
println!("sync: {} is not whole in the backup", a.path);
continue;
};
if Vault.write(&a.path, &data) {
written += 1;
changed_p2p |= a.path.starts_with("/p2p/");
}
}
if changed_p2p {
protocol::reload();
}
self.scan();
println!("sync: restored {} files, {written} written", index.len());
Some((index.len() as u32, written))
}
}
/// Sends what the run has for the other device.
fn pump(run: &mut Run) {
while let Some(m) = run.sync.output(&mut Vault) {
if !run.channel.send(&m, Vec::new()) {
break;
}
}
}
#[unsafe(no_mangle)]
fn main(_argument: u64) -> u64 {
while fs::disk("data").is_none() {
pinnacle_rt::sleep(WAIT_MS);
}
let Some(service) = pinnacle_rt::register(protocol::SYNC_SERVICE) else {
println!("sync: could not register");
return 1;
};
let p2p = loop {
if let Some(c) = protocol::Client::connect(WAIT_MS) {
break c;
}
};
let card = p2p.card(&mut Vec::new());
let Some(me) = card.get(..32).and_then(|k| <Key>::try_from(k).ok()) else {
println!("sync: no card from the p2p service");
return 1;
};
drop(p2p);
let name = fs::read_string("system:/settings/name").unwrap_or_else(|| "Pinnacle".into());
let mut s = Service {
me,
name: name.trim().into(),
index: fs::read("data:/sync/index")
.map(|b| Index::from_bytes(&b))
.unwrap_or_default(),
manifest: Vec::new(),
generation: 0,
runs: Vec::new(),
known: Vec::new(),
};
s.scan();
println!("sync: {} files in the vault", s.manifest.len());
// Connections not yet saying which device they are from.
let mut arriving: Vec<Channel> = Vec::new();
let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
let mut next_scan = pinnacle_rt::time() + SCAN_MS;
let mut next_due = 0;
loop {
let now = pinnacle_rt::time();
if now >= next_scan {
s.scan();
next_scan = now + SCAN_MS;
}
// Not at every message of a sync running: once a second.
if now >= next_due {
s.due(now);
next_due = now + 1000;
}
let mut i = 0;
while i < s.runs.len() {
if s.runs[i].sync.outcome().is_some() || now - s.runs[i].heard >= QUIET_MS {
s.finish(i);
} else {
i += 1;
}
}
let mut channels: Vec<&Channel> = alloc::vec![&service];
channels.extend(arriving.iter());
let first_run = channels.len();
channels.extend(s.runs.iter().map(|r| &r.channel));
let deadline = (now + CHANGED_MS).min(next_scan);
let got = pinnacle_rt::receive(&channels, &mut buffer, Some(deadline));
drop(channels);
let now = pinnacle_rt::time();
match got {
Received::Message {
index: 0,
mut handles,
..
} if !handles.is_empty() => {
arriving.push(Channel(handles.remove(0)));
}
Received::Message { index, len, .. } if index >= first_run => {
let run = &mut s.runs[index - first_run];
run.heard = now;
run.sync.receive(&buffer[..len], &mut Vault);
pump(run);
}
Received::Message { index, len, .. } if index >= 1 => {
let channel = arriving.remove(index - 1);
match buffer[..len].split_first() {
Some((&protocol::SYNC_FROM, key)) => {
if let Ok(device) = <Key>::try_from(key) {
s.incoming(device, channel, now);
}
}
Some((&kind @ (protocol::BACKUP | protocol::RESTORE), password)) => {
let password = String::from_utf8_lossy(password).into_owned();
let done = if kind == protocol::BACKUP {
s.backup(&password)
} else {
s.restore(&password)
};
let mut answer = alloc::vec![u8::from(done.is_some())];
if let Some((files, written)) = done {
answer.extend_from_slice(&files.to_le_bytes());
answer.extend_from_slice(&written.to_le_bytes());
}
channel.send(&answer, Vec::new());
}
_ => {}
}
}
Received::Closed { index } if index >= first_run => {
let run = &s.runs[index - first_run];
if run.sync.outcome().is_none() {
s.finish(index - first_run);
}
}
Received::Closed { index } if index >= 1 => {
arriving.remove(index - 1);
}
_ => {}
}
}
}