blob: ab251802096ccdcdf885f4d2a308addbe39899db [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#ifndef PATCHPANEL_SCOPED_NS_H_
6#define PATCHPANEL_SCOPED_NS_H_
Garrick Evanscf036f32018-12-21 12:56:59 +09007
Jie Jiangf6799312021-05-14 16:27:03 +09008#include <memory>
9#include <string>
10
Garrick Evanscf036f32018-12-21 12:56:59 +090011#include <base/files/scoped_file.h>
12#include <base/macros.h>
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 +090016// Utility class for running code blocks within a network namespace or a mount
17// namespace.
Garrick Evanscf036f32018-12-21 12:56:59 +090018class ScopedNS {
19 public:
Jie Jiangf6799312021-05-14 16:27:03 +090020 // Records the current mount (network) namespace and enters another namespace
21 // identified by the input argument. Will go back to the current namespace if
22 // the returned object goes out of scope. Returns nullptr on failure.
23 static std::unique_ptr<ScopedNS> EnterMountNS(pid_t pid);
24 static std::unique_ptr<ScopedNS> EnterNetworkNS(pid_t pid);
25 static std::unique_ptr<ScopedNS> EnterNetworkNS(
26 const std::string& netns_name);
Hugo Benichi0781d402021-02-22 13:43:11 +090027
Qijiang Fan6bc59e12020-11-11 02:51:06 +090028 ScopedNS(const ScopedNS&) = delete;
29 ScopedNS& operator=(const ScopedNS&) = delete;
30
Garrick Evanscf036f32018-12-21 12:56:59 +090031 ~ScopedNS();
32
Garrick Evanscf036f32018-12-21 12:56:59 +090033 private:
Jie Jiangf6799312021-05-14 16:27:03 +090034 ScopedNS(int nstype,
35 const std::string& current_ns_path,
36 const std::string& target_ns_path);
37
Hugo Benichi0781d402021-02-22 13:43:11 +090038 int nstype_;
Garrick Evanscf036f32018-12-21 12:56:59 +090039 bool valid_;
40 base::ScopedFD ns_fd_;
41 base::ScopedFD self_fd_;
Garrick Evanscf036f32018-12-21 12:56:59 +090042};
43
Garrick Evans3388a032020-03-24 11:25:55 +090044} // namespace patchpanel
Garrick Evanscf036f32018-12-21 12:56:59 +090045
Garrick Evans3388a032020-03-24 11:25:55 +090046#endif // PATCHPANEL_SCOPED_NS_H_