2 use bch_bindgen::{bcachefs, bcachefs::bch_sb_handle};
3 use log::{info, warn, debug, error, trace, LevelFilter};
6 use std::convert::TryInto;
7 use std::path::PathBuf;
9 use crate::key::KeyLoc;
10 use crate::logger::SimpleLogger;
11 use std::ffi::{CStr, CString, OsStr, c_int, c_char, c_void};
12 use std::os::unix::ffi::OsStrExt;
16 target: impl AsRef<std::path::Path>,
20 ) -> anyhow::Result<()> {
22 // bind the CStrings to keep them alive
23 let src = CString::new(src)?;
24 let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
25 let data = data.map(CString::new).transpose()?;
26 let fstype = CString::new(fstype)?;
28 // convert to pointers for ffi
29 let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
30 let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
31 let data = data.as_ref().map_or(std::ptr::null(), |data| {
32 data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
34 let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
37 info!("mounting filesystem");
38 // REQUIRES: CAP_SYS_ADMIN
39 unsafe { libc::mount(src, target, fstype, mountflags, data) }
43 _ => Err(crate::ErrnoError(errno::errno()).into()),
47 /// Parse a comma-separated mount options and split out mountflags and filesystem
49 fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, u64) {
50 use either::Either::*;
51 debug!("parsing mount options: {}", options.as_ref());
52 let (opts, flags) = options
56 "dirsync" => Left(libc::MS_DIRSYNC),
57 "lazytime" => Left(1 << 25), // MS_LAZYTIME
58 "mand" => Left(libc::MS_MANDLOCK),
59 "noatime" => Left(libc::MS_NOATIME),
60 "nodev" => Left(libc::MS_NODEV),
61 "nodiratime" => Left(libc::MS_NODIRATIME),
62 "noexec" => Left(libc::MS_NOEXEC),
63 "nosuid" => Left(libc::MS_NOSUID),
64 "relatime" => Left(libc::MS_RELATIME),
65 "remount" => Left(libc::MS_REMOUNT),
66 "ro" => Left(libc::MS_RDONLY),
68 "strictatime" => Left(libc::MS_STRICTATIME),
69 "sync" => Left(libc::MS_SYNCHRONOUS),
73 .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
74 Left(f) => (opts, flags | f),
81 use itertools::Itertools;
86 Some(opts.iter().join(","))
94 target: impl AsRef<std::path::Path>,
95 options: impl AsRef<str>,
96 ) -> anyhow::Result<()> {
97 let (data, mountflags) = parse_mount_options(options);
100 "mounting bcachefs filesystem, {}",
101 target.as_ref().display()
103 mount_inner(device, target, "bcachefs", mountflags, data)
106 fn read_super_silent(path: &std::path::PathBuf) -> anyhow::Result<bch_sb_handle> {
107 // Stop libbcachefs from spamming the output
108 let _gag = gag::BufferRedirect::stdout().unwrap();
110 bch_bindgen::rs::read_super(&path)
113 fn get_devices_by_uuid(uuid: Uuid) -> anyhow::Result<Vec<(PathBuf, bch_sb_handle)>> {
114 debug!("enumerating udev devices");
115 let mut udev = udev::Enumerator::new()?;
117 udev.match_subsystem("block")?;
122 .filter_map(|dev| dev.devnode().map(ToOwned::to_owned))
123 .map(|dev| (dev.clone(), read_super_silent(&dev)))
124 .filter_map(|(dev, sb)| sb.ok().map(|sb| (dev, sb)))
125 .filter(|(_, sb)| sb.sb().uuid() == uuid)
130 /// Mount a bcachefs filesystem by its UUID.
131 #[derive(Parser, Debug)]
132 #[command(author, version, about, long_about = None)]
134 /// Where the password would be loaded from.
136 /// Possible values are:
137 /// "fail" - don't ask for password, fail if filesystem is encrypted;
138 /// "wait" - wait for password to become available before mounting;
139 /// "ask" - prompt the user for password;
140 #[arg(short, long, default_value = "ask", verbatim_doc_comment)]
141 key_location: KeyLoc,
143 /// Device, or UUID=<UUID>
146 /// Where the filesystem should be mounted. If not set, then the filesystem
147 /// won't actually be mounted. But all steps preceeding mounting the
148 /// filesystem (e.g. asking for passphrase) will still be performed.
149 mountpoint: std::path::PathBuf,
152 #[arg(short, default_value = "")]
155 /// Force color on/off. Default: autodetect tty
156 #[arg(short, long, action = clap::ArgAction::Set, default_value_t=atty::is(Stream::Stdout))]
160 #[arg(short, long, action = clap::ArgAction::Count)]
164 fn cmd_mount_inner(opt: Cli) -> anyhow::Result<()> {
165 let (devs, sbs) = if opt.dev.starts_with("UUID=") {
166 let uuid = opt.dev.replacen("UUID=", "", 1);
167 let uuid = Uuid::parse_str(&uuid)?;
168 let devs_sbs = get_devices_by_uuid(uuid)?;
170 let devs_strs: Vec<_> = devs_sbs.iter().map(|(dev, _)| dev.clone().into_os_string().into_string().unwrap()).collect();
171 let devs_str = devs_strs.join(":");
172 let sbs = devs_sbs.iter().map(|(_, sb)| *sb).collect();
176 let mut sbs = Vec::new();
178 for dev in opt.dev.split(':') {
179 let dev = PathBuf::from(dev);
180 sbs.push(bch_bindgen::rs::read_super(&dev)?);
186 if unsafe { bcachefs::bch2_sb_is_encrypted(sbs[0].sb) } {
190 .ok_or_else(|| anyhow::anyhow!("no keyoption specified for locked filesystem"))?;
192 key::prepare_key(&sbs[0], key)?;
195 mount(devs, &opt.mountpoint, &opt.options)?;
200 pub extern "C" fn cmd_mount(argc: c_int, argv: *const *const c_char) {
201 let argv: Vec<_> = (0..argc)
202 .map(|i| unsafe { CStr::from_ptr(*argv.add(i as usize)) })
203 .map(|i| OsStr::from_bytes(i.to_bytes()))
206 let opt = Cli::parse_from(argv);
208 log::set_boxed_logger(Box::new(SimpleLogger)).unwrap();
210 // @TODO : more granular log levels via mount option
211 log::set_max_level(match opt.verbose {
212 0 => LevelFilter::Warn,
213 1 => LevelFilter::Trace,
214 2_u8..=u8::MAX => todo!(),
217 colored::control::set_override(opt.colorize);
218 if let Err(e) = cmd_mount_inner(opt) {
219 error!("Fatal error: {}", e);
221 info!("Successfully mounted");