forked from ivmarkov/edge-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
873 lines (705 loc) · 22.3 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
#![allow(async_fn_in_trait)]
#![warn(clippy::large_futures)]
use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use core::ops::Deref;
use core::pin::pin;
use std::io;
use std::net::{self, Shutdown, TcpStream, ToSocketAddrs, UdpSocket as StdUdpSocket};
#[cfg(not(feature = "async-io-mini"))]
use async_io::Async;
#[cfg(feature = "async-io-mini")]
use async_io_mini::Async;
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use embedded_io_async::{ErrorType, Read, Write};
use edge_nal::{
AddrType, Dns, MulticastV4, MulticastV6, Readable, TcpAccept, TcpBind, TcpConnect, TcpShutdown,
TcpSplit, UdpBind, UdpConnect, UdpReceive, UdpSend, UdpSplit,
};
#[cfg(all(unix, not(target_os = "espidf")))]
pub use raw::*;
#[derive(Default)]
pub struct Stack(());
impl Stack {
pub const fn new() -> Self {
Self(())
}
}
impl TcpConnect for Stack {
type Error = io::Error;
type Socket<'a>
= TcpSocket
where
Self: 'a;
async fn connect(&self, remote: SocketAddr) -> Result<Self::Socket<'_>, Self::Error> {
let socket = Async::<TcpStream>::connect(remote).await?;
Ok(TcpSocket(socket))
}
}
impl TcpBind for Stack {
type Error = io::Error;
type Accept<'a>
= TcpAcceptor
where
Self: 'a;
async fn bind(&self, local: SocketAddr) -> Result<Self::Accept<'_>, Self::Error> {
let acceptor = Async::<net::TcpListener>::bind(local).map(TcpAcceptor)?;
Ok(acceptor)
}
}
pub struct TcpAcceptor(Async<net::TcpListener>);
impl TcpAccept for TcpAcceptor {
type Error = io::Error;
type Socket<'a>
= TcpSocket
where
Self: 'a;
#[cfg(not(target_os = "espidf"))]
async fn accept(&self) -> Result<(SocketAddr, Self::Socket<'_>), Self::Error> {
let socket = self.0.accept().await.map(|(socket, _)| socket)?;
Ok((socket.as_ref().peer_addr()?, TcpSocket(socket)))
}
#[cfg(target_os = "espidf")]
async fn accept(&self) -> Result<(SocketAddr, Self::Socket<'_>), Self::Error> {
// ESP IDF (lwIP actually) does not really support `select`-ing on
// socket accept: https://groups.google.com/g/osdeve_mirror_tcpip_lwip/c/Vsz7SVa6a2M
//
// If we do this, `select` would block and not return with our accepting socket `fd`
// marked as ready even if our accepting socket has a pending connection.
//
// (Note also that since the time when the above link was posted on the internet,
// the lwIP `accept` API has improved a bit in that it would now return `EWOULDBLOCK`
// instead of blocking indefinitely
// - and we take advantage of that in the "async" implementation below.)
//
// The workaround below is not ideal in that
// it uses a timer to poll the socket, but it avoids spinning a hidden,
// separate thread just to accept connections - which would be the alternative.
loop {
match self.0.as_ref().accept() {
Ok((socket, _)) => break Ok((socket.peer_addr()?, TcpSocket(Async::new(socket)?))),
Err(err) if err.kind() == io::ErrorKind::WouldBlock => {
#[cfg(not(feature = "async-io-mini"))]
use async_io::Timer;
#[cfg(feature = "async-io-mini")]
use async_io_mini::Timer;
Timer::after(core::time::Duration::from_millis(20)).await;
}
Err(err) => break Err(err),
}
}
}
}
pub struct TcpSocket(Async<TcpStream>);
impl TcpSocket {
pub const fn new(socket: Async<TcpStream>) -> Self {
Self(socket)
}
pub fn release(self) -> Async<TcpStream> {
self.0
}
}
impl Deref for TcpSocket {
type Target = Async<TcpStream>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ErrorType for TcpSocket {
type Error = io::Error;
}
impl Read for TcpSocket {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
self.0.read(buf).await
}
}
impl Write for TcpSocket {
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
self.0.write(buf).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
self.0.flush().await
}
}
impl Readable for TcpSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
self.0.readable().await
}
}
impl ErrorType for &TcpSocket {
type Error = io::Error;
}
impl Read for &TcpSocket {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
(&self.0).read(buf).await
}
}
impl Write for &TcpSocket {
async fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
(&self.0).write(buf).await
}
async fn flush(&mut self) -> Result<(), Self::Error> {
(&self.0).flush().await
}
}
impl Readable for &TcpSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
self.0.readable().await
}
}
impl TcpSplit for TcpSocket {
type Read<'a>
= &'a TcpSocket
where
Self: 'a;
type Write<'a>
= &'a TcpSocket
where
Self: 'a;
fn split(&mut self) -> (Self::Read<'_>, Self::Write<'_>) {
let socket = &*self;
(socket, socket)
}
}
impl TcpShutdown for TcpSocket {
async fn close(&mut self, what: edge_nal::Close) -> Result<(), Self::Error> {
match what {
edge_nal::Close::Read => self.0.as_ref().shutdown(Shutdown::Read)?,
edge_nal::Close::Write => self.0.as_ref().shutdown(Shutdown::Write)?,
edge_nal::Close::Both => self.0.as_ref().shutdown(Shutdown::Both)?,
}
Ok(())
}
async fn abort(&mut self) -> Result<(), Self::Error> {
// No-op, STD will abort the socket on drop anyway
Ok(())
}
}
impl UdpConnect for Stack {
type Error = io::Error;
type Socket<'a>
= UdpSocket
where
Self: 'a;
async fn connect(
&self,
local: SocketAddr,
remote: SocketAddr,
) -> Result<Self::Socket<'_>, Self::Error> {
let socket = Async::<StdUdpSocket>::bind(local)?;
socket.as_ref().connect(remote)?;
Ok(UdpSocket(socket))
}
}
impl UdpBind for Stack {
type Error = io::Error;
type Socket<'a>
= UdpSocket
where
Self: 'a;
async fn bind(&self, local: SocketAddr) -> Result<Self::Socket<'_>, Self::Error> {
let socket = Async::<StdUdpSocket>::bind(local)?;
socket.as_ref().set_broadcast(true)?;
Ok(UdpSocket(socket))
}
}
pub struct UdpSocket(Async<StdUdpSocket>);
impl UdpSocket {
pub const fn new(socket: Async<StdUdpSocket>) -> Self {
Self(socket)
}
pub fn release(self) -> Async<StdUdpSocket> {
self.0
}
pub fn join_multicast_v4(
&self,
multiaddr: &Ipv4Addr,
interface: &Ipv4Addr,
) -> Result<(), io::Error> {
#[cfg(not(target_os = "espidf"))]
self.as_ref().join_multicast_v4(multiaddr, interface)?;
#[cfg(target_os = "espidf")]
self.setsockopt_ipproto_ip(
multiaddr, interface, 3, /* IP_ADD_MEMBERSHIP in ESP IDF*/
)?;
Ok(())
}
pub fn leave_multicast_v4(
&self,
multiaddr: &Ipv4Addr,
interface: &Ipv4Addr,
) -> Result<(), io::Error> {
#[cfg(not(target_os = "espidf"))]
self.as_ref().leave_multicast_v4(multiaddr, interface)?;
#[cfg(target_os = "espidf")]
self.setsockopt_ipproto_ip(
multiaddr, interface, 4, /* IP_LEAVE_MEMBERSHIP in ESP IDF*/
)?;
Ok(())
}
#[cfg(target_os = "espidf")]
pub fn setsockopt_ipproto_ip(
&self,
multiaddr: &Ipv4Addr,
interface: &Ipv4Addr,
option: u32,
) -> Result<(), io::Error> {
// join_multicast_v4() is broken for ESP-IDF due to IP_ADD_MEMBERSHIP being wrongly defined to 11,
// while it should be 3: https://github.com/rust-lang/libc/blob/main/src/unix/newlib/mod.rs#L568
//
// leave_multicast_v4() is broken for ESP-IDF due to IP_ADD_MEMBERSHIP being wrongly defined to 12,
// while it should be 4: https://github.com/rust-lang/libc/blob/main/src/unix/newlib/mod.rs#L569
let mreq = sys::ip_mreq {
imr_multiaddr: sys::in_addr {
s_addr: u32::from_ne_bytes(multiaddr.octets()),
},
imr_interface: sys::in_addr {
s_addr: u32::from_ne_bytes(interface.octets()),
},
};
use std::os::fd::AsRawFd;
syscall_los!(unsafe {
sys::setsockopt(
self.0.as_raw_fd(),
sys::IPPROTO_IP as _,
option as _,
&mreq as *const _ as *const _,
core::mem::size_of::<sys::ip_mreq>() as _,
)
})?;
Ok(())
}
}
impl Deref for UdpSocket {
type Target = Async<StdUdpSocket>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ErrorType for &UdpSocket {
type Error = io::Error;
}
impl UdpReceive for &UdpSocket {
async fn receive(&mut self, buffer: &mut [u8]) -> Result<(usize, SocketAddr), Self::Error> {
let remote = self.0.as_ref().peer_addr();
let (len, remote) = if let Ok(remote) = remote {
// Connected socket
let fut = pin!(self.0.recv(buffer));
let len = fut.await?;
(len, remote)
} else {
// Unconnected socket
let fut = pin!(self.0.recv_from(buffer));
let (len, remote) = fut.await?;
(len, remote)
};
Ok((len, remote))
}
}
impl UdpSend for &UdpSocket {
async fn send(&mut self, remote: SocketAddr, data: &[u8]) -> Result<(), Self::Error> {
let is_remote = self.0.as_ref().peer_addr().is_ok();
if is_remote {
// Connected socket
let mut offset = 0;
loop {
let fut = pin!(self.0.send(&data[offset..]));
offset += fut.await?;
if offset == data.len() {
break;
}
}
} else {
// Unconnected socket
let mut offset = 0;
loop {
let fut = pin!(self.0.send_to(&data[offset..], remote));
offset += fut.await?;
if offset == data.len() {
break;
}
}
}
Ok(())
}
}
impl MulticastV4 for &UdpSocket {
async fn join_v4(
&mut self,
multicast_addr: Ipv4Addr,
interface: Ipv4Addr,
) -> Result<(), Self::Error> {
self.join_multicast_v4(&multicast_addr, &interface)
}
async fn leave_v4(
&mut self,
multicast_addr: Ipv4Addr,
interface: Ipv4Addr,
) -> Result<(), Self::Error> {
self.leave_multicast_v4(&multicast_addr, &interface)
}
}
impl MulticastV6 for &UdpSocket {
async fn join_v6(
&mut self,
multicast_addr: Ipv6Addr,
interface: u32,
) -> Result<(), Self::Error> {
self.0
.as_ref()
.join_multicast_v6(&multicast_addr, interface)
}
async fn leave_v6(
&mut self,
multicast_addr: Ipv6Addr,
interface: u32,
) -> Result<(), Self::Error> {
self.0
.as_ref()
.leave_multicast_v6(&multicast_addr, interface)
}
}
impl Readable for &UdpSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
self.0.readable().await
}
}
impl ErrorType for UdpSocket {
type Error = io::Error;
}
impl UdpReceive for UdpSocket {
async fn receive(&mut self, buffer: &mut [u8]) -> Result<(usize, SocketAddr), Self::Error> {
let mut rself = &*self;
let fut = pin!(rself.receive(buffer));
fut.await
}
}
impl UdpSend for UdpSocket {
async fn send(&mut self, remote: SocketAddr, data: &[u8]) -> Result<(), Self::Error> {
let mut rself = &*self;
let fut = pin!(rself.send(remote, data));
fut.await
}
}
impl MulticastV4 for UdpSocket {
async fn join_v4(
&mut self,
multicast_addr: Ipv4Addr,
interface: Ipv4Addr,
) -> Result<(), Self::Error> {
self.join_multicast_v4(&multicast_addr, &interface)
}
async fn leave_v4(
&mut self,
multicast_addr: Ipv4Addr,
interface: Ipv4Addr,
) -> Result<(), Self::Error> {
self.leave_multicast_v4(&multicast_addr, &interface)
}
}
impl MulticastV6 for UdpSocket {
async fn join_v6(
&mut self,
multicast_addr: Ipv6Addr,
interface: u32,
) -> Result<(), Self::Error> {
self.0
.as_ref()
.join_multicast_v6(&multicast_addr, interface)
}
async fn leave_v6(
&mut self,
multicast_addr: Ipv6Addr,
interface: u32,
) -> Result<(), Self::Error> {
self.0
.as_ref()
.leave_multicast_v6(&multicast_addr, interface)
}
}
impl Readable for UdpSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
let mut rself = &*self;
let fut = pin!(rself.readable());
fut.await
}
}
impl UdpSplit for UdpSocket {
type Receive<'a>
= &'a Self
where
Self: 'a;
type Send<'a>
= &'a Self
where
Self: 'a;
fn split(&mut self) -> (Self::Receive<'_>, Self::Send<'_>) {
let socket = &*self;
(socket, socket)
}
}
impl Dns for Stack {
type Error = io::Error;
async fn get_host_by_name(
&self,
host: &str,
addr_type: AddrType,
) -> Result<IpAddr, Self::Error> {
let host = host.to_string();
dns_lookup_host(&host, addr_type)
}
async fn get_host_by_address(
&self,
_addr: IpAddr,
_result: &mut [u8],
) -> Result<usize, Self::Error> {
Err(io::ErrorKind::Unsupported.into())
}
}
fn dns_lookup_host(host: &str, addr_type: AddrType) -> Result<IpAddr, io::Error> {
(host, 0_u16)
.to_socket_addrs()?
.find(|addr| match addr_type {
AddrType::IPv4 => matches!(addr, std::net::SocketAddr::V4(_)),
AddrType::IPv6 => matches!(addr, std::net::SocketAddr::V6(_)),
AddrType::Either => true,
})
.map(|addr| match addr {
std::net::SocketAddr::V4(v4) => v4.ip().octets().into(),
std::net::SocketAddr::V6(v6) => v6.ip().octets().into(),
})
.ok_or_else(|| io::ErrorKind::AddrNotAvailable.into())
}
#[cfg(all(unix, not(target_os = "espidf")))]
mod raw {
use core::ops::Deref;
use core::pin::pin;
use std::io::{self, ErrorKind};
use std::os::fd::{AsFd, AsRawFd};
#[cfg(not(feature = "async-io-mini"))]
use async_io::Async;
#[cfg(feature = "async-io-mini")]
use async_io_mini::Async;
use edge_nal::{MacAddr, RawBind, RawReceive, RawSend, RawSplit, Readable};
use embedded_io_async::ErrorType;
use crate::sys;
use crate::syscall_los;
#[derive(Default)]
pub struct Interface(u32);
impl Interface {
pub const fn new(interface: u32) -> Self {
Self(interface)
}
}
impl RawBind for Interface {
type Error = io::Error;
type Socket<'a>
= RawSocket
where
Self: 'a;
async fn bind(&self) -> Result<Self::Socket<'_>, Self::Error> {
let socket = syscall_los!(unsafe {
sys::socket(
sys::PF_PACKET,
sys::SOCK_DGRAM,
(sys::ETH_P_IP as u16).to_be() as _,
)
})?;
let sockaddr = sys::sockaddr_ll {
sll_family: sys::AF_PACKET as _,
sll_protocol: (sys::ETH_P_IP as u16).to_be() as _,
sll_ifindex: self.0 as _,
sll_hatype: 0,
sll_pkttype: 0,
sll_halen: 0,
sll_addr: Default::default(),
};
syscall_los!(unsafe {
sys::bind(
socket,
&sockaddr as *const _ as *const _,
core::mem::size_of::<sys::sockaddr_ll>() as _,
)
})?;
// TODO
// syscall_los!(unsafe {
// sys::setsockopt(socket, sys::SOL_PACKET, sys::PACKET_AUXDATA, &1_u32 as *const _ as *const _, 4)
// })?;
let socket = {
use std::os::fd::FromRawFd;
unsafe { std::net::UdpSocket::from_raw_fd(socket) }
};
socket.set_broadcast(true)?;
Ok(RawSocket(Async::new(socket)?, self.0 as _))
}
}
pub struct RawSocket(Async<std::net::UdpSocket>, u32);
impl RawSocket {
pub const fn new(socket: Async<std::net::UdpSocket>, interface: u32) -> Self {
Self(socket, interface)
}
pub fn release(self) -> (Async<std::net::UdpSocket>, u32) {
(self.0, self.1)
}
}
impl Deref for RawSocket {
type Target = Async<std::net::UdpSocket>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ErrorType for &RawSocket {
type Error = io::Error;
}
impl RawReceive for &RawSocket {
async fn receive(&mut self, buffer: &mut [u8]) -> Result<(usize, MacAddr), Self::Error> {
let fut = pin!(self.0.read_with(|io| {
let mut storage: sys::sockaddr_storage = unsafe { core::mem::zeroed() };
let mut addrlen = core::mem::size_of_val(&storage) as sys::socklen_t;
let ret = syscall_los!(unsafe {
sys::recvfrom(
io.as_fd().as_raw_fd(),
buffer.as_mut_ptr() as *mut _,
buffer.len(),
0,
&mut storage as *mut _ as *mut _,
&mut addrlen,
)
})?;
let sockaddr = as_sockaddr_ll(&storage, addrlen as usize)?;
let mut mac = [0; 6];
mac.copy_from_slice(&sockaddr.sll_addr[..6]);
Ok((ret as usize, mac))
}));
fut.await
}
}
impl RawSend for &RawSocket {
async fn send(&mut self, mac: MacAddr, data: &[u8]) -> Result<(), Self::Error> {
let mut sockaddr = sys::sockaddr_ll {
sll_family: sys::AF_PACKET as _,
sll_protocol: (sys::ETH_P_IP as u16).to_be() as _,
sll_ifindex: self.1 as _,
sll_hatype: 0,
sll_pkttype: 0,
sll_halen: 0,
sll_addr: Default::default(),
};
sockaddr.sll_halen = mac.len() as _;
sockaddr.sll_addr[..mac.len()].copy_from_slice(&mac);
let fut = pin!(self.0.write_with(|io| {
let len = core::cmp::min(data.len(), u16::MAX as usize);
let ret = syscall_los!(unsafe {
sys::sendto(
io.as_fd().as_raw_fd(),
data.as_ptr() as *const _,
len,
sys::MSG_NOSIGNAL,
&sockaddr as *const _ as *const _,
core::mem::size_of::<sys::sockaddr_ll>() as _,
)
})?;
Ok(ret as usize)
}));
let len = fut.await?;
assert_eq!(len, data.len());
Ok(())
}
}
impl Readable for &RawSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
self.0.readable().await
}
}
impl ErrorType for RawSocket {
type Error = io::Error;
}
impl RawReceive for RawSocket {
async fn receive(&mut self, buffer: &mut [u8]) -> Result<(usize, MacAddr), Self::Error> {
let mut rself = &*self;
let fut = pin!(rself.receive(buffer));
fut.await
}
}
impl RawSend for RawSocket {
async fn send(&mut self, mac: MacAddr, data: &[u8]) -> Result<(), Self::Error> {
let mut rself = &*self;
let fut = pin!(rself.send(mac, data));
fut.await
}
}
impl RawSplit for RawSocket {
type Receive<'a>
= &'a Self
where
Self: 'a;
type Send<'a>
= &'a Self
where
Self: 'a;
fn split(&mut self) -> (Self::Receive<'_>, Self::Send<'_>) {
let socket = &*self;
(socket, socket)
}
}
impl Readable for RawSocket {
async fn readable(&mut self) -> Result<(), Self::Error> {
self.0.readable().await
}
}
fn as_sockaddr_ll(
storage: &sys::sockaddr_storage,
len: usize,
) -> io::Result<&sys::sockaddr_ll> {
match storage.ss_family as core::ffi::c_int {
sys::AF_PACKET => {
assert!(len >= core::mem::size_of::<sys::sockaddr_ll>());
Ok(unsafe { (storage as *const _ as *const sys::sockaddr_ll).as_ref() }.unwrap())
}
_ => Err(io::Error::new(ErrorKind::InvalidInput, "invalid argument")),
}
}
}
mod sys {
pub use libc::*;
#[macro_export]
macro_rules! syscall {
($ret:expr) => {{
let result = $ret;
if result != 0 {
Err(::std::io::Error::from_raw_os_error(result))
} else {
Ok(result)
}
}};
}
#[macro_export]
macro_rules! syscall_los {
($ret:expr) => {{
let result = $ret;
if result == -1 {
Err(::std::io::Error::last_os_error())
} else {
Ok(result)
}
}};
}
#[macro_export]
macro_rules! syscall_los_eagain {
($ret:expr) => {{
#[allow(unreachable_patterns)]
match syscall_los!($ret) {
Ok(_) => Ok(()),
Err(e)
if matches!(
e.raw_os_error(),
Some(sys::EINPROGRESS) | Some(sys::EAGAIN) | Some(sys::EWOULDBLOCK)
) =>
{
Ok(())
}
Err(e) => Err(e),
}?;
Ok::<_, io::Error>(())
}};
}
}