blob: 431deafe7c675a35f7720a7c0a8e3dac95c870ef [file] [log] [blame]
Garrick Evanscf036f32018-12-21 12:56:59 +09001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
Garrick Evans3388a032020-03-24 11:25:55 +09005#include "patchpanel/scoped_ns.h"
Garrick Evanscf036f32018-12-21 12:56:59 +09006
7#include <fcntl.h>
8#include <sched.h>
Hugo Benichi0781d402021-02-22 13:43:11 +09009#include <sys/types.h>
10#include <sys/stat.h>
Garrick Evanscf036f32018-12-21 12:56:59 +090011
12#include <string>
13
Garrick Evans3388a032020-03-24 11:25:55 +090014namespace patchpanel {
Garrick Evanscf036f32018-12-21 12:56:59 +090015
Hugo Benichi0781d402021-02-22 13:43:11 +090016ScopedNS::ScopedNS(pid_t pid, Type type) : valid_(false) {
17 std::string current_ns_path;
18 std::string target_ns_path;
19 switch (type) {
20 case Mount:
21 nstype_ = CLONE_NEWNS;
22 current_ns_path = "/proc/self/ns/mnt";
23 target_ns_path = "/proc/" + std::to_string(pid) + "/ns/mnt";
24 break;
25 case Network:
26 nstype_ = CLONE_NEWNET;
27 current_ns_path = "/proc/self/ns/net";
28 target_ns_path = "/proc/" + std::to_string(pid) + "/ns/net";
29 break;
30 default:
31 LOG(ERROR) << "Unsupported namespace type " << type;
32 return;
33 }
34
35 ns_fd_.reset(open(target_ns_path.c_str(), O_RDONLY | O_CLOEXEC));
Garrick Evanscf036f32018-12-21 12:56:59 +090036 if (!ns_fd_.is_valid()) {
Hugo Benichi0781d402021-02-22 13:43:11 +090037 PLOG(ERROR) << "Could not open namespace " << target_ns_path;
Garrick Evanscf036f32018-12-21 12:56:59 +090038 return;
39 }
Hugo Benichi0781d402021-02-22 13:43:11 +090040 self_fd_.reset(open(current_ns_path.c_str(), O_RDONLY | O_CLOEXEC));
Garrick Evanscf036f32018-12-21 12:56:59 +090041 if (!self_fd_.is_valid()) {
Hugo Benichi0781d402021-02-22 13:43:11 +090042 PLOG(ERROR) << "Could not open host namespace " << current_ns_path;
Garrick Evanscf036f32018-12-21 12:56:59 +090043 return;
44 }
Hugo Benichi0781d402021-02-22 13:43:11 +090045 if (setns(ns_fd_.get(), nstype_) != 0) {
46 PLOG(ERROR) << "Could not enter namespace " << target_ns_path;
Garrick Evanscf036f32018-12-21 12:56:59 +090047 return;
48 }
49 valid_ = true;
50}
51
52ScopedNS::~ScopedNS() {
53 if (valid_) {
Hugo Benichi0781d402021-02-22 13:43:11 +090054 if (setns(self_fd_.get(), nstype_) != 0)
55 PLOG(FATAL) << "Could not re-enter host namespace type " << nstype_;
Garrick Evanscf036f32018-12-21 12:56:59 +090056 }
57}
58
Garrick Evans3388a032020-03-24 11:25:55 +090059} // namespace patchpanel