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 | #ifndef PATCHPANEL_SCOPED_NS_H_ |
| 6 | #define PATCHPANEL_SCOPED_NS_H_ |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 7 | |
| 8 | #include <base/files/scoped_file.h> |
| 9 | #include <base/macros.h> |
| 10 | |
Garrick Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 11 | namespace patchpanel { |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 12 | |
Hugo Benichi | 0781d40 | 2021-02-22 13:43:11 +0900 | [diff] [blame] | 13 | // Utility class for running code blocks within a network namespace or a mount |
| 14 | // namespace. |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 15 | class ScopedNS { |
| 16 | public: |
Hugo Benichi | 0781d40 | 2021-02-22 13:43:11 +0900 | [diff] [blame] | 17 | enum Type { |
| 18 | Network = 1, |
| 19 | Mount, |
| 20 | }; |
| 21 | |
| 22 | explicit ScopedNS(pid_t pid, Type type); |
Qijiang Fan | 6bc59e1 | 2020-11-11 02:51:06 +0900 | [diff] [blame] | 23 | ScopedNS(const ScopedNS&) = delete; |
| 24 | ScopedNS& operator=(const ScopedNS&) = delete; |
| 25 | |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 26 | ~ScopedNS(); |
| 27 | |
Hugo Benichi | 0781d40 | 2021-02-22 13:43:11 +0900 | [diff] [blame] | 28 | // Returns whether or not the object was able to enter the target namespace. |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 29 | bool IsValid() const { return valid_; } |
| 30 | |
| 31 | private: |
Hugo Benichi | 0781d40 | 2021-02-22 13:43:11 +0900 | [diff] [blame] | 32 | int nstype_; |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 33 | bool valid_; |
| 34 | base::ScopedFD ns_fd_; |
| 35 | base::ScopedFD self_fd_; |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 36 | }; |
| 37 | |
Garrick Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 38 | } // namespace patchpanel |
Garrick Evans | cf036f3 | 2018-12-21 12:56:59 +0900 | [diff] [blame] | 39 | |
Garrick Evans | 3388a03 | 2020-03-24 11:25:55 +0900 | [diff] [blame] | 40 | #endif // PATCHPANEL_SCOPED_NS_H_ |