Repository navigation
Expand file tree
/
Copy pathsocket.rs
More file actions
2024 lines (1846 loc) · 63 KB
/
Copy pathsocket.rs
File metadata and controls
2024 lines (1846 loc) · 63 KB
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
#[cfg(unix)]
use crate::os::CheckLibcResult;
#[cfg(unix)]
use core::ffi::CStr;
#[cfg(unix)]
use std::os::fd::AsRawFd;
#[cfg(unix)]
use std::{io, os::fd::BorrowedFd};
/// Returns the system's hostname.
#[cfg(not(target_arch = "wasm32"))]
pub fn hostname() -> std::ffi::OsString {
gethostname::gethostname()
}
#[cfg(not(target_arch = "wasm32"))]
pub use ::dns_lookup as dns;
#[cfg(not(target_arch = "wasm32"))]
pub use ::socket2 as raw;
#[cfg(target_os = "linux")]
pub mod bluetooth;
#[cfg(not(any(
target_os = "ios",
target_os = "android",
target_os = "windows",
target_arch = "wasm32",
target_os = "redox"
)))]
fn select_mac_address(addresses: impl IntoIterator<Item = [u8; 6]>) -> Option<[u8; 6]> {
let mut first_local = None;
for address in addresses {
if address == [0; 6] {
continue;
}
if address[0] & 0x02 == 0 {
return Some(address);
}
first_local.get_or_insert(address);
}
first_local
}
/// Returns a universally administered MAC address when available, otherwise
/// the first locally administered address, or `None` when lookup fails.
#[cfg(not(any(
target_os = "ios",
target_os = "android",
target_os = "windows",
target_arch = "wasm32",
target_os = "redox"
)))]
pub fn mac_address() -> Option<[u8; 6]> {
let addresses = mac_address::MacAddressIterator::new().ok()?;
select_mac_address(addresses.map(|address| address.bytes()))
}
#[cfg(test)]
#[cfg(not(any(
target_os = "ios",
target_os = "android",
target_os = "windows",
target_arch = "wasm32",
target_os = "redox"
)))]
mod mac_address_tests {
use super::select_mac_address;
#[test]
fn prefers_universally_administered_address() {
let local = [0x02, 0, 0, 0, 0, 1];
let universal = [0x00, 0, 0, 0, 0, 2];
assert_eq!(select_mac_address([local, universal]), Some(universal));
}
#[test]
fn falls_back_to_first_locally_administered_address() {
let first = [0x02, 0, 0, 0, 0, 1];
let second = [0x06, 0, 0, 0, 0, 2];
assert_eq!(select_mac_address([first, second]), Some(first));
}
#[test]
fn ignores_zero_address() {
let universal = [0x00, 0, 0, 0, 0, 1];
assert_eq!(select_mac_address([[0; 6], universal]), Some(universal));
assert_eq!(select_mac_address([[0; 6]]), None);
}
}
#[cfg(unix)]
pub use libc::{AF_UNIX, SOCK_STREAM, sa_family_t, sockaddr_storage, socklen_t};
/// Integer names the VM published from `libc as c` on unix. Windows already
/// takes the overlapping set from this module.
#[cfg(unix)]
pub use libc::{
AF_INET, AF_INET6, AF_UNSPEC, AI_ADDRCONFIG, AI_CANONNAME, AI_NUMERICHOST, AI_NUMERICSERV,
AI_PASSIVE, INADDR_ANY, INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_NONE, IPPROTO_ICMP,
IPPROTO_ICMPV6, IPPROTO_IP, IPPROTO_IPV6, IPPROTO_TCP, IPPROTO_UDP, MSG_CTRUNC, MSG_DONTROUTE,
MSG_OOB, MSG_PEEK, MSG_TRUNC, MSG_WAITALL, NI_DGRAM, NI_MAXHOST, NI_NAMEREQD, NI_NOFQDN,
NI_NUMERICHOST, NI_NUMERICSERV, SHUT_RD, SHUT_RDWR, SHUT_WR, SO_BROADCAST, SO_ERROR,
SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE, SO_RCVBUF, SO_REUSEADDR, SO_SNDBUF, SO_TYPE, SOCK_DGRAM,
SOL_SOCKET, SOMAXCONN, TCP_NODELAY,
};
#[cfg(all(unix, not(target_os = "redox")))]
pub use libc::{
AF_APPLETALK, AF_DECnet, AF_IPX, IPPROTO_AH, IPPROTO_DSTOPTS, IPPROTO_EGP, IPPROTO_ESP,
IPPROTO_FRAGMENT, IPPROTO_HOPOPTS, IPPROTO_IDP, IPPROTO_IGMP, IPPROTO_IPIP, IPPROTO_NONE,
IPPROTO_PIM, IPPROTO_PUP, IPPROTO_RAW, IPPROTO_ROUTING, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET,
};
#[cfg(unix)]
pub use libc::SO_REUSEPORT;
#[cfg(any(unix, target_os = "android"))]
pub use libc::{
EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY, EAI_MEMORY, EAI_NONAME, EAI_SERVICE,
EAI_SOCKTYPE, EAI_SYSTEM, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_HDRINCL, IP_MULTICAST_IF,
IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TOS, IP_TTL, IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF,
IPV6_MULTICAST_LOOP, IPV6_UNICAST_HOPS, IPV6_V6ONLY, MSG_EOR, SO_ACCEPTCONN, SO_DEBUG,
SO_DONTROUTE, SO_RCVLOWAT, SO_RCVTIMEO, SO_SNDLOWAT, SO_SNDTIMEO,
};
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use libc::{IP_OPTIONS, IPV6_HOPOPTS, IPV6_RECVRTHDR, IPV6_RTHDR};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_vendor = "apple",
))]
pub use libc::IPV6_DONTFRAG;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_vendor = "apple",
))]
pub use libc::{IPV6_CHECKSUM, IPV6_HOPLIMIT};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple",
))]
pub use libc::{AI_ALL, AI_V4MAPPED};
#[cfg(any(
target_os = "android",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
))]
pub use libc::EAI_NODATA;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
))]
pub use libc::IPV6_PKTINFO;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
))]
pub use libc::{IPV6_RECVTCLASS, IPV6_TCLASS};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
pub use libc::{
AF_LINK, IP_RECVDSTADDR, IPPROTO_GGP, IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP, SO_USELOOPBACK,
};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_vendor = "apple",
))]
pub use libc::IPPROTO_ND;
#[cfg(any(target_os = "netbsd", target_os = "openbsd"))]
pub use libc::{MSG_BCAST, MSG_MCAST};
#[cfg(any(target_os = "netbsd", target_os = "redox", target_vendor = "apple"))]
pub use libc::NI_MAXSERV;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
pub use libc::{
AF_ROUTE, AF_SNA, EAI_OVERFLOW, IPPROTO_GRE, IPPROTO_RSVP, IPPROTO_TP, IPV6_RECVPKTINFO,
MSG_DONTWAIT, SCM_RIGHTS, TCP_MAXSEG,
};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "redox"
))]
pub use libc::{SOCK_CLOEXEC, SOCK_NONBLOCK};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_vendor = "apple"
))]
pub use libc::{TCP_KEEPCNT, TCP_KEEPINTVL};
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "redox"
))]
pub use libc::TCP_KEEPIDLE;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd"
))]
pub use libc::{MSG_CMSG_CLOEXEC, MSG_NOSIGNAL};
#[cfg(target_vendor = "apple")]
pub use libc::{
AF_SYSTEM, IP_ADD_SOURCE_MEMBERSHIP, IP_BLOCK_SOURCE, IP_DROP_SOURCE_MEMBERSHIP, IP_PKTINFO,
IP_RECVTTL, IP_UNBLOCK_SOURCE, IPPROTO_MAX, IPPROTO_SCTP, MSG_NOSIGNAL, PF_SYSTEM,
SYSPROTO_CONTROL, TCP_CONNECTION_INFO, TCP_KEEPALIVE,
};
#[cfg(target_os = "linux")]
pub use libc::{
CAN_BCM, CAN_EFF_FLAG, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_ERR_MASK, CAN_ISOTP, CAN_J1939, CAN_RAW,
CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER, CAN_RAW_JOIN_FILTERS, CAN_RAW_LOOPBACK,
CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG, CAN_SFF_MASK, IPPROTO_MPTCP, J1939_IDLE_ADDR,
J1939_MAX_UNICAST_ADDR, J1939_NLA_BYTES_ACKED, J1939_NLA_PAD, J1939_NO_ADDR, J1939_NO_NAME,
J1939_NO_PGN, J1939_PGN_ADDRESS_CLAIMED, J1939_PGN_ADDRESS_COMMANDED, J1939_PGN_MAX,
J1939_PGN_PDU1_MAX, J1939_PGN_REQUEST, SCM_J1939_DEST_ADDR, SCM_J1939_DEST_NAME,
SCM_J1939_ERRQUEUE, SCM_J1939_PRIO, SO_J1939_ERRQUEUE, SO_J1939_FILTER, SO_J1939_PROMISC,
SO_J1939_SEND_PRIO, SOL_CAN_BASE, SOL_CAN_RAW,
};
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub use libc::SOL_RDS;
#[cfg(target_os = "android")]
pub use libc::{SOL_ATALK, SOL_AX25, SOL_IPX, SOL_NETROM, SOL_ROSE};
#[cfg(target_os = "freebsd")]
pub use libc::SO_SETFIB;
#[cfg(target_os = "netbsd")]
pub use libc::IPPROTO_VRRP;
#[cfg(any(target_os = "android", target_os = "linux"))]
pub use libc::{
ALG_OP_DECRYPT, ALG_OP_ENCRYPT, ALG_SET_AEAD_ASSOCLEN, ALG_SET_AEAD_AUTHSIZE, ALG_SET_IV,
ALG_SET_KEY, ALG_SET_OP, IP_DEFAULT_MULTICAST_LOOP, IP_RECVOPTS, IP_RETOPTS, IPV6_DSTOPTS,
IPV6_NEXTHOP, IPV6_PATHMTU, IPV6_RECVDSTOPTS, IPV6_RECVHOPLIMIT, IPV6_RECVHOPOPTS,
IPV6_RECVPATHMTU, IPV6_RTHDRDSTOPTS, NETLINK_CRYPTO, NETLINK_DNRTMSG, NETLINK_FIREWALL,
NETLINK_IP6_FW, NETLINK_NFLOG, NETLINK_ROUTE, NETLINK_USERSOCK, NETLINK_XFRM, SO_PASSSEC,
SO_PEERSEC, SOL_ALG,
};
#[cfg(any(target_os = "android", target_vendor = "apple"))]
pub use libc::{AI_DEFAULT, AI_MASK, AI_V4MAPPED_CFG};
#[cfg(any(target_os = "freebsd", target_os = "netbsd"))]
pub use libc::MSG_NOTIFICATION;
#[cfg(any(target_os = "fuchsia", target_os = "linux"))]
pub use libc::TCP_USER_TIMEOUT;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub use libc::{
AF_ASH, AF_ATMPVC, AF_ATMSVC, AF_AX25, AF_BRIDGE, AF_ECONET, AF_IRDA, AF_LLC, AF_NETBEUI,
AF_NETLINK, AF_NETROM, AF_PACKET, AF_PPPOX, AF_RDS, AF_SECURITY, AF_TIPC, AF_VSOCK, AF_WANPIPE,
AF_X25, IP_TRANSPARENT, MSG_CONFIRM, MSG_ERRQUEUE, MSG_FASTOPEN, MSG_MORE, PF_CAN, PF_PACKET,
PF_RDS, SCM_CREDENTIALS, SO_BINDTODEVICE, SO_MARK, SOL_IP, SOL_TIPC, SOL_UDP, TCP_CORK,
TCP_DEFER_ACCEPT, TCP_LINGER2, TCP_QUICKACK, TCP_SYNCNT, TCP_WINDOW_CLAMP,
};
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_vendor = "apple"
))]
pub use libc::{IPPROTO_HELLO, IPPROTO_XTP, LOCAL_PEERCRED, MSG_EOF};
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
pub use libc::{IPPROTO_UDPLITE, TCP_CONGESTION};
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
pub use libc::AF_KEY;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
target_os = "redox"
))]
pub use libc::SO_DOMAIN;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
all(
target_os = "linux",
any(
target_arch = "aarch64",
target_arch = "x86",
target_arch = "loongarch64",
target_arch = "mips",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "riscv64",
target_arch = "s390x",
target_arch = "x86_64"
)
),
target_os = "redox"
))]
pub use libc::SO_PRIORITY;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
pub use libc::IPPROTO_MOBILE;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_vendor = "apple"
))]
pub use libc::SCM_CREDS;
#[cfg(any(
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple"
))]
pub use libc::TCP_FASTOPEN;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
all(
target_os = "linux",
any(
target_arch = "aarch64",
target_arch = "x86",
target_arch = "loongarch64",
target_arch = "mips",
target_arch = "powerpc",
target_arch = "powerpc64",
target_arch = "riscv64",
target_arch = "s390x",
target_arch = "x86_64"
)
),
target_os = "redox"
))]
pub use libc::SO_PROTOCOL;
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "fuchsia",
target_os = "linux",
target_os = "redox"
))]
pub use libc::{SO_PASSCRED, SO_PEERCRED};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd"
))]
pub use libc::TCP_INFO;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_vendor = "apple"
))]
pub use libc::IP_RECVTOS;
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple"
))]
pub use libc::{IPPROTO_EON, IPPROTO_IPCOMP};
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd"
))]
pub use libc::IPPROTO_SCTP;
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
pub use libc::AF_BLUETOOTH;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub use libc::{AF_ALG, AF_CAN};
// bionic (Android) does not define the CAN/ALG sockaddr structs.
#[cfg(target_os = "linux")]
pub use libc::{sockaddr_alg, sockaddr_can};
/// Port numbers some Unix libcs omit. Windows takes `IPPORT_RESERVED` from
/// WinSock and defines `IPPORT_USERRESERVED` beside the other extras.
#[cfg(unix)]
pub const IPPORT_RESERVED: i32 = 1024;
#[cfg(unix)]
pub const IPPORT_USERRESERVED: i32 = 5000;
/// Multicast groups as unsigned host-order words. Windows publishes the
/// same bits as signed C longs (`INADDR_*_GROUP` below).
#[cfg(unix)]
pub const INADDR_UNSPEC_GROUP: u32 = 0xe000_0000;
#[cfg(unix)]
pub const INADDR_ALLHOSTS_GROUP: u32 = 0xe000_0001;
#[cfg(unix)]
pub const INADDR_MAX_LOCAL_GROUP: u32 = 0xe000_00ff;
/// POSIX `<netdb.h>` `NI_MAXSERV`. libc omits it on linux-gnu.
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const NI_MAXSERV: i32 = 32;
/// `<netinet/in.h>` join/leave and routing-header type. libc omits them
/// on linux-gnu.
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const IPV6_JOIN_GROUP: i32 = 20;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const IPV6_LEAVE_GROUP: i32 = 21;
#[cfg(any(target_os = "linux", target_os = "android"))]
pub const IPV6_RTHDR_TYPE_0: i32 = 0;
// spell-checker:ignore SETTIMER STARTTIMER COUNTEVT AUTOTIMER
/// `linux/can/bcm.h` opcodes and flags. Not in libc.
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_SETUP: i32 = 1;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_DELETE: i32 = 2;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_READ: i32 = 3;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_SEND: i32 = 4;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_SETUP: i32 = 5;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_DELETE: i32 = 6;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_READ: i32 = 7;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_STATUS: i32 = 8;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_EXPIRED: i32 = 9;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_STATUS: i32 = 10;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_TIMEOUT: i32 = 11;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_CHANGED: i32 = 12;
#[cfg(target_os = "linux")]
pub const CAN_BCM_SETTIMER: i32 = 0x0001;
#[cfg(target_os = "linux")]
pub const CAN_BCM_STARTTIMER: i32 = 0x0002;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_COUNTEVT: i32 = 0x0004;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_ANNOUNCE: i32 = 0x0008;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_CP_CAN_ID: i32 = 0x0010;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_FILTER_ID: i32 = 0x0020;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_CHECK_DLC: i32 = 0x0040;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_NO_AUTOTIMER: i32 = 0x0080;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_ANNOUNCE_RESUME: i32 = 0x0100;
#[cfg(target_os = "linux")]
pub const CAN_BCM_TX_RESET_MULTI_IDX: i32 = 0x0200;
#[cfg(target_os = "linux")]
pub const CAN_BCM_RX_RTR_FRAME: i32 = 0x0400;
#[cfg(target_os = "linux")]
pub const CAN_BCM_CAN_FD_FRAME: i32 = 0x0800;
/// `linux/vm_sockets.h`. libc does not bind the vsock sockopt / cid names.
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const SO_VM_SOCKETS_BUFFER_SIZE: u32 = 0;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const SO_VM_SOCKETS_BUFFER_MIN_SIZE: u32 = 1;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const SO_VM_SOCKETS_BUFFER_MAX_SIZE: u32 = 2;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const VMADDR_CID_ANY: u32 = 0xffff_ffff;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const VMADDR_PORT_ANY: u32 = 0xffff_ffff;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const VMADDR_CID_HOST: u32 = 2;
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
pub const VM_SOCKETS_INVALID_VERSION: u32 = 0xffff_ffff;
/// `netinet/udplite.h`. libc does not bind the coverage sockopts.
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
pub const UDPLITE_SEND_CSCOV: i32 = 10;
#[cfg(any(
target_os = "android",
target_os = "fuchsia",
target_os = "freebsd",
target_os = "linux"
))]
pub const UDPLITE_RECV_CSCOV: i32 = 11;
/// `SOL_IP` / `SOL_UDP` when libc does not bind them. Linux takes the
/// header names; Windows takes WinSock `SOL_IP`. Elsewhere they are the
/// IANA protocol numbers.
#[cfg(not(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
windows
)))]
pub const SOL_IP: i32 = 0;
#[cfg(not(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
windows
)))]
pub const SOL_UDP: i32 = 17;
/// `SOMAXCONN` when neither libc nor WinSock publishes it.
#[cfg(not(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_vendor = "apple",
windows
)))]
pub const SOMAXCONN: i32 = 5;
/// Bluetooth wildcard / local addresses. Header strings, not libc names.
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
pub const BDADDR_ANY: &str = "00:00:00:00:00:00";
#[cfg(any(
target_os = "android",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "linux",
target_os = "openbsd"
))]
pub const BDADDR_LOCAL: &str = "00:00:00:FF:FF:FF";
/// RFC 3542 IPv6 socket options (`netinet6/in6.h`). Not in libc.
#[cfg(target_vendor = "apple")]
pub const IPV6_RECVHOPLIMIT: i32 = 37;
#[cfg(target_vendor = "apple")]
pub const IPV6_RECVRTHDR: i32 = 38;
#[cfg(target_vendor = "apple")]
pub const IPV6_RECVHOPOPTS: i32 = 39;
#[cfg(target_vendor = "apple")]
pub const IPV6_RECVDSTOPTS: i32 = 40;
#[cfg(target_vendor = "apple")]
pub const IPV6_USE_MIN_MTU: i32 = 42;
#[cfg(target_vendor = "apple")]
pub const IPV6_RECVPATHMTU: i32 = 43;
#[cfg(target_vendor = "apple")]
pub const IPV6_PATHMTU: i32 = 44;
#[cfg(target_vendor = "apple")]
pub const IPV6_NEXTHOP: i32 = 48;
#[cfg(target_vendor = "apple")]
pub const IPV6_HOPOPTS: i32 = 49;
#[cfg(target_vendor = "apple")]
pub const IPV6_DSTOPTS: i32 = 50;
#[cfg(target_vendor = "apple")]
pub const IPV6_RTHDR: i32 = 51;
#[cfg(target_vendor = "apple")]
pub const IPV6_RTHDRDSTOPTS: i32 = 57;
#[cfg(target_vendor = "apple")]
pub const IPV6_RTHDR_TYPE_0: i32 = 0;
/// Darwin `<netdb.h>` `EAI_*` names the libc crate does not re-export.
#[cfg(target_vendor = "apple")]
pub const EAI_ADDRFAMILY: i32 = 1;
#[cfg(target_vendor = "apple")]
pub const EAI_BADHINTS: i32 = 12;
#[cfg(target_vendor = "apple")]
pub const EAI_PROTOCOL: i32 = 13;
#[cfg(target_vendor = "apple")]
pub const EAI_MAX: i32 = 15;
/// Set the system's hostname from its filesystem-encoded bytes.
///
/// `socketmodule.c socket_sethostname` reads the argument as a buffer and
/// passes `buf.buf`/`buf.len` straight to the syscall, so a name is not
/// required to be UTF-8; taking `&[u8]` keeps that true here as well.
#[cfg(all(unix, not(target_os = "redox")))]
pub fn sethostname(hostname: &[u8]) -> io::Result<()> {
use std::os::unix::ffi::OsStrExt;
nix::unistd::sethostname(std::ffi::OsStr::from_bytes(hostname)).map_err(io::Error::from)
}
#[cfg(unix)]
pub fn close_socket_ignore_connreset(socket: libc::c_int) -> io::Result<()> {
let ret = unsafe { libc::close(socket) };
if ret < 0 {
let err = io::Error::last_os_error();
if err.raw_os_error() != Some(libc::ECONNRESET) {
return Err(err);
}
}
Ok(())
}
#[cfg(unix)]
pub fn getsockopt_int(fd: libc::c_int, level: i32, name: i32) -> io::Result<i32> {
let mut flag: libc::c_int = 0;
let mut flagsize = core::mem::size_of::<libc::c_int>() as libc::socklen_t;
unsafe {
libc::getsockopt(
fd,
level,
name,
&mut flag as *mut libc::c_int as *mut _,
&mut flagsize,
)
}
.check_libc_neg()?;
Ok(flag)
}
#[cfg(unix)]
pub fn getsockopt_bytes(
fd: libc::c_int,
level: i32,
name: i32,
buflen: usize,
) -> io::Result<Vec<u8>> {
let mut buf = vec![0u8; buflen];
let mut optlen = buflen as libc::socklen_t;
unsafe { libc::getsockopt(fd, level, name, buf.as_mut_ptr() as *mut _, &mut optlen) }
.check_libc_neg()?;
buf.truncate(optlen as usize);
Ok(buf)
}
#[cfg(unix)]
pub fn setsockopt_bytes(fd: libc::c_int, level: i32, name: i32, value: &[u8]) -> io::Result<()> {
unsafe {
libc::setsockopt(
fd,
level,
name,
value.as_ptr() as *const _,
value.len() as libc::socklen_t,
)
}
.check_libc_neg()?;
Ok(())
}
#[cfg(unix)]
pub fn setsockopt_int(fd: libc::c_int, level: i32, name: i32, value: i32) -> io::Result<()> {
unsafe {
libc::setsockopt(
fd,
level,
name,
&value as *const i32 as *const _,
core::mem::size_of::<i32>() as libc::socklen_t,
)
}
.check_libc_neg()?;
Ok(())
}
#[cfg(unix)]
pub fn setsockopt_none(fd: libc::c_int, level: i32, name: i32, optlen: u32) -> io::Result<()> {
unsafe {
libc::setsockopt(
fd,
level,
name,
core::ptr::null(),
optlen as libc::socklen_t,
)
}
.check_libc_neg()?;
Ok(())
}
#[cfg(any(
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "ios",
target_os = "linux",
target_os = "macos",
target_os = "netbsd",
target_os = "openbsd",
))]
pub fn if_nameindex() -> io::Result<Vec<(u32, String)>> {
let list = nix::net::if_::if_nameindex().map_err(io::Error::from)?;
Ok(list
.to_slice()
.iter()
.map(|iface| (iface.index(), iface.name().to_string_lossy().into_owned()))
.collect())
}
#[cfg(unix)]
pub fn if_nametoindex_checked(name: &CStr) -> io::Result<u32> {
let ret = unsafe { libc::if_nametoindex(name.as_ptr()) };
if ret == 0 {
Err(io::Error::last_os_error())
} else {
Ok(ret)
}
}
#[cfg(unix)]
pub fn if_indextoname_checked(index: u32) -> io::Result<String> {
let mut buf = [0u8; libc::IF_NAMESIZE];
let ret = unsafe {
libc::if_indextoname(index as libc::c_uint, buf.as_mut_ptr() as *mut libc::c_char)
};
if ret.is_null() {
Err(io::Error::last_os_error())
} else {
let buf = unsafe { CStr::from_ptr(buf.as_ptr() as *const libc::c_char) };
Ok(buf.to_string_lossy().into_owned())
}
}
#[cfg(unix)]
pub fn gai_error_string(err: i32) -> String {
unsafe { CStr::from_ptr(libc::gai_strerror(err)) }
.to_string_lossy()
.into_owned()
}
#[cfg(unix)]
pub fn h_error_string(err: i32) -> String {
unsafe { CStr::from_ptr(libc::hstrerror(err)) }
.to_string_lossy()
.into_owned()
}
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(Debug, Clone)]
pub struct AncillaryMessage {
pub level: i32,
pub kind: i32,
pub data: Vec<u8>,
}
#[cfg(all(unix, not(target_os = "redox")))]
pub type SocketAddressBytes = [u8; core::mem::size_of::<libc::sockaddr_storage>()];
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(Debug, Clone)]
pub struct RawSocketAddress {
pub storage: SocketAddressBytes,
pub len: usize,
}
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(Debug, Clone)]
pub struct RecvMsgResult {
pub data: Vec<u8>,
pub ancdata: Vec<AncillaryMessage>,
pub msg_flags: i32,
pub address: Option<RawSocketAddress>,
}
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(Debug)]
pub struct RecvMsgIntoResult {
pub bytes_read: usize,
pub ancdata: Vec<AncillaryMessage>,
pub msg_flags: i32,
pub address: Option<RawSocketAddress>,
}
#[cfg(all(unix, not(target_os = "redox")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AncillaryPackError {
ItemTooLarge,
TooMuchData,
UnexpectedNullHeader,
}
#[cfg(all(unix, not(target_os = "redox")))]
pub fn checked_cmsg_len(len: usize) -> Option<usize> {
let cmsg_len = |length| unsafe { libc::CMSG_LEN(length) };
if len as u64 > (i32::MAX as u64 - cmsg_len(0) as u64) {
return None;
}
let res = cmsg_len(len as _) as usize;
if res > i32::MAX as usize || res < len {
return None;
}
Some(res)
}
#[cfg(all(unix, not(target_os = "redox")))]
pub fn checked_cmsg_space(len: usize) -> Option<usize> {
let cmsg_space = |length| unsafe { libc::CMSG_SPACE(length) };
if len as u64 > (i32::MAX as u64 - cmsg_space(1) as u64) {
return None;
}
let res = cmsg_space(len as _) as usize;
if res > i32::MAX as usize || res < len {
return None;
}
Some(res)
}
#[cfg(all(unix, not(target_os = "redox")))]
pub fn pack_ancillary_messages(cmsgs: &[(i32, i32, &[u8])]) -> Result<Vec<u8>, AncillaryPackError> {
use core::{mem, ptr};
if cmsgs.is_empty() {
return Ok(vec![]);
}
let capacity = cmsgs
.iter()
.map(|(_, _, buf)| buf.len())
.try_fold(0usize, |sum, len| {
let space = checked_cmsg_space(len).ok_or(AncillaryPackError::ItemTooLarge)?;
usize::checked_add(sum, space).ok_or(AncillaryPackError::TooMuchData)
})?;
let mut cmsg_buffer = vec![0u8; capacity];
let mut mhdr = unsafe { mem::zeroed::<libc::msghdr>() };
mhdr.msg_control = cmsg_buffer.as_mut_ptr().cast();
mhdr.msg_controllen = capacity as _;
let mut pmhdr: *mut libc::cmsghdr = unsafe { libc::CMSG_FIRSTHDR(&mhdr) };
for (lvl, typ, data) in cmsgs {
if pmhdr.is_null() {
return Err(AncillaryPackError::UnexpectedNullHeader);
}
let cmsg_len = checked_cmsg_len(data.len()).ok_or(AncillaryPackError::ItemTooLarge)?;
unsafe {
(*pmhdr).cmsg_level = *lvl;
(*pmhdr).cmsg_type = *typ;
(*pmhdr).cmsg_len = cmsg_len as _;
ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(pmhdr), data.len());
pmhdr = libc::CMSG_NXTHDR(&mhdr, pmhdr);
}
}
Ok(cmsg_buffer)
}
#[cfg(all(unix, not(target_os = "redox")))]
pub fn parse_ancillary_messages(control: &[u8]) -> Vec<AncillaryMessage> {
let header_size = core::mem::size_of::<libc::cmsghdr>();
let data_offset = unsafe { libc::CMSG_LEN(0) } as usize;
let mut result = Vec::new();
let mut offset = 0usize;
while let Some(remaining) = control.get(offset..) {
if remaining.len() < header_size || remaining.len() < data_offset {
break;
}
// SAFETY: A complete header is present. The input may be unaligned,
// so read the integer fields with an unaligned load.
let header = unsafe { remaining.as_ptr().cast::<libc::cmsghdr>().read_unaligned() };
#[allow(
clippy::unnecessary_cast,
reason = "cmsg_len is not usize on all platforms"
)]
let declared_len = header.cmsg_len as usize;
let Some(payload_len) = declared_len.checked_sub(data_offset) else {
break;
};
#[cfg(target_os = "hurd")]
if offset != 0
&& checked_cmsg_space(payload_len).is_none_or(|space| space > remaining.len())
{
// Hurd's CMSG_NXTHDR requires the next message to fit in full.
break;
}
let available = remaining.len() - data_offset;
let data_len = payload_len.min(available);
result.push(AncillaryMessage {
level: header.cmsg_level,
kind: header.cmsg_type,
data: remaining[data_offset..data_offset + data_len].to_vec(),
});
// A truncated final message has no complete next header.
if payload_len > available {
break;