shardline-storage 1.0.0

Content-addressed object storage contracts and adapters for Shardline.
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::{
    ffi::{OsStr, OsString},
    fs::{self, DirBuilder, File, OpenOptions},
    io::{self, ErrorKind, Write},
    path::{Component, Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
    time::{SystemTime, UNIX_EPOCH},
};

use std::os::unix::{
    fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
    io::AsRawFd,
};

static TEMPORARY_FILE_COUNTER: AtomicU64 = AtomicU64::new(0);

/// File and directory mode overrides for anchored filesystem writes.
#[derive(Debug, Clone, Copy)]
pub struct AnchoredPathOptions {
    /// Optional mode applied to newly-created directories.
    pub directory_mode: Option<u32>,
    /// Optional mode applied to newly-created files.
    pub file_mode: Option<u32>,
}

impl AnchoredPathOptions {
    /// Creates anchored path options.
    #[must_use]
    pub const fn new(directory_mode: Option<u32>, file_mode: Option<u32>) -> Self {
        Self {
            directory_mode,
            file_mode,
        }
    }
}

/// Open parent directory and final filename for a write anchored under a root.
pub struct AnchoredTarget {
    parent_dir: File,
    parent_path: PathBuf,
    file_name: OsString,
}

impl AnchoredTarget {
    /// Creates an anchored target from an already-open parent directory.
    #[must_use]
    pub const fn new(parent_dir: File, parent_path: PathBuf, file_name: OsString) -> Self {
        Self {
            parent_dir,
            parent_path,
            file_name,
        }
    }

    /// Returns the open parent directory file descriptor.
    #[must_use]
    pub const fn parent_dir(&self) -> &File {
        &self.parent_dir
    }

    /// Returns the final target filename within the anchored parent directory.
    #[must_use]
    pub fn file_name(&self) -> &OsStr {
        &self.file_name
    }

    /// Returns the descriptor-relative path used for race-resistant filesystem operations.
    #[must_use]
    pub fn final_path(&self) -> PathBuf {
        fd_child_path(&self.parent_dir, &self.file_name)
    }

    /// Returns the logical path requested by the caller.
    #[must_use]
    pub fn logical_path(&self) -> PathBuf {
        self.parent_path.join(&self.file_name)
    }
}

/// Opens a file target under `root` without following symlinked path components.
///
/// # Errors
///
/// Returns an error when `path` falls outside `root`, contains an invalid component, or the
/// anchored parent directory cannot be opened or created safely.
pub fn open_anchored_target(
    root: &Path,
    path: &Path,
    options: AnchoredPathOptions,
    invalid_path_error: fn() -> io::Error,
) -> io::Result<AnchoredTarget> {
    let parent_path = path.parent().ok_or_else(invalid_path_error)?;
    let file_name = path.file_name().ok_or_else(invalid_path_error)?;
    let relative_parent = parent_path
        .strip_prefix(root)
        .map_err(|_error| invalid_path_error())?;
    let mut current = match open_directory(root) {
        Ok(directory) => directory,
        Err(error) if error.kind() == ErrorKind::NotFound => {
            create_directory_all(root, options.directory_mode)?;
            open_directory(root)?
        }
        Err(error) => return Err(error),
    };

    for component in relative_parent.components() {
        let Component::Normal(segment) = component else {
            return Err(invalid_path_error());
        };
        current = open_or_create_child_directory(&current, segment, true, options.directory_mode)?;
    }

    Ok(AnchoredTarget::new(
        current,
        parent_path.to_path_buf(),
        file_name.to_os_string(),
    ))
}

/// Opens a directory path component-by-component without following symlinks.
///
/// # Errors
///
/// Returns an error when a path component is invalid, a non-directory is encountered, or a
/// directory cannot be opened or created.
pub fn open_directory_chain(
    path: &Path,
    create_missing: bool,
    directory_mode: Option<u32>,
    invalid_path_error: fn() -> io::Error,
) -> io::Result<File> {
    let mut current = if path.is_absolute() {
        open_directory(Path::new("/"))?
    } else {
        open_directory(Path::new("."))?
    };

    for component in path.components() {
        match component {
            Component::RootDir | Component::CurDir => {}
            Component::ParentDir => {
                current = open_directory(&fd_child_path(&current, OsStr::new("..")))?;
            }
            Component::Normal(segment) => {
                current = open_or_create_child_directory(
                    &current,
                    segment,
                    create_missing,
                    directory_mode,
                )?;
            }
            Component::Prefix(_prefix) => return Err(invalid_path_error()),
        }
    }

    Ok(current)
}

/// Opens one child directory below `parent`, optionally creating it first.
///
/// # Errors
///
/// Returns an error when the child is missing and creation is disabled, when the child is not a
/// directory, or when opening or creating the directory fails.
pub fn open_or_create_child_directory(
    parent: &File,
    segment: &OsStr,
    create_missing: bool,
    directory_mode: Option<u32>,
) -> io::Result<File> {
    let child_path = fd_child_path(parent, segment);
    match open_directory(&child_path) {
        Ok(directory) => Ok(directory),
        Err(error) if error.kind() == ErrorKind::NotFound && create_missing => {
            match create_directory(&child_path, directory_mode) {
                Ok(()) => {}
                Err(create_error) if create_error.kind() == ErrorKind::AlreadyExists => {}
                Err(create_error) => return Err(create_error),
            }
            open_directory(&child_path)
        }
        Err(error) => Err(error),
    }
}

/// Writes `bytes` into a new temporary file anchored beside the target path.
///
/// # Errors
///
/// Returns an error when a temporary file cannot be created safely or the payload cannot be fully
/// written and flushed.
pub fn write_anchored_temporary_file(
    anchored: &AnchoredTarget,
    bytes: &[u8],
    file_mode: Option<u32>,
) -> io::Result<PathBuf> {
    loop {
        let temporary = fd_child_path(
            anchored.parent_dir(),
            &temporary_file_name(anchored.file_name()),
        );
        match open_new_file(&temporary, file_mode) {
            Ok(mut file) => {
                file.write_all(bytes)?;
                file.flush()?;
                return Ok(temporary);
            }
            Err(error) if error.kind() == ErrorKind::AlreadyExists => {}
            Err(error) => return Err(error),
        }
    }
}

/// Returns a collision-resistant temporary filename beside `file_name`.
#[must_use]
pub fn temporary_file_name(file_name: &OsStr) -> OsString {
    let counter = TEMPORARY_FILE_COUNTER.fetch_add(1, Ordering::Relaxed);
    let unix_nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0_u128, |duration| duration.as_nanos());
    let mut name = file_name.to_os_string();
    name.push(format!(".tmp-{unix_nanos}-{counter}"));
    name
}

/// Verifies that the anchored parent directory still points at the same on-disk directory.
///
/// # Errors
///
/// Returns an error when the logical parent path has been replaced, turned into a symlink, or can
/// no longer be inspected.
pub fn ensure_parent_path_matches_anchor(
    anchored: &AnchoredTarget,
    changed_message: &'static str,
) -> io::Result<()> {
    let anchored_metadata = anchored.parent_dir.metadata()?;
    let current_metadata = fs::symlink_metadata(&anchored.parent_path)?;
    if current_metadata.file_type().is_symlink() || !current_metadata.is_dir() {
        return Err(io::Error::new(ErrorKind::InvalidData, changed_message));
    }
    if anchored_metadata.dev() != current_metadata.dev()
        || anchored_metadata.ino() != current_metadata.ino()
    {
        return Err(io::Error::new(ErrorKind::InvalidData, changed_message));
    }

    Ok(())
}

/// Opens a directory without following symlinks.
///
/// # Errors
///
/// Returns an error when `path` does not name an existing directory or the directory cannot be
/// opened safely.
pub fn open_directory(path: &Path) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options.read(true);
    // On macOS, /dev/fd/N paths are kernel-created symlinks for file descriptors.
    // The FD-based path approach is already secure by construction (the FD is obtained
    // from a verified directory open), so O_NOFOLLOW is not needed on macOS.
    // On Linux, /proc/self/fd/N is not a symlink, so O_NOFOLLOW provides defense-in-depth.
    #[cfg(not(target_os = "macos"))]
    options.custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW);
    #[cfg(target_os = "macos")]
    options.custom_flags(libc::O_DIRECTORY);
    options.open(path)
}

/// Creates and opens a brand-new file without following symlinks.
///
/// # Errors
///
/// Returns an error when the file already exists, the path is invalid, or the file cannot be
/// created with the requested mode.
pub fn open_new_file(path: &Path, file_mode: Option<u32>) -> io::Result<File> {
    let mut options = OpenOptions::new();
    options
        .write(true)
        .create_new(true)
        .custom_flags(libc::O_NOFOLLOW);
    if let Some(mode) = file_mode {
        options.mode(mode);
    }
    options.open(path)
}

/// Creates a single directory, optionally applying an explicit mode.
///
/// # Errors
///
/// Returns an error when the directory cannot be created at `path`.
pub fn create_directory(path: &Path, directory_mode: Option<u32>) -> io::Result<()> {
    let mut builder = DirBuilder::new();
    if let Some(mode) = directory_mode {
        builder.mode(mode);
    }
    builder.create(path)
}

/// Recursively creates a directory chain, optionally applying an explicit mode.
///
/// # Errors
///
/// Returns an error when any directory in the chain cannot be created.
pub fn create_directory_all(path: &Path, directory_mode: Option<u32>) -> io::Result<()> {
    let mut builder = DirBuilder::new();
    builder.recursive(true);
    if let Some(mode) = directory_mode {
        builder.mode(mode);
    }
    builder.create(path)
}

/// Builds a descriptor-relative child path below an open directory.
#[must_use]
pub fn fd_child_path(directory: &File, child: &OsStr) -> PathBuf {
    let mut path = fd_base_path(directory);
    path.push(child);
    path
}

/// Atomically renames a file within the same parent directory using FD-relative
/// operations on macOS.
///
/// On Linux, `/proc/self/fd/N/child` paths resolve through the FD, so `std::fs::rename`
/// works even after the parent directory is renamed. On macOS, `/dev/fd/N` cannot traverse
/// children, so this uses `renameat` with the parent FD instead.
///
/// # Errors
///
/// Returns an error when either name contains a null byte or the rename fails.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
pub fn rename_at(parent: &File, old_name: &OsStr, new_name: &OsStr) -> io::Result<()> {
    use std::ffi::CString;
    use std::os::unix::io::AsRawFd;

    let old_cstr = CString::new(old_name.as_encoded_bytes()).map_err(|e| {
        io::Error::new(
            ErrorKind::InvalidInput,
            format!("name contains null byte: {e}"),
        )
    })?;
    let new_cstr = CString::new(new_name.as_encoded_bytes()).map_err(|e| {
        io::Error::new(
            ErrorKind::InvalidInput,
            format!("name contains null byte: {e}"),
        )
    })?;

    // SAFETY: renameat(2) is safe when given valid FDs and null-terminated strings.
    // The parent FD is an open directory descriptor; old_cstr and new_cstr are
    // valid C strings produced by CString::new above.
    let result = unsafe {
        libc::renameat(
            parent.as_raw_fd(),
            old_cstr.as_ptr(),
            parent.as_raw_fd(),
            new_cstr.as_ptr(),
        )
    };

    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// Renames a file. On non-macOS platforms, this delegates to `std::fs::rename`.
///
/// # Errors
///
/// Returns an error if the source path does not exist, the target path already
/// exists, or the filesystem prevents the rename.
#[cfg(not(target_os = "macos"))]
pub fn rename_at(parent: &File, old_name: &OsStr, new_name: &OsStr) -> io::Result<()> {
    let old_path = fd_child_path(parent, old_name);
    let new_path = fd_child_path(parent, new_name);
    std::fs::rename(old_path, new_path)
}

/// Removes a file within a directory using FD-relative operations.
///
/// On macOS, `/dev/fd/N` cannot traverse children, so this uses `unlinkat`.
///
/// # Errors
///
/// Returns an error when the name contains a null byte or the removal fails.
#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
pub fn remove_at(parent: &File, name: &OsStr) -> io::Result<()> {
    use std::ffi::CString;
    use std::os::unix::io::AsRawFd;

    let cstr = CString::new(name.as_encoded_bytes()).map_err(|e| {
        io::Error::new(
            ErrorKind::InvalidInput,
            format!("name contains null byte: {e}"),
        )
    })?;
    // SAFETY: unlinkat(2) is safe when given a valid FD and null-terminated string.
    // The parent FD is an open directory descriptor; cstr is a valid C string.
    let result = unsafe { libc::unlinkat(parent.as_raw_fd(), cstr.as_ptr(), 0) };
    if result == 0 {
        Ok(())
    } else {
        Err(io::Error::last_os_error())
    }
}

/// Removes a file. On non-macOS, delegates to `std::fs::remove_file`.
///
/// # Errors
///
/// Returns an error if the file does not exist or cannot be removed.
#[cfg(not(target_os = "macos"))]
pub fn remove_at(parent: &File, name: &OsStr) -> io::Result<()> {
    let path = fd_child_path(parent, name);
    std::fs::remove_file(path)
}

/// Removes a file when it exists.
///
/// # Errors
///
/// Returns an error when file removal fails for any reason other than the path being absent.
pub fn remove_if_present(path: &Path) -> io::Result<()> {
    match fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

#[cfg(target_os = "macos")]
#[allow(unsafe_code)]
fn macos_fd_real_path(fd: std::os::unix::io::RawFd) -> PathBuf {
    let mut buf = [0i8; 1024];
    // SAFETY: fcntl(2) with F_GETPATH writes a NUL-terminated path into buf.
    // buf is stack-allocated with sufficient size for any valid filesystem path.
    let result = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_mut_ptr()) };
    if result < 0 {
        return PathBuf::from(format!("/dev/fd/{fd}"));
    }
    // SAFETY: fcntl(F_GETPATH) guarantees the buffer contains a valid NUL-terminated
    // C string when it returns success (result >= 0).
    let c_str = unsafe { std::ffi::CStr::from_ptr(buf.as_ptr()) };
    PathBuf::from(c_str.to_string_lossy().as_ref())
}

fn fd_base_path(directory: &File) -> PathBuf {
    #[cfg(target_os = "linux")]
    {
        PathBuf::from(format!("/proc/self/fd/{}", directory.as_raw_fd()))
    }
    #[cfg(target_os = "macos")]
    {
        // On macOS, /dev/fd/N is a fescfs virtual directory entry, NOT a symlink.
        // You cannot traverse children through it (open("/dev/fd/3/var") fails with ENOENT).
        // Use fcntl(F_GETPATH) to resolve the real path from the file descriptor.
        macos_fd_real_path(directory.as_raw_fd())
    }
    #[cfg(not(target_os = "linux"))]
    #[cfg(not(target_os = "macos"))]
    {
        PathBuf::from(format!("/dev/fd/{}", directory.as_raw_fd()))
    }
}