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