blob: 3fae72c71b976de4a756ee445ebb38211fa5e1ef [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>
9
10#include <string>
11
12#include <base/strings/stringprintf.h>
13
Garrick Evans3388a032020-03-24 11:25:55 +090014namespace patchpanel {
Garrick Evanscf036f32018-12-21 12:56:59 +090015
16ScopedNS::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
36ScopedNS::~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 Evans3388a032020-03-24 11:25:55 +090043} // namespace patchpanel