1 /*
2  * Copyright (c) 2017 Facebook, Inc.
3  * Copyright (c) 2017 VMware, Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include <memory>
21 #include <sys/types.h>
22 
23 #include "file_desc.h"
24 
25 class ProcMountNSGuard;
26 
27 // ProcMountNS opens an fd corresponding to the current mount namespace and the
28 // mount namespace of the target process.
29 // The fds will remain uninitialized (<0) if the open fails, or if the current
30 // and target namespaces are identical.
31 class ProcMountNS {
32  public:
33   explicit ProcMountNS(int pid);
self()34   int self() const { return self_fd_; }
target()35   int target() const { return target_fd_; }
target_ino()36   ino_t target_ino() const { return target_ino_; }
37 
38  private:
39   ebpf::FileDesc self_fd_;
40   ebpf::FileDesc target_fd_;
41   ino_t target_ino_;
42 };
43 
44 // ProcMountNSGuard switches to the target mount namespace and restores the
45 // original upon going out of scope.
46 class ProcMountNSGuard {
47  public:
48   explicit ProcMountNSGuard(ProcMountNS *mount_ns);
49   explicit ProcMountNSGuard(int pid);
50 
51   ~ProcMountNSGuard();
52 
53  private:
54   void init();
55 
56   std::unique_ptr<ProcMountNS> mount_ns_instance_;
57   ProcMountNS *mount_ns_;
58   bool entered_;
59 };
60