Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
session_devices.cpp
Go to the documentation of this file.
1
5#include "session_devices.h"
6#include "session_lineage.h"
7
8// standard includes
9#include <cctype>
10#include <cerrno>
11#include <cstdio>
12#include <cstring>
13#include <filesystem>
14#include <fstream>
15#include <mutex>
16#include <optional>
17#include <set>
18#include <string>
19#include <thread>
20
21// platform includes
22#include <fcntl.h>
23#include <linux/netlink.h>
24#include <sched.h>
25#include <sys/capability.h>
26#include <sys/mount.h>
27#include <sys/socket.h>
28#include <sys/stat.h>
29#include <sys/syscall.h>
30#include <sys/sysmacros.h>
31#include <unistd.h>
32
33// lib includes
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>
39
40// local includes
41#include "src/logging.h"
42
43namespace bp = boost::process::v1;
44namespace fs = std::filesystem;
45using namespace std::literals;
46
47namespace platf::session_devices {
48 struct plan_t::op_t {
49 enum kind_e {
50 tmpfs,
51 mkdir,
52 mknod,
53 symlink,
54 bind,
55 move,
56 } kind;
57
58 std::string path;
59 std::string source;
60 mode_t mode {};
61 dev_t dev {};
62 unsigned long flags {};
63 };
64
65 namespace {
66 constexpr std::uint32_t needed_caps = (1u << CAP_SYS_ADMIN) | (1u << CAP_MKNOD) | (1u << CAP_SYS_CHROOT);
67
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);
73 ::_exit(127);
74 }
75
76 // Raw system calls: the child of a multithreaded parent may not allocate.
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)) {
81 return false;
82 }
83 if (raise) {
84 data[0].effective |= data[0].permitted & needed_caps;
85 } else {
86 for (auto &set : data) {
87 set.effective = set.permitted = set.inheritable = 0;
88 }
89 }
90 return ::syscall(SYS_capset, &header, data) == 0;
91 }
92
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;
96 }
97 } // namespace
98
99 plan_t::plan_t() = default;
100 plan_t::~plan_t() = default;
101
102 bool available() {
103 cap_t caps = cap_get_proc();
104 if (!caps) {
105 return false;
106 }
107 const bool ok = has_cap(caps, CAP_SYS_ADMIN) && has_cap(caps, CAP_MKNOD);
108 cap_free(caps);
109 return ok;
110 }
111
112 std::unique_ptr<plan_t> plan_t::isolate(const std::string &staging, options_t options) {
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});
116 };
117
118 if (!options.devices) {
119 if (options.sound && fs::is_directory("/dev/snd")) {
120 add(op_t::tmpfs, "/dev/snd", {}, 0, 0, MS_NODEV);
121 }
122 return plan;
123 }
124
125 plan->staging = staging;
126 const auto under = [&](const std::string &name) {
127 return staging + "/" + name;
128 };
129 add(op_t::tmpfs, staging);
130
131 // Copies of the nodes anyone may use, and of those the user can already
132 // open. Never the host's input, sound, USB, camera or storage devices.
133 std::vector<std::string> nodes {"null", "zero", "full", "random", "urandom", "tty", "ptmx", "fuse", "uinput", "ntsync", "kfd", "udmabuf"};
134 std::error_code ec;
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);
138 }
139 }
140 for (const auto &name : nodes) {
141 const auto path = "/dev/" + name;
142 struct stat st {};
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))) {
145 continue;
146 }
147 add(op_t::mknod, under(name), {}, (st.st_mode & 0006) == 0006 ? 0666 : 0600, st.st_rdev);
148 }
149
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);
152 }
153 if (fs::is_symlink("/dev/log", ec)) {
154 add(op_t::symlink, under("log"), fs::read_symlink("/dev/log", ec).string());
155 }
156
157 // Live: GPUs (Hermes-KMS cards come and go), terminals, shared memory.
158 std::vector<std::string> live {"dri", "pts", "shm", "mqueue", "hugepages"};
159 if (!options.sound) {
160 live.emplace_back("snd");
161 }
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);
166 }
167 }
168
169 // Filled by mirror() as the session's devices appear.
170 add(op_t::mkdir, under("input"), {}, 0755);
171 add(op_t::move, "/dev", staging);
172 return plan;
173 }
174
175 std::unique_ptr<plan_t> plan_t::join(pid_t pid) {
176 auto plan = std::make_unique<plan_t>();
177 plan->join_path = "/proc/" + std::to_string(pid) + "/ns/mnt";
178 return plan;
179 }
180
181 void plan_t::apply() const noexcept {
182 if (!set_caps(true)) {
183 fail("capset");
184 }
185
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());
190 }
191 ::close(fd);
192 } else {
193 if (::unshare(CLONE_NEWNS) || ::mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr)) {
194 fail("unshare");
195 }
196 const mode_t mask = ::umask(0);
197 for (const auto &op : ops) {
198 int result = 0;
199 switch (op.kind) {
200 case op_t::tmpfs:
201 result = ::mount("tmpfs", op.path.c_str(), "tmpfs", MS_NOSUID | MS_NOEXEC | op.flags, "mode=0755,size=1m");
202 break;
203 case op_t::mkdir:
204 result = ::mkdir(op.path.c_str(), op.mode);
205 break;
206 case op_t::mknod:
207 result = ::mknod(op.path.c_str(), S_IFCHR | op.mode, op.dev);
208 break;
209 case op_t::symlink:
210 result = ::symlink(op.source.c_str(), op.path.c_str());
211 break;
212 case op_t::bind:
213 result = ::mount(op.source.c_str(), op.path.c_str(), nullptr, MS_BIND | MS_REC, nullptr);
214 break;
215 case op_t::move:
216 result = ::mount(op.source.c_str(), op.path.c_str(), nullptr, MS_MOVE, nullptr);
217 break;
218 }
219 if (result) {
220 fail(op.path.c_str());
221 }
222 }
223 ::umask(mask);
224 }
225
226 if (!set_caps(false)) {
227 fail("capset");
228 }
229 }
230
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) {
232 // First, so start_dir's chdir happens inside the joined namespace.
233 auto setup = bp::extend::on_exec_setup([plan](auto &) {
234 if (plan) {
235 plan->apply();
236 }
237 });
238 // clang-format off
239 if (!group) {
240 if (!file) {
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);
242 }
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);
244 }
245 if (!file) {
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);
247 }
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);
249 // clang-format on
250 }
251
252 namespace {
253 std::string read_line(const fs::path &path) {
254 std::ifstream file {path};
255 std::string line;
256 std::getline(file, line);
257 return line;
258 }
259
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);
265 }
266 }
267 return {};
268 }
269
270 struct device_t {
271 std::string action;
272 std::string subsystem;
273 std::string devpath;
274 std::string devname;
275 unsigned major {};
276 unsigned minor {};
277
278 fs::path sysfs() const {
279 return fs::path {"/sys"} / devpath.substr(1);
280 }
281
282 // What Hermes stamped the device with: its seat.
283 std::string phys() const {
284 if (subsystem == "hidraw") {
285 return uevent_value(sysfs().parent_path().parent_path() / "uevent", "HID_PHYS");
286 }
287 return read_line(sysfs().parent_path() / "phys");
288 }
289
290 // The event and joystick nodes of a gamepad Hermes made through uhid, which
291 // a kernel HID driver (hid-nintendo, hid-playstation) runs; its hidraw node
292 // is not one. Hermes' keyboard, mice, touch and pen are uinput devices.
293 bool hid_gamepad_input() const {
294 return subsystem == "input" && devpath.starts_with("/devices/virtual/misc/uhid/");
295 }
296
297 // Steam Input's pads: uinput devices with Valve's vendor id.
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";
302 }
303 };
304
305 std::optional<ino_t> mount_namespace_of(pid_t pid) {
306 struct stat st {};
307 if (::stat(("/proc/" + std::to_string(pid) + "/ns/mnt").c_str(), &st)) {
308 return std::nullopt;
309 }
310 return st.st_ino;
311 }
312
313 std::optional<pid_t> parent_of(pid_t pid) {
314 std::ifstream status {"/proc/" + std::to_string(pid) + "/status"};
315 std::string line;
316 while (std::getline(status, line)) {
317 if (line.starts_with("PPid:")) {
318 try {
319 return static_cast<pid_t>(std::stol(line.substr(5)));
320 } catch (const std::exception &) {
321 return std::nullopt;
322 }
323 }
324 }
325 return std::nullopt;
326 }
327
328 // Whether only the session's processes hold uinput, Hermes aside: a uinput
329 // device does not record who made it, and a Steam outside the session (its
330 // virtual pads pass on the host's controllers) must not count. The session's
331 // own Steam runs in its runtime's mount namespace, inside the session's, so
332 // a holder counts when it descends from the session (belongs_to_session).
333 bool only_session_holds_uinput(ino_t ns) {
334 std::error_code ec;
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]))) {
340 continue;
341 }
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") {
346 continue;
347 }
348 if (!belongs_to_session(static_cast<pid_t>(std::stol(pid)), ns, mount_namespace_of, parent_of)) {
349 return false;
350 }
351 session = true;
352 break;
353 }
354 }
355 return session;
356 }
357
358 // Capabilities are per thread: raise CAP_MKNOD around the call only.
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);
363 cap_set_proc(caps);
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);
368 }
369 const int error = errno;
370 cap_set_flag(caps, CAP_EFFECTIVE, 1, &mknod_cap, CAP_CLEAR);
371 cap_set_proc(caps);
372 cap_free(caps);
373 errno = error;
374 return result;
375 }
376
377 class mirror_impl_t: public mirror_t {
378 public:
379 mirror_impl_t(int dev_fd, ino_t ns, std::string seat, bool hide_hid_gamepads):
380 dev_fd {dev_fd},
381 ns {ns},
382 seat {std::move(seat)},
383 hide_hid_gamepads {hide_hid_gamepads} {
384 }
385
386 ~mirror_impl_t() override;
387
388 bool owns(const device_t &device) const {
389 // Steam does not grab a HID gamepad's event node, so a game reading it
390 // would get every press twice: raw, and through Steam Input.
391 if (hide_hid_gamepads && device.hid_gamepad_input()) {
392 return false;
393 }
394 return device.phys() == seat || (device.valve_virtual_pad() && only_session_holds_uinput(ns));
395 }
396
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);
400 return;
401 }
402 nodes.insert(device.devname);
403 BOOST_LOG(debug) << "Session seat ["sv << seat << "] got /dev/"sv << device.devname;
404 }
405
406 void remove(const device_t &device) {
407 if (nodes.erase(device.devname)) {
408 ::unlinkat(dev_fd, device.devname.c_str(), 0);
409 }
410 }
411
412 int dev_fd;
413 ino_t ns;
414 std::string seat;
415 bool hide_hid_gamepads;
416 std::set<std::string> nodes;
417 };
418
419 std::mutex mirrors_mutex;
420 std::vector<mirror_impl_t *> mirrors;
421
422 mirror_impl_t::~mirror_impl_t() {
423 std::lock_guard lock {mirrors_mutex};
424 std::erase(mirrors, this);
425 ::close(dev_fd);
426 }
427
428 // Kernel uevents arrive before udev has processed the device, and so
429 // before any application in the session hears of it from udev.
430 void monitor() {
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);
437 return;
438 }
439
440 char buffer[8192];
441 while (true) {
442 const auto size = ::recv(fd, buffer, sizeof buffer - 1, 0);
443 if (size <= 0) {
444 if (size < 0 && errno == ENOBUFS) {
445 BOOST_LOG(warning) << "Kernel uevents were lost; a session may miss a device"sv;
446 }
447 continue;
448 }
449 buffer[size] = '\0';
450
451 device_t device;
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) {
456 continue;
457 }
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);
472 }
473 }
474 if (device.devname.empty() || (device.subsystem != "input" && device.subsystem != "hidraw")) {
475 continue;
476 }
477
478 std::lock_guard lock {mirrors_mutex};
479 for (auto *mirror : mirrors) {
480 if (device.action == "add" && mirror->owns(device)) {
481 mirror->add(device);
482 } else if (device.action == "remove") {
483 mirror->remove(device);
484 }
485 }
486 }
487 }
488
489 // Devices that already exist: from sysfs, as the kernel would announce them.
490 void sync(mirror_impl_t &mirror) {
491 for (const auto *klass : {"/sys/class/input", "/sys/class/hidraw"}) {
492 std::error_code ec;
493 for (const auto &entry : fs::directory_iterator {klass, ec}) {
494 device_t device;
495 device.subsystem = fs::path {klass}.filename().string();
496 device.devname = uevent_value(entry.path() / "uevent", "DEVNAME");
497 unsigned major = 0;
498 unsigned minor = 0;
499 if (device.devname.empty() || std::sscanf(read_line(entry.path() / "dev").c_str(), "%u:%u", &major, &minor) != 2) {
500 continue;
501 }
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)) {
507 mirror.add(device);
508 }
509 }
510 }
511 }
512 } // namespace
513
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();
518 });
519
520 const auto proc = "/proc/" + std::to_string(pid);
521 struct stat st {};
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);
525 if (dev_fd >= 0) {
526 ::close(dev_fd);
527 }
528 return nullptr;
529 }
530
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};
533 sync(*mirror);
534 mirrors.push_back(mirror.get());
535 return mirror;
536 }
537} // namespace platf::session_devices
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.
@ ok
Success.
Definition common.h:436
Declarations for logging related functions.
util::safe_ptr< UPNPDev, freeUPNPDevlist > device_t
Owning pointer to miniupnpc device discovery results.
Definition upnp.h:33
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.