forge
Explore
Log in

Don't you dare go Hollow

niri

Clone
★ 0

0 watching0 forksRustGPL-3.012.1 MiBe0ec6e5Ivan Molodetskikh2 years ago752 commits

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