mirror of
https://github.com/koverstreet/bcachefs-tools.git
synced 2025-12-11 00:00:12 +03:00
rust: use rustfmt defaults
follow the kernel style guide, i.e idiomatic rust style. Signed-off-by: Alexander Fougner <fougner89@gmail.com>
This commit is contained in:
parent
bdc290eee0
commit
20aecb42d8
@ -1,67 +1,91 @@
|
|||||||
fn main() {
|
fn main() {
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
let out_dir: PathBuf = std::env::var_os("OUT_DIR").expect("ENV Var 'OUT_DIR' Expected").into();
|
let out_dir: PathBuf = std::env::var_os("OUT_DIR")
|
||||||
let top_dir: PathBuf = std::env::var_os("CARGO_MANIFEST_DIR")
|
.expect("ENV Var 'OUT_DIR' Expected")
|
||||||
.expect("ENV Var 'CARGO_MANIFEST_DIR' Expected")
|
.into();
|
||||||
.into();
|
let top_dir: PathBuf = std::env::var_os("CARGO_MANIFEST_DIR")
|
||||||
let libbcachefs_inc_dir =
|
.expect("ENV Var 'CARGO_MANIFEST_DIR' Expected")
|
||||||
std::env::var("LIBBCACHEFS_INCLUDE").unwrap_or_else(|_| top_dir.join("libbcachefs").display().to_string());
|
.into();
|
||||||
let libbcachefs_inc_dir = std::path::Path::new(&libbcachefs_inc_dir);
|
let libbcachefs_inc_dir = std::env::var("LIBBCACHEFS_INCLUDE")
|
||||||
println!("{}", libbcachefs_inc_dir.display());
|
.unwrap_or_else(|_| top_dir.join("libbcachefs").display().to_string());
|
||||||
|
let libbcachefs_inc_dir = std::path::Path::new(&libbcachefs_inc_dir);
|
||||||
|
println!("{}", libbcachefs_inc_dir.display());
|
||||||
|
|
||||||
println!("cargo:rustc-link-lib=dylib=bcachefs");
|
println!("cargo:rustc-link-lib=dylib=bcachefs");
|
||||||
println!("cargo:rustc-link-search={}", env!("LIBBCACHEFS_LIB"));
|
println!("cargo:rustc-link-search={}", env!("LIBBCACHEFS_LIB"));
|
||||||
|
|
||||||
let _libbcachefs_dir = top_dir.join("libbcachefs").join("libbcachefs");
|
let _libbcachefs_dir = top_dir.join("libbcachefs").join("libbcachefs");
|
||||||
let bindings = bindgen::builder()
|
let bindings = bindgen::builder()
|
||||||
.header(top_dir.join("src").join("libbcachefs_wrapper.h").display().to_string())
|
.header(
|
||||||
.clang_arg(format!("-I{}", libbcachefs_inc_dir.join("include").display()))
|
top_dir
|
||||||
.clang_arg(format!("-I{}", libbcachefs_inc_dir.display()))
|
.join("src")
|
||||||
.clang_arg("-DZSTD_STATIC_LINKING_ONLY")
|
.join("libbcachefs_wrapper.h")
|
||||||
.clang_arg("-DNO_BCACHEFS_FS")
|
.display()
|
||||||
.clang_arg("-D_GNU_SOURCE")
|
.to_string(),
|
||||||
.derive_debug(true)
|
)
|
||||||
.derive_default(true)
|
.clang_arg(format!(
|
||||||
.derive_eq(true)
|
"-I{}",
|
||||||
.layout_tests(true)
|
libbcachefs_inc_dir.join("include").display()
|
||||||
.default_enum_style(bindgen::EnumVariation::Rust { non_exhaustive: true })
|
))
|
||||||
.allowlist_function(".*bch2_.*")
|
.clang_arg(format!("-I{}", libbcachefs_inc_dir.display()))
|
||||||
.allowlist_function("bio_.*")
|
.clang_arg("-DZSTD_STATIC_LINKING_ONLY")
|
||||||
.allowlist_function("bch2_super_write_fd")
|
.clang_arg("-DNO_BCACHEFS_FS")
|
||||||
.allowlist_function("derive_passphrase")
|
.clang_arg("-D_GNU_SOURCE")
|
||||||
.allowlist_function("request_key")
|
.derive_debug(true)
|
||||||
.allowlist_function("add_key")
|
.derive_default(true)
|
||||||
.allowlist_function("keyctl_search")
|
.derive_eq(true)
|
||||||
.blocklist_type("bch_extent_ptr")
|
.layout_tests(true)
|
||||||
.blocklist_type("btree_node")
|
.default_enum_style(bindgen::EnumVariation::Rust {
|
||||||
.blocklist_type("bch_extent_crc32")
|
non_exhaustive: true,
|
||||||
.blocklist_type("rhash_lock_head")
|
})
|
||||||
.blocklist_type("srcu_struct")
|
.allowlist_function(".*bch2_.*")
|
||||||
.allowlist_var("BCH_.*")
|
.allowlist_function("bio_.*")
|
||||||
.allowlist_var("KEY_SPEC_.*")
|
.allowlist_function("bch2_super_write_fd")
|
||||||
.allowlist_type("bch_kdf_types")
|
.allowlist_function("derive_passphrase")
|
||||||
.allowlist_type("bch_sb_field_.*")
|
.allowlist_function("request_key")
|
||||||
.allowlist_type("bch_encrypted_key")
|
.allowlist_function("add_key")
|
||||||
.allowlist_type("nonce")
|
.allowlist_function("keyctl_search")
|
||||||
.newtype_enum("bch_kdf_types")
|
.blocklist_type("bch_extent_ptr")
|
||||||
.opaque_type("gendisk")
|
.blocklist_type("btree_node")
|
||||||
.opaque_type("bkey")
|
.blocklist_type("bch_extent_crc32")
|
||||||
.opaque_type("gc_stripe")
|
.blocklist_type("rhash_lock_head")
|
||||||
.opaque_type("open_bucket.*")
|
.blocklist_type("srcu_struct")
|
||||||
.generate()
|
.allowlist_var("BCH_.*")
|
||||||
.expect("BindGen Generation Failiure: [libbcachefs_wrapper]");
|
.allowlist_var("KEY_SPEC_.*")
|
||||||
bindings
|
.allowlist_type("bch_kdf_types")
|
||||||
.write_to_file(out_dir.join("bcachefs.rs"))
|
.allowlist_type("bch_sb_field_.*")
|
||||||
.expect("Writing to output file failed for: `bcachefs.rs`");
|
.allowlist_type("bch_encrypted_key")
|
||||||
|
.allowlist_type("nonce")
|
||||||
|
.newtype_enum("bch_kdf_types")
|
||||||
|
.opaque_type("gendisk")
|
||||||
|
.opaque_type("bkey")
|
||||||
|
.opaque_type("gc_stripe")
|
||||||
|
.opaque_type("open_bucket.*")
|
||||||
|
.generate()
|
||||||
|
.expect("BindGen Generation Failiure: [libbcachefs_wrapper]");
|
||||||
|
bindings
|
||||||
|
.write_to_file(out_dir.join("bcachefs.rs"))
|
||||||
|
.expect("Writing to output file failed for: `bcachefs.rs`");
|
||||||
|
|
||||||
let keyutils = pkg_config::probe_library("libkeyutils").expect("Failed to find keyutils lib");
|
let keyutils = pkg_config::probe_library("libkeyutils").expect("Failed to find keyutils lib");
|
||||||
let bindings = bindgen::builder()
|
let bindings = bindgen::builder()
|
||||||
.header(top_dir.join("src").join("keyutils_wrapper.h").display().to_string())
|
.header(
|
||||||
.clang_args(keyutils.include_paths.iter().map(|p| format!("-I{}", p.display())))
|
top_dir
|
||||||
.generate()
|
.join("src")
|
||||||
.expect("BindGen Generation Failiure: [Keyutils]");
|
.join("keyutils_wrapper.h")
|
||||||
bindings
|
.display()
|
||||||
.write_to_file(out_dir.join("keyutils.rs"))
|
.to_string(),
|
||||||
.expect("Writing to output file failed for: `keyutils.rs`");
|
)
|
||||||
|
.clang_args(
|
||||||
|
keyutils
|
||||||
|
.include_paths
|
||||||
|
.iter()
|
||||||
|
.map(|p| format!("-I{}", p.display())),
|
||||||
|
)
|
||||||
|
.generate()
|
||||||
|
.expect("BindGen Generation Failiure: [Keyutils]");
|
||||||
|
bindings
|
||||||
|
.write_to_file(out_dir.join("keyutils.rs"))
|
||||||
|
.expect("Writing to output file failed for: `keyutils.rs`");
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,2 +1,3 @@
|
|||||||
max_width=120
|
# Default settings, i.e. idiomatic rust
|
||||||
hard_tabs = true
|
edition = "2021"
|
||||||
|
newline_style = "Unix"
|
||||||
@ -7,101 +7,104 @@ include!(concat!(env!("OUT_DIR"), "/bcachefs.rs"));
|
|||||||
|
|
||||||
use bitfield::bitfield;
|
use bitfield::bitfield;
|
||||||
bitfield! {
|
bitfield! {
|
||||||
pub struct bch_scrypt_flags(u64);
|
pub struct bch_scrypt_flags(u64);
|
||||||
pub N, _: 15, 0;
|
pub N, _: 15, 0;
|
||||||
pub R, _: 31, 16;
|
pub R, _: 31, 16;
|
||||||
pub P, _: 47, 32;
|
pub P, _: 47, 32;
|
||||||
}
|
}
|
||||||
bitfield! {
|
bitfield! {
|
||||||
pub struct bch_crypt_flags(u64);
|
pub struct bch_crypt_flags(u64);
|
||||||
pub TYPE, _: 4, 0;
|
pub TYPE, _: 4, 0;
|
||||||
}
|
}
|
||||||
use memoffset::offset_of;
|
use memoffset::offset_of;
|
||||||
impl bch_sb_field_crypt {
|
impl bch_sb_field_crypt {
|
||||||
pub fn scrypt_flags(&self) -> Option<bch_scrypt_flags> {
|
pub fn scrypt_flags(&self) -> Option<bch_scrypt_flags> {
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
match bch_kdf_types(bch_crypt_flags(self.flags).TYPE().try_into().ok()?) {
|
match bch_kdf_types(bch_crypt_flags(self.flags).TYPE().try_into().ok()?) {
|
||||||
bch_kdf_types::BCH_KDF_SCRYPT => Some(bch_scrypt_flags(self.kdf_flags)),
|
bch_kdf_types::BCH_KDF_SCRYPT => Some(bch_scrypt_flags(self.kdf_flags)),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub fn key(&self) -> &bch_encrypted_key {
|
pub fn key(&self) -> &bch_encrypted_key {
|
||||||
&self.key
|
&self.key
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl PartialEq for bch_sb {
|
impl PartialEq for bch_sb {
|
||||||
fn eq(&self, other: &Self) -> bool {
|
fn eq(&self, other: &Self) -> bool {
|
||||||
self.magic.b == other.magic.b
|
self.magic.b == other.magic.b
|
||||||
&& self.user_uuid.b == other.user_uuid.b
|
&& self.user_uuid.b == other.user_uuid.b
|
||||||
&& self.block_size == other.block_size
|
&& self.block_size == other.block_size
|
||||||
&& self.version == other.version
|
&& self.version == other.version
|
||||||
&& self.uuid.b == other.uuid.b
|
&& self.uuid.b == other.uuid.b
|
||||||
&& self.seq == other.seq
|
&& self.seq == other.seq
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl bch_sb {
|
impl bch_sb {
|
||||||
pub fn crypt(&self) -> Option<&bch_sb_field_crypt> {
|
pub fn crypt(&self) -> Option<&bch_sb_field_crypt> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let ptr = bch2_sb_field_get(self as *const _ as *mut _, bch_sb_field_type::BCH_SB_FIELD_crypt) as *const u8;
|
let ptr = bch2_sb_field_get(
|
||||||
if ptr.is_null() {
|
self as *const _ as *mut _,
|
||||||
None
|
bch_sb_field_type::BCH_SB_FIELD_crypt,
|
||||||
} else {
|
) as *const u8;
|
||||||
let offset = offset_of!(bch_sb_field_crypt, field);
|
if ptr.is_null() {
|
||||||
Some(&*((ptr.sub(offset)) as *const _))
|
None
|
||||||
}
|
} else {
|
||||||
}
|
let offset = offset_of!(bch_sb_field_crypt, field);
|
||||||
}
|
Some(&*((ptr.sub(offset)) as *const _))
|
||||||
pub fn uuid(&self) -> uuid::Uuid {
|
}
|
||||||
uuid::Uuid::from_bytes(self.user_uuid.b)
|
}
|
||||||
}
|
}
|
||||||
|
pub fn uuid(&self) -> uuid::Uuid {
|
||||||
|
uuid::Uuid::from_bytes(self.user_uuid.b)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the nonce used to encrypt the superblock
|
/// Get the nonce used to encrypt the superblock
|
||||||
pub fn nonce(&self) -> nonce {
|
pub fn nonce(&self) -> nonce {
|
||||||
use byteorder::{LittleEndian, ReadBytesExt};
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
let mut internal_uuid = &self.uuid.b[..];
|
let mut internal_uuid = &self.uuid.b[..];
|
||||||
let dword1 = internal_uuid.read_u32::<LittleEndian>().unwrap();
|
let dword1 = internal_uuid.read_u32::<LittleEndian>().unwrap();
|
||||||
let dword2 = internal_uuid.read_u32::<LittleEndian>().unwrap();
|
let dword2 = internal_uuid.read_u32::<LittleEndian>().unwrap();
|
||||||
nonce {
|
nonce {
|
||||||
d: [0, 0, dword1, dword2],
|
d: [0, 0, dword1, dword2],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl bch_sb_handle {
|
impl bch_sb_handle {
|
||||||
pub fn sb(&self) -> &bch_sb {
|
pub fn sb(&self) -> &bch_sb {
|
||||||
unsafe { &*self.sb }
|
unsafe { &*self.sb }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn bdev(&self) -> &block_device {
|
pub fn bdev(&self) -> &block_device {
|
||||||
unsafe { &*self.bdev }
|
unsafe { &*self.bdev }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(C)]
|
#[repr(C)]
|
||||||
// #[repr(align(8))]
|
// #[repr(align(8))]
|
||||||
#[derive(Debug, Default, Copy, Clone)]
|
#[derive(Debug, Default, Copy, Clone)]
|
||||||
pub struct bch_extent_ptr {
|
pub struct bch_extent_ptr {
|
||||||
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>,
|
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 8usize]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(C, packed(8))]
|
#[repr(C, packed(8))]
|
||||||
pub struct btree_node {
|
pub struct btree_node {
|
||||||
pub csum: bch_csum,
|
pub csum: bch_csum,
|
||||||
pub magic: __le64,
|
pub magic: __le64,
|
||||||
pub flags: __le64,
|
pub flags: __le64,
|
||||||
pub min_key: bpos,
|
pub min_key: bpos,
|
||||||
pub max_key: bpos,
|
pub max_key: bpos,
|
||||||
pub _ptr: bch_extent_ptr,
|
pub _ptr: bch_extent_ptr,
|
||||||
pub format: bkey_format,
|
pub format: bkey_format,
|
||||||
pub __bindgen_anon_1: btree_node__bindgen_ty_1,
|
pub __bindgen_anon_1: btree_node__bindgen_ty_1,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[repr(C, packed(8))]
|
#[repr(C, packed(8))]
|
||||||
// #[repr(align(8))]
|
// #[repr(align(8))]
|
||||||
#[derive(Debug, Default, Copy, Clone)]
|
#[derive(Debug, Default, Copy, Clone)]
|
||||||
pub struct bch_extent_crc32 {
|
pub struct bch_extent_crc32 {
|
||||||
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>,
|
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize]>,
|
||||||
pub csum: __u32,
|
pub csum: __u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[repr(u8)]
|
// #[repr(u8)]
|
||||||
|
|||||||
@ -3,5 +3,5 @@ pub mod keyutils;
|
|||||||
pub mod rs;
|
pub mod rs;
|
||||||
|
|
||||||
pub mod c {
|
pub mod c {
|
||||||
pub use crate::bcachefs::*;
|
pub use crate::bcachefs::*;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,58 +1,61 @@
|
|||||||
use crate::bcachefs;
|
use crate::bcachefs;
|
||||||
|
|
||||||
pub const SUPERBLOCK_MAGIC: uuid::Uuid = uuid::Uuid::from_u128(
|
pub const SUPERBLOCK_MAGIC: uuid::Uuid =
|
||||||
0x_c68573f6_4e1a_45ca_8265_f57f48ba6d81
|
uuid::Uuid::from_u128(0x_c68573f6_4e1a_45ca_8265_f57f48ba6d81);
|
||||||
);
|
|
||||||
|
|
||||||
extern "C" {
|
extern "C" {
|
||||||
pub static stdout: *mut libc::FILE;
|
pub static stdout: *mut libc::FILE;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum ReadSuperErr {
|
pub enum ReadSuperErr {
|
||||||
Io(std::io::Error),
|
Io(std::io::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
type RResult<T> = std::io::Result<std::io::Result<T>>;
|
type RResult<T> = std::io::Result<std::io::Result<T>>;
|
||||||
|
|
||||||
#[tracing_attributes::instrument(skip(opts))]
|
#[tracing_attributes::instrument(skip(opts))]
|
||||||
pub fn read_super_opts(path: &std::path::Path, mut opts: bcachefs::bch_opts) -> RResult<bcachefs::bch_sb_handle> {
|
pub fn read_super_opts(
|
||||||
// let devp = camino::Utf8Path::from_path(devp).unwrap();
|
path: &std::path::Path,
|
||||||
|
mut opts: bcachefs::bch_opts,
|
||||||
|
) -> RResult<bcachefs::bch_sb_handle> {
|
||||||
|
// let devp = camino::Utf8Path::from_path(devp).unwrap();
|
||||||
|
|
||||||
use std::os::unix::ffi::OsStrExt;
|
use std::os::unix::ffi::OsStrExt;
|
||||||
let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
|
let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
|
||||||
|
|
||||||
let mut sb = std::mem::MaybeUninit::zeroed();
|
let mut sb = std::mem::MaybeUninit::zeroed();
|
||||||
|
|
||||||
// use gag::{BufferRedirect};
|
// use gag::{BufferRedirect};
|
||||||
// // Stop libbcachefs from spamming the output
|
// // Stop libbcachefs from spamming the output
|
||||||
// let gag = BufferRedirect::stderr().unwrap();
|
// let gag = BufferRedirect::stderr().unwrap();
|
||||||
// tracing::trace!("entering libbcachefs");
|
// tracing::trace!("entering libbcachefs");
|
||||||
|
|
||||||
let ret = unsafe { crate::bcachefs::bch2_read_super(path.as_ptr(), &mut opts, sb.as_mut_ptr()) };
|
let ret =
|
||||||
tracing::trace!(%ret);
|
unsafe { crate::bcachefs::bch2_read_super(path.as_ptr(), &mut opts, sb.as_mut_ptr()) };
|
||||||
|
tracing::trace!(%ret);
|
||||||
|
|
||||||
match -ret {
|
match -ret {
|
||||||
libc::EACCES => Err(std::io::Error::new(
|
libc::EACCES => Err(std::io::Error::new(
|
||||||
std::io::ErrorKind::PermissionDenied,
|
std::io::ErrorKind::PermissionDenied,
|
||||||
"Access Permission Denied",
|
"Access Permission Denied",
|
||||||
)),
|
)),
|
||||||
0 => Ok(Ok(unsafe { sb.assume_init() })),
|
0 => Ok(Ok(unsafe { sb.assume_init() })),
|
||||||
22 => Ok(Err(std::io::Error::new(
|
22 => Ok(Err(std::io::Error::new(
|
||||||
std::io::ErrorKind::InvalidData,
|
std::io::ErrorKind::InvalidData,
|
||||||
"Not a BCacheFS SuperBlock",
|
"Not a BCacheFS SuperBlock",
|
||||||
))),
|
))),
|
||||||
code => {
|
code => {
|
||||||
tracing::debug!(msg = "BCacheFS return error code", ?code);
|
tracing::debug!(msg = "BCacheFS return error code", ?code);
|
||||||
Ok(Err(std::io::Error::new(
|
Ok(Err(std::io::Error::new(
|
||||||
std::io::ErrorKind::Other,
|
std::io::ErrorKind::Other,
|
||||||
"Failed to Read SuperBlock",
|
"Failed to Read SuperBlock",
|
||||||
)))
|
)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing_attributes::instrument]
|
#[tracing_attributes::instrument]
|
||||||
pub fn read_super(path: &std::path::Path) -> RResult<bcachefs::bch_sb_handle> {
|
pub fn read_super(path: &std::path::Path) -> RResult<bcachefs::bch_sb_handle> {
|
||||||
let opts = bcachefs::bch_opts::default(); //unsafe {std::mem::MaybeUninit::zeroed().assume_init()};
|
let opts = bcachefs::bch_opts::default(); //unsafe {std::mem::MaybeUninit::zeroed().assume_init()};
|
||||||
read_super_opts(path, opts)
|
read_super_opts(path, opts)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,2 +1,3 @@
|
|||||||
max_width=120
|
# Default settings, i.e. idiomatic rust
|
||||||
hard_tabs = true
|
edition = "2021"
|
||||||
|
newline_style = "Unix"
|
||||||
@ -1,158 +1,159 @@
|
|||||||
extern "C" {
|
extern "C" {
|
||||||
pub static stdout: *mut libc::FILE;
|
pub static stdout: *mut libc::FILE;
|
||||||
}
|
}
|
||||||
|
|
||||||
use getset::{CopyGetters, Getters};
|
use getset::{CopyGetters, Getters};
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
#[derive(Getters, CopyGetters)]
|
#[derive(Getters, CopyGetters)]
|
||||||
pub struct FileSystem {
|
pub struct FileSystem {
|
||||||
/// External UUID of the bcachefs
|
/// External UUID of the bcachefs
|
||||||
#[getset(get = "pub")]
|
#[getset(get = "pub")]
|
||||||
uuid: uuid::Uuid,
|
uuid: uuid::Uuid,
|
||||||
/// Whether filesystem is encrypted
|
/// Whether filesystem is encrypted
|
||||||
#[getset(get_copy = "pub")]
|
#[getset(get_copy = "pub")]
|
||||||
encrypted: bool,
|
encrypted: bool,
|
||||||
/// Super block
|
/// Super block
|
||||||
#[getset(get = "pub")]
|
#[getset(get = "pub")]
|
||||||
sb: bcachefs::bch_sb_handle,
|
sb: bcachefs::bch_sb_handle,
|
||||||
/// Member devices for this filesystem
|
/// Member devices for this filesystem
|
||||||
#[getset(get = "pub")]
|
#[getset(get = "pub")]
|
||||||
devices: Vec<PathBuf>,
|
devices: Vec<PathBuf>,
|
||||||
}
|
}
|
||||||
impl std::fmt::Debug for FileSystem {
|
impl std::fmt::Debug for FileSystem {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.debug_struct("FileSystem")
|
f.debug_struct("FileSystem")
|
||||||
.field("uuid", &self.uuid)
|
.field("uuid", &self.uuid)
|
||||||
.field("encrypted", &self.encrypted)
|
.field("encrypted", &self.encrypted)
|
||||||
.field("devices", &self.device_string())
|
.field("devices", &self.device_string())
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
impl std::fmt::Display for FileSystem {
|
impl std::fmt::Display for FileSystem {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let devs = self.device_string();
|
let devs = self.device_string();
|
||||||
write!(
|
write!(
|
||||||
f,
|
f,
|
||||||
"{:?}: locked?={lock} ({}) ",
|
"{:?}: locked?={lock} ({}) ",
|
||||||
self.uuid,
|
self.uuid,
|
||||||
devs,
|
devs,
|
||||||
lock = self.encrypted
|
lock = self.encrypted
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl FileSystem {
|
impl FileSystem {
|
||||||
pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
|
pub(crate) fn new(sb: bcachefs::bch_sb_handle) -> Self {
|
||||||
Self {
|
Self {
|
||||||
uuid: sb.sb().uuid(),
|
uuid: sb.sb().uuid(),
|
||||||
encrypted: sb.sb().crypt().is_some(),
|
encrypted: sb.sb().crypt().is_some(),
|
||||||
sb: sb,
|
sb: sb,
|
||||||
devices: Vec::new(),
|
devices: Vec::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn device_string(&self) -> String {
|
pub fn device_string(&self) -> String {
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
self.devices.iter().map(|d| d.display()).join(":")
|
self.devices.iter().map(|d| d.display()).join(":")
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mount(
|
pub fn mount(
|
||||||
&self,
|
&self,
|
||||||
target: impl AsRef<std::path::Path>,
|
target: impl AsRef<std::path::Path>,
|
||||||
options: impl AsRef<str>,
|
options: impl AsRef<str>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
tracing::info_span!("mount").in_scope(|| {
|
tracing::info_span!("mount").in_scope(|| {
|
||||||
let src = self.device_string();
|
let src = self.device_string();
|
||||||
let (data, mountflags) = parse_mount_options(options);
|
let (data, mountflags) = parse_mount_options(options);
|
||||||
// let fstype = c_str!("bcachefs");
|
// let fstype = c_str!("bcachefs");
|
||||||
|
|
||||||
tracing::info!(msg="mounting bcachefs filesystem", target=%target.as_ref().display());
|
tracing::info!(msg="mounting bcachefs filesystem", target=%target.as_ref().display());
|
||||||
mount_inner(src, target, "bcachefs", mountflags, data)
|
mount_inner(src, target, "bcachefs", mountflags, data)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn mount_inner(
|
fn mount_inner(
|
||||||
src: String,
|
src: String,
|
||||||
target: impl AsRef<std::path::Path>,
|
target: impl AsRef<std::path::Path>,
|
||||||
fstype: &str,
|
fstype: &str,
|
||||||
mountflags: u64,
|
mountflags: u64,
|
||||||
data: Option<String>,
|
data: Option<String>,
|
||||||
) -> anyhow::Result<()> {
|
) -> anyhow::Result<()> {
|
||||||
use std::{
|
use std::{
|
||||||
ffi::{c_void, CString},
|
ffi::{c_void, CString},
|
||||||
os::{raw::c_char, unix::ffi::OsStrExt},
|
os::{raw::c_char, unix::ffi::OsStrExt},
|
||||||
};
|
};
|
||||||
|
|
||||||
// bind the CStrings to keep them alive
|
// bind the CStrings to keep them alive
|
||||||
let src = CString::new(src)?;
|
let src = CString::new(src)?;
|
||||||
let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
|
let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
|
||||||
let data = data.map(CString::new).transpose()?;
|
let data = data.map(CString::new).transpose()?;
|
||||||
let fstype = CString::new(fstype)?;
|
let fstype = CString::new(fstype)?;
|
||||||
|
|
||||||
// convert to pointers for ffi
|
// convert to pointers for ffi
|
||||||
let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
||||||
let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
||||||
let data = data.as_ref().map_or(std::ptr::null(), |data| {
|
let data = data.as_ref().map_or(std::ptr::null(), |data| {
|
||||||
data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
|
data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
|
||||||
});
|
});
|
||||||
let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
|
||||||
|
|
||||||
let ret = {let _entered = tracing::info_span!("libc::mount").entered();
|
let ret = {
|
||||||
tracing::info!("mounting filesystem");
|
let _entered = tracing::info_span!("libc::mount").entered();
|
||||||
// REQUIRES: CAP_SYS_ADMIN
|
tracing::info!("mounting filesystem");
|
||||||
unsafe { libc::mount(src, target, fstype, mountflags, data) }
|
// REQUIRES: CAP_SYS_ADMIN
|
||||||
};
|
unsafe { libc::mount(src, target, fstype, mountflags, data) }
|
||||||
match ret {
|
};
|
||||||
0 => Ok(()),
|
match ret {
|
||||||
_ => Err(crate::ErrnoError(errno::errno()).into()),
|
0 => Ok(()),
|
||||||
}
|
_ => Err(crate::ErrnoError(errno::errno()).into()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse a comma-separated mount options and split out mountflags and filesystem
|
/// Parse a comma-separated mount options and split out mountflags and filesystem
|
||||||
/// specific options.
|
/// specific options.
|
||||||
#[tracing_attributes::instrument(skip(options))]
|
#[tracing_attributes::instrument(skip(options))]
|
||||||
fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, u64) {
|
fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, u64) {
|
||||||
use either::Either::*;
|
use either::Either::*;
|
||||||
tracing::debug!(msg="parsing mount options", options=?options.as_ref());
|
tracing::debug!(msg="parsing mount options", options=?options.as_ref());
|
||||||
let (opts, flags) = options
|
let (opts, flags) = options
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.split(",")
|
.split(",")
|
||||||
.map(|o| match o {
|
.map(|o| match o {
|
||||||
"dirsync" => Left(libc::MS_DIRSYNC),
|
"dirsync" => Left(libc::MS_DIRSYNC),
|
||||||
"lazytime" => Left(1 << 25), // MS_LAZYTIME
|
"lazytime" => Left(1 << 25), // MS_LAZYTIME
|
||||||
"mand" => Left(libc::MS_MANDLOCK),
|
"mand" => Left(libc::MS_MANDLOCK),
|
||||||
"noatime" => Left(libc::MS_NOATIME),
|
"noatime" => Left(libc::MS_NOATIME),
|
||||||
"nodev" => Left(libc::MS_NODEV),
|
"nodev" => Left(libc::MS_NODEV),
|
||||||
"nodiratime" => Left(libc::MS_NODIRATIME),
|
"nodiratime" => Left(libc::MS_NODIRATIME),
|
||||||
"noexec" => Left(libc::MS_NOEXEC),
|
"noexec" => Left(libc::MS_NOEXEC),
|
||||||
"nosuid" => Left(libc::MS_NOSUID),
|
"nosuid" => Left(libc::MS_NOSUID),
|
||||||
"ro" => Left(libc::MS_RDONLY),
|
"ro" => Left(libc::MS_RDONLY),
|
||||||
"rw" => Left(0),
|
"rw" => Left(0),
|
||||||
"relatime" => Left(libc::MS_RELATIME),
|
"relatime" => Left(libc::MS_RELATIME),
|
||||||
"strictatime" => Left(libc::MS_STRICTATIME),
|
"strictatime" => Left(libc::MS_STRICTATIME),
|
||||||
"sync" => Left(libc::MS_SYNCHRONOUS),
|
"sync" => Left(libc::MS_SYNCHRONOUS),
|
||||||
"" => Left(0),
|
"" => Left(0),
|
||||||
o @ _ => Right(o),
|
o @ _ => Right(o),
|
||||||
})
|
})
|
||||||
.fold((Vec::new(), 0), |(mut opts, flags), next| match next {
|
.fold((Vec::new(), 0), |(mut opts, flags), next| match next {
|
||||||
Left(f) => (opts, flags | f),
|
Left(f) => (opts, flags | f),
|
||||||
Right(o) => {
|
Right(o) => {
|
||||||
opts.push(o);
|
opts.push(o);
|
||||||
(opts, flags)
|
(opts, flags)
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
use itertools::Itertools;
|
use itertools::Itertools;
|
||||||
(
|
(
|
||||||
if opts.len() == 0 {
|
if opts.len() == 0 {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(opts.iter().join(","))
|
Some(opts.iter().join(","))
|
||||||
},
|
},
|
||||||
flags,
|
flags,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
use bch_bindgen::bcachefs;
|
use bch_bindgen::bcachefs;
|
||||||
@ -161,53 +162,57 @@ use uuid::Uuid;
|
|||||||
|
|
||||||
#[tracing_attributes::instrument]
|
#[tracing_attributes::instrument]
|
||||||
pub fn probe_filesystems() -> anyhow::Result<HashMap<Uuid, FileSystem>> {
|
pub fn probe_filesystems() -> anyhow::Result<HashMap<Uuid, FileSystem>> {
|
||||||
tracing::trace!("enumerating udev devices");
|
tracing::trace!("enumerating udev devices");
|
||||||
let mut udev = udev::Enumerator::new()?;
|
let mut udev = udev::Enumerator::new()?;
|
||||||
|
|
||||||
udev.match_subsystem("block")?; // find kernel block devices
|
udev.match_subsystem("block")?; // find kernel block devices
|
||||||
|
|
||||||
let mut fs_map = HashMap::new();
|
let mut fs_map = HashMap::new();
|
||||||
let devresults =
|
let devresults = udev
|
||||||
udev.scan_devices()?
|
.scan_devices()?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|dev| dev.devnode().map(ToOwned::to_owned));
|
.filter_map(|dev| dev.devnode().map(ToOwned::to_owned));
|
||||||
|
|
||||||
for pathbuf in devresults {
|
|
||||||
match get_super_block_uuid(&pathbuf)? {
|
|
||||||
|
|
||||||
Ok((uuid_key, superblock)) => {
|
for pathbuf in devresults {
|
||||||
let fs = fs_map.entry(uuid_key).or_insert_with(|| {
|
match get_super_block_uuid(&pathbuf)? {
|
||||||
tracing::info!(msg="found bcachefs pool", uuid=?uuid_key);
|
Ok((uuid_key, superblock)) => {
|
||||||
FileSystem::new(superblock)
|
let fs = fs_map.entry(uuid_key).or_insert_with(|| {
|
||||||
});
|
tracing::info!(msg="found bcachefs pool", uuid=?uuid_key);
|
||||||
|
FileSystem::new(superblock)
|
||||||
|
});
|
||||||
|
|
||||||
fs.devices.push(pathbuf);
|
fs.devices.push(pathbuf);
|
||||||
},
|
}
|
||||||
|
|
||||||
Err(e) => { tracing::debug!(inner2_error=?e);}
|
Err(e) => {
|
||||||
}
|
tracing::debug!(inner2_error=?e);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tracing::info!(msg = "found filesystems", count = fs_map.len());
|
||||||
tracing::info!(msg = "found filesystems", count = fs_map.len());
|
Ok(fs_map)
|
||||||
Ok(fs_map)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// #[tracing_attributes::instrument(skip(dev, fs_map))]
|
// #[tracing_attributes::instrument(skip(dev, fs_map))]
|
||||||
fn get_super_block_uuid(path: &std::path::Path) -> std::io::Result<std::io::Result<(Uuid, bcachefs::bch_sb_handle)>> {
|
fn get_super_block_uuid(
|
||||||
use gag::{BufferRedirect};
|
path: &std::path::Path,
|
||||||
// Stop libbcachefs from spamming the output
|
) -> std::io::Result<std::io::Result<(Uuid, bcachefs::bch_sb_handle)>> {
|
||||||
let gag = BufferRedirect::stdout().unwrap();
|
use gag::BufferRedirect;
|
||||||
|
// Stop libbcachefs from spamming the output
|
||||||
|
let gag = BufferRedirect::stdout().unwrap();
|
||||||
|
|
||||||
let sb = bch_bindgen::rs::read_super(&path)?;
|
let sb = bch_bindgen::rs::read_super(&path)?;
|
||||||
let super_block = match sb {
|
let super_block = match sb {
|
||||||
Err(e) => { return Ok(Err(e)); }
|
Err(e) => {
|
||||||
Ok(sb) => sb,
|
return Ok(Err(e));
|
||||||
};
|
}
|
||||||
drop(gag);
|
Ok(sb) => sb,
|
||||||
|
};
|
||||||
|
drop(gag);
|
||||||
|
|
||||||
let uuid = (&super_block).sb().uuid();
|
let uuid = (&super_block).sb().uuid();
|
||||||
tracing::debug!(found="bcachefs superblock", devnode=?path, ?uuid);
|
tracing::debug!(found="bcachefs superblock", devnode=?path, ?uuid);
|
||||||
|
|
||||||
Ok(Ok((uuid, super_block)))
|
Ok(Ok((uuid, super_block)))
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,97 +1,97 @@
|
|||||||
use tracing::info;
|
use tracing::info;
|
||||||
|
|
||||||
fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
|
fn check_for_key(key_name: &std::ffi::CStr) -> anyhow::Result<bool> {
|
||||||
use bch_bindgen::keyutils::{self, keyctl_search};
|
use bch_bindgen::keyutils::{self, keyctl_search};
|
||||||
let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
|
let key_name = key_name.to_bytes_with_nul().as_ptr() as *const _;
|
||||||
let key_type = c_str!("logon");
|
let key_type = c_str!("logon");
|
||||||
|
|
||||||
let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
|
let key_id = unsafe { keyctl_search(keyutils::KEY_SPEC_USER_KEYRING, key_type, key_name, 0) };
|
||||||
if key_id > 0 {
|
if key_id > 0 {
|
||||||
info!("Key has became avaiable");
|
info!("Key has became avaiable");
|
||||||
Ok(true)
|
Ok(true)
|
||||||
} else if errno::errno().0 != libc::ENOKEY {
|
} else if errno::errno().0 != libc::ENOKEY {
|
||||||
Err(crate::ErrnoError(errno::errno()).into())
|
Err(crate::ErrnoError(errno::errno()).into())
|
||||||
} else {
|
} else {
|
||||||
Ok(false)
|
Ok(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
|
fn wait_for_key(uuid: &uuid::Uuid) -> anyhow::Result<()> {
|
||||||
let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
|
let key_name = std::ffi::CString::new(format!("bcachefs:{}", uuid)).unwrap();
|
||||||
loop {
|
loop {
|
||||||
if check_for_key(&key_name)? {
|
if check_for_key(&key_name)? {
|
||||||
break Ok(());
|
break Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
std::thread::sleep(std::time::Duration::from_secs(1));
|
std::thread::sleep(std::time::Duration::from_secs(1));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const BCH_KEY_MAGIC: &str = "bch**key";
|
const BCH_KEY_MAGIC: &str = "bch**key";
|
||||||
use crate::filesystem::FileSystem;
|
use crate::filesystem::FileSystem;
|
||||||
fn ask_for_key(fs: &FileSystem) -> anyhow::Result<()> {
|
fn ask_for_key(fs: &FileSystem) -> anyhow::Result<()> {
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use byteorder::{LittleEndian, ReadBytesExt};
|
use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
|
||||||
use bch_bindgen::bcachefs::{self, bch2_chacha_encrypt_key, bch_encrypted_key, bch_key};
|
use byteorder::{LittleEndian, ReadBytesExt};
|
||||||
use std::os::raw::c_char;
|
use std::os::raw::c_char;
|
||||||
|
|
||||||
let key_name = std::ffi::CString::new(format!("bcachefs:{}", fs.uuid())).unwrap();
|
let key_name = std::ffi::CString::new(format!("bcachefs:{}", fs.uuid())).unwrap();
|
||||||
if check_for_key(&key_name)? {
|
if check_for_key(&key_name)? {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
|
let bch_key_magic = BCH_KEY_MAGIC.as_bytes().read_u64::<LittleEndian>().unwrap();
|
||||||
let crypt = fs.sb().sb().crypt().unwrap();
|
let crypt = fs.sb().sb().crypt().unwrap();
|
||||||
let pass = rpassword::read_password_from_tty(Some("Enter passphrase: "))?;
|
let pass = rpassword::read_password_from_tty(Some("Enter passphrase: "))?;
|
||||||
let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
|
let pass = std::ffi::CString::new(pass.trim_end())?; // bind to keep the CString alive
|
||||||
let mut output: bch_key = unsafe {
|
let mut output: bch_key = unsafe {
|
||||||
bcachefs::derive_passphrase(
|
bcachefs::derive_passphrase(
|
||||||
crypt as *const _ as *mut _,
|
crypt as *const _ as *mut _,
|
||||||
pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
|
pass.as_c_str().to_bytes_with_nul().as_ptr() as *const _,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut key = crypt.key().clone();
|
let mut key = crypt.key().clone();
|
||||||
let ret = unsafe {
|
let ret = unsafe {
|
||||||
bch2_chacha_encrypt_key(
|
bch2_chacha_encrypt_key(
|
||||||
&mut output as *mut _,
|
&mut output as *mut _,
|
||||||
fs.sb().sb().nonce(),
|
fs.sb().sb().nonce(),
|
||||||
&mut key as *mut _ as *mut _,
|
&mut key as *mut _ as *mut _,
|
||||||
std::mem::size_of::<bch_encrypted_key>() as usize,
|
std::mem::size_of::<bch_encrypted_key>() as usize,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
if ret != 0 {
|
if ret != 0 {
|
||||||
Err(anyhow!("chacha decryption failure"))
|
Err(anyhow!("chacha decryption failure"))
|
||||||
} else if key.magic != bch_key_magic {
|
} else if key.magic != bch_key_magic {
|
||||||
Err(anyhow!("failed to verify the password"))
|
Err(anyhow!("failed to verify the password"))
|
||||||
} else {
|
} else {
|
||||||
let key_type = c_str!("logon");
|
let key_type = c_str!("logon");
|
||||||
let ret = unsafe {
|
let ret = unsafe {
|
||||||
bch_bindgen::keyutils::add_key(
|
bch_bindgen::keyutils::add_key(
|
||||||
key_type,
|
key_type,
|
||||||
key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
|
key_name.as_c_str().to_bytes_with_nul() as *const _ as *const c_char,
|
||||||
&output as *const _ as *const _,
|
&output as *const _ as *const _,
|
||||||
std::mem::size_of::<bch_key>() as usize,
|
std::mem::size_of::<bch_key>() as usize,
|
||||||
bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
|
bch_bindgen::keyutils::KEY_SPEC_USER_KEYRING,
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
if ret == -1 {
|
if ret == -1 {
|
||||||
Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
|
Err(anyhow!("failed to add key to keyring: {}", errno::errno()))
|
||||||
} else {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tracing_attributes::instrument]
|
#[tracing_attributes::instrument]
|
||||||
pub fn prepare_key(fs: &FileSystem, password: crate::KeyLocation) -> anyhow::Result<()> {
|
pub fn prepare_key(fs: &FileSystem, password: crate::KeyLocation) -> anyhow::Result<()> {
|
||||||
use crate::KeyLocation::*;
|
use crate::KeyLocation::*;
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
|
|
||||||
tracing::info!(msg = "checking if key exists for filesystem");
|
tracing::info!(msg = "checking if key exists for filesystem");
|
||||||
match password {
|
match password {
|
||||||
Fail => Err(anyhow!("no key available")),
|
Fail => Err(anyhow!("no key available")),
|
||||||
Wait => Ok(wait_for_key(fs.uuid())?),
|
Wait => Ok(wait_for_key(fs.uuid())?),
|
||||||
Ask => ask_for_key(fs),
|
Ask => ask_for_key(fs),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,99 +3,99 @@ use clap::Parser;
|
|||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub mod err {
|
pub mod err {
|
||||||
pub enum GError {
|
pub enum GError {
|
||||||
Unknown{
|
Unknown {
|
||||||
message: std::borrow::Cow<'static, String>
|
message: std::borrow::Cow<'static, String>,
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
pub type GResult<T, E, OE> =::core::result::Result< ::core::result::Result<T, E>, OE>;
|
pub type GResult<T, E, OE> = ::core::result::Result<::core::result::Result<T, E>, OE>;
|
||||||
pub type Result<T, E> = GResult<T, E, GError>;
|
pub type Result<T, E> = GResult<T, E, GError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! c_str {
|
macro_rules! c_str {
|
||||||
($lit:expr) => {
|
($lit:expr) => {
|
||||||
unsafe {
|
unsafe {
|
||||||
std::ffi::CStr::from_ptr(concat!($lit, "\0").as_ptr() as *const std::os::raw::c_char)
|
std::ffi::CStr::from_ptr(concat!($lit, "\0").as_ptr() as *const std::os::raw::c_char)
|
||||||
.to_bytes_with_nul()
|
.to_bytes_with_nul()
|
||||||
.as_ptr() as *const std::os::raw::c_char
|
.as_ptr() as *const std::os::raw::c_char
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct ErrnoError(errno::Errno);
|
struct ErrnoError(errno::Errno);
|
||||||
impl std::fmt::Display for ErrnoError {
|
impl std::fmt::Display for ErrnoError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
|
||||||
self.0.fmt(f)
|
self.0.fmt(f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::error::Error for ErrnoError {}
|
impl std::error::Error for ErrnoError {}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum KeyLocation {
|
pub enum KeyLocation {
|
||||||
Fail,
|
Fail,
|
||||||
Wait,
|
Wait,
|
||||||
Ask,
|
Ask,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct KeyLoc(pub Option<KeyLocation>);
|
pub struct KeyLoc(pub Option<KeyLocation>);
|
||||||
impl std::ops::Deref for KeyLoc {
|
impl std::ops::Deref for KeyLoc {
|
||||||
type Target = Option<KeyLocation>;
|
type Target = Option<KeyLocation>;
|
||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
impl std::str::FromStr for KeyLoc {
|
impl std::str::FromStr for KeyLoc {
|
||||||
type Err = anyhow::Error;
|
type Err = anyhow::Error;
|
||||||
fn from_str(s: &str) -> anyhow::Result<Self> {
|
fn from_str(s: &str) -> anyhow::Result<Self> {
|
||||||
// use anyhow::anyhow;
|
// use anyhow::anyhow;
|
||||||
match s {
|
match s {
|
||||||
"" => Ok(KeyLoc(None)),
|
"" => Ok(KeyLoc(None)),
|
||||||
"fail" => Ok(KeyLoc(Some(KeyLocation::Fail))),
|
"fail" => Ok(KeyLoc(Some(KeyLocation::Fail))),
|
||||||
"wait" => Ok(KeyLoc(Some(KeyLocation::Wait))),
|
"wait" => Ok(KeyLoc(Some(KeyLocation::Wait))),
|
||||||
"ask" => Ok(KeyLoc(Some(KeyLocation::Ask))),
|
"ask" => Ok(KeyLoc(Some(KeyLocation::Ask))),
|
||||||
_ => Err(anyhow!("invalid password option")),
|
_ => Err(anyhow!("invalid password option")),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn parse_fstab_uuid(uuid_raw: &str) -> Result<Uuid, uuid::Error> {
|
fn parse_fstab_uuid(uuid_raw: &str) -> Result<Uuid, uuid::Error> {
|
||||||
let mut uuid = String::from(uuid_raw);
|
let mut uuid = String::from(uuid_raw);
|
||||||
if uuid.starts_with("UUID=") {
|
if uuid.starts_with("UUID=") {
|
||||||
uuid = uuid.replacen("UUID=", "", 1);
|
uuid = uuid.replacen("UUID=", "", 1);
|
||||||
}
|
}
|
||||||
return Uuid::parse_str(&uuid);
|
return Uuid::parse_str(&uuid);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Mount a bcachefs filesystem by its UUID.
|
/// Mount a bcachefs filesystem by its UUID.
|
||||||
#[derive(Parser, Debug)]
|
#[derive(Parser, Debug)]
|
||||||
#[command(author, version, about, long_about = None)]
|
#[command(author, version, about, long_about = None)]
|
||||||
pub struct Cli {
|
pub struct Cli {
|
||||||
/// Where the password would be loaded from.
|
/// Where the password would be loaded from.
|
||||||
///
|
///
|
||||||
/// Possible values are:
|
/// Possible values are:
|
||||||
/// "fail" - don't ask for password, fail if filesystem is encrypted;
|
/// "fail" - don't ask for password, fail if filesystem is encrypted;
|
||||||
/// "wait" - wait for password to become available before mounting;
|
/// "wait" - wait for password to become available before mounting;
|
||||||
/// "ask" - prompt the user for password;
|
/// "ask" - prompt the user for password;
|
||||||
#[arg(short, long, default_value = "", verbatim_doc_comment)]
|
#[arg(short, long, default_value = "", verbatim_doc_comment)]
|
||||||
pub key_location: KeyLoc,
|
pub key_location: KeyLoc,
|
||||||
|
|
||||||
/// External UUID of the bcachefs filesystem
|
/// External UUID of the bcachefs filesystem
|
||||||
///
|
///
|
||||||
/// Accepts the UUID as is or as fstab style UUID=<UUID>
|
/// Accepts the UUID as is or as fstab style UUID=<UUID>
|
||||||
#[arg(value_parser=parse_fstab_uuid)]
|
#[arg(value_parser=parse_fstab_uuid)]
|
||||||
pub uuid: uuid::Uuid,
|
pub uuid: uuid::Uuid,
|
||||||
|
|
||||||
/// Where the filesystem should be mounted. If not set, then the filesystem
|
/// Where the filesystem should be mounted. If not set, then the filesystem
|
||||||
/// won't actually be mounted. But all steps preceeding mounting the
|
/// won't actually be mounted. But all steps preceeding mounting the
|
||||||
/// filesystem (e.g. asking for passphrase) will still be performed.
|
/// filesystem (e.g. asking for passphrase) will still be performed.
|
||||||
pub mountpoint: Option<std::path::PathBuf>,
|
pub mountpoint: Option<std::path::PathBuf>,
|
||||||
|
|
||||||
/// Mount options
|
/// Mount options
|
||||||
#[arg(short, default_value = "")]
|
#[arg(short, default_value = "")]
|
||||||
pub options: String,
|
pub options: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod filesystem;
|
pub mod filesystem;
|
||||||
@ -105,6 +105,6 @@ pub mod key;
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn verify_cli() {
|
fn verify_cli() {
|
||||||
use clap::CommandFactory;
|
use clap::CommandFactory;
|
||||||
Cli::command().debug_assert()
|
Cli::command().debug_assert()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,64 +1,57 @@
|
|||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// convert existing log statements to tracing events
|
// convert existing log statements to tracing events
|
||||||
// tracing_log::LogTracer::init().expect("logtracer init failed!");
|
// tracing_log::LogTracer::init().expect("logtracer init failed!");
|
||||||
// format tracing log data to env_logger like stdout
|
// format tracing log data to env_logger like stdout
|
||||||
tracing_subscriber::fmt::init();
|
tracing_subscriber::fmt::init();
|
||||||
|
|
||||||
if let Err(e) = crate::main_inner() {
|
if let Err(e) = crate::main_inner() {
|
||||||
tracing::error!(fatal_error = ?e);
|
tracing::error!(fatal_error = ?e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[tracing_attributes::instrument("main")]
|
#[tracing_attributes::instrument("main")]
|
||||||
pub fn main_inner() -> anyhow::Result<()> {
|
pub fn main_inner() -> anyhow::Result<()> {
|
||||||
use bcachefs_mount::{Cli, filesystem, key};
|
use bcachefs_mount::{filesystem, key, Cli};
|
||||||
unsafe {
|
unsafe {
|
||||||
libc::setvbuf(
|
libc::setvbuf(filesystem::stdout, std::ptr::null_mut(), libc::_IONBF, 0);
|
||||||
filesystem::stdout,
|
// libc::fflush(filesystem::stdout);
|
||||||
std::ptr::null_mut(),
|
}
|
||||||
libc::_IONBF,
|
|
||||||
0,
|
|
||||||
);
|
|
||||||
// libc::fflush(filesystem::stdout);
|
|
||||||
}
|
|
||||||
|
|
||||||
let opt = Cli::parse();
|
let opt = Cli::parse();
|
||||||
|
|
||||||
tracing::trace!(?opt);
|
tracing::trace!(?opt);
|
||||||
|
|
||||||
let fss = filesystem::probe_filesystems()?;
|
let fss = filesystem::probe_filesystems()?;
|
||||||
let fs = fss
|
let fs = fss
|
||||||
.get(&opt.uuid)
|
.get(&opt.uuid)
|
||||||
.ok_or_else(|| anyhow::anyhow!("filesystem was not found"))?;
|
.ok_or_else(|| anyhow::anyhow!("filesystem was not found"))?;
|
||||||
|
|
||||||
tracing::info!(msg="found filesystem", %fs);
|
tracing::info!(msg="found filesystem", %fs);
|
||||||
if fs.encrypted() {
|
if fs.encrypted() {
|
||||||
let key = opt
|
let key = opt
|
||||||
.key_location
|
.key_location
|
||||||
.0
|
.0
|
||||||
.ok_or_else(|| anyhow::anyhow!("no keyoption specified for locked filesystem"))?;
|
.ok_or_else(|| anyhow::anyhow!("no keyoption specified for locked filesystem"))?;
|
||||||
|
|
||||||
key::prepare_key(&fs, key)?;
|
key::prepare_key(&fs, key)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
let mountpoint = opt
|
let mountpoint = opt
|
||||||
.mountpoint
|
.mountpoint
|
||||||
.ok_or_else(|| anyhow::anyhow!("mountpoint option was not specified"))?;
|
.ok_or_else(|| anyhow::anyhow!("mountpoint option was not specified"))?;
|
||||||
|
|
||||||
fs.mount(&mountpoint, &opt.options)?;
|
fs.mount(&mountpoint, &opt.options)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
// use insta::assert_debug_snapshot;
|
// use insta::assert_debug_snapshot;
|
||||||
// #[test]
|
// #[test]
|
||||||
// fn snapshot_testing() {
|
// fn snapshot_testing() {
|
||||||
// insta::assert_debug_snapshot!();
|
// insta::assert_debug_snapshot!();
|
||||||
// }
|
// }
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user