summaryrefslogtreecommitdiff
path: root/src/commands/mount.rs
blob: 235a1825f81ae526ff7b79e46c09d28377795200 (plain)
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
use std::{
    collections::HashMap,
    env,
    ffi::CString,
    fs,
    io::{stdout, IsTerminal},
    path::{Path, PathBuf},
    ptr, str,
};

use anyhow::{ensure, Result};
use bch_bindgen::{bcachefs, bcachefs::bch_sb_handle, opt_set, path_to_cstr};
use clap::Parser;
use log::{debug, info};
use uuid::Uuid;

use crate::{
    key::{KeyHandle, Passphrase, UnlockPolicy},
    logging,
};

fn mount_inner(
    src: String,
    target: impl AsRef<std::path::Path>,
    fstype: &str,
    mountflags: libc::c_ulong,
    data: Option<String>,
) -> anyhow::Result<()> {
    // bind the CStrings to keep them alive
    let src = CString::new(src)?;
    let target = path_to_cstr(target);
    let data = data.map(CString::new).transpose()?;
    let fstype = CString::new(fstype)?;

    // convert to pointers for ffi
    let src = src.as_ptr();
    let target = target.as_ptr();
    let data = data.map_or(ptr::null(), |data| data.as_ptr().cast());
    let fstype = fstype.as_ptr();

    let ret = {
        info!("mounting filesystem");
        // REQUIRES: CAP_SYS_ADMIN
        unsafe { libc::mount(src, target, fstype, mountflags, data) }
    };
    match ret {
        0 => Ok(()),
        _ => Err(crate::ErrnoError(errno::errno()).into()),
    }
}

/// Parse a comma-separated mount options and split out mountflags and filesystem
/// specific options.
fn parse_mount_options(options: impl AsRef<str>) -> (Option<String>, libc::c_ulong) {
    use either::Either::{Left, Right};

    debug!("parsing mount options: {}", options.as_ref());
    let (opts, flags) = options
        .as_ref()
        .split(',')
        .map(|o| match o {
            "dirsync" => Left(libc::MS_DIRSYNC),
            "lazytime" => Left(1 << 25), // MS_LAZYTIME
            "mand" => Left(libc::MS_MANDLOCK),
            "noatime" => Left(libc::MS_NOATIME),
            "nodev" => Left(libc::MS_NODEV),
            "nodiratime" => Left(libc::MS_NODIRATIME),
            "noexec" => Left(libc::MS_NOEXEC),
            "nosuid" => Left(libc::MS_NOSUID),
            "relatime" => Left(libc::MS_RELATIME),
            "remount" => Left(libc::MS_REMOUNT),
            "ro" => Left(libc::MS_RDONLY),
            "rw" | "" => Left(0),
            "strictatime" => Left(libc::MS_STRICTATIME),
            "sync" => Left(libc::MS_SYNCHRONOUS),
            o => Right(o),
        })
        .fold((Vec::new(), 0), |(mut opts, flags), next| match next {
            Left(f) => (opts, flags | f),
            Right(o) => {
                opts.push(o);
                (opts, flags)
            }
        });

    (
        if opts.is_empty() {
            None
        } else {
            Some(opts.join(","))
        },
        flags,
    )
}

fn read_super_silent(path: impl AsRef<Path>) -> anyhow::Result<bch_sb_handle> {
    let mut opts = bcachefs::bch_opts::default();
    opt_set!(opts, noexcl, 1);

    bch_bindgen::sb_io::read_super_silent(path.as_ref(), opts)
}

fn device_property_map(dev: &udev::Device) -> HashMap<String, String> {
    let rc: HashMap<_, _> = dev
        .properties()
        .map(|i| {
            (
                String::from(i.name().to_string_lossy()),
                String::from(i.value().to_string_lossy()),
            )
        })
        .collect();
    rc
}

fn udev_bcachefs_info() -> anyhow::Result<HashMap<String, Vec<String>>> {
    let mut info = HashMap::new();

    if env::var("BCACHEFS_BLOCK_SCAN").is_ok() {
        debug!("Checking all block devices for bcachefs super block!");
        return Ok(info);
    }

    let mut udev = udev::Enumerator::new()?;

    debug!("Walking udev db!");

    udev.match_subsystem("block")?;
    udev.match_property("ID_FS_TYPE", "bcachefs")?;

    for m in udev
        .scan_devices()?
        .filter(udev::Device::is_initialized)
        .map(|dev| device_property_map(&dev))
        .filter(|m| m.contains_key("ID_FS_UUID") && m.contains_key("DEVNAME"))
    {
        let fs_uuid = m["ID_FS_UUID"].clone();
        let dev_node = m["DEVNAME"].clone();
        info.insert(dev_node.clone(), vec![fs_uuid.clone()]);
        info.entry(fs_uuid).or_insert(vec![]).push(dev_node.clone());
    }

    Ok(info)
}

fn get_super_blocks(uuid: Uuid, devices: &[String]) -> Vec<(PathBuf, bch_sb_handle)> {
    devices
        .iter()
        .filter_map(|dev| {
            read_super_silent(PathBuf::from(dev))
                .ok()
                .map(|sb| (PathBuf::from(dev), sb))
        })
        .filter(|(_, sb)| sb.sb().uuid() == uuid)
        .collect::<Vec<_>>()
}

fn get_all_block_devnodes() -> anyhow::Result<Vec<String>> {
    let mut udev = udev::Enumerator::new()?;
    udev.match_subsystem("block")?;

    let devices = udev
        .scan_devices()?
        .filter_map(|dev| {
            if dev.is_initialized() {
                dev.devnode().map(|dn| dn.to_string_lossy().into_owned())
            } else {
                None
            }
        })
        .collect::<Vec<_>>();
    Ok(devices)
}

fn get_devices_by_uuid(
    udev_bcachefs: &HashMap<String, Vec<String>>,
    uuid: Uuid,
) -> anyhow::Result<Vec<(PathBuf, bch_sb_handle)>> {
    let devices = {
        if !udev_bcachefs.is_empty() {
            let uuid_string = uuid.hyphenated().to_string();
            if let Some(devices) = udev_bcachefs.get(&uuid_string) {
                devices.clone()
            } else {
                Vec::new()
            }
        } else {
            get_all_block_devnodes()?
        }
    };

    Ok(get_super_blocks(uuid, &devices))
}

#[allow(clippy::type_complexity)]
fn get_uuid_for_dev_node(
    udev_bcachefs: &HashMap<String, Vec<String>>,
    device: impl AsRef<Path>,
) -> Result<(Option<Uuid>, Option<(PathBuf, bch_sb_handle)>)> {
    let canonical = fs::canonicalize(device)?;

    if !udev_bcachefs.is_empty() {
        let dev_node_str = canonical.into_os_string().into_string().unwrap();

        if udev_bcachefs.contains_key(&dev_node_str) && udev_bcachefs[&dev_node_str].len() == 1 {
            let uuid_str = udev_bcachefs[&dev_node_str][0].clone();
            return Ok((Some(Uuid::parse_str(&uuid_str)?), None));
        }
    } else {
        return read_super_silent(&canonical).map_or(Ok((None, None)), |sb| {
            Ok((Some(sb.sb().uuid()), Some((canonical, sb))))
        });
    }
    Ok((None, None))
}

/// Mount a bcachefs filesystem by its UUID.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
    /// Path to passphrase file
    ///
    /// This can be used to optionally specify a file to read the passphrase
    /// from. An explictly specified key_location/unlock_policy overrides this
    /// argument.
    #[arg(short = 'f', long)]
    passphrase_file: Option<PathBuf>,

    /// Passphrase policy to use in case of an encrypted filesystem. If not
    /// specified, the password will be searched for in the keyring. If not
    /// found, the password will be prompted or read from stdin, depending on
    /// whether the stdin is connected to a terminal or not.
    #[arg(short = 'k', long = "key_location", value_enum)]
    unlock_policy: Option<UnlockPolicy>,

    /// Device, or UUID=\<UUID\>
    dev: String,

    /// Where the filesystem should be mounted. If not set, then the filesystem
    /// won't actually be mounted. But all steps preceeding mounting the
    /// filesystem (e.g. asking for passphrase) will still be performed.
    mountpoint: Option<PathBuf>,

    /// Mount options
    #[arg(short, default_value = "")]
    options: String,

    // FIXME: would be nicer to have `--color[=WHEN]` like diff or ls?
    /// Force color on/off. Autodetect tty is used to define default:
    #[arg(short, long, action = clap::ArgAction::Set, default_value_t=stdout().is_terminal())]
    colorize: bool,

    /// Quiet mode
    #[arg(short, long)]
    quiet: bool,

    /// Verbose mode
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
}

fn devs_str_sbs_from_uuid(
    udev_info: &HashMap<String, Vec<String>>,
    uuid: &str,
) -> anyhow::Result<(String, Vec<bch_sb_handle>)> {
    debug!("enumerating devices with UUID {}", uuid);

    let devs_sbs = Uuid::parse_str(uuid).map(|uuid| get_devices_by_uuid(udev_info, uuid))??;

    let devs_str = devs_sbs
        .iter()
        .map(|(dev, _)| dev.to_str().unwrap())
        .collect::<Vec<_>>()
        .join(":");

    let sbs: Vec<bch_sb_handle> = devs_sbs.iter().map(|(_, sb)| *sb).collect();

    Ok((devs_str, sbs))
}

fn devs_str_sbs_from_device(
    udev_info: &HashMap<String, Vec<String>>,
    device: impl AsRef<Path>,
) -> anyhow::Result<(String, Vec<bch_sb_handle>)> {
    let (uuid, sb_info) = get_uuid_for_dev_node(udev_info, device)?;

    match (uuid, sb_info) {
        (Some(uuid), Some((path, sb))) => {
            // If we have a super block, it implies we aren't using udev db.  If we only need
            // 1 device to mount, we'll simply return it as we're done, else we'll use the uuid
            // to walk through all the block devices.
            debug!(
                "number of devices in this FS = {}",
                sb.sb().number_of_devices()
            );
            if sb.sb().number_of_devices() == 1 {
                let dev = path.into_os_string().into_string().unwrap();
                Ok((dev, vec![sb]))
            } else {
                devs_str_sbs_from_uuid(udev_info, &uuid.to_string())
            }
        }
        (Some(uuid), None) => devs_str_sbs_from_uuid(udev_info, &uuid.to_string()),
        _ => Ok((String::new(), Vec::new())),
    }
}

/// If a user explicitly specifies `unlock_policy` or `passphrase_file` then use
/// that without falling back to other mechanisms. If these options are not
/// used, then search for the key or ask for it.
fn handle_unlock(cli: &Cli, sb: &bch_sb_handle) -> Result<KeyHandle> {
    if let Some(policy) = cli.unlock_policy.as_ref() {
        return policy.apply(sb);
    }

    if let Some(path) = cli.passphrase_file.as_deref() {
        return Passphrase::new_from_file(path).and_then(|p| KeyHandle::new(sb, &p));
    }

    KeyHandle::new_from_search(&sb.sb().uuid())
        .or_else(|_| Passphrase::new().and_then(|p| KeyHandle::new(sb, &p)))
}

fn cmd_mount_inner(cli: &Cli) -> Result<()> {
    // Grab the udev information once
    let udev_info = udev_bcachefs_info()?;

    let (devices, sbs) = if let Some(("UUID" | "OLD_BLKID_UUID", uuid)) = cli.dev.split_once('=') {
        devs_str_sbs_from_uuid(&udev_info, uuid)?
    } else if cli.dev.contains(':') {
        // If the device string contains ":" we will assume the user knows the
        // entire list. If they supply a single device it could be either the FS
        // only has 1 device or it's only 1 of a number of devices which are
        // part of the FS. This appears to be the case when we get called during
        // fstab mount processing and the fstab specifies a UUID.

        let sbs = cli
            .dev
            .split(':')
            .map(read_super_silent)
            .collect::<Result<Vec<_>>>()?;

        (cli.dev.clone(), sbs)
    } else {
        devs_str_sbs_from_device(&udev_info, Path::new(&cli.dev))?
    };

    ensure!(!sbs.is_empty(), "No device(s) to mount specified");

    let first_sb = sbs[0];
    if unsafe { bcachefs::bch2_sb_is_encrypted(first_sb.sb) } {
        handle_unlock(cli, &first_sb)?;
    }

    if let Some(mountpoint) = cli.mountpoint.as_deref() {
        info!(
            "mounting with params: device: {}, target: {}, options: {}",
            devices,
            mountpoint.to_string_lossy(),
            &cli.options
        );

        let (data, mountflags) = parse_mount_options(&cli.options);
        mount_inner(devices, mountpoint, "bcachefs", mountflags, data)
    } else {
        info!(
            "would mount with params: device: {}, options: {}",
            devices, &cli.options
        );

        Ok(())
    }
}

pub fn mount(mut argv: Vec<String>, symlink_cmd: Option<&str>) -> Result<()> {
    // If the bcachefs tool is being called as "bcachefs mount dev ..." (as opposed to via a
    // symlink like "/usr/sbin/mount.bcachefs dev ...", then we need to pop the 0th argument
    // ("bcachefs") since the CLI parser here expects the device at position 1.
    if symlink_cmd.is_none() {
        argv.remove(0);
    }

    let cli = Cli::parse_from(argv);

    // TODO: centralize this on the top level CLI
    logging::setup(cli.quiet, cli.verbose, cli.colorize);

    cmd_mount_inner(&cli)
}