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