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