libbtrfs 0.0.20

Rust library for working with the btrfs filesystem
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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Btrfs subvolume operations.
//!
//! This module contains methods for basic management of subvolumes in a btrfs filesystem.
//!
use crate::{
    bindings::{
        btrfs_dir_item, btrfs_ioctl_get_subvol_info_args, btrfs_ioctl_timespec,
        btrfs_ioctl_vol_args_v2, btrfs_root_ref, vol_args_v2_volume, BTRFS_DIR_ITEM_KEY,
        BTRFS_FIRST_FREE_OBJECTID, BTRFS_FS_TREE_OBJECTID, BTRFS_IOC_DEFAULT_SUBVOL,
        BTRFS_IOC_GET_SUBVOL_INFO, BTRFS_IOC_SNAP_CREATE_V2, BTRFS_IOC_SNAP_DESTROY_V2,
        BTRFS_IOC_SUBVOL_CREATE_V2, BTRFS_IOC_SUBVOL_GETFLAGS, BTRFS_IOC_SUBVOL_SETFLAGS,
        BTRFS_ROOT_BACKREF_KEY, BTRFS_ROOT_TREE_DIR_OBJECTID, BTRFS_ROOT_TREE_OBJECTID,
        BTRFS_SUBVOL_RDONLY, BTRFS_SUBVOL_SPEC_BY_ID,
    },
    lookup,
    tree_search::fd::TreeSearch,
    util::{btrfs_ioctl, subvolume_parent_and_name, vol_args_v2_name_from_str_checked},
};
use std::{
    ffi::CStr,
    fs::File,
    io,
    os::unix::{fs::OpenOptionsExt, io::AsRawFd},
    path::Path,
};
use uuid::Uuid;

mod subvol_entry;
pub use subvol_entry::{walk, walk_user, Iter, IterUser, SubvolEntry};

mod subvol_info;
pub use subvol_info::{get_info, get_info_by_id, SubvolInfo};

/// Time structure used by the btrfs filesystem
pub type Timespec = btrfs_ioctl_timespec;

/// Check if a path represents a btrfs subvolume
///
/// This function returns `Ok(true)` if `subvol` can be determined to represent a btrfs subvolume.
pub fn is_subvol<P: AsRef<Path>>(subvol: P) -> io::Result<bool> {
    #[cfg(VERSION_3_12)]
    {
        let fd = File::options()
            .read(true)
            .custom_flags(libc::O_PATH)
            .open(subvol)?;

        fd::is_subvol(fd.as_raw_fd())
    }
    #[cfg(not(VERSION_3_12))]
    {
        use std::os::unix::fs::MetadataExt;

        Ok(crate::fs::is_btrfs(subvol.as_ref())?
            && subvol.as_ref().metadata()?.ino() == BTRFS_FIRST_FREE_OBJECTID)
    }
}

/// Create a btrfs subvolume
///
/// This function attempts to create a btrfs subvolume named `pathname`.
///
/// The newly created subvolume will be owned by the effective user ID of the calling process.
///
/// # Errors
///
/// * [`io::ErrorKind::AlreadyExists`]
///
/// `pathname` already exists.
///
/// * [`io::ErrorKind::NotFound`]
///
/// A directory component in pathname does not exist or is a dangling symbolic link.
///
/// * [`io::ErrorKind::PermissionDenied`]
///
/// Read/Write permissions to the parent directory is not allowed or search permissions is denied
/// for on the the directorys in path prefix of `subvol`.
///
pub fn create<P: AsRef<Path>>(pathname: P) -> io::Result<()> {
    let (parent, name) = subvolume_parent_and_name(pathname.as_ref())?;

    let parent_fd = File::options()
        .read(true)
        .custom_flags(libc::O_DIRECTORY)
        .open(parent)?;

    fd::create(parent_fd.as_raw_fd(), name)
}

/// Remove a btrfs subvolume
///
/// This function attempts to remove a btrfs subvolume referenced by `subvol`. The subvolume cannot
/// contain nested subvolumes, however it can contains regular files and directory's which will be
/// deleted if the call succeeds.
///
/// # Errors
///
/// * [`io::ErrorKind::DirectoryNotEmpty`]
///
/// The subvolume contained nested subvolumes.
///
/// * [`io::ErrorKind::InvalidInput`]
///
/// `subvol` is not a subvolume root.
///
/// * [`io::ErrorKind::NotADirectory`]
///
/// `subvol`, or a component used as a directory in `subvol`, is not, in fact, a directory.
///
/// * [`io::ErrorKind::NotFound`]
///
/// No file exists at `subvol`.
///
/// # Notes
///
/// **Requires CAP_SYS_ADMIN capabilities *unless the filesystem is mounted with
/// user_subvol_rm_allowed***
///
pub fn destroy<P: AsRef<Path>>(subvol: P) -> io::Result<()> {
    let (parent, name) = subvolume_parent_and_name(subvol.as_ref())?;

    let parent_fd = File::options()
        .read(true)
        .custom_flags(libc::O_DIRECTORY)
        .open(parent)?;

    fd::destroy(parent_fd.as_raw_fd(), name)
}

/// Remove a btrfs subvolume by its subvolume id
///
/// This function attempts to remove a btrfs subvolume by its subvolume id in a btrfs filesystem
/// referenced by `fs`. The subvolume cannot contain nested subvolumes, however it can contains
/// regular files and directory's which will be deleted if the call succeeds.
///
/// # Errors
///
/// * [`io::ErrorKind::DirectoryNotEmpty`]
///
/// The subvolume contained nested subvolumes.
///
/// * [`io::ErrorKind::NotFound`]
///
/// `subvolid` is not a valid subvolume id.
///
/// # Notes
///
/// **Requires CAP_SYS_ADMIN capabilities *unless the filesystem is mounted with
/// user_subvol_rm_allowed***
///
pub fn destroy_by_id<P: AsRef<Path>>(subvolid: u64, fs: P) -> io::Result<()> {
    let fd = File::open(fs.as_ref())?;

    fd::destroy_by_id(subvolid, fd.as_raw_fd())
}

/// Btrfs subvolume snapshots
pub mod snap {
    use super::*;
    /// Create a btrfs snapshot
    ///
    /// This function will attempt to create a btrfs snapshot named `pathname` of the subvolume
    /// referenced by `snapvol`. The `readonly` argument determines the read-only status for the
    /// snapshot. The owner and group for the The newly created snapshot will be the same as the
    /// subvolume referened by `snapvol`
    ///
    /// # Errors
    ///
    /// * [`io::ErrorKind::AlreadyExists`]
    ///
    /// `pathname` refers to to a file that already exists.
    ///
    /// * [`io::ErrorKind::CrossesDevices`]
    ///
    /// `snapvol` does not refer to a file or directory within the same filesystem as `pathname`.
    ///
    /// * [`io::ErrorKind::InvalidInput`]
    ///
    /// `snapvol` does not refer to a subvolume root.
    ///
    /// * [`io::ErrorKind::NotADirectory`]
    ///
    /// A component used as a directory in `pathname` is not, in fact, a directory.
    ///
    /// * [`io::ErrorKind::PermissionDenied`]
    ///
    /// Filesystem UID for the current process does not match the UID of the subvolume referenced
    /// by `snapvol`. Note that this is not required if the current user has `CAP_FOWNER`
    /// permissions.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let subvol = "/path/to/subvolume/named/foo";
    ///
    /// // create a read-only snapshot of `foo` called `foo_snapshot`
    /// libbtrfs::snap::create(subvol, "/.snapshots/foo_snapshot", true)?;
    ///
    /// # Ok::<(), std::io::Error>(())
    /// ```
    ///
    pub fn create<P: AsRef<Path>>(snapvol: P, pathname: P, readonly: bool) -> io::Result<()> {
        let (parent, name) = subvolume_parent_and_name(pathname.as_ref())?;

        let snap_fd = File::open(snapvol.as_ref())?;
        let parent_fd = File::options()
            .read(true)
            .custom_flags(libc::O_DIRECTORY)
            .open(parent)?;

        fd::create(snap_fd.as_raw_fd(), parent_fd.as_raw_fd(), name, readonly)
    }

    /// Support for raw file descriptors
    pub mod fd {
        use super::*;
        use std::os::unix::io::RawFd;

        /// See [super::create()]
        pub fn create(snapfd: RawFd, dirfd: RawFd, name: &str, readonly: bool) -> io::Result<()> {
            let mut vol_args = btrfs_ioctl_vol_args_v2 {
                fd: snapfd as i64,
                inner2: vol_args_v2_volume {
                    name: vol_args_v2_name_from_str_checked(name)?,
                },
                ..Default::default()
            };

            if readonly {
                vol_args.flags |= BTRFS_SUBVOL_RDONLY
            }

            btrfs_ioctl(dirfd, BTRFS_IOC_SNAP_CREATE_V2, &mut vol_args)
        }
    }
}

/// Gets the full subvolume path to the filesystem root
///
/// This function returns The full path to the filesystem root for the subvolume with id of
/// `treeid` in the btrfs filesystem referend by `fs`. This path is not relative to a btrfs mount
/// point but is relative to the level 5 (BTRFS_FS_TREE_OBJECTID) subvolume for the filesystem.
///
/// # Notes
///
/// **Requires CAP_SYS_ADMIN capabilities**
///
pub fn get_path<P: AsRef<Path>>(treeid: u64, fs: P) -> io::Result<String> {
    let fd = File::open(fs.as_ref())?;

    fd::get_path(treeid, fd.as_raw_fd())
}

/// Gets the default subvolume for the filesystem
///
/// # Notes
///
/// **Requires CAP_SYS_ADMIN capabilities**
///
pub fn get_default<P: AsRef<Path>>(fs: P) -> io::Result<u64> {
    let fd = File::open(fs.as_ref())?;

    fd::get_default(fd.as_raw_fd())
}

/// Sets the default subvolume for a btrfs filesystem
///
/// # Errors
///
/// * [`io::ErrorKind::NotFound`]
///
/// `id` is not a valid subvolume id.
///
/// # Notes
///
/// **Requires CAP_SYS_ADMIN capabilities**
///
pub fn set_default<P: AsRef<Path>>(id: u64, fs: P) -> io::Result<()> {
    let fd = File::open(fs.as_ref())?;

    fd::set_default(id, fd.as_raw_fd())
}

/// Gets the read-only status for a subvolume
///
/// # Errors
///
/// * [`io::ErrorKind::InvalidInput`]
///
/// `subvol` is not a subvolume root.
///
/// * [`io::ErrorKind::NotFound`]
///
/// No file exists at `subvol`.
///
/// * [`io::ErrorKind::PermissionDenied`]
///
/// Read access for `subvol` is not allowed, or search permission is denied for one of the
/// directorys in path prefix of `subvol`.
///
pub fn is_readonly<P: AsRef<Path>>(subvol: P) -> io::Result<bool> {
    let fd = File::open(subvol.as_ref())?;

    fd::is_readonly(fd.as_raw_fd())
}

/// Gets the raw flags for a subvolume
///
/// # Errors
///
/// * [`io::ErrorKind::InvalidInput`]
///
/// `subvol` is not a subvolume root.
///
/// * [`io::ErrorKind::NotFound`]
///
/// No file exists at `subvol`.
///
/// * [`io::ErrorKind::PermissionDenied`]
///
/// Read access for `subvol` is not allowed, or search permission is denied for one of the
/// directorys in path prefix of `subvol`.
///
pub fn get_flags<P: AsRef<Path>>(subvol: P) -> io::Result<u64> {
    let fd = File::open(subvol.as_ref())?;

    fd::get_flags(fd.as_raw_fd())
}

/// Sets the readonly flag for a subvolume
///
/// <div class="warning">
///
/// Please note that setting the readonly status of the subvolume that currently contains the
/// rust project using libbtrfs may cause problems because you will no longer be able to edit the
/// rust project to change the readonly status back. Btrfs-progs does not contain a command to
/// change readonly status.
///
/// One way to solve this is to copying the project to another subvolume that is read/write then
/// set the read-only status by calling [`set_readonly`].
///
/// </div>
///
/// # Errors
///
/// * [`io::ErrorKind::InvalidInput`]
///
/// `subvol` is not a subvolume root.
///
/// * [`io::ErrorKind::NotFound`]
///
/// No file exists at `subvol`.
///
/// * [`io::ErrorKind::PermissionDenied`]
///
/// Read access for `subvol` is not allowed, or search permission is denied for one of the
/// directorys in path prefix of `subvol`.
///
pub fn set_readonly<P: AsRef<Path>>(subvol: P, readonly: bool) -> io::Result<()> {
    let fd = File::open(&subvol)?;

    fd::set_readonly(fd.as_raw_fd(), readonly)
}

/// Raw file descriptor support
pub mod fd {
    use super::*;
    use std::{mem::MaybeUninit as Uninit, os::unix::io::RawFd};

    pub use subvol_entry::fd::{walk, walk_user};

    pub use subvol_info::fd::{get_info, get_info_by_id};

    /// See [super::is_subvol()]
    pub fn is_subvol(fd: RawFd) -> io::Result<bool> {
        let mut sb = Uninit::<libc::stat>::uninit();
        unsafe {
            syscall!(fstat(fd, sb.as_mut_ptr()))?;

            Ok(crate::fs::fd::is_btrfs(fd)?
                && (sb.assume_init().st_ino == BTRFS_FIRST_FREE_OBJECTID))
        }
    }

    /// See [super::create()]
    pub fn create(dirfd: RawFd, name: &str) -> io::Result<()> {
        let mut vol_args = btrfs_ioctl_vol_args_v2 {
            inner2: vol_args_v2_volume {
                name: vol_args_v2_name_from_str_checked(name)?,
            },
            ..Default::default()
        };
        btrfs_ioctl(dirfd, BTRFS_IOC_SUBVOL_CREATE_V2, &mut vol_args)
    }

    /// See [super::destroy()]
    pub fn destroy(dirfd: RawFd, name: &str) -> io::Result<()> {
        let mut vol_args = btrfs_ioctl_vol_args_v2 {
            inner2: vol_args_v2_volume {
                name: vol_args_v2_name_from_str_checked(name)?,
            },
            ..Default::default()
        };
        btrfs_ioctl(dirfd, BTRFS_IOC_SNAP_DESTROY_V2, &mut vol_args)
    }

    /// See [super::destroy_by_id()]
    pub fn destroy_by_id(subvolid: u64, fd: RawFd) -> io::Result<()> {
        let mut vol_args = btrfs_ioctl_vol_args_v2 {
            flags: BTRFS_SUBVOL_SPEC_BY_ID,
            inner2: vol_args_v2_volume { subvolid },
            ..Default::default()
        };
        btrfs_ioctl(fd, BTRFS_IOC_SNAP_DESTROY_V2, &mut vol_args)
    }

    /// See [super::get_path()]
    pub fn get_path(treeid: u64, fd: RawFd) -> io::Result<String> {
        let mut pos = 1024;
        let mut buf = vec![0u8; pos];
        let mut ts = TreeSearch::new(fd, |key| {
            key.tree_id = BTRFS_ROOT_TREE_OBJECTID;
            key.min_objectid = treeid;
            key.max_objectid = treeid;
            key.min_type = BTRFS_ROOT_BACKREF_KEY;
            key.max_type = BTRFS_ROOT_BACKREF_KEY;
            key.nr_items = 1;
        });

        while let Some(mut item) = ts.search()? {
            let item = item.next().unwrap();

            let treeid = item.offset();
            let rref = item.get::<&btrfs_root_ref>();
            let name = item.name_as_bytes(rref);
            let lookup = lookup::fd::path_as_bytes(fd, u64::from_le(rref.dirid), treeid)?;
            let total_len = lookup.len() + name.len();

            if total_len + (treeid != BTRFS_FS_TREE_OBJECTID) as usize > pos {
                let old_len = buf.len();

                buf.resize_with(old_len << 1, Default::default);
                buf.copy_within(..old_len, old_len);
                pos += old_len;
            }
            pos -= total_len;
            unsafe {
                lookup
                    .as_ptr()
                    .copy_to_nonoverlapping(buf.as_mut_ptr().add(pos), lookup.len());
                name.as_ptr()
                    .copy_to_nonoverlapping(buf.as_mut_ptr().add(pos + lookup.len()), name.len());
            }
            if treeid != BTRFS_FS_TREE_OBJECTID {
                ts.min_objectid(treeid);
                pos -= 1;
                buf[pos] = b'/';
            } else {
                return String::from_utf8(buf[pos..].to_vec())
                    .or(Err(io::Error::from(io::ErrorKind::InvalidData)));
            }
        }
        error!(NotFound)
    }

    /// See [super::get_default()]
    pub fn get_default(fd: RawFd) -> io::Result<u64> {
        let mut search = TreeSearch::new(fd, |key| {
            key.tree_id = BTRFS_ROOT_TREE_OBJECTID;
            key.min_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
            key.max_objectid = BTRFS_ROOT_TREE_DIR_OBJECTID;
            key.min_type = BTRFS_DIR_ITEM_KEY;
            key.max_type = BTRFS_DIR_ITEM_KEY;
        });

        while let Some(items) = search.search_with(|key, item| {
            key.min_offset = item.offset() + 1;
        })? {
            for item in items {
                debug_assert!(item.key() == BTRFS_DIR_ITEM_KEY);

                let dir = item.get::<&btrfs_dir_item>();
                let name = item.name_as_bytes(dir);
                if name == b"default" {
                    return Ok(u64::from_le(dir.location.objectid));
                }
            }
        }
        error!(NotFound)
    }

    /// See [super::set_default()]
    pub fn set_default(mut id: u64, fd: RawFd) -> io::Result<()> {
        btrfs_ioctl(fd, BTRFS_IOC_DEFAULT_SUBVOL, &mut id)
    }

    /// See [super::get_flags()]
    pub fn get_flags(fd: RawFd) -> io::Result<u64> {
        let mut flags: u64 = 0;

        btrfs_ioctl(fd, BTRFS_IOC_SUBVOL_GETFLAGS, &mut flags)?;

        Ok(flags)
    }

    /// See [super::is_readonly()]
    pub fn is_readonly(fd: RawFd) -> io::Result<bool> {
        let flags = get_flags(fd)?;

        Ok(flags & BTRFS_SUBVOL_RDONLY != 0)
    }

    /// See [super::set_readonly()]
    pub fn set_readonly(fd: RawFd, readonly: bool) -> io::Result<()> {
        let mut flags = get_flags(fd)?;

        if BTRFS_SUBVOL_RDONLY & flags != BTRFS_SUBVOL_RDONLY * readonly as u64 {
            flags ^= BTRFS_SUBVOL_RDONLY;

            btrfs_ioctl(fd, BTRFS_IOC_SUBVOL_SETFLAGS, &mut flags)?;
        }
        Ok(())
    }
}