]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/sgx/net.rs
SGX target: implemented vectored I/O
[rust.git] / src / libstd / sys / sgx / net.rs
1 use crate::fmt;
2 use crate::io::{self, IoSlice, IoSliceMut};
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;
8 use crate::error;
9 use crate::sync::Arc;
10
11 use super::abi::usercalls;
12
13 const DEFAULT_FAKE_TTL: u32 = 64;
14
15 #[derive(Debug, Clone)]
16 pub struct Socket {
17     inner: Arc<FileDesc>,
18     local_addr: Option<String>,
19 }
20
21 impl Socket {
22     fn new(fd: usercalls::raw::Fd, local_addr: String) -> Socket {
23         Socket { inner: Arc::new(FileDesc::new(fd)), local_addr: Some(local_addr) }
24     }
25 }
26
27 impl AsInner<FileDesc> for Socket {
28     fn as_inner(&self) -> &FileDesc { &self.inner }
29 }
30
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 } )
35     }
36 }
37
38 impl FromInner<FileDesc> for Socket {
39     fn from_inner(inner: FileDesc) -> Socket {
40         Socket { inner: Arc::new(inner), local_addr: None }
41     }
42 }
43
44 #[derive(Clone)]
45 pub struct TcpStream {
46     inner: Socket,
47     peer_addr: Option<String>,
48 }
49
50 impl fmt::Debug for TcpStream {
51     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52         let mut res = f.debug_struct("TcpStream");
53
54         if let Some(ref addr) = self.inner.local_addr {
55             res.field("addr", addr);
56         }
57
58         if let Some(ref peer) = self.peer_addr {
59             res.field("peer", peer);
60         }
61
62         res.field("fd", &self.inner.inner.as_inner())
63             .finish()
64     }
65 }
66
67 fn io_err_to_addr(result: io::Result<&SocketAddr>) -> io::Result<String> {
68     match result {
69         Ok(saddr) => Ok(saddr.to_string()),
70         // need to downcast twice because io::Error::into_inner doesn't return the original
71         // value if the conversion fails
72         Err(e) => if e.get_ref().and_then(|e| e.downcast_ref::<NonIpSockAddr>()).is_some() {
73             Ok(e.into_inner().unwrap().downcast::<NonIpSockAddr>().unwrap().host)
74         } else {
75             Err(e)
76         }
77     }
78 }
79
80 fn addr_to_sockaddr(addr: &Option<String>) -> io::Result<SocketAddr> {
81     addr.as_ref()
82         .ok_or(io::ErrorKind::AddrNotAvailable)?
83         .to_socket_addrs()
84         // unwrap OK: if an iterator is returned, we're guaranteed to get exactly one entry
85         .map(|mut it| it.next().unwrap())
86 }
87
88 impl TcpStream {
89     pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
90         let addr = io_err_to_addr(addr)?;
91         let (fd, local_addr, peer_addr) = usercalls::connect_stream(&addr)?;
92         Ok(TcpStream { inner: Socket::new(fd, local_addr), peer_addr: Some(peer_addr) })
93     }
94
95     pub fn connect_timeout(addr: &SocketAddr, dur: Duration) -> io::Result<TcpStream> {
96         if dur == Duration::default() {
97             return Err(io::Error::new(io::ErrorKind::InvalidInput,
98                                       "cannot set a 0 duration timeout"));
99         }
100         Self::connect(Ok(addr)) // FIXME: ignoring timeout
101     }
102
103     pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
104         match dur {
105             Some(dur) if dur == Duration::default() => {
106                 return Err(io::Error::new(io::ErrorKind::InvalidInput,
107                                           "cannot set a 0 duration timeout"));
108             }
109             _ => sgx_ineffective(())
110         }
111     }
112
113     pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
114         match dur {
115             Some(dur) if dur == Duration::default() => {
116                 return Err(io::Error::new(io::ErrorKind::InvalidInput,
117                                           "cannot set a 0 duration timeout"));
118             }
119             _ => sgx_ineffective(())
120         }
121     }
122
123     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
124         sgx_ineffective(None)
125     }
126
127     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
128         sgx_ineffective(None)
129     }
130
131     pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
132         Ok(0)
133     }
134
135     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
136         self.inner.inner.read(buf)
137     }
138
139     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
140         self.inner.inner.read_vectored(bufs)
141     }
142
143     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
144         self.inner.inner.write(buf)
145     }
146
147     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
148         self.inner.inner.write_vectored(bufs)
149     }
150
151     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
152         addr_to_sockaddr(&self.peer_addr)
153     }
154
155     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
156         addr_to_sockaddr(&self.inner.local_addr)
157     }
158
159     pub fn shutdown(&self, _: Shutdown) -> io::Result<()> {
160         sgx_ineffective(())
161     }
162
163     pub fn duplicate(&self) -> io::Result<TcpStream> {
164         Ok(self.clone())
165     }
166
167     pub fn set_nodelay(&self, _: bool) -> io::Result<()> {
168         sgx_ineffective(())
169     }
170
171     pub fn nodelay(&self) -> io::Result<bool> {
172         sgx_ineffective(false)
173     }
174
175     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
176         sgx_ineffective(())
177     }
178
179     pub fn ttl(&self) -> io::Result<u32> {
180         sgx_ineffective(DEFAULT_FAKE_TTL)
181     }
182
183     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
184         Ok(None)
185     }
186
187     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
188         sgx_ineffective(())
189     }
190 }
191
192 impl AsInner<Socket> for TcpStream {
193     fn as_inner(&self) -> &Socket { &self.inner }
194 }
195
196 // `Inner` includes `peer_addr` so that a `TcpStream` maybe correctly
197 // reconstructed if `Socket::try_into_inner` fails.
198 impl IntoInner<(Socket, Option<String>)> for TcpStream {
199     fn into_inner(self) -> (Socket, Option<String>) {
200         (self.inner, self.peer_addr)
201     }
202 }
203
204 impl FromInner<(Socket, Option<String>)> for TcpStream {
205     fn from_inner((inner, peer_addr): (Socket, Option<String>)) -> TcpStream {
206         TcpStream { inner, peer_addr }
207     }
208 }
209
210 #[derive(Clone)]
211 pub struct TcpListener {
212     inner: Socket,
213 }
214
215 impl fmt::Debug for TcpListener {
216     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217         let mut res = f.debug_struct("TcpListener");
218
219         if let Some(ref addr) = self.inner.local_addr {
220             res.field("addr", addr);
221         }
222
223         res.field("fd", &self.inner.inner.as_inner())
224             .finish()
225     }
226 }
227
228 impl TcpListener {
229     pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
230         let addr = io_err_to_addr(addr)?;
231         let (fd, local_addr) = usercalls::bind_stream(&addr)?;
232         Ok(TcpListener { inner: Socket::new(fd, local_addr) })
233     }
234
235     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
236         addr_to_sockaddr(&self.inner.local_addr)
237     }
238
239     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
240         let (fd, local_addr, peer_addr) = usercalls::accept_stream(self.inner.inner.raw())?;
241         let peer_addr = Some(peer_addr);
242         let ret_peer = addr_to_sockaddr(&peer_addr).unwrap_or_else(|_| ([0; 4], 0).into());
243         Ok((TcpStream { inner: Socket::new(fd, local_addr), peer_addr }, ret_peer))
244     }
245
246     pub fn duplicate(&self) -> io::Result<TcpListener> {
247         Ok(self.clone())
248     }
249
250     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
251         sgx_ineffective(())
252     }
253
254     pub fn ttl(&self) -> io::Result<u32> {
255         sgx_ineffective(DEFAULT_FAKE_TTL)
256     }
257
258     pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
259         sgx_ineffective(())
260     }
261
262     pub fn only_v6(&self) -> io::Result<bool> {
263         sgx_ineffective(false)
264     }
265
266     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
267         Ok(None)
268     }
269
270     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
271         sgx_ineffective(())
272     }
273 }
274
275 impl AsInner<Socket> for TcpListener {
276     fn as_inner(&self) -> &Socket { &self.inner }
277 }
278
279 impl IntoInner<Socket> for TcpListener {
280     fn into_inner(self) -> Socket {
281         self.inner
282     }
283 }
284
285 impl FromInner<Socket> for TcpListener {
286     fn from_inner(inner: Socket) -> TcpListener {
287         TcpListener { inner }
288     }
289 }
290
291 pub struct UdpSocket(Void);
292
293 impl UdpSocket {
294     pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
295         unsupported()
296     }
297
298     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
299         match self.0 {}
300     }
301
302     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
303         match self.0 {}
304     }
305
306     pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
307         match self.0 {}
308     }
309
310     pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
311         match self.0 {}
312     }
313
314     pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
315         match self.0 {}
316     }
317
318     pub fn duplicate(&self) -> io::Result<UdpSocket> {
319         match self.0 {}
320     }
321
322     pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
323         match self.0 {}
324     }
325
326     pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
327         match self.0 {}
328     }
329
330     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
331         match self.0 {}
332     }
333
334     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
335         match self.0 {}
336     }
337
338     pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
339         match self.0 {}
340     }
341
342     pub fn broadcast(&self) -> io::Result<bool> {
343         match self.0 {}
344     }
345
346     pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
347         match self.0 {}
348     }
349
350     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
351         match self.0 {}
352     }
353
354     pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
355         match self.0 {}
356     }
357
358     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
359         match self.0 {}
360     }
361
362     pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
363         match self.0 {}
364     }
365
366     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
367         match self.0 {}
368     }
369
370     pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
371                          -> io::Result<()> {
372         match self.0 {}
373     }
374
375     pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32)
376                          -> io::Result<()> {
377         match self.0 {}
378     }
379
380     pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr)
381                           -> io::Result<()> {
382         match self.0 {}
383     }
384
385     pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32)
386                           -> io::Result<()> {
387         match self.0 {}
388     }
389
390     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
391         match self.0 {}
392     }
393
394     pub fn ttl(&self) -> io::Result<u32> {
395         match self.0 {}
396     }
397
398     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
399         match self.0 {}
400     }
401
402     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
403         match self.0 {}
404     }
405
406     pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
407         match self.0 {}
408     }
409
410     pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
411         match self.0 {}
412     }
413
414     pub fn send(&self, _: &[u8]) -> io::Result<usize> {
415         match self.0 {}
416     }
417
418     pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
419         match self.0 {}
420     }
421 }
422
423 impl fmt::Debug for UdpSocket {
424     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
425         match self.0 {}
426     }
427 }
428
429 #[derive(Debug)]
430 pub struct NonIpSockAddr {
431     host: String
432 }
433
434 impl error::Error for NonIpSockAddr {
435     fn description(&self) -> &str {
436         "Failed to convert address to SocketAddr"
437     }
438 }
439
440 impl fmt::Display for NonIpSockAddr {
441     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
442         write!(f, "Failed to convert address to SocketAddr: {}", self.host)
443     }
444 }
445
446 pub struct LookupHost(Void);
447
448 impl LookupHost {
449     fn new(host: String) -> io::Result<LookupHost> {
450         Err(io::Error::new(io::ErrorKind::Other, NonIpSockAddr { host }))
451     }
452
453     pub fn port(&self) -> u16 {
454         match self.0 {}
455     }
456 }
457
458 impl Iterator for LookupHost {
459     type Item = SocketAddr;
460     fn next(&mut self) -> Option<SocketAddr> {
461         match self.0 {}
462     }
463 }
464
465 impl TryFrom<&str> for LookupHost {
466     type Error = io::Error;
467
468     fn try_from(v: &str) -> io::Result<LookupHost> {
469         LookupHost::new(v.to_owned())
470     }
471 }
472
473 impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
474     type Error = io::Error;
475
476     fn try_from((host, port): (&'a str, u16)) -> io::Result<LookupHost> {
477         LookupHost::new(format!("{}:{}", host, port))
478     }
479 }
480
481 #[allow(bad_style)]
482 pub mod netc {
483     pub const AF_INET: u8 = 0;
484     pub const AF_INET6: u8 = 1;
485     pub type sa_family_t = u8;
486
487     #[derive(Copy, Clone)]
488     pub struct in_addr {
489         pub s_addr: u32,
490     }
491
492     #[derive(Copy, Clone)]
493     pub struct sockaddr_in {
494         pub sin_family: sa_family_t,
495         pub sin_port: u16,
496         pub sin_addr: in_addr,
497     }
498
499     #[derive(Copy, Clone)]
500     pub struct in6_addr {
501         pub s6_addr: [u8; 16],
502     }
503
504     #[derive(Copy, Clone)]
505     pub struct sockaddr_in6 {
506         pub sin6_family: sa_family_t,
507         pub sin6_port: u16,
508         pub sin6_addr: in6_addr,
509         pub sin6_flowinfo: u32,
510         pub sin6_scope_id: u32,
511     }
512
513     #[derive(Copy, Clone)]
514     pub struct sockaddr {
515     }
516
517     pub type socklen_t = usize;
518 }