aboutsummaryrefslogtreecommitdiffstats
path: root/brillo/scoped_mount_namespace.cc
blob: 0f35e82e6a22567abee34b0e525b01a622dbf75e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "brillo/scoped_mount_namespace.h"

#include <fcntl.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <string>
#include <utility>

#include <base/posix/eintr_wrapper.h>
#include <base/strings/stringprintf.h>

namespace {
constexpr char kCurrentMountNamespacePath[] = "/proc/self/ns/mnt";
}  // anonymous namespace

namespace brillo {

ScopedMountNamespace::ScopedMountNamespace(base::ScopedFD mount_namespace_fd)
    : mount_namespace_fd_(std::move(mount_namespace_fd)) {}

ScopedMountNamespace::~ScopedMountNamespace() {
  PLOG_IF(ERROR, setns(mount_namespace_fd_.get(), CLONE_NEWNS) != 0)
      << "Ignoring failure to restore original mount namespace";
}

// static
std::unique_ptr<ScopedMountNamespace> ScopedMountNamespace::CreateForPid(
    pid_t pid) {
  std::string ns_path = base::StringPrintf("/proc/%d/ns/mnt", pid);
  return CreateFromPath(base::FilePath(ns_path));
}

// static
std::unique_ptr<ScopedMountNamespace> ScopedMountNamespace::CreateFromPath(
    base::FilePath ns_path) {
  base::ScopedFD original_mount_namespace_fd(
      HANDLE_EINTR(open(kCurrentMountNamespacePath, O_RDONLY)));
  if (!original_mount_namespace_fd.is_valid()) {
    PLOG(ERROR) << "Failed to open original mount namespace FD at "
                << kCurrentMountNamespacePath;
    return nullptr;
  }

  base::ScopedFD mount_namespace_fd(
      HANDLE_EINTR(open(ns_path.value().c_str(), O_RDONLY)));
  if (!mount_namespace_fd.is_valid()) {
    PLOG(ERROR) << "Failed to open mount namespace FD at " << ns_path.value();
    return nullptr;
  }

  if (setns(mount_namespace_fd.get(), CLONE_NEWNS) != 0) {
    PLOG(ERROR) << "Failed to enter mount namespace at " << ns_path.value();
    return nullptr;
  }

  return std::make_unique<ScopedMountNamespace>(
      std::move(original_mount_namespace_fd));
}

}  // namespace brillo