2 use bch_bindgen::{bcachefs, bcachefs::bch_sb_handle};
3 use log::{info, debug, error, LevelFilter};
6 use std::path::PathBuf;
8 use crate::key::KeyLoc;
9 use crate::logger::SimpleLogger;
10 use std::ffi::{CStr, CString, OsStr, c_int, c_char, c_void};
11 use std::os::unix::ffi::OsStrExt;
15 target: impl AsRef<std::path::Path>,
17 mountflags: libc::c_ulong,
19 ) -> anyhow::Result<()> {
21 // bind the CStrings to keep them alive
22 let src = CString::new(src)?;
23 let target = CString::new(target.as_ref().as_os_str().as_bytes())?;
24 let data = data.map(CString::new).transpose()?;
25 let fstype = CString::new(fstype)?;
27 // convert to pointers for ffi
28 let src = src.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
29 let target = target.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
30 let data = data.as_ref().map_or(std::ptr::null(), |data| {
31 data.as_c_str().to_bytes_with_nul().as_ptr() as *const c_void
33 let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
36 info!("mounting filesystem");
37 // REQUIRES: CAP_SYS_ADMIN
38 unsafe { libc::mount(src, target, fstype, mountflags, data) }
42 _ => Err(crate::ErrnoError(errno::errno()).into()),
46 /// Parse a comma-separated mount options and split out mountflags and filesystem
48 fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, libc::c_ulong) {
49 use either::Either::*;
50 debug!("parsing mount options: {}", options.as_ref());
51 let (opts, flags) = options
55 "dirsync" => Left(libc::MS_DIRSYNC),
56 "lazytime" => Left(1 << 25), // MS_LAZYTIME
57 "mand" => Left(libc::MS_MANDLOCK),
58 "noatime" => Left(libc::MS_NOATIME),
59 "nodev" => Left(libc::MS_NODEV),
60 "nodiratime" => Left(libc::MS_NODIRATIME),
61 "noexec" => Left(libc::MS_NOEXEC),
62 "nosuid" => Left(libc::MS_NOSUID),
63 "relatime" => Left(libc::MS_RELATIME),
64 "remount" => Left(libc::MS_REMOUNT),
65 "ro" => Left(libc::MS_RDONLY),
67 "strictatime" => Left(libc::MS_STRICTATIME),
68 "sync" => Left(libc::MS_SYNCHRONOUS),
72 .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
73 Left(f) => (opts, flags | f),
80 use itertools::Itertools;
85 Some(opts.iter().join(","))
93 target: impl AsRef<std::path::Path>,
94 options: impl AsRef<str>,
95 ) -> anyhow::Result<()> {
96 let (data, mountflags) = parse_mount_options(options);
99 "mounting bcachefs filesystem, {}",
100 target.as_ref().display()
102 mount_inner(device, target, "bcachefs", mountflags, data)
105 fn read_super_silent(path: &std::path::PathBuf) -> anyhow::Result<bch_sb_handle> {
106 // Stop libbcachefs from spamming the output
107 let _gag = gag::BufferRedirect::stdout().unwrap();
109 bch_bindgen::rs::read_super(&path)
112 fn get_devices_by_uuid(uuid: Uuid) -> anyhow::Result<Vec<(PathBuf, bch_sb_handle)>> {
113 debug!("enumerating udev devices");
114 let mut udev = udev::Enumerator::new()?;
116 udev.match_subsystem("block")?;
121 .filter_map(|dev| dev.devnode().map(ToOwned::to_owned))
122 .map(|dev| (dev.clone(), read_super_silent(&dev)))
123 .filter_map(|(dev, sb)| sb.ok().map(|sb| (dev, sb)))
124 .filter(|(_, sb)| sb.sb().uuid() == uuid)
129 /// Mount a bcachefs filesystem by its UUID.
130 #[derive(Parser, Debug)]
131 #[command(author, version, about, long_about = None)]
133 /// Where the password would be loaded from.
135 /// Possible values are:
136 /// "fail" - don't ask for password, fail if filesystem is encrypted;
137 /// "wait" - wait for password to become available before mounting;
138 /// "ask" - prompt the user for password;
139 #[arg(short, long, default_value = "ask", verbatim_doc_comment)]
140 key_location: KeyLoc,
142 /// Device, or UUID=<UUID>
145 /// Where the filesystem should be mounted. If not set, then the filesystem
146 /// won't actually be mounted. But all steps preceeding mounting the
147 /// filesystem (e.g. asking for passphrase) will still be performed.
148 mountpoint: Option<std::path::PathBuf>,
151 #[arg(short, default_value = "")]
154 /// Force color on/off. Default: autodetect tty
155 #[arg(short, long, action = clap::ArgAction::Set, default_value_t=atty::is(Stream::Stdout))]
159 #[arg(short, long, action = clap::ArgAction::Count)]
163 fn devs_str_sbs_from_uuid(uuid: String) -> anyhow::Result<(String, Vec<bch_sb_handle>)> {
164 debug!("enumerating devices with UUID {}", uuid);
166 let devs_sbs = Uuid::parse_str(&uuid)
167 .map(|uuid| get_devices_by_uuid(uuid))??;
169 let devs_str = devs_sbs
171 .map(|(dev, _)| dev.to_str().unwrap())
175 let sbs: Vec<bch_sb_handle> = devs_sbs.iter().map(|(_, sb)| *sb).collect();
181 fn cmd_mount_inner(opt: Cli) -> anyhow::Result<()> {
182 let (devs, sbs) = if opt.dev.starts_with("UUID=") {
183 let uuid = opt.dev.replacen("UUID=", "", 1);
184 devs_str_sbs_from_uuid(uuid)?
185 } else if opt.dev.starts_with("OLD_BLKID_UUID=") {
186 let uuid = opt.dev.replacen("OLD_BLKID_UUID=", "", 1);
187 devs_str_sbs_from_uuid(uuid)?
189 let mut sbs = Vec::new();
191 for dev in opt.dev.split(':') {
192 let dev = PathBuf::from(dev);
193 sbs.push(bch_bindgen::rs::read_super(&dev)?);
200 Err(anyhow::anyhow!("No device found from specified parameters"))?;
201 } else if unsafe { bcachefs::bch2_sb_is_encrypted(sbs[0].sb) } {
205 .ok_or_else(|| anyhow::anyhow!("no keyoption specified for locked filesystem"))?;
207 key::prepare_key(&sbs[0], key)?;
210 if let Some(mountpoint) = opt.mountpoint {
212 "mounting with params: device: {}, target: {}, options: {}",
214 mountpoint.to_string_lossy(),
218 mount(devs, mountpoint, &opt.options)?;
221 "would mount with params: device: {}, options: {}",
231 pub extern "C" fn cmd_mount(argc: c_int, argv: *const *const c_char) -> c_int {
232 let argv: Vec<_> = (0..argc)
233 .map(|i| unsafe { CStr::from_ptr(*argv.add(i as usize)) })
234 .map(|i| OsStr::from_bytes(i.to_bytes()))
237 let opt = Cli::parse_from(argv);
239 log::set_boxed_logger(Box::new(SimpleLogger)).unwrap();
241 // @TODO : more granular log levels via mount option
242 log::set_max_level(match opt.verbose {
243 0 => LevelFilter::Warn,
244 1 => LevelFilter::Trace,
245 2_u8..=u8::MAX => todo!(),
248 colored::control::set_override(opt.colorize);
249 if let Err(e) = cmd_mount_inner(opt) {
250 error!("Fatal error: {}", e);
253 info!("Successfully mounted");