forge
Explore
Log in

Don't you dare go Hollow

utils/spawning: Pass grandchild PID only on systemd

Browse files at this commit

1971a41fdd68f0a33bd5db22f776821682c23206Ivan MolodetskikhParent: 4ea9014
libc::close_range() is not available on musl, so do this workaround for
now.
src/utils/spawning.rsmodified+256 -202
@@ -1,17 +1,12 @@
11 use std::ffi::OsStr;
2-use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
32 use std::os::unix::process::CommandExt;
43 use std::path::Path;
5-use std::process::{Command, Stdio};
4+use std::process::{Child, Command, Stdio};
65 use std::sync::atomic::{AtomicBool, Ordering};
76 use std::sync::RwLock;
87 use std::{io, thread};
98
10-use libc::close_range;
119 use niri_config::Environment;
12-use smithay::reexports::rustix;
13-use smithay::reexports::rustix::io::{close, read, retry_on_intr, write};
14-use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags};
1510
1611 use crate::utils::expand_home;
1712
@@ -81,244 +76,303 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As
8176 }
8277 drop(env);
8378
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();
79+ let Some(mut child) = do_spawn(command, process) else {
80+ return;
81+ };
11482
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());
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+}
12294
95+#[cfg(not(feature = "systemd"))]
96+fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
97+ unsafe {
12398 // Double-fork to avoid having to waitpid the child.
12499 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-
138100 match libc::fork() {
139101 -1 => return Err(io::Error::last_os_error()),
140102 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- }
103+ _ => libc::_exit(0),
160104 }
161105
162106 Ok(())
163107 });
164108 }
165109
166- let mut child = match process.spawn() {
110+ let child = match process.spawn() {
167111 Ok(child) => child,
168112 Err(err) => {
169113 warn!("error spawning {command:?}: {err:?}");
170- return;
114+ return None;
171115 }
172116 };
173117
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:?}");
118+ Some(child)
119+}
120+
121+#[cfg(feature = "systemd")]
122+use systemd::do_spawn;
123+
124+#[cfg(feature = "systemd")]
125+mod 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);
189184 }
190- }
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,
191223 Err(err) => {
192- warn!("error reading child PID: {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+ }
193249 }
194250 }
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)
195258 }
196259
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);
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+ }
200268
201- match child.wait() {
202- Ok(status) => {
203- if !status.success() {
204- warn!("child did not exit successfully: {status:?}");
269+ written += n;
270+ if written == buf.len() {
271+ return Ok(());
205272 }
206273 }
207- Err(err) => {
208- warn!("error waiting for child: {err:?}");
209- }
210274 }
211-}
212275
213-fn 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- }
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+ }
220284
221- written += n;
222- if written == buf.len() {
223- return Ok(());
285+ start += n;
286+ if start == buf.len() {
287+ return Ok(());
288+ }
224289 }
225290 }
226-}
227-
228-fn 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- }
235291
236- start += n;
237- if start == buf.len() {
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) {
238313 return Ok(());
239314 }
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")]
248-fn 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;
257315
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!();
316+ let _span = tracy_client::span!();
264317
265- // Extract the basename.
266- let name = Path::new(name).file_name().unwrap_or(name);
318+ // Extract the basename.
319+ let name = Path::new(name).file_name().unwrap_or(name);
267320
268- let mut scope_name = String::from("app-niri-");
321+ let mut scope_name = String::from("app-niri-");
269322
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}");
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+ }
277331 }
278- }
279332
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;
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+ }
320374 }
321- }
322375
323- Ok(())
376+ Ok(())
377+ }
324378 }