]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/hermit/net.rs
Rollup merge of #84320 - jsha:details-implementors, r=Manishearth,Nemo157,GuillaumeGomez
[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::Other,
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::Other,
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::Other,
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::Other, &"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::Other, &"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::Other, &"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::Other, &"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::Other, &"set_nodelay 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..])
117                 .map_err(|_| io::Error::new_const(ErrorKind::Other, &"Unable to read on socket"))?;
118
119             if ret != 0 {
120                 size += ret;
121             }
122         }
123
124         Ok(size)
125     }
126
127     #[inline]
128     pub fn is_read_vectored(&self) -> bool {
129         true
130     }
131
132     pub fn write(&self, buffer: &[u8]) -> io::Result<usize> {
133         self.write_vectored(&[IoSlice::new(buffer)])
134     }
135
136     pub fn write_vectored(&self, ioslice: &[IoSlice<'_>]) -> io::Result<usize> {
137         let mut size: usize = 0;
138
139         for i in ioslice.iter() {
140             size += abi::tcpstream::write(*self.0.as_inner(), i).map_err(|_| {
141                 io::Error::new_const(ErrorKind::Other, &"Unable to write on socket")
142             })?;
143         }
144
145         Ok(size)
146     }
147
148     #[inline]
149     pub fn is_write_vectored(&self) -> bool {
150         true
151     }
152
153     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
154         let (ipaddr, port) = abi::tcpstream::peer_addr(*self.0.as_inner())
155             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"peer_addr failed"))?;
156
157         let saddr = match ipaddr {
158             Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
159             Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
160             _ => {
161                 return Err(io::Error::new_const(ErrorKind::Other, &"peer_addr failed"));
162             }
163         };
164
165         Ok(saddr)
166     }
167
168     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
169         unsupported()
170     }
171
172     pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
173         abi::tcpstream::shutdown(*self.0.as_inner(), how as i32)
174             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to shutdown socket"))
175     }
176
177     pub fn duplicate(&self) -> io::Result<TcpStream> {
178         Ok(self.clone())
179     }
180
181     pub fn set_nodelay(&self, mode: bool) -> io::Result<()> {
182         abi::tcpstream::set_nodelay(*self.0.as_inner(), mode)
183             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"set_nodelay failed"))
184     }
185
186     pub fn nodelay(&self) -> io::Result<bool> {
187         abi::tcpstream::nodelay(*self.0.as_inner())
188             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"nodelay failed"))
189     }
190
191     pub fn set_ttl(&self, tll: u32) -> io::Result<()> {
192         abi::tcpstream::set_tll(*self.0.as_inner(), tll)
193             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to set TTL"))
194     }
195
196     pub fn ttl(&self) -> io::Result<u32> {
197         abi::tcpstream::get_tll(*self.0.as_inner())
198             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to get TTL"))
199     }
200
201     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
202         unsupported()
203     }
204
205     pub fn set_nonblocking(&self, mode: bool) -> io::Result<()> {
206         abi::tcpstream::set_nonblocking(*self.0.as_inner(), mode)
207             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"unable to set blocking mode"))
208     }
209 }
210
211 impl fmt::Debug for TcpStream {
212     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
213         Ok(())
214     }
215 }
216
217 #[derive(Clone)]
218 pub struct TcpListener(SocketAddr);
219
220 impl TcpListener {
221     pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result<TcpListener> {
222         let addr = addr?;
223
224         Ok(TcpListener(*addr))
225     }
226
227     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
228         Ok(self.0)
229     }
230
231     pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
232         let (handle, ipaddr, port) = abi::tcplistener::accept(self.0.port())
233             .map_err(|_| io::Error::new_const(ErrorKind::Other, &"accept failed"))?;
234         let saddr = match ipaddr {
235             Ipv4(ref addr) => SocketAddr::new(IpAddr::V4(Ipv4Addr::from(addr.0)), port),
236             Ipv6(ref addr) => SocketAddr::new(IpAddr::V6(Ipv6Addr::from(addr.0)), port),
237             _ => {
238                 return Err(io::Error::new_const(ErrorKind::Other, &"accept failed"));
239             }
240         };
241
242         Ok((TcpStream(Arc::new(Socket(handle))), saddr))
243     }
244
245     pub fn duplicate(&self) -> io::Result<TcpListener> {
246         Ok(self.clone())
247     }
248
249     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
250         unsupported()
251     }
252
253     pub fn ttl(&self) -> io::Result<u32> {
254         unsupported()
255     }
256
257     pub fn set_only_v6(&self, _: bool) -> io::Result<()> {
258         unsupported()
259     }
260
261     pub fn only_v6(&self) -> io::Result<bool> {
262         unsupported()
263     }
264
265     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
266         unsupported()
267     }
268
269     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
270         unsupported()
271     }
272 }
273
274 impl fmt::Debug for TcpListener {
275     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
276         Ok(())
277     }
278 }
279
280 pub struct UdpSocket(abi::Handle);
281
282 impl UdpSocket {
283     pub fn bind(_: io::Result<&SocketAddr>) -> io::Result<UdpSocket> {
284         unsupported()
285     }
286
287     pub fn peer_addr(&self) -> io::Result<SocketAddr> {
288         unsupported()
289     }
290
291     pub fn socket_addr(&self) -> io::Result<SocketAddr> {
292         unsupported()
293     }
294
295     pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
296         unsupported()
297     }
298
299     pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
300         unsupported()
301     }
302
303     pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result<usize> {
304         unsupported()
305     }
306
307     pub fn duplicate(&self) -> io::Result<UdpSocket> {
308         unsupported()
309     }
310
311     pub fn set_read_timeout(&self, _: Option<Duration>) -> io::Result<()> {
312         unsupported()
313     }
314
315     pub fn set_write_timeout(&self, _: Option<Duration>) -> io::Result<()> {
316         unsupported()
317     }
318
319     pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
320         unsupported()
321     }
322
323     pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
324         unsupported()
325     }
326
327     pub fn set_broadcast(&self, _: bool) -> io::Result<()> {
328         unsupported()
329     }
330
331     pub fn broadcast(&self) -> io::Result<bool> {
332         unsupported()
333     }
334
335     pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> {
336         unsupported()
337     }
338
339     pub fn multicast_loop_v4(&self) -> io::Result<bool> {
340         unsupported()
341     }
342
343     pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> {
344         unsupported()
345     }
346
347     pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
348         unsupported()
349     }
350
351     pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> {
352         unsupported()
353     }
354
355     pub fn multicast_loop_v6(&self) -> io::Result<bool> {
356         unsupported()
357     }
358
359     pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
360         unsupported()
361     }
362
363     pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
364         unsupported()
365     }
366
367     pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) -> io::Result<()> {
368         unsupported()
369     }
370
371     pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) -> io::Result<()> {
372         unsupported()
373     }
374
375     pub fn set_ttl(&self, _: u32) -> io::Result<()> {
376         unsupported()
377     }
378
379     pub fn ttl(&self) -> io::Result<u32> {
380         unsupported()
381     }
382
383     pub fn take_error(&self) -> io::Result<Option<io::Error>> {
384         unsupported()
385     }
386
387     pub fn set_nonblocking(&self, _: bool) -> io::Result<()> {
388         unsupported()
389     }
390
391     pub fn recv(&self, _: &mut [u8]) -> io::Result<usize> {
392         unsupported()
393     }
394
395     pub fn peek(&self, _: &mut [u8]) -> io::Result<usize> {
396         unsupported()
397     }
398
399     pub fn send(&self, _: &[u8]) -> io::Result<usize> {
400         unsupported()
401     }
402
403     pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> {
404         unsupported()
405     }
406 }
407
408 impl fmt::Debug for UdpSocket {
409     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> fmt::Result {
410         Ok(())
411     }
412 }
413
414 pub struct LookupHost(!);
415
416 impl LookupHost {
417     pub fn port(&self) -> u16 {
418         self.0
419     }
420 }
421
422 impl Iterator for LookupHost {
423     type Item = SocketAddr;
424     fn next(&mut self) -> Option<SocketAddr> {
425         self.0
426     }
427 }
428
429 impl TryFrom<&str> for LookupHost {
430     type Error = io::Error;
431
432     fn try_from(_v: &str) -> io::Result<LookupHost> {
433         unsupported()
434     }
435 }
436
437 impl<'a> TryFrom<(&'a str, u16)> for LookupHost {
438     type Error = io::Error;
439
440     fn try_from(_v: (&'a str, u16)) -> io::Result<LookupHost> {
441         unsupported()
442     }
443 }
444
445 #[allow(nonstandard_style)]
446 pub mod netc {
447     pub const AF_INET: u8 = 0;
448     pub const AF_INET6: u8 = 1;
449     pub type sa_family_t = u8;
450
451     #[derive(Copy, Clone)]
452     pub struct in_addr {
453         pub s_addr: u32,
454     }
455
456     #[derive(Copy, Clone)]
457     pub struct sockaddr_in {
458         pub sin_family: sa_family_t,
459         pub sin_port: u16,
460         pub sin_addr: in_addr,
461     }
462
463     #[derive(Copy, Clone)]
464     pub struct in6_addr {
465         pub s6_addr: [u8; 16],
466     }
467
468     #[derive(Copy, Clone)]
469     pub struct sockaddr_in6 {
470         pub sin6_family: sa_family_t,
471         pub sin6_port: u16,
472         pub sin6_addr: in6_addr,
473         pub sin6_flowinfo: u32,
474         pub sin6_scope_id: u32,
475     }
476
477     #[derive(Copy, Clone)]
478     pub struct sockaddr {}
479
480     pub type socklen_t = usize;
481 }