std/os/unix/net/listener.rs
1use super::{SocketAddr, UnixStream, sockaddr_un};
2use crate::macros::rustdoc_skip_body;
3use crate::os::unix::io::{
4 AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd, unsafe_impl_fd_asrefs,
5};
6use crate::path::Path;
7use crate::sys::net::Socket;
8use crate::sys::{AsInner, FromInner, IntoInner, cvt};
9use crate::{fmt, io, mem};
10
11/// A structure representing a Unix domain socket server.
12///
13/// # Examples
14///
15#[cfg_attr(target_family = "unix", doc = "```no_run")]
16#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
17/// use std::thread;
18/// use std::os::unix::net::{UnixStream, UnixListener};
19///
20/// fn handle_client(stream: UnixStream) {
21/// // ...
22/// }
23///
24/// fn main() -> std::io::Result<()> {
25/// let listener = UnixListener::bind("/path/to/the/socket")?;
26///
27/// // accept connections and process them, spawning a new thread for each one
28/// for stream in listener.incoming() {
29/// match stream {
30/// Ok(stream) => {
31/// /* connection succeeded */
32/// thread::spawn(|| handle_client(stream));
33/// }
34/// Err(err) => {
35/// /* connection failed */
36/// break;
37/// }
38/// }
39/// }
40/// Ok(())
41/// }
42/// ```
43#[stable(feature = "unix_socket", since = "1.10.0")]
44pub struct UnixListener(Socket);
45
46#[stable(feature = "unix_socket", since = "1.10.0")]
47impl fmt::Debug for UnixListener {
48 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
49 let mut builder = fmt.debug_struct("UnixListener");
50 builder.field("fd", self.0.as_inner());
51 if let Ok(addr) = self.local_addr() {
52 builder.field("local", &addr);
53 }
54 builder.finish()
55 }
56}
57
58impl UnixListener {
59 /// Creates a new `UnixListener` bound to the specified socket.
60 ///
61 /// # Examples
62 ///
63 #[cfg_attr(target_family = "unix", doc = "```no_run")]
64 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
65 /// use std::os::unix::net::UnixListener;
66 ///
67 /// let listener = match UnixListener::bind("/path/to/the/socket") {
68 /// Ok(sock) => sock,
69 /// Err(e) => {
70 /// println!("Couldn't connect: {e:?}");
71 /// return
72 /// }
73 /// };
74 /// ```
75 #[stable(feature = "unix_socket", since = "1.10.0")]
76 pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
77 unsafe {
78 let inner = Socket::new(libc::AF_UNIX, libc::SOCK_STREAM)?;
79 let (addr, len) = sockaddr_un(path.as_ref())?;
80 #[cfg(any(
81 target_os = "windows",
82 target_os = "redox",
83 target_os = "espidf",
84 target_os = "horizon"
85 ))]
86 const backlog: core::ffi::c_int = 128;
87 #[cfg(any(
88 // Silently capped to `/proc/sys/net/core/somaxconn`.
89 target_os = "linux",
90 // Silently capped to `kern.ipc.soacceptqueue`.
91 target_os = "freebsd",
92 // Silently capped to `kern.somaxconn sysctl`.
93 target_os = "openbsd",
94 // Silently capped to the default 128.
95 target_vendor = "apple",
96 ))]
97 const backlog: core::ffi::c_int = -1;
98 #[cfg(not(any(
99 target_os = "windows",
100 target_os = "redox",
101 target_os = "espidf",
102 target_os = "horizon",
103 target_os = "linux",
104 target_os = "freebsd",
105 target_os = "openbsd",
106 target_vendor = "apple",
107 )))]
108 const backlog: libc::c_int = libc::SOMAXCONN;
109
110 cvt(libc::bind(inner.as_inner().as_raw_fd(), (&raw const addr) as *const _, len as _))?;
111 cvt(libc::listen(inner.as_inner().as_raw_fd(), backlog))?;
112
113 Ok(UnixListener(inner))
114 }
115 }
116
117 /// Creates a new `UnixListener` bound to the specified [`socket address`].
118 ///
119 /// [`socket address`]: crate::os::unix::net::SocketAddr
120 ///
121 /// # Examples
122 ///
123 #[cfg_attr(target_family = "unix", doc = "```no_run")]
124 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
125 /// use std::os::unix::net::{SocketAddr, UnixListener};
126 ///
127 /// fn main() -> std::io::Result<()> {
128 /// let addr = SocketAddr::from_pathname("path/to/socket")?;
129 ///
130 /// let listener = match UnixListener::bind_addr(&addr) {
131 /// Ok(sock) => sock,
132 /// Err(err) => {
133 /// println!("Couldn't bind: {err:?}");
134 /// return Err(err);
135 /// }
136 /// };
137 /// Ok(())
138 /// }
139 /// ```
140 #[stable(feature = "unix_socket_abstract", since = "1.70.0")]
141 pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixListener> {
142 unsafe {
143 let inner = Socket::new(libc::AF_UNIX, libc::SOCK_STREAM)?;
144 #[cfg(target_os = "linux")]
145 const backlog: core::ffi::c_int = -1;
146 #[cfg(not(target_os = "linux"))]
147 const backlog: core::ffi::c_int = 128;
148 cvt(libc::bind(
149 inner.as_raw_fd(),
150 (&raw const socket_addr.addr) as *const _,
151 socket_addr.len as _,
152 ))?;
153 cvt(libc::listen(inner.as_raw_fd(), backlog))?;
154 Ok(UnixListener(inner))
155 }
156 }
157
158 /// Accepts a new incoming connection to this listener.
159 ///
160 /// This function will block the calling thread until a new Unix connection
161 /// is established. When established, the corresponding [`UnixStream`] and
162 /// the remote peer's address will be returned.
163 ///
164 /// [`UnixStream`]: crate::os::unix::net::UnixStream
165 ///
166 /// # Examples
167 ///
168 #[cfg_attr(target_family = "unix", doc = "```no_run")]
169 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
170 /// use std::os::unix::net::UnixListener;
171 ///
172 /// fn main() -> std::io::Result<()> {
173 /// let listener = UnixListener::bind("/path/to/the/socket")?;
174 ///
175 /// match listener.accept() {
176 /// Ok((socket, addr)) => println!("Got a client: {addr:?}"),
177 /// Err(e) => println!("accept function failed: {e:?}"),
178 /// }
179 /// Ok(())
180 /// }
181 /// ```
182 #[stable(feature = "unix_socket", since = "1.10.0")]
183 pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
184 let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
185 let mut len = size_of_val(&storage) as libc::socklen_t;
186 let sock = self.0.accept((&raw mut storage) as *mut _, &mut len)?;
187 let addr = SocketAddr::from_parts(storage, len)?;
188 Ok((UnixStream(sock), addr))
189 }
190
191 /// Creates a new independently owned handle to the underlying socket.
192 ///
193 /// The returned `UnixListener` is a reference to the same socket that this
194 /// object references. Both handles can be used to accept incoming
195 /// connections and options set on one listener will affect the other.
196 ///
197 /// # Examples
198 ///
199 #[cfg_attr(target_family = "unix", doc = "```no_run")]
200 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
201 /// use std::os::unix::net::UnixListener;
202 ///
203 /// fn main() -> std::io::Result<()> {
204 /// let listener = UnixListener::bind("/path/to/the/socket")?;
205 /// let listener_copy = listener.try_clone().expect("`UnixListener::try_clone` should not fail");
206 /// Ok(())
207 /// }
208 /// ```
209 #[stable(feature = "unix_socket", since = "1.10.0")]
210 pub fn try_clone(&self) -> io::Result<UnixListener> {
211 self.0.duplicate().map(UnixListener)
212 }
213
214 /// Returns the local socket address of this listener.
215 ///
216 /// # Examples
217 ///
218 #[cfg_attr(target_family = "unix", doc = "```no_run")]
219 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
220 /// use std::os::unix::net::UnixListener;
221 ///
222 /// fn main() -> std::io::Result<()> {
223 /// let listener = UnixListener::bind("/path/to/the/socket")?;
224 /// let addr = listener.local_addr().expect("`UnixListener::local_addr` should not fail");
225 /// Ok(())
226 /// }
227 /// ```
228 #[stable(feature = "unix_socket", since = "1.10.0")]
229 #[rustdoc_skip_body]
230 pub fn local_addr(&self) -> io::Result<SocketAddr> {
231 SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.as_raw_fd(), addr, len) })
232 }
233
234 /// Moves the socket into or out of nonblocking mode.
235 ///
236 /// This will result in the `accept` operation becoming nonblocking,
237 /// i.e., immediately returning from their calls. If the IO operation is
238 /// successful, `Ok` is returned and no further action is required. If the
239 /// IO operation could not be completed and needs to be retried, an error
240 /// with kind [`io::ErrorKind::WouldBlock`] is returned.
241 ///
242 /// # Examples
243 ///
244 #[cfg_attr(target_family = "unix", doc = "```no_run")]
245 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
246 /// use std::os::unix::net::UnixListener;
247 ///
248 /// fn main() -> std::io::Result<()> {
249 /// let listener = UnixListener::bind("/path/to/the/socket")?;
250 /// listener.set_nonblocking(true).expect("`UnixListener::set_nonblocking` should not fail");
251 /// Ok(())
252 /// }
253 /// ```
254 #[stable(feature = "unix_socket", since = "1.10.0")]
255 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
256 self.0.set_nonblocking(nonblocking)
257 }
258
259 /// Returns the value of the `SO_ERROR` option.
260 ///
261 /// # Examples
262 ///
263 #[cfg_attr(target_family = "unix", doc = "```no_run")]
264 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
265 /// use std::os::unix::net::UnixListener;
266 ///
267 /// fn main() -> std::io::Result<()> {
268 /// let listener = UnixListener::bind("/tmp/sock")?;
269 ///
270 /// if let Ok(Some(err)) = listener.take_error() {
271 /// println!("Got error: {err:?}");
272 /// }
273 /// Ok(())
274 /// }
275 /// ```
276 ///
277 /// # Platform specific
278 /// On Redox this always returns `None`.
279 #[stable(feature = "unix_socket", since = "1.10.0")]
280 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
281 self.0.take_error()
282 }
283
284 /// Returns an iterator over incoming connections.
285 ///
286 /// The iterator will never return [`None`] and will also not yield the
287 /// peer's [`SocketAddr`] structure.
288 ///
289 /// # Examples
290 ///
291 #[cfg_attr(target_family = "unix", doc = "```no_run")]
292 #[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
293 /// use std::thread;
294 /// use std::os::unix::net::{UnixStream, UnixListener};
295 ///
296 /// fn handle_client(stream: UnixStream) {
297 /// // ...
298 /// }
299 ///
300 /// fn main() -> std::io::Result<()> {
301 /// let listener = UnixListener::bind("/path/to/the/socket")?;
302 ///
303 /// for stream in listener.incoming() {
304 /// match stream {
305 /// Ok(stream) => {
306 /// thread::spawn(|| handle_client(stream));
307 /// }
308 /// Err(err) => {
309 /// break;
310 /// }
311 /// }
312 /// }
313 /// Ok(())
314 /// }
315 /// ```
316 #[stable(feature = "unix_socket", since = "1.10.0")]
317 pub fn incoming(&self) -> Incoming<'_> {
318 Incoming { listener: self }
319 }
320}
321
322#[stable(feature = "unix_socket", since = "1.10.0")]
323impl AsRawFd for UnixListener {
324 #[inline]
325 #[rustdoc_skip_body]
326 fn as_raw_fd(&self) -> RawFd {
327 self.0.as_inner().as_raw_fd()
328 }
329}
330
331#[stable(feature = "unix_socket", since = "1.10.0")]
332impl FromRawFd for UnixListener {
333 #[inline]
334 #[rustdoc_skip_body]
335 unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
336 UnixListener(Socket::from_inner(FromInner::from_inner(OwnedFd::from_raw_fd(fd))))
337 }
338}
339
340#[stable(feature = "unix_socket", since = "1.10.0")]
341impl IntoRawFd for UnixListener {
342 #[inline]
343 #[rustdoc_skip_body]
344 fn into_raw_fd(self) -> RawFd {
345 self.0.into_inner().into_inner().into_raw_fd()
346 }
347}
348
349#[stable(feature = "io_safety", since = "1.63.0")]
350impl AsFd for UnixListener {
351 #[inline]
352 #[rustdoc_skip_body]
353 fn as_fd(&self) -> BorrowedFd<'_> {
354 self.0.as_inner().as_fd()
355 }
356}
357
358#[stable(feature = "io_safety", since = "1.63.0")]
359impl From<OwnedFd> for UnixListener {
360 #[inline]
361 #[rustdoc_skip_body]
362 fn from(fd: OwnedFd) -> UnixListener {
363 UnixListener(Socket::from_inner(FromInner::from_inner(fd)))
364 }
365}
366
367// SAFETY: It's a tower of 1-field wrappers around OwnedFd.
368// No methods to close the socket, no methods with safety preconditions,
369// other than the fd being valid.
370unsafe_impl_fd_asrefs!(UnixListener);
371
372#[stable(feature = "io_safety", since = "1.63.0")]
373impl From<UnixListener> for OwnedFd {
374 /// Takes ownership of a [`UnixListener`]'s socket file descriptor.
375 #[inline]
376 #[rustdoc_skip_body]
377 fn from(listener: UnixListener) -> OwnedFd {
378 listener.0.into_inner().into_inner()
379 }
380}
381
382#[stable(feature = "unix_socket", since = "1.10.0")]
383impl<'a> IntoIterator for &'a UnixListener {
384 type Item = io::Result<UnixStream>;
385 type IntoIter = Incoming<'a>;
386
387 fn into_iter(self) -> Incoming<'a> {
388 self.incoming()
389 }
390}
391
392/// An iterator over incoming connections to a [`UnixListener`].
393///
394/// It will never return [`None`].
395///
396/// # Examples
397///
398#[cfg_attr(target_family = "unix", doc = "```no_run")]
399#[cfg_attr(not(target_family = "unix"), doc = "```ignore (needs unix)")]
400/// use std::thread;
401/// use std::os::unix::net::{UnixStream, UnixListener};
402///
403/// fn handle_client(stream: UnixStream) {
404/// // ...
405/// }
406///
407/// fn main() -> std::io::Result<()> {
408/// let listener = UnixListener::bind("/path/to/the/socket")?;
409///
410/// for stream in listener.incoming() {
411/// match stream {
412/// Ok(stream) => {
413/// thread::spawn(|| handle_client(stream));
414/// }
415/// Err(err) => {
416/// break;
417/// }
418/// }
419/// }
420/// Ok(())
421/// }
422/// ```
423#[derive(Debug)]
424#[must_use = "iterators are lazy and do nothing unless consumed"]
425#[stable(feature = "unix_socket", since = "1.10.0")]
426pub struct Incoming<'a> {
427 listener: &'a UnixListener,
428}
429
430#[stable(feature = "unix_socket", since = "1.10.0")]
431impl<'a> Iterator for Incoming<'a> {
432 type Item = io::Result<UnixStream>;
433
434 fn next(&mut self) -> Option<io::Result<UnixStream>> {
435 Some(self.listener.accept().map(|s| s.0))
436 }
437
438 fn size_hint(&self) -> (usize, Option<usize>) {
439 (usize::MAX, None)
440 }
441}