forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBf51dd67Ivan Molodetskikh2 years ago981 commits

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