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