1use 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
13pub struct TcpStream {
19 inner: Option<std::net::TcpStream>,
20 peer: SocketAddr,
21}
22
23impl TcpStream {
24 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 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 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 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 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 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 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 pub fn close(&mut self) {
142 self.inner.take();
143 }
144
145 #[must_use]
147 pub const fn is_open(&self) -> bool {
148 self.inner.is_some()
149 }
150
151 #[must_use]
153 pub const fn peer_addr(&self) -> SocketAddr {
154 self.peer
155 }
156
157 #[must_use]
159 pub const fn remote_addr(&self) -> IpAddr {
160 self.peer.ip()
161 }
162
163 #[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
184pub struct TcpListener {
188 inner: Option<std::net::TcpListener>,
189 local: SocketAddr,
190}
191
192impl TcpListener {
193 pub fn bind_any(port: u16) -> Result<Self> {
199 Self::bind("0.0.0.0", port, 128)
200 }
201
202 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 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 pub fn close(&mut self) {
260 self.inner.take();
261 }
262
263 #[must_use]
265 pub const fn is_open(&self) -> bool {
266 self.inner.is_some()
267 }
268
269 #[must_use]
271 pub const fn local_addr(&self) -> SocketAddr {
272 self.local
273 }
274
275 #[must_use]
277 pub const fn port(&self) -> u16 {
278 self.local.port()
279 }
280}