Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
wayland_peer.h
Go to the documentation of this file.
1
5#pragma once
6
7#include "session_socket.h"
8
9#include <csignal>
10#include <fcntl.h>
11#include <filesystem>
12#include <linux/capability.h>
13#include <sys/prctl.h>
14#include <sys/syscall.h>
15#include <sys/wait.h>
16
17namespace platf::kwin {
18 // Internal mode of hermes-detached-session, entered before desktop startup.
19 // This is a fresh exec: making the helper dumpable must never expose a forked
20 // copy of the capability-bearing Hermes process's address space.
21 inline int serve_wayland_peer(const char *path) {
22 constexpr int channel = 3;
23 if (::getuid() != ::geteuid() || ::getgid() != ::getegid()) {
24 return 1;
25 }
26 __user_cap_header_struct header {_LINUX_CAPABILITY_VERSION_3, 0};
27 __user_cap_data_struct capabilities[2] {};
28 if (::syscall(SYS_capset, &header, capabilities) < 0 ||
29 ::prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_CLEAR_ALL, 0L, 0L, 0L) < 0 ||
30 ::prctl(PR_SET_NO_NEW_PRIVS, 1L, 0L, 0L, 0L) < 0 ||
31 ::prctl(PR_SET_DUMPABLE, 1L, 0L, 0L, 0L) < 0) {
32 return 1;
33 }
34 int type = 0;
35 socklen_t size = sizeof(type);
36 if (::getsockopt(channel, SOL_SOCKET, SO_TYPE, &type, &size) < 0 || type != SOCK_SEQPACKET) {
37 return 1;
38 }
39
40 std::string error;
41 const int connection = connect_session_socket(path, error);
42 const char success = connection >= 0 ? 1 : 0;
43 alignas(cmsghdr) char control[CMSG_SPACE(sizeof(int))] {};
44 iovec payload {const_cast<char *>(&success), sizeof(success)};
45 msghdr message {};
46 message.msg_iov = &payload;
47 message.msg_iovlen = 1;
48 if (connection >= 0) {
49 message.msg_control = control;
50 message.msg_controllen = sizeof(control);
51 auto *item = CMSG_FIRSTHDR(&message);
52 item->cmsg_level = SOL_SOCKET;
53 item->cmsg_type = SCM_RIGHTS;
54 item->cmsg_len = CMSG_LEN(sizeof(connection));
55 std::memcpy(CMSG_DATA(item), &connection, sizeof(connection));
56 }
57 const auto sent = ::sendmsg(channel, &message, MSG_NOSIGNAL | MSG_DONTWAIT);
58 if (connection >= 0) {
59 ::close(connection);
60 }
61 if (sent != sizeof(success) || !success) {
62 return 1;
63 }
64 // KWin reads /proc/<peer-pid>/exe when it accepts the socket. Stay alive
65 // until the parent's registry round trips complete, or the parent exits.
66 // The parent also bounds setup and owns reaping us on every failure path.
67 pollfd event {channel, POLLIN, 0};
68 return ::poll(&event, 1, 30000) > 0 ? 0 : 1;
69 }
70
71 class wayland_peer_t {
72 public:
73 wayland_peer_t() = default;
74 wayland_peer_t(const wayland_peer_t &) = delete;
75 wayland_peer_t &operator=(const wayland_peer_t &) = delete;
76
77 ~wayland_peer_t() {
78 if (channel >= 0) {
79 ::close(channel);
80 }
81 if (child > 0) {
82 int status;
83 pid_t result;
84 do {
85 result = ::waitpid(child, &status, WNOHANG);
86 } while (result < 0 && errno == EINTR);
87 if (result == 0) {
88 // The setup has finished (or failed); there is no remaining work.
89 // A stuck loader/helper must not stall shutdown or retain its PID.
90 ::kill(child, SIGKILL);
91 do {
92 result = ::waitpid(child, &status, 0);
93 } while (result < 0 && errno == EINTR);
94 }
95 }
96 }
97
98 // The returned socket belongs to libwayland/the caller. This guard must
99 // live until KWin has accepted it and sent the initial registry responses.
100 int open(const std::string &path, std::string &error) {
101 std::error_code ec;
102 auto executable = std::filesystem::read_symlink("/proc/self/exe", ec);
103 if (ec) {
104 error = "Could not locate Hermes's private Wayland connection helper: " + ec.message();
105 return -1;
106 }
107 return open_with_helper(path, (executable.parent_path() / "hermes-detached-session").string(), error);
108 }
109
110 int open_with_helper(const std::string &path, const std::string &helper, std::string &error) {
111 error.clear();
112 sockaddr_un address {};
113 if (child > 0 || path.empty() || path.front() != '/' || path.find('\0') != std::string::npos || path.size() >= sizeof(address.sun_path) ||
114 helper.empty() || helper.front() != '/' || helper.find('\0') != std::string::npos) {
115 error = "Private Wayland connection requires an absolute socket and helper path";
116 return -1;
117 }
118 const long max_fd = ::sysconf(_SC_OPEN_MAX);
119 if (max_fd < 0) {
120 error = "Could not determine the descriptor limit for the private Wayland helper";
121 return -1;
122 }
123 int descriptors[2];
124 if (::socketpair(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0, descriptors) != 0) {
125 error = "Could not create private Wayland helper channel: " + std::string(std::strerror(errno));
126 return -1;
127 }
128 // Keep the child's source away from fd 3, even with closed stdin/stdout.
129 const int source = ::fcntl(descriptors[1], F_DUPFD_CLOEXEC, 4);
130 ::close(descriptors[1]);
131 if (source < 0) {
132 ::close(descriptors[0]);
133 error = "Could not prepare private Wayland helper descriptor";
134 return -1;
135 }
136 char *const arguments[] {const_cast<char *>(helper.c_str()), const_cast<char *>("--connect-wayland"), const_cast<char *>(path.c_str()), nullptr};
137 char *const environment[] {nullptr};
138 child = ::fork();
139 if (child == 0) {
140 // Only async-signal-safe operations between fork and exec. In
141 // particular, never make this copy of Hermes's memory dumpable.
142 if (::dup2(source, 3) < 0) {
143 ::_exit(127);
144 }
145 ::close(0);
146 ::close(1);
147 ::close(2);
148#ifdef SYS_close_range
149 if (::syscall(SYS_close_range, 4U, ~0U, 0U) != 0)
150#endif
151 {
152 for (long fd = 4; fd < max_fd; ++fd) {
153 ::close(static_cast<int>(fd));
154 }
155 }
156 // No inherited loader variables, display defaults, credentials or
157 // stream descriptors enter the helper. Its only job uses fd 3.
158 ::execve(helper.c_str(), arguments, environment);
159 ::_exit(127);
160 }
161 ::close(source);
162 channel = descriptors[0];
163 if (child < 0) {
164 error = "Could not start private Wayland connection helper";
165 return -1;
166 }
167
168 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
169 pollfd event {channel, POLLIN, 0};
170 int result;
171 do {
172 const auto left = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count();
173 result = ::poll(&event, 1, static_cast<int>(std::max<std::int64_t>(0, left)));
174 } while (result < 0 && errno == EINTR && std::chrono::steady_clock::now() < deadline);
175 if (result <= 0 || !(event.revents & POLLIN)) {
176 error = "Private Wayland connection helper failed or timed out; check hermes-detached-session beside Hermes";
177 return -1;
178 }
179 char success = 0;
180 alignas(cmsghdr) char control[CMSG_SPACE(sizeof(int))] {};
181 iovec payload {&success, sizeof(success)};
182 msghdr message {};
183 message.msg_iov = &payload;
184 message.msg_iovlen = 1;
185 message.msg_control = control;
186 message.msg_controllen = sizeof(control);
187 const auto received = ::recvmsg(channel, &message, MSG_CMSG_CLOEXEC | MSG_DONTWAIT);
188 int connection = -1;
189 bool extra = false;
190 for (auto *item = CMSG_FIRSTHDR(&message); received >= 0 && item; item = CMSG_NXTHDR(&message, item)) {
191 if (item->cmsg_level == SOL_SOCKET && item->cmsg_type == SCM_RIGHTS && item->cmsg_len >= CMSG_LEN(0)) {
192 const auto count = (item->cmsg_len - CMSG_LEN(0)) / sizeof(int);
193 for (size_t i = 0; i < count; ++i) {
194 int fd;
195 std::memcpy(&fd, CMSG_DATA(item) + i * sizeof(int), sizeof(fd));
196 if (connection < 0) {
197 connection = fd;
198 } else {
199 ::close(fd);
200 extra = true;
201 }
202 }
203 }
204 }
205 if (received != 1 || success != 1 || connection < 0 || extra || (message.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
206 if (connection >= 0) {
207 ::close(connection);
208 }
209 error = "Private Wayland helper could not connect to the requested socket; refusing host fallback";
210 return -1;
211 }
212 return connection;
213 }
214
215 private:
216 int channel {-1};
217 pid_t child {-1};
218 };
219} // namespace platf::kwin
Explicit, bounded Unix socket connection without display or remote environment lookup.