Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 1 | // 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 Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 5 | #include "patchpanel/scoped_ns.h" |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 6 | |
| 7 | #include <fcntl.h> |
| 8 | #include <sched.h> |
| 9 | |
| 10 | #include <string> |
| 11 | |
| 12 | #include <base/strings/stringprintf.h> |
| 13 | |
Garrick Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 14 | namespace patchpanel { |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 15 | |
| 16 | ScopedNS::ScopedNS(pid_t pid) : valid_(false) { |
| 17 | const std::string filename = |
| 18 | base::StringPrintf("/proc/%d/ns/net", static_cast<int>(pid)); |
| 19 | ns_fd_.reset(open(filename.c_str(), O_RDONLY)); |
| 20 | if (!ns_fd_.is_valid()) { |
| 21 | PLOG(ERROR) << "Could not open " << filename; |
| 22 | return; |
| 23 | } |
| 24 | self_fd_.reset(open("/proc/self/ns/net", O_RDONLY)); |
| 25 | if (!self_fd_.is_valid()) { |
| 26 | PLOG(ERROR) << "Could not open host netns"; |
| 27 | return; |
| 28 | } |
| 29 | if (setns(ns_fd_.get(), CLONE_NEWNET) != 0) { |
| 30 | PLOG(ERROR) << "Could not enter netns for " << pid; |
| 31 | return; |
| 32 | } |
| 33 | valid_ = true; |
| 34 | } |
| 35 | |
| 36 | ScopedNS::~ScopedNS() { |
| 37 | if (valid_) { |
| 38 | if (setns(self_fd_.get(), CLONE_NEWNET) != 0) |
| 39 | PLOG(FATAL) << "Could not enter host ns"; |
| 40 | } |
| 41 | } |
| 42 | |
Garrick Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 43 | } // namespace patchpanel |