xref: /aosp_15_r20/external/libbrillo/brillo/scoped_mount_namespace.h (revision 1a96fba65179ea7d3f56207137718607415c5953)
1*1a96fba6SXin Li // Copyright 2019 The Chromium OS Authors. All rights reserved.
2*1a96fba6SXin Li // Use of this source code is governed by a BSD-style license that can be
3*1a96fba6SXin Li // found in the LICENSE file.
4*1a96fba6SXin Li 
5*1a96fba6SXin Li #ifndef LIBBRILLO_BRILLO_SCOPED_MOUNT_NAMESPACE_H_
6*1a96fba6SXin Li #define LIBBRILLO_BRILLO_SCOPED_MOUNT_NAMESPACE_H_
7*1a96fba6SXin Li 
8*1a96fba6SXin Li #include <memory>
9*1a96fba6SXin Li 
10*1a96fba6SXin Li #include <base/macros.h>
11*1a96fba6SXin Li #include <base/files/file_path.h>
12*1a96fba6SXin Li #include <base/files/scoped_file.h>
13*1a96fba6SXin Li 
14*1a96fba6SXin Li #include <brillo/brillo_export.h>
15*1a96fba6SXin Li 
16*1a96fba6SXin Li namespace brillo {
17*1a96fba6SXin Li 
18*1a96fba6SXin Li // A class that restores a mount namespace when it goes out of scope. This can
19*1a96fba6SXin Li // be done by entering another process' mount namespace by using
20*1a96fba6SXin Li // CreateForPid(), or by supplying a mount namespace FD directly.
21*1a96fba6SXin Li class BRILLO_EXPORT ScopedMountNamespace {
22*1a96fba6SXin Li  public:
23*1a96fba6SXin Li   // Enters the process identified by |pid|'s mount namespace and returns a
24*1a96fba6SXin Li   // unique_ptr that restores the original mount namespace when it goes out of
25*1a96fba6SXin Li   // scope.
26*1a96fba6SXin Li   static std::unique_ptr<ScopedMountNamespace> CreateForPid(pid_t pid);
27*1a96fba6SXin Li 
28*1a96fba6SXin Li   // Enters the mount namespace identified by |path| and returns a unique_ptr
29*1a96fba6SXin Li   // that restores the original mount namespace when it goes out of scope.
30*1a96fba6SXin Li   static std::unique_ptr<ScopedMountNamespace> CreateFromPath(
31*1a96fba6SXin Li       const base::FilePath& ns_path);
32*1a96fba6SXin Li 
33*1a96fba6SXin Li   explicit ScopedMountNamespace(base::ScopedFD mount_namespace_fd);
34*1a96fba6SXin Li   ~ScopedMountNamespace();
35*1a96fba6SXin Li 
36*1a96fba6SXin Li  private:
37*1a96fba6SXin Li   base::ScopedFD mount_namespace_fd_;
38*1a96fba6SXin Li 
39*1a96fba6SXin Li   DISALLOW_COPY_AND_ASSIGN(ScopedMountNamespace);
40*1a96fba6SXin Li };
41*1a96fba6SXin Li 
42*1a96fba6SXin Li }  // namespace brillo
43*1a96fba6SXin Li 
44*1a96fba6SXin Li #endif  // LIBBRILLO_BRILLO_SCOPED_MOUNT_NAMESPACE_H_
45