1#[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
28pub(crate) const MAX_CONNECTIONS: usize = 64;
30
31const BACK_OFF: Duration = Duration::from_secs(1);
34
35#[derive(Clone)]
49pub struct SocketServer {
50 inner: Rc<Inner>,
51}
52
53type OnConnection = Rc<dyn Fn(&Cx, Socket)>;
55
56struct Inner {
57 shared: Option<Rc<Shared>>,
59 path: PathBuf,
60 cx: Cx,
63 listener: RefCell<Option<UnixListener>>,
66 file: Cell<Option<(u64, u64)>>,
68 stopped: Cell<bool>,
71 source: Cell<Option<RegistrationToken>>,
74 open: Rc<Cell<usize>>,
76 on_connection: RefCell<Option<(OnConnection, &'static Location<'static>)>>,
77}
78
79pub(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 cx.owner().signal(StopOnDrop(Rc::clone(&inner)));
102 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
114struct StopOnDrop(Rc<Inner>);
116
117impl Drop for StopOnDrop {
118 fn drop(&mut self) {
119 let on_connection = self.0.on_connection.borrow_mut().take();
122 drop(on_connection);
123 self.0.stop();
124 }
125}
126
127struct 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 #[track_caller]
165 pub fn on_connection(self, on_connection: impl Fn(&Cx, Socket) + 'static) -> SocketServer {
166 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 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 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 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 fn accept(self: &Rc<Self>) {
232 loop {
233 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 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 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 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 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
321fn 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
346fn 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}