Files
gtk-ahfail/crates/ahfail-display/src/main.rs
T
Asger Geel Weirsøe a4b6297156 Make the update check optional and harden the legacy paths
The Gitea update check is now the default feature update-check of
ahfail-ui; distro builds drop it, and the HTTP client with it.
ahfail-display refuses to run as root and keeps its lock file in
XDG_RUNTIME_DIR instead of a fixed name in the shared /tmp, and the PAM
module no longer spawns it from a root context such as a greeter.
Removes pam_tests.rs, which tested helpers dropped in v0.9.0 and has not
compiled since.

Claude-Session: https://claude.ai/code/session_012LCTmU2ewo8tnM1dByYAoG
2026-09-30 19:18:21 +02:00

226 lines
7.6 KiB
Rust

use gtk::prelude::*;
use gtk::gdk;
use gstreamer as gst;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
const AUDIO_URI: &str = "resource:///ahfail/audio/magic-word.mp3";
const FAILSAFE_MINUTES: u32 = 15;
static SIGTERM_RECEIVED: AtomicBool = AtomicBool::new(false);
extern "C" fn handle_sigterm(_: libc::c_int) {
SIGTERM_RECEIVED.store(true, Ordering::Relaxed);
}
#[cfg(target_os = "linux")]
mod x11_grab {
use std::os::raw::{c_char, c_int, c_ulong, c_void};
type XDisplay = c_void;
type Window = c_ulong;
type Atom = c_ulong;
const GRAB_SUCCESS: c_int = 0;
const GRAB_MODE_ASYNC: c_int = 1;
const XA_CARDINAL: Atom = 6;
const PROP_MODE_REPLACE: c_int = 0;
extern "C" {
fn XOpenDisplay(name: *const c_char) -> *mut XDisplay;
fn XCloseDisplay(dpy: *mut XDisplay) -> c_int;
fn XDefaultRootWindow(dpy: *mut XDisplay) -> Window;
fn XGrabKeyboard(
dpy: *mut XDisplay, grab_window: Window, owner_events: c_int,
pointer_mode: c_int, keyboard_mode: c_int, time: c_ulong,
) -> c_int;
fn XUngrabKeyboard(dpy: *mut XDisplay, time: c_ulong) -> c_int;
fn XInternAtom(dpy: *mut XDisplay, name: *const c_char, only_if_exists: c_int) -> Atom;
fn XChangeProperty(
dpy: *mut XDisplay, w: Window, property: Atom, type_: Atom,
format: c_int, mode: c_int, data: *const u8, nelements: c_int,
) -> c_int;
fn XFlush(dpy: *mut XDisplay) -> c_int;
fn gdk_x11_window_get_xid(window: *mut c_void) -> c_ulong;
}
pub fn is_screen_unlocked() -> bool {
unsafe {
let dpy = XOpenDisplay(std::ptr::null());
if dpy.is_null() { return false; }
let root = XDefaultRootWindow(dpy);
let result = XGrabKeyboard(dpy, root, 0, GRAB_MODE_ASYNC, GRAB_MODE_ASYNC, 0);
if result == GRAB_SUCCESS {
XUngrabKeyboard(dpy, 0);
}
XCloseDisplay(dpy);
result == GRAB_SUCCESS
}
}
/// Tell picom/compton not to draw a shadow around this window.
/// Works by setting _COMPTON_SHADOW=0 directly on the X window,
/// which the compositor respects regardless of its config.
pub fn disable_compositor_shadow(gdk_window: &gdk::Window) {
use glib::ObjectType;
unsafe {
let xid = gdk_x11_window_get_xid(gdk_window.as_ptr() as *mut c_void);
let dpy = XOpenDisplay(std::ptr::null());
if dpy.is_null() { return; }
let atom = XInternAtom(dpy, b"_COMPTON_SHADOW\0".as_ptr() as *const c_char, 0);
let value: u32 = 0;
XChangeProperty(
dpy, xid, atom, XA_CARDINAL, 32,
PROP_MODE_REPLACE, &value as *const u32 as *const u8, 1,
);
XFlush(dpy);
XCloseDisplay(dpy);
}
}
}
fn display_lock_path() -> std::path::PathBuf {
match std::env::var("XDG_RUNTIME_DIR") {
Ok(dir) if !dir.is_empty() => std::path::Path::new(&dir).join("ahfail-display.lock"),
_ => std::path::PathBuf::from(format!("/tmp/ahfail-display-{}.lock", unsafe { libc::getuid() })),
}
}
fn main() {
unsafe {
libc::signal(libc::SIGTERM, handle_sigterm as *const () as libc::sighandler_t);
}
// Never run as root (the PAM module refuses to spawn us there, but the
// binary can also be started by hand).
if unsafe { libc::getuid() == 0 || libc::geteuid() == 0 } {
eprintln!("[ahfail] ahfail-display refuses to run as root");
return;
}
// Single-instance guard, per user: a fixed name in the shared /tmp could be
// pre-created by another user to block us.
let lock_file = std::fs::OpenOptions::new()
.create(true).write(true)
.open(display_lock_path());
let lock_file = match lock_file {
Ok(f) => f,
Err(_) => return,
};
use std::os::unix::io::AsRawFd;
if unsafe { libc::flock(lock_file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
return;
}
// Give PAM a moment to complete, then bail if auth already succeeded.
std::thread::sleep(Duration::from_millis(200));
#[cfg(target_os = "linux")]
if x11_grab::is_screen_unlocked() {
return;
}
if gtk::init().is_err() { return; }
if gst::init().is_err() { return; }
let animation = unsafe { ahfail_ui::animation::load_animation() };
let Some(animation) = animation else { return; };
let Some(display) = gdk::Display::default() else { return; };
let Some(monitor) = display.primary_monitor().or_else(|| display.monitor(0)) else {
return;
};
let geom = monitor.geometry();
let (screen_w, screen_h) = (geom.width(), geom.height());
let config = parse_args();
let (sprite_x, sprite_y) = ahfail_ui::display::sprite_position(
&animation, screen_w, screen_h, &config,
);
let sprite_w = animation.width();
let sprite_h = animation.height();
// Window sized exactly to the sprite — no full-screen background to worry about
let window = gtk::Window::new(gtk::WindowType::Popup);
window.set_decorated(false);
window.set_keep_above(true);
window.set_skip_taskbar_hint(true);
window.set_accept_focus(false);
window.set_type_hint(gdk::WindowTypeHint::Notification);
window.move_(geom.x() + sprite_x, geom.y() + sprite_y);
window.set_default_size(sprite_w, sprite_h);
// RGBA visual so sprite edges (from PNG alpha) composite correctly
if let Some(screen) = window.screen() {
if let Some(visual) = screen.rgba_visual() {
window.set_visual(Some(&visual));
}
}
window.set_app_paintable(true);
window.connect_draw(|_, cr| {
cr.set_source_rgba(0.0, 0.0, 0.0, 0.0);
cr.set_operator(cairo::Operator::Source);
let _ = cr.paint();
gtk::Inhibit(false)
});
let image = gtk::Image::from_animation(&animation);
window.add(&image);
let player = ahfail_ui::audio::create_player(AUDIO_URI);
player.play();
std::thread::spawn(|| ahfail_ui::update::check_for_update(ahfail_ui::VERSION));
let volume_state = ahfail_ui::volume::save_and_set_max();
glib::timeout_add_seconds(FAILSAFE_MINUTES * 60, || {
gtk::main_quit();
glib::Continue(false)
});
glib::timeout_add(Duration::from_millis(200), || {
if SIGTERM_RECEIVED.load(Ordering::Relaxed) {
gtk::main_quit();
return glib::Continue(false);
}
glib::Continue(true)
});
#[cfg(target_os = "linux")]
glib::timeout_add(Duration::from_millis(500), || {
if x11_grab::is_screen_unlocked() {
gtk::main_quit();
return glib::Continue(false);
}
glib::Continue(true)
});
window.show_all();
#[cfg(target_os = "linux")]
if let Some(gdk_win) = window.window() {
x11_grab::disable_compositor_shadow(&gdk_win);
}
gtk::main();
player.stop();
if let Some(vs) = volume_state {
ahfail_ui::volume::restore(vs);
}
}
fn parse_args() -> ahfail_ui::config::ModuleConfig {
let deadzone = std::env::args()
.find(|a| a.starts_with("--deadzone="))
.and_then(|a| {
let val = a.trim_start_matches("--deadzone=");
let p: Vec<&str> = val.split(',').collect();
if p.len() != 4 { return None; }
let x: i32 = p[0].parse().ok()?;
let y: i32 = p[1].parse().ok()?;
let w: i32 = p[2].parse().ok()?;
let h: i32 = p[3].parse().ok()?;
Some(gdk::Rectangle::new(x, y, w, h))
});
ahfail_ui::config::ModuleConfig { deadzone }
}