1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
use super::{sockaddr_un, SocketAddr, UnixStream};
use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use crate::path::Path;
use crate::sys::cvt;
use crate::sys::net::Socket;
use crate::sys_common::{AsInner, FromInner, IntoInner};
use crate::{fmt, io, mem};
/// 表示 Unix 域套接字服务器的结构体。
///
/// # Examples
///
/// ```no_run
/// use std::thread;
/// use std::os::unix::net::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
/// // ...
/// }
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
///
/// // 接受连接并处理它们,为每个连接产生一个新线程
/// for stream in listener.incoming() {
/// match stream {
/// Ok(stream) => {
/// /* connection succeeded */
/// thread::spawn(|| handle_client(stream));
/// }
/// Err(err) => {
/// /* connection failed */
/// break;
/// }
/// }
/// }
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub struct UnixListener(Socket);
#[stable(feature = "unix_socket", since = "1.10.0")]
impl fmt::Debug for UnixListener {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut builder = fmt.debug_struct("UnixListener");
builder.field("fd", self.0.as_inner());
if let Ok(addr) = self.local_addr() {
builder.field("local", &addr);
}
builder.finish()
}
}
impl UnixListener {
/// 创建绑定到指定套接字的新 `UnixListener`。
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// let listener = match UnixListener::bind("/path/to/the/socket") {
/// Ok(sock) => sock,
/// Err(e) => {
/// println!("Couldn't connect: {e:?}");
/// return
/// }
/// };
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> {
unsafe {
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
let (addr, len) = sockaddr_un(path.as_ref())?;
const backlog: libc::c_int =
if cfg!(any(target_os = "linux", target_os = "freebsd")) { -1 } else { 128 };
cvt(libc::bind(inner.as_inner().as_raw_fd(), &addr as *const _ as *const _, len as _))?;
cvt(libc::listen(inner.as_inner().as_raw_fd(), backlog))?;
Ok(UnixListener(inner))
}
}
/// 创建绑定到指定 [套接字地址][`socket address`] 的新 `UnixListener`。
///
/// [`socket address`]: crate::os::unix::net::SocketAddr
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::{UnixListener};
///
/// fn main() -> std::io::Result<()> {
/// let listener1 = UnixListener::bind("path/to/socket")?;
/// let addr = listener1.local_addr()?;
///
/// let listener2 = match UnixListener::bind_addr(&addr) {
/// Ok(sock) => sock,
/// Err(err) => {
/// println!("Couldn't bind: {err:?}");
/// return Err(err);
/// }
/// };
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket_abstract", since = "1.70.0")]
pub fn bind_addr(socket_addr: &SocketAddr) -> io::Result<UnixListener> {
unsafe {
let inner = Socket::new_raw(libc::AF_UNIX, libc::SOCK_STREAM)?;
#[cfg(target_os = "linux")]
const backlog: libc::c_int = -1;
#[cfg(not(target_os = "linux"))]
const backlog: libc::c_int = 128;
cvt(libc::bind(
inner.as_raw_fd(),
&socket_addr.addr as *const _ as *const _,
socket_addr.len as _,
))?;
cvt(libc::listen(inner.as_raw_fd(), backlog))?;
Ok(UnixListener(inner))
}
}
/// 接受与此侦听器的新传入连接。
///
/// 该函数将阻塞调用线程,直到建立新的 Unix 连接为止。
/// 建立后,将返回相应的 [`UnixStream`] 和远程对等方的地址。
///
///
/// [`UnixStream`]: crate::os::unix::net::UnixStream
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
///
/// match listener.accept() {
/// Ok((socket, addr)) => println!("Got a client: {addr:?}"),
/// Err(e) => println!("accept function failed: {e:?}"),
/// }
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
let mut storage: libc::sockaddr_un = unsafe { mem::zeroed() };
let mut len = mem::size_of_val(&storage) as libc::socklen_t;
let sock = self.0.accept(&mut storage as *mut _ as *mut _, &mut len)?;
let addr = SocketAddr::from_parts(storage, len)?;
Ok((UnixStream(sock), addr))
}
/// 为底层套接字创建一个新的独立的拥有所有权的句柄。
///
/// 返回的 `UnixListener` 是与此对象引用相同的套接字的引用。
/// 这两个句柄均可用于接受传入连接,并且在一个侦听器上设置的选项将影响另一个。
///
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
/// let listener_copy = listener.try_clone().expect("try_clone failed");
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn try_clone(&self) -> io::Result<UnixListener> {
self.0.duplicate().map(UnixListener)
}
/// 返回此侦听器的本地套接字地址。
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
/// let addr = listener.local_addr().expect("Couldn't get local address");
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn local_addr(&self) -> io::Result<SocketAddr> {
SocketAddr::new(|addr, len| unsafe { libc::getsockname(self.as_raw_fd(), addr, len) })
}
/// 将套接字移入或移出非阻塞模式。
///
/// 这将导致 `accept` 操作变为非阻塞,即立即从其调用中返回。
/// 如果 IO 操作成功,则返回 `Ok`,并且不需要进一步的操作。
/// 如果 IO 操作无法完成,需要重试,则返回类型为 [`io::ErrorKind::WouldBlock`] 的错误。
///
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
/// listener.set_nonblocking(true).expect("Couldn't set non blocking");
/// Ok(())
/// }
/// ```
///
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.0.set_nonblocking(nonblocking)
}
/// 返回 `SO_ERROR` 选项的值。
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::net::UnixListener;
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/tmp/sock")?;
///
/// if let Ok(Some(err)) = listener.take_error() {
/// println!("Got error: {err:?}");
/// }
/// Ok(())
/// }
/// ```
///
/// # 特定于平台
/// 在 Redox 上,它总是返回 `None`。
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.0.take_error()
}
/// 返回传入连接上的迭代器。
///
/// 迭代器将永远不会返回 [`None`],也不会产生对等方的 [`SocketAddr`] 结构体。
///
///
/// # Examples
///
/// ```no_run
/// use std::thread;
/// use std::os::unix::net::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
/// // ...
/// }
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
///
/// for stream in listener.incoming() {
/// match stream {
/// Ok(stream) => {
/// thread::spawn(|| handle_client(stream));
/// }
/// Err(err) => {
/// break;
/// }
/// }
/// }
/// Ok(())
/// }
/// ```
#[stable(feature = "unix_socket", since = "1.10.0")]
pub fn incoming(&self) -> Incoming<'_> {
Incoming { listener: self }
}
}
#[stable(feature = "unix_socket", since = "1.10.0")]
impl AsRawFd for UnixListener {
#[inline]
fn as_raw_fd(&self) -> RawFd {
self.0.as_inner().as_raw_fd()
}
}
#[stable(feature = "unix_socket", since = "1.10.0")]
impl FromRawFd for UnixListener {
#[inline]
unsafe fn from_raw_fd(fd: RawFd) -> UnixListener {
UnixListener(Socket::from_inner(FromInner::from_inner(OwnedFd::from_raw_fd(fd))))
}
}
#[stable(feature = "unix_socket", since = "1.10.0")]
impl IntoRawFd for UnixListener {
#[inline]
fn into_raw_fd(self) -> RawFd {
self.0.into_inner().into_inner().into_raw_fd()
}
}
#[stable(feature = "io_safety", since = "1.63.0")]
impl AsFd for UnixListener {
#[inline]
fn as_fd(&self) -> BorrowedFd<'_> {
self.0.as_inner().as_fd()
}
}
#[stable(feature = "io_safety", since = "1.63.0")]
impl From<OwnedFd> for UnixListener {
#[inline]
fn from(fd: OwnedFd) -> UnixListener {
UnixListener(Socket::from_inner(FromInner::from_inner(fd)))
}
}
#[stable(feature = "io_safety", since = "1.63.0")]
impl From<UnixListener> for OwnedFd {
#[inline]
fn from(listener: UnixListener) -> OwnedFd {
listener.0.into_inner().into_inner()
}
}
#[stable(feature = "unix_socket", since = "1.10.0")]
impl<'a> IntoIterator for &'a UnixListener {
type Item = io::Result<UnixStream>;
type IntoIter = Incoming<'a>;
fn into_iter(self) -> Incoming<'a> {
self.incoming()
}
}
/// 在 [`UnixListener`] 的传入连接上进行迭代的迭代器。
///
/// 它将永远不会返回 [`None`]。
///
/// # Examples
///
/// ```no_run
/// use std::thread;
/// use std::os::unix::net::{UnixStream, UnixListener};
///
/// fn handle_client(stream: UnixStream) {
/// // ...
/// }
///
/// fn main() -> std::io::Result<()> {
/// let listener = UnixListener::bind("/path/to/the/socket")?;
///
/// for stream in listener.incoming() {
/// match stream {
/// Ok(stream) => {
/// thread::spawn(|| handle_client(stream));
/// }
/// Err(err) => {
/// break;
/// }
/// }
/// }
/// Ok(())
/// }
/// ```
#[derive(Debug)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
#[stable(feature = "unix_socket", since = "1.10.0")]
pub struct Incoming<'a> {
listener: &'a UnixListener,
}
#[stable(feature = "unix_socket", since = "1.10.0")]
impl<'a> Iterator for Incoming<'a> {
type Item = io::Result<UnixStream>;
fn next(&mut self) -> Option<io::Result<UnixStream>> {
Some(self.listener.accept().map(|s| s.0))
}
fn size_hint(&self) -> (usize, Option<usize>) {
(usize::MAX, None)
}
}