Debian Codegraph @

src/bind.rs

raw symbols SCIP
1 use std::fmt;
2 use std::ffi::{CStr, CString, OsStr};
3 use std::os::unix::ffi::OsStrExt;
4 use std::path::Path;
5
6 use nix::mount::{MsFlags, mount};
7
8 use {OSError, Error};
9 use util::{path_to_cstring, as_path};
10 use explain::{Explainable, exists, user};
11 use remount::Remount;
12
13
14 /// A mount bind definition
15 ///
16 /// By default bind mount is recursive (it's what you want most of the time).
17 ///
18 /// Also recursive mounts can be used in user namespaces.
19 #[derive(Debug, Clone)]
20 pub struct BindMount {
21 source: CString,
22 target: CString,
23 recursive: bool,
24 readonly: bool,
25 }
26
27 impl BindMount {
28 /// Create a new, recursive bind mount
29 ///
30 /// You can disable recursion with a `non_recursive()` method
31 pub fn new<A: AsRef<Path>, B: AsRef<Path>>(source: A, target: B)
32 -> BindMount
33 {
34 BindMount {
35 source: path_to_cstring(source.as_ref()),
36 target: path_to_cstring(target.as_ref()),
37 recursive: true,
38 readonly: false,
39 }
40 }
41 /// Toggle recursion
42 pub fn recursive(mut self, flag: bool) -> BindMount {
43 self.recursive = flag;
44 self
45 }
46 /// If set to `true` makes bind-mount readonly
47 ///
48 /// Few notes:
49 ///
50 /// 1. This makes additional `mount` call (`Remount().readonly()`)
51 /// 2. If remount fails mount bind is left on the filesystem, no cleanup
52 /// is done
53 /// 3. If set to `false` is option is no-op (does **not** remount `rw`)
54 pub fn readonly(mut self, flag: bool) -> BindMount {
55 self.readonly = flag;
56 self
57 }
58
59 /// Execute a bind mount
60 pub fn bare_mount(self) -> Result<(), OSError> {
61 let mut flags = MsFlags::MS_BIND;
62 if self.recursive {
63 flags = flags | MsFlags::MS_REC;
64 }
65 if let Err(err) = mount(
66 Some(&*self.source),
67 &*self.target,
68 None::<&CStr>,
69 flags,
70 None::<&CStr>,
71 ) {
72 return Err(OSError::from_nix(err, Box::new(self)));
73 }
74 if self.readonly {
75 try!(Remount::new(OsStr::from_bytes(self.target.as_bytes()))
76 .bind(true)
77 .readonly(true)
78 .bare_remount());
79 }
80 Ok(())
81 }
82
83 /// Execute a bind mount and explain the error immediately
84 pub fn mount(self) -> Result<(), Error> {
85 self.bare_mount().map_err(OSError::explain)
86 }
87 }
88
89 impl fmt::Display for BindMount {
90 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
91 if self.recursive {
92 try!(write!(fmt, "recursive "));
93 }
94 write!(fmt, "bind mount {:?} -> {:?}",
95 as_path(&self.source), as_path(&self.target))
96 }
97 }
98
99 impl Explainable for BindMount {
100 fn explain(&self) -> String {
101 [
102 format!("source: {}", exists(as_path(&self.source))),
103 format!("target: {}", exists(as_path(&self.target))),
104 format!("{}", user()),
105 ].join(", ")
106 }
107 }
108