use std::cell::RefCell;
use std::fmt;
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use rightkit_fs::digest::Sha256Hasher;
use rightkit_fs::lock::FileLock;
use serde::de::{Deserializer, IgnoredAny, MapAccess, Visitor};
use super::sync::{open_state_file, too_large, MAX_LEDGER_FILE_BYTES};
const HEAD_PROBE_BYTES: usize = 4096;
const READ_BUFFER_BYTES: usize = 64 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) enum ScopeState {
Bound(String),
Unbound,
Unknown,
}
struct ScopeProbe<'a>(&'a RefCell<Option<Option<String>>>);
impl<'de> Visitor<'de> for ScopeProbe<'_> {
type Value = ();
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a ledger")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<(), A::Error> {
while let Some(key) = map.next_key::<String>()? {
if key == "scope" {
let value = map.next_value::<Option<String>>()?;
*self.0.borrow_mut() = Some(value);
return Err(<A::Error as serde::de::Error>::custom("scope found"));
}
map.next_value::<IgnoredAny>()?;
}
Ok(())
}
}
pub(super) fn scope_of_head(head: &[u8]) -> ScopeState {
let found: RefCell<Option<Option<String>>> = RefCell::new(None);
let mut deserializer = serde_json::Deserializer::from_slice(head);
let _ = (&mut deserializer).deserialize_map(ScopeProbe(&found));
match found.into_inner() {
Some(Some(scope)) => ScopeState::Bound(scope),
Some(None) => ScopeState::Unbound,
None => ScopeState::Unknown,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Seen {
len: u64,
digest: [u8; 32],
scope: ScopeState,
}
impl Seen {
fn of_bytes(bytes: &[u8]) -> Self {
let mut hasher = Sha256Hasher::new();
hasher.update(bytes);
Self {
len: bytes.len() as u64,
digest: hasher.finalize_bytes(),
scope: scope_of_head(&bytes[..bytes.len().min(HEAD_PROBE_BYTES)]),
}
}
fn same_bytes(&self, other: &Seen) -> bool {
self.len == other.len && self.digest == other.digest
}
}
enum Known {
Unloaded,
Absent,
Present(Seen),
}
impl Known {
fn matches(&self, disk: &Option<Seen>) -> bool {
match (self, disk) {
(Known::Absent, None) => true,
(Known::Present(seen), Some(on_disk)) => seen.same_bytes(on_disk),
_ => false,
}
}
fn scope(&self) -> ScopeState {
match self {
Known::Present(seen) => seen.scope.clone(),
Known::Absent => ScopeState::Unbound,
Known::Unloaded => ScopeState::Unknown,
}
}
}
fn fingerprint_file(path: &Path) -> io::Result<Option<Seen>> {
let file = match open_state_file(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
if file.metadata()?.len() > MAX_LEDGER_FILE_BYTES {
return Err(too_large());
}
let mut limited = file.take(MAX_LEDGER_FILE_BYTES.saturating_add(1));
let mut hasher = Sha256Hasher::new();
let mut head: Vec<u8> = Vec::with_capacity(HEAD_PROBE_BYTES);
let mut buffer = vec![0u8; READ_BUFFER_BYTES];
let mut len: u64 = 0;
loop {
let read = limited.read(&mut buffer)?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
len = len.saturating_add(read as u64);
if head.len() < HEAD_PROBE_BYTES {
let room = HEAD_PROBE_BYTES - head.len();
head.extend_from_slice(&buffer[..read.min(room)]);
}
}
if len > MAX_LEDGER_FILE_BYTES {
return Err(too_large());
}
Ok(Some(Seen {
len,
digest: hasher.finalize_bytes(),
scope: scope_of_head(&head),
}))
}
struct GuardState {
known: Known,
expected: Option<String>,
diverged: bool,
}
pub(super) enum Disk {
Matches(ScopeState),
Differs,
}
pub(super) struct LedgerGuard {
path: PathBuf,
state: Mutex<GuardState>,
}
fn poisoned() -> String {
"cloud sync ledger guard poisoned".to_string()
}
impl LedgerGuard {
pub(super) fn new(path: PathBuf) -> Self {
Self {
path,
state: Mutex::new(GuardState {
known: Known::Unloaded,
expected: None,
diverged: false,
}),
}
}
fn file_lock(&self) -> Result<FileLock, String> {
crate::storage::ledger_file_lock(&self.path)
}
pub(super) fn record_loaded(&self, bytes: Option<&[u8]>) {
if let Ok(mut state) = self.state.lock() {
state.known = match bytes {
None => Known::Absent,
Some(bytes) => Known::Present(Seen::of_bytes(bytes)),
};
state.diverged = false;
}
}
pub(super) fn set_expected(&self, scope: Option<String>) {
if let Ok(mut state) = self.state.lock() {
state.expected = scope;
}
}
pub(super) fn is_diverged(&self) -> bool {
self.state.lock().map_or(true, |state| state.diverged)
}
pub(super) fn check(&self) -> Result<Disk, String> {
let state = self.state.lock().map_err(|_| poisoned())?;
if state.diverged {
return Ok(Disk::Differs);
}
let _lock = self.file_lock()?;
let disk = fingerprint_file(&self.path)
.map_err(|error| format!("read cloud sync ledger: {error}"))?;
if state.known.matches(&disk) {
Ok(Disk::Matches(
disk.map_or(ScopeState::Unbound, |seen| seen.scope),
))
} else {
Ok(Disk::Differs)
}
}
pub(super) fn replace(
&self,
bytes: &[u8],
write: impl FnOnce(&[u8]) -> Result<(), String>,
) -> Result<(), String> {
let mut state = self.state.lock().map_err(|_| poisoned())?;
let _lock = self.file_lock()?;
let disk = fingerprint_file(&self.path)
.map_err(|error| format!("read cloud sync ledger: {error}"))?;
if state.diverged || !state.known.matches(&disk) {
state.diverged = true;
return Err("cloud sync ledger changed since it was read; not replaced".to_string());
}
let current = state.known.scope();
let next = Seen::of_bytes(bytes);
if next.scope != current {
let allowed = match (¤t, &next.scope) {
(ScopeState::Bound(_), ScopeState::Unbound | ScopeState::Unknown) => false,
(_, ScopeState::Bound(to)) => state.expected.as_deref() == Some(to.as_str()),
(_, ScopeState::Unbound) => true,
(_, ScopeState::Unknown) => false,
};
if !allowed {
return Err(
"cloud sync ledger account change refused: not the account established for this pass"
.to_string(),
);
}
}
match write(bytes) {
Ok(()) => {
state.known = Known::Present(next);
Ok(())
}
Err(error) => {
state.diverged = true;
Err(error)
}
}
}
}