23#include <linux/netlink.h>
25#include <sys/capability.h>
27#include <sys/socket.h>
29#include <sys/syscall.h>
30#include <sys/sysmacros.h>
34#include <boost/process/v1/env.hpp>
35#include <boost/process/v1/extend.hpp>
36#include <boost/process/v1/handles.hpp>
37#include <boost/process/v1/io.hpp>
38#include <boost/process/v1/start_dir.hpp>
43namespace bp = boost::process::v1;
44namespace fs = std::filesystem;
45using namespace std::literals;
47namespace platf::session_devices {
62 unsigned long flags {};
66 constexpr std::uint32_t needed_caps = (1u << CAP_SYS_ADMIN) | (1u << CAP_MKNOD) | (1u << CAP_SYS_CHROOT);
68 [[noreturn]]
void fail(
const char *what)
noexcept {
69 constexpr char prefix[] =
"hermes: session /dev setup failed at ";
70 (void) !::write(STDERR_FILENO, prefix,
sizeof prefix - 1);
71 (void) !::write(STDERR_FILENO, what, std::strlen(what));
72 (void) !::write(STDERR_FILENO,
"\n", 1);
77 bool set_caps(
bool raise)
noexcept {
78 __user_cap_header_struct header {_LINUX_CAPABILITY_VERSION_3, 0};
79 __user_cap_data_struct data[2] {};
80 if (::syscall(SYS_capget, &header, data)) {
84 data[0].effective |= data[0].permitted & needed_caps;
86 for (
auto &set : data) {
87 set.effective = set.permitted = set.inheritable = 0;
90 return ::syscall(SYS_capset, &header, data) == 0;
93 bool has_cap(cap_t caps, cap_value_t cap) {
94 cap_flag_value_t value = CAP_CLEAR;
95 return cap_get_flag(caps, cap, CAP_PERMITTED, &value) == 0 && value == CAP_SET;
99 plan_t::plan_t() =
default;
100 plan_t::~plan_t() =
default;
103 cap_t caps = cap_get_proc();
107 const bool ok = has_cap(caps, CAP_SYS_ADMIN) && has_cap(caps, CAP_MKNOD);
113 auto plan = std::make_unique<plan_t>();
114 auto add = [&](op_t::kind_e kind, std::string path, std::string source = {}, mode_t mode = 0, dev_t dev = 0,
unsigned long flags = 0) {
115 plan->ops.push_back({kind, std::move(path), std::move(source), mode, dev, flags});
119 if (options.
sound && fs::is_directory(
"/dev/snd")) {
120 add(op_t::tmpfs,
"/dev/snd", {}, 0, 0, MS_NODEV);
125 plan->staging = staging;
126 const auto under = [&](
const std::string &name) {
127 return staging +
"/" + name;
129 add(op_t::tmpfs, staging);
133 std::vector<std::string> nodes {
"null",
"zero",
"full",
"random",
"urandom",
"tty",
"ptmx",
"fuse",
"uinput",
"ntsync",
"kfd",
"udmabuf"};
135 for (
const auto &entry : fs::directory_iterator {
"/dev", ec}) {
136 if (
const auto name = entry.path().filename().string(); name.starts_with(
"nvidia")) {
137 nodes.push_back(name);
140 for (
const auto &name : nodes) {
141 const auto path =
"/dev/" + name;
143 if (::lstat(path.c_str(), &st) || !S_ISCHR(st.st_mode) ||
144 (::access(path.c_str(), R_OK) && ::access(path.c_str(), W_OK))) {
147 add(op_t::mknod, under(name), {}, (st.st_mode & 0006) == 0006 ? 0666 : 0600, st.st_rdev);
150 for (
const auto &[name, target] : {std::pair {
"fd",
"/proc/self/fd"}, {
"stdin",
"/proc/self/fd/0"}, {
"stdout",
"/proc/self/fd/1"}, {
"stderr",
"/proc/self/fd/2"}}) {
151 add(op_t::symlink, under(name), target);
153 if (fs::is_symlink(
"/dev/log", ec)) {
154 add(op_t::symlink, under(
"log"), fs::read_symlink(
"/dev/log", ec).
string());
158 std::vector<std::string> live {
"dri",
"pts",
"shm",
"mqueue",
"hugepages"};
159 if (!options.
sound) {
160 live.emplace_back(
"snd");
162 for (
const auto &name : live) {
163 if (fs::is_directory(
"/dev/" + name, ec)) {
164 add(op_t::mkdir, under(name), {}, 0755);
165 add(op_t::bind, under(name),
"/dev/" + name);
170 add(op_t::mkdir, under(
"input"), {}, 0755);
171 add(op_t::move,
"/dev", staging);
176 auto plan = std::make_unique<plan_t>();
177 plan->join_path =
"/proc/" + std::to_string(pid) +
"/ns/mnt";
182 if (!set_caps(
true)) {
186 if (!join_path.empty()) {
187 const int fd = ::open(join_path.c_str(), O_RDONLY | O_CLOEXEC);
188 if (fd < 0 || ::setns(fd, CLONE_NEWNS)) {
189 fail(join_path.c_str());
193 if (::unshare(CLONE_NEWNS) || ::mount(
nullptr,
"/",
nullptr, MS_REC | MS_SLAVE,
nullptr)) {
196 const mode_t mask = ::umask(0);
197 for (
const auto &op : ops) {
201 result = ::mount(
"tmpfs", op.path.c_str(),
"tmpfs", MS_NOSUID | MS_NOEXEC | op.flags,
"mode=0755,size=1m");
204 result = ::mkdir(op.path.c_str(), op.mode);
207 result = ::mknod(op.path.c_str(), S_IFCHR | op.mode, op.dev);
210 result = ::symlink(op.source.c_str(), op.path.c_str());
213 result = ::mount(op.source.c_str(), op.path.c_str(),
nullptr, MS_BIND | MS_REC,
nullptr);
216 result = ::mount(op.source.c_str(), op.path.c_str(),
nullptr, MS_MOVE,
nullptr);
220 fail(op.path.c_str());
226 if (!set_caps(
false)) {
231 bp::child run_command(
const plan_t *plan,
const std::string &cmd, boost::filesystem::path &working_dir,
const bp::environment &env, FILE *file, std::error_code &ec, bp::group *group) {
233 auto setup = bp::extend::on_exec_setup([plan](
auto &) {
241 return bp::child(cmd, setup, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > bp::null, bp::std_err > bp::null, bp::limit_handles, ec);
243 return bp::child(cmd, setup, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > file, bp::std_err > file, bp::limit_handles, ec);
246 return bp::child(cmd, setup, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > bp::null, bp::std_err > bp::null, bp::limit_handles, ec, *group);
248 return bp::child(cmd, setup, env, bp::start_dir(working_dir), bp::std_in < bp::null, bp::std_out > file, bp::std_err > file, bp::limit_handles, ec, *group);
253 std::string read_line(
const fs::path &path) {
254 std::ifstream file {path};
256 std::getline(file, line);
260 std::string uevent_value(
const fs::path &uevent, std::string_view key) {
261 std::ifstream file {uevent};
262 for (std::string line; std::getline(file, line);) {
263 if (line.size() > key.size() && line.starts_with(key) && line[key.size()] ==
'=') {
264 return line.substr(key.size() + 1);
272 std::string subsystem;
278 fs::path sysfs()
const {
279 return fs::path {
"/sys"} / devpath.substr(1);
283 std::string phys()
const {
284 if (subsystem ==
"hidraw") {
285 return uevent_value(sysfs().parent_path().parent_path() /
"uevent",
"HID_PHYS");
287 return read_line(sysfs().parent_path() /
"phys");
293 bool hid_gamepad_input()
const {
294 return subsystem ==
"input" && devpath.starts_with(
"/devices/virtual/misc/uhid/");
298 bool valve_virtual_pad()
const {
299 return subsystem ==
"input" && devpath.starts_with(
"/devices/virtual/input/") &&
300 read_line(sysfs().parent_path() /
"phys").empty() &&
301 read_line(sysfs().parent_path() /
"id" /
"vendor") ==
"28de";
305 std::optional<ino_t> mount_namespace_of(pid_t pid) {
307 if (::stat((
"/proc/" + std::to_string(pid) +
"/ns/mnt").c_str(), &st)) {
313 std::optional<pid_t> parent_of(pid_t pid) {
314 std::ifstream status {
"/proc/" + std::to_string(pid) +
"/status"};
316 while (std::getline(status, line)) {
317 if (line.starts_with(
"PPid:")) {
319 return static_cast<pid_t
>(std::stol(line.substr(5)));
320 }
catch (
const std::exception &) {
333 bool only_session_holds_uinput(ino_t ns) {
335 const auto self = std::to_string(::getpid());
336 bool session =
false;
337 for (
const auto &proc : fs::directory_iterator {
"/proc", ec}) {
338 const auto pid = proc.path().filename().string();
339 if (pid == self || !std::isdigit(
static_cast<unsigned char>(pid[0]))) {
342 std::error_code fd_ec;
343 for (
const auto &fd : fs::directory_iterator {proc.path() /
"fd", fd_ec}) {
344 std::error_code link_ec;
345 if (fs::read_symlink(fd.path(), link_ec) !=
"/dev/uinput") {
348 if (!
belongs_to_session(
static_cast<pid_t
>(std::stol(pid)), ns, mount_namespace_of, parent_of)) {
359 int mknod_as_hermes(
int dirfd,
const char *path, dev_t dev) {
360 cap_t caps = cap_get_proc();
361 cap_value_t mknod_cap = CAP_MKNOD;
362 cap_set_flag(caps, CAP_EFFECTIVE, 1, &mknod_cap, CAP_SET);
364 int result = ::mknodat(dirfd, path, S_IFCHR | 0600, dev);
365 if (result && errno == EEXIST) {
366 ::unlinkat(dirfd, path, 0);
367 result = ::mknodat(dirfd, path, S_IFCHR | 0600, dev);
369 const int error = errno;
370 cap_set_flag(caps, CAP_EFFECTIVE, 1, &mknod_cap, CAP_CLEAR);
377 class mirror_impl_t:
public mirror_t {
379 mirror_impl_t(
int dev_fd, ino_t ns, std::string seat,
bool hide_hid_gamepads):
382 seat {std::move(seat)},
383 hide_hid_gamepads {hide_hid_gamepads} {
386 ~mirror_impl_t()
override;
388 bool owns(
const device_t &device)
const {
391 if (hide_hid_gamepads && device.hid_gamepad_input()) {
394 return device.phys() == seat || (device.valve_virtual_pad() && only_session_holds_uinput(ns));
397 void add(
const device_t &device) {
398 if (mknod_as_hermes(dev_fd, device.devname.c_str(), makedev(device.major, device.minor))) {
399 BOOST_LOG(warning) <<
"Couldn't give session seat ["sv << seat <<
"] /dev/"sv << device.devname <<
": "sv << std::strerror(errno);
402 nodes.insert(device.devname);
403 BOOST_LOG(debug) <<
"Session seat ["sv << seat <<
"] got /dev/"sv << device.devname;
406 void remove(
const device_t &device) {
407 if (nodes.erase(device.devname)) {
408 ::unlinkat(dev_fd, device.devname.c_str(), 0);
415 bool hide_hid_gamepads;
416 std::set<std::string> nodes;
419 std::mutex mirrors_mutex;
420 std::vector<mirror_impl_t *> mirrors;
422 mirror_impl_t::~mirror_impl_t() {
423 std::lock_guard lock {mirrors_mutex};
424 std::erase(mirrors,
this);
431 const int fd = ::socket(AF_NETLINK, SOCK_DGRAM | SOCK_CLOEXEC, NETLINK_KOBJECT_UEVENT);
432 sockaddr_nl address {};
433 address.nl_family = AF_NETLINK;
434 address.nl_groups = 1;
435 if (fd < 0 || ::bind(fd,
reinterpret_cast<sockaddr *
>(&address),
sizeof address)) {
436 BOOST_LOG(error) <<
"Couldn't listen to kernel uevents; isolated sessions get no input devices: "sv << std::strerror(errno);
442 const auto size = ::recv(fd, buffer,
sizeof buffer - 1, 0);
444 if (size < 0 && errno == ENOBUFS) {
445 BOOST_LOG(warning) <<
"Kernel uevents were lost; a session may miss a device"sv;
452 for (
const char *field = buffer; field < buffer + size; field += std::strlen(field) + 1) {
453 const std::string_view entry {field};
454 const auto equals = entry.find(
'=');
455 if (equals == std::string_view::npos) {
458 const auto key = entry.substr(0, equals);
459 const auto value = std::string {entry.substr(equals + 1)};
460 if (key ==
"ACTION") {
461 device.action = value;
462 }
else if (key ==
"SUBSYSTEM") {
463 device.subsystem = value;
464 }
else if (key ==
"DEVPATH") {
465 device.devpath = value;
466 }
else if (key ==
"DEVNAME") {
467 device.devname = value;
468 }
else if (key ==
"MAJOR") {
469 device.major = std::stoul(value);
470 }
else if (key ==
"MINOR") {
471 device.minor = std::stoul(value);
474 if (device.devname.empty() || (device.subsystem !=
"input" && device.subsystem !=
"hidraw")) {
478 std::lock_guard lock {mirrors_mutex};
479 for (
auto *mirror : mirrors) {
480 if (device.action ==
"add" &&
mirror->owns(device)) {
482 }
else if (device.action ==
"remove") {
490 void sync(mirror_impl_t &mirror) {
491 for (
const auto *klass : {
"/sys/class/input",
"/sys/class/hidraw"}) {
493 for (
const auto &entry : fs::directory_iterator {klass, ec}) {
495 device.subsystem = fs::path {klass}.filename().string();
496 device.devname = uevent_value(entry.path() /
"uevent",
"DEVNAME");
499 if (device.devname.empty() || std::sscanf(read_line(entry.path() /
"dev").c_str(),
"%u:%u", &major, &minor) != 2) {
502 device.major = major;
503 device.minor = minor;
504 std::error_code canonical_ec;
505 device.devpath = fs::canonical(entry.path(), canonical_ec).string().substr(
"/sys"sv.size());
506 if (!canonical_ec &&
mirror.owns(device)) {
514 std::unique_ptr<mirror_t>
mirror(pid_t pid,
const std::string &seat,
bool hide_hid_gamepads) {
515 static std::once_flag started;
516 std::call_once(started, [] {
517 std::thread {monitor}.detach();
520 const auto proc =
"/proc/" + std::to_string(pid);
522 const int dev_fd = ::open((proc +
"/root/dev").c_str(), O_PATH | O_DIRECTORY | O_CLOEXEC);
523 if (dev_fd < 0 || ::stat((proc +
"/ns/mnt").c_str(), &st)) {
524 BOOST_LOG(error) <<
"Couldn't reach the /dev of session seat ["sv << seat <<
"]: "sv << std::strerror(errno);
531 auto mirror = std::make_unique<mirror_impl_t>(dev_fd, st.st_ino, seat, hide_hid_gamepads);
532 std::lock_guard lock {mirrors_mutex};
534 mirrors.push_back(
mirror.get());
bool remove(const std::string &name)
Remove a card this user created. Removal is a hot-unplug, so a compositor still holding the card sees...
Keeps a session's /dev holding its devices while they come and go.
Work done in a session's process between fork and exec.
static std::unique_ptr< plan_t > isolate(const std::string &staging, options_t options)
A new mount namespace with /dev built on the empty directory staging.
static std::unique_ptr< plan_t > join(pid_t pid)
The mount namespace of a running session process.
void apply() const noexcept
Child side; exits the child on failure.
Declarations for logging related functions.
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
std::unique_ptr< mirror_t > mirror(pid_t pid, const std::string &seat, bool hide_hid_gamepads)
Mirror into the /dev of pid's mount namespace; nullptr on failure.
bool available()
Whether Hermes holds what isolation needs: CAP_SYS_ADMIN and CAP_MKNOD.
What an isolated session sees of the host's /dev.
Whether a process belongs to an isolated session.
bool belongs_to_session(pid_t pid, ino_t ns, MountNs mount_ns, Parent parent)
bool sound
No /dev/snd; the session's audio server is its only way to sound.