smb-server 0.11.0

SMB2/3 file-sharing server library with pluggable storage backends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Renaming a file: its entry takes the new key, the old key becomes a key
//! the entry deletes once its content is at the new one, and the entry it
//! replaces, if any, gives its keys up to be deleted.

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, 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 {
    /// Renames the file or directory at `from` to `to`. The change of a file
    /// is local: the only requests are the lookups of the two names and of the
    /// parent of `to`. A directory also lists the keys below it.
    ///
    /// # Errors
    ///
    /// Fails with `Exists` if another file has the name and `replace` is not
    /// set, with `AccessDenied` if a directory has it or a directory is to
    /// replace a file, and with `PathNotFound` if the parent of `to` is not a
    /// directory.
    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)?;
        // A store that ignores case answers a lookup of the new spelling with
        // the directory itself, and the lookup would give the entry that
        // spelling: the name stays that of the directory.
        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(target) if target.entry.is_dir() => return Err(SmbError::AccessDenied),
                Some(_) if !replace => return Err(SmbError::Exists),
                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)))?;
            // A name that another change took since the lookup is looked up
            // again, to be replaced.
            attempts += 1;
            if !(replace && matches!(done, Err(SmbError::Exists)) && attempts < RENAME_ATTEMPTS) {
                return done;
            }
        }
    }
}

impl Shared {
    /// Fails with `AccessDenied` if the directory `held` in the directory
    /// `parent` is to get the spelling `key` of its name, which differs in case
    /// only, and the listing of `parent` has another directory with that
    /// spelling: the store keeps both, and the rename would mix them.
    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 duplicate = listing
            .find_exact(last_name(key))
            .is_some_and(|row| matches!(row.kind, RowKind::Dir) && row.name != last_name(held));
        if duplicate {
            return Err(SmbError::AccessDenied);
        }
        Ok(())
    }
}

/// How often a rename that replaces looks up its name again after another
/// change took it.
const RENAME_ATTEMPTS: u32 = 3;

/// The keys an entry owns to delete after it moves from `old` to `to`:
/// `owned`, and `old` if `old_exists`, less `to`.
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
}

/// The ETag the key `to` had when `state`, the entry that held it, was
/// replaced, if the entry knows it. A multipart upload over the key tells its
/// own object from this one. `None` while the entry has a job, which can store
/// a newer version, and when `to` differs from the entry's key in case only.
fn prior_etag(state: &State, to: &str) -> Option<String> {
    if state.job.is_some() || state.key != to {
        return None;
    }
    state.prior.clone()
}

/// The entry a rename replaces: its record becomes a tombstone record of
/// `keys`.
struct Replaced<'a> {
    entry: &'a Arc<Entry>,
    id: RecordId,
    /// The entry had a record.
    recorded: bool,
    keys: Vec<String>,
    /// What puts the entry back in the batch of a directory rename it left.
    left: Option<Left>,
}

/// Moves the entry of `source` to `to`, in this order: the record of the
/// entry `replaced`, which becomes a tombstone record of its keys to delete
/// or goes; the record of the moved entry, with its new key; the overlay.
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);

    // The replaced entry first: its job stops, and its keys go.
    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(())
}

/// Puts the replaced entry back as it was before a rename that failed: it is
/// a member of its batch again. Its own record is written again if it had
/// one, or if the record of the batch could not be written with it, which
/// replaces the tombstone record that took its id. In every other case, and
/// when that write fails, the tombstone record is removed. The caller holds
/// the lock of the keys to delete, `tombs`, so no record of them changes
/// meanwhile.
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");
    }
}

/// What the record of a moved entry says.
struct Moved {
    /// What the record seals.
    sealed: Option<Sealed>,
    /// A record is on disk.
    recorded: bool,
    /// The key the record says the content is copied from.
    source: Option<String>,
    /// The entry has left the batch of a directory rename.
    left_batch: bool,
}

/// Writes the record of `entry` as it is with the key `to`, or removes it if
/// the entry would have nothing to keep.
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, file, 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 {
        // The entry has nothing to record: a batch that lists it must not
        // bring its earlier place back.
        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(file) = file {
        file.sync_all().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);
    }
}