blob: a77a8f15f01fc270ea1d8b54b38c178ab653aa74 [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
8#include <base/files/scoped_file.h>
9#include <base/macros.h>
10
Garrick Evans3388a032020-03-24 11:25:55 +090011namespace patchpanel {
Garrick Evanscf036f32018-12-21 12:56:59 +090012
Hugo Benichi0781d402021-02-22 13:43:11 +090013// Utility class for running code blocks within a network namespace or a mount
14// namespace.
Garrick Evanscf036f32018-12-21 12:56:59 +090015class ScopedNS {
16 public:
Hugo Benichi0781d402021-02-22 13:43:11 +090017 enum Type {
18 Network = 1,
19 Mount,
20 };
21
22 explicit ScopedNS(pid_t pid, Type type);
Qijiang Fan6bc59e12020-11-11 02:51:06 +090023 ScopedNS(const ScopedNS&) = delete;
24 ScopedNS& operator=(const ScopedNS&) = delete;
25
Garrick Evanscf036f32018-12-21 12:56:59 +090026 ~ScopedNS();
27
Hugo Benichi0781d402021-02-22 13:43:11 +090028 // Returns whether or not the object was able to enter the target namespace.
Garrick Evanscf036f32018-12-21 12:56:59 +090029 bool IsValid() const { return valid_; }
30
31 private:
Hugo Benichi0781d402021-02-22 13:43:11 +090032 int nstype_;
Garrick Evanscf036f32018-12-21 12:56:59 +090033 bool valid_;
34 base::ScopedFD ns_fd_;
35 base::ScopedFD self_fd_;
Garrick Evanscf036f32018-12-21 12:56:59 +090036};
37
Garrick Evans3388a032020-03-24 11:25:55 +090038} // namespace patchpanel
Garrick Evanscf036f32018-12-21 12:56:59 +090039
Garrick Evans3388a032020-03-24 11:25:55 +090040#endif // PATCHPANEL_SCOPED_NS_H_