Skip to main content

oa/net/
tcp.rs

1//! Rust-owned blocking TCP sockets with OA errors and explicit close.
2
3use std::{
4	io::{Read, Write},
5	net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, SocketAddrV4},
6	time::Duration,
7};
8
9use socket2::{Domain, Protocol, SockAddr, Socket, Type};
10
11use crate::{Error, Result};
12
13/// One connected blocking TCP byte stream.
14///
15/// This type owns its socket. Dropping it releases the socket; `close` makes
16/// that lifecycle transition explicit and idempotent. A clone obtained with
17/// `try_clone` shares the underlying TCP connection, including shutdown state.
18pub struct TcpStream {
19	inner: Option<std::net::TcpStream>,
20	peer: SocketAddr,
21}
22
23impl TcpStream {
24	/// Connect to one resolved host and TCP port.
25	///
26	/// # Errors
27	///
28	/// Returns an OA I/O error if name resolution or connection fails.
29	pub fn connect(host: &str, port: u16) -> Result<Self> {
30		if host.is_empty() {
31			return Err(Error::invalid_argument("TCP host must not be empty"));
32		}
33		let inner = std::net::TcpStream::connect((host, port))
34			.map_err(|error| Error::io("TCP connect", error))?;
35		inner
36			.set_nodelay(true)
37			.map_err(|error| Error::io("TCP disable Nagle", error))?;
38		Self::from_std(inner)
39	}
40
41	fn from_std(inner: std::net::TcpStream) -> Result<Self> {
42		let peer = inner
43			.peer_addr()
44			.map_err(|error| Error::io("TCP peer address", error))?;
45		Ok(Self {
46			inner: Some(inner),
47			peer,
48		})
49	}
50
51	/// Read at most `bytes.len()` bytes. Zero means peer EOF or an empty buffer.
52	///
53	/// # Errors
54	///
55	/// Returns `FailedPrecondition` after close, or `Io` for a socket failure.
56	pub fn read(&mut self, bytes: &mut [u8]) -> Result<usize> {
57		self
58			.raw_mut()?
59			.read(bytes)
60			.map_err(|error| Error::io("TCP read", error))
61	}
62
63	/// Write at most `bytes.len()` bytes.
64	///
65	/// # Errors
66	///
67	/// Returns `FailedPrecondition` after close, or `Io` for a socket failure.
68	pub fn write(&mut self, bytes: &[u8]) -> Result<usize> {
69		self
70			.raw_mut()?
71			.write(bytes)
72			.map_err(|error| Error::io("TCP write", error))
73	}
74
75	/// Write every byte or report the socket failure.
76	///
77	/// # Errors
78	///
79	/// Returns `FailedPrecondition` after close, or `Io` for a socket failure.
80	pub fn write_all(&mut self, bytes: &[u8]) -> Result<()> {
81		self
82			.raw_mut()?
83			.write_all(bytes)
84			.map_err(|error| Error::io("TCP write all", error))
85	}
86
87	/// Set both read and write timeouts. Zero restores blocking behavior.
88	///
89	/// If configuring the write timeout fails, the prior read timeout is
90	/// restored before the error is returned.
91	///
92	/// # Errors
93	///
94	/// Returns `FailedPrecondition` after close, or `Io` for a socket failure.
95	pub fn set_io_timeout(&self, timeout: Duration) -> Result<()> {
96		let inner = self.raw()?;
97		let previous_read = inner
98			.read_timeout()
99			.map_err(|error| Error::io("TCP read timeout query", error))?;
100		let timeout = (!timeout.is_zero()).then_some(timeout);
101		inner
102			.set_read_timeout(timeout)
103			.map_err(|error| Error::io("TCP read timeout", error))?;
104		if let Err(error) = inner.set_write_timeout(timeout) {
105			let _ = inner.set_read_timeout(previous_read);
106			return Err(Error::io("TCP write timeout", error));
107		}
108		Ok(())
109	}
110
111	/// Return a second handle to the same connection, useful for interrupting a
112	/// blocking read from another thread with `shutdown`.
113	///
114	/// # Errors
115	///
116	/// Returns `FailedPrecondition` after close, or `Io` for clone failure.
117	pub fn try_clone(&self) -> Result<Self> {
118		let inner = self
119			.raw()?
120			.try_clone()
121			.map_err(|error| Error::io("TCP clone", error))?;
122		Ok(Self {
123			inner: Some(inner),
124			peer: self.peer,
125		})
126	}
127
128	/// Interrupt reads and writes on this connection and its clones.
129	///
130	/// # Errors
131	///
132	/// Returns `FailedPrecondition` after close, or `Io` for shutdown failure.
133	pub fn shutdown(&self) -> Result<()> {
134		self
135			.raw()?
136			.shutdown(Shutdown::Both)
137			.map_err(|error| Error::io("TCP shutdown", error))
138	}
139
140	/// Release this socket handle. Cloned handles remain valid until closed.
141	pub fn close(&mut self) {
142		self.inner.take();
143	}
144
145	/// Whether this wrapper still owns a socket handle.
146	#[must_use]
147	pub const fn is_open(&self) -> bool {
148		self.inner.is_some()
149	}
150
151	/// Return the resolved peer address captured when the stream was created.
152	#[must_use]
153	pub const fn peer_addr(&self) -> SocketAddr {
154		self.peer
155	}
156
157	/// Return the resolved peer IP address.
158	#[must_use]
159	pub const fn remote_addr(&self) -> IpAddr {
160		self.peer.ip()
161	}
162
163	/// Return the resolved peer port.
164	#[must_use]
165	pub const fn remote_port(&self) -> u16 {
166		self.peer.port()
167	}
168
169	fn raw(&self) -> Result<&std::net::TcpStream> {
170		self
171			.inner
172			.as_ref()
173			.ok_or_else(|| Error::failed_precondition("TCP stream is closed"))
174	}
175
176	pub(super) fn raw_mut(&mut self) -> Result<&mut std::net::TcpStream> {
177		self
178			.inner
179			.as_mut()
180			.ok_or_else(|| Error::failed_precondition("TCP stream is closed"))
181	}
182}
183
184/// One blocking IPv4 TCP listener.
185///
186/// The caller owns the listener and every accepted stream independently.
187pub struct TcpListener {
188	inner: Option<std::net::TcpListener>,
189	local: SocketAddr,
190}
191
192impl TcpListener {
193	/// Bind all IPv4 interfaces with the donor's default backlog of 128.
194	///
195	/// # Errors
196	///
197	/// Returns an OA I/O error if socket creation, binding, or listening fails.
198	pub fn bind_any(port: u16) -> Result<Self> {
199		Self::bind("0.0.0.0", port, 128)
200	}
201
202	/// Bind an IPv4 host and port with an explicit positive listen backlog.
203	/// A zero port asks the operating system to select an available port.
204	///
205	/// # Errors
206	///
207	/// Returns `InvalidArgument` for an invalid IPv4 address or backlog, or
208	/// `Io` for a socket failure.
209	pub fn bind(host: &str, port: u16, backlog: i32) -> Result<Self> {
210		if backlog <= 0 {
211			return Err(Error::invalid_argument(
212				"TCP listen backlog must be positive",
213			));
214		}
215		let address = host
216			.parse::<Ipv4Addr>()
217			.map_err(|_| Error::invalid_argument("TCP bind host must be an IPv4 address"))?;
218		let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))
219			.map_err(|error| Error::io("TCP socket", error))?;
220		socket
221			.set_reuse_address(true)
222			.map_err(|error| Error::io("TCP reuse address", error))?;
223		socket
224			.bind(&SockAddr::from(SocketAddrV4::new(address, port)))
225			.map_err(|error| Error::io("TCP bind", error))?;
226		socket
227			.listen(backlog)
228			.map_err(|error| Error::io("TCP listen", error))?;
229		let inner: std::net::TcpListener = socket.into();
230		let local = inner
231			.local_addr()
232			.map_err(|error| Error::io("TCP local address", error))?;
233		Ok(Self {
234			inner: Some(inner),
235			local,
236		})
237	}
238
239	/// Accept one connected stream.
240	///
241	/// # Errors
242	///
243	/// Returns `FailedPrecondition` after close, or `Io` for accept failure.
244	pub fn accept(&self) -> Result<TcpStream> {
245		let inner = self
246			.inner
247			.as_ref()
248			.ok_or_else(|| Error::failed_precondition("TCP listener is closed"))?;
249		let (stream, _) = inner
250			.accept()
251			.map_err(|error| Error::io("TCP accept", error))?;
252		stream
253			.set_nodelay(true)
254			.map_err(|error| Error::io("TCP disable Nagle", error))?;
255		TcpStream::from_std(stream)
256	}
257
258	/// Release the listener socket without affecting accepted streams.
259	pub fn close(&mut self) {
260		self.inner.take();
261	}
262
263	/// Whether this wrapper still owns a listener socket.
264	#[must_use]
265	pub const fn is_open(&self) -> bool {
266		self.inner.is_some()
267	}
268
269	/// Return the bound address captured after listen, including an OS-selected port.
270	#[must_use]
271	pub const fn local_addr(&self) -> SocketAddr {
272		self.local
273	}
274
275	/// Return the bound port.
276	#[must_use]
277	pub const fn port(&self) -> u16 {
278		self.local.port()
279	}
280}