forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBfff3b86Ivan Molodetskikh1 month ago2973 commits

spawning.rs489 lines, 16.5 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(
224 first: libc::c_uint,
225 last: libc::c_uint,
226 flags: libc::c_uint,
227 ) -> libc::c_long {
228 unsafe {
229 libc::syscall(
230 libc::SYS_close_range,
231 first as usize,
232 last as usize,
233 flags as usize,
234 )
235 }
236 }
237
238 // When running as a systemd session, we want to put children into their own transient
239 // scopes in order to separate them from the niri process. This is helpful for
240 // example to prevent the OOM killer from taking down niri together with a
241 // misbehaving client.
242 //
243 // Putting a child into a scope is done by calling systemd's StartTransientUnit D-Bus method
244 // with a PID. Unfortunately, there seems to be a race in systemd where if the child exits
245 // at just the right time, the transient unit will be created but empty, so it will
246 // linger around forever.
247 //
248 // To prevent this, we'll use our double-fork (done for a separate reason) to help. In our
249 // intermediate child we will send back the grandchild PID, and in niri we will create a
250 // transient scope with both our intermediate child and the grandchild PIDs set. Only then
251 // we will signal our intermediate child to exit. This way, even if the grandchild
252 // exits quickly, a non-empty scope will be created (with just our intermediate
253 // child), then cleaned up when our intermediate child exits.
254
255 // Make a pipe to receive the grandchild PID.
256
257 let (pipe_pid_read, pipe_pid_write) = pipe_with(PipeFlags::CLOEXEC)
258 .map_err(|err| {
259 warn!("error creating a pipe to transfer child PID: {err:?}");
260 })
261 .ok()
262 .unzip();
263 // Make a pipe to wait in the intermediate child.
264 let (pipe_wait_read, pipe_wait_write) = pipe_with(PipeFlags::CLOEXEC)
265 .map_err(|err| {
266 warn!("error creating a pipe for child to wait on: {err:?}");
267 })
268 .ok()
269 .unzip();
270
271 unsafe {
272 // The fds will be duplicated after a fork and closed on exec or exit automatically. Get
273 // the raw fd inside so that it's not closed any extra times.
274 let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd());
275 let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd());
276 let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd());
277 let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd());
278
279 // Double-fork to avoid having to waitpid the child.
280 process.pre_exec(move || {
281 // Close FDs that we don't need. Especially important for the write ones to unblock
282 // the readers.
283 if let Some(fd) = pipe_pid_read_fd.take() {
284 close(fd);
285 }
286 if let Some(fd) = pipe_wait_write_fd.take() {
287 close(fd);
288 }
289
290 // Convert the FDs to OwnedFd, which will close them in all of our fork paths.
291 let pipe_pid_write = pipe_pid_write_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
292 let pipe_wait_read = pipe_wait_read_fd.take().map(|fd| OwnedFd::from_raw_fd(fd));
293
294 match libc::fork() {
295 -1 => return Err(io::Error::last_os_error()),
296 0 => (),
297 grandchild_pid => {
298 // Send back the PID.
299 if let Some(pipe) = pipe_pid_write {
300 let _ = write_all(pipe, &grandchild_pid.to_ne_bytes());
301 }
302
303 // Wait until the parent signals us to exit.
304 if let Some(pipe) = pipe_wait_read {
305 // We're going to exit afterwards. Close all other FDs to allow
306 // Command::spawn() to return in the parent process.
307 #[cfg(not(target_os = "openbsd"))]
308 {
309 let raw = pipe.as_raw_fd() as u32;
310 let _ = close_range(0, raw - 1, 0);
311 let _ = close_range(raw + 1, !0, 0);
312 }
313 #[cfg(target_os = "openbsd")]
314 {
315 let raw = pipe.as_raw_fd();
316 for fd in 0..raw {
317 close(fd);
318 }
319 closefrom(raw + 1);
320 }
321
322 let _ = read_all(pipe, &mut [0]);
323 }
324
325 libc::_exit(0)
326 }
327 }
328
329 restore_nofile_rlimit();
330
331 Ok(())
332 });
333 }
334
335 let child = match process.spawn() {
336 Ok(child) => child,
337 Err(err) => {
338 warn!("error spawning {command:?}: {err:?}");
339 return None;
340 }
341 };
342
343 drop(pipe_pid_write);
344 drop(pipe_wait_read);
345
346 // Wait for the grandchild PID.
347 if let Some(pipe) = pipe_pid_read {
348 let mut buf = [0; 4];
349 match read_all(pipe, &mut buf) {
350 Ok(()) => {
351 let pid = i32::from_ne_bytes(buf);
352 trace!("spawned PID: {pid}");
353
354 // Start a systemd scope for the grandchild.
355 if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) {
356 trace!("error starting systemd scope for spawned command: {err:?}");
357 }
358 }
359 Err(err) => {
360 warn!("error reading child PID: {err:?}");
361 }
362 }
363 }
364
365 // Signal the intermediate child to exit now that we're done trying to creating a systemd
366 // scope.
367 trace!("signaling child to exit");
368 drop(pipe_wait_write);
369
370 Some(child)
371 }
372
373 fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> {
374 let mut written = 0;
375 loop {
376 let n = retry_on_intr(|| write(&fd, &buf[written..]))?;
377 if n == 0 {
378 return Err(rustix::io::Errno::CANCELED);
379 }
380
381 written += n;
382 if written == buf.len() {
383 return Ok(());
384 }
385 }
386 }
387
388 fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> {
389 let mut start = 0;
390 loop {
391 let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?;
392 if n == 0 {
393 return Err(rustix::io::Errno::CANCELED);
394 }
395
396 start += n;
397 if start == buf.len() {
398 return Ok(());
399 }
400 }
401 }
402
403 /// Puts a (newly spawned) pid into a transient systemd scope.
404 ///
405 /// This separates the pid from the compositor scope, which for example prevents the OOM killer
406 /// from bringing down the compositor together with a misbehaving client.
407 fn start_systemd_scope(
408 name: &OsStr,
409 intermediate_pid: u32,
410 child_pid: u32,
411 ) -> anyhow::Result<()> {
412 use std::fmt::Write as _;
413 use std::os::unix::ffi::OsStrExt;
414 use std::sync::OnceLock;
415
416 use anyhow::Context;
417 use zbus::zvariant::{OwnedObjectPath, Value};
418
419 use crate::utils::IS_SYSTEMD_SERVICE;
420
421 // We only start transient scopes if we're a systemd service ourselves.
422 if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) {
423 return Ok(());
424 }
425
426 let _span = tracy_client::span!();
427
428 // Extract the basename.
429 let name = Path::new(name).file_name().unwrap_or(name);
430
431 let mut scope_name = String::from("app-niri-");
432
433 // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from
434 // systemd source.
435 for &c in name.as_bytes() {
436 if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') {
437 scope_name.push(char::from(c));
438 } else {
439 let _ = write!(scope_name, "\\x{c:02x}");
440 }
441 }
442
443 let _ = write!(scope_name, "-{child_pid}.scope");
444
445 // Ask systemd to start a transient scope.
446 static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new();
447 let conn = CONNECTION
448 .get_or_init(zbus::blocking::Connection::session)
449 .clone()
450 .context("error connecting to session bus")?;
451
452 let proxy = zbus::blocking::Proxy::new(
453 &conn,
454 "org.freedesktop.systemd1",
455 "/org/freedesktop/systemd1",
456 "org.freedesktop.systemd1.Manager",
457 )
458 .context("error creating a Proxy")?;
459
460 let signals = proxy
461 .receive_signal("JobRemoved")
462 .context("error creating a signal iterator")?;
463
464 let pids: &[_] = &[intermediate_pid, child_pid];
465 let properties: &[_] = &[
466 ("PIDs", Value::new(pids)),
467 ("CollectMode", Value::new("inactive-or-failed")),
468 ];
469 let aux: &[(&str, &[(&str, Value)])] = &[];
470
471 let job: OwnedObjectPath = proxy
472 .call("StartTransientUnit", &(scope_name, "fail", properties, aux))
473 .context("error calling StartTransientUnit")?;
474
475 trace!("waiting for JobRemoved");
476 for message in signals {
477 let body = message.body();
478 let body: (u32, OwnedObjectPath, &str, &str) =
479 body.deserialize().context("error parsing signal")?;
480
481 if body.1 == job {
482 // Our transient unit had started, we're good to exit the intermediate child.
483 break;
484 }
485 }
486
487 Ok(())
488 }
489}