forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB2d82fddIvan Molodetskikh1 year ago2536 commits

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