forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBbbbd35eIvan Molodetskikh1 year ago1693 commits

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