use std::io;
use std::sync::{Arc, MutexGuard};
use tokio::task::spawn_blocking;
use tracing::warn;
use crate::error::{SmbError, SmbResult};
use crate::path::SmbPath;
use super::backend::Shared;
use super::data::disk_error;
use super::dirmove::Left;
use super::entry::{Entry, Sealed, State};
use super::keys::{RowKind, child_key, dir_prefix, last_name, path_below, slot};
use super::overlay::{Held, Moving};
use super::record::RecordId;
use super::retry::Retry;
use super::unlink::{drop_record, leave_batch, supersede};
impl Shared {
pub(super) async fn rename(
self: &Arc<Self>,
from: &SmbPath,
to: &SmbPath,
replace: bool,
) -> SmbResult<()> {
self.local()?;
if from.is_root() || to.is_root() {
return Err(SmbError::AccessDenied);
}
let retry = self.retry();
let source = self.locate(from, &retry).await?;
let parent = self.parent_dir(to, &retry).await?;
let name = to.file_name().ok_or(SmbError::NameInvalid)?;
let key = child_key(&parent.key, name)?;
let fold = self.case_insensitive;
if source.entry.is_dir() {
let held_key = source.entry.state().key.clone();
if slot(&key, fold) == slot(&held_key, fold) {
self.refuse_case_duplicate(&parent.key, &held_key, &key, &retry)
.await?;
return self.rename_dir(source, key, &retry).await;
}
}
let mut attempts = 0;
loop {
let target = match self.locate(to, &retry).await {
Ok(target) => Some(target),
Err(SmbError::NotFound) => None,
Err(e) => return Err(e),
};
let target = match target {
Some(target) if Arc::ptr_eq(&target.entry, &source.entry) => None,
Some(_) if !replace => return Err(SmbError::Exists),
Some(target) if target.entry.is_dir() => return Err(SmbError::AccessDenied),
Some(_) if source.entry.is_dir() => return Err(SmbError::AccessDenied),
other => other,
};
if source.entry.is_dir() {
return self.rename_dir(source, key, &retry).await;
}
let (shared, moving, key) = (Arc::clone(self), source.another(), key.clone());
let done = spawn_blocking(move || rename_file(&shared, &moving, &key, target))
.await
.map_err(|e| SmbError::Io(io::Error::other(e)))?;
attempts += 1;
if !(replace && matches!(done, Err(SmbError::Exists)) && attempts < RENAME_ATTEMPTS) {
return done;
}
}
}
}
impl Shared {
async fn refuse_case_duplicate(
&self,
parent: &str,
held: &str,
key: &str,
retry: &Retry,
) -> SmbResult<()> {
if held == key {
return Ok(());
}
let listing = self.listing(parent, retry).await?;
let is_dir = |name: &str| {
listing
.find_exact(name)
.is_some_and(|row| matches!(row.kind, RowKind::Dir))
};
let duplicate = is_dir(last_name(key))
&& is_dir(last_name(held))
&& !self.overlay.to_delete(&dir_prefix(key));
if duplicate {
return Err(SmbError::AccessDenied);
}
Ok(())
}
}
const RENAME_ATTEMPTS: u32 = 3;
pub(super) fn gone_after(owned: &[String], old: &str, old_exists: bool, to: &str) -> Vec<String> {
let mut gone: Vec<String> = Vec::new();
for key in owned
.iter()
.map(String::as_str)
.chain(old_exists.then_some(old))
{
if key != to && !gone.iter().any(|held| held == key) {
gone.push(key.to_owned());
}
}
gone
}
fn prior_etag(state: &State, to: &str) -> Option<String> {
if state.job.is_some() || state.key != to {
return None;
}
state.prior.clone()
}
struct Replaced<'a> {
entry: &'a Arc<Entry>,
id: RecordId,
recorded: bool,
keys: Vec<String>,
left: Option<Left>,
}
fn rename_file(shared: &Shared, source: &Held, to: &str, replaced: Option<Held>) -> SmbResult<()> {
let cache = shared.local()?;
let entry = &source.entry;
let other = replaced.as_ref().map(|held| &held.entry);
let order: Vec<&Arc<Entry>> = std::iter::once(entry).chain(other).collect();
let _locks = Entry::lock_all(&order);
let gone = {
let state = entry.state();
state.attached()?;
if state.key == to {
return Ok(());
}
gone_after(&state.gone, &state.key, state.in_bucket(), to)
};
let tombs = shared.overlay.lock_tombs();
let _reserved = shared.overlay.reserve(to, entry, other)?;
#[cfg(test)]
super::jobs::pause_blocking(&shared.jobs.pause_reserved);
let mut replacing = None;
let (mut prior, mut may_exist) = (None, shared.overlay.tombstoned(to));
if let Some(x) = other {
let (id, recorded, batch) = {
let mut state = x.state();
state.attached()?;
state.bump();
prior = prior_etag(&state, to);
may_exist |= state.in_bucket();
(
state.id().map_err(SmbError::Io)?,
state.recorded,
state.batch.clone(),
)
};
let moving = Moving {
entry,
to,
gone: &gone,
};
let keys = shared.overlay.tomb_keys(x, Some(moving));
let left = leave_batch(shared, cache, batch.as_ref(), &id, recorded, &keys)?;
replacing = Some(Replaced {
entry: x,
id,
recorded,
keys,
left,
});
}
let moved = move_record(shared, entry, to, &gone, may_exist);
let moved = match moved {
Ok(moved) => moved,
Err(e) => {
if let Some(x) = replacing {
restore(shared, x, &tombs);
}
drop(tombs);
return Err(e);
}
};
if let Some(x) = &replacing
&& let Err(e) = cache.remove_data(&x.id)
{
warn!(error = %e, "a data file that is no longer needed could not be removed");
}
let keys = replacing
.as_ref()
.map(|x| x.keys.clone())
.unwrap_or_default();
shared.overlay.renamed(
entry,
to,
|state| {
state.gone = gone;
state.may_exist = may_exist;
state.prior = prior;
state.bump();
if let Some(sealed) = moved.sealed {
state.set_sealed(sealed);
}
state.recorded = moved.recorded;
state.recorded_source = moved.source;
if moved.left_batch {
state.batch = None;
}
},
replacing
.as_ref()
.map(|x| (x.entry, x.keys.as_slice(), &x.id)),
);
drop(tombs);
super::change::superseded(shared, entry, None);
supersede(shared, &keys);
Ok(())
}
fn restore(shared: &Shared, x: Replaced<'_>, tombs: &MutexGuard<'_, ()>) {
let Ok(cache) = shared.local() else {
return;
};
let rejoined = x
.left
.map_or(Ok(()), |left| shared.overlay.rejoin_batch(cache, left));
if let Err(e) = &rejoined {
warn!(error = %e, "the record of a directory rename could not be written again");
}
if x.recorded || rejoined.is_err() {
match super::change::persist_locked(shared, x.entry, tombs) {
Ok(()) => return,
Err(e) => {
warn!(error = %e, "the record of an entry that was not replaced could not be written again");
}
}
}
if let Err(e) = cache.remove_record(&x.id) {
warn!(error = %e, "the tombstone record of an entry that was not replaced could not be removed");
}
}
struct Moved {
sealed: Option<Sealed>,
recorded: bool,
source: Option<String>,
left_batch: bool,
}
fn move_record(
shared: &Shared,
entry: &Arc<Entry>,
to: &str,
gone: &[String],
may_exist: bool,
) -> SmbResult<Moved> {
let cache = shared.local()?;
let (record, id, recorded, first, data, batch) = {
let mut state = entry.state();
state.attached()?;
let work = state.local().is_some()
|| state.own.is_some()
|| state.base.as_ref().is_some_and(|base| base.key != to)
|| !gone.is_empty();
let record = work.then(|| Entry::record(&mut state, &shared.prefix, shared.built));
(
record,
state.id.clone(),
state.recorded,
state.sealed().is_none(),
state.local().map(|local| Arc::clone(&local.file)),
state.batch.clone(),
)
};
let Some(record) = record else {
drop_record(shared, cache, batch.as_ref(), id.as_ref(), recorded)?;
return Ok(Moved {
sealed: None,
recorded: false,
source: None,
left_batch: batch.is_some(),
});
};
let mut record = record.map_err(SmbError::Io)?;
record.key = to.to_owned();
record.path = path_below(&shared.prefix, to);
record.gone = gone.to_vec();
record.remote = may_exist;
record.generation += 1;
if let Some(data) = data {
cache.sync_data(&data).map_err(disk_error)?;
if first {
cache.sync_data_dir().map_err(disk_error)?;
}
}
cache
.write_record(&record.id, &record.encode())
.map_err(disk_error)?;
let sealed = record.local.as_ref().map(|local| Sealed {
generation: record.generation,
len: local.len,
});
Ok(Moved {
sealed,
recorded: true,
source: record.source().map(str::to_owned),
left_batch: false,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(keys: &[&str]) -> Vec<String> {
keys.iter().map(|key| (*key).to_owned()).collect()
}
#[test]
fn the_old_key_is_to_be_deleted_when_the_bucket_may_hold_it() {
assert_eq!(gone_after(&[], "a", true, "b"), keys(&["a"]));
assert!(gone_after(&[], "a", false, "b").is_empty());
}
#[test]
fn a_chain_of_renames_keeps_the_keys_it_passed_and_not_the_one_it_ends_at() {
let first = gone_after(&[], "a", true, "b");
let second = gone_after(&first, "b", false, "c");
assert_eq!(second, keys(&["a"]));
let third = gone_after(&second, "c", true, "a");
assert_eq!(third, keys(&["c"]));
}
#[test]
fn a_key_is_to_be_deleted_once() {
assert_eq!(
gone_after(&keys(&["a", "b"]), "b", true, "c"),
keys(&["a", "b"])
);
}
#[test]
fn the_etag_a_key_had_is_unknown_while_the_entry_that_held_it_has_a_job() {
let mut state = State::new("to".to_owned(), false);
assert_eq!(prior_etag(&state, "to"), None);
state.prior = Some("\"p\"".to_owned());
assert_eq!(prior_etag(&state, "to").as_deref(), Some("\"p\""));
assert_eq!(prior_etag(&state, "TO"), None, "another spelling");
state.job = Some(crate::s3::retry::Stop::new());
assert_eq!(prior_etag(&state, "to"), None);
}
}