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
#[allow(dead_code)]
enum Priv {
    Bind {
        src: String,
        rw: bool,
        ignore_nonexist: bool,
        recursive: bool,
    },
    Tmpfs {
        rw: bool,
        opts: Vec<String>,
    },
    Normal {
        src: String,
        rw: bool,
        ignore_nonexist: bool,
        opts: Vec<String>,
    },
}

/// The description of a mount.
pub struct Mount(Priv);

impl Mount {
    /// Create a new bind mount.
    ///
    /// Read `BindPaths` and `BindReadOnlyPaths` in
    /// [systemd.exec(5)](man:systemd.exec(5)) for details.
    ///
    /// This setting is not available if the feature `systemd_233` is
    /// disabled.
    #[cfg(feature = "systemd_233")]
    pub fn bind<T: AsRef<str>>(src: T) -> Self {
        Self(Priv::Bind {
            src: src.as_ref().to_owned(),
            rw: false,
            recursive: false,
            ignore_nonexist: false,
        })
    }

    /// Create a tmpfs mount.
    ///
    /// Read `TemporaryFileSystem` in [systemd.exec(5)](man:systemd.exec(5))
    /// for details.
    ///
    /// This setting is not available if the feature `systemd_238` is
    /// disabled.
    #[cfg(feature = "systemd_238")]
    pub fn tmpfs() -> Self {
        Self(Priv::Tmpfs {
            rw: false,
            opts: vec![],
        })
    }

    /// Create a normal mount.
    ///
    /// Read `MountImages` in [systemd.exec(5)](man:systemd.exec(5)) for
    /// details.
    ///
    /// This setting is not available if the feature `systemd_247` is
    /// disabled.
    #[cfg(feature = "systemd_247")]
    pub fn normal<T: AsRef<str>>(src: T) -> Self {
        Self(Priv::Normal {
            src: src.as_ref().to_owned(),
            rw: false,
            ignore_nonexist: false,
            opts: vec![],
        })
    }

    /// Make the [Mount] writable.
    pub fn writable(self) -> Self {
        match self {
            Self(Priv::Bind {
                src,
                recursive,
                ignore_nonexist,
                ..
            }) => Self(Priv::Bind {
                src,
                recursive,
                ignore_nonexist,
                rw: true,
            }),
            Self(Priv::Tmpfs { opts, .. }) => Self(Priv::Tmpfs { opts, rw: true }),
            Self(Priv::Normal {
                opts,
                src,
                ignore_nonexist,
                ..
            }) => Self(Priv::Normal {
                opts,
                src,
                ignore_nonexist,
                rw: true,
            }),
        }
    }

    /// Make the [Mount] recursive.  It only makes a difference for a bind
    /// mount.
    pub fn recursive(self) -> Self {
        match self {
            Self(Priv::Bind { src, rw, .. }) => Self(Priv::Bind {
                src,
                rw,
                recursive: true,
                ignore_nonexist: true,
            }),
            _ => self,
        }
    }

    /// Append a mount option.  If the option contains a comma (`,`), or
    /// it is `ro`, `rw`, or empty, or it's applied for a bind mount,
    /// [None] will be returned.  But the option will not be validated
    /// further.
    ///
    /// For `rw`, use [Self::writable] instead.
    pub fn opt<T: AsRef<str>>(self, option: T) -> Option<Self> {
        let o = option.as_ref();
        if o.contains(',') {
            return None;
        }
        match o {
            "" | "ro" | "rw" => return None,
            _ => {}
        }
        match self {
            Self(Priv::Bind { .. }) => None,
            Self(Priv::Tmpfs { rw, mut opts }) => {
                opts.push(o.to_owned());
                Some(Self(Priv::Tmpfs { rw, opts }))
            }
            Self(Priv::Normal {
                src,
                rw,
                mut opts,
                ignore_nonexist,
            }) => {
                opts.push(o.to_owned());
                Some(Self(Priv::Normal {
                    src,
                    rw,
                    opts,
                    ignore_nonexist,
                }))
            }
        }
    }

    /// Ignore the mount if the source does not exist.  This does not make
    /// any difference for tmpfs mounts.
    pub fn ignore_nonexist(self) -> Self {
        match self {
            Self(Priv::Tmpfs { .. }) => self,
            Self(Priv::Normal { src, rw, opts, .. }) => Self(Priv::Normal {
                src,
                rw,
                opts,
                ignore_nonexist: true,
            }),
            Self(Priv::Bind {
                src, rw, recursive, ..
            }) => Self(Priv::Bind {
                src,
                rw,
                recursive,
                ignore_nonexist: true,
            }),
        }
    }
}

fn escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace(':', "\\:")
        .replace(' ', "\\ ")
}

pub enum MarshaledMount {
    /// src, dest, ignore_nonexist, flags (MS_REC or 0)
    Bind(String, String, bool, u64),
    /// src, dest, ignore_nonexist, flags (MS_REC or 0)
    BindReadOnly(String, String, bool, u64),
    /// src, dest, ignore_nonexist, `[(GPT label, flags)]`
    /// Currently only `root` used as `GPT label`
    Normal(String, String, bool, Vec<(&'static str, String)>),
    /// dest, flags (joined with comma)
    Tmpfs(String, String),
}

pub fn marshal<T: AsRef<str>>(mount_point: T, mount: Mount) -> MarshaledMount {
    use MarshaledMount::*;
    let mp = escape(mount_point.as_ref());

    match mount {
        Mount(Priv::Bind {
            src,
            rw,
            ignore_nonexist,
            recursive,
        }) => {
            let src = escape(&src);
            let flags: u64 = match recursive {
                true => 16384, // MS_REC
                false => 0,
            };
            match rw {
                true => Bind(src, mp, ignore_nonexist, flags),
                false => BindReadOnly(src, mp, ignore_nonexist, flags),
            }
        }
        Mount(Priv::Normal {
            src,
            rw,
            ignore_nonexist,
            mut opts,
        }) => {
            let src = escape(&src);
            if !rw {
                opts.push("ro".into());
            }
            let opts = opts.into_iter().map(|x| ("root", x)).collect();
            Normal(src, mp, ignore_nonexist, opts)
        }
        Mount(Priv::Tmpfs { rw, mut opts }) => {
            if !rw {
                opts.push("ro".into());
            }
            Tmpfs(mp, opts.join(","))
        }
    }
}