1 // Copyright (c) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 use std::io::{self, IoSlice, IoSliceMut, Read, Write}; 15 use std::net::{self, Shutdown, SocketAddr}; 16 use std::os::unix::io::AsRawFd; 17 18 use super::TcpSocket; 19 use crate::source::Fd; 20 use crate::{Interest, Selector, Source, Token}; 21 22 /// A non-blocking TCP Stream between a local socket and a remote socket. 23 pub struct TcpStream { 24 /// Raw TCP socket 25 pub inner: net::TcpStream, 26 } 27 28 impl TcpStream { 29 /// Create a new TCP stream and issue a non-blocking connect to the 30 /// specified address. connect(addr: SocketAddr) -> io::Result<TcpStream>31 pub fn connect(addr: SocketAddr) -> io::Result<TcpStream> { 32 let socket = TcpSocket::new_socket(addr)?; 33 socket.connect(addr) 34 } 35 36 /// Creates a new `TcpStream` from a standard `net::TcpStream`. from_std(stream: net::TcpStream) -> TcpStream37 pub fn from_std(stream: net::TcpStream) -> TcpStream { 38 TcpStream { inner: stream } 39 } 40 41 /// Clones the TcpStream. try_clone(&self) -> Self42 pub fn try_clone(&self) -> Self { 43 TcpStream { 44 inner: self.inner.try_clone().unwrap(), 45 } 46 } 47 48 /// Returns the socket address of the local half of this TCP connection. 49 /// 50 /// # Examples 51 /// 52 /// ```no_run 53 /// use std::net::{IpAddr, Ipv4Addr}; 54 /// 55 /// use ylong_io::TcpStream; 56 /// 57 /// let addr = "127.0.0.1:1234".parse().unwrap(); 58 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 59 /// assert_eq!( 60 /// stream.local_addr().unwrap().ip(), 61 /// IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)) 62 /// ); 63 /// ``` local_addr(&self) -> io::Result<SocketAddr>64 pub fn local_addr(&self) -> io::Result<SocketAddr> { 65 self.inner.local_addr() 66 } 67 68 /// Returns the socket address of the remote half of this TCP connection. 69 /// 70 /// # Examples 71 /// 72 /// ```no_run 73 /// use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; 74 /// 75 /// use ylong_io::TcpStream; 76 /// 77 /// let addr = "127.0.0.1:1234".parse().unwrap(); 78 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 79 /// assert_eq!( 80 /// stream.peer_addr().unwrap(), 81 /// SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234)) 82 /// ); 83 /// ``` peer_addr(&self) -> io::Result<SocketAddr>84 pub fn peer_addr(&self) -> io::Result<SocketAddr> { 85 self.inner.peer_addr() 86 } 87 88 /// Sets the value of the `TCP_NODELAY`. 89 /// 90 /// # Examples 91 /// 92 /// ```no_run 93 /// use ylong_io::TcpStream; 94 /// 95 /// let addr = "127.0.0.1:1234".parse().unwrap(); 96 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 97 /// stream.set_nodelay(true).expect("set_nodelay call failed"); 98 /// ``` set_nodelay(&self, nodelay: bool) -> io::Result<()>99 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { 100 self.inner.set_nodelay(nodelay) 101 } 102 103 /// Gets the value of the `TCP_NODELAY`. 104 /// 105 /// # Examples 106 /// 107 /// ```no_run 108 /// use ylong_io::TcpStream; 109 /// 110 /// let addr = "127.0.0.1:1234".parse().unwrap(); 111 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 112 /// stream.set_nodelay(true).expect("set_nodelay call failed"); 113 /// assert_eq!(stream.nodelay().unwrap_or(false), true); 114 /// ``` nodelay(&self) -> io::Result<bool>115 pub fn nodelay(&self) -> io::Result<bool> { 116 self.inner.nodelay() 117 } 118 119 /// Sets the value for the `IP_TTL`. 120 /// 121 /// # Examples 122 /// 123 /// ```no_run 124 /// use ylong_io::TcpStream; 125 /// 126 /// let addr = "127.0.0.1:1234".parse().unwrap(); 127 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 128 /// stream.set_ttl(100).expect("set_ttl call failed"); 129 /// ``` set_ttl(&self, ttl: u32) -> io::Result<()>130 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { 131 self.inner.set_ttl(ttl) 132 } 133 134 /// Gets the value of the `IP_TTL`. 135 /// 136 /// # Examples 137 /// 138 /// ```no_run 139 /// use ylong_io::TcpStream; 140 /// 141 /// let addr = "127.0.0.1:1234".parse().unwrap(); 142 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 143 /// stream.set_ttl(100).expect("set_ttl call failed"); 144 /// assert_eq!(stream.ttl().unwrap_or(0), 100); 145 /// ``` ttl(&self) -> io::Result<u32>146 pub fn ttl(&self) -> io::Result<u32> { 147 self.inner.ttl() 148 } 149 150 /// Gets the value of the `SO_ERROR` option on this socket. take_error(&self) -> io::Result<Option<io::Error>>151 pub fn take_error(&self) -> io::Result<Option<io::Error>> { 152 self.inner.take_error() 153 } 154 155 /// Shuts down the read, write, or both halves of this connection. shutdown(&self, how: Shutdown) -> io::Result<()>156 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> { 157 self.inner.shutdown(how) 158 } 159 160 /// Same as std::net::TcpStream::peek(). 161 /// 162 /// Receives data on the socket from the remote address to which it is 163 /// connected, without removing that data from the queue. On success, 164 /// returns the number of bytes peeked. 165 /// 166 /// # Examples 167 /// 168 /// ```no_run 169 /// use ylong_io::TcpStream; 170 /// 171 /// let addr = "127.0.0.1:1234".parse().unwrap(); 172 /// let stream = TcpStream::connect(addr).expect("Couldn't connect to the server..."); 173 /// let mut buf = [0; 10]; 174 /// let len = stream.peek(&mut buf).expect("peek failed"); 175 /// ``` peek(&self, buf: &mut [u8]) -> io::Result<usize>176 pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> { 177 self.inner.peek(buf) 178 } 179 } 180 181 impl Read for TcpStream { read(&mut self, buf: &mut [u8]) -> io::Result<usize>182 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 183 self.inner.read(buf) 184 } 185 read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>186 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { 187 self.inner.read_vectored(bufs) 188 } 189 } 190 191 impl Write for TcpStream { write(&mut self, buf: &[u8]) -> io::Result<usize>192 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 193 self.inner.write(buf) 194 } 195 write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>196 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { 197 self.inner.write_vectored(bufs) 198 } 199 flush(&mut self) -> io::Result<()>200 fn flush(&mut self) -> io::Result<()> { 201 self.inner.flush() 202 } 203 } 204 205 impl Read for &TcpStream { read(&mut self, buf: &mut [u8]) -> io::Result<usize>206 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { 207 let mut inner = &self.inner; 208 inner.read(buf) 209 } 210 read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize>211 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { 212 let mut inner = &self.inner; 213 inner.read_vectored(bufs) 214 } 215 } 216 217 impl Write for &TcpStream { write(&mut self, buf: &[u8]) -> io::Result<usize>218 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { 219 let mut inner = &self.inner; 220 inner.write(buf) 221 } 222 write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize>223 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { 224 let mut inner = &self.inner; 225 inner.write_vectored(bufs) 226 } 227 flush(&mut self) -> io::Result<()>228 fn flush(&mut self) -> io::Result<()> { 229 let mut inner = &self.inner; 230 inner.flush() 231 } 232 } 233 234 impl std::fmt::Debug for TcpStream { fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 236 self.inner.fmt(f) 237 } 238 } 239 240 impl Source for TcpStream { register( &mut self, selector: &Selector, token: Token, interests: Interest, ) -> io::Result<()>241 fn register( 242 &mut self, 243 selector: &Selector, 244 token: Token, 245 interests: Interest, 246 ) -> io::Result<()> { 247 selector.register(self.as_raw_fd(), token, interests) 248 } 249 reregister( &mut self, selector: &Selector, token: Token, interests: Interest, ) -> io::Result<()>250 fn reregister( 251 &mut self, 252 selector: &Selector, 253 token: Token, 254 interests: Interest, 255 ) -> io::Result<()> { 256 selector.reregister(self.as_raw_fd(), token, interests) 257 } 258 deregister(&mut self, selector: &Selector) -> io::Result<()>259 fn deregister(&mut self, selector: &Selector) -> io::Result<()> { 260 selector.deregister(self.as_raw_fd()) 261 } 262 as_raw_fd(&self) -> Fd263 fn as_raw_fd(&self) -> Fd { 264 self.inner.as_raw_fd() 265 } 266 } 267