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 @@
1 use std::ffi::OsStr;1 use std::ffi::OsStr;
2-use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
3 use std::os::unix::process::CommandExt;2 use std::os::unix::process::CommandExt;
4 use std::path::Path;3 use std::path::Path;
5-use std::process::{Command, Stdio};4+use std::process::{Child, Command, Stdio};
6 use std::sync::atomic::{AtomicBool, Ordering};5 use std::sync::atomic::{AtomicBool, Ordering};
7 use std::sync::RwLock;6 use std::sync::RwLock;
8 use std::{io, thread};7 use std::{io, thread};
9 8
10-use libc::close_range;
11 use niri_config::Environment;9 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};
15 10
16 use crate::utils::expand_home;11 use crate::utils::expand_home;
17 12
@@ -81,244 +76,303 @@ fn spawn_sync(command: impl AsRef<OsStr>, args: impl IntoIterator<Item = impl As
81 }76 }
82 drop(env);77 drop(env);
83 78
84- // When running as a systemd session, we want to put children into their own transient scopes79+ let Some(mut child) = do_spawn(command, process) else {
85- // in order to separate them from the niri process. This is helpful for example to prevent the80+ return;
86- // OOM killer from taking down niri together with a misbehaving client.81+ };
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 82
115- unsafe {83+ match child.wait() {
116- // The fds will be duplicated after a fork and closed on exec or exit automatically. Get84+ Ok(status) => {
117- // the raw fd inside so that it's not closed any extra times.85+ if !status.success() {
118- let mut pipe_pid_read_fd = pipe_pid_read.as_ref().map(|fd| fd.as_raw_fd());86+ warn!("child did not exit successfully: {status:?}");
119- let mut pipe_pid_write_fd = pipe_pid_write.as_ref().map(|fd| fd.as_raw_fd());87+ }
120- let mut pipe_wait_read_fd = pipe_wait_read.as_ref().map(|fd| fd.as_raw_fd());88+ }
121- let mut pipe_wait_write_fd = pipe_wait_write.as_ref().map(|fd| fd.as_raw_fd());89+ Err(err) => {
90+ warn!("error waiting for child: {err:?}");
91+ }
92+ }
93+}
122 94
95+#[cfg(not(feature = "systemd"))]
96+fn do_spawn(command: &OsStr, mut process: Command) -> Option<Child> {
97+ unsafe {
123 // Double-fork to avoid having to waitpid the child.98 // Double-fork to avoid having to waitpid the child.
124 process.pre_exec(move || {99 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() {100 match libc::fork() {
139 -1 => return Err(io::Error::last_os_error()),101 -1 => return Err(io::Error::last_os_error()),
140 0 => (),102 0 => (),
141- grandchild_pid => {103+ _ => libc::_exit(0),
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 }104 }
161 105
162 Ok(())106 Ok(())
163 });107 });
164 }108 }
165 109
166- let mut child = match process.spawn() {110+ let child = match process.spawn() {
167 Ok(child) => child,111 Ok(child) => child,
168 Err(err) => {112 Err(err) => {
169 warn!("error spawning {command:?}: {err:?}");113 warn!("error spawning {command:?}: {err:?}");
170- return;114+ return None;
171 }115 }
172 };116 };
173 117
174- drop(pipe_pid_write);118+ Some(child)
175- drop(pipe_wait_read);119+}
176-120+
177- // Wait for the grandchild PID.121+#[cfg(feature = "systemd")]
178- if let Some(pipe) = pipe_pid_read {122+use systemd::do_spawn;
179- let mut buf = [0; 4];123+
180- match read_all(pipe, &mut buf) {124+#[cfg(feature = "systemd")]
181- Ok(()) => {125+mod systemd {
182- let pid = i32::from_ne_bytes(buf);126+ use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd};
183- trace!("spawned PID: {pid}");127+
184-128+ use smithay::reexports::rustix;
185- // Start a systemd scope for the grandchild.129+ use smithay::reexports::rustix::io::{close, read, retry_on_intr, write};
186- #[cfg(feature = "systemd")]130+ use smithay::reexports::rustix::pipe::{pipe_with, PipeFlags};
187- if let Err(err) = start_systemd_scope(command, child.id(), pid as u32) {131+
188- trace!("error starting systemd scope for spawned command: {err:?}");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);
189 }184 }
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,
191 Err(err) => {223 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+ }
193 }249 }
194 }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)
195 }258 }
196 259
197- // Signal the intermediate child to exit now that we're done trying to creating a systemd scope.260+ #[cfg(feature = "systemd")]
198- trace!("signaling child to exit");261+ fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> {
199- drop(pipe_wait_write);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+ }
200 268
201- match child.wait() {269+ written += n;
202- Ok(status) => {270+ if written == buf.len() {
203- if !status.success() {271+ return Ok(());
204- warn!("child did not exit successfully: {status:?}");
205 }272 }
206 }273 }
207- Err(err) => {
208- warn!("error waiting for child: {err:?}");
209- }
210 }274 }
211-}
212 275
213-fn write_all(fd: impl AsFd, buf: &[u8]) -> rustix::io::Result<()> {276+ #[cfg(feature = "systemd")]
214- let mut written = 0;277+ fn read_all(fd: impl AsFd, buf: &mut [u8]) -> rustix::io::Result<()> {
215- loop {278+ let mut start = 0;
216- let n = retry_on_intr(|| write(&fd, &buf[written..]))?;279+ loop {
217- if n == 0 {280+ let n = retry_on_intr(|| read(&fd, &mut buf[start..]))?;
218- return Err(rustix::io::Errno::CANCELED);281+ if n == 0 {
219- }282+ return Err(rustix::io::Errno::CANCELED);
283+ }
220 284
221- written += n;285+ start += n;
222- if written == buf.len() {286+ if start == buf.len() {
223- return Ok(());287+ return Ok(());
288+ }
224 }289 }
225 }290 }
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- }
235 291
236- start += n;292+ /// Puts a (newly spawned) pid into a transient systemd scope.
237- if start == buf.len() {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) {
238 return Ok(());313 return Ok(());
239 }314 }
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;
257 315
258- // We only start transient scopes if we're a systemd service ourselves.316+ let _span = tracy_client::span!();
259- if !IS_SYSTEMD_SERVICE.load(Ordering::Relaxed) {
260- return Ok(());
261- }
262-
263- let _span = tracy_client::span!();
264 317
265- // Extract the basename.318+ // Extract the basename.
266- let name = Path::new(name).file_name().unwrap_or(name);319+ let name = Path::new(name).file_name().unwrap_or(name);
267 320
268- let mut scope_name = String::from("app-niri-");321+ let mut scope_name = String::from("app-niri-");
269 322
270- // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from323+ // Escape for systemd similarly to libgnome-desktop, which says it had adapted this from
271- // systemd source.324+ // systemd source.
272- for &c in name.as_bytes() {325+ for &c in name.as_bytes() {
273- if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') {326+ if c.is_ascii_alphanumeric() || matches!(c, b':' | b'_' | b'.') {
274- scope_name.push(char::from(c));327+ scope_name.push(char::from(c));
275- } else {328+ } else {
276- let _ = write!(scope_name, "\\x{c:02x}");329+ let _ = write!(scope_name, "\\x{c:02x}");
330+ }
277 }331 }
278- }
279 332
280- let _ = write!(scope_name, "-{child_pid}.scope");333+ let _ = write!(scope_name, "-{child_pid}.scope");
281-334+
282- // Ask systemd to start a transient scope.335+ // Ask systemd to start a transient scope.
283- static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new();336+ static CONNECTION: OnceLock<zbus::Result<zbus::blocking::Connection>> = OnceLock::new();
284- let conn = CONNECTION337+ let conn = CONNECTION
285- .get_or_init(zbus::blocking::Connection::session)338+ .get_or_init(zbus::blocking::Connection::session)
286- .clone()339+ .clone()
287- .context("error connecting to session bus")?;340+ .context("error connecting to session bus")?;
288-341+
289- let proxy = zbus::blocking::Proxy::new(342+ let proxy = zbus::blocking::Proxy::new(
290- &conn,343+ &conn,
291- "org.freedesktop.systemd1",344+ "org.freedesktop.systemd1",
292- "/org/freedesktop/systemd1",345+ "/org/freedesktop/systemd1",
293- "org.freedesktop.systemd1.Manager",346+ "org.freedesktop.systemd1.Manager",
294- )347+ )
295- .context("error creating a Proxy")?;348+ .context("error creating a Proxy")?;
296-349+
297- let signals = proxy350+ let signals = proxy
298- .receive_signal("JobRemoved")351+ .receive_signal("JobRemoved")
299- .context("error creating a signal iterator")?;352+ .context("error creating a signal iterator")?;
300-353+
301- let pids: &[_] = &[intermediate_pid, child_pid];354+ let pids: &[_] = &[intermediate_pid, child_pid];
302- let properties: &[_] = &[355+ let properties: &[_] = &[
303- ("PIDs", Value::new(pids)),356+ ("PIDs", Value::new(pids)),
304- ("CollectMode", Value::new("inactive-or-failed")),357+ ("CollectMode", Value::new("inactive-or-failed")),
305- ];358+ ];
306- let aux: &[(&str, &[(&str, Value)])] = &[];359+ let aux: &[(&str, &[(&str, Value)])] = &[];
307-360+
308- let job: OwnedObjectPath = proxy361+ let job: OwnedObjectPath = proxy
309- .call("StartTransientUnit", &(scope_name, "fail", properties, aux))362+ .call("StartTransientUnit", &(scope_name, "fail", properties, aux))
310- .context("error calling StartTransientUnit")?;363+ .context("error calling StartTransientUnit")?;
311-364+
312- trace!("waiting for JobRemoved");365+ trace!("waiting for JobRemoved");
313- for message in signals {366+ for message in signals {
314- let body: (u32, OwnedObjectPath, &str, &str) =367+ let body: (u32, OwnedObjectPath, &str, &str) =
315- message.body().context("error parsing signal")?;368+ message.body().context("error parsing signal")?;
316-369+
317- if body.1 == job {370+ if body.1 == job {
318- // Our transient unit had started, we're good to exit the intermediate child.371+ // Our transient unit had started, we're good to exit the intermediate child.
319- break;372+ break;
373+ }
320 }374 }
321- }
322 375
323- Ok(())376+ Ok(())
377+ }
324 }378 }