2 use crate::io::{self, IoVec, IoVecMut};
3 use crate::net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
4 use crate::time::Duration;
5 use crate::sys::{unsupported, Void, sgx_ineffective, AsInner, FromInner, IntoInner, TryIntoInner};
6 use crate::sys::fd::FileDesc;
7 use crate::convert::TryFrom;
11 use super::abi::usercalls;
13 const DEFAULT_FAKE_TTL: u32 = 64;
15 #[derive(Debug, Clone)]
18 local_addr: Option<String>,
22 fn new(fd: usercalls::raw::Fd, local_addr: String) -> Socket {
23 Socket { inner: Arc::new(FileDesc::new(fd)), local_addr: Some(local_addr) }
27 impl AsInner<FileDesc> for Socket {
28 fn as_inner(&self) -> &FileDesc { &self.inner }
31 impl TryIntoInner<FileDesc> for Socket {
32 fn try_into_inner(self) -> Result<FileDesc, Socket> {
33 let Socket { inner, local_addr } = self;
34 Arc::try_unwrap(inner).map_err(|inner| Socket { inner, local_addr } )
38 impl FromInner<FileDesc> for Socket {
39 fn from_inner(inner: FileDesc) -> Socket {
40 Socket { inner: Arc::new(inner), local_addr: None }
44 #[derive(Debug, Clone)]
45 pub struct TcpStream {
47 peer_addr: Option<String>,
50 fn io_err_to_addr(result: io::Result<&SocketAddr>) -> io::Result<String> {
52 Ok(saddr) => Ok(saddr.to_string()),
53 // need to downcast twice because io::Error::into_inner doesn't return the original
54 // value if the conversion fails
55 Err(e) => if e.get_ref().and_then(|e| e.downcast_ref::<NonIpSockAddr>()).is_some() {
56 Ok(e.into_inner().unwrap().downcast::<NonIpSockAddr>().unwrap().host)
63 fn addr_to_sockaddr(addr: &Option<String>) -> io::Result<SocketAddr> {
65 .ok_or(io::ErrorKind::AddrNotAvailable)?
67 // unwrap OK: if an iterator is returned, we're guaranteed to get exactly one entry
68 .map(|mut it| it.next().unwrap())
72 pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
73 let addr = io_err_to_addr(addr)?;
74 let (fd, local_addr, peer_addr) = usercalls::connect_stream(&addr)?;
75 Ok(TcpStream { inner: Socket::new(fd, local_addr), peer_addr: Some(peer_addr) })
78 pub fn connect_timeout(addr: &SocketAddr, _: Duration) -> io::Result<TcpStream> {
79 Self::connect(Ok(addr)) // FIXME: ignoring timeout
82 pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
86 pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
90 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
94 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
98 pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
102 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
103 self.inner.inner.read(buf)
106 pub fn read_vectored(&self, bufs: &mut [IoVecMut<'_>]) -> io::Result<usize> {
107 match bufs.iter_mut().find(|b| !b.is_empty()) {
108 Some(buf) => self.read(buf),
113 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
114 self.inner.inner.write(buf)
117 pub fn write_vectored(&self, bufs: &[IoVec<'_>]) -> io::Result<usize> {
118 match bufs.iter().find(|b| !b.is_empty()) {
119 Some(buf) => self.write(buf),
124 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
125 addr_to_sockaddr(&self.peer_addr)
128 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
129 addr_to_sockaddr(&self.inner.local_addr)
132 pub fn shutdown(&self, _: Shutdown) -> io::Result<()> {
136 pub fn duplicate(&self) -> io::Result<TcpStream> {
140 pub fn set_nodelay(&self, _: bool) -> io::Result<()> {
144 pub fn nodelay(&self) -> io::Result<bool> {
145 sgx_ineffective(false)
148 pub fn set_ttl(&self, _: u32) -> io::Result<()> {
152 pub fn ttl(&self) -> io::Result<u32> {
153 sgx_ineffective(DEFAULT_FAKE_TTL)
156 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
160 pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
165 impl AsInner<Socket> for TcpStream {
166 fn as_inner(&self) -> &Socket { &self.inner }
169 // `Inner` includes `peer_addr` so that a `TcpStream` maybe correctly
170 // reconstructed if `Socket::try_into_inner` fails.
171 impl IntoInner<(Socket, Option<String>)> for TcpStream {
172 fn into_inner(self) -> (Socket, Option<String>) {
173 (self.inner, self.peer_addr)
177 impl FromInner<(Socket, Option<String>)> for TcpStream {
178 fn from_inner((inner, peer_addr): (Socket, Option<String>)) -> TcpStream {
179 TcpStream { inner, peer_addr }
183 #[derive(Debug, Clone)]
184 pub struct TcpListener {
189 pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
190 let addr = io_err_to_addr(addr)?;
191 let (fd, local_addr) = usercalls::bind_stream(&addr)?;
192 Ok(TcpListener { inner: Socket::new(fd, local_addr) })
195 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
196 addr_to_sockaddr(&self.inner.local_addr)
199 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
200 let (fd, local_addr, peer_addr) = usercalls::accept_stream(self.inner.inner.raw())?;
201 let peer_addr = Some(peer_addr);
202 let ret_peer = addr_to_sockaddr(&peer_addr).unwrap_or_else(|_| ([0; 4], 0).into());
203 Ok((TcpStream { inner: Socket::new(fd, local_addr), peer_addr }, ret_peer))
206 pub fn duplicate(&self) -> io::Result<TcpListener> {
210 pub fn set_ttl(&self, _: u32) -> io::Result<()> {
214 pub fn ttl(&self) -> io::Result<u32> {
215 sgx_ineffective(DEFAULT_FAKE_TTL)
218 pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
222 pub fn only_v6(&self) -> io::Result<bool> {
223 sgx_ineffective(false)
226 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
230 pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
235 impl AsInner<Socket> for TcpListener {
236 fn as_inner(&self) -> &Socket { &self.inner }
239 impl IntoInner<Socket> for TcpListener {
240 fn into_inner(self) -> Socket {
245 impl FromInner<Socket> for TcpListener {
246 fn from_inner(inner: Socket) -> TcpListener {
247 TcpListener { inner }
251 pub struct UdpSocket(Void);
254 pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
258 pub fn socket_addr(&self) -> io::Result<SocketAddr> {
262 pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
266 pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
270 pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
274 pub fn duplicate(&self) -> io::Result<UdpSocket> {
278 pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
282 pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
286 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
290 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
294 pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
298 pub fn broadcast(&self) -> io::Result<bool> {
302 pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
306 pub fn multicast_loop_v4(&self) -> io::Result<bool> {
310 pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
314 pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
318 pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
322 pub fn multicast_loop_v6(&self) -> io::Result<bool> {
326 pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
331 pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
336 pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
341 pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
346 pub fn set_ttl(&self, _: u32) -> io::Result<()> {
350 pub fn ttl(&self) -> io::Result<u32> {
354 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
358 pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
362 pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
366 pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
370 pub fn send(&self, _: &[u8]) -> io::Result<usize> {
374 pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
379 impl fmt::Debug for UdpSocket {
380 fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result {
386 pub struct NonIpSockAddr {
390 impl error::Error for NonIpSockAddr {
391 fn description(&self) -> &str {
392 "Failed to convert address to SocketAddr"
396 impl fmt::Display for NonIpSockAddr {
397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
398 write!(f, "Failed to convert address to SocketAddr: {}", self.host)
402 pub struct LookupHost(Void);
405 fn new(host: String) -> io::Result<LookupHost> {
406 Err(io::Error::new(io::ErrorKind::Other, NonIpSockAddr { host }))
409 pub fn port(&self) -> u16 {
414 impl Iterator for LookupHost {
415 type Item = SocketAddr;
416 fn next(&mut self) -> Option<SocketAddr> {
421 impl<'a> TryFrom<&'a str> for LookupHost {
422 type Error = io::Error;
424 fn try_from(v: &'a str) -> io::Result<LookupHost> {
425 LookupHost::new(v.to_owned())
429 impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
430 type Error = io::Error;
432 fn try_from((host, port): (&'a str, u16)) -> io::Result<LookupHost> {
433 LookupHost::new(format!("{}:{}", host, port))
439 pub const AF_INET: u8 = 0;
440 pub const AF_INET6: u8 = 1;
441 pub type sa_family_t = u8;
443 #[derive(Copy, Clone)]
448 #[derive(Copy, Clone)]
449 pub struct sockaddr_in {
450 pub sin_family: sa_family_t,
452 pub sin_addr: in_addr,
455 #[derive(Copy, Clone)]
456 pub struct in6_addr {
457 pub s6_addr: [u8; 16],
460 #[derive(Copy, Clone)]
461 pub struct sockaddr_in6 {
462 pub sin6_family: sa_family_t,
464 pub sin6_addr: in6_addr,
465 pub sin6_flowinfo: u32,
466 pub sin6_scope_id: u32,
469 #[derive(Copy, Clone)]
470 pub struct sockaddr {
473 pub type socklen_t = usize;