forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiB38df8d4Cole Helbling1 year ago2269 commits

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