Skip to main content

std/os/windows/net/
listener.rs

1#![unstable(feature = "windows_unix_domain_sockets", issue = "150487")]
2
3use crate::macros::rustdoc_skip_body;
4use crate::os::windows::io::{AsRawSocket, FromRawSocket, IntoRawSocket, RawSocket};
5use crate::os::windows::net::{SocketAddr, UnixStream};
6use crate::path::Path;
7#[cfg(not(doc))]
8use crate::sys::c::{AF_UNIX, SOCK_STREAM, SOCKADDR_UN, bind, getsockname, listen};
9use crate::sys::net::Socket;
10#[cfg(not(doc))]
11use crate::sys::winsock::startup;
12use crate::sys::{AsInner, cvt_nz};
13use crate::{fmt, io};
14
15/// A structure representing a Unix domain socket server.
16///
17/// Under Windows, it will only work starting from Windows 10 17063.
18///
19/// # Examples
20///
21#[cfg_attr(windows, doc = "```no_run")]
22#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
23/// #![feature(windows_unix_domain_sockets)]
24/// use std::thread;
25/// use std::os::windows::net::{UnixStream, UnixListener};
26///
27/// fn handle_client(stream: UnixStream) {
28///     // ...
29/// }
30///
31/// fn main() -> std::io::Result<()> {
32///     let listener = UnixListener::bind("/path/to/the/socket")?;
33///
34///     // accept connections and process them, spawning a new thread for each one
35///     for stream in listener.incoming() {
36///         match stream {
37///             Ok(stream) => {
38///                 /* connection succeeded */
39///                 thread::spawn(|| handle_client(stream));
40///             }
41///             Err(err) => {
42///                 /* connection failed */
43///                 break;
44///             }
45///         }
46///     }
47///     Ok(())
48/// }
49/// ```
50pub struct UnixListener(Socket);
51
52impl fmt::Debug for UnixListener {
53    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
54        let mut builder = fmt.debug_struct("UnixListener");
55        builder.field("sock", self.0.as_inner());
56        if let Ok(addr) = self.local_addr() {
57            builder.field("local", &addr);
58        }
59        builder.finish()
60    }
61}
62impl UnixListener {
63    /// Creates a new `UnixListener` bound to the specified socket.
64    ///
65    /// # Examples
66    ///
67    #[cfg_attr(windows, doc = "```no_run")]
68    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
69    /// #![feature(windows_unix_domain_sockets)]
70    /// use std::os::windows::net::UnixListener;
71    ///
72    /// let listener = match UnixListener::bind("/path/to/the/socket") {
73    ///     Ok(sock) => sock,
74    ///     Err(e) => {
75    ///         println!("Couldn't connect: {e:?}");
76    ///         return
77    ///     }
78    /// };
79    /// ```
80    pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
81        let socket_addr = SocketAddr::from_pathname(path)?;
82        Self::bind_addr(&socket_addr)
83    }
84
85    /// Creates a new `UnixListener` bound to the specified [`socket address`].
86    ///
87    /// [`socket address`]: crate::os::windows::net::SocketAddr
88    ///
89    /// # Examples
90    ///
91    #[cfg_attr(windows, doc = "```no_run")]
92    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
93    /// #![feature(windows_unix_domain_sockets)]
94    /// use std::os::windows::net::{UnixListener};
95    ///
96    /// fn main() -> std::io::Result<()> {
97    ///     let listener1 = UnixListener::bind("path/to/socket")?;
98    ///     let addr = listener1.local_addr()?;
99    ///
100    ///     let listener2 = match UnixListener::bind_addr(&addr) {
101    ///         Ok(sock) => sock,
102    ///         Err(err) => {
103    ///             println!("Couldn't bind: {err:?}");
104    ///             return Err(err);
105    ///         }
106    ///     };
107    ///     Ok(())
108    /// }
109    /// ```
110    pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixListener> {
111        startup();
112        let inner = Socket::new(AF_UNIX as _, SOCK_STREAM)?;
113        unsafe {
114            cvt_nz(bind(inner.as_raw(), &raw const socket_addr.addr as _, socket_addr.len as _))?;
115            cvt_nz(listen(inner.as_raw(), 128))?;
116        }
117        Ok(UnixListener(inner))
118    }
119
120    /// Accepts a new incoming connection to this listener.
121    ///
122    /// This function will block the calling thread until a new Unix connection
123    /// is established. When established, the corresponding [`UnixStream`] and
124    /// the remote peer's address will be returned.
125    ///
126    /// [`UnixStream`]: crate::os::windows::net::UnixStream
127    ///
128    /// # Examples
129    ///
130    #[cfg_attr(windows, doc = "```no_run")]
131    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
132    /// #![feature(windows_unix_domain_sockets)]
133    /// use std::os::windows::net::UnixListener;
134    ///
135    /// fn main() -> std::io::Result<()> {
136    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
137    ///
138    ///     match listener.accept() {
139    ///         Ok((socket, addr)) => println!("Got a client: {addr:?}"),
140    ///         Err(e) => println!("accept function failed: {e:?}"),
141    ///     }
142    ///     Ok(())
143    /// }
144    /// ```
145    pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
146        let mut storage = SOCKADDR_UN::default();
147        let mut len = size_of::<SOCKADDR_UN>() as _;
148        let inner = self.0.accept(&raw mut storage as *mut _, &raw mut len)?;
149        let addr = SocketAddr::from_parts(storage, len)?;
150        Ok((UnixStream(inner), addr))
151    }
152
153    /// Returns the local socket address of this listener.
154    ///
155    /// # Examples
156    ///
157    #[cfg_attr(windows, doc = "```no_run")]
158    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
159    /// #![feature(windows_unix_domain_sockets)]
160    /// use std::os::windows::net::UnixListener;
161    ///
162    /// fn main() -> std::io::Result<()> {
163    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
164    ///     let addr = listener.local_addr().expect("Couldn't get local address");
165    ///     Ok(())
166    /// }
167    /// ```
168    #[rustdoc_skip_body]
169    pub fn local_addr(&self) -> io::Result<SocketAddr> {
170        SocketAddr::new(|addr, len| unsafe { getsockname(self.0.as_raw(), addr, len) })
171    }
172
173    /// Creates a new independently owned handle to the underlying socket.
174    ///
175    /// The returned `UnixListener` is a reference to the same socket that this
176    /// object references. Both handles can be used to accept incoming
177    /// connections and options set on one listener will affect the other.
178    ///
179    /// # Examples
180    ///
181    #[cfg_attr(windows, doc = "```no_run")]
182    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
183    /// #![feature(windows_unix_domain_sockets)]
184    /// use std::os::windows::net::UnixListener;
185    ///
186    /// fn main() -> std::io::Result<()> {
187    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
188    ///     let listener_copy = listener.try_clone().expect("try_clone failed");
189    ///     Ok(())
190    /// }
191    /// ```
192    pub fn try_clone(&self) -> io::Result<UnixListener> {
193        self.0.duplicate().map(UnixListener)
194    }
195
196    /// Moves the socket into or out of nonblocking mode.
197    ///
198    /// This will result in the `accept` operation becoming nonblocking,
199    /// i.e., immediately returning from their calls. If the IO operation is
200    /// successful, `Ok` is returned and no further action is required. If the
201    /// IO operation could not be completed and needs to be retried, an error
202    /// with kind [`io::ErrorKind::WouldBlock`] is returned.
203    ///
204    /// # Examples
205    ///
206    #[cfg_attr(windows, doc = "```no_run")]
207    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
208    /// #![feature(windows_unix_domain_sockets)]
209    /// use std::os::windows::net::UnixListener;
210    ///
211    /// fn main() -> std::io::Result<()> {
212    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
213    ///     listener.set_nonblocking(true).expect("Couldn't set non blocking");
214    ///     Ok(())
215    /// }
216    /// ```
217    pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
218        self.0.set_nonblocking(nonblocking)
219    }
220
221    /// Returns the value of the `SO_ERROR` option.
222    ///
223    /// # Examples
224    ///
225    #[cfg_attr(windows, doc = "```no_run")]
226    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
227    /// #![feature(windows_unix_domain_sockets)]
228    /// use std::os::windows::net::UnixListener;
229    ///
230    /// fn main() -> std::io::Result<()> {
231    ///     let listener = UnixListener::bind("/tmp/sock")?;
232    ///
233    ///     if let Ok(Some(err)) = listener.take_error() {
234    ///         println!("Got error: {err:?}");
235    ///     }
236    ///     Ok(())
237    /// }
238    /// ```
239    pub fn take_error(&self) -> io::Result<Option<io::Error>> {
240        self.0.take_error()
241    }
242
243    /// Returns an iterator over incoming connections.
244    ///
245    /// The iterator will never return [`None`] and will also not yield the
246    /// peer's [`SocketAddr`] structure.
247    ///
248    /// # Examples
249    ///
250    #[cfg_attr(windows, doc = "```no_run")]
251    #[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
252    /// #![feature(windows_unix_domain_sockets)]
253    /// use std::thread;
254    /// use std::os::windows::net::{UnixStream, UnixListener};
255    ///
256    /// fn handle_client(stream: UnixStream) {
257    ///     // ...
258    /// }
259    ///
260    /// fn main() -> std::io::Result<()> {
261    ///     let listener = UnixListener::bind("/path/to/the/socket")?;
262    ///
263    ///     for stream in listener.incoming() {
264    ///         match stream {
265    ///             Ok(stream) => {
266    ///                 thread::spawn(|| handle_client(stream));
267    ///             }
268    ///             Err(err) => {
269    ///                 break;
270    ///             }
271    ///         }
272    ///     }
273    ///     Ok(())
274    /// }
275    /// ```
276    pub fn incoming(&self) -> Incoming<'_> {
277        Incoming { listener: self }
278    }
279}
280
281/// An iterator over incoming connections to a [`UnixListener`].
282///
283/// It will never return [`None`].
284///
285/// # Examples
286///
287#[cfg_attr(windows, doc = "```no_run")]
288#[cfg_attr(not(windows), doc = "```ignore (needs windows)")]
289/// #![feature(windows_unix_domain_sockets)]
290/// use std::thread;
291/// use std::os::windows::net::{UnixStream, UnixListener};
292///
293/// fn handle_client(stream: UnixStream) {
294///     // ...
295/// }
296///
297/// fn main() -> std::io::Result<()> {
298///     let listener = UnixListener::bind("/path/to/the/socket")?;
299///
300///     for stream in listener.incoming() {
301///         match stream {
302///             Ok(stream) => {
303///                 thread::spawn(|| handle_client(stream));
304///             }
305///             Err(err) => {
306///                 break;
307///             }
308///         }
309///     }
310///     Ok(())
311/// }
312/// ```
313pub struct Incoming<'a> {
314    listener: &'a UnixListener,
315}
316
317impl<'a> Iterator for Incoming<'a> {
318    type Item = io::Result<UnixStream>;
319
320    fn next(&mut self) -> Option<io::Result<UnixStream>> {
321        Some(self.listener.accept().map(|s| s.0))
322    }
323
324    fn size_hint(&self) -> (usize, Option<usize>) {
325        (usize::MAX, None)
326    }
327}
328
329impl AsRawSocket for UnixListener {
330    #[inline]
331    #[rustdoc_skip_body]
332    fn as_raw_socket(&self) -> RawSocket {
333        self.0.as_raw_socket()
334    }
335}
336
337impl FromRawSocket for UnixListener {
338    #[inline]
339    #[rustdoc_skip_body]
340    unsafe fn from_raw_socket(sock: RawSocket) -> Self {
341        UnixListener(unsafe { Socket::from_raw_socket(sock) })
342    }
343}
344
345impl IntoRawSocket for UnixListener {
346    #[inline]
347    #[rustdoc_skip_body]
348    fn into_raw_socket(self) -> RawSocket {
349        self.0.into_raw_socket()
350    }
351}
352
353impl<'a> IntoIterator for &'a UnixListener {
354    type Item = io::Result<UnixStream>;
355    type IntoIter = Incoming<'a>;
356
357    fn into_iter(self) -> Incoming<'a> {
358        self.incoming()
359    }
360}