Skip to main content

crabshell_services/
socket_server.rs

1//! Unix socket servers a config runs, as Quickshell's `SocketServer`: each
2//! client that connects is a [`Socket`].
3
4#[cfg(test)]
5mod tests;
6
7use std::cell::{Cell, RefCell};
8use std::io::ErrorKind;
9use std::os::fd::AsFd;
10use std::os::unix::fs::{FileTypeExt, MetadataExt};
11use std::os::unix::net::{UnixListener, UnixStream};
12use std::panic::{self, AssertUnwindSafe, Location};
13use std::path::{Path, PathBuf};
14use std::rc::Rc;
15use std::sync::Once;
16use std::time::{Duration, Instant};
17
18use calloop::timer::TimeoutAction;
19use calloop::{Interest, RegistrationToken};
20use crabshell_ui::Cx;
21use rustix::io::Errno;
22use rustix::net::{AddressFamily, SocketAddrUnix, SocketFlags, SocketType};
23
24use crate::Shared;
25use crate::lines::panic_message;
26use crate::socket::{self, Socket, Sockets};
27
28/// The most connections open at once. A client past it is closed at once.
29pub(crate) const MAX_CONNECTIONS: usize = 64;
30
31/// How long the server rests after an accept that failed and left the
32/// client waiting, as when the shell is out of file descriptors.
33const BACK_OFF: Duration = Duration::from_secs(1);
34
35/// A server on a Unix socket, from `cx.socket_server(path)`, as
36/// Quickshell's `SocketServer`. It listens from the start and hands each
37/// client that connects to [`on_connection`](Self::on_connection) as a
38/// [`Socket`]. A clone is cheap and shares the server.
39///
40/// It stops when the context that made it goes, or at
41/// [`close`](Self::close): every connection closes, and the socket file
42/// goes if it is still the one the server made. A socket file already at
43/// the path is replaced if nothing listens on it. One that something
44/// listens on, or anything that isn't a socket, is left alone and logged,
45/// and the server never listens. The file gets the permissions the
46/// shell's umask leaves, so keep it in a directory only the user can
47/// reach, such as `$XDG_RUNTIME_DIR`.
48#[derive(Clone)]
49pub struct SocketServer {
50  inner: Rc<Inner>,
51}
52
53/// What a config does with each connection.
54type OnConnection = Rc<dyn Fn(&Cx, Socket)>;
55
56struct Inner {
57  /// `None` when the shell provided no services.
58  shared: Option<Rc<Shared>>,
59  path: PathBuf,
60  /// The server's own context. Each connection's is made inside it, so
61  /// disposing it ends them all.
62  cx: Cx,
63  /// Taken when the server stops, so a client still waiting is turned
64  /// away.
65  listener: RefCell<Option<UnixListener>>,
66  /// The socket file's device and inode, so only ours is ever removed.
67  file: Option<(u64, u64)>,
68  /// The loop source that waits for clients, or the timer that brings it
69  /// back after a back-off.
70  source: Cell<Option<RegistrationToken>>,
71  /// How many connections' contexts are alive.
72  open: Rc<Cell<usize>>,
73  on_connection: RefCell<Option<(OnConnection, &'static Location<'static>)>>,
74}
75
76/// `cx.socket_server(path)`.
77pub(crate) fn socket_server(cx: &Cx, path: PathBuf) -> SocketServer {
78  let shared = cx.service::<Sockets>().map(|sockets| Rc::clone(&sockets.0));
79  if shared.is_none() {
80    static LOGGED: Once = Once::new();
81    LOGGED.call_once(|| {
82      tracing::warn!("cx.socket_server() needs the services the shell provides; it never listens");
83    });
84  }
85  let bound = shared.as_ref().and_then(|_| {
86    bind(&path)
87      .inspect_err(|error| {
88        let path = path.display();
89        tracing::warn!(%path, %error, "can't listen on the socket");
90      })
91      .ok()
92  });
93  let (listener, file) = bound.unzip();
94  let cx = cx.child();
95  let inner = Rc::new(Inner {
96    shared,
97    path,
98    cx: cx.clone(),
99    listener: RefCell::new(listener),
100    file,
101    source: Cell::new(None),
102    open: Rc::default(),
103    on_connection: RefCell::new(None),
104  });
105  // Dropped with the server's context, which stops it.
106  cx.owner().signal(StopOnDrop(Rc::clone(&inner)));
107  inner.listen();
108  SocketServer { inner }
109}
110
111/// Stops the server when its context's owner drops it.
112struct StopOnDrop(Rc<Inner>);
113
114impl Drop for StopOnDrop {
115  fn drop(&mut self) {
116    // Dropped outside the borrow: it may hold this server, and its drop
117    // may use it.
118    let on_connection = self.0.on_connection.borrow_mut().take();
119    drop(on_connection);
120    self.0.stop();
121  }
122}
123
124/// Counts a connection while its context lives.
125struct Open(Rc<Cell<usize>>);
126
127impl Open {
128  fn count(open: &Rc<Cell<usize>>) -> Open {
129    open.set(open.get() + 1);
130    Open(Rc::clone(open))
131  }
132}
133
134impl Drop for Open {
135  fn drop(&mut self) {
136    self.0.set(self.0.get() - 1);
137  }
138}
139
140impl SocketServer {
141  /// Calls `on_connection` with each client that connects: a context of
142  /// the connection's own, which goes on the loop's turn after the
143  /// connection ends, and the connection as a [`Socket`], connected, for
144  /// `on_line` or `on_split`, `write` and `close`. Lines are capped as a
145  /// `Socket`'s are. The socket's `connected` signal goes with that
146  /// context too, so code outside it reads it with `try_get`. A client
147  /// that connects while nothing handles it is closed at once.
148  ///
149  /// A client that only stops sending, as `printf cmd | socat -
150  /// UNIX-CONNECT:path` does, has its last line passed on, and the
151  /// connection stays open for the reply until the config closes it, a
152  /// write fails or 5 s pass, as the shell's own IPC socket waits. One
153  /// that hangs up ends the connection at once, whether it was still
154  /// sending or, as socat does once its wait for a reply ends, had
155  /// stopped.
156  ///
157  /// It runs on the main thread. If it panics, that is logged with the
158  /// server's path and where `on_connection` was called, that connection
159  /// is closed, and it isn't called again; the server and its other
160  /// connections go on.
161  #[track_caller]
162  pub fn on_connection(self, on_connection: impl Fn(&Cx, Socket) + 'static) -> SocketServer {
163    // Kept only while the server runs, so a handler that holds it can't
164    // keep it alive.
165    if !self.inner.cx.owner().is_disposed() {
166      let handler: OnConnection = Rc::new(on_connection);
167      let older = (self.inner.on_connection)
168        .borrow_mut()
169        .replace((handler, Location::caller()));
170      drop(older);
171    }
172    self
173  }
174
175  /// Stops it, as its context going does: every connection closes, and
176  /// the socket file goes. Nothing opens it again.
177  pub fn close(&self) {
178    self.inner.cx.owner().dispose();
179  }
180}
181
182impl Inner {
183  fn event_loop(&self) -> Option<Box<dyn crate::EventLoop>> {
184    self.shared.as_ref()?.event_loop()
185  }
186
187  /// Waits for clients, unless the server stopped.
188  fn listen(self: &Rc<Self>) {
189    let Some(event_loop) = self.event_loop() else {
190      return;
191    };
192    let fd = match self
193      .listener
194      .borrow()
195      .as_ref()
196      .map(|listener| listener.as_fd().try_clone_to_owned())
197    {
198      Some(Ok(fd)) => fd,
199      Some(Err(error)) => {
200        let path = self.path.display();
201        return tracing::warn!(%path, %error, "can't listen on the socket");
202      }
203      None => return,
204    };
205    let inner = Rc::clone(self);
206    let ready = Box::new(move || inner.accept());
207    self
208      .source
209      .set(event_loop.insert_fd(fd, Interest::READ, ready));
210  }
211
212  /// Takes every client waiting.
213  fn accept(self: &Rc<Self>) {
214    loop {
215      // Not borrowed while a handler runs: it may close the server.
216      let accepted = self.listener.borrow().as_ref().map(UnixListener::accept);
217      match accepted {
218        Some(Ok((stream, _))) => self.serve(stream),
219        Some(Err(error)) if error.kind() == ErrorKind::WouldBlock => return,
220        Some(Err(error))
221          if matches!(
222            error.kind(),
223            ErrorKind::Interrupted | ErrorKind::ConnectionAborted
224          ) => {}
225        Some(Err(error)) => {
226          let path = self.path.display();
227          tracing::warn!(%path, %error, "can't accept a connection; trying again in 1 s");
228          return self.back_off();
229        }
230        None => return,
231      }
232    }
233  }
234
235  /// Stops waiting for clients for [`BACK_OFF`], since the one waiting
236  /// would wake the loop again at once.
237  fn back_off(self: &Rc<Self>) {
238    let Some(event_loop) = self.event_loop() else {
239      return;
240    };
241    if let Some(token) = self.source.take() {
242      event_loop.remove(token);
243    }
244    let inner = Rc::clone(self);
245    let again = Box::new(move || {
246      inner.source.set(None);
247      inner.listen();
248      TimeoutAction::Drop
249    });
250    self
251      .source
252      .set(event_loop.insert_timer(Instant::now() + BACK_OFF, again));
253  }
254
255  /// Hands a client to the config's handler, under a context of its own.
256  fn serve(self: &Rc<Self>, stream: UnixStream) {
257    let path = self.path.display();
258    if self.open.get() >= MAX_CONNECTIONS {
259      return tracing::warn!(%path, "refused a connection: {MAX_CONNECTIONS} are open already");
260    }
261    let handler = self.on_connection.borrow().clone();
262    let (Some((handler, at)), Some(shared)) = (handler, &self.shared) else {
263      return tracing::info!(%path, "closed a connection, as nothing handles it");
264    };
265    let cx = self.cx.child();
266    cx.owner().signal(Open::count(&self.open));
267    let Some(socket) = socket::accepted(&cx, shared, self.path.clone(), stream) else {
268      return cx.owner().dispose();
269    };
270    let handed = socket.clone();
271    if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(|| handler(&cx, handed))) {
272      let message = panic_message(payload.as_ref());
273      tracing::error!("socket server {path} on_connection (called at {at}) panicked: {message}");
274      let mut current = self.on_connection.borrow_mut();
275      // Unless it set a new one meanwhile.
276      let disabled = current
277        .as_ref()
278        .is_some_and(|(now, _)| Rc::ptr_eq(now, &handler))
279        .then(|| current.take());
280      drop(current);
281      drop(disabled);
282      socket.close();
283    }
284  }
285
286  /// Stops listening and removes the socket file if it is still ours.
287  fn stop(&self) {
288    if let (Some(token), Some(event_loop)) = (self.source.take(), self.event_loop()) {
289      event_loop.remove(token);
290    }
291    let listener = self.listener.borrow_mut().take();
292    if let (Some(_), Some((dev, ino))) = (listener, self.file) {
293      let ours = std::fs::symlink_metadata(&self.path)
294        .is_ok_and(|meta| (meta.dev(), meta.ino()) == (dev, ino));
295      if ours {
296        let _ = std::fs::remove_file(&self.path);
297      }
298    }
299  }
300}
301
302/// Listens at `path`, in place of a socket file nobody listens on.
303fn bind(path: &Path) -> std::io::Result<(UnixListener, (u64, u64))> {
304  match std::fs::symlink_metadata(path) {
305    Ok(meta) if !meta.file_type().is_socket() => {
306      let why = "something that isn't a socket is there";
307      return Err(std::io::Error::new(ErrorKind::AlreadyExists, why));
308    }
309    Ok(_) if listening(path)? => {
310      let why = "another program listens there";
311      return Err(std::io::Error::new(ErrorKind::AddrInUse, why));
312    }
313    Ok(_) => {
314      std::fs::remove_file(path)?;
315      let path = path.display();
316      tracing::info!(%path, "replaced a socket nobody listened on");
317    }
318    Err(error) if error.kind() == ErrorKind::NotFound => {}
319    Err(error) => return Err(error),
320  }
321  let listener = UnixListener::bind(path)?;
322  listener.set_nonblocking(true)?;
323  let meta = std::fs::symlink_metadata(path)?;
324  Ok((listener, (meta.dev(), meta.ino())))
325}
326
327/// Whether something takes connections at `path`, found without waiting:
328/// a full backlog counts as listening.
329fn listening(path: &Path) -> std::io::Result<bool> {
330  let flags = SocketFlags::NONBLOCK | SocketFlags::CLOEXEC;
331  let probe = rustix::net::socket_with(AddressFamily::UNIX, SocketType::STREAM, flags, None)?;
332  let refused = rustix::net::connect(&probe, &SocketAddrUnix::new(path)?);
333  Ok(!matches!(refused, Err(Errno::CONNREFUSED | Errno::NOENT)))
334}