1use std::io::{self, Read, Write};
6use std::net::Shutdown;
7#[cfg(unix)]
8use std::path::{Path, PathBuf};
9#[cfg(unix)]
10use std::sync::{Arc, Mutex, PoisonError};
11use std::time::Duration;
12#[cfg(unix)]
13use std::time::Instant;
14
15#[cfg(unix)]
16use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
17
18#[cfg(unix)]
19use crate::accept::{Accepted, Acceptor};
20#[cfg(unix)]
21use crate::driver::DriverKind;
22use crate::error::NetError;
23#[cfg(unix)]
24use crate::error::{ConfigReason, LimitKind, TimeoutKind};
25use crate::gate::KillHandle;
26#[cfg(unix)]
27use crate::id::{ConnectionId, ListenerId};
28use crate::info::ConnectionInfo;
29#[cfg(unix)]
30use crate::info::{Endpoint, Origin, PeerCredentials, Transport, UnixPath};
31use crate::limits::Limits;
32#[cfg(unix)]
33use crate::link::{ClockRef, Got, Link, WakeSource};
34#[cfg(windows)]
35use crate::local_windows::{UnixConnection, UnixListener};
36#[cfg(unix)]
37use crate::opts::LocalOptions;
38#[cfg(windows)]
39use crate::pipe::{PipeConnection, PipeListener};
40#[cfg(unix)]
41use crate::proxy::ProxyMode;
42#[cfg(unix)]
43use crate::session::Phase;
44#[cfg(unix)]
45use crate::sys::{self, Interest, KillSlot, Ready};
46#[cfg(unix)]
47use crate::tcp::{ListenerInfo, TcpConnection};
48
49#[cfg(unix)]
51const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
52
53#[cfg(unix)]
62pub struct Descriptors {
63 slots: [Option<OwnedFd>; sys::MAX_FDS],
64 len: usize,
65}
66
67#[cfg(unix)]
68impl Descriptors {
69 #[must_use]
71 pub fn new() -> Descriptors {
72 Descriptors {
73 slots: [const { None }; sys::MAX_FDS],
74 len: 0,
75 }
76 }
77
78 #[must_use]
80 pub fn len(&self) -> usize {
81 self.len
82 }
83
84 #[must_use]
86 pub fn is_empty(&self) -> bool {
87 self.len == 0
88 }
89
90 pub fn take(&mut self) -> impl Iterator<Item = OwnedFd> + '_ {
92 self.len = 0;
93 self.slots.iter_mut().filter_map(Option::take)
94 }
95
96 fn clear(&mut self) {
97 for slot in &mut self.slots {
98 *slot = None;
99 }
100 self.len = 0;
101 }
102}
103
104#[cfg(unix)]
105impl Default for Descriptors {
106 fn default() -> Descriptors {
107 Descriptors::new()
108 }
109}
110
111#[cfg(unix)]
112impl std::fmt::Debug for Descriptors {
113 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
114 f.debug_struct("Descriptors")
115 .field("len", &self.len)
116 .finish()
117 }
118}
119
120#[cfg(unix)]
122type FileId = (u64, u64);
123
124#[cfg(unix)]
125fn file_id(path: &Path) -> Option<(FileId, bool)> {
126 use std::os::unix::fs::{FileTypeExt, MetadataExt};
127 let meta = std::fs::symlink_metadata(path).ok()?;
129 Some(((meta.dev(), meta.ino()), meta.file_type().is_socket()))
130}
131
132#[cfg(unix)]
134fn path_bytes(path: &Path) -> Result<&[u8], NetError> {
135 let bytes = path.as_os_str().as_encoded_bytes();
136 if bytes.is_empty() {
137 return Err(NetError::InvalidConfig {
138 field: "path",
139 reason: ConfigReason::Zero,
140 });
141 }
142 if bytes.contains(&0) {
143 return Err(NetError::InvalidConfig {
144 field: "path",
145 reason: ConfigReason::Malformed,
146 });
147 }
148 if bytes.len() >= sys::UNIX_PATH_MAX {
149 return Err(NetError::PathTooLong {
150 max: sys::UNIX_PATH_MAX,
151 });
152 }
153 Ok(bytes)
154}
155
156#[cfg(unix)]
157fn os_error(op: &'static str, e: io::Error) -> NetError {
158 match e.kind() {
159 io::ErrorKind::PermissionDenied => NetError::PermissionDenied { what: op },
160 io::ErrorKind::NotFound => NetError::NotFound,
161 _ => NetError::Os { op, source: e },
162 }
163}
164
165#[cfg(unix)]
167fn live(path: &[u8]) -> Result<bool, NetError> {
168 let sock = sys::unix_socket().map_err(|e| NetError::from_os("socket", e))?;
169 let probe = std::os::unix::net::UnixStream::from(sock);
170 let _ = probe.set_write_timeout(Some(Duration::from_secs(1)));
172 match sys::unix_connect(probe.as_fd(), path) {
173 Ok(()) => Ok(true),
174 Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => Ok(false),
175 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
176 Err(e)
178 if matches!(
179 e.kind(),
180 io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
181 ) =>
182 {
183 Ok(true)
184 }
185 Err(e) => Err(os_error("connect", e)),
186 }
187}
188
189#[cfg(unix)]
200pub struct UnixListener {
201 inner: std::os::unix::net::UnixListener,
202 path: PathBuf,
203 created: Option<FileId>,
204 keep: std::sync::atomic::AtomicBool,
206 shared_path: Arc<UnixPath>,
207 info: ListenerInfo,
208 require_uid: Option<u32>,
209 acceptor: Mutex<Acceptor>,
210}
211
212#[cfg(unix)]
213impl UnixListener {
214 pub fn bind<P: AsRef<Path>>(path: P) -> Result<UnixListener, NetError> {
223 UnixListener::bind_with(path, LocalOptions::new())
224 }
225
226 pub fn bind_with<P: AsRef<Path>>(
255 path: P,
256 options: LocalOptions,
257 ) -> Result<UnixListener, NetError> {
258 UnixListener::create(path.as_ref(), &options, false)
259 }
260
261 pub fn bind_atomic<P: AsRef<Path>>(
272 path: P,
273 options: LocalOptions,
274 ) -> Result<UnixListener, NetError> {
275 UnixListener::create(path.as_ref(), &options, true)
276 }
277
278 fn create(path: &Path, options: &LocalOptions, atomic: bool) -> Result<UnixListener, NetError> {
279 use std::os::unix::fs::MetadataExt;
280 let bytes = path_bytes(path)?;
281 let shared_path = Arc::new(UnixPath::new(bytes).ok_or(NetError::PathTooLong {
282 max: sys::UNIX_PATH_MAX,
283 })?);
284 let (dir_bytes, leaf) = split_path(bytes)?;
285 let dir = sys::open_directory(Path::new(os_str(dir_bytes)), false)
288 .map_err(|e| os_error("open", e))?;
289 let dir_meta = dir.metadata().map_err(|e| os_error("fstat", e))?;
290 let trust = dir_trust(dir_meta.uid(), dir_meta.mode(), sys::effective_uid()).ok_or(
291 NetError::InvalidConfig {
292 field: "path",
293 reason: ConfigReason::InsecureDirectory,
294 },
295 )?;
296 if let Some((_, is_socket)) = file_id(path) {
298 let stale = is_socket && !live(bytes)?;
299 if !stale {
300 return Err(NetError::StaleSocketInUse {
301 path: path.to_path_buf(),
302 });
303 }
304 if !options.remove_stale {
305 return Err(NetError::StaleSocketInUse {
306 path: path.to_path_buf(),
307 });
308 }
309 if !atomic {
310 std::fs::remove_file(path).map_err(|e| os_error("unlink", e))?;
312 }
313 }
314 let sock = sys::unix_socket().map_err(|e| NetError::from_os("socket", e))?;
315 let place = Place {
316 dir: &dir,
317 dir_bytes,
318 leaf,
319 path,
320 };
321 let created = match trust {
322 DirTrust::Safe => place.bind_in_place(sock.as_fd(), options, atomic)?,
323 DirTrust::Shared => place.bind_privately(sock.as_fd(), options, atomic)?,
324 };
325 let inner = std::os::unix::net::UnixListener::from(sock);
326 inner
328 .set_nonblocking(true)
329 .map_err(|e| NetError::from_os("ioctl", e))?;
330 Ok(UnixListener {
331 inner,
332 path: path.to_path_buf(),
333 created: Some(created),
334 keep: std::sync::atomic::AtomicBool::new(false),
335 info: ListenerInfo {
336 id: ListenerId(0),
337 name: None,
338 local: Endpoint::Unix(shared_path.clone()),
339 backlog: if cfg!(target_os = "linux") {
340 crate::tcp::effective_backlog(options.backlog)
341 } else {
342 None
343 },
344 transport: Transport::Unix,
345 proxy: ProxyMode::Off,
346 tls: false,
347 },
348 shared_path,
349 require_uid: options.require_uid,
350 acceptor: Mutex::new(Acceptor::new()),
351 })
352 }
353
354 pub fn accept(&self) -> Result<(UnixConnection, ConnectionInfo), NetError> {
362 match self.accept_until(None)? {
363 Some(pair) => Ok(pair),
364 None => Err(NetError::TimedOut {
365 kind: TimeoutKind::Read,
366 }),
367 }
368 }
369
370 pub fn accept_timeout(
376 &self,
377 timeout: Duration,
378 ) -> Result<Option<(UnixConnection, ConnectionInfo)>, NetError> {
379 self.accept_until(Some(Instant::now() + timeout))
380 }
381
382 fn accept_until(
383 &self,
384 deadline: Option<Instant>,
385 ) -> Result<Option<(UnixConnection, ConnectionInfo)>, NetError> {
386 let mut paused_once = false;
387 loop {
388 let outcome = self
389 .acceptor
390 .lock()
391 .unwrap_or_else(PoisonError::into_inner)
392 .accept_unix(&self.inner);
393 match outcome {
394 Accepted::Conn(stream) => {
395 let credentials = credentials_of(&stream);
396 if !self.permits(credentials) {
397 continue;
398 }
399 let info = ConnectionInfo::new_unix(
400 crate::id::issue_single(),
401 Some(self.info.id),
402 Origin::Accepted,
403 Endpoint::Unix(self.shared_path.clone()),
404 Endpoint::Unnamed,
405 credentials,
406 Instant::now(),
407 );
408 let conn = UnixConnection::from_stream(stream, info.clone(), Phase::Idle);
409 return Ok(Some((conn, info)));
410 }
411 Accepted::Skipped(_) => continue,
412 Accepted::Again => {
413 let timeout = match deadline {
414 None => None,
415 Some(d) => {
416 let left = d.saturating_duration_since(Instant::now());
417 if left.is_zero() {
418 return Ok(None);
419 }
420 Some(left)
421 }
422 };
423 match sys::wait(self.inner.as_fd(), Interest::Read, None, timeout) {
424 Ok(Ready::TimedOut) => return Ok(None),
425 Ok(_) => continue,
426 Err(e) => return Err(NetError::from_os("poll", e)),
427 }
428 }
429 Accepted::Pause(backoff) => {
430 if paused_once {
431 return Err(NetError::Limit {
432 which: LimitKind::Descriptors,
433 });
434 }
435 paused_once = true;
436 std::thread::sleep(backoff);
437 }
438 Accepted::Failed(e) => return Err(NetError::from_os("accept", e)),
439 }
440 }
441 }
442
443 pub(crate) fn adopt(sock: OwnedFd) -> Result<UnixListener, NetError> {
446 let inner = std::os::unix::net::UnixListener::from(sock);
447 inner
448 .set_nonblocking(true)
449 .map_err(|e| NetError::from_os("ioctl", e))?;
450 let path = inner
451 .local_addr()
452 .ok()
453 .and_then(|a| a.as_pathname().map(Path::to_path_buf))
454 .unwrap_or_default();
455 let shared_path = Arc::new(UnixPath::new(path.as_os_str().as_encoded_bytes()).ok_or(
456 NetError::PathTooLong {
457 max: sys::UNIX_PATH_MAX,
458 },
459 )?);
460 let local = if path.as_os_str().is_empty() {
461 Endpoint::Unnamed
462 } else {
463 Endpoint::Unix(shared_path.clone())
464 };
465 Ok(UnixListener {
466 inner,
467 path,
468 created: None,
469 keep: std::sync::atomic::AtomicBool::new(true),
470 info: ListenerInfo {
471 id: ListenerId(0),
472 name: None,
473 local,
474 backlog: None,
475 transport: Transport::Unix,
476 proxy: ProxyMode::Off,
477 tls: false,
478 },
479 shared_path,
480 require_uid: None,
481 acceptor: Mutex::new(Acceptor::new()),
482 })
483 }
484
485 pub(crate) fn keep_file(&self) {
487 self.keep.store(true, std::sync::atomic::Ordering::Release);
488 }
489
490 pub(crate) fn permits(&self, credentials: Option<PeerCredentials>) -> bool {
492 match self.require_uid {
493 None => true,
494 Some(uid) => credentials.and_then(|c| c.uid) == Some(uid),
495 }
496 }
497
498 pub(crate) fn std(&self) -> &std::os::unix::net::UnixListener {
499 &self.inner
500 }
501
502 pub(crate) fn shared_path(&self) -> &Arc<UnixPath> {
503 &self.shared_path
504 }
505
506 pub(crate) fn set_identity(&mut self, id: ListenerId, name: Option<String>) {
507 self.info.id = id;
508 self.info.name = name;
509 }
510
511 pub(crate) fn set_proxy_mode(&mut self, mode: ProxyMode) {
512 self.info.proxy = mode;
513 }
514
515 pub(crate) fn set_tls(&mut self, on: bool) {
516 self.info.tls = on;
517 }
518
519 #[must_use]
521 pub fn info(&self) -> &ListenerInfo {
522 &self.info
523 }
524
525 #[must_use]
528 pub fn path(&self) -> Option<&Path> {
529 (!self.path.as_os_str().is_empty()).then_some(self.path.as_path())
530 }
531}
532
533#[cfg(unix)]
534impl Drop for UnixListener {
535 fn drop(&mut self) {
538 if self.keep.load(std::sync::atomic::Ordering::Acquire) {
539 return;
540 }
541 if let Some(created) = self.created {
542 if file_id(&self.path) == Some((created, true)) {
543 let _ = std::fs::remove_file(&self.path);
544 }
545 }
546 }
547}
548
549#[cfg(unix)]
550impl AsFd for UnixListener {
551 fn as_fd(&self) -> BorrowedFd<'_> {
552 self.inner.as_fd()
553 }
554}
555
556#[cfg(unix)]
557impl std::fmt::Debug for UnixListener {
558 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
559 f.debug_struct("UnixListener")
560 .field("path", &self.path)
561 .field("info", &self.info)
562 .finish()
563 }
564}
565
566#[cfg(unix)]
567fn replaced(path: &Path) -> NetError {
568 NetError::StaleSocketInUse {
569 path: path.to_path_buf(),
570 }
571}
572
573#[cfg(unix)]
576#[derive(Clone, Copy, Debug, PartialEq, Eq)]
577enum DirTrust {
578 Safe,
581 Shared,
585}
586
587#[cfg(unix)]
591fn dir_trust(owner: u32, mode: u32, me: u32) -> Option<DirTrust> {
592 let sticky = mode & 0o1000 != 0;
593 if mode & 0o002 != 0 && !sticky {
594 return None;
595 }
596 let nobody_else_writes = mode & 0o022 == 0 || sticky;
599 if (owner == me || owner == 0) && nobody_else_writes {
600 Some(DirTrust::Safe)
601 } else {
602 Some(DirTrust::Shared)
603 }
604}
605
606#[cfg(unix)]
610fn split_path(bytes: &[u8]) -> Result<(&[u8], &[u8]), NetError> {
611 let (dir, leaf) = match bytes.iter().rposition(|&b| b == b'/') {
612 Some(0) => (&b"/"[..], &bytes[1..]),
613 Some(i) => (&bytes[..i], &bytes[i + 1..]),
614 None => (&b"."[..], bytes),
615 };
616 if leaf.is_empty() || leaf == b"." || leaf == b".." {
617 return Err(NetError::InvalidConfig {
618 field: "path",
619 reason: ConfigReason::Malformed,
620 });
621 }
622 Ok((dir, leaf))
623}
624
625#[cfg(unix)]
626fn os_str(bytes: &[u8]) -> &std::ffi::OsStr {
627 <std::ffi::OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(bytes)
628}
629
630#[cfg(unix)]
632fn join(dir: &[u8], name: &[u8]) -> PathBuf {
633 let mut joined = Vec::with_capacity(dir.len() + 1 + name.len());
634 joined.extend_from_slice(dir);
635 if dir.last() != Some(&b'/') {
636 joined.push(b'/');
637 }
638 joined.extend_from_slice(name);
639 PathBuf::from(<std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(joined))
640}
641
642#[cfg(unix)]
644fn c_name(name: &[u8]) -> Result<std::ffi::CString, NetError> {
645 std::ffi::CString::new(name).map_err(|_| NetError::InvalidConfig {
646 field: "path",
647 reason: ConfigReason::Malformed,
648 })
649}
650
651#[cfg(unix)]
653fn temporary_leaf(name: &[u8]) -> Vec<u8> {
654 use std::sync::atomic::{AtomicU32, Ordering};
655 static NEXT: AtomicU32 = AtomicU32::new(0);
656 let mut leaf = Vec::with_capacity(name.len() + 24);
657 leaf.push(b'.');
658 leaf.extend_from_slice(name);
659 leaf.extend_from_slice(
660 format!(
661 ".{}.{}",
662 std::process::id(),
663 NEXT.fetch_add(1, Ordering::Relaxed)
664 )
665 .as_bytes(),
666 );
667 leaf
668}
669
670#[cfg(unix)]
673fn random_u32() -> u32 {
674 use std::hash::{BuildHasher, Hasher};
675 use std::sync::atomic::{AtomicU64, Ordering};
676 static NEXT: AtomicU64 = AtomicU64::new(0);
677 let mut h = std::collections::hash_map::RandomState::new().build_hasher();
678 h.write_u32(std::process::id());
679 h.write_u64(NEXT.fetch_add(1, Ordering::Relaxed));
680 h.finish() as u32
681}
682
683#[cfg(unix)]
685fn bind_socket(sock: BorrowedFd<'_>, at: &Path, path: &Path) -> Result<(), NetError> {
686 sys::unix_bind(sock, path_bytes(at)?).map_err(|e| match e.kind() {
687 io::ErrorKind::AddrInUse => NetError::StaleSocketInUse {
688 path: path.to_path_buf(),
689 },
690 _ => os_error("bind", e),
691 })
692}
693
694#[cfg(unix)]
696const PRIVATE_DIRECTORY_TRIES: usize = 8;
697
698#[cfg(unix)]
703fn private_directory(
704 dir: &std::fs::File,
705 dir_bytes: &[u8],
706) -> Result<(Vec<u8>, std::fs::File), NetError> {
707 use std::os::unix::fs::{DirBuilderExt, MetadataExt};
708 let me = sys::effective_uid();
709 for _ in 0..PRIVATE_DIRECTORY_TRIES {
710 let name = format!(".nio{:08x}", random_u32()).into_bytes();
711 let at = join(dir_bytes, &name);
712 match std::fs::DirBuilder::new().mode(0o700).create(&at) {
713 Ok(()) => {}
714 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
715 Err(e) => return Err(os_error("mkdir", e)),
716 }
717 let opened = match sys::open_directory(&at, true) {
718 Ok(opened) => opened,
719 Err(e) => {
720 if let Ok(c) = c_name(&name) {
722 let _ = sys::unlink_at(dir.as_fd(), &c, true);
723 }
724 return Err(os_error("open", e));
725 }
726 };
727 let meta = opened.metadata().map_err(|e| os_error("fstat", e))?;
728 if !meta.is_dir() || meta.uid() != me || meta.mode() & 0o077 != 0 {
729 return Err(NetError::Os {
732 op: "mkdir",
733 source: io::Error::other("the private directory was replaced"),
734 });
735 }
736 return Ok((name, opened));
737 }
738 Err(os_error(
739 "mkdir",
740 io::Error::from(io::ErrorKind::AlreadyExists),
741 ))
742}
743
744#[cfg(unix)]
747struct Place<'a> {
748 dir: &'a std::fs::File,
749 dir_bytes: &'a [u8],
750 leaf: &'a [u8],
751 path: &'a Path,
752}
753
754#[cfg(unix)]
755impl Place<'_> {
756 fn bind_in_place(
761 &self,
762 sock: BorrowedFd<'_>,
763 options: &LocalOptions,
764 atomic: bool,
765 ) -> Result<FileId, NetError> {
766 let target_leaf = if atomic {
767 temporary_leaf(self.leaf)
768 } else {
769 self.leaf.to_vec()
770 };
771 let target = join(self.dir_bytes, &target_leaf);
772 bind_socket(sock, &target, self.path)?;
773 let result = (|| {
774 let created = match file_id(&target) {
775 Some((id, true)) => id,
776 _ => return Err(replaced(&target)),
777 };
778 let name = c_name(&target_leaf)?;
779 set_access(self.dir, &name, options)?;
780 sys::unix_listen(sock, options.backlog).map_err(|e| NetError::from_os("listen", e))?;
781 if atomic {
782 let fin = c_name(self.leaf)?;
783 sys::rename_at(self.dir.as_fd(), &name, self.dir.as_fd(), &fin)
784 .map_err(|e| os_error("rename", e))?;
785 }
786 Ok(created)
787 })();
788 if result.is_err() && file_id(&target).is_some_and(|(_, sock)| sock) {
789 let _ = std::fs::remove_file(&target);
790 }
791 result
792 }
793
794 fn bind_privately(
800 &self,
801 sock: BorrowedFd<'_>,
802 options: &LocalOptions,
803 atomic: bool,
804 ) -> Result<FileId, NetError> {
805 let (private_leaf, private) = private_directory(self.dir, self.dir_bytes)?;
806 let private_path = join(self.dir_bytes, &private_leaf);
807 let result = (|| {
808 bind_socket(sock, &private_path.join("s"), self.path)?;
809 set_access(&private, c"s", options)?;
810 sys::unix_listen(sock, options.backlog).map_err(|e| NetError::from_os("listen", e))?;
811 let fin = c_name(self.leaf)?;
812 if atomic {
813 sys::rename_at(private.as_fd(), c"s", self.dir.as_fd(), &fin)
814 .map_err(|e| os_error("rename", e))?;
815 } else {
816 sys::link_at(private.as_fd(), c"s", self.dir.as_fd(), &fin).map_err(|e| match e
817 .kind()
818 {
819 io::ErrorKind::AlreadyExists => NetError::StaleSocketInUse {
820 path: self.path.to_path_buf(),
821 },
822 _ => os_error("link", e),
823 })?;
824 }
825 match file_id(self.path) {
828 Some((id, true)) => Ok(id),
829 _ => Err(replaced(self.path)),
830 }
831 })();
832 let _ = sys::unlink_at(private.as_fd(), c"s", false);
835 if let Ok(name) = c_name(&private_leaf) {
836 let _ = sys::unlink_at(self.dir.as_fd(), &name, true);
837 }
838 result
839 }
840}
841
842#[cfg(unix)]
847fn set_access(
848 dir: &std::fs::File,
849 name: &std::ffi::CStr,
850 options: &LocalOptions,
851) -> Result<(), NetError> {
852 sys::chmod_at(dir.as_fd(), name, options.mode).map_err(|e| os_error("chmod", e))?;
853 if options.owner.is_some() || options.group.is_some() {
854 sys::chown_at(dir.as_fd(), name, options.owner, options.group)
855 .map_err(|e| os_error("chown", e))?;
856 }
857 Ok(())
858}
859
860#[cfg(unix)]
861pub(crate) fn credentials_of(stream: &std::os::unix::net::UnixStream) -> Option<PeerCredentials> {
862 sys::peer_credentials(stream.as_fd())
863 .ok()
864 .map(|(pid, uid, gid)| PeerCredentials {
865 pid,
866 uid: Some(uid),
867 gid: Some(gid),
868 })
869}
870
871#[cfg(unix)]
880pub struct UnixConnection {
881 inner: TcpConnection,
882}
883
884#[cfg(unix)]
885impl UnixConnection {
886 pub fn connect<P: AsRef<Path>>(path: P) -> Result<UnixConnection, NetError> {
893 let path = path.as_ref();
894 let bytes = path_bytes(path)?;
895 let shared = Arc::new(UnixPath::new(bytes).ok_or(NetError::PathTooLong {
896 max: sys::UNIX_PATH_MAX,
897 })?);
898 let sock = sys::unix_socket().map_err(|e| NetError::from_os("socket", e))?;
899 let stream = std::os::unix::net::UnixStream::from(sock);
900 stream
901 .set_write_timeout(Some(CONNECT_TIMEOUT))
902 .map_err(|e| NetError::from_os("setsockopt", e))?;
903 if let Err(e) = sys::unix_connect(stream.as_fd(), bytes) {
904 return Err(match e.kind() {
905 io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused => NetError::NotFound,
906 io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut => NetError::TimedOut {
907 kind: TimeoutKind::Connect,
908 },
909 _ => os_error("connect", e),
910 });
911 }
912 stream
913 .set_write_timeout(None)
914 .map_err(|e| NetError::from_os("setsockopt", e))?;
915 if sys::WAIT_BEFORE_RECV {
916 stream
917 .set_nonblocking(true)
918 .map_err(|e| NetError::from_os("ioctl", e))?;
919 }
920 let info = ConnectionInfo::new_unix(
921 crate::id::issue_single(),
922 None,
923 Origin::Dialed,
924 Endpoint::Unnamed,
925 Endpoint::Unix(shared),
926 credentials_of(&stream),
927 Instant::now(),
928 );
929 Ok(UnixConnection::from_stream(stream, info, Phase::Receiving))
930 }
931
932 fn from_stream(
933 stream: std::os::unix::net::UnixStream,
934 info: ConnectionInfo,
935 phase: Phase,
936 ) -> UnixConnection {
937 let limits = Arc::new(Limits::default().effective(DriverKind::Blocking));
938 UnixConnection {
939 inner: TcpConnection::from_link(Link::new(
940 sys::Stream::Unix(stream),
941 info,
942 limits,
943 ClockRef::Monotonic,
944 Arc::new(KillSlot::new()),
945 WakeSource::Thread,
946 phase,
947 )),
948 }
949 }
950
951 pub fn recv(&mut self, buf: &mut [u8]) -> Result<usize, NetError> {
957 self.inner.recv(buf)
958 }
959
960 pub fn recv_exact(&mut self, buf: &mut [u8]) -> Result<(), NetError> {
966 self.inner.recv_exact(buf)
967 }
968
969 pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
975 self.inner.send(buf)
976 }
977
978 pub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError> {
984 self.inner.send_all(buf)
985 }
986
987 pub fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError> {
993 self.inner.shutdown(how)
994 }
995
996 pub fn close(self) -> Result<(), NetError> {
1002 self.inner.close()
1003 }
1004
1005 pub fn abort(self) {
1007 self.inner.abort();
1008 }
1009
1010 fn close_in_place(&mut self) -> Result<(), NetError> {
1011 match self.inner.take_link() {
1012 Some(link) => TcpConnection::from_link(link).close(),
1013 None => Ok(()),
1014 }
1015 }
1016
1017 fn abort_in_place(&mut self) {
1018 if let Some(link) = self.inner.take_link() {
1019 TcpConnection::from_link(link).abort();
1020 }
1021 }
1022
1023 #[must_use]
1025 pub fn info(&self) -> &ConnectionInfo {
1026 self.inner.info()
1027 }
1028
1029 #[must_use]
1031 pub fn id(&self) -> ConnectionId {
1032 self.inner.id()
1033 }
1034
1035 #[must_use]
1037 pub fn kill_handle(&self) -> KillHandle {
1038 self.inner.kill_handle()
1039 }
1040
1041 pub fn set_limits(&mut self, limits: Limits) {
1043 self.inner.set_limits(limits);
1044 }
1045
1046 pub fn set_phase(&mut self, phase: Phase) {
1048 self.inner.set_phase(phase);
1049 }
1050
1051 pub fn set_exchange_deadline(&mut self, at: Option<Instant>) {
1053 self.inner.set_exchange_deadline(at);
1054 }
1055
1056 pub fn peer_credentials(&self) -> Result<PeerCredentials, NetError> {
1062 self.info().peer_credentials.ok_or(NetError::Unsupported {
1063 feature: "peer credentials",
1064 platform: std::env::consts::OS,
1065 })
1066 }
1067
1068 pub fn send_descriptors(
1076 &mut self,
1077 body: &[u8],
1078 descriptors: &[BorrowedFd<'_>],
1079 ) -> Result<(), NetError> {
1080 self.inner.link()?.write_with_fds(body, descriptors)
1081 }
1082
1083 pub fn recv_descriptors(
1093 &mut self,
1094 body: &mut [u8],
1095 into: &mut Descriptors,
1096 ) -> Result<usize, NetError> {
1097 into.clear();
1098 let link = self.inner.link()?;
1099 loop {
1100 match link.read_with_fds(body, &mut into.slots)? {
1101 (Got::Data(n), fds) => {
1102 into.len = fds;
1103 return Ok(n);
1104 }
1105 (Got::Eof, _) => return Ok(0),
1106 (Got::Woken, _) => continue,
1107 }
1108 }
1109 }
1110}
1111
1112#[cfg(unix)]
1113impl Read for UnixConnection {
1114 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1115 self.inner.read(buf)
1116 }
1117}
1118
1119#[cfg(unix)]
1120impl Write for UnixConnection {
1121 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1122 self.inner.write(buf)
1123 }
1124
1125 fn flush(&mut self) -> io::Result<()> {
1126 Ok(())
1127 }
1128}
1129
1130#[cfg(unix)]
1131impl AsFd for UnixConnection {
1132 fn as_fd(&self) -> BorrowedFd<'_> {
1133 AsFd::as_fd(&self.inner.link_ref().stream)
1134 }
1135}
1136
1137#[cfg(unix)]
1138impl std::fmt::Debug for UnixConnection {
1139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1140 f.debug_struct("UnixConnection")
1141 .field("info", self.inner.info())
1142 .finish()
1143 }
1144}
1145
1146#[cfg(unix)]
1149macro_rules! inside {
1150 ($kind:ident, $this:expr, $v:ident => $body:expr) => {
1151 match $this {
1152 $kind::Unix($v) => $body,
1153 }
1154 };
1155}
1156
1157#[cfg(windows)]
1158macro_rules! inside {
1159 ($kind:ident, $this:expr, $v:ident => $body:expr) => {
1160 match $this {
1161 $kind::Unix($v) => $body,
1162 $kind::Pipe($v) => $body,
1163 }
1164 };
1165}
1166
1167#[non_exhaustive]
1169#[derive(Debug)]
1170pub enum LocalListener {
1171 Unix(UnixListener),
1173 #[cfg(windows)]
1175 Pipe(PipeListener),
1176}
1177
1178impl LocalListener {
1179 pub fn accept(&self) -> Result<(LocalConnection, ConnectionInfo), NetError> {
1185 match self {
1186 LocalListener::Unix(l) => l.accept().map(|(c, info)| (LocalConnection::Unix(c), info)),
1187 #[cfg(windows)]
1188 LocalListener::Pipe(l) => l.accept().map(|(c, info)| (LocalConnection::Pipe(c), info)),
1189 }
1190 }
1191}
1192
1193#[non_exhaustive]
1195#[derive(Debug)]
1196pub enum LocalConnection {
1197 Unix(UnixConnection),
1199 #[cfg(windows)]
1201 Pipe(PipeConnection),
1202}
1203
1204impl LocalConnection {
1205 pub fn recv(&mut self, buf: &mut [u8]) -> Result<usize, NetError> {
1211 inside!(LocalConnection, self, c => c.recv(buf))
1212 }
1213
1214 pub fn recv_exact(&mut self, buf: &mut [u8]) -> Result<(), NetError> {
1220 inside!(LocalConnection, self, c => c.recv_exact(buf))
1221 }
1222
1223 pub fn send(&mut self, buf: &[u8]) -> Result<usize, NetError> {
1229 inside!(LocalConnection, self, c => c.send(buf))
1230 }
1231
1232 pub fn send_all(&mut self, buf: &[u8]) -> Result<(), NetError> {
1238 inside!(LocalConnection, self, c => c.send_all(buf))
1239 }
1240
1241 pub fn shutdown(&mut self, how: Shutdown) -> Result<(), NetError> {
1247 inside!(LocalConnection, self, c => c.shutdown(how))
1248 }
1249
1250 pub fn close(mut self) -> Result<(), NetError> {
1256 let this = &mut self;
1257 inside!(LocalConnection, this, c => c.close_in_place())
1258 }
1259
1260 pub fn abort(mut self) {
1262 let this = &mut self;
1263 inside!(LocalConnection, this, c => c.abort_in_place());
1264 }
1265
1266 #[must_use]
1268 pub fn info(&self) -> &ConnectionInfo {
1269 inside!(LocalConnection, self, c => c.info())
1270 }
1271
1272 #[must_use]
1274 pub fn kill_handle(&self) -> KillHandle {
1275 inside!(LocalConnection, self, c => c.kill_handle())
1276 }
1277
1278 pub fn set_limits(&mut self, limits: Limits) {
1280 inside!(LocalConnection, self, c => c.set_limits(limits));
1281 }
1282}
1283
1284impl Read for LocalConnection {
1285 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1286 self.recv(buf).map_err(io::Error::from)
1287 }
1288}
1289
1290impl Write for LocalConnection {
1291 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1292 self.send(buf).map_err(io::Error::from)
1293 }
1294
1295 fn flush(&mut self) -> io::Result<()> {
1296 Ok(())
1297 }
1298}
1299
1300pub(crate) fn listen(name: &str) -> Result<LocalListener, NetError> {
1302 #[cfg(unix)]
1303 {
1304 UnixListener::bind(name).map(LocalListener::Unix)
1305 }
1306 #[cfg(windows)]
1307 {
1308 PipeListener::create(name).map(LocalListener::Pipe)
1309 }
1310}
1311
1312pub(crate) fn connect(name: &str) -> Result<LocalConnection, NetError> {
1314 #[cfg(unix)]
1315 {
1316 UnixConnection::connect(name).map(LocalConnection::Unix)
1317 }
1318 #[cfg(windows)]
1319 {
1320 PipeConnection::connect(name, Duration::from_secs(10)).map(LocalConnection::Pipe)
1321 }
1322}
1323
1324#[cfg(all(test, unix))]
1325mod tests {
1326 use super::*;
1327 use std::os::unix::fs::PermissionsExt;
1328
1329 fn dir(tag: &str) -> PathBuf {
1331 let d = std::env::temp_dir().join(format!("nio-{}-{tag}", std::process::id()));
1332 let _ = std::fs::remove_dir_all(&d);
1333 std::fs::create_dir(&d).unwrap();
1334 d
1335 }
1336
1337 #[test]
1338 fn test_bind_accept_echo_and_credentials() {
1339 let d = dir("echo");
1340 let path = d.join("s.sock");
1341 let l = UnixListener::bind(&path).unwrap();
1342 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1343 assert_eq!(mode, 0o600);
1344 assert_eq!(l.path(), Some(path.as_path()));
1345 let p2 = path.clone();
1346 let t = std::thread::spawn(move || {
1347 let mut c = UnixConnection::connect(&p2).unwrap();
1348 assert_eq!(c.info().transport, Transport::Unix);
1349 assert_eq!(c.info().origin, Origin::Dialed);
1350 c.send_all(b"ping").unwrap();
1351 let mut b = [0u8; 4];
1352 c.recv_exact(&mut b).unwrap();
1353 assert_eq!(&b, b"ping");
1354 c.peer_credentials().unwrap()
1355 });
1356 let (mut c, info) = l.accept().unwrap();
1357 assert_eq!(info.transport, Transport::Unix);
1358 assert_eq!(info.peer, Endpoint::Unnamed);
1359 let creds = info.peer_credentials.unwrap();
1360 assert_eq!(creds.pid, Some(std::process::id()));
1361 let mut b = [0u8; 4];
1362 c.recv_exact(&mut b).unwrap();
1363 c.send_all(&b).unwrap();
1364 let theirs = t.join().unwrap();
1365 assert_eq!(theirs.uid, creds.uid);
1366 assert_eq!(c.recv(&mut b).unwrap(), 0);
1367 drop(l);
1368 assert!(!path.exists(), "the listener removed its file");
1369 let _ = std::fs::remove_dir_all(&d);
1370 }
1371
1372 #[test]
1373 fn test_stale_socket_removed_live_one_refused() {
1374 let d = dir("stale");
1375 let path = d.join("s.sock");
1376 {
1378 let s = sys::unix_socket().unwrap();
1379 sys::unix_bind(s.as_fd(), path.as_os_str().as_encoded_bytes()).unwrap();
1380 }
1381 assert!(path.exists());
1382 let refused = UnixListener::bind_with(&path, LocalOptions::new().remove_stale(false));
1383 assert!(matches!(refused, Err(NetError::StaleSocketInUse { .. })));
1384 let l = UnixListener::bind(&path).unwrap();
1385 assert!(matches!(
1387 UnixListener::bind(&path),
1388 Err(NetError::StaleSocketInUse { .. })
1389 ));
1390 drop(l);
1391 std::fs::write(&path, b"data").unwrap();
1393 assert!(matches!(
1394 UnixListener::bind(&path),
1395 Err(NetError::StaleSocketInUse { .. })
1396 ));
1397 assert_eq!(std::fs::read(&path).unwrap(), b"data");
1398 let _ = std::fs::remove_dir_all(&d);
1399 }
1400
1401 #[test]
1404 fn test_longest_path_binds_and_non_sockets_stay() {
1405 let d = dir("max");
1406 let base = d.as_os_str().len() + 1;
1407 let name = "a".repeat(sys::UNIX_PATH_MAX - 1 - base);
1408 let longest = d.join(&name);
1409 assert_eq!(longest.as_os_str().len(), sys::UNIX_PATH_MAX - 1);
1410 let l = UnixListener::bind(&longest).unwrap();
1411 let _c = UnixConnection::connect(&longest).unwrap();
1412 drop(l);
1413 let too_long = d.join(format!("{name}a"));
1414 assert!(matches!(
1415 UnixListener::bind(&too_long),
1416 Err(NetError::PathTooLong { .. })
1417 ));
1418 let sub = d.join("sub");
1419 std::fs::create_dir(&sub).unwrap();
1420 assert!(matches!(
1421 UnixListener::bind(&sub),
1422 Err(NetError::StaleSocketInUse { .. })
1423 ));
1424 assert!(sub.is_dir());
1425 let target = d.join("t.sock");
1426 let live = UnixListener::bind(&target).unwrap();
1427 let link = d.join("link.sock");
1428 std::os::unix::fs::symlink(&target, &link).unwrap();
1429 assert!(matches!(
1430 UnixListener::bind(&link),
1431 Err(NetError::StaleSocketInUse { .. })
1432 ));
1433 assert!(
1434 std::fs::symlink_metadata(&link)
1435 .unwrap()
1436 .file_type()
1437 .is_symlink()
1438 );
1439 drop(live);
1440 let _ = std::fs::remove_dir_all(&d);
1441 }
1442
1443 #[test]
1445 fn test_unknown_credentials_fail_require_uid() {
1446 let d = dir("nocreds");
1447 let path = d.join("s.sock");
1448 let l = UnixListener::bind_with(&path, LocalOptions::new().require_uid(0)).unwrap();
1449 assert!(!l.permits(None));
1450 let no_uid = PeerCredentials {
1451 pid: Some(1),
1452 uid: None,
1453 gid: None,
1454 };
1455 assert!(!l.permits(Some(no_uid)));
1456 let root = PeerCredentials {
1457 pid: None,
1458 uid: Some(0),
1459 gid: None,
1460 };
1461 assert!(l.permits(Some(root)));
1462 let open = UnixListener::bind(d.join("o.sock")).unwrap();
1463 assert!(open.permits(None));
1464 let _ = std::fs::remove_dir_all(&d);
1465 }
1466
1467 #[test]
1468 fn test_drop_leaves_a_replacement_alone() {
1469 let d = dir("replace");
1470 let path = d.join("s.sock");
1471 let l = UnixListener::bind(&path).unwrap();
1472 std::fs::remove_file(&path).unwrap();
1473 let other = UnixListener::bind(&path).unwrap();
1474 drop(l);
1475 assert!(
1476 path.exists(),
1477 "the first listener did not remove the second's file"
1478 );
1479 drop(other);
1480 assert!(!path.exists());
1481 let _ = std::fs::remove_dir_all(&d);
1482 }
1483
1484 #[test]
1485 fn test_bind_atomic_sets_mode_and_leaves_no_temporary() {
1486 let d = dir("atomic");
1487 let path = d.join("s.sock");
1488 let l = UnixListener::bind_atomic(&path, LocalOptions::new().mode(0o640)).unwrap();
1489 let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
1490 assert_eq!(mode, 0o640);
1491 let names: Vec<_> = std::fs::read_dir(&d)
1492 .unwrap()
1493 .map(|e| e.unwrap().file_name())
1494 .collect();
1495 assert_eq!(names.len(), 1, "{names:?}");
1496 let c = UnixConnection::connect(&path).unwrap();
1497 let (_s, _) = l.accept().unwrap();
1498 drop(c);
1499 let _ = std::fs::remove_dir_all(&d);
1500 }
1501
1502 #[test]
1503 fn test_path_checks() {
1504 let long = format!("/tmp/{}", "a".repeat(sys::UNIX_PATH_MAX));
1505 assert!(matches!(
1506 UnixListener::bind(&long),
1507 Err(NetError::PathTooLong { max }) if max == sys::UNIX_PATH_MAX
1508 ));
1509 assert!(matches!(
1510 UnixConnection::connect(&long),
1511 Err(NetError::PathTooLong { .. })
1512 ));
1513 let nul = <std::ffi::OsStr as std::os::unix::ffi::OsStrExt>::from_bytes(b"/tmp/a\0b");
1514 assert!(matches!(
1515 UnixListener::bind(nul),
1516 Err(NetError::InvalidConfig {
1517 field: "path",
1518 reason: ConfigReason::Malformed
1519 })
1520 ));
1521 let d = dir("missing");
1522 assert!(matches!(
1523 UnixConnection::connect(d.join("none.sock")),
1524 Err(NetError::NotFound)
1525 ));
1526 let _ = std::fs::remove_dir_all(&d);
1527 }
1528
1529 #[test]
1530 fn test_require_uid_closes_other_users() {
1531 let d = dir("uid");
1532 let path = d.join("s.sock");
1533 let me = std::os::unix::fs::MetadataExt::uid(&std::fs::metadata(&d).unwrap());
1534 let l = UnixListener::bind_with(&path, LocalOptions::new().require_uid(me.wrapping_add(1)))
1535 .unwrap();
1536 let mut c = UnixConnection::connect(&path).unwrap();
1537 assert!(
1538 l.accept_timeout(Duration::from_millis(200))
1539 .unwrap()
1540 .is_none()
1541 );
1542 c.set_limits(
1544 Limits::builder()
1545 .read_timeout(Duration::from_secs(2))
1546 .build()
1547 .unwrap(),
1548 );
1549 let mut b = [0u8; 1];
1550 assert!(matches!(
1551 c.recv(&mut b),
1552 Ok(0) | Err(NetError::ConnectionReset)
1553 ));
1554 drop(l);
1555 let l = UnixListener::bind_with(&path, LocalOptions::new().require_uid(me)).unwrap();
1556 let _c = UnixConnection::connect(&path).unwrap();
1557 assert!(l.accept_timeout(Duration::from_secs(2)).unwrap().is_some());
1558 let _ = std::fs::remove_dir_all(&d);
1559 }
1560
1561 #[test]
1562 fn test_descriptors_travel_with_bytes() {
1563 let d = dir("fds");
1564 let path = d.join("s.sock");
1565 let l = UnixListener::bind(&path).unwrap();
1566 let p2 = path.clone();
1567 let t = std::thread::spawn(move || {
1568 let mut c = UnixConnection::connect(&p2).unwrap();
1569 let (mut mine, theirs) = std::os::unix::net::UnixStream::pair().unwrap();
1570 c.send_descriptors(b"take this", &[theirs.as_fd()]).unwrap();
1571 mine.write_all(b"hello").unwrap();
1572 let mut b = [0u8; 1];
1573 let _ = c.recv(&mut b);
1574 drop(theirs);
1577 });
1578 let (mut c, _) = l.accept().unwrap();
1579 let mut fds = Descriptors::new();
1580 let mut body = [0u8; 32];
1581 let n = c.recv_descriptors(&mut body, &mut fds).unwrap();
1583 assert_eq!(&body[..n], b"take this");
1584 assert_eq!(fds.len(), 1);
1585 let fd = fds.take().next().unwrap();
1586 assert!(fds.is_empty());
1587 let mut s = std::os::unix::net::UnixStream::from(fd);
1588 let mut b = [0u8; 5];
1589 s.read_exact(&mut b).unwrap();
1590 assert_eq!(&b, b"hello");
1591 assert!(matches!(
1592 c.send_descriptors(b"", &[]),
1593 Err(NetError::InvalidConfig { field: "body", .. })
1594 ));
1595 c.close().unwrap();
1596 t.join().unwrap();
1597 let _ = std::fs::remove_dir_all(&d);
1598 }
1599
1600 fn dir_with_mode(tag: &str, mode: u32) -> PathBuf {
1602 let d = dir(tag);
1603 std::fs::set_permissions(&d, std::fs::Permissions::from_mode(mode)).unwrap();
1604 d
1605 }
1606
1607 fn mode_of(p: &Path) -> u32 {
1608 std::fs::symlink_metadata(p).unwrap().permissions().mode() & 0o7777
1609 }
1610
1611 fn names_in(d: &Path) -> Vec<std::ffi::OsString> {
1612 let mut names: Vec<_> = std::fs::read_dir(d)
1613 .unwrap()
1614 .map(|e| e.unwrap().file_name())
1615 .collect();
1616 names.sort();
1617 names
1618 }
1619
1620 #[test]
1624 fn test_bind_refuses_a_directory_others_can_rename_in() {
1625 let d = dir_with_mode("open", 0o777);
1626 let path = d.join("s.sock");
1627 for atomic in [false, true] {
1628 let r = if atomic {
1629 UnixListener::bind_atomic(&path, LocalOptions::new())
1630 } else {
1631 UnixListener::bind(&path)
1632 };
1633 assert!(
1634 matches!(
1635 r,
1636 Err(NetError::InvalidConfig {
1637 field: "path",
1638 reason: ConfigReason::InsecureDirectory
1639 })
1640 ),
1641 "atomic {atomic}: {r:?}"
1642 );
1643 }
1644 assert!(names_in(&d).is_empty(), "{:?}", names_in(&d));
1645 std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o1777)).unwrap();
1646 let l = UnixListener::bind(&path).unwrap();
1647 assert_eq!(mode_of(&path) & 0o777, 0o600);
1648 drop(l);
1649 let _ = std::fs::remove_dir_all(&d);
1650 }
1651
1652 #[test]
1657 fn test_socket_swapped_for_a_link_never_changes_its_target() {
1658 use std::os::unix::fs::FileTypeExt;
1659 use std::sync::atomic::{AtomicBool, Ordering};
1660 let d = dir_with_mode("swap", 0o770);
1661 let victim = d.join("victim");
1662 std::fs::write(&victim, b"secret").unwrap();
1663 std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o644)).unwrap();
1664 let path = d.join("s.sock");
1665 let stop = Arc::new(AtomicBool::new(false));
1666 let (v2, d2, s2) = (victim.clone(), d.clone(), stop.clone());
1667 let swapper = std::thread::spawn(move || {
1668 let link = d2.join("link");
1669 let mut swaps = 0u64;
1670 while !s2.load(Ordering::Relaxed) {
1671 let Ok(entries) = std::fs::read_dir(&d2) else {
1672 continue;
1673 };
1674 for e in entries.flatten() {
1675 if std::fs::symlink_metadata(&link).is_err() {
1676 let _ = std::os::unix::fs::symlink(&v2, &link);
1677 }
1678 if e.file_type().is_ok_and(|t| t.is_socket())
1679 && std::fs::rename(&link, e.path()).is_ok()
1680 {
1681 swaps += 1;
1682 }
1683 }
1684 }
1685 swaps
1686 });
1687 let start = Instant::now();
1688 let mut tries = 0u32;
1689 let mut changed = false;
1690 while tries < 400 && start.elapsed() < Duration::from_secs(20) && !changed {
1691 tries += 1;
1692 let _ = std::fs::remove_file(&path);
1693 let options = LocalOptions::new().mode(0o666);
1694 let r = if tries % 2 == 0 {
1695 UnixListener::bind_atomic(&path, options)
1696 } else {
1697 UnixListener::bind_with(&path, options)
1698 };
1699 drop(r);
1700 changed = mode_of(&victim) != 0o644;
1701 }
1702 stop.store(true, Ordering::Relaxed);
1703 let swaps = swapper.join().unwrap();
1704 eprintln!("{tries} binds, {swaps} swaps, {:?}", start.elapsed());
1705 assert!(
1706 !changed,
1707 "the victim's mode changed to {:o} after {tries} binds ({swaps} swaps)",
1708 mode_of(&victim)
1709 );
1710 let left: Vec<_> = names_in(&d)
1711 .into_iter()
1712 .filter(|n| n.as_encoded_bytes().starts_with(b".nio"))
1713 .collect();
1714 assert!(left.is_empty(), "private directories left behind: {left:?}");
1715 let _ = std::fs::remove_dir_all(&d);
1716 }
1717
1718 #[test]
1722 fn test_shared_directory_binds_with_mode_and_group() {
1723 use std::os::unix::fs::{FileTypeExt, MetadataExt};
1724 let d = dir_with_mode("shared", 0o770);
1725 let gid = std::fs::metadata(&d).unwrap().gid();
1727 let path = d.join("s.sock");
1728 let l = UnixListener::bind_with(&path, LocalOptions::new().group_access(gid)).unwrap();
1729 let meta = std::fs::symlink_metadata(&path).unwrap();
1730 assert!(meta.file_type().is_socket());
1731 assert_eq!((meta.mode() & 0o7777, meta.gid()), (0o660, gid));
1732 assert_eq!(l.path(), Some(path.as_path()));
1733 assert_eq!(names_in(&d), ["s.sock"]);
1734 let c = UnixConnection::connect(&path).unwrap();
1735 let (_s, _) = l.accept().unwrap();
1736 drop(c);
1737 assert!(matches!(
1739 UnixListener::bind(&path),
1740 Err(NetError::StaleSocketInUse { .. })
1741 ));
1742 assert!(matches!(
1743 UnixListener::bind_atomic(&path, LocalOptions::new()),
1744 Err(NetError::StaleSocketInUse { .. })
1745 ));
1746 drop(l);
1747 assert!(!path.exists(), "the listener removed its file");
1748 {
1750 let s = sys::unix_socket().unwrap();
1751 sys::unix_bind(s.as_fd(), path.as_os_str().as_encoded_bytes()).unwrap();
1752 }
1753 let stale = std::fs::symlink_metadata(&path).unwrap().ino();
1754 let l = UnixListener::bind_atomic(&path, LocalOptions::new().mode(0o640)).unwrap();
1755 let meta = std::fs::symlink_metadata(&path).unwrap();
1756 assert!(meta.file_type().is_socket() && meta.ino() != stale);
1757 assert_eq!(meta.mode() & 0o7777, 0o640);
1758 assert_eq!(names_in(&d), ["s.sock"]);
1759 let c = UnixConnection::connect(&path).unwrap();
1760 let (_s, _) = l.accept().unwrap();
1761 drop(c);
1762 drop(l);
1763 {
1765 let s = sys::unix_socket().unwrap();
1766 sys::unix_bind(s.as_fd(), path.as_os_str().as_encoded_bytes()).unwrap();
1767 }
1768 let l = UnixListener::bind(&path).unwrap();
1769 assert_eq!(mode_of(&path), 0o600);
1770 assert_eq!(names_in(&d), ["s.sock"]);
1771 drop(l);
1772 let _ = std::fs::remove_dir_all(&d);
1773 }
1774
1775 #[test]
1778 fn test_private_directory_binds_in_place_with_mode_and_group() {
1779 use std::os::unix::fs::{FileTypeExt, MetadataExt};
1780 let d = dir_with_mode("own", 0o700);
1781 let gid = std::fs::metadata(&d).unwrap().gid();
1783 let path = d.join("s.sock");
1784 let l = UnixListener::bind_with(&path, LocalOptions::new().group_access(gid)).unwrap();
1785 let meta = std::fs::symlink_metadata(&path).unwrap();
1786 assert!(meta.file_type().is_socket());
1787 assert_eq!((meta.mode() & 0o7777, meta.gid()), (0o660, gid));
1788 assert_eq!(names_in(&d), ["s.sock"]);
1789 drop(l);
1790 {
1791 let s = sys::unix_socket().unwrap();
1792 sys::unix_bind(s.as_fd(), path.as_os_str().as_encoded_bytes()).unwrap();
1793 }
1794 let l = UnixListener::bind_atomic(&path, LocalOptions::new().mode(0o604)).unwrap();
1795 assert_eq!(mode_of(&path), 0o604);
1796 assert_eq!(names_in(&d), ["s.sock"]);
1797 let c = UnixConnection::connect(&path).unwrap();
1798 let (_s, _) = l.accept().unwrap();
1799 drop(c);
1800 drop(l);
1801 assert!(matches!(
1802 UnixListener::bind(d.join("missing").join("s.sock")),
1803 Err(NetError::NotFound)
1804 ));
1805 let _ = std::fs::remove_dir_all(&d);
1806 }
1807
1808 #[test]
1811 fn test_another_users_directory_binds_through_a_private_one() {
1812 if sys::effective_uid() != 0 {
1813 return;
1814 }
1815 let d = dir_with_mode("theirs", 0o755);
1816 std::os::unix::fs::chown(&d, Some(65_534), None).unwrap();
1817 let path = d.join("s.sock");
1818 let l = UnixListener::bind_with(&path, LocalOptions::new().owner(65_534)).unwrap();
1819 let meta = std::fs::symlink_metadata(&path).unwrap();
1820 assert_eq!(
1821 (
1822 meta.permissions().mode() & 0o7777,
1823 std::os::unix::fs::MetadataExt::uid(&meta)
1824 ),
1825 (0o600, 65_534)
1826 );
1827 assert_eq!(names_in(&d), ["s.sock"]);
1828 drop(l);
1829 let _ = std::fs::remove_dir_all(&d);
1830 }
1831
1832 #[test]
1833 fn test_directory_trust_from_owner_and_mode() {
1834 use DirTrust::{Safe, Shared};
1835 let me = 1000;
1836 let cases = [
1837 (me, 0o700, Some(Safe)),
1838 (me, 0o755, Some(Safe)),
1839 (0, 0o755, Some(Safe)),
1840 (0, 0o1777, Some(Safe)),
1841 (me, 0o1777, Some(Safe)),
1842 (me, 0o1770, Some(Safe)),
1843 (me, 0o770, Some(Shared)),
1844 (0, 0o775, Some(Shared)),
1845 (2000, 0o700, Some(Shared)),
1846 (2000, 0o1777, Some(Shared)),
1847 (me, 0o777, None),
1848 (0, 0o777, None),
1849 (me, 0o703, None),
1850 (2000, 0o2777, None),
1851 ];
1852 for (owner, mode, want) in cases {
1853 assert_eq!(dir_trust(owner, mode, me), want, "{owner} {mode:o}");
1854 }
1855 assert_eq!(
1856 split_path(b"/run/a.sock").unwrap(),
1857 (&b"/run"[..], &b"a.sock"[..])
1858 );
1859 assert_eq!(split_path(b"/a.sock").unwrap(), (&b"/"[..], &b"a.sock"[..]));
1860 assert_eq!(split_path(b"a.sock").unwrap(), (&b"."[..], &b"a.sock"[..]));
1861 assert_eq!(split_path(b"x//a").unwrap(), (&b"x/"[..], &b"a"[..]));
1862 for bad in [&b"x/"[..], b"x/.", b"x/..", b".", b".."] {
1863 assert!(matches!(
1864 split_path(bad),
1865 Err(NetError::InvalidConfig {
1866 field: "path",
1867 reason: ConfigReason::Malformed
1868 })
1869 ));
1870 }
1871 }
1872
1873 #[test]
1874 fn test_local_enums_round_trip() {
1875 let d = dir("enums");
1876 let path = d.join("s.sock");
1877 let name = path.to_str().unwrap().to_owned();
1878 let l = listen(&name).unwrap();
1879 let n2 = name.clone();
1880 let t = std::thread::spawn(move || {
1881 let mut c = connect(&n2).unwrap();
1882 c.send_all(b"hi").unwrap();
1883 c.close().unwrap();
1884 });
1885 let (mut c, info) = l.accept().unwrap();
1886 assert_eq!(info.transport, Transport::Unix);
1887 let mut b = [0u8; 2];
1888 c.recv_exact(&mut b).unwrap();
1889 assert_eq!(&b, b"hi");
1890 t.join().unwrap();
1891 let _ = std::fs::remove_dir_all(&d);
1892 }
1893}