uds_fork/addr.rs
1
2use std::
3{
4 mem,
5 slice,
6 fmt::{self, Debug, Display},
7 hash::{Hash, Hasher},
8 path::Path,
9 ffi::{OsStr, CStr},
10 os::unix::{net, ffi::OsStrExt},
11 io::{self, ErrorKind}
12};
13
14
15use libc::{sockaddr, sa_family_t, AF_UNIX, socklen_t, sockaddr_un, c_char};
16
17/// Offset of `.sun_path` in `sockaddr_un`.
18///
19/// This is not always identical to `mem::size_of::<sa_family_t>()`,
20/// as there can be other fields before or after `.sun_family`.
21fn path_offset() -> socklen_t
22{
23 unsafe
24 {
25 let total_size = mem::size_of::<sockaddr_un>();
26 let name_size = mem::size_of_val(&mem::zeroed::<sockaddr_un>().sun_path);
27
28 (total_size - name_size) as socklen_t
29 }
30}
31
32const
33fn as_u8(slice: &[c_char]) -> &[u8]
34{
35 unsafe { &*(slice as *const[c_char] as *const[u8]) }
36}
37
38const
39fn as_char(slice: &[u8]) -> &[c_char]
40{
41 unsafe { &*(slice as *const[u8] as *const[c_char]) }
42}
43
44const TOO_LONG_DESC: &str = "address is too long";
45
46
47/// A unix domain socket address.
48///
49/// # Differences from `std`'s `unix::net::SocketAddr`
50///
51/// This type fully supports Linux's abstract socket addresses,
52/// and can be created by user code instead of just returned by `accept()`
53/// and similar.
54///
55/// # Examples
56///
57/// Creating an abstract address (fails if the OS doesn't support them):
58///
59#[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
60#[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
61/// use uds_fork::UnixSocketAddr;
62///
63/// let addr = UnixSocketAddr::new("@abstract").unwrap();
64/// assert!(addr.is_abstract());
65/// assert_eq!(addr.to_string(), "@abstract");
66/// ```
67#[derive(Clone,Copy)]
68pub struct UnixSocketAddr
69{
70 addr: sockaddr_un,
71
72 /// How many bytes of addr are in use.
73 ///
74 /// Must never be greater than `size_of::<sockaddr_un>()`.
75 ///
76 /// On BSDs and macOS, `sockaddr_un` has a (non-standard) `.sun_len` field
77 /// that *could* be used to store the length instead, but doing that is
78 /// not a very good idea:
79 /// At least [NetBSD ignores it](http://mail-index.netbsd.org/tech-net/2006/10/11/0008.html)
80 /// so we would still need to pass a correctly set `socklen_t`,
81 /// in some cases by referece.
82 /// Because it's rarely used and some BSDs aren't afraid to break stuff,
83 /// it could even dissappear in the future.
84 /// The size this extra field is also rather minor compared to the size of
85 /// `sockaddr_un`, so the possible benefit is tiny.
86 len: socklen_t,
87}
88
89/// An enum representation of an unix socket address.
90///
91/// Useful for pattern matching an [`UnixSocketAddr`](struct.UnixSocketAddr.html)
92/// via [`UnixSocketAddr.name()`](struct.UnixSocketAddr.html#method.name).
93///
94/// It cannot be used to bind or connect a socket directly as it
95/// doesn't contain a `sockaddr_un`, but a `UnixSocketAddr` can be created
96/// from it.
97///
98/// # Examples
99///
100/// Cleaning up pathname socket files after ourselves:
101///
102/// ```no_run
103/// # use uds_fork::{UnixSocketAddr, AddrName};
104/// let addr = UnixSocketAddr::from_path("/var/run/socket.sock").unwrap();
105/// if let AddrName::Path(path) = addr.name() {
106/// let _ = std::fs::remove_file(path);
107/// }
108/// ```
109#[derive(Clone,Copy, PartialEq,Eq,Hash, Debug)]
110pub enum AddrName<'a>
111{
112 /// Unnamed / anonymous address.
113 Unnamed,
114 /// Regular file path based address.
115 ///
116 /// Can be both relative and absolute.
117 Path(&'a Path),
118 /// Address in the abstract namespace.
119 Abstract(&'a [u8]),
120}
121
122impl<'a> From<&'a UnixSocketAddr> for AddrName<'a>
123{
124 fn from(addr: &'a UnixSocketAddr) -> AddrName<'a>
125 {
126 let name_len = addr.len as isize - path_offset() as isize;
127
128 if addr.is_unnamed() == true
129 {
130 AddrName::Unnamed
131 }
132 else if addr.is_abstract() == true
133 {
134 let slice = &addr.addr.sun_path[1..name_len as usize];
135 AddrName::Abstract(as_u8(slice))
136 }
137 else
138 {
139 let mut slice = &addr.addr.sun_path[..name_len as usize];
140
141 // remove trailing NUL if present (and multiple NULs on OpenBSD)
142 while let Some(&0) = slice.last()
143 {
144 slice = &slice[..slice.len()-1];
145 }
146
147 AddrName::Path(Path::new(OsStr::from_bytes(as_u8(slice))))
148 }
149 }
150}
151
152pub type UnixSocketAddrRef<'a> = AddrName<'a>;
153
154impl Debug for UnixSocketAddr
155{
156 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result
157 {
158 #[derive(Debug)]
159 struct Unnamed;
160 #[derive(Debug)]
161 struct Path<'a>(&'a std::path::Path);
162 #[derive(Debug)]
163 struct Abstract<'a>(&'a OsStr);
164
165 // doesn't live long enough if created inside match
166 let mut path_type = Path("".as_ref());
167 let mut abstract_type = Abstract(OsStr::new(""));
168
169 let variant: &dyn Debug =
170 match self.into()
171 {
172 UnixSocketAddrRef::Unnamed =>
173 &Unnamed,
174 UnixSocketAddrRef::Path(path) =>
175 {
176 path_type.0 = path;
177 &path_type
178 },
179 UnixSocketAddrRef::Abstract(name) =>
180 {
181 abstract_type.0 = OsStr::from_bytes(name);
182 &abstract_type
183 },
184 };
185 fmtr.debug_tuple("UnixSocketAddr").field(variant).finish()
186 }
187}
188
189impl Display for UnixSocketAddr
190{
191 fn fmt(&self, fmtr: &mut fmt::Formatter) -> fmt::Result
192 {
193 match self.into()
194 {
195 UnixSocketAddrRef::Unnamed =>
196 fmtr.write_str("unnamed"),
197 UnixSocketAddrRef::Path(path) =>
198 write!(fmtr, "{}", path.display()), // TODO check that display() doesn't print \n as-is
199 UnixSocketAddrRef::Abstract(name) =>
200 write!(fmtr, "@{}", OsStr::from_bytes(name).to_string_lossy()), // FIXME escape to sane characters
201 }
202 }
203}
204
205impl UnixSocketAddr
206{
207 /// Allows creating abstract, path or unspecified address based on an
208 /// user-supplied string.
209 ///
210 /// A leading `'@'` or `'\0'` signifies an abstract address,
211 /// an empty slice is taken as the unnamed address, and anything else is a
212 /// path address.
213 /// If a relative path address starts with `@`, escape it by prepending
214 /// `"./"`.
215 /// To avoid surprises, abstract addresses will be detected regargsless of
216 /// wheither the OS supports them, and result in an error if it doesn't.
217 ///
218 /// # Errors
219 ///
220 /// * A path or abstract address is too long.
221 /// * A path address contains `'\0'`.
222 /// * An abstract name was supplied on an OS that doesn't support them.
223 ///
224 /// # Examples
225 ///
226 /// Abstract address:
227 ///
228 /// ```
229 /// # use uds_fork::UnixSocketAddr;
230 /// if UnixSocketAddr::has_abstract_addresses() {
231 /// assert!(UnixSocketAddr::new("@abstract").unwrap().is_abstract());
232 /// assert!(UnixSocketAddr::new("\0abstract").unwrap().is_abstract());
233 /// } else {
234 /// assert!(UnixSocketAddr::new("@abstract").is_err());
235 /// assert!(UnixSocketAddr::new("\0abstract").is_err());
236 /// }
237 /// ```
238 ///
239 /// Escaped path address:
240 ///
241 /// ```
242 /// # use uds_fork::UnixSocketAddr;
243 /// assert!(UnixSocketAddr::new("./@path").unwrap().is_relative_path());
244 /// ```
245 ///
246 /// Unnamed address:
247 ///
248 /// ```
249 /// # use uds_fork::UnixSocketAddr;
250 /// assert!(UnixSocketAddr::new("").unwrap().is_unnamed());
251 /// ```
252 pub
253 fn new<A: AsRef<[u8]>+?Sized>(addr: &A) -> Result<Self, io::Error>
254 {
255 fn parse(addr: &[u8]) -> Result<UnixSocketAddr, io::Error>
256 {
257 match addr.first()
258 {
259 Some(&b'@') | Some(&b'\0') =>
260 UnixSocketAddr::from_abstract(&addr[1..]),
261 Some(_) =>
262 UnixSocketAddr::from_path(Path::new(OsStr::from_bytes(addr))),
263 None =>
264 Ok(UnixSocketAddr::new_unspecified()),
265 }
266 }
267
268 return parse(addr.as_ref());
269 }
270
271 /// Creates an unnamed address, which on Linux can be used for auto-bind.
272 ///
273 /// Binding a socket to the unnamed address is different from not binding
274 /// at all:
275 ///
276 /// On Linux doing so binds the socket to a random abstract address
277 /// determined by the OS.
278 ///
279 /// # Examples
280 ///
281 #[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
282 #[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
283 /// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
284 /// # use std::os::unix::net::UnixDatagram;
285 /// let addr = UnixSocketAddr::new_unspecified();
286 /// assert!(addr.is_unnamed());
287 /// let socket = UnixDatagram::unbound().unwrap();
288 /// socket.bind_to_unix_addr(&addr).unwrap();
289 /// assert!(socket.local_unix_addr().unwrap().is_abstract());
290 /// ```
291 pub
292 fn new_unspecified() -> Self
293 {
294 let mut addr: sockaddr_un = unsafe { mem::zeroed() };
295 addr.sun_family = AF_UNIX as sa_family_t;
296
297 return
298 UnixSocketAddr
299 {
300 len: path_offset(),
301 addr,
302 };
303 }
304
305 /// Returns the maximum size of pathname addresses supported by `UnixSocketAddr`.
306 ///
307 /// Is the size of the underlying `sun_path` field, minus 1 if the OS
308 /// is known to either require a trailing NUL (`'\0'`) byte,
309 /// or supports longer paths that go past the end of `sun_path`.
310 ///
311 /// These OSes are:
312 ///
313 /// * OpenBSD: Enforces that `sun_path`` is NUL-terminated.
314 /// * macOS / iOS / anything else Apple: I haven't found a manpage,
315 /// but it supports longer paths.
316 /// * Illumos: [The manpage](https://illumos.org/man/3SOCKET/sockaddr_un)
317 /// says it must be NUL-terminated (and that it cannot be longer),
318 /// but when I tested on an older version, neither of these constraints seem to be the case.
319 /// * Solaris: Assumed to be identical to Illumos.
320 ///
321 /// OSes that have been tested that they allow using the full `sun_path`
322 /// without NUL and no longer paths, and whose manpages don't state the opposite:
323 ///
324 /// * [Linux](https://www.man7.org/linux/man-pages/man7/unix.7.html)
325 /// * [FreeBSD](https://man.freebsd.org/cgi/man.cgi?query=unix&sektion=4)
326 /// * [NetBSD](https://man.netbsd.org/unix.4)
327 /// * [Dragonfly BSD](https://man.dragonflybsd.org/?command=unix§ion=4)
328 pub
329 fn max_path_len() -> usize
330 {
331 let always_nul_terminate =
332 cfg!(any(
333 target_os="openbsd",
334 target_vendor="apple",
335 target_os="illumos",
336 target_os="solaris",
337 ));
338
339 return
340 if always_nul_terminate == true
341 {
342 mem::size_of_val(&Self::new_unspecified().addr.sun_path) - 1
343 }
344 else
345 {
346 mem::size_of_val(&Self::new_unspecified().addr.sun_path)
347 };
348 }
349
350 /// Creates a pathname unix socket address.
351 ///
352 /// # Errors
353 ///
354 /// This function will return an error if the path is too long for the
355 /// underlying `sockaddr_un` type, or contains NUL (`'\0'`) bytes.
356 pub
357 fn from_path<P: AsRef<Path>+?Sized>(path: &P) -> Result<Self, io::Error>
358 {
359 fn from_path_inner(path: &[u8]) -> Result<UnixSocketAddr, io::Error>
360 {
361 let mut addr = UnixSocketAddr::new_unspecified();
362 let capacity = UnixSocketAddr::max_path_len();
363
364 if path.is_empty() == true
365 {
366 return Err(io::Error::new(ErrorKind::NotFound, "path is empty"));
367 }
368 else if path.len() > capacity
369 {
370 let message = "path is too long for an unix socket address";
371
372 return Err(io::Error::new(ErrorKind::InvalidInput, message));
373 }
374 else if path.iter().any(|&b| b == b'\0' ) == true
375 {
376 return Err(io::Error::new(ErrorKind::InvalidInput, "path cannot contain nul bytes"));
377 }
378 else
379 {
380 addr.addr.sun_path[..path.len()].copy_from_slice(as_char(path));
381 addr.len = path_offset() + path.len() as socklen_t;
382 if path.len() < capacity {
383 addr.len += 1; // for increased portability
384 }
385
386 return Ok(addr);
387 }
388 }
389 from_path_inner(path.as_ref().as_os_str().as_bytes())
390 }
391
392 /// Returns maximum size of abstract addesses supported by `UnixSocketAddr`.
393 ///
394 /// Is the size of the underlying `sun_path` field minus 1 for the
395 /// leading `'\0'` byte.
396 ///
397 /// This value is also returned on operating systems that doesn't support
398 /// abstract addresses.
399 pub
400 fn max_abstract_len() -> usize
401 {
402 mem::size_of_val(&Self::new_unspecified().addr.sun_path) - 1
403 }
404
405 /// Returns whether the operating system is known to support
406 /// abstract unix domain socket addresses.
407 ///
408 /// Is `true` for Linux & Android, and `false` for all other OSes.
409 pub const
410 fn has_abstract_addresses() -> bool
411 {
412 cfg!(any(target_os="linux", target_os="android"))
413 }
414
415 /// Creates an abstract unix domain socket address.
416 ///
417 /// Abstract addresses use a namespace separate from the file system,
418 /// that doesn't have directories (ie. is flat) or permissions.
419 /// The advandage of it is that the address disappear when the socket bound
420 /// to it is closed, which frees one from dealing with removing it when
421 /// shutting down cleanly.
422 ///
423 /// They are a Linux-only feature though, and this function will fail
424 /// if abstract addresses are not supported.
425 ///
426 /// # Errors
427 ///
428 /// This function will return an error if the name is too long.
429 /// Call [`max_abstract_len()`](#method.max_abstract_len)
430 /// get the limit.
431 ///
432 /// It will also fail on operating systems that don't support abstract
433 /// addresses. (ie. anything other than Linux and Android)
434 pub
435 fn from_abstract<N: AsRef<[u8]>+?Sized>(name: &N) -> Result<Self, io::Error>
436 {
437 fn from_abstract_inner(name: &[u8]) -> Result<UnixSocketAddr, io::Error>
438 {
439 let mut addr = UnixSocketAddr::new_unspecified();
440
441 if UnixSocketAddr::has_abstract_addresses() == false
442 {
443 return
444 Err(
445 io::Error::new(
446 ErrorKind::AddrNotAvailable,
447 format!( "abstract unix domain socket addresses are not available on {}",
448 std::env::consts::OS)
449 )
450 );
451 }
452 else if name.len() > UnixSocketAddr::max_abstract_len()
453 {
454 return
455 Err(io::Error::new(ErrorKind::InvalidInput, "abstract name is too long"));
456 }
457 else
458 {
459 addr.addr.sun_path[1..1+name.len()].copy_from_slice(as_char(name));
460 addr.len = path_offset() + 1 + name.len() as socklen_t;
461 return Ok(addr);
462 }
463 }
464
465 return from_abstract_inner(name.as_ref());
466 }
467
468 /// Tries to convert a `std::os::unix::net::SocketAddr` into an `UnixSocketAddr`.
469 ///
470 /// This can fail (produce `None`) on Linux and Android
471 /// if the `std` `SocketAddr` represents an abstract address,
472 /// as it provides no method for viewing abstract addresses.
473 /// (other than parsing its `Debug` output, anyway.)
474 pub
475 fn from_std(addr: net::SocketAddr) -> Option<Self>
476 {
477 return
478 if let Some(path) = addr.as_pathname()
479 {
480 Some(Self::from_path(path).expect("pathname addr cannot be converted"))
481 }
482 else if addr.is_unnamed()
483 {
484 Some(Self::new_unspecified())
485 }
486 else
487 {
488 None
489 };
490 }
491
492 /// Returns unnamed addres for empty strings, and path addresses otherwise.
493 ///
494 /// # Errors
495 ///
496 /// Returns ENAMETOOLONG if path (without the trailing `'\0'`) is too long
497 /// for `sockaddr_un.sun_path`.
498 pub
499 fn from_c_str(path: &CStr) -> Result<Self, io::Error>
500 {
501 let path = path.to_bytes();
502 let mut addr = Self::new_unspecified();
503
504 if path.is_empty()
505 {
506 return Ok(addr);
507 }
508 else if path.len() > mem::size_of_val(&addr.addr.sun_path)
509 {
510 let message = "path is too long for unix socket address";
511
512 return Err(io::Error::new(ErrorKind::InvalidInput, message));
513 }
514 else
515 {
516 addr.addr.sun_path[..path.len()].copy_from_slice(as_char(path));
517 addr.len = path_offset() + path.len() as socklen_t;
518
519 if path.len() < mem::size_of_val(&addr.addr.sun_path)
520 {
521 addr.len += 1;
522 }
523
524 return Ok(addr);
525 }
526 }
527
528 /// Checks whether the address is unnamed.
529 #[inline]
530 pub
531 fn is_unnamed(&self) -> bool
532 {
533 if Self::has_abstract_addresses()
534 {
535 return self.len <= path_offset();
536 }
537 else
538 {
539 // MacOS can apparently return non-empty addresses but with
540 // all-zeroes path for unnamed addresses.
541 return self.len <= path_offset() || self.addr.sun_path[0] as u8 == b'\0';
542 }
543 }
544
545 /// Checks whether the address is a name in the abstract namespace.
546 ///
547 /// Always returns `false` on operating systems that don't support abstract
548 /// addresses.
549 pub
550 fn is_abstract(&self) -> bool
551 {
552 if Self::has_abstract_addresses() == true
553 {
554 return self.len > path_offset() && self.addr.sun_path[0] as u8 == b'\0';
555 }
556 else
557 {
558 return false;
559 }
560 }
561
562 /// Checks whether the address is a path that begins with '/'.
563 #[inline]
564 pub fn is_absolute_path(&self) -> bool
565 {
566 self.len > path_offset() && self.addr.sun_path[0] as u8 == b'/'
567 }
568
569 /// Checks whether the address is a path that doesn't begin with '/'.
570 #[inline]
571 pub
572 fn is_relative_path(&self) -> bool
573 {
574 self.len > path_offset()
575 && self.addr.sun_path[0] as u8 != b'\0'
576 && self.addr.sun_path[0] as u8 != b'/'
577 }
578 /// Checks whether the address is a path.
579 #[inline]
580 pub
581 fn is_path(&self) -> bool
582 {
583 self.len > path_offset() && self.addr.sun_path[0] as u8 != b'\0'
584 }
585
586 /// Returns a view of the address that can be pattern matched
587 /// to the differnt types of addresses.
588 ///
589 /// # Examples
590 ///
591 /// ```
592 /// use uds_fork::{UnixSocketAddr, AddrName};
593 /// use std::path::Path;
594 ///
595 /// assert_eq!(
596 /// UnixSocketAddr::new_unspecified().name(),
597 /// AddrName::Unnamed
598 /// );
599 /// assert_eq!(
600 /// UnixSocketAddr::from_path("/var/run/socket.sock").unwrap().name(),
601 /// AddrName::Path(Path::new("/var/run/socket.sock"))
602 /// );
603 /// if UnixSocketAddr::has_abstract_addresses() {
604 /// assert_eq!(
605 /// UnixSocketAddr::from_abstract("tcartsba").unwrap().name(),
606 /// AddrName::Abstract(b"tcartsba")
607 /// );
608 /// }
609 /// ```
610 pub
611 fn name(&self) -> AddrName<'_>
612 {
613 AddrName::from(self)
614 }
615
616 /// Returns the path of a path-based address.
617 pub
618 fn as_pathname(&self) -> Option<&Path>
619 {
620 let UnixSocketAddrRef::Path(path) = UnixSocketAddrRef::from(self)
621 else { return None };
622
623 return Some(path);
624 }
625
626 /// Returns the name of an address which is in the abstract namespace.
627 pub
628 fn as_abstract(&self) -> Option<&[u8]>
629 {
630 let UnixSocketAddrRef::Abstract(name) = UnixSocketAddrRef::from(self)
631 else {return None};
632
633 return Some(name);
634 }
635
636 /// Returns a view that can be pattern matched to the differnt types of
637 /// addresses.
638 ///
639 /// # Examples
640 ///
641 /// ```
642 /// use uds_fork::{UnixDatagramExt, UnixSocketAddr, UnixSocketAddrRef};
643 /// use std::os::unix::net::UnixDatagram;
644 /// use std::path::Path;
645 ///
646 /// # let _ = std::fs::remove_file("/tmp/dgram.socket");
647 /// let receiver = UnixDatagram::bind("/tmp/dgram.socket").expect("create datagram socket");
648 /// assert_eq!(
649 /// receiver.local_unix_addr().unwrap().as_ref(),
650 /// UnixSocketAddrRef::Path(Path::new("/tmp/dgram.socket"))
651 /// );
652 ///
653 /// let sender = UnixDatagram::unbound().expect("create unbound datagram socket");
654 /// sender.send_to(b"I can't hear you", "/tmp/dgram.socket").expect("send");
655 ///
656 /// let mut buf = [0; 100];
657 /// let (len, addr) = receiver.recv_from_unix_addr(&mut buf).unwrap();
658 /// assert_eq!(addr.as_ref(), UnixSocketAddrRef::Unnamed);
659 /// # std::fs::remove_file("/tmp/dgram.socket").expect("clean up socket file");
660 /// ```
661 pub
662 fn as_ref(&self) -> UnixSocketAddrRef<'_>
663 {
664 UnixSocketAddrRef::from(self)
665 }
666
667 /// Creates an address from a slice of bytes to place in `sun_path`.
668 ///
669 /// This is a low-level but simple interface for creating addresses by
670 /// other unix socket wrappers without exposing any libc types.
671 /// The meaning of a slice can vary between operating systems.
672 ///
673 /// `addr` should point to thes start of the "path" part of a socket
674 /// address, with length being the number of valid bytes of the path.
675 /// (Trailing NULs are not stripped by this function.)
676 ///
677 /// # Errors
678 ///
679 /// If the slice is longer than `sun_path`, an error of kind `Other` is
680 /// returned. No other validation of the bytes is performed.
681 ///
682 /// # Examples
683 ///
684 /// A normal path-based address
685 ///
686 /// ```
687 /// # use std::path::Path;
688 /// # use uds_fork::UnixSocketAddr;
689 /// let addr = UnixSocketAddr::from_raw_bytes(b"/tmp/a.sock\0").unwrap();
690 /// assert_eq!(addr.as_pathname(), Some(Path::new("/tmp/a.sock")));
691 /// assert_eq!(addr.as_raw_bytes(), b"/tmp/a.sock\0");
692 /// ```
693 ///
694 /// On Linux:
695 ///
696 #[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
697 #[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
698 /// # use uds_fork::UnixSocketAddr;
699 /// let addr = UnixSocketAddr::from_raw_bytes(b"\0a").unwrap();
700 /// assert_eq!(addr.as_abstract(), Some(&b"a"[..]));
701 /// assert_eq!(addr.as_raw_bytes(), b"\0a");
702 /// ```
703 ///
704 /// Elsewhere:
705 ///
706 #[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```")]
707 #[cfg_attr(any(target_os="linux", target_os="android"), doc="```no_run")]
708 /// # use uds_fork::UnixSocketAddr;
709 /// let addr = UnixSocketAddr::from_raw_bytes(b"\0a").unwrap();
710 /// assert!(addr.is_unnamed());
711 /// assert_eq!(addr.as_raw_bytes().len(), 2);
712 /// ```
713 ///
714 /// A portable unnamed address:
715 ///
716 /// ```
717 /// # use uds_fork::UnixSocketAddr;
718 /// let addr = UnixSocketAddr::from_raw_bytes(&[]).expect("not too long");
719 /// assert!(addr.is_unnamed());
720 /// assert!(addr.as_raw_bytes().is_empty());
721 /// ```
722 pub
723 fn from_raw_bytes(addr: &[u8]) -> Result<Self, io::Error>
724 {
725 if addr.len() <= Self::max_path_len()
726 {
727 let name = addr;
728 let mut addr = Self::default();
729 addr.addr.sun_path[..name.len()].copy_from_slice(as_char(name));
730 addr.len = path_offset() + name.len() as socklen_t;
731
732 return Ok(addr);
733 }
734 else
735 {
736 return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
737 }
738 }
739 /// Returns a low-level view of the address without using any libc types.
740 ///
741 /// The returned slice points to the start of `sun_addr` of the contained
742 /// `sockaddr_un`, and the length is the number of bytes of `sun_addr`
743 /// that were filled out by the OS. Any trailing NUL(s) will be preserved.
744 ///
745 /// # Examples
746 ///
747 /// A normal path-based address:
748 ///
749 /// ```
750 /// # use std::path::Path;
751 /// # use std::os::unix::net::UnixDatagram;
752 /// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
753 /// let pathname = "/tmp/a_file";
754 /// let socket = UnixDatagram::bind(pathname).expect("create datagram socket");
755 /// # let _ = std::fs::remove_file(pathname);
756 /// let addr = socket.local_unix_addr().expect("get its address");
757 /// assert!(addr.as_raw_bytes().starts_with(pathname.as_bytes()));
758 /// assert!(addr.as_raw_bytes()[pathname.len()..].iter().all(|&b| b == b'\0' ));
759 /// assert_eq!(addr.as_pathname(), Some(Path::new(pathname)));
760 /// ```
761 ///
762 /// Abstract address:
763 ///
764 #[cfg_attr(any(target_os="linux", target_os="android"), doc="```")]
765 #[cfg_attr(not(any(target_os="linux", target_os="android")), doc="```no_run")]
766 /// # use uds_fork::UnixSocketAddr;
767 /// let addr = UnixSocketAddr::new("@someone@").unwrap();
768 /// assert_eq!(addr.as_raw_bytes(), b"\0someone@");
769 /// ```
770 ///
771 /// Unnamed address on macOS, OpenBSD and maybe others:
772 ///
773 #[cfg_attr(any(target_vendor="apple", target_os="openbsd"), doc="```")]
774 #[cfg_attr(not(any(target_vendor="apple", target_os="openbsd")), doc="```no_run")]
775 /// # use std::os::unix::net::UnixDatagram;
776 /// # use uds_fork::{UnixSocketAddr, UnixDatagramExt};
777 /// let socket = UnixDatagram::unbound().expect("create datagram socket");
778 /// let addr = socket.local_unix_addr().expect("get its unbound address");
779 /// let bytes = addr.as_raw_bytes();
780 /// assert!(bytes.len() > 0);
781 /// assert!(bytes.iter().all(|&b| b == b'\0' ));
782 /// assert!(addr.is_unnamed());
783 /// ```
784 pub
785 fn as_raw_bytes(&self) -> &[u8]
786 {
787 as_u8(&self.addr.sun_path[..(self.len-path_offset()) as usize])
788 }
789
790 /// Prepares a `struct sockaddr*` and `socklen_t*` for passing to FFI
791 /// (such as `getsockname()`, `getpeername()`, or `accept()`),
792 /// and validate and normalize the produced address afterwards.
793 ///
794 /// Validation:
795 ///
796 /// * Check that the address family is `AF_UNIX`.
797 /// * Check that the address wasn't truncated (the `socklen_t` is too big).
798 ///
799 /// Normalization:
800 ///
801 /// * Ensure path addresses have a trailing NUL byte if there is space.
802 pub
803 fn new_from_ffi<R, F>(call: F) -> Result<(R, Self), io::Error>
804 where
805 F: FnOnce(&mut sockaddr, &mut socklen_t) -> Result<R, io::Error>
806 {
807 let mut addr = Self::new_unspecified();
808 let capacity = mem::size_of_val(&addr.addr) as socklen_t;
809 addr.len = capacity;
810
811 unsafe
812 {
813 let (addr_ptr, addr_len_ptr) = addr.as_raw_mut_general();
814 let ret = call(addr_ptr, addr_len_ptr)?;
815
816 if addr.addr.sun_family != AF_UNIX as sa_family_t
817 {
818 return Err(
819 io::Error::new(
820 ErrorKind::InvalidData,
821 "file descriptor did not correspond to a Unix socket" // identical to std's
822 )
823 );
824 }
825
826 if addr.is_abstract() == true
827 {
828 if addr.len > capacity
829 {
830 return Err(
831 io::Error::new(ErrorKind::InvalidData, "abstract name was too long")
832 );
833 }
834 }
835 else if addr.is_path() == true
836 {
837 if addr.len > capacity+1
838 {
839 return Err(io::Error::new(ErrorKind::InvalidData, "path was too long"));
840 // accept lengths one too big; assume the truncated byte was NUL
841 }
842 else
843 {
844 // normalize addr.len to include terminating NUL byte if possible
845 // and not be greater than capacity
846 if addr.len >= capacity
847 {
848 addr.len = capacity;
849 }
850 else if addr.addr.sun_path[(addr.len-1-path_offset()) as usize] != 0
851 {
852 addr.len += 1;
853 addr.addr.sun_path[(addr.len-1-path_offset()) as usize] = 0;
854 }
855 }
856 }
857
858 return Ok((ret, addr));
859 }
860 }
861
862 /// Creates an `UnixSocketAddr` from a pointer to a generic `sockaddr` and
863 /// a length.
864 ///
865 /// # Safety
866 ///
867 /// * `len` must not be greater than the size of the memory `addr` points to.
868 /// * `addr` must point to valid memory if `len` is greater than zero, or be NULL.
869 pub unsafe
870 fn from_raw(addr: *const sockaddr, len: socklen_t) -> Result<Self, io::Error>
871 {
872 let mut copy = Self::new_unspecified();
873
874 if addr.is_null() == true && len == 0
875 {
876 return Ok(Self::new_unspecified());
877 }
878 else if addr.is_null() == true
879 {
880 return Err(io::Error::new(ErrorKind::InvalidInput, "addr is NULL"));
881 }
882 else if len < path_offset()
883 {
884 return Err(io::Error::new(ErrorKind::InvalidInput, "address length is too short"));
885 }
886 else if len > mem::size_of::<sockaddr_un>() as socklen_t
887 {
888 return Err(io::Error::new(ErrorKind::InvalidInput, TOO_LONG_DESC));
889 }
890 else if unsafe { (&*addr).sa_family } != AF_UNIX as sa_family_t
891 {
892 return Err(io::Error::new(ErrorKind::InvalidData, "not an unix socket address"));
893 }
894 else
895 {
896 let addr = addr as *const sockaddr_un;
897 let sun_path_ptr = unsafe { (&*addr).sun_path.as_ptr() };
898 let path_len = (len - path_offset()) as usize;
899 let sun_path = unsafe { slice::from_raw_parts(sun_path_ptr, path_len) };
900
901 copy.addr.sun_path[..path_len].copy_from_slice(sun_path);
902 copy.len = len;
903
904 return Ok(copy);
905 }
906 }
907
908 /// Creates an `UnixSocketAddr` without any validation.
909 ///
910 /// # Safety
911 ///
912 /// * `len` must be `<= size_of::<sockaddr_un>()`.
913 /// * `addr.sun_family` should be `AF_UNIX` or strange things might happen.
914 /// * `addr.sun_len`, if it exists, should be zero (but is probably ignored).
915 pub unsafe
916 fn from_raw_unchecked(addr: sockaddr_un, len: socklen_t) -> Self
917 {
918 Self{addr, len}
919 }
920
921 /// Splits the address into its inner, raw parts.
922 pub
923 fn into_raw(self) -> (sockaddr_un, socklen_t)
924 {
925 (self.addr, self.len)
926 }
927
928 /// Returns a general `sockaddr` reference to the address and its length.
929 ///
930 /// Useful for passing to `bind()`, `connect()`, `sendto()` or other FFI.
931 ///
932 /// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
933 /// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
934 /// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
935 /// Therefore do not call `SUN_LEN()` on unknown addresses.
936 /// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
937 pub
938 fn as_raw_general(&self) -> (&sockaddr, socklen_t)
939 {
940 // SAFETY: sockaddr is a super-type of sockaddr_un.
941 (unsafe { &*(&self.addr as *const sockaddr_un as *const sockaddr) }, self.len)
942 }
943
944 /// Returns a reference to the inner `struct sockaddr_un`, and length.
945 ///
946 /// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
947 /// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
948 /// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
949 /// Therefore do not call `SUN_LEN()` on unknown addresses.
950 /// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
951 pub
952 fn as_raw(&self) -> (&sockaddr_un, socklen_t)
953 {
954 (&self.addr, self.len)
955 }
956
957 /// Returns mutable references to a general `struct sockaddr` and `socklen_t`.
958 ///
959 /// If passing to `getpeername()`, `accept()` or similar, remember to set
960 /// the length to the capacity,
961 /// and consider using [`new_from_ffi()`](#method.new_from_ffi) instead.
962 ///
963 /// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
964 /// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
965 /// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
966 /// Therefore do not call `SUN_LEN()` on unknown addresses.
967 /// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects.
968 ///
969 /// # Safety
970 ///
971 /// Assigning a value > `sizeof(struct sockaddr_un)` to the `socklen_t`
972 /// reference might lead to out-of-bounds reads later.
973 pub unsafe
974 fn as_raw_mut_general(&mut self) -> (&mut sockaddr, &mut socklen_t)
975 {
976 // SAFETY: sockaddr is a super-type of sockaddr_un.
977 (unsafe { &mut*(&mut self.addr as *mut sockaddr_un as *mut sockaddr) }, &mut self.len)
978 }
979
980 /// Returns mutable references to the inner `struct sockaddr_un` and length.
981 ///
982 /// Pathname addresses are not guaranteed to be NUL-terminated on most OSes:
983 /// Most paths will be NUL-terminated, but paths that just fit within `sockaddr_un.sun_len`
984 /// (iow their length is equal to `addr.sun_len[..].len()`) will not have one.
985 /// Therefore do not call `SUN_LEN()` on unknown addresses.
986 /// See [`max_path_len()`](#tymethod.max_path_len) for which OSes this affects
987 ///
988 /// # Safety
989 ///
990 /// Assigning a value > `sizeof(struct sockaddr_un)` to the `socklen_t`
991 /// reference might lead to out-of-bounds reads later.
992 pub unsafe
993 fn as_raw_mut(&mut self) -> (&mut sockaddr_un, &mut socklen_t)
994 {
995 (&mut self.addr, &mut self.len)
996 }
997}
998
999impl Default for UnixSocketAddr
1000{
1001 fn default() -> Self {
1002 Self::new_unspecified()
1003 }
1004}
1005
1006impl PartialEq for UnixSocketAddr
1007{
1008 fn eq(&self, other: &Self) -> bool {
1009 self.as_ref() == other.as_ref()
1010 }
1011}
1012impl Eq for UnixSocketAddr {}
1013
1014impl Hash for UnixSocketAddr
1015{
1016 fn hash<H: Hasher>(&self, hasher: &mut H)
1017 {
1018 self.as_ref().hash(hasher)
1019 }
1020}
1021
1022impl PartialEq<[u8]> for UnixSocketAddr
1023{
1024 fn eq(&self, unescaped: &[u8]) -> bool
1025 {
1026 match (self.as_ref(), unescaped.first())
1027 {
1028 (UnixSocketAddrRef::Path(path), Some(_)) =>
1029 path.as_os_str().as_bytes() == unescaped,
1030 (UnixSocketAddrRef::Abstract(name), Some(b'\0')) =>
1031 name == &unescaped[1..],
1032 (UnixSocketAddrRef::Unnamed, None) =>
1033 true,
1034 (_, _) =>
1035 false,
1036 }
1037 }
1038}
1039impl PartialEq<UnixSocketAddr> for [u8]
1040{
1041 fn eq(&self, addr: &UnixSocketAddr) -> bool
1042 {
1043 addr == self
1044 }
1045}