forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 3
/
net.rs
1414 lines (1202 loc) · 40.4 KB
/
net.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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![deny(unsafe_op_in_unsafe_fn)]
#![allow(dead_code)]
use super::err2io;
use super::fd::WasiFd;
use crate::fmt;
use crate::collections::VecDeque;
use crate::io::{self, IoSlice, IoSliceMut};
use crate::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr};
use crate::os::wasi::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, RawFd};
use crate::sys_common::{AsInner, FromInner, IntoInner};
use crate::sync::{Arc, Mutex};
use crate::time::Instant;
use crate::time::Duration;
use libc::{
c_int,
};
pub use crate::sys::{cvt, cvt_r};
pub struct Socket {
fd: Option<WasiFd>,
addr: SocketAddr,
peer: Arc<Mutex<Option<SocketAddr>>>,
}
impl Socket
{
pub fn new(addr: &SocketAddr, ty: c_int) -> io::Result<Socket> {
let fam = match *addr {
SocketAddr::V4(..) => AF_INET,
SocketAddr::V6(..) => AF_INET6,
};
let mut sock = Self::new_raw(fam, ty)?;
sock.addr = addr.clone();
unsafe {
let addr = to_wasi_addr_port(addr.clone());
wasi::sock_bind(sock.fd(), &addr).map_err(err2io)?;
}
Ok(sock)
}
pub fn new_raw(fam: c_int, ty: c_int) -> io::Result<Socket> {
unsafe {
let wasi_fam = match fam {
AF_INET6 => wasi::ADDRESS_FAMILY_INET6,
AF_INET => wasi::ADDRESS_FAMILY_INET4,
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid address family")); }
};
let wasi_ty = match ty {
SOCK_DGRAM => wasi::SOCK_TYPE_SOCKET_DGRAM,
SOCK_STREAM => wasi::SOCK_TYPE_SOCKET_STREAM,
SOCK_RAW => wasi::SOCK_TYPE_SOCKET_RAW,
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid socket type")); }
};
let wasi_proto = match ty {
SOCK_DGRAM => wasi::SOCK_PROTO_UDP,
SOCK_STREAM => wasi::SOCK_PROTO_TCP,
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid socket protocol")); }
};
let ip = match fam {
AF_INET6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
AF_INET => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid address family")); }
};
let fd = wasi::sock_open(wasi_fam, wasi_ty, wasi_proto).map_err(err2io)?;
Ok(Socket {
fd: Some(WasiFd::from_raw_fd(fd as RawFd)),
addr: SocketAddr::new(ip, 0),
peer: Arc::new(Mutex::new(None)),
})
}
}
pub fn new_pair(fam: c_int, _ty: c_int) -> io::Result<(Socket, Socket)> {
let ip = match fam {
AF_INET6 => IpAddr::V6(Ipv6Addr::UNSPECIFIED),
AF_INET => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid address family")); }
};
let (fd1, fd2) = unsafe {
wasi::fd_pipe().map_err(err2io)?
};
let socket1 = Socket {
fd: Some(unsafe { WasiFd::from_raw_fd(fd1 as RawFd) }),
addr: SocketAddr::new(ip, 0),
peer: Arc::new(Mutex::new(None)),
};
let socket2 = Socket {
fd: Some(unsafe { WasiFd::from_raw_fd(fd2 as RawFd) }),
addr: SocketAddr::new(ip, 0),
peer: Arc::new(Mutex::new(None)),
};
Ok((socket1, socket2))
}
pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> {
let timeout = self.timeout_internal(wasi::SOCK_OPTION_CONNECT_TIMEOUT)?
.unwrap_or_else(|| Duration::from_secs(20));
self.connect_timeout(addr, timeout)
}
pub fn connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
let r = unsafe {
let addr = to_wasi_addr_port(*addr);
wasi::sock_connect(self.fd(), &addr).map_err(err2io)
};
match r {
Ok(_) => return Ok(()),
Err(ref e) if e.raw_os_error() == Some(wasi::ERRNO_INPROGRESS.raw() as i32) => {}
Err(e) => return Err(e),
}
{
let mut peer = self.peer.lock().unwrap();
peer.replace(addr.clone());
}
let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLOUT, revents: 0 };
if timeout.as_secs() == 0 && timeout.subsec_nanos() == 0 {
return Err(io::const_io_error!(
io::ErrorKind::InvalidInput,
"cannot set a 0 duration timeout",
));
}
let start = Instant::now();
loop {
let elapsed = start.elapsed();
if elapsed >= timeout {
return Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out"));
}
let timeout = timeout - elapsed;
let mut timeout = timeout
.as_secs()
.saturating_mul(1_000)
.saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
if timeout == 0 {
timeout = 1;
}
let timeout = timeout.min(libc::c_int::MAX as u64) as c_int;
match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
-1 => {
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::Interrupted {
return Err(err);
}
}
0 => {}
_ => {
// linux returns POLLOUT|POLLERR|POLLHUP for refused connections (!), so look
// for POLLHUP rather than read readiness
if pollfd.revents & libc::POLLHUP != 0 {
let e = self.take_error()?.unwrap_or_else(|| {
io::const_io_error!(
io::ErrorKind::Uncategorized,
"no error set after POLLHUP",
)
});
return Err(e);
}
return Ok(());
}
}
}
}
pub fn accept(&self) -> io::Result<Socket> {
let (fd, addr) = unsafe {
wasi::sock_accept2(self.fd(), 0).map_err(err2io)?
};
let addr = conv_addr_port(addr);
Ok(Socket {
fd: Some(unsafe { WasiFd::from_raw_fd(fd as RawFd) }),
addr,
peer: Arc::new(Mutex::new(Some(addr))),
})
}
pub fn accept_timeout(&self, timeout: Duration) -> io::Result<Socket> {
self.set_nonblocking(true)?;
loop {
let mut pollfd = libc::pollfd { fd: self.as_raw_fd(), events: libc::POLLIN, revents: 0 };
let start = Instant::now();
loop {
let elapsed = start.elapsed();
if elapsed >= timeout {
return Err(io::const_io_error!(io::ErrorKind::TimedOut, "connection timed out"));
}
let timeout = timeout - elapsed;
let mut timeout = timeout
.as_secs()
.saturating_mul(1_000)
.saturating_add(timeout.subsec_nanos() as u64 / 1_000_000);
if timeout == 0 {
timeout = 1;
}
let timeout = timeout.min(libc::c_int::MAX as u64) as c_int;
match unsafe { libc::poll(&mut pollfd, 1, timeout) } {
-1 => {
let err = io::Error::last_os_error();
if err.kind() != io::ErrorKind::Interrupted {
return Err(err);
}
}
0 => {}
_ => {
break;
}
}
}
unsafe {
match wasi::sock_accept2(self.fd(), 0) {
Ok((fd, addr)) => {
let addr = conv_addr_port(addr);
return Ok(Socket {
fd: Some(WasiFd::from_raw_fd(fd as RawFd)),
addr,
peer: Arc::new(Mutex::new(Some(addr))),
});
}
Err(wasi::x::ERRNO_AGAIN) => {
crate::thread::yield_now();
continue;
}
Err(err) => {
return Err(err2io(err))
}
}
}
}
}
pub fn duplicate(&self) -> io::Result<Socket> {
let peer = self.peer.lock().unwrap();
let fd = unsafe {
wasi::fd_dup(self.fd()).map_err(err2io)?
};
Ok(
Socket {
fd: Some(unsafe { WasiFd::from_raw_fd(fd as RawFd) }),
addr: self.addr.clone(),
peer: Arc::new(Mutex::new(peer.clone())),
}
)
}
fn recv_with_flags(
&self,
ri_data: &mut [IoSliceMut<'_>],
ri_flags: wasi::Riflags,
) -> io::Result<(usize, wasi::Roflags)> {
let (amt, flags) = unsafe {
wasi::sock_recv(self.fd(), super::fd::iovec(ri_data), ri_flags).map_err(err2io)?
};
Ok((amt as usize, flags))
}
pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> {
let mut data = [ IoSliceMut::new(buf) ];
let ret = self.recv_with_flags(&mut data, 0)?;
Ok(ret.0)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.recv(buf)
}
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
let mut data = [ IoSliceMut::new(buf) ];
let ret = self.recv_with_flags(&mut data, MSG_PEEK as u16)?;
Ok(ret.0)
}
pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.recv_vectored(bufs)
}
#[inline]
pub fn is_read_vectored(&self) -> bool {
self.is_recv_vectored()
}
pub fn recv_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
let ret = self.recv_with_flags(bufs, 0)?;
Ok(ret.0)
}
#[inline]
pub fn is_recv_vectored(&self) -> bool {
true
}
fn recv_from_with_flags(
&self,
ri_data: &mut [IoSliceMut<'_>],
ri_flags: wasi::Riflags,
) -> io::Result<(usize, wasi::Roflags, SocketAddr)> {
let ret = unsafe {
wasi::sock_recv_from(self.fd(), super::fd::iovec(ri_data), ri_flags).map_err(err2io)?
};
Ok((
ret.0 as usize,
ret.1,
conv_addr_port(ret.2)
))
}
pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
let mut data = [ IoSliceMut::new(buf) ];
let ret = self.recv_from_with_flags(&mut data, 0)?;
Ok((ret.0, ret.2))
}
pub fn recv_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
let n = cvt(unsafe { libc::recvmsg(self.as_raw_fd(), msg, libc::MSG_CMSG_CLOEXEC) })?;
Ok(n as usize)
}
pub fn peek_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
let mut data = [ IoSliceMut::new(buf) ];
let ret = self.recv_from_with_flags(&mut data, MSG_PEEK as u16)?;
Ok((ret.0, ret.2))
}
fn send_with_flags(
&self,
si_data: &[IoSlice<'_>],
si_flags: wasi::Siflags
) -> io::Result<usize> {
unsafe {
wasi::sock_send(self.fd(), super::fd::ciovec(si_data), si_flags).map(|a| a as usize).map_err(err2io)
}
}
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
let data = [ IoSlice::new(buf) ];
self.send_with_flags(&data, 0)
}
pub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.send_with_flags(bufs, 0)
}
#[inline]
pub fn is_send_vectored(&self) -> bool {
true
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.send(buf)
}
pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.send_vectored(bufs)
}
#[inline]
pub fn is_write_vectored(&self) -> bool {
self.is_send_vectored()
}
fn send_to_with_flags(
&self,
si_data: &[IoSlice<'_>],
si_flags: wasi::Siflags,
addr: SocketAddr
) -> io::Result<usize> {
let addr = to_wasi_addr_port(addr);
unsafe {
wasi::sock_send_to(self.fd(), super::fd::ciovec(si_data), si_flags, &addr).map(|a| a as usize).map_err(err2io)
}
}
pub fn send_to(&self, buf: &[u8], addr: SocketAddr) -> io::Result<usize> {
let data = [ IoSlice::new(buf) ];
self.send_to_with_flags(&data, 0, addr)
}
pub fn send_to_vectored(&self, bufs: &[IoSlice<'_>], addr: SocketAddr) -> io::Result<usize> {
self.send_to_with_flags(bufs, 0, addr)
}
pub fn send_msg(&self, msg: &mut libc::msghdr) -> io::Result<usize> {
let n = cvt(unsafe { libc::sendmsg(self.as_raw_fd(), msg, 0) })?;
Ok(n as usize)
}
pub fn set_timeout(&self, dur: Option<Duration>, kind: libc::c_int) -> io::Result<()> {
let option = match kind {
SO_RCVTIMEO => wasi::SOCK_OPTION_RECV_TIMEOUT,
SO_SNDTIMEO => wasi::SOCK_OPTION_SEND_TIMEOUT,
SO_CONNTIMEO => wasi::SOCK_OPTION_CONNECT_TIMEOUT,
SO_ACCPTIMEO => wasi::SOCK_OPTION_ACCEPT_TIMEOUT,
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid timeout type")); }
};
self.set_timeout_internal(dur, option)
}
pub fn timeout(&self, kind: libc::c_int) -> io::Result<Option<Duration>> {
let option = match kind {
SO_RCVTIMEO => wasi::SOCK_OPTION_RECV_TIMEOUT,
SO_SNDTIMEO => wasi::SOCK_OPTION_SEND_TIMEOUT,
SO_CONNTIMEO => wasi::SOCK_OPTION_CONNECT_TIMEOUT,
SO_ACCPTIMEO => wasi::SOCK_OPTION_ACCEPT_TIMEOUT,
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid timeout type")); }
};
self.timeout_internal(option)
}
fn set_timeout_internal(&self, dur: Option<Duration>, option: wasi::SockOption) -> io::Result<()> {
let dur = match dur {
Some(dur) => wasi::OptionTimestamp {
tag: wasi::OPTION_SOME.raw(),
u: wasi::OptionTimestampU {
some: dur.as_nanos() as u64,
}
},
None => wasi::OptionTimestamp {
tag: wasi::OPTION_NONE.raw(),
u: wasi::OptionTimestampU {
none: 0,
}
}
};
unsafe {
wasi::sock_set_opt_time(self.fd(), option, &dur).map_err(err2io)
}
}
fn timeout_internal(&self, option: wasi::SockOption) -> io::Result<Option<Duration>> {
let ret = unsafe {
wasi::sock_get_opt_time(self.fd(), option).map_err(err2io)?
};
Ok(
match ret.tag {
a if a == wasi::OPTION_SOME.raw() => {
unsafe {
Some(Duration::from_nanos(ret.u.some as u64))
}
},
a if a == wasi::OPTION_NONE.raw() => {
None
},
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid response")); }
}
)
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
use crate::ops::Deref;
let peer = self.peer.lock().unwrap();
if let Some(peer) = peer.deref() {
Ok(peer.clone())
} else {
Ok(
match self.addr {
SocketAddr::V4(..) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
SocketAddr::V6(..) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
}
)
}
}
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
Ok(self.addr.clone())
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
let how = match how {
Shutdown::Read => wasi::SDFLAGS_RD,
Shutdown::Write => wasi::SDFLAGS_WR,
Shutdown::Both => wasi::SDFLAGS_WR | wasi::SDFLAGS_RD,
};
unsafe { wasi::sock_shutdown(self.fd(), how).map_err(err2io) }
}
pub fn set_reuse_addr(&self, reuse: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_REUSE_ADDR, reuse)
}
pub fn reuse_addr(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_REUSE_ADDR)
}
pub fn set_reuse_port(&self, reuse: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_REUSE_PORT, reuse)
}
pub fn reuse_port(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_REUSE_PORT)
}
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_NO_DELAY, nodelay)
}
pub fn nodelay(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_NO_DELAY)
}
pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_ONLY_V6, only_v6)
}
pub fn only_v6(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_ONLY_V6)
}
pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_BROADCAST, broadcast)
}
pub fn broadcast(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_BROADCAST)
}
pub fn set_multicast_loop_v4(&self, val: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_MULTICAST_LOOP_V4, val)
}
pub fn multicast_loop_v4(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_MULTICAST_LOOP_V4)
}
pub fn set_multicast_loop_v6(&self, val: bool) -> io::Result<()> {
self.set_opt_flag(wasi::SOCK_OPTION_MULTICAST_LOOP_V6, val)
}
pub fn multicast_loop_v6(&self) -> io::Result<bool> {
self.get_opt_flag(wasi::SOCK_OPTION_MULTICAST_LOOP_V6)
}
fn set_opt_flag(&self, sockopt: wasi::SockOption, val: bool) -> io::Result<()> {
unsafe {
let val = match val {
false => wasi::BOOL_FALSE,
true => wasi::BOOL_TRUE
};
wasi::sock_set_opt_flag(self.fd(), sockopt, val).map_err(err2io)
}
}
fn get_opt_flag(&self, sockopt: wasi::SockOption) -> io::Result<bool> {
let val = unsafe {
wasi::sock_get_opt_flag(self.fd(), sockopt).map_err(err2io)?
};
Ok(
match val {
wasi::BOOL_TRUE => true,
wasi::BOOL_FALSE | _ => false,
}
)
}
pub fn set_linger(&self, val: Option<Duration>) -> io::Result<()> {
let val = match val {
Some(dur) => wasi::OptionTimestamp {
tag: wasi::OPTION_SOME.raw(),
u: wasi::OptionTimestampU {
some: dur.as_nanos() as u64,
}
},
None => wasi::OptionTimestamp {
tag: wasi::OPTION_NONE.raw(),
u: wasi::OptionTimestampU {
none: 0,
}
}
};
unsafe {
wasi::sock_set_opt_time(self.fd(), wasi::SOCK_OPTION_LINGER, &val).map_err(err2io)
}
}
pub fn linger(&self) -> io::Result<Option<Duration>> {
let ret = unsafe {
wasi::sock_get_opt_time(self.fd(), wasi::SOCK_OPTION_LINGER).map_err(err2io)?
};
Ok(
match ret.tag {
a if a == wasi::OPTION_SOME.raw() => {
unsafe {
Some(Duration::from_nanos(ret.u.some as u64))
}
},
a if a == wasi::OPTION_NONE.raw() => {
None
},
_ => { return Err(io::const_io_error!(io::ErrorKind::Uncategorized, "invalid response")); }
}
)
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
let fdstat = unsafe {
wasi::fd_fdstat_get(self.fd()).map_err(err2io)?
};
let mut flags = fdstat.fs_flags;
if nonblocking {
flags |= wasi::FDFLAGS_NONBLOCK;
} else {
flags &= !wasi::FDFLAGS_NONBLOCK;
}
unsafe {
wasi::fd_fdstat_set_flags(self.fd(), flags)
.map_err(err2io)?;
}
Ok(())
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
unsafe {
wasi::sock_set_opt_size(self.fd(), wasi::SOCK_OPTION_TTL, ttl as wasi::Filesize).map_err(err2io)
}
}
pub fn ttl(&self) -> io::Result<u32> {
let ttl = unsafe {
wasi::sock_get_opt_size(self.fd(), wasi::SOCK_OPTION_TTL).map_err(err2io)? as u32
};
Ok(ttl)
}
pub fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()> {
unsafe {
wasi::sock_set_opt_size(self.fd(), wasi::SOCK_OPTION_MULTICAST_TTL_V4, ttl as wasi::Filesize).map_err(err2io)
}
}
pub fn multicast_ttl_v4(&self) -> io::Result<u32> {
let ttl = unsafe {
wasi::sock_get_opt_size(self.fd(), wasi::SOCK_OPTION_MULTICAST_TTL_V4).map_err(err2io)? as u32
};
Ok(ttl)
}
pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
let multiaddr = to_wasi_addr_v4(*multiaddr);
let interface = to_wasi_addr_v4(*interface);
unsafe {
wasi::sock_join_multicast_v4(self.fd(), &multiaddr, &interface).map_err(err2io)
}
}
pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
let multiaddr = to_wasi_addr_v6(*multiaddr);
unsafe {
wasi::sock_join_multicast_v6(self.fd(), &multiaddr, interface).map_err(err2io)
}
}
pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
let multiaddr = to_wasi_addr_v4(*multiaddr);
let interface = to_wasi_addr_v4(*interface);
unsafe {
wasi::sock_leave_multicast_v4(self.fd(), &multiaddr, &interface).map_err(err2io)
}
}
pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
let multiaddr = to_wasi_addr_v6(*multiaddr);
unsafe {
wasi::sock_leave_multicast_v6(self.fd(), &multiaddr, interface).map_err(err2io)
}
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
Ok(None)
}
pub fn as_raw(&self) -> RawFd {
self.as_raw_fd()
}
fn fd(&self) -> wasi::Fd {
self.as_raw_fd() as wasi::Fd
}
}
impl Drop
for Socket
{
fn drop(&mut self) {
unsafe {
if let Some(fd) = self.fd.take() {
let _ = wasi::fd_close(fd.as_raw_fd() as wasi::Fd);
}
}
}
}
fn conv_addr_port(addr: wasi::AddrPort) -> SocketAddr {
unsafe {
match addr.tag {
a if a == wasi::ADDRESS_FAMILY_INET6.raw() => {
let u = &addr.u.inet6.addr;
let ip = IpAddr::V6(Ipv6Addr::new(u.n0, u.n1, u.n2, u.n3, u.h0, u.h1, u.h2, u.h3));
SocketAddr::new(ip, addr.u.inet6.port)
}
_ => {
let u = &addr.u.inet4.addr;
let ip = IpAddr::V4(Ipv4Addr::new(u.n0, u.n1, u.h0, u.h1));
SocketAddr::new(ip, addr.u.inet4.port)
},
}
}
}
fn conv_addr_v4(u: wasi::AddrIp4) -> Ipv4Addr {
Ipv4Addr::new(u.n0, u.n1, u.h0, u.h1)
}
fn conv_addr_v6(u: wasi::AddrIp6) -> Ipv6Addr {
Ipv6Addr::new(u.n0, u.n1, u.n2, u.n3, u.h0, u.h1, u.h2, u.h3)
}
fn conv_addr(addr: wasi::Addr) -> IpAddr {
unsafe {
match addr.tag {
a if a == wasi::ADDRESS_FAMILY_INET6.raw() => {
IpAddr::V6(conv_addr_v6(addr.u.inet6))
},
_ => {
IpAddr::V4(conv_addr_v4(addr.u.inet4))
}
}
}
}
fn to_wasi_addr_port(addr: SocketAddr) -> wasi::AddrPort {
let ip = to_wasi_addr(addr.ip());
unsafe {
wasi::AddrPort {
tag: ip.tag,
u: match ip.tag {
a if a == wasi::ADDRESS_FAMILY_INET6.raw() => {
wasi::AddrPortU {
inet6: wasi::AddrIp6Port {
addr: ip.u.inet6,
port: addr.port()
}
}
},
_ => {
wasi::AddrPortU {
inet4: wasi::AddrIp4Port {
addr: ip.u.inet4,
port: addr.port()
}
}
}
}
}
}
}
fn to_wasi_addr_v4(ip: Ipv4Addr) -> wasi::AddrIp4 {
let octs = ip.octets();
wasi::AddrIp4 {
n0: octs[0],
n1: octs[1],
h0: octs[2],
h1: octs[3],
}
}
fn to_wasi_addr_v6(ip: Ipv6Addr) -> wasi::AddrIp6 {
let segs = ip.segments();
wasi::AddrIp6 {
n0: segs[0],
n1: segs[1],
n2: segs[2],
n3: segs[3],
h0: segs[4],
h1: segs[5],
h2: segs[6],
h3: segs[7]
}
}
fn to_wasi_addr(addr: IpAddr) -> wasi::Addr {
match addr {
IpAddr::V4(ip) => {
wasi::Addr {
tag: wasi::ADDRESS_FAMILY_INET4.raw(),
u: wasi::AddrU {
inet4: to_wasi_addr_v4(ip)
}
}
},
IpAddr::V6(ip) => {
wasi::Addr {
tag: wasi::ADDRESS_FAMILY_INET6.raw(),
u: wasi::AddrU {
inet6: to_wasi_addr_v6(ip)
}
}
}
}
}
impl AsInner<WasiFd> for Socket {
fn as_inner(&self) -> &WasiFd {
self.fd.as_ref().unwrap()
}
}
impl IntoInner<WasiFd> for Socket {
fn into_inner(mut self) -> WasiFd {
self.fd.take().unwrap()
}
}
impl FromInner<WasiFd> for Socket {
fn from_inner(inner: WasiFd) -> Socket {
Socket {
fd: Some(inner),
addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
peer: Arc::new(Mutex::new(None)),
}
}
}
impl AsFd for Socket {
fn as_fd(&self) -> BorrowedFd<'_> {
let fd = self.as_raw_fd();
unsafe {
BorrowedFd::borrow_raw(fd)
}
}
}
impl AsRawFd for Socket {
fn as_raw_fd(&self) -> RawFd {
self.fd.as_ref().map(|fd| fd.as_raw_fd()).unwrap_or_default()
}
}
impl IntoRawFd for Socket {
fn into_raw_fd(mut self) -> RawFd {
self.fd.take().map(|fd| fd.as_raw_fd()).unwrap_or_default()
}
}
impl FromRawFd for Socket {
unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
Self {
fd: Some(unsafe { WasiFd::from_raw_fd(raw_fd) }),
addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
peer: Arc::new(Mutex::new(None)),
}
}
}
pub struct TcpStream {
inner: Socket,
}
impl TcpStream {
pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result<TcpStream> {
let addr = addr?;
let fam = match *addr {
SocketAddr::V4(..) => AF_INET,
SocketAddr::V6(..) => AF_INET6,
};
let sock = Socket::new_raw(fam, SOCK_STREAM)?;
sock.connect(addr)?;
Ok(
TcpStream {
inner: sock
}
)
}
pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
let fam = match *addr {
SocketAddr::V4(..) => AF_INET,
SocketAddr::V6(..) => AF_INET6,
};
let sock = Socket::new_raw(fam, SOCK_STREAM)?;
sock.connect_timeout(addr, timeout)?;
Ok(
TcpStream {
inner: sock
}
)
}
pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout_internal(timeout, wasi::SOCK_OPTION_RECV_TIMEOUT)
}
pub fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
self.inner.set_timeout_internal(timeout, wasi::SOCK_OPTION_SEND_TIMEOUT)
}
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout_internal(wasi::SOCK_OPTION_RECV_TIMEOUT)
}
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.inner.timeout_internal(wasi::SOCK_OPTION_SEND_TIMEOUT)
}
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.peek(buf)
}
pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
self.inner.recv(buf)
}
pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
self.inner.recv_vectored(bufs)
}
pub fn is_read_vectored(&self) -> bool {
self.inner.is_recv_vectored()
}
pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
self.inner.send(buf)
}
pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.inner.send_vectored(bufs)
}
pub fn is_write_vectored(&self) -> bool {
self.inner.is_send_vectored()
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.inner.peer_addr()
}
pub fn socket_addr(&self) -> io::Result<SocketAddr> {
self.inner.socket_addr()
}
pub fn shutdown(&self, shutdown: Shutdown) -> io::Result<()> {
self.inner.shutdown(shutdown)
}
pub fn duplicate(&self) -> io::Result<TcpStream> {
Ok(
TcpStream {
inner: self.inner.duplicate()?
}
)
}
pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
self.inner.set_linger(linger)
}
pub fn linger(&self) -> io::Result<Option<Duration>> {
self.inner.linger()
}
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.inner.set_nodelay(nodelay)
}
pub fn nodelay(&self) -> io::Result<bool> {
self.inner.nodelay()
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.inner.set_ttl(ttl)
}
pub fn ttl(&self) -> io::Result<u32> {
self.inner.ttl()
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.inner.take_error()
}
pub fn set_nonblocking(&self, state: bool) -> io::Result<()> {
self.inner.set_nonblocking(state)
}