]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/hermit/net.rs
ca6c383f181da1f3e802db781a86c30ca59f1ff5
[rust.git] / library / std / src / sys / hermit / net.rs
1 use crate::convert::TryFrom;
2 use crate::fmt;
3 use crate::io::{self, ErrorKind, IoSlice, IoSliceMut};
4 use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
5 use crate::str;
6 use crate::sync::Arc;
7 use crate::sys::hermit::abi;
8 use crate::sys::hermit::abi::IpAddress::{Ipv4, Ipv6};
9 use crate::sys::unsupported;
10 use crate::sys_common::AsInner;
11 use crate::time::Duration;
12
13 /// Checks whether the HermitCore's socket interface has been started already, and
14 /// if not, starts it.
15 pub fn init() -> io::Result<()> {
16     if abi::network_init() < 0 {
17         return Err(io::Error::new_const(
18             ErrorKind::Unknown,
19             &"Unable to initialize network interface",
20         ));
21     }
22
23     Ok(())
24 }
25
26 #[derive(Debug, Clone)]
27 pub struct Socket(abi::Handle);
28
29 impl AsInner<abi::Handle> for Socket {
30     fn as_inner(&self) -> &abi::Handle {
31         &self.0
32     }
33 }
34
35 impl Drop for Socket {
36     fn drop(&mut self) {
37         let _ = abi::tcpstream::close(self.0);
38     }
39 }
40
41 // Arc is used to count the number of used sockets.
42 // Only if all sockets are released, the drop
43 // method will close the socket.
44 #[derive(Clone)]
45 pub struct TcpStream(Arc<Socket>);
46
47 impl TcpStream {
48     pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
49         let addr = addr?;
50
51         match abi::tcpstream::connect(addr.ip().to_string().as_bytes(), addr.port(), None) {
52             Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))),
53             _ => Err(io::Error::new_const(
54                 ErrorKind::Unknown,
55                 &"Unable to initiate a connection on a socket",
56             )),
57         }
58     }
59
60     pub fn connect_timeout(saddr: &SocketAddr, duration: Duration) -> io::Result<TcpStream> {
61         match abi::tcpstream::connect(
62             saddr.ip().to_string().as_bytes(),
63             saddr.port(),
64             Some(duration.as_millis() as u64),
65         ) {
66             Ok(handle) => Ok(TcpStream(Arc::new(Socket(handle)))),
67             _ => Err(io::Error::new_const(
68                 ErrorKind::Unknown,
69                 &"Unable to initiate a connection on a socket",
70             )),
71         }
72     }
73
74     pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
75         abi::tcpstream::set_read_timeout(*self.0.as_inner(), duration.map(|d| d.as_millis() as u64))
76             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"Unable to set timeout value"))
77     }
78
79     pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> {
80         abi::tcpstream::set_write_timeout(
81             *self.0.as_inner(),
82             duration.map(|d| d.as_millis() as u64),
83         )
84         .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"Unable to set timeout value"))
85     }
86
87     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
88         let duration = abi::tcpstream::get_read_timeout(*self.0.as_inner()).map_err(|_| {
89             io::Error::new_const(ErrorKind::Unknown, &"Unable to determine timeout value")
90         })?;
91
92         Ok(duration.map(|d| Duration::from_millis(d)))
93     }
94
95     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
96         let duration = abi::tcpstream::get_write_timeout(*self.0.as_inner()).map_err(|_| {
97             io::Error::new_const(ErrorKind::Unknown, &"Unable to determine timeout value")
98         })?;
99
100         Ok(duration.map(|d| Duration::from_millis(d)))
101     }
102
103     pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
104         abi::tcpstream::peek(*self.0.as_inner(), buf)
105             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"peek failed"))
106     }
107
108     pub fn read(&self, buffer: &mut [u8]) -> io::Result<usize> {
109         self.read_vectored(&mut [IoSliceMut::new(buffer)])
110     }
111
112     pub fn read_vectored(&self, ioslice: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
113         let mut size: usize = 0;
114
115         for i in ioslice.iter_mut() {
116             let ret = abi::tcpstream::read(*self.0.as_inner(), &mut i[0..]).map_err(|_| {
117                 io::Error::new_const(ErrorKind::Unknown, &"Unable to read on socket")
118             })?;
119
120             if ret != 0 {
121                 size += ret;
122             }
123         }
124
125         Ok(size)
126     }
127
128     #[inline]
129     pub fn is_read_vectored(&self) -> bool {
130         true
131     }
132
133     pub fn write(&self, buffer: &[u8]) -> io::Result<usize> {
134         self.write_vectored(&[IoSlice::new(buffer)])
135     }
136
137     pub fn write_vectored(&self, ioslice: &[IoSlice<'_>]) -> io::Result<usize> {
138         let mut size: usize = 0;
139
140         for i in ioslice.iter() {
141             size += abi::tcpstream::write(*self.0.as_inner(), i).map_err(|_| {
142                 io::Error::new_const(ErrorKind::Unknown, &"Unable to write on socket")
143             })?;
144         }
145
146         Ok(size)
147     }
148
149     #[inline]
150     pub fn is_write_vectored(&self) -> bool {
151         true
152     }
153
154     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
155         let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner())
156             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"peer_addr failed"))?;
157
158         let saddr = match ipaddr {
159             Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
160             Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
161             _ => {
162                 return Err(io::Error::new_const(ErrorKind::Unknown, &"peer_addr failed"));
163             }
164         };
165
166         Ok(saddr)
167     }
168
169     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
170         unsupported()
171     }
172
173     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
174         abi::tcpstream::shutdown(*self.0.as_inner(), how as i32)
175             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"unable to shutdown socket"))
176     }
177
178     pub fn duplicate(&self) -> io::Result<TcpStream> {
179         Ok(self.clone())
180     }
181
182     pub fn set_nodelay(&self, mode: bool) -> io::Result<()> {
183         abi::tcpstream::set_nodelay(*self.0.as_inner(), mode)
184             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"set_nodelay failed"))
185     }
186
187     pub fn nodelay(&self) -> io::Result<bool> {
188         abi::tcpstream::nodelay(*self.0.as_inner())
189             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"nodelay failed"))
190     }
191
192     pub fn set_ttl(&self, tll: u32) -> io::Result<()> {
193         abi::tcpstream::set_tll(*self.0.as_inner(), tll)
194             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"unable to set TTL"))
195     }
196
197     pub fn ttl(&self) -> io::Result<u32> {
198         abi::tcpstream::get_tll(*self.0.as_inner())
199             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"unable to get TTL"))
200     }
201
202     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
203         unsupported()
204     }
205
206     pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> {
207         abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode)
208             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"unable to set blocking mode"))
209     }
210 }
211
212 impl fmt::Debug for TcpStream {
213     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
214         Ok(())
215     }
216 }
217
218 #[derive(Clone)]
219 pub struct TcpListener(SocketAddr);
220
221 impl TcpListener {
222     pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
223         let addr = addr?;
224
225         Ok(TcpListener(*addr))
226     }
227
228     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
229         Ok(self.0)
230     }
231
232     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
233         let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port())
234             .map_err(|_| io::Error::new_const(ErrorKind::Unknown, &"accept failed"))?;
235         let saddr = match ipaddr {
236             Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
237             Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
238             _ => {
239                 return Err(io::Error::new_const(ErrorKind::Unknown, &"accept failed"));
240             }
241         };
242
243         Ok((TcpStream(Arc::new(Socket(handle))), saddr))
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         unsupported()
252     }
253
254     pub fn ttl(&self) -> io::Result<u32> {
255         unsupported()
256     }
257
258     pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
259         unsupported()
260     }
261
262     pub fn only_v6(&self) -> io::Result<bool> {
263         unsupported()
264     }
265
266     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
267         unsupported()
268     }
269
270     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
271         unsupported()
272     }
273 }
274
275 impl fmt::Debug for TcpListener {
276     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
277         Ok(())
278     }
279 }
280
281 pub struct UdpSocket(abi::Handle);
282
283 impl UdpSocket {
284     pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
285         unsupported()
286     }
287
288     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
289         unsupported()
290     }
291
292     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
293         unsupported()
294     }
295
296     pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
297         unsupported()
298     }
299
300     pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
301         unsupported()
302     }
303
304     pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
305         unsupported()
306     }
307
308     pub fn duplicate(&self) -> io::Result<UdpSocket> {
309         unsupported()
310     }
311
312     pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
313         unsupported()
314     }
315
316     pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
317         unsupported()
318     }
319
320     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
321         unsupported()
322     }
323
324     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
325         unsupported()
326     }
327
328     pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
329         unsupported()
330     }
331
332     pub fn broadcast(&self) -> io::Result<bool> {
333         unsupported()
334     }
335
336     pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
337         unsupported()
338     }
339
340     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
341         unsupported()
342     }
343
344     pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
345         unsupported()
346     }
347
348     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
349         unsupported()
350     }
351
352     pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
353         unsupported()
354     }
355
356     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
357         unsupported()
358     }
359
360     pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
361         unsupported()
362     }
363
364     pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
365         unsupported()
366     }
367
368     pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
369         unsupported()
370     }
371
372     pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
373         unsupported()
374     }
375
376     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
377         unsupported()
378     }
379
380     pub fn ttl(&self) -> io::Result<u32> {
381         unsupported()
382     }
383
384     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
385         unsupported()
386     }
387
388     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
389         unsupported()
390     }
391
392     pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
393         unsupported()
394     }
395
396     pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
397         unsupported()
398     }
399
400     pub fn send(&self, _: &[u8]) -> io::Result<usize> {
401         unsupported()
402     }
403
404     pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
405         unsupported()
406     }
407 }
408
409 impl fmt::Debug for UdpSocket {
410     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
411         Ok(())
412     }
413 }
414
415 pub struct LookupHost(!);
416
417 impl LookupHost {
418     pub fn port(&self) -> u16 {
419         self.0
420     }
421 }
422
423 impl Iterator for LookupHost {
424     type Item = SocketAddr;
425     fn next(&mut self) -> Option<SocketAddr> {
426         self.0
427     }
428 }
429
430 impl TryFrom<&str> for LookupHost {
431     type Error = io::Error;
432
433     fn try_from(_v: &str) -> io::Result<LookupHost> {
434         unsupported()
435     }
436 }
437
438 impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
439     type Error = io::Error;
440
441     fn try_from(_v: (&'a str, u16)) -> io::Result<LookupHost> {
442         unsupported()
443     }
444 }
445
446 #[allow(nonstandard_style)]
447 pub mod netc {
448     pub const AF_INET: u8 = 0;
449     pub const AF_INET6: u8 = 1;
450     pub type sa_family_t = u8;
451
452     #[derive(Copy, Clone)]
453     pub struct in_addr {
454         pub s_addr: u32,
455     }
456
457     #[derive(Copy, Clone)]
458     pub struct sockaddr_in {
459         pub sin_family: sa_family_t,
460         pub sin_port: u16,
461         pub sin_addr: in_addr,
462     }
463
464     #[derive(Copy, Clone)]
465     pub struct in6_addr {
466         pub s6_addr: [u8; 16],
467     }
468
469     #[derive(Copy, Clone)]
470     pub struct sockaddr_in6 {
471         pub sin6_family: sa_family_t,
472         pub sin6_port: u16,
473         pub sin6_addr: in6_addr,
474         pub sin6_flowinfo: u32,
475         pub sin6_scope_id: u32,
476     }
477
478     #[derive(Copy, Clone)]
479     pub struct sockaddr {}
480
481     pub type socklen_t = usize;
482 }