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: Cell<Option<(u64, u64)>>,
68  /// Closed, so a bind that waited for the shell to run alone doesn't
69  /// happen.
70  stopped: Cell<bool>,
71  /// The loop source that waits for clients, or the timer that brings it
72  /// back after a back-off.
73  source: Cell<Option<RegistrationToken>>,
74  /// How many connections' contexts are alive.
75  open: Rc<Cell<usize>>,
76  on_connection: RefCell<Option<(OnConnection, &'static Location<'static>)>>,
77}
78
79/// `cx.socket_server(path)`.
80pub(crate) fn socket_server(cx: &Cx, path: PathBuf) -> SocketServer {
81  let shared = cx.service::<Sockets>().map(|sockets| Rc::clone(&sockets.0));
82  if shared.is_none() {
83    static LOGGED: Once = Once::new();
84    LOGGED.call_once(|| {
85      tracing::warn!("cx.socket_server() needs the services the shell provides; it never listens");
86    });
87  }
88  let cx = cx.child();
89  let inner = Rc::new(Inner {
90    shared: shared.clone(),
91    path,
92    cx: cx.clone(),
93    listener: RefCell::new(None),
94    file: Cell::new(None),
95    stopped: Cell::new(false),
96    source: Cell::new(None),
97    open: Rc::default(),
98    on_connection: RefCell::new(None),
99  });
100  // Dropped with the server's context, which stops it.
101  cx.owner().signal(StopOnDrop(Rc::clone(&inner)));
102  // The old shell of a reload listens there until it exits.
103  let weak = Rc::downgrade(&inner);
104  if let Some(shared) = shared {
105    shared.when_alone(move || {
106      if let Some(inner) = weak.upgrade().filter(|inner| !inner.stopped.get()) {
107        inner.bind();
108      }
109    });
110  }
111  SocketServer { inner }
112}
113
114/// Stops the server when its context's owner drops it.
115struct StopOnDrop(Rc<Inner>);
116
117impl Drop for StopOnDrop {
118  fn drop(&mut self) {
119    // Dropped outside the borrow: it may hold this server, and its drop
120    // may use it.
121    let on_connection = self.0.on_connection.borrow_mut().take();
122    drop(on_connection);
123    self.0.stop();
124  }
125}
126
127/// Counts a connection while its context lives.
128struct Open(Rc<Cell<usize>>);
129
130impl Open {
131  fn count(open: &Rc<Cell<usize>>) -> Open {
132    open.set(open.get() + 1);
133    Open(Rc::clone(open))
134  }
135}
136
137impl Drop for Open {
138  fn drop(&mut self) {
139    self.0.set(self.0.get() - 1);
140  }
141}
142
143impl SocketServer {
144  /// Calls `on_connection` with each client that connects: a context of
145  /// the connection's own, which goes on the loop's turn after the
146  /// connection ends, and the connection as a [`Socket`], connected, for
147  /// `on_line` or `on_split`, `write` and `close`. Lines are capped as a
148  /// `Socket`'s are. The socket's `connected` signal goes with that
149  /// context too, so code outside it reads it with `try_get`. A client
150  /// that connects while nothing handles it is closed at once.
151  ///
152  /// A client that only stops sending, as `printf cmd | socat -
153  /// UNIX-CONNECT:path` does, has its last line passed on, and the
154  /// connection stays open for the reply until the config closes it, a
155  /// write fails or 5 s pass, as the shell's own IPC socket waits. One
156  /// that hangs up ends the connection at once, whether it was still
157  /// sending or, as socat does once its wait for a reply ends, had
158  /// stopped.
159  ///
160  /// It runs on the main thread. If it panics, that is logged with the
161  /// server's path and where `on_connection` was called, that connection
162  /// is closed, and it isn't called again; the server and its other
163  /// connections go on.
164  #[track_caller]
165  pub fn on_connection(self, on_connection: impl Fn(&Cx, Socket) + 'static) -> SocketServer {
166    // Kept only while the server runs, so a handler that holds it can't
167    // keep it alive.
168    if !self.inner.cx.owner().is_disposed() {
169      let handler: OnConnection = Rc::new(on_connection);
170      let older = (self.inner.on_connection)
171        .borrow_mut()
172        .replace((handler, Location::caller()));
173      drop(older);
174    }
175    self
176  }
177
178  /// Stops it, as its context going does: every connection closes, and
179  /// the socket file goes. Nothing opens it again.
180  pub fn close(&self) {
181    self.inner.cx.owner().dispose();
182  }
183}
184
185impl Inner {
186  fn event_loop(&self) -> Option<Box<dyn crate::EventLoop>> {
187    self.shared.as_ref()?.event_loop()
188  }
189
190  /// Takes the socket and waits for clients. A failure is logged.
191  fn bind(self: &Rc<Self>) {
192    match bind(&self.path) {
193      Ok((listener, file)) => {
194        *self.listener.borrow_mut() = Some(listener);
195        self.file.set(Some(file));
196        self.listen();
197      }
198      Err(error) => {
199        let path = self.path.display();
200        tracing::warn!(%path, %error, "can't listen on the socket");
201      }
202    }
203  }
204
205  /// Waits for clients, unless the server stopped.
206  fn listen(self: &Rc<Self>) {
207    let Some(event_loop) = self.event_loop() else {
208      return;
209    };
210    let fd = match self
211      .listener
212      .borrow()
213      .as_ref()
214      .map(|listener| listener.as_fd().try_clone_to_owned())
215    {
216      Some(Ok(fd)) => fd,
217      Some(Err(error)) => {
218        let path = self.path.display();
219        return tracing::warn!(%path, %error, "can't listen on the socket");
220      }
221      None => return,
222    };
223    let inner = Rc::clone(self);
224    let ready = Box::new(move || inner.accept());
225    self
226      .source
227      .set(event_loop.insert_fd(fd, Interest::READ, ready));
228  }
229
230  /// Takes every client waiting.
231  fn accept(self: &Rc<Self>) {
232    loop {
233      // Not borrowed while a handler runs: it may close the server.
234      let accepted = self.listener.borrow().as_ref().map(UnixListener::accept);
235      match accepted {
236        Some(Ok((stream, _))) => self.serve(stream),
237        Some(Err(error)) if error.kind() == ErrorKind::WouldBlock => return,
238        Some(Err(error))
239          if matches!(
240            error.kind(),
241            ErrorKind::Interrupted | ErrorKind::ConnectionAborted
242          ) => {}
243        Some(Err(error)) => {
244          let path = self.path.display();
245          tracing::warn!(%path, %error, "can't accept a connection; trying again in 1 s");
246          return self.back_off();
247        }
248        None => return,
249      }
250    }
251  }
252
253  /// Stops waiting for clients for [`BACK_OFF`], since the one waiting
254  /// would wake the loop again at once.
255  fn back_off(self: &Rc<Self>) {
256    let Some(event_loop) = self.event_loop() else {
257      return;
258    };
259    if let Some(token) = self.source.take() {
260      event_loop.remove(token);
261    }
262    let inner = Rc::clone(self);
263    let again = Box::new(move || {
264      inner.source.set(None);
265      inner.listen();
266      TimeoutAction::Drop
267    });
268    self
269      .source
270      .set(event_loop.insert_timer(Instant::now() + BACK_OFF, again));
271  }
272
273  /// Hands a client to the config's handler, under a context of its own.
274  fn serve(self: &Rc<Self>, stream: UnixStream) {
275    let path = self.path.display();
276    if self.open.get() >= MAX_CONNECTIONS {
277      return tracing::warn!(%path, "refused a connection: {MAX_CONNECTIONS} are open already");
278    }
279    let handler = self.on_connection.borrow().clone();
280    let (Some((handler, at)), Some(shared)) = (handler, &self.shared) else {
281      return tracing::info!(%path, "closed a connection, as nothing handles it");
282    };
283    let cx = self.cx.child();
284    cx.owner().signal(Open::count(&self.open));
285    let Some(socket) = socket::accepted(&cx, shared, self.path.clone(), stream) else {
286      return cx.owner().dispose();
287    };
288    let handed = socket.clone();
289    if let Err(payload) = panic::catch_unwind(AssertUnwindSafe(|| handler(&cx, handed))) {
290      let message = panic_message(payload.as_ref());
291      tracing::error!("socket server {path} on_connection (called at {at}) panicked: {message}");
292      let mut current = self.on_connection.borrow_mut();
293      // Unless it set a new one meanwhile.
294      let disabled = current
295        .as_ref()
296        .is_some_and(|(now, _)| Rc::ptr_eq(now, &handler))
297        .then(|| current.take());
298      drop(current);
299      drop(disabled);
300      socket.close();
301    }
302  }
303
304  /// Stops listening and removes the socket file if it is still ours.
305  fn stop(&self) {
306    self.stopped.set(true);
307    if let (Some(token), Some(event_loop)) = (self.source.take(), self.event_loop()) {
308      event_loop.remove(token);
309    }
310    let listener = self.listener.borrow_mut().take();
311    if let (Some(_), Some((dev, ino))) = (listener, self.file.get()) {
312      let ours = std::fs::symlink_metadata(&self.path)
313        .is_ok_and(|meta| (meta.dev(), meta.ino()) == (dev, ino));
314      if ours {
315        let _ = std::fs::remove_file(&self.path);
316      }
317    }
318  }
319}
320
321/// Listens at `path`, in place of a socket file nobody listens on.
322fn bind(path: &Path) -> std::io::Result<(UnixListener, (u64, u64))> {
323  match std::fs::symlink_metadata(path) {
324    Ok(meta) if !meta.file_type().is_socket() => {
325      let why = "something that isn't a socket is there";
326      return Err(std::io::Error::new(ErrorKind::AlreadyExists, why));
327    }
328    Ok(_) if listening(path)? => {
329      let why = "another program listens there";
330      return Err(std::io::Error::new(ErrorKind::AddrInUse, why));
331    }
332    Ok(_) => {
333      std::fs::remove_file(path)?;
334      let path = path.display();
335      tracing::info!(%path, "replaced a socket nobody listened on");
336    }
337    Err(error) if error.kind() == ErrorKind::NotFound => {}
338    Err(error) => return Err(error),
339  }
340  let listener = UnixListener::bind(path)?;
341  listener.set_nonblocking(true)?;
342  let meta = std::fs::symlink_metadata(path)?;
343  Ok((listener, (meta.dev(), meta.ino())))
344}
345
346/// Whether something takes connections at `path`, found without waiting:
347/// a full backlog counts as listening.
348fn listening(path: &Path) -> std::io::Result<bool> {
349  let flags = SocketFlags::NONBLOCK | SocketFlags::CLOEXEC;
350  let probe = rustix::net::socket_with(AddressFamily::UNIX, SocketType::STREAM, flags, None)?;
351  let refused = rustix::net::connect(&probe, &SocketAddrUnix::new(path)?);
352  Ok(!matches!(refused, Err(Errno::CONNREFUSED | Errno::NOENT)))
353}