Skip to main content

drmkit_session/
seat.rs

1// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
2// SPDX-License-Identifier: MIT
3
4//! The libseat backend.
5//!
6//! A thin adapter. Everything about *when* the seat is called lives in
7//! [`Session`](crate::Session), which is tested against a fake; what is here is
8//! the translation, and it is the part that cannot be exercised on a machine
9//! with no seat -- which is every machine drmkit is currently built on.
10
11use std::cell::RefCell;
12use std::collections::HashMap;
13use std::os::fd::{AsFd as _, AsRawFd as _, RawFd};
14use std::path::Path;
15use std::rc::Rc;
16use std::time::{Duration, Instant};
17
18use crate::SessionError;
19use crate::session::{Backend, DeviceId, RawEvent};
20
21/// How long [`LibseatBackend::open`] waits for the seat to activate.
22///
23/// Port of upstream's `Seat::k_default_enable_timeout` (`60c6f10`).
24pub const DEFAULT_ENABLE_TIMEOUT: Duration = Duration::from_secs(3);
25
26/// The longest single dispatch while the wait is bounded, so the deadline is
27/// checked often enough to be kept.
28const DISPATCH_SLICE_MS: u128 = 100;
29
30/// Events the seat has delivered but the session has not collected.
31///
32/// Shared with the listener libseat calls. Shared rather than owned because the
33/// crate takes a `'static` callback at open, before there is a backend for it
34/// to belong to.
35type Inbox = Rc<RefCell<Vec<RawEvent>>>;
36
37/// A session backed by libseat.
38///
39/// Whichever backend libseat finds: logind, seatd, or the builtin fallback for
40/// a process running as root on a TTY. `LIBSEAT_BACKEND` picks one explicitly.
41#[derive(Debug)]
42pub struct LibseatBackend {
43    seat: libseat::Seat,
44    /// Open devices, by the id handed out to the session.
45    ///
46    /// The crate's `close_device` consumes the `Device`, so they are held here
47    /// rather than handed to the caller, who only needs the descriptor.
48    devices: HashMap<i32, libseat::Device>,
49    next_id: i32,
50    inbox: Inbox,
51    /// The connection's descriptor, read once at open.
52    ///
53    /// The crate's accessor needs `&mut`, and a caller polling in a loop wants
54    /// `&self`. It does not change for the life of the connection.
55    poll_fd: Option<RawFd>,
56}
57
58impl LibseatBackend {
59    /// Connect to whatever seat is available, and wait for it to activate.
60    ///
61    /// # Errors
62    ///
63    /// - [`SessionError::NoBackend`] when there is no seat. That is the
64    ///   ordinary case outside a login session -- over SSH, in a container, on
65    ///   a CI runner -- and a caller that only wants to look at a display can
66    ///   open devices directly instead. What it gives up is surviving a VT
67    ///   switch.
68    ///   The same when the backend connects but does not activate the seat
69    ///   within [`DEFAULT_ENABLE_TIMEOUT`] -- seatd over SSH, with no VT to
70    ///   take -- so the caller falls back the same way.
71    /// - [`SessionError::Seat`] if a dispatch fails.
72    pub fn open() -> Result<Self, SessionError> {
73        Self::open_within(Some(DEFAULT_ENABLE_TIMEOUT))
74    }
75
76    /// As [`open`](Self::open), waiting up to `timeout` for the seat to
77    /// activate; `None` waits indefinitely.
78    ///
79    /// Without a bound, a backend that connects but never activates the seat
80    /// blocked forever, and SIGINT could not break the wait, so the process
81    /// kept DRM master (drm-cxx `60c6f10`). On timeout the seat is closed.
82    ///
83    /// # Errors
84    ///
85    /// As [`open`](Self::open).
86    pub fn open_within(timeout: Option<Duration>) -> Result<Self, SessionError> {
87        let inbox: Inbox = Rc::new(RefCell::new(Vec::new()));
88        let listener = {
89            let inbox = Rc::clone(&inbox);
90            move |_: &mut libseat::SeatRef, event: libseat::SeatEvent| {
91                // Nothing is done here beyond recording it. libseat is calling
92                // us from inside its own dispatch, and acting now would mean
93                // re-entering it; the session picks these up afterwards.
94                inbox.borrow_mut().push(match event {
95                    libseat::SeatEvent::Enable => RawEvent::Enable,
96                    libseat::SeatEvent::Disable => RawEvent::Disable,
97                });
98            }
99        };
100
101        let mut seat = libseat::Seat::open(listener).map_err(|errno| {
102            // Which backend refused, and why, is the whole of the diagnosis
103            // when a seat is expected and does not appear.
104            drmkit_log::log_debug!("no seat: {errno}");
105            SessionError::NoBackend
106        })?;
107        let poll_fd = seat.get_fd().ok().map(|fd| fd.as_raw_fd());
108        let mut backend = Self {
109            seat,
110            devices: HashMap::new(),
111            next_id: 1,
112            inbox,
113            poll_fd,
114        };
115        // Dropped on a timeout, which closes the seat.
116        backend.wait_for_activation(timeout)?;
117        Ok(backend)
118    }
119
120    /// The seat's name, for logging.
121    pub fn name(&mut self) -> &str {
122        self.seat.name()
123    }
124
125    /// Block until the seat says it is ours.
126    ///
127    /// A freshly opened seat is not active: libseat sends the first enable over
128    /// the connection, so it only arrives once something dispatches. Skipping
129    /// this leaves the first `open_device` racing the activation, which is a
130    /// startup that fails on a loaded machine and works on an idle one.
131    ///
132    /// The enable is swallowed rather than queued. [`Session`](crate::Session)
133    /// starts active, and a resume it never paused for would have it close and
134    /// reopen every device for nothing.
135    fn wait_for_activation(&mut self, timeout: Option<Duration>) -> Result<(), SessionError> {
136        let Self { seat, inbox, .. } = self;
137        wait_until_active(
138            |timeout_ms| {
139                seat.dispatch(timeout_ms)
140                    .map(|_| ())
141                    .map_err(|errno| SessionError::Seat(format!("dispatch: {errno}")))
142            },
143            inbox,
144            timeout,
145        )?;
146        drmkit_log::log_info!("seat {} is ours", self.seat.name());
147        Ok(())
148    }
149}
150
151/// Dispatch until the seat's first enable arrives in `inbox`, or `timeout`
152/// passes; `None` waits indefinitely.
153///
154/// `dispatch` is the seat's, taking a timeout in milliseconds with `-1` to
155/// block. While bounded, no single dispatch outlasts [`DISPATCH_SLICE_MS`] or
156/// the time left, so the deadline is kept. A timeout is
157/// [`SessionError::NoBackend`], the "no seat" a caller already falls back on.
158fn wait_until_active(
159    mut dispatch: impl FnMut(i32) -> Result<(), SessionError>,
160    inbox: &Inbox,
161    timeout: Option<Duration>,
162) -> Result<(), SessionError> {
163    let deadline = timeout.map(|timeout| Instant::now() + timeout);
164    loop {
165        let timeout_ms = match deadline {
166            None => -1,
167            Some(deadline) => {
168                let left = deadline.saturating_duration_since(Instant::now());
169                if left.is_zero() {
170                    drmkit_log::log_warn!(
171                        "seat not enabled within {} ms; open devices directly instead",
172                        timeout.unwrap_or_default().as_millis()
173                    );
174                    return Err(SessionError::NoBackend);
175                }
176                // At most DISPATCH_SLICE_MS, so it fits.
177                i32::try_from(left.as_millis().min(DISPATCH_SLICE_MS)).unwrap_or(0)
178            }
179        };
180        dispatch(timeout_ms)?;
181        if drain_through_activation(&mut inbox.borrow_mut()) {
182            return Ok(());
183        }
184    }
185}
186
187/// Drop everything up to and including the seat's first enable.
188///
189/// Returns whether one was there. What is left is what happened *after* the
190/// seat became ours, which the session does have to hear about -- a seat that
191/// enables and immediately disables is a switch away that has already
192/// happened, and swallowing it wholesale would leave a session that thinks it
193/// owns a display it does not.
194fn drain_through_activation(events: &mut Vec<RawEvent>) -> bool {
195    if let Some(enable) = events.iter().position(|event| *event == RawEvent::Enable) {
196        events.drain(..=enable);
197        true
198    } else {
199        // A disable before the first enable describes a seat that was never
200        // ours. There is nothing for the session to stop doing.
201        events.clear();
202        false
203    }
204}
205
206impl Drop for LibseatBackend {
207    fn drop(&mut self) {
208        // Closing the seat releases these anyway. Done explicitly so that stays
209        // true of a backend that outlives its devices for a while, and so the
210        // count the seat is holding matches the count this thinks it has.
211        for (_, device) in self.devices.drain() {
212            let _ = self.seat.close_device(device);
213        }
214    }
215}
216
217impl Backend for LibseatBackend {
218    fn open_device(&mut self, path: &Path) -> Result<(DeviceId, RawFd), SessionError> {
219        // The crate builds the C string with `unwrap`, so a path that is not
220        // UTF-8, or has a NUL in it, panics inside the binding. Neither can
221        // come from `/dev/dri`, but neither has to reach it either.
222        if path.to_str().is_none_or(|path| path.contains('\0')) {
223            return Err(SessionError::Seat(format!(
224                "{} is not a path libseat can take",
225                path.display()
226            )));
227        }
228        let device = self
229            .seat
230            .open_device(&path)
231            .map_err(|errno| SessionError::Seat(format!("open {}: {errno}", path.display())))?;
232        let fd = device.as_fd().as_raw_fd();
233        let id = self.next_id;
234        self.next_id += 1;
235        self.devices.insert(id, device);
236        Ok((DeviceId(id), fd))
237    }
238
239    fn close_device(&mut self, id: DeviceId) -> Result<(), SessionError> {
240        // One this session does not hold is not an error to pass on: it is
241        // already closed, which is what was asked for.
242        let Some(device) = self.devices.remove(&id.0) else {
243            return Ok(());
244        };
245        self.seat
246            .close_device(device)
247            .map_err(|errno| SessionError::Seat(format!("close: {errno}")))
248    }
249
250    fn acknowledge_pause(&mut self) -> Result<(), SessionError> {
251        self.seat
252            .disable()
253            .map_err(|errno| SessionError::Seat(format!("disable: {errno}")))
254    }
255
256    fn switch_session(&mut self, session: i32) -> Result<(), SessionError> {
257        self.seat
258            .switch_session(session)
259            .map_err(|errno| SessionError::Seat(format!("switch to {session}: {errno}")))
260    }
261
262    fn poll_fd(&self) -> Option<RawFd> {
263        self.poll_fd
264    }
265
266    fn dispatch(
267        &mut self,
268        timeout_ms: i32,
269        events: &mut Vec<RawEvent>,
270    ) -> Result<(), SessionError> {
271        self.seat
272            .dispatch(timeout_ms)
273            .map_err(|errno| SessionError::Seat(format!("dispatch: {errno}")))?;
274        // Whatever the listener recorded while that ran.
275        events.append(&mut self.inbox.borrow_mut());
276        Ok(())
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn activation_swallows_the_enable_that_announced_it() {
286        // The session starts active. A resume it never paused for would have it
287        // close and reopen every device for nothing.
288        let mut events = vec![RawEvent::Enable];
289        assert!(drain_through_activation(&mut events));
290        assert!(events.is_empty());
291    }
292
293    #[test]
294    fn a_switch_away_during_startup_still_reaches_the_session() {
295        // Rare, but it is the case that matters: swallow this and the session
296        // thinks it owns a display that now belongs to someone else.
297        let mut events = vec![RawEvent::Enable, RawEvent::Disable];
298        assert!(drain_through_activation(&mut events));
299        assert_eq!(events, vec![RawEvent::Disable]);
300    }
301
302    #[test]
303    fn without_an_enable_the_seat_is_not_ours_yet() {
304        let mut events = vec![RawEvent::Disable];
305        assert!(!drain_through_activation(&mut events));
306        assert!(events.is_empty(), "and nothing is left to act on");
307    }
308
309    /// A seat that answers but never enables -- seatd over SSH, with no VT to
310    /// take -- gives up within the bound, as "no seat", and never blocks
311    /// longer than the time left. Port of upstream's
312    /// `OpenTimesOutWhenSeatNeverEnabled` (`60c6f10`).
313    #[test]
314    fn a_seat_that_never_enables_times_out_as_no_seat() {
315        let inbox: Inbox = Rc::new(RefCell::new(Vec::new()));
316        let mut waits = Vec::new();
317        let started = Instant::now();
318        let result = wait_until_active(
319            |timeout_ms| {
320                waits.push(timeout_ms);
321                std::thread::sleep(Duration::from_millis(
322                    u64::try_from(timeout_ms.max(0)).unwrap_or(0),
323                ));
324                Ok(())
325            },
326            &inbox,
327            Some(Duration::from_millis(50)),
328        );
329        assert_eq!(result, Err(SessionError::NoBackend));
330        assert!(started.elapsed() < Duration::from_secs(2));
331        assert!(!waits.is_empty());
332        assert!(
333            waits.iter().all(|ms| (0..=50).contains(ms)),
334            "no dispatch may block past the deadline: {waits:?}"
335        );
336    }
337
338    /// The first enable ends the wait, and what came after it stays for the
339    /// session.
340    #[test]
341    fn the_first_enable_ends_the_wait() {
342        let inbox: Inbox = Rc::new(RefCell::new(Vec::new()));
343        let mut calls = 0;
344        let result = wait_until_active(
345            |_| {
346                calls += 1;
347                if calls == 3 {
348                    inbox
349                        .borrow_mut()
350                        .extend([RawEvent::Enable, RawEvent::Disable]);
351                }
352                Ok(())
353            },
354            &inbox,
355            Some(DEFAULT_ENABLE_TIMEOUT),
356        );
357        assert_eq!(result, Ok(()));
358        assert_eq!(calls, 3);
359        assert_eq!(*inbox.borrow(), [RawEvent::Disable]);
360    }
361
362    /// Unbounded, each dispatch blocks until the seat says something.
363    #[test]
364    fn an_unbounded_wait_blocks_in_dispatch() {
365        let inbox: Inbox = Rc::new(RefCell::new(Vec::new()));
366        let mut waits = Vec::new();
367        let result = wait_until_active(
368            |timeout_ms| {
369                waits.push(timeout_ms);
370                inbox.borrow_mut().push(RawEvent::Enable);
371                Ok(())
372            },
373            &inbox,
374            None,
375        );
376        assert_eq!(result, Ok(()));
377        assert_eq!(waits, [-1]);
378    }
379
380    /// A failed dispatch ends the wait with its error, not a timeout.
381    #[test]
382    fn a_failed_dispatch_is_reported() {
383        let inbox: Inbox = Rc::new(RefCell::new(Vec::new()));
384        let result = wait_until_active(
385            |_| Err(SessionError::Seat("dispatch: EIO".to_owned())),
386            &inbox,
387            Some(DEFAULT_ENABLE_TIMEOUT),
388        );
389        assert_eq!(result, Err(SessionError::Seat("dispatch: EIO".to_owned())));
390    }
391}