1mod datagram;
41mod endpoint;
42mod json;
43mod net;
44mod rendezvous;
45mod ring;
46mod stdio;
47#[cfg(unix)]
48mod unix;
49#[cfg(windows)]
50mod windows;
51
52pub use endpoint::Endpoint;
53
54use std::collections::BTreeMap;
55use std::fmt;
56use std::io::{self, Read, Write};
57use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
58use std::sync::mpsc;
59use std::sync::{Arc, Mutex, OnceLock};
60use std::thread;
61use std::time::Duration;
62
63pub const KINDS: &[&str] = &[
65 "tcp", "udp", "unix", "pipe", "fifo", "stdio", "exec", "shm", "mmap", "file", "signal", "mq",
66 "sysvmq", "mailslot", "copydata", "alpc",
67];
68
69pub trait Transport: Send + Sync + fmt::Debug {
74 fn read(&self, buf: &mut [u8], timeout: Option<Duration>) -> io::Result<usize>;
78 fn write(&self, buf: &[u8]) -> io::Result<usize>;
80 fn flush(&self) -> io::Result<()> {
82 Ok(())
83 }
84 fn close_write(&self) -> io::Result<()>;
86 fn shutdown(&self);
88 fn kind(&self) -> &'static str;
90}
91
92#[derive(Clone)]
96pub struct IpcStream {
97 inner: Arc<dyn Transport>,
98 read_timeout: Option<Duration>,
99}
100
101impl fmt::Debug for IpcStream {
102 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103 formatter
104 .debug_struct("IpcStream")
105 .field("transport", &self.inner)
106 .field("read_timeout", &self.read_timeout)
107 .finish()
108 }
109}
110
111impl IpcStream {
112 pub fn new(transport: impl Transport + 'static) -> Self {
114 Self::from_arc(Arc::new(transport))
115 }
116
117 pub fn from_arc(transport: Arc<dyn Transport>) -> Self {
119 Self {
120 inner: transport,
121 read_timeout: None,
122 }
123 }
124
125 pub fn kind(&self) -> &'static str {
127 self.inner.kind()
128 }
129
130 pub fn transport(&self) -> &Arc<dyn Transport> {
132 &self.inner
133 }
134
135 pub fn set_read_timeout(&mut self, timeout: Option<Duration>) {
138 self.read_timeout = timeout;
139 }
140
141 pub fn read_timeout(&self) -> Option<Duration> {
143 self.read_timeout
144 }
145
146 pub fn close_write(&self) -> io::Result<()> {
148 self.inner.close_write()
149 }
150
151 pub fn shutdown(&self) {
153 self.inner.shutdown()
154 }
155}
156
157impl Read for IpcStream {
158 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
159 if buf.is_empty() {
160 return Ok(0);
161 }
162 loop {
163 match self.inner.read(buf, self.read_timeout) {
164 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
165 result => return result,
166 }
167 }
168 }
169}
170
171impl Write for IpcStream {
172 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
173 if buf.is_empty() {
174 return Ok(0);
175 }
176 loop {
177 match self.inner.write(buf) {
178 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
179 result => return result,
180 }
181 }
182 }
183
184 fn flush(&mut self) -> io::Result<()> {
185 self.inner.flush()
186 }
187}
188
189pub type Waker = Arc<dyn Fn() + Send + Sync>;
191
192pub trait Listener: Send + fmt::Debug {
194 fn accept(&mut self) -> io::Result<Option<IpcStream>>;
198 fn endpoint(&self) -> String;
201 fn endpoints(&self) -> Vec<String> {
204 vec![self.endpoint()]
205 }
206 fn local_addr(&self) -> Option<std::net::SocketAddr> {
208 None
209 }
210 fn closer(&self) -> Waker;
213}
214
215pub fn connect(endpoint: &str) -> io::Result<IpcStream> {
217 connect_endpoint(&Endpoint::parse(endpoint)?)
218}
219
220pub fn connect_endpoint(endpoint: &Endpoint) -> io::Result<IpcStream> {
222 trace!("connect {endpoint}");
223 let stream = match registered(endpoint.kind()) {
224 Some(Registered {
225 connect: Some(connect),
226 ..
227 }) => connect(endpoint),
228 Some(_) => Err(unsupported(endpoint.kind(), "connecting")),
229 None => builtin_connect(endpoint),
230 };
231 match &stream {
232 Ok(_) => trace!("connected {endpoint}"),
233 Err(error) => trace!("connect {endpoint} failed: {error}"),
234 }
235 stream
236}
237
238pub fn listen(endpoint: &str) -> io::Result<Box<dyn Listener>> {
240 listen_endpoint(&Endpoint::parse(endpoint)?)
241}
242
243pub fn listen_endpoint(endpoint: &Endpoint) -> io::Result<Box<dyn Listener>> {
245 let listener = match registered(endpoint.kind()) {
246 Some(Registered {
247 listen: Some(listen),
248 ..
249 }) => listen(endpoint),
250 Some(_) => Err(unsupported(endpoint.kind(), "listening")),
251 None => builtin_listen(endpoint),
252 }?;
253 trace!("listening on {}", listener.endpoint());
254 Ok(listener)
255}
256
257pub fn from_tcp_stream(stream: std::net::TcpStream) -> IpcStream {
259 net::tcp_stream(stream)
260}
261
262pub fn from_tcp_listener(listener: std::net::TcpListener) -> io::Result<Box<dyn Listener>> {
264 Ok(Box::new(net::TcpIpcListener::new(listener)?))
265}
266
267pub fn listen_all<S: AsRef<str>>(endpoints: &[S]) -> io::Result<Box<dyn Listener>> {
269 let mut listeners = Vec::with_capacity(endpoints.len());
270 for endpoint in endpoints {
271 listeners.push(listen(endpoint.as_ref())?);
272 }
273 match listeners.len() {
274 0 => Err(io::Error::new(
275 io::ErrorKind::InvalidInput,
276 "no endpoint to listen on",
277 )),
278 1 => Ok(listeners.pop().expect("one listener")),
279 _ => Ok(Box::new(MultiListener::new(listeners))),
280 }
281}
282
283pub fn supports(kind: &str, listen: bool) -> bool {
286 if let Some(registered) = registered(kind) {
287 return if listen {
288 registered.listen.is_some()
289 } else {
290 registered.connect.is_some()
291 };
292 }
293 let kind = kind.to_ascii_lowercase();
294 match kind.as_str() {
295 "tcp" | "udp" | "mmap" | "file" | "shm" | "signal" | "pipe" => cfg!(any(unix, windows)),
296 "stdio" => listen,
297 "exec" => !listen,
298 "unix" => cfg!(any(unix, windows)),
299 "fifo" => cfg!(unix),
300 "sysvmq" => cfg!(any(target_os = "linux", target_vendor = "apple")),
301 "mq" => cfg!(target_os = "linux"),
302 "mailslot" | "copydata" => cfg!(windows),
303 "alpc" => cfg!(all(windows, target_pointer_width = "64")),
304 _ => false,
305 }
306}
307
308pub type ConnectFn = Arc<dyn Fn(&Endpoint) -> io::Result<IpcStream> + Send + Sync>;
310pub type ListenFn = Arc<dyn Fn(&Endpoint) -> io::Result<Box<dyn Listener>> + Send + Sync>;
312
313#[derive(Clone)]
314struct Registered {
315 connect: Option<ConnectFn>,
316 listen: Option<ListenFn>,
317}
318
319fn registry() -> &'static Mutex<BTreeMap<String, Registered>> {
320 static REGISTRY: OnceLock<Mutex<BTreeMap<String, Registered>>> = OnceLock::new();
321 REGISTRY.get_or_init(|| Mutex::new(BTreeMap::new()))
322}
323
324fn registered(kind: &str) -> Option<Registered> {
325 registry()
326 .lock()
327 .unwrap_or_else(|poisoned| poisoned.into_inner())
328 .get(&kind.to_ascii_lowercase())
329 .cloned()
330}
331
332pub(crate) fn is_registered(kind: &str) -> bool {
334 registered(kind).is_some()
335}
336
337pub fn register(
342 kind: &str,
343 connect: Option<ConnectFn>,
344 listen: Option<ListenFn>,
345) -> io::Result<()> {
346 let kind = kind.to_ascii_lowercase();
347 if kind.is_empty()
348 || !kind
349 .bytes()
350 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
351 {
352 return Err(io::Error::new(
353 io::ErrorKind::InvalidInput,
354 format!("invalid endpoint kind `{kind}`"),
355 ));
356 }
357 if KINDS.contains(&kind.as_str()) {
358 return Err(io::Error::new(
359 io::ErrorKind::AlreadyExists,
360 format!("`{kind}` is a built-in endpoint kind"),
361 ));
362 }
363 registry()
364 .lock()
365 .unwrap_or_else(|poisoned| poisoned.into_inner())
366 .insert(kind, Registered { connect, listen });
367 Ok(())
368}
369
370fn unsupported(kind: &str, what: &str) -> io::Error {
371 io::Error::new(
372 io::ErrorKind::Unsupported,
373 format!("{what} on `{kind}:` endpoints is not supported on this platform"),
374 )
375}
376
377fn builtin_connect(endpoint: &Endpoint) -> io::Result<IpcStream> {
378 match endpoint.kind() {
379 "tcp" => net::connect_tcp(endpoint),
380 "udp" => net::connect_udp(endpoint),
381 "exec" => stdio::connect_exec(endpoint),
382 "stdio" => Err(io::Error::new(
383 io::ErrorKind::Unsupported,
384 "`stdio` can only be listened on; connect with `exec:COMMAND` instead",
385 )),
386 "mmap" | "file" | "shm" | "signal" => ring::connect(endpoint),
387 "unix" => net::connect_unix(endpoint),
388 #[cfg(unix)]
389 "pipe" | "fifo" => unix::connect_fifo(endpoint),
390 #[cfg(windows)]
391 "pipe" => windows::connect_pipe(endpoint),
392 #[cfg(any(target_os = "linux", target_vendor = "apple"))]
393 "sysvmq" => unix::connect_sysvmq(endpoint),
394 #[cfg(target_os = "linux")]
395 "mq" => unix::connect_mq(endpoint),
396 #[cfg(windows)]
397 "mailslot" => windows::connect_mailslot(endpoint),
398 #[cfg(windows)]
399 "copydata" => windows::connect_copydata(endpoint),
400 #[cfg(all(windows, target_pointer_width = "64"))]
401 "alpc" => windows::connect_alpc(endpoint),
402 kind => Err(unsupported(kind, "connecting")),
403 }
404}
405
406fn builtin_listen(endpoint: &Endpoint) -> io::Result<Box<dyn Listener>> {
407 match endpoint.kind() {
408 "tcp" => net::listen_tcp(endpoint),
409 "udp" => net::listen_udp(endpoint),
410 "stdio" => stdio::listen_stdio(endpoint),
411 "exec" => Err(io::Error::new(
412 io::ErrorKind::Unsupported,
413 "`exec` can only be connected to; listen on `stdio` in the started command",
414 )),
415 "mmap" | "file" | "shm" | "signal" => ring::listen(endpoint),
416 "unix" => net::listen_unix(endpoint),
417 #[cfg(unix)]
418 "pipe" | "fifo" => unix::listen_fifo(endpoint),
419 #[cfg(windows)]
420 "pipe" => windows::listen_pipe(endpoint),
421 #[cfg(any(target_os = "linux", target_vendor = "apple"))]
422 "sysvmq" => unix::listen_sysvmq(endpoint),
423 #[cfg(target_os = "linux")]
424 "mq" => unix::listen_mq(endpoint),
425 #[cfg(windows)]
426 "mailslot" => windows::listen_mailslot(endpoint),
427 #[cfg(windows)]
428 "copydata" => windows::listen_copydata(endpoint),
429 #[cfg(all(windows, target_pointer_width = "64"))]
430 "alpc" => windows::listen_alpc(endpoint),
431 kind => Err(unsupported(kind, "listening")),
432 }
433}
434
435pub struct MultiListener {
437 endpoints: Vec<String>,
438 local_addr: Option<std::net::SocketAddr>,
439 closers: Vec<Waker>,
440 incoming: mpsc::Receiver<Option<io::Result<IpcStream>>>,
441 open: usize,
442 closed: Arc<AtomicBool>,
443}
444
445impl fmt::Debug for MultiListener {
446 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
447 formatter
448 .debug_struct("MultiListener")
449 .field("endpoints", &self.endpoints)
450 .finish_non_exhaustive()
451 }
452}
453
454impl MultiListener {
455 pub fn new(listeners: Vec<Box<dyn Listener>>) -> Self {
457 let (sender, incoming) = mpsc::channel();
458 let endpoints = listeners
459 .iter()
460 .flat_map(|listener| listener.endpoints())
461 .collect();
462 let local_addr = listeners.iter().find_map(|listener| listener.local_addr());
463 let closers = listeners.iter().map(|listener| listener.closer()).collect();
464 let open = listeners.len();
465 for mut listener in listeners {
466 let sender = sender.clone();
467 thread::spawn(move || loop {
468 match listener.accept() {
469 Ok(Some(stream)) => {
470 if sender.send(Some(Ok(stream))).is_err() {
471 return;
472 }
473 }
474 Ok(None) => {
475 let _ = sender.send(None);
476 return;
477 }
478 Err(error) => {
479 if sender.send(Some(Err(error))).is_err() {
480 return;
481 }
482 }
483 }
484 });
485 }
486 Self {
487 endpoints,
488 local_addr,
489 closers,
490 incoming,
491 open,
492 closed: Arc::new(AtomicBool::new(false)),
493 }
494 }
495}
496
497impl Listener for MultiListener {
498 fn accept(&mut self) -> io::Result<Option<IpcStream>> {
499 while self.open > 0 && !self.closed.load(Ordering::SeqCst) {
500 match self.incoming.recv() {
501 Ok(Some(result)) => return result.map(Some),
502 Ok(None) => self.open -= 1,
503 Err(_) => break,
504 }
505 }
506 Ok(None)
507 }
508
509 fn endpoint(&self) -> String {
510 self.endpoints.join(" ")
511 }
512
513 fn endpoints(&self) -> Vec<String> {
514 self.endpoints.clone()
515 }
516
517 fn local_addr(&self) -> Option<std::net::SocketAddr> {
518 self.local_addr
519 }
520
521 fn closer(&self) -> Waker {
522 let closers = self.closers.clone();
523 let closed = Arc::clone(&self.closed);
524 Arc::new(move || {
525 closed.store(true, Ordering::SeqCst);
526 for closer in &closers {
527 closer();
528 }
529 })
530 }
531}
532
533impl Drop for MultiListener {
534 fn drop(&mut self) {
535 for closer in &self.closers {
536 closer();
537 }
538 }
539}
540
541pub fn forward(a: IpcStream, b: IpcStream) -> io::Result<(u64, u64)> {
548 let (a2, b2) = (a.clone(), b.clone());
549 let backward = thread::spawn(move || pump(b2, a2));
550 let forward = pump(a.clone(), b.clone());
551 let backward = backward
552 .join()
553 .unwrap_or_else(|_| Err(io::Error::other("relay thread panicked")));
554 a.shutdown();
555 b.shutdown();
556 Ok((forward?, backward?))
557}
558
559fn pump(mut from: IpcStream, mut to: IpcStream) -> io::Result<u64> {
560 let mut buffer = vec![0; 64 * 1024];
561 let mut total = 0;
562 loop {
563 let read = match from.read(&mut buffer) {
564 Ok(0) => break,
565 Ok(read) => read,
566 Err(error) => {
567 trace!("relay {} -> {}: {error}", from.kind(), to.kind());
568 to.shutdown();
570 from.shutdown();
571 return Err(error);
572 }
573 };
574 if let Err(error) = to.write_all(&buffer[..read]).and_then(|()| to.flush()) {
575 trace!("relay {} -> {}: {error}", from.kind(), to.kind());
576 from.shutdown();
577 to.shutdown();
578 return Err(error);
579 }
580 total += read as u64;
581 }
582 trace!(
583 "relay {} -> {}: end after {total} bytes",
584 from.kind(),
585 to.kind()
586 );
587 let _ = to.close_write();
588 Ok(total)
589}
590
591pub fn relay(listener: &mut dyn Listener, target: &Endpoint) -> io::Result<()> {
595 let mut connections = Vec::new();
596 loop {
597 let stream = match listener.accept() {
598 Ok(Some(stream)) => stream,
599 Ok(None) => break,
600 Err(error) => {
601 trace!("relay accept on {} failed: {error}", listener.endpoint());
602 thread::sleep(Duration::from_millis(10));
604 continue;
605 }
606 };
607 let target = target.clone();
608 connections.push(thread::spawn(move || match connect_endpoint(&target) {
609 Ok(outgoing) => {
610 if let Err(error) = forward(stream, outgoing) {
611 trace!("relay to {target} ended: {error}");
612 }
613 }
614 Err(error) => {
615 crate::diagnostics::stderr!("clink: cannot forward to {target}: {error}");
616 stream.shutdown();
617 }
618 }));
619 connections.retain(|connection| !connection.is_finished());
620 }
621 for connection in connections {
622 let _ = connection.join();
623 }
624 Ok(())
625}
626
627const TRACE_UNSET: u8 = 0;
628const TRACE_OFF: u8 = 1;
629const TRACE_ON: u8 = 2;
630static TRACE: AtomicU8 = AtomicU8::new(TRACE_UNSET);
631
632pub fn set_trace(enabled: bool) {
635 TRACE.store(
636 if enabled { TRACE_ON } else { TRACE_OFF },
637 Ordering::Relaxed,
638 );
639}
640
641pub fn trace_enabled() -> bool {
643 match TRACE.load(Ordering::Relaxed) {
644 TRACE_ON => true,
645 TRACE_OFF => false,
646 _ => {
647 let enabled = std::env::var("CLINK_IPC_TRACE").is_ok_and(|value| value == "1");
648 set_trace(enabled);
649 enabled
650 }
651 }
652}
653
654macro_rules! trace {
655 ($($argument:tt)*) => {
656 if $crate::protocol::ipc::trace_enabled() {
657 $crate::diagnostics::stderr!("[ipc] {}", ::std::format_args!($($argument)*));
658 }
659 };
660}
661pub(crate) use trace;
662
663pub(crate) fn random_id() -> String {
665 let [a, b] = random_u64s();
666 format!("{:016x}{:04x}", a, b & 0xffff)
667}
668
669pub(crate) fn random_token() -> [u8; 16] {
671 let [a, b] = random_u64s();
672 let mut token = [0; 16];
673 token[..8].copy_from_slice(&a.to_le_bytes());
674 token[8..].copy_from_slice(&b.to_le_bytes());
675 token
676}
677
678fn random_u64s() -> [u64; 2] {
679 use std::collections::hash_map::RandomState;
680 use std::hash::{BuildHasher, Hasher};
681 use std::sync::atomic::AtomicU64;
682 static COUNTER: AtomicU64 = AtomicU64::new(0);
683 let count = COUNTER.fetch_add(1, Ordering::Relaxed);
684 let nanos = web_time::SystemTime::now()
685 .duration_since(web_time::UNIX_EPOCH)
686 .map_or(0, |elapsed| elapsed.as_nanos() as u64);
687 let mut values = [0; 2];
688 for (index, value) in values.iter_mut().enumerate() {
689 let mut hasher = RandomState::new().build_hasher();
690 hasher.write_u64(count);
691 hasher.write_u64(nanos);
692 hasher.write_u32(std::process::id());
693 hasher.write_usize(index);
694 *value = hasher.finish();
695 }
696 values
697}
698
699pub(crate) fn process_alive(pid: u32) -> bool {
701 #[cfg(unix)]
702 {
703 unix::process_alive(pid)
704 }
705 #[cfg(windows)]
706 {
707 windows::process_alive(pid)
708 }
709 #[cfg(not(any(unix, windows)))]
710 {
711 let _ = pid;
712 true
713 }
714}
715
716#[derive(Debug)]
718pub(crate) struct PeerWatch {
719 pid: u32,
720 state: Mutex<(web_time::Instant, bool)>,
721}
722
723impl PeerWatch {
724 pub(crate) fn new(pid: u32) -> Self {
725 Self {
726 pid,
727 state: Mutex::new((web_time::Instant::now(), true)),
728 }
729 }
730
731 pub(crate) fn pid(&self) -> u32 {
732 self.pid
733 }
734
735 pub(crate) fn alive(&self) -> bool {
736 let mut state = self
737 .state
738 .lock()
739 .unwrap_or_else(|poisoned| poisoned.into_inner());
740 if state.1 && state.0.elapsed() >= Duration::from_millis(100) {
741 state.1 = process_alive(self.pid);
742 state.0 = web_time::Instant::now();
743 }
744 state.1
745 }
746}
747
748pub(crate) fn hung_up() -> io::Error {
749 io::Error::new(io::ErrorKind::ConnectionReset, "the peer hung up")
750}
751
752pub(crate) fn broken_pipe() -> io::Error {
753 io::Error::new(io::ErrorKind::BrokenPipe, "the peer no longer reads")
754}
755
756pub(crate) fn timed_out() -> io::Error {
757 io::Error::new(io::ErrorKind::TimedOut, "timed out")
758}
759
760#[cfg(test)]
761mod tests;