]> git.sesse.net Git - bcachefs-tools-debian/blob - rust-src/src/cmd_mount.rs
chore: logger for idiomatic style and expanded logging levels
[bcachefs-tools-debian] / rust-src / src / cmd_mount.rs
1 use atty::Stream;
2 use bch_bindgen::{bcachefs, bcachefs::bch_sb_handle};
3 use log::{info, warn, debug, error, trace, LevelFilter};
4 use clap::Parser;
5 use uuid::Uuid;
6 use std::convert::TryInto;
7 use std::path::PathBuf;
8 use crate::key;
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;
13
14 fn mount_inner(
15     src: String,
16     target: impl AsRef<std::path::Path>,
17     fstype: &str,
18     mountflags: u64,
19     data: Option<String>,
20 ) -> anyhow::Result<()> {
21
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)?;
27
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
33     });
34     let fstype = fstype.as_c_str().to_bytes_with_nul().as_ptr() as *const c_char;
35
36     let ret = {
37         info!("mounting filesystem");
38         // REQUIRES: CAP_SYS_ADMIN
39         unsafe { libc::mount(src, target, fstype, mountflags, data) }
40     };
41     match ret {
42         0 => Ok(()),
43         _ => Err(crate::ErrnoError(errno::errno()).into()),
44     }
45 }
46
47 /// Parse a comma-separated mount options and split out mountflags and filesystem
48 /// specific options.
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
53         .as_ref()
54         .split(",")
55         .map(|o| match o {
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),
67             "rw"            => Left(0),
68             "strictatime"   => Left(libc::MS_STRICTATIME),
69             "sync"          => Left(libc::MS_SYNCHRONOUS),
70             ""              => Left(0),
71             o @ _           => Right(o),
72         })
73         .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
74             Left(f) => (opts, flags | f),
75             Right(o) => {
76                 opts.push(o);
77                 (opts, flags)
78             }
79         });
80
81     use itertools::Itertools;
82     (
83         if opts.len() == 0 {
84             None
85         } else {
86             Some(opts.iter().join(","))
87         },
88         flags,
89     )
90 }
91
92 fn mount(
93     device: String,
94     target: impl AsRef<std::path::Path>,
95     options: impl AsRef<str>,
96 ) -> anyhow::Result<()> {
97     let (data, mountflags) = parse_mount_options(options);
98
99     info!(
100         "mounting bcachefs filesystem, {}",
101         target.as_ref().display()
102     );
103     mount_inner(device, target, "bcachefs", mountflags, data)
104 }
105
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();
109
110     bch_bindgen::rs::read_super(&path)
111 }
112
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()?;
116
117     udev.match_subsystem("block")?;
118
119     let devs = udev
120         .scan_devices()?
121         .into_iter()
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)
126         .collect();
127     Ok(devs)
128 }
129
130 /// Mount a bcachefs filesystem by its UUID.
131 #[derive(Parser, Debug)]
132 #[command(author, version, about, long_about = None)]
133 struct Cli {
134     /// Where the password would be loaded from.
135     ///
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,
142
143     /// Device, or UUID=<UUID>
144     dev:            String,
145
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,
150
151     /// Mount options
152     #[arg(short, default_value = "")]
153     options:        String,
154
155     /// Force color on/off. Default: autodetect tty
156     #[arg(short, long, action = clap::ArgAction::Set, default_value_t=atty::is(Stream::Stdout))]
157     colorize:       bool,
158
159     /// Verbose mode
160     #[arg(short, long, action = clap::ArgAction::Count)]
161     verbose:        u8,
162 }
163
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)?;
169
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();
173
174         (devs_str, sbs)
175     } else {
176         let mut sbs = Vec::new();
177
178         for dev in opt.dev.split(':') {
179             let dev = PathBuf::from(dev);
180             sbs.push(bch_bindgen::rs::read_super(&dev)?);
181         }
182
183         (opt.dev, sbs)
184     };
185
186     if unsafe { bcachefs::bch2_sb_is_encrypted(sbs[0].sb) } {
187         let key = opt
188             .key_location
189             .0
190             .ok_or_else(|| anyhow::anyhow!("no keyoption specified for locked filesystem"))?;
191
192         key::prepare_key(&sbs[0], key)?;
193     }
194
195     mount(devs, &opt.mountpoint, &opt.options)?;
196     Ok(())
197 }
198
199 #[no_mangle]
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()))
204         .collect();
205
206     let opt = Cli::parse_from(argv);
207     
208     log::set_boxed_logger(Box::new(SimpleLogger)).unwrap();
209
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!(),
215     });
216
217     colored::control::set_override(opt.colorize);
218     if let Err(e) = cmd_mount_inner(opt) {
219         error!("Fatal error: {}", e);
220     } else {
221         info!("Successfully mounted");
222     }
223 }