forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBeac4e8ePatrick Gaskin1 month ago2939 commits

spawning.rs485 lines, 16.4 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
86/// Spawns the command through the shell.
87///
88/// We hardcode `sh -c`, consistent with other compositors:
89///
90/// - https://github.com/swaywm/sway/blob/b3dcde8d69c3f1304b076968a7a64f54d0c958be/sway/commands/exec_always.c#L64
91/// - https://github.com/hyprwm/Hyprland/blob/1ac1ff457ab8ef1ae6a8f2ab17ee7965adfa729f/src/managers/KeybindManager.cpp#L987
92pub fn spawn_sh(command: String, token: Option<XdgActivationToken>) {
93 spawn(vec![String::from("sh"), String::from("-c"), command], token);
94}
95
96fn spawn_sync(
97 command: impl AsRef<OsStr>,
98 args: impl IntoIterator<Item = impl AsRef<OsStr>>,
99 token: Option<XdgActivationToken>,
100) {
101 let _span = tracy_client::span!();
102
103 let mut command = command.as_ref();
104
105 // Expand `~` at the start.
106 let expanded = expand_home(Path::new(command));
107 match &expanded {
108 Ok(Some(expanded)) => command = expanded.as_ref(),
109 Ok(None) => (),
110 Err(err) => {
111 warn!("error expanding ~: {err:?}");
112 }
113 }
114
115 let mut process = Command::new(command);
116 process
117 .args(args)
118 .stdin(Stdio::null())
119 .stdout(Stdio::null())
120 .stderr(Stdio::null());
121
122 // Remove RUST_BACKTRACE and RUST_LIB_BACKTRACE from the environment if needed.
123 if REMOVE_ENV_RUST_BACKTRACE.load(Ordering::Relaxed) {
124 process.env_remove("RUST_BACKTRACE");
125 }
126 if REMOVE_ENV_RUST_LIB_BACKTRACE.load(Ordering::Relaxed) {
127 process.env_remove("RUST_LIB_BACKTRACE");
128 }
129
130 // Remove the systemd NOTIFY_SOCKET variable.
131 process.env_remove("NOTIFY_SOCKET");
132
133 // Set DISPLAY if needed.
134 let display = CHILD_DISPLAY.read().unwrap();
135 if let Some(display) = &*display {
136 process.env("DISPLAY", display);
137 } else {
138 process.env_remove("DISPLAY");
139 }
140
141 // Set configured environment.
142 let env = CHILD_ENV.read().unwrap();
143 for var in &env.0 {
144 if let Some(value) = &var.value {
145 process.env(&var.name, value);
146 } else {
147 process.env_remove(&var.name);
148 }
149 }
150 drop(env);
151
152 if let Some(token) = token.as_ref() {
153 process.env("XDG_ACTIVATION_TOKEN", token.as_str());
154 process.env("DESKTOP_STARTUP_ID", token.as_str());
155 }
156
157 unsafe { process.pre_exec(crate::utils::signals::unblock_all) };
158
159 let Some(mut child) = do_spawn(command, process) else {
160 return;
161 };
162
163 match child.wait() {
164 Ok(status) => {
165 if !status.success() {
166 warn!("child did not exit successfully: {status:?}");
167 }
168 }
169 Err(err) => {
170 warn!("error waiting for child: {err:?}");
171 }
172 }
173}
174
175#[cfg(not(feature = "systemd"))]
176fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
177 unsafe {
178 // Double-fork to avoid having to waitpid the child.
179 process.pre_exec(move || {
180 match libc::fork() {
181 -1 => return Err(io::Error::last_os_error()),
182 0 => (),
183 _ => libc::_exit(0),
184 }
185
186 restore_nofile_rlimit();
187
188 Ok(())
189 });
190 }
191
192 let child = match process.spawn() {
193 Ok(child) => child,
194 Err(err) => {
195 warn!("error spawning {command:?}: {err:?}");
196 return None;
197 }
198 };
199
200 Some(child)
201}
202
203#[cfg(feature = "systemd")]
204use systemd::do_spawn;
205
206#[cfg(feature = "systemd")]
207mod systemd {
208 use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
209
210 use smithay::reexports::rustix;
211 use smithay::reexports::rustix::io::{close, read, retry_on_intr, write};
212 use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags};
213
214 use super::*;
215
216 pub fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
217 #[cfg(target_env = "gnu")]
218 use libc::close_range;
219 #[cfg(target_os = "openbsd")]
220 use libc::closefrom;
221
222 #[cfg(not(target_env = "gnu"))] // musl
223 pub fn close_range(first: libc::c_uint, last: libc::c_uint, flags: libc::c_uint) -> i64 {
224 unsafe {
225 libc::syscall(
226 libc::SYS_close_range,
227 first as usize,
228 last as usize,
229 flags as usize,
230 )
231 }
232 }
233
234 // When running as a systemd session, we want to put children into their own transient
235 // scopes in order to separate them from the niri process. This is helpful for
236 // example to prevent the OOM killer from taking down niri together with a
237 // misbehaving client.
238 //
239 // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method
240 // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits
241 // at just the right time, the transient unit will be created but empty, so it will
242 // linger around forever.
243 //
244 // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our
245 // intermediate child we will send back the grandchild PID, and in niri we will create a
246 // transient scope with both our intermediate child and the grandchild PIDs set. Only then
247 // we will signal our intermediate child to exit. This way, even if the grandchild
248 // exits quickly, a non-empty scope will be created (with just our intermediate
249 // child), then cleaned up when our intermediate child exits.
250
251 // Make a pipe to receive the grandchild PID.
252
253 let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC)
254 .map_err(|err| {
255 warn!("error creating a pipe to transfer child PID: {err:?}");
256 })
257 .ok()
258 .unzip();
259 // Make a pipe to wait in the intermediate child.
260 let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC)
261 .map_err(|err| {
262 warn!("error creating a pipe for child to wait on: {err:?}");
263 })
264 .ok()
265 .unzip();
266
267 unsafe {
268 // The fds will be duplicated after a fork and closed on exec or exit automatically. Get
269 // the raw fd inside so that it's not closed any extra times.
270 let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd());
271 let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd());
272 let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd());
273 let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd());
274
275 // Double-fork to avoid having to waitpid the child.
276 process.pre_exec(move || {
277 // Close FDs that we don't need. Especially important for the write ones to unblock
278 // the readers.
279 if let Some(fd) = pipe_pid_read_fd.take() {
280 close(fd);
281 }
282 if let Some(fd) = pipe_wait_write_fd.take() {
283 close(fd);
284 }
285
286 // Convert the FDs to OwnedFd, which will close them in all of our fork paths.
287 let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
288 let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
289
290 match libc::fork() {
291 -1 => return Err(io::Error::last_os_error()),
292 0 => (),
293 grandchild_pid => {
294 // Send back the PID.
295 if let Some(pipe) = pipe_pid_write {
296 let _ = write_all(pipe, &grandchild_pid.to_ne_bytes());
297 }
298
299 // Wait until the parent signals us to exit.
300 if let Some(pipe) = pipe_wait_read {
301 // We're going to exit afterwards. Close all other FDs to allow
302 // Command::spawn() to return in the parent process.
303 #[cfg(not(target_os = "openbsd"))]
304 {
305 let raw = pipe.as_raw_fd() as u32;
306 let _ = close_range(0, raw - 1, 0);
307 let _ = close_range(raw + 1, !0, 0);
308 }
309 #[cfg(target_os = "openbsd")]
310 {
311 let raw = pipe.as_raw_fd();
312 for fd in 0..raw {
313 close(fd);
314 }
315 closefrom(raw + 1);
316 }
317
318 let _ = read_all(pipe, &mut [0]);
319 }
320
321 libc::_exit(0)
322 }
323 }
324
325 restore_nofile_rlimit();
326
327 Ok(())
328 });
329 }
330
331 let child = match process.spawn() {
332 Ok(child) => child,
333 Err(err) => {
334 warn!("error spawning {command:?}: {err:?}");
335 return None;
336 }
337 };
338
339 drop(pipe_pid_write);
340 drop(pipe_wait_read);
341
342 // Wait for the grandchild PID.
343 if let Some(pipe) = pipe_pid_read {
344 let mut buf = [0; 4];
345 match read_all(pipe, &mut buf) {
346 Ok(()) => {
347 let pid = i32::from_ne_bytes(buf);
348 trace!("spawned PID: {pid}");
349
350 // Start a systemd scope for the grandchild.
351 if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) {
352 trace!("error starting systemd scope for spawned command: {err:?}");
353 }
354 }
355 Err(err) => {
356 warn!("error reading child PID: {err:?}");
357 }
358 }
359 }
360
361 // Signal the intermediate child to exit now that we're done trying to creating a systemd
362 // scope.
363 trace!("signaling child to exit");
364 drop(pipe_wait_write);
365
366 Some(child)
367 }
368
369 fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> {
370 let mut written = 0;
371 loop {
372 let n = retry_on_intr(|| write(&fd, &buf[written..]))?;
373 if n == 0 {
374 return Err(rustix::io::Errno::CANCELED);
375 }
376
377 written += n;
378 if written == buf.len() {
379 return Ok(());
380 }
381 }
382 }
383
384 fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> {
385 let mut start = 0;
386 loop {
387 let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?;
388 if n == 0 {
389 return Err(rustix::io::Errno::CANCELED);
390 }
391
392 start += n;
393 if start == buf.len() {
394 return Ok(());
395 }
396 }
397 }
398
399 /// Puts a (newly spawned) pid into a transient systemd scope.
400 ///
401 /// This separates the pid from the compositor scope, which for example prevents the OOM killer
402 /// from bringing down the compositor together with a misbehaving client.
403 fn start_systemd_scope(
404 name: &OsStr,
405 intermediate_pid: u32,
406 child_pid: u32,
407 ) -> anyhow::Result<()> {
408 use std::fmt::Write as _;
409 use std::os::unix::ffi::OsStrExt;
410 use std::sync::OnceLock;
411
412 use anyhow::Context;
413 use zbus::zvariant::{OwnedObjectPath, Value};
414
415 use crate::utils::IS_SYSTEMD_SERVICE;
416
417 // We only start transient scopes if we're a systemd service ourselves.
418 if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) {
419 return Ok(());
420 }
421
422 let _span = tracy_client::span!();
423
424 // Extract the basename.
425 let name = Path::new(name).file_name().unwrap_or(name);
426
427 let mut scope_name = String::from("app-niri-");
428
429 // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from
430 // systemd source.
431 for &c in name.as_bytes() {
432 if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') {
433 scope_name.push(char::from(c));
434 } else {
435 let _ = write!(scope_name, "\\x{c:02x}");
436 }
437 }
438
439 let _ = write!(scope_name, "-{child_pid}.scope");
440
441 // Ask systemd to start a transient scope.
442 static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new();
443 let conn = CONNECTION
444 .get_or_init(zbus::blocking::Connection::session)
445 .clone()
446 .context("error connecting to session bus")?;
447
448 let proxy = zbus::blocking::Proxy::new(
449 &conn,
450 "org.freedesktop.systemd1",
451 "/org/freedesktop/systemd1",
452 "org.freedesktop.systemd1.Manager",
453 )
454 .context("error creating a Proxy")?;
455
456 let signals = proxy
457 .receive_signal("JobRemoved")
458 .context("error creating a signal iterator")?;
459
460 let pids: &[_] = &[intermediate_pid, child_pid];
461 let properties: &[_] = &[
462 ("PIDs", Value::new(pids)),
463 ("CollectMode", Value::new("inactive-or-failed")),
464 ];
465 let aux: &[(&str, &[(&str, Value)])] = &[];
466
467 let job: OwnedObjectPath = proxy
468 .call("StartTransientUnit", &(scope_name, "fail", properties, aux))
469 .context("error calling StartTransientUnit")?;
470
471 trace!("waiting for JobRemoved");
472 for message in signals {
473 let body = message.body();
474 let body: (u32, OwnedObjectPath, &str, &str) =
475 body.deserialize().context("error parsing signal")?;
476
477 if body.1 == job {
478 // Our transient unit had started, we're good to exit the intermediate child.
479 break;
480 }
481 }
482
483 Ok(())
484 }
485}