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