netns-rs 0.2.0

A library to handle Linux network namespaces in Rust
Documentation
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Copyright 2022 Alibaba Cloud. All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//

use std::fs::File;
use std::os::unix::fs::MetadataExt;
use std::os::unix::io::AsRawFd;
use std::path::{Path, PathBuf};
use std::thread::{self, JoinHandle};

use nix::mount::{mount, umount2, MntFlags, MsFlags};
use nix::sched::{setns, unshare, CloneFlags};
use nix::unistd::gettid;

use crate::{Error, Result};

/// Defines a NetNs environment behavior.
pub trait Env {
    /// The persist directory of the NetNs environment.
    fn persist_dir(&self) -> PathBuf;

    /// Returns `true` if the given path is in this Env.
    fn contains<P: AsRef<Path>>(&self, p: P) -> bool {
        p.as_ref().starts_with(self.persist_dir())
    }

    /// Initialize the environment.
    fn init(&self) -> Result<()> {
        // Create the directory for mounting network namespaces.
        // This needs to be a shared mountpoint in case it is mounted in to
        // other namespaces (containers)
        let persist_dir = self.persist_dir();
        std::fs::create_dir_all(&persist_dir).map_err(Error::CreateNsDirError)?;

        // Remount the namespace directory shared. This will fail if it is not
        // already a mountpoint, so bind-mount it on to itself to "upgrade" it
        // to a mountpoint.
        let mut made_netns_persist_dir_mount: bool = false;
        while let Err(e) = mount(
            Some(""),
            &persist_dir,
            Some("none"),
            MsFlags::MS_SHARED | MsFlags::MS_REC,
            Some(""),
        ) {
            // Fail unless we need to make the mount point
            if e != nix::errno::Errno::EINVAL || made_netns_persist_dir_mount {
                return Err(Error::MountError(
                    format!("--make-rshared {}", persist_dir.display()),
                    e,
                ));
            }
            // Recursively remount /var/persist/netns on itself. The recursive flag is
            // so that any existing netns bindmounts are carried over.
            mount(
                Some(&persist_dir),
                &persist_dir,
                Some("none"),
                MsFlags::MS_BIND | MsFlags::MS_REC,
                Some(""),
            )
            .map_err(|e| {
                Error::MountError(
                    format!(
                        "-rbind {} to {}",
                        persist_dir.display(),
                        persist_dir.display()
                    ),
                    e,
                )
            })?;
            made_netns_persist_dir_mount = true;
        }

        Ok(())
    }
}

/// A default network namespace environment.
///
/// Its persistence directory is `/var/run/netns`, which is for consistency with the `ip-netns` tool.
/// See [ip-netns](https://man7.org/linux/man-pages/man8/ip-netns.8.html) for details.
#[derive(Copy, Clone, Default, Debug)]
pub struct DefaultEnv;

impl Env for DefaultEnv {
    fn persist_dir(&self) -> PathBuf {
        PathBuf::from("/var/run/netns")
    }
}

/// A network namespace type.
///
/// It could be used to enter network namespace.
#[derive(Debug)]
pub struct NetNs<E: Env = DefaultEnv> {
    file: File,
    path: PathBuf,
    env: Option<E>,
}

impl<E: Env> std::fmt::Display for NetNs<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if let Ok(meta) = self.file.metadata() {
            write!(
                f,
                "NetNS {{ fd: {}, dev: {}, ino: {}, path: {} }}",
                self.file.as_raw_fd(),
                meta.dev(),
                meta.ino(),
                self.path.display()
            )
        } else {
            write!(
                f,
                "NetNS {{ fd: {}, path: {} }}",
                self.file.as_raw_fd(),
                self.path.display()
            )
        }
    }
}

impl<E1: Env, E2: Env> PartialEq<NetNs<E1>> for NetNs<E2> {
    fn eq(&self, other: &NetNs<E1>) -> bool {
        if self.file.as_raw_fd() == other.file.as_raw_fd() {
            return true;
        }
        let cmp_meta = |f1: &File, f2: &File| -> Option<bool> {
            let m1 = match f1.metadata() {
                Ok(m) => m,
                Err(_) => return None,
            };
            let m2 = match f2.metadata() {
                Ok(m) => m,
                Err(_) => return None,
            };
            Some(m1.dev() == m2.dev() && m1.ino() == m2.ino())
        };
        cmp_meta(&self.file, &other.file).unwrap_or_else(|| self.path == other.path)
    }
}

impl<E: Env> NetNs<E> {
    /// Creates a new `NetNs` with the specified name and Env.
    ///
    /// The persist dir of network namespace will be created if it doesn't already exist.
    pub fn new_with_env<S: AsRef<str>>(ns_name: S, env: E) -> Result<Self> {
        env.init()?;

        // create an empty file at the mount point
        let ns_path = env.persist_dir().join(ns_name.as_ref());
        let _ = File::create(&ns_path).map_err(Error::CreateNsError)?;
        Self::persistent(&ns_path, true).inspect_err(|_e| {
            // Ensure the mount point is cleaned up on errors; if the namespace was successfully
            // mounted this will have no effect because the file is in-use
            std::fs::remove_file(&ns_path).ok();
        })?;
        Self::get_from_env(ns_name, env)
    }

    fn persistent<P: AsRef<Path>>(ns_path: &P, new_thread: bool) -> Result<()> {
        if new_thread {
            let ns_path_clone = ns_path.as_ref().to_path_buf();
            let new_thread: JoinHandle<Result<()>> =
                thread::spawn(move || Self::persistent(&ns_path_clone, false));
            match new_thread.join() {
                Ok(t) => t?,
                Err(e) => {
                    return Err(Error::JoinThreadError(format!("{:?}", e)));
                }
            };
        } else {
            // Create a new netns for the current thread.
            unshare(CloneFlags::CLONE_NEWNET).map_err(Error::UnshareError)?;
            // bind mount the netns from the current thread (from /proc) onto the mount point.
            // This persists the namespace, even when there are no threads in the ns.
            let src = get_current_thread_netns_path();
            mount(
                Some(src.as_path()),
                ns_path.as_ref(),
                Some("none"),
                MsFlags::MS_BIND,
                Some(""),
            )
            .map_err(|e| {
                Error::MountError(
                    format!("rbind {} to {}", src.display(), ns_path.as_ref().display()),
                    e,
                )
            })?;
        }

        Ok(())
    }

    /// Gets the path of this network namespace.
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Gets the Env of this network namespace.
    pub fn env(&self) -> Option<&E> {
        self.env.as_ref()
    }

    /// Gets the Env of this network namespace.
    pub fn file(&self) -> &File {
        &self.file
    }

    /// Makes the current thread enter this network namespace.
    ///
    /// Requires elevated privileges.
    pub fn enter(&self) -> Result<()> {
        setns(&self.file, CloneFlags::CLONE_NEWNET).map_err(Error::SetnsError)
    }

    /// Returns the NetNs with the specified name and Env.
    pub fn get_from_env<S: AsRef<str>>(ns_name: S, env: E) -> Result<Self> {
        let ns_path = env.persist_dir().join(ns_name.as_ref());
        let file = File::open(&ns_path).map_err(|e| Error::OpenNsError(ns_path.clone(), e))?;

        Ok(Self {
            file,
            path: ns_path,
            env: Some(env),
        })
    }

    /// Removes this network namespace manually.
    ///
    /// Once called, this instance will not be available.
    pub fn remove(self) -> Result<()> {
        // Close the file descriptor by dropping it.
        drop(self.file);
        // Only unmount if it's been bind-mounted (don't touch namespaces in /proc...)
        if let Some(env) = &self.env {
            if env.contains(&self.path) {
                Self::umount_ns(&self.path)?;
            }
        }
        Ok(())
    }

    fn umount_ns<P: AsRef<Path>>(path: P) -> Result<()> {
        let path = path.as_ref();
        umount2(path, MntFlags::MNT_DETACH).map_err(|e| Error::UnmountError(path.to_owned(), e))?;
        // Donot return error.
        std::fs::remove_file(path).ok();
        Ok(())
    }

    /// Run a closure in NetNs, which is specified by name and Env.
    ///
    /// Requires elevated privileges.
    pub fn run<F, T>(&self, f: F) -> Result<T>
    where
        F: FnOnce(&Self) -> T,
    {
        // get current network namespace
        let src_ns = get_from_current_thread()?;

        // do nothing if ns_path is same as current_ns
        if &src_ns == self {
            return Ok(f(self));
        }
        // enter new namespace
        self.enter()?;

        let result = f(self);
        // back to old namespace
        src_ns.enter()?;

        Ok(result)
    }
}

impl NetNs {
    /// Creates a new persistent (bind-mounted) network namespace and returns an object representing
    /// that namespace, without switching to it.
    ///
    /// The persist directory of network namespace will be created if it doesn't already exist.
    /// This function will use [`DefaultEnv`] to create persist directory.
    ///
    /// Requires elevated privileges.
    ///
    /// [`DefaultEnv`]: DefaultEnv
    ///
    pub fn new<S: AsRef<str>>(ns_name: S) -> Result<Self> {
        Self::new_with_env(ns_name, DefaultEnv)
    }

    /// Returns the NetNs with the specified name and `DefaultEnv`.
    pub fn get<S: AsRef<str>>(ns_name: S) -> Result<Self> {
        Self::get_from_env(ns_name, DefaultEnv)
    }

    /// Run a closure in NetNs, which is specified by name and `DefaultEnv`.
    ///
    /// Requires elevated privileges.
    pub fn run_in<S, F, T>(ns_name: S, f: F) -> Result<T>
    where
        S: AsRef<str>,
        F: FnOnce(&Self) -> T,
    {
        // get network namespace
        let run_ns = Self::get_from_env(ns_name, DefaultEnv)?;
        run_ns.run(f)
    }
}

/// Returns the NetNs with the spectified path.
pub fn get_from_path<P: AsRef<Path>>(ns_path: P) -> Result<NetNs> {
    let ns_path = ns_path.as_ref().to_path_buf();
    let file = File::open(&ns_path).map_err(|e| Error::OpenNsError(ns_path.clone(), e))?;

    Ok(NetNs {
        file,
        path: ns_path,
        env: None,
    })
}

/// Returns the NetNs of current thread.
pub fn get_from_current_thread() -> Result<NetNs> {
    let ns_path = get_current_thread_netns_path();
    let file = File::open(&ns_path).map_err(|e| Error::OpenNsError(ns_path.clone(), e))?;

    Ok(NetNs {
        file,
        path: ns_path,
        env: None,
    })
}

#[inline]
fn get_current_thread_netns_path() -> PathBuf {
    PathBuf::from(format!("/proc/self/task/{}/ns/net", gettid()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::mem::ManuallyDrop;
    use std::os::unix::io::FromRawFd;

    fn make_dummy_netns(fd: i32, path: &str) -> ManuallyDrop<NetNs<DefaultEnv>> {
        ManuallyDrop::new(NetNs {
            file: unsafe { File::from_raw_fd(fd) },
            path: PathBuf::from(path),
            env: None,
        })
    }

    #[test]
    fn test_netns_display() {
        let ns = get_from_current_thread().unwrap();
        let print = format!("{}", ns);
        assert!(print.contains("dev"));
        assert!(print.contains("ino"));

        let ns = make_dummy_netns(i32::MAX, "");
        let print = format!("{}", *ns);
        assert!(!print.contains("dev"));
        assert!(!print.contains("ino"));
    }

    #[test]
    fn test_netns_eq() {
        let ns1 = get_from_current_thread().unwrap();
        let ns2 = get_from_path("/proc/self/ns/net").unwrap();
        assert_eq!(ns1, ns2);

        let ns1 = make_dummy_netns(i32::MAX, "aaaaaa");
        let ns2 = make_dummy_netns(i32::MAX, "bbbbbb");
        assert_eq!(*ns1, *ns2);

        let ns2 = make_dummy_netns(i32::MAX - 1, "aaaaaa");
        assert_eq!(*ns1, *ns2);
    }

    #[test]
    fn test_netns_init() {
        let ns = NetNs::new("test_netns_init").unwrap();
        assert!(ns.path().exists());
        ns.remove().unwrap();
        assert!(!Path::new(&DefaultEnv.persist_dir())
            .join("test_netns_init")
            .exists());
    }

    struct TestNetNs {
        netns: Option<NetNs>,
        ns_name: String,
    }

    impl TestNetNs {
        fn new(name: &str) -> Self {
            let netns = NetNs::new(name).unwrap();
            assert!(netns.path().exists());
            Self {
                netns: Some(netns),
                ns_name: String::from(name),
            }
        }

        fn netns(&self) -> &NetNs {
            self.netns.as_ref().unwrap()
        }
    }

    impl Drop for TestNetNs {
        fn drop(&mut self) {
            let ns_name = self.ns_name.clone();
            self.netns.take().unwrap().remove().unwrap();
            assert!(!Path::new(&DefaultEnv.persist_dir()).join(ns_name).exists());
        }
    }

    #[test]
    fn test_netns_enter() {
        let new = TestNetNs::new("test_netns_enter");

        let src = get_from_current_thread().unwrap();
        assert_ne!(&src, new.netns());

        new.netns().enter().unwrap();

        let cur = get_from_current_thread().unwrap();

        assert_eq!(new.netns(), &cur);
        assert_ne!(src, cur);
        assert_ne!(&src, new.netns());
    }

    struct TestEnv;
    impl Env for TestEnv {
        fn persist_dir(&self) -> PathBuf {
            PathBuf::from("/tmp/test_netns")
        }
    }

    #[test]
    fn test_netns_with_env() {
        let ns_res = NetNs::get_from_env("test_netns_run", TestEnv);
        assert!(matches!(ns_res, Err(Error::OpenNsError(_, _))));

        let ns = NetNs::new_with_env("test_netns_run", TestEnv).unwrap();
        assert!(ns.path().exists());

        ns.remove().unwrap();
        assert!(!Path::new(&TestEnv.persist_dir())
            .join("test_netns_set")
            .exists());
    }

    #[test]
    fn test_netns_run() {
        let new = TestNetNs::new("test_netns_run");

        let src_ns = get_from_current_thread().unwrap();

        let ret = new
            .netns()
            .run(|cur_ns| -> Result<()> {
                let cur_thread = get_from_current_thread().unwrap();
                assert_eq!(cur_ns, &cur_thread);
                // captured variables
                assert_eq!(cur_ns, new.netns());
                assert_ne!(cur_ns, &src_ns);

                Ok(())
            })
            .unwrap();
        assert!(ret.is_ok());
    }
}