forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB97dfd2bIvan Molodetskikh1 year ago2184 commits

spawning.rs448 lines, 15.0 KiBHistoryRawDownload
1use std::ffi::OsStr;
2use std::os::unix::process::CommandExt;
3use std::path::Path;
4use std::process::{Child, Command, Stdio};
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::sync::RwLock;
7use std::{io, thread};
8
9use atomic::Atomic;
10use libc::{getrlimit, rlim_t, rlimit, setrlimit, RLIMIT_NOFILE};
11use niri_config::Environment;
12use smithay::wayland::xdg_activation::XdgActivationToken;
13
14use crate::utils::expand_home;
15
16pub static REMOVE_ENV_RUST_BACKTRACE: AtomicBool = AtomicBool::new(false);
17pub static REMOVE_ENV_RUST_LIB_BACKTRACE: AtomicBool = AtomicBool::new(false);
18pub static CHILD_ENV: RwLock<Environment> = RwLock::new(Environment(Vec::new()));
19pub static CHILD_DISPLAY: RwLock<Option<String>> = RwLock::new(None);
20
21static ORIGINAL_NOFILE_RLIMIT_CUR: Atomic<rlim_t> = Atomic::new(0);
22static ORIGINAL_NOFILE_RLIMIT_MAX: Atomic<rlim_t> = Atomic::new(0);
23
24/// Increases the nofile rlimit to the maximum and stores the original value.
25pub fn store_and_increase_nofile_rlimit() {
26 let mut rlim = rlimit {
27 rlim_cur: 0,
28 rlim_max: 0,
29 };
30 if unsafe { getrlimit(RLIMIT_NOFILE, &mut rlim) } != 0 {
31 let err = io::Error::last_os_error();
32 warn!("error getting nofile rlimit: {err:?}");
33 return;
34 }
35
36 ORIGINAL_NOFILE_RLIMIT_CUR.store(rlim.rlim_cur, Ordering::SeqCst);
37 ORIGINAL_NOFILE_RLIMIT_MAX.store(rlim.rlim_max, Ordering::SeqCst);
38
39 trace!(
40 "changing nofile rlimit from {} to {}",
41 rlim.rlim_cur,
42 rlim.rlim_max
43 );
44 rlim.rlim_cur = rlim.rlim_max;
45
46 if unsafe { setrlimit(RLIMIT_NOFILE, &rlim) } != 0 {
47 let err = io::Error::last_os_error();
48 warn!("error setting nofile rlimit: {err:?}");
49 }
50}
51
52/// Restores the original nofile rlimit.
53pub fn restore_nofile_rlimit() {
54 let rlim_cur = ORIGINAL_NOFILE_RLIMIT_CUR.load(Ordering::SeqCst);
55 let rlim_max = ORIGINAL_NOFILE_RLIMIT_MAX.load(Ordering::SeqCst);
56
57 if rlim_cur == 0 {
58 return;
59 }
60
61 let rlim = rlimit { rlim_cur, rlim_max };
62 unsafe { setrlimit(RLIMIT_NOFILE, &rlim) };
63}
64
65/// Spawns the command to run independently of the compositor.
66pub fn spawn<T: AsRef<OsStr> + Send + 'static>(command: Vec<T>, token: Option<XdgActivationToken>) {
67 let _span = tracy_client::span!();
68
69 if command.is_empty() {
70 return;
71 }
72
73 // Spawning and waiting takes some milliseconds, so do it in a thread.
74 let res = thread::Builder::new()
75 .name("Command Spawner".to_owned())
76 .spawn(move || {
77 let (command, args) = command.split_first().unwrap();
78 spawn_sync(command, args, token);
79 });
80
81 if let Err(err) = res {
82 warn!("error spawning a thread to spawn the command: {err:?}");
83 }
84}
85
86fn spawn_sync(
87 command: impl AsRef<OsStr>,
88 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
89 token: Option<XdgActivationToken>,
90) {
91 let _span = tracy_client::span!();
92
93 let mut command = command.as_ref();
94
95 // Expand `~` at the start.
96 let expanded = expand_home(Path::new(command));
97 match &expanded {
98 Ok(Some(expanded)) => command = expanded.as_ref(),
99 Ok(None) => (),
100 Err(err) => {
101 warn!("error expanding ~: {err:?}");
102 }
103 }
104
105 let mut process = Command::new(command);
106 process
107 .args(args)
108 .stdin(Stdio::null())
109 .stdout(Stdio::null())
110 .stderr(Stdio::null());
111
112 // Remove RUST_BACKTRACE and RUST_LIB_BACKTRACE from the environment if needed.
113 if REMOVE_ENV_RUST_BACKTRACE.load(Ordering::Relaxed) {
114 process.env_remove("RUST_BACKTRACE");
115 }
116 if REMOVE_ENV_RUST_LIB_BACKTRACE.load(Ordering::Relaxed) {
117 process.env_remove("RUST_LIB_BACKTRACE");
118 }
119
120 // Set DISPLAY if needed.
121 let display = CHILD_DISPLAY.read().unwrap();
122 if let Some(display) = &*display {
123 process.env("DISPLAY", display);
124 } else {
125 process.env_remove("DISPLAY");
126 }
127
128 // Set configured environment.
129 let env = CHILD_ENV.read().unwrap();
130 for var in &env.0 {
131 if let Some(value) = &var.value {
132 process.env(&var.name, value);
133 } else {
134 process.env_remove(&var.name);
135 }
136 }
137 drop(env);
138
139 if let Some(token) = token.as_ref() {
140 process.env("XDG_ACTIVATION_TOKEN", token.as_str());
141 process.env("DESKTOP_STARTUP_ID", token.as_str());
142 }
143
144 let Some(mut child) = do_spawn(command, process) else {
145 return;
146 };
147
148 match child.wait() {
149 Ok(status) => {
150 if !status.success() {
151 warn!("child did not exit successfully: {status:?}");
152 }
153 }
154 Err(err) => {
155 warn!("error waiting for child: {err:?}");
156 }
157 }
158}
159
160#[cfg(not(feature = "systemd"))]
161fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
162 unsafe {
163 // Double-fork to avoid having to waitpid the child.
164 process.pre_exec(move || {
165 match libc::fork() {
166 -1 => return Err(io::Error::last_os_error()),
167 0 => (),
168 _ => libc::_exit(0),
169 }
170
171 restore_nofile_rlimit();
172
173 Ok(())
174 });
175 }
176
177 let child = match process.spawn() {
178 Ok(child) => child,
179 Err(err) => {
180 warn!("error spawning {command:?}: {err:?}");
181 return None;
182 }
183 };
184
185 Some(child)
186}
187
188#[cfg(feature = "systemd")]
189use systemd::do_spawn;
190
191#[cfg(feature = "systemd")]
192mod systemd {
193 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
194
195 use smithay::reexports::rustix;
196 use smithay::reexports::rustix::io::{close, read, retry_on_intr, write};
197 use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags};
198
199 use super::*;
200
201 pub fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
202 use libc::close_range;
203
204 // When running as a systemd session, we want to put children into their own transient
205 // scopes in order to separate them from the niri process. This is helpful for
206 // example to prevent the OOM killer from taking down niri together with a
207 // misbehaving client.
208 //
209 // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method
210 // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits
211 // at just the right time, the transient unit will be created but empty, so it will
212 // linger around forever.
213 //
214 // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our
215 // intermediate child we will send back the grandchild PID, and in niri we will create a
216 // transient scope with both our intermediate child and the grandchild PIDs set. Only then
217 // we will signal our intermediate child to exit. This way, even if the grandchild
218 // exits quickly, a non-empty scope will be created (with just our intermediate
219 // child), then cleaned up when our intermediate child exits.
220
221 // Make a pipe to receive the grandchild PID.
222
223 let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC)
224 .map_err(|err| {
225 warn!("error creating a pipe to transfer child PID: {err:?}");
226 })
227 .ok()
228 .unzip();
229 // Make a pipe to wait in the intermediate child.
230 let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC)
231 .map_err(|err| {
232 warn!("error creating a pipe for child to wait on: {err:?}");
233 })
234 .ok()
235 .unzip();
236
237 unsafe {
238 // The fds will be duplicated after a fork and closed on exec or exit automatically. Get
239 // the raw fd inside so that it's not closed any extra times.
240 let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd());
241 let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd());
242 let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd());
243 let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd());
244
245 // Double-fork to avoid having to waitpid the child.
246 process.pre_exec(move || {
247 // Close FDs that we don't need. Especially important for the write ones to unblock
248 // the readers.
249 if let Some(fd) = pipe_pid_read_fd.take() {
250 close(fd);
251 }
252 if let Some(fd) = pipe_wait_write_fd.take() {
253 close(fd);
254 }
255
256 // Convert the FDs to OwnedFd, which will close them in all of our fork paths.
257 let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
258 let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
259
260 match libc::fork() {
261 -1 => return Err(io::Error::last_os_error()),
262 0 => (),
263 grandchild_pid => {
264 // Send back the PID.
265 if let Some(pipe) = pipe_pid_write {
266 let _ = write_all(pipe, &grandchild_pid.to_ne_bytes());
267 }
268
269 // Wait until the parent signals us to exit.
270 if let Some(pipe) = pipe_wait_read {
271 // We're going to exit afterwards. Close all other FDs to allow
272 // Command::spawn() to return in the parent process.
273 let raw = pipe.as_raw_fd() as u32;
274 let _ = close_range(0, raw - 1, 0);
275 let _ = close_range(raw + 1, !0, 0);
276
277 let _ = read_all(pipe, &mut [0]);
278 }
279
280 libc::_exit(0)
281 }
282 }
283
284 restore_nofile_rlimit();
285
286 Ok(())
287 });
288 }
289
290 let child = match process.spawn() {
291 Ok(child) => child,
292 Err(err) => {
293 warn!("error spawning {command:?}: {err:?}");
294 return None;
295 }
296 };
297
298 drop(pipe_pid_write);
299 drop(pipe_wait_read);
300
301 // Wait for the grandchild PID.
302 if let Some(pipe) = pipe_pid_read {
303 let mut buf = [0; 4];
304 match read_all(pipe, &mut buf) {
305 Ok(()) => {
306 let pid = i32::from_ne_bytes(buf);
307 trace!("spawned PID: {pid}");
308
309 // Start a systemd scope for the grandchild.
310 #[cfg(feature = "systemd")]
311 if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) {
312 trace!("error starting systemd scope for spawned command: {err:?}");
313 }
314 }
315 Err(err) => {
316 warn!("error reading child PID: {err:?}");
317 }
318 }
319 }
320
321 // Signal the intermediate child to exit now that we're done trying to creating a systemd
322 // scope.
323 trace!("signaling child to exit");
324 drop(pipe_wait_write);
325
326 Some(child)
327 }
328
329 #[cfg(feature = "systemd")]
330 fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> {
331 let mut written = 0;
332 loop {
333 let n = retry_on_intr(|| write(&fd, &buf[written..]))?;
334 if n == 0 {
335 return Err(rustix::io::Errno::CANCELED);
336 }
337
338 written += n;
339 if written == buf.len() {
340 return Ok(());
341 }
342 }
343 }
344
345 #[cfg(feature = "systemd")]
346 fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> {
347 let mut start = 0;
348 loop {
349 let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?;
350 if n == 0 {
351 return Err(rustix::io::Errno::CANCELED);
352 }
353
354 start += n;
355 if start == buf.len() {
356 return Ok(());
357 }
358 }
359 }
360
361 /// Puts a (newly spawned) pid into a transient systemd scope.
362 ///
363 /// This separates the pid from the compositor scope, which for example prevents the OOM killer
364 /// from bringing down the compositor together with a misbehaving client.
365 #[cfg(feature = "systemd")]
366 fn start_systemd_scope(
367 name: &OsStr,
368 intermediate_pid: u32,
369 child_pid: u32,
370 ) -> anyhow::Result<()> {
371 use std::fmt::Write as _;
372 use std::os::unix::ffi::OsStrExt;
373 use std::sync::OnceLock;
374
375 use anyhow::Context;
376 use zbus::zvariant::{OwnedObjectPath, Value};
377
378 use crate::utils::IS_SYSTEMD_SERVICE;
379
380 // We only start transient scopes if we're a systemd service ourselves.
381 if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) {
382 return Ok(());
383 }
384
385 let _span = tracy_client::span!();
386
387 // Extract the basename.
388 let name = Path::new(name).file_name().unwrap_or(name);
389
390 let mut scope_name = String::from("app-niri-");
391
392 // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from
393 // systemd source.
394 for &c in name.as_bytes() {
395 if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') {
396 scope_name.push(char::from(c));
397 } else {
398 let _ = write!(scope_name, "\\x{c:02x}");
399 }
400 }
401
402 let _ = write!(scope_name, "-{child_pid}.scope");
403
404 // Ask systemd to start a transient scope.
405 static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new();
406 let conn = CONNECTION
407 .get_or_init(zbus::blocking::Connection::session)
408 .clone()
409 .context("error connecting to session bus")?;
410
411 let proxy = zbus::blocking::Proxy::new(
412 &conn,
413 "org.freedesktop.systemd1",
414 "/org/freedesktop/systemd1",
415 "org.freedesktop.systemd1.Manager",
416 )
417 .context("error creating a Proxy")?;
418
419 let signals = proxy
420 .receive_signal("JobRemoved")
421 .context("error creating a signal iterator")?;
422
423 let pids: &[_] = &[intermediate_pid, child_pid];
424 let properties: &[_] = &[
425 ("PIDs", Value::new(pids)),
426 ("CollectMode", Value::new("inactive-or-failed")),
427 ];
428 let aux: &[(&str, &[(&str, Value)])] = &[];
429
430 let job: OwnedObjectPath = proxy
431 .call("StartTransientUnit", &(scope_name, "fail", properties, aux))
432 .context("error calling StartTransientUnit")?;
433
434 trace!("waiting for JobRemoved");
435 for message in signals {
436 let body = message.body();
437 let body: (u32, OwnedObjectPath, &str, &str) =
438 body.deserialize().context("error parsing signal")?;
439
440 if body.1 == job {
441 // Our transient unit had started, we're good to exit the intermediate child.
442 break;
443 }
444 }
445
446 Ok(())
447 }
448}