• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <fcntl.h>
19 #include <sched.h>
20 #include <sys/stat.h>
21 #include <string>
22 
23 #include "ns_guard.h"
24 
25 // TODO: Remove this when CentOS 6 support is not needed anymore
26 #include "setns.h"
27 
ProcMountNS(int pid)28 ProcMountNS::ProcMountNS(int pid) : target_ino_(0) {
29   if (pid < 0)
30     return;
31 
32   std::string target_path = "/proc/" + std::to_string(pid) + "/ns/mnt";
33   ebpf::FileDesc target_fd(open(target_path.c_str(), O_RDONLY));
34   ebpf::FileDesc self_fd(open("/proc/self/ns/mnt", O_RDONLY));
35 
36   if (self_fd < 0 || target_fd < 0)
37     return;
38 
39   struct stat self_stat, target_stat;
40   if (fstat(self_fd, &self_stat) != 0)
41     return;
42   if (fstat(target_fd, &target_stat) != 0)
43     return;
44 
45   target_ino_ = target_stat.st_ino;
46   if (self_stat.st_ino == target_stat.st_ino)
47     // Both current and target Process are in same mount namespace
48     return;
49 
50   self_fd_ = std::move(self_fd);
51   target_fd_ = std::move(target_fd);
52 }
53 
ProcMountNSGuard(ProcMountNS * mount_ns)54 ProcMountNSGuard::ProcMountNSGuard(ProcMountNS *mount_ns)
55     : mount_ns_instance_(nullptr), mount_ns_(mount_ns), entered_(false) {
56   init();
57 }
58 
ProcMountNSGuard(int pid)59 ProcMountNSGuard::ProcMountNSGuard(int pid)
60     : mount_ns_instance_(pid > 0 ? new ProcMountNS(pid) : nullptr),
61       mount_ns_(mount_ns_instance_.get()),
62       entered_(false) {
63   init();
64 }
65 
init()66 void ProcMountNSGuard::init() {
67   if (!mount_ns_ || mount_ns_->self() < 0 || mount_ns_->target() < 0)
68     return;
69 
70   if (setns(mount_ns_->target(), CLONE_NEWNS) == 0)
71     entered_ = true;
72 }
73 
~ProcMountNSGuard()74 ProcMountNSGuard::~ProcMountNSGuard() {
75   if (mount_ns_ && entered_ && mount_ns_->self() >= 0)
76     setns(mount_ns_->self(), CLONE_NEWNS);
77 }
78