-
Notifications
You must be signed in to change notification settings - Fork 676
/
mod.rs
2545 lines (2339 loc) · 94.2 KB
/
mod.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
//! Socket interface functions
//!
//! [Further reading](https://man7.org/linux/man-pages/man7/socket.7.html)
#[cfg(any(target_os = "freebsd", linux_android))]
#[cfg(feature = "uio")]
use crate::sys::time::TimeSpec;
#[cfg(not(target_os = "redox"))]
#[cfg(feature = "uio")]
use crate::sys::time::TimeVal;
use crate::{errno::Errno, Result};
use cfg_if::cfg_if;
use libc::{self, c_int, size_t, socklen_t};
#[cfg(all(feature = "uio", not(target_os = "redox")))]
use libc::{
c_void, iovec, CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_NXTHDR, CMSG_SPACE,
MSG_CTRUNC,
};
#[cfg(not(target_os = "redox"))]
use std::io::{IoSlice, IoSliceMut};
#[cfg(feature = "net")]
use std::net;
use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::{mem, ptr};
#[deny(missing_docs)]
mod addr;
#[deny(missing_docs)]
pub mod sockopt;
/*
*
* ===== Re-exports =====
*
*/
pub use self::addr::{SockaddrLike, SockaddrStorage};
#[cfg(solarish)]
pub use self::addr::{AddressFamily, UnixAddr};
#[cfg(not(solarish))]
pub use self::addr::{AddressFamily, UnixAddr};
#[cfg(not(any(
solarish,
target_os = "haiku",
target_os = "hurd",
target_os = "redox"
)))]
#[cfg(feature = "net")]
pub use self::addr::{LinkAddr, SockaddrIn, SockaddrIn6};
#[cfg(any(
solarish,
target_os = "haiku",
target_os = "hurd",
target_os = "redox"
))]
#[cfg(feature = "net")]
pub use self::addr::{SockaddrIn, SockaddrIn6};
#[cfg(linux_android)]
pub use crate::sys::socket::addr::alg::AlgAddr;
#[cfg(linux_android)]
pub use crate::sys::socket::addr::netlink::NetlinkAddr;
#[cfg(apple_targets)]
#[cfg(feature = "ioctl")]
pub use crate::sys::socket::addr::sys_control::SysControlAddr;
#[cfg(any(linux_android, apple_targets))]
pub use crate::sys::socket::addr::vsock::VsockAddr;
#[cfg(all(feature = "uio", not(target_os = "redox")))]
pub use libc::{cmsghdr, msghdr};
pub use libc::{sa_family_t, sockaddr, sockaddr_storage, sockaddr_un};
#[cfg(feature = "net")]
pub use libc::{sockaddr_in, sockaddr_in6};
#[cfg(feature = "net")]
use crate::sys::socket::addr::{ipv4addr_to_libc, ipv6addr_to_libc};
/// These constants are used to specify the communication semantics
/// when creating a socket with [`socket()`](fn.socket.html)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(i32)]
#[non_exhaustive]
pub enum SockType {
/// Provides sequenced, reliable, two-way, connection-
/// based byte streams. An out-of-band data transmission
/// mechanism may be supported.
Stream = libc::SOCK_STREAM,
/// Supports datagrams (connectionless, unreliable
/// messages of a fixed maximum length).
Datagram = libc::SOCK_DGRAM,
/// Provides a sequenced, reliable, two-way connection-
/// based data transmission path for datagrams of fixed
/// maximum length; a consumer is required to read an
/// entire packet with each input system call.
SeqPacket = libc::SOCK_SEQPACKET,
/// Provides raw network protocol access.
#[cfg(not(target_os = "redox"))]
Raw = libc::SOCK_RAW,
/// Provides a reliable datagram layer that does not
/// guarantee ordering.
#[cfg(not(any(target_os = "haiku", target_os = "redox")))]
Rdm = libc::SOCK_RDM,
}
// The TryFrom impl could've been derived using libc_enum!. But for
// backwards-compatibility with Nix-0.25.0 we manually implement it, so as to
// keep the old variant names.
impl TryFrom<i32> for SockType {
type Error = crate::Error;
fn try_from(x: i32) -> Result<Self> {
match x {
libc::SOCK_STREAM => Ok(Self::Stream),
libc::SOCK_DGRAM => Ok(Self::Datagram),
libc::SOCK_SEQPACKET => Ok(Self::SeqPacket),
#[cfg(not(target_os = "redox"))]
libc::SOCK_RAW => Ok(Self::Raw),
#[cfg(not(any(target_os = "haiku", target_os = "redox")))]
libc::SOCK_RDM => Ok(Self::Rdm),
_ => Err(Errno::EINVAL),
}
}
}
/// Constants used in [`socket`](fn.socket.html) and [`socketpair`](fn.socketpair.html)
/// to specify the protocol to use.
#[repr(i32)]
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SockProtocol {
/// TCP protocol ([ip(7)](https://man7.org/linux/man-pages/man7/ip.7.html))
Tcp = libc::IPPROTO_TCP,
/// UDP protocol ([ip(7)](https://man7.org/linux/man-pages/man7/ip.7.html))
Udp = libc::IPPROTO_UDP,
/// Raw sockets ([raw(7)](https://man7.org/linux/man-pages/man7/raw.7.html))
Raw = libc::IPPROTO_RAW,
/// Allows applications to configure and control a KEXT
/// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html))
#[cfg(apple_targets)]
KextControl = libc::SYSPROTO_CONTROL,
/// Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link
// parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkRoute = libc::NETLINK_ROUTE,
/// Reserved for user-mode socket protocols
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkUserSock = libc::NETLINK_USERSOCK,
/// Query information about sockets of various protocol families from the kernel
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkSockDiag = libc::NETLINK_SOCK_DIAG,
/// Netfilter/iptables ULOG.
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkNFLOG = libc::NETLINK_NFLOG,
/// SELinux event notifications.
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkSELinux = libc::NETLINK_SELINUX,
/// Open-iSCSI
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkISCSI = libc::NETLINK_ISCSI,
/// Auditing
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkAudit = libc::NETLINK_AUDIT,
/// Access to FIB lookup from user space
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkFIBLookup = libc::NETLINK_FIB_LOOKUP,
/// Netfilter subsystem
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkNetFilter = libc::NETLINK_NETFILTER,
/// SCSI Transports
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkSCSITransport = libc::NETLINK_SCSITRANSPORT,
/// Infiniband RDMA
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkRDMA = libc::NETLINK_RDMA,
/// Transport IPv6 packets from netfilter to user space. Used by ip6_queue kernel module.
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkIPv6Firewall = libc::NETLINK_IP6_FW,
/// DECnet routing messages
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkDECNetRoutingMessage = libc::NETLINK_DNRTMSG,
/// Kernel messages to user space
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkKObjectUEvent = libc::NETLINK_KOBJECT_UEVENT,
/// Generic netlink family for simplified netlink usage.
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkGeneric = libc::NETLINK_GENERIC,
/// Netlink interface to request information about ciphers registered with the kernel crypto API as well as allow
/// configuration of the kernel crypto API.
/// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html))
#[cfg(linux_android)]
NetlinkCrypto = libc::NETLINK_CRYPTO,
/// Non-DIX type protocol number defined for the Ethernet IEEE 802.3 interface that allows packets of all protocols
/// defined in the interface to be received.
/// ([ref](https://man7.org/linux/man-pages/man7/packet.7.html))
// The protocol number is fed into the socket syscall in network byte order.
#[cfg(linux_android)]
EthAll = (libc::ETH_P_ALL as u16).to_be() as i32,
/// ICMP protocol ([icmp(7)](https://man7.org/linux/man-pages/man7/icmp.7.html))
Icmp = libc::IPPROTO_ICMP,
/// ICMPv6 protocol (ICMP over IPv6)
IcmpV6 = libc::IPPROTO_ICMPV6,
/// SCTP ([sctp(7)](https://man7.org/linux/man-pages/man7/sctp.7.html))
#[cfg(any(
apple_targets,
linux_android,
target_os = "freebsd",
target_os = "netbsd"
))]
Sctp = libc::IPPROTO_SCTP,
}
impl SockProtocol {
/// The Controller Area Network raw socket protocol
/// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan))
#[cfg(target_os = "linux")]
#[allow(non_upper_case_globals)]
pub const CanRaw: SockProtocol = SockProtocol::Icmp; // Matches libc::CAN_RAW
/// The Controller Area Network broadcast manager protocol
/// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan))
#[cfg(target_os = "linux")]
#[allow(non_upper_case_globals)]
pub const CanBcm: SockProtocol = SockProtocol::NetlinkUserSock; // Matches libc::CAN_BCM
/// Allows applications and other KEXTs to be notified when certain kernel events occur
/// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html))
#[cfg(apple_targets)]
#[allow(non_upper_case_globals)]
pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT
}
#[cfg(linux_android)]
libc_bitflags! {
/// Configuration flags for `SO_TIMESTAMPING` interface
///
/// For use with [`Timestamping`][sockopt::Timestamping].
/// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html)
pub struct TimestampingFlag: libc::c_uint {
/// Report any software timestamps when available.
SOF_TIMESTAMPING_SOFTWARE;
/// Report hardware timestamps as generated by SOF_TIMESTAMPING_TX_HARDWARE when available.
SOF_TIMESTAMPING_RAW_HARDWARE;
/// Collect transmitting timestamps as reported by hardware
SOF_TIMESTAMPING_TX_HARDWARE;
/// Collect transmitting timestamps as reported by software
SOF_TIMESTAMPING_TX_SOFTWARE;
/// Collect receiving timestamps as reported by hardware
SOF_TIMESTAMPING_RX_HARDWARE;
/// Collect receiving timestamps as reported by software
SOF_TIMESTAMPING_RX_SOFTWARE;
/// Generate a unique identifier along with each transmitted packet
SOF_TIMESTAMPING_OPT_ID;
/// Return transmit timestamps alongside an empty packet instead of the original packet
SOF_TIMESTAMPING_OPT_TSONLY;
}
}
libc_bitflags! {
/// Additional socket options
pub struct SockFlag: c_int {
/// Set non-blocking mode on the new socket
#[cfg(any(linux_android,
freebsdlike,
netbsdlike,
solarish))]
SOCK_NONBLOCK;
/// Set close-on-exec on the new descriptor
#[cfg(any(linux_android,
freebsdlike,
netbsdlike,
solarish))]
SOCK_CLOEXEC;
/// Return `EPIPE` instead of raising `SIGPIPE`
#[cfg(target_os = "netbsd")]
SOCK_NOSIGPIPE;
/// For domains `AF_INET(6)`, only allow `connect(2)`, `sendto(2)`, or `sendmsg(2)`
/// to the DNS port (typically 53)
#[cfg(target_os = "openbsd")]
SOCK_DNS;
}
}
libc_bitflags! {
/// Flags for send/recv and their relatives
pub struct MsgFlags: c_int {
/// Sends or requests out-of-band data on sockets that support this notion
/// (e.g., of type [`Stream`](enum.SockType.html)); the underlying protocol must also
/// support out-of-band data.
MSG_OOB;
/// Peeks at an incoming message. The data is treated as unread and the next
/// [`recv()`](fn.recv.html)
/// or similar function shall still return this data.
MSG_PEEK;
/// Receive operation blocks until the full amount of data can be
/// returned. The function may return smaller amount of data if a signal
/// is caught, an error or disconnect occurs.
MSG_WAITALL;
/// Enables nonblocking operation; if the operation would block,
/// `EAGAIN` or `EWOULDBLOCK` is returned. This provides similar
/// behavior to setting the `O_NONBLOCK` flag
/// (via the [`fcntl`](../../fcntl/fn.fcntl.html)
/// `F_SETFL` operation), but differs in that `MSG_DONTWAIT` is a per-
/// call option, whereas `O_NONBLOCK` is a setting on the open file
/// description (see [open(2)](https://man7.org/linux/man-pages/man2/open.2.html)),
/// which will affect all threads in
/// the calling process and as well as other processes that hold
/// file descriptors referring to the same open file description.
#[cfg(not(target_os = "aix"))]
MSG_DONTWAIT;
/// Receive flags: Control Data was discarded (buffer too small)
MSG_CTRUNC;
/// For raw ([`Packet`](addr/enum.AddressFamily.html)), Internet datagram
/// (since Linux 2.4.27/2.6.8),
/// netlink (since Linux 2.6.22) and UNIX datagram (since Linux 3.4)
/// sockets: return the real length of the packet or datagram, even
/// when it was longer than the passed buffer. Not implemented for UNIX
/// domain ([unix(7)](https://linux.die.net/man/7/unix)) sockets.
///
/// For use with Internet stream sockets, see [tcp(7)](https://linux.die.net/man/7/tcp).
MSG_TRUNC;
/// Terminates a record (when this notion is supported, as for
/// sockets of type [`SeqPacket`](enum.SockType.html)).
MSG_EOR;
/// This flag specifies that queued errors should be received from
/// the socket error queue. (For more details, see
/// [recvfrom(2)](https://linux.die.net/man/2/recvfrom))
#[cfg(linux_android)]
MSG_ERRQUEUE;
/// Set the `close-on-exec` flag for the file descriptor received via a UNIX domain
/// file descriptor using the `SCM_RIGHTS` operation (described in
/// [unix(7)](https://linux.die.net/man/7/unix)).
/// This flag is useful for the same reasons as the `O_CLOEXEC` flag of
/// [open(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html).
///
/// Only used in [`recvmsg`](fn.recvmsg.html) function.
#[cfg(any(linux_android, freebsdlike, netbsdlike))]
MSG_CMSG_CLOEXEC;
/// Requests not to send `SIGPIPE` errors when the other end breaks the connection.
/// (For more details, see [send(2)](https://linux.die.net/man/2/send)).
#[cfg(any(linux_android,
freebsdlike,
solarish,
netbsdlike,
target_os = "fuchsia",
target_os = "haiku"))]
MSG_NOSIGNAL;
/// Turns on [`MSG_DONTWAIT`] after the first message has been received (only for
/// `recvmmsg()`).
#[cfg(any(linux_android,
netbsdlike,
target_os = "fuchsia",
target_os = "freebsd"))]
MSG_WAITFORONE;
/// Indicates that this message is not a user message but an SCTP notification.
#[cfg(target_os = "linux")]
MSG_NOTIFICATION;
}
}
#[cfg(target_os = "freebsd")]
libc_enum! {
/// A selector for which clock to use when generating packet timestamps.
/// Used when setting [`TsClock`](crate::sys::socket::sockopt::TsClock) on a socket.
/// (For more details, see [setsockopt(2)](https://man.freebsd.org/cgi/man.cgi?setsockopt)).
#[repr(i32)]
#[non_exhaustive]
pub enum SocketTimestamp {
/// Microsecond resolution, realtime. This is the default.
SO_TS_REALTIME_MICRO,
/// Sub-nanosecond resolution, realtime.
SO_TS_BINTIME,
/// Nanosecond resolution, realtime.
SO_TS_REALTIME,
/// Nanosecond resolution, monotonic.
SO_TS_MONOTONIC,
}
}
cfg_if! {
if #[cfg(linux_android)] {
/// Unix credentials of the sending process.
///
/// This struct is used with the `SO_PEERCRED` ancillary message
/// and the `SCM_CREDENTIALS` control message for UNIX sockets.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UnixCredentials(libc::ucred);
impl UnixCredentials {
/// Creates a new instance with the credentials of the current process
pub fn new() -> Self {
// Safe because these FFI functions are inherently safe
unsafe {
UnixCredentials(libc::ucred {
pid: libc::getpid(),
uid: libc::getuid(),
gid: libc::getgid()
})
}
}
/// Returns the process identifier
pub fn pid(&self) -> libc::pid_t {
self.0.pid
}
/// Returns the user identifier
pub fn uid(&self) -> libc::uid_t {
self.0.uid
}
/// Returns the group identifier
pub fn gid(&self) -> libc::gid_t {
self.0.gid
}
}
impl Default for UnixCredentials {
fn default() -> Self {
Self::new()
}
}
impl From<libc::ucred> for UnixCredentials {
fn from(cred: libc::ucred) -> Self {
UnixCredentials(cred)
}
}
impl From<UnixCredentials> for libc::ucred {
fn from(uc: UnixCredentials) -> Self {
uc.0
}
}
} else if #[cfg(freebsdlike)] {
/// Unix credentials of the sending process.
///
/// This struct is used with the `SCM_CREDS` ancillary message for UNIX sockets.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct UnixCredentials(libc::cmsgcred);
impl UnixCredentials {
/// Returns the process identifier
pub fn pid(&self) -> libc::pid_t {
self.0.cmcred_pid
}
/// Returns the real user identifier
pub fn uid(&self) -> libc::uid_t {
self.0.cmcred_uid
}
/// Returns the effective user identifier
pub fn euid(&self) -> libc::uid_t {
self.0.cmcred_euid
}
/// Returns the real group identifier
pub fn gid(&self) -> libc::gid_t {
self.0.cmcred_gid
}
/// Returns a list group identifiers (the first one being the effective GID)
pub fn groups(&self) -> &[libc::gid_t] {
unsafe {
std::slice::from_raw_parts(
self.0.cmcred_groups.as_ptr(),
self.0.cmcred_ngroups as _
)
}
}
}
impl From<libc::cmsgcred> for UnixCredentials {
fn from(cred: libc::cmsgcred) -> Self {
UnixCredentials(cred)
}
}
}
}
cfg_if! {
if #[cfg(any(freebsdlike, apple_targets))] {
/// Return type of [`LocalPeerCred`](crate::sys::socket::sockopt::LocalPeerCred)
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct XuCred(libc::xucred);
impl XuCred {
/// Structure layout version
pub fn version(&self) -> u32 {
self.0.cr_version
}
/// Effective user ID
pub fn uid(&self) -> libc::uid_t {
self.0.cr_uid
}
/// Returns a list of group identifiers (the first one being the
/// effective GID)
pub fn groups(&self) -> &[libc::gid_t] {
&self.0.cr_groups
}
}
}
}
cfg_if! {
if #[cfg(apple_targets)] {
use std::fmt;
/// Return type of [`LocalPeerToken`].
///
/// The audit token is an opaque token which identifies Mach tasks and
/// senders of Mach messages as subjects to the BSM audit system. Only
/// the appropriate BSM library routines should be used to interpret
/// the contents of the audit token as the representation of the
/// subject identity within the token may change over time.
///
/// Starting with macOS 11, almost all audit functions have been
/// deprecated (see the system header `bsm/libbsm.h`), do not use them
/// if your program target more recent versions of macOS.
///
/// [`LocalPeerToken`]: crate::sys::socket::sockopt::LocalPeerToken
#[repr(C)]
#[derive(Default, Copy, Clone, PartialEq, Eq, Hash)]
pub struct audit_token_t {
/// Value of the token.
///
/// This is considered an opaque value, do not rely on its format.
pub val: [libc::c_uint; 8],
}
// Make the debug representation a hex string to make it shorter and clearer.
impl fmt::Debug for audit_token_t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("audit_token_t")
.field(&format!("0x{:08X}", self))
.finish()
}
}
impl fmt::LowerHex for audit_token_t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for v in self.val {
fmt::LowerHex::fmt(&v, f)?;
}
Ok(())
}
}
impl fmt::UpperHex for audit_token_t {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for v in self.val {
fmt::UpperHex::fmt(&v, f)?;
}
Ok(())
}
}
}
}
feature! {
#![feature = "net"]
/// Request for multicast socket operations
///
/// This is a wrapper type around `ip_mreq`.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IpMembershipRequest(libc::ip_mreq);
impl IpMembershipRequest {
/// Instantiate a new `IpMembershipRequest`
///
/// If `interface` is `None`, then `Ipv4Addr::any()` will be used for the interface.
pub fn new(group: net::Ipv4Addr, interface: Option<net::Ipv4Addr>)
-> Self
{
let imr_addr = match interface {
None => net::Ipv4Addr::UNSPECIFIED,
Some(addr) => addr
};
IpMembershipRequest(libc::ip_mreq {
imr_multiaddr: ipv4addr_to_libc(group),
imr_interface: ipv4addr_to_libc(imr_addr)
})
}
}
/// Request for ipv6 multicast socket operations
///
/// This is a wrapper type around `ipv6_mreq`.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Ipv6MembershipRequest(libc::ipv6_mreq);
impl Ipv6MembershipRequest {
/// Instantiate a new `Ipv6MembershipRequest`
pub const fn new(group: net::Ipv6Addr) -> Self {
Ipv6MembershipRequest(libc::ipv6_mreq {
ipv6mr_multiaddr: ipv6addr_to_libc(&group),
ipv6mr_interface: 0,
})
}
}
}
#[cfg(not(target_os = "redox"))]
feature! {
#![feature = "uio"]
/// Create a buffer large enough for storing some control messages as returned
/// by [`recvmsg`](fn.recvmsg.html).
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate nix;
/// # use nix::sys::time::TimeVal;
/// # use std::os::unix::io::RawFd;
/// # fn main() {
/// // Create a buffer for a `ControlMessageOwned::ScmTimestamp` message
/// let _ = cmsg_space!(TimeVal);
/// // Create a buffer big enough for a `ControlMessageOwned::ScmRights` message
/// // with two file descriptors
/// let _ = cmsg_space!([RawFd; 2]);
/// // Create a buffer big enough for a `ControlMessageOwned::ScmRights` message
/// // and a `ControlMessageOwned::ScmTimestamp` message
/// let _ = cmsg_space!(RawFd, TimeVal);
/// # }
/// ```
#[macro_export]
macro_rules! cmsg_space {
( $( $x:ty ),* ) => {
{
let space = 0 $(+ $crate::sys::socket::cmsg_space::<$x>())*;
vec![0u8; space]
}
}
}
#[inline]
#[doc(hidden)]
pub const fn cmsg_space<T>() -> usize {
// SAFETY: CMSG_SPACE is always safe
unsafe { libc::CMSG_SPACE(mem::size_of::<T>() as libc::c_uint) as usize }
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// Contains outcome of sending or receiving a message
///
/// Use [`cmsgs`][RecvMsg::cmsgs] to access all the control messages present, and
/// [`iovs`][RecvMsg::iovs`] to access underlying io slices.
pub struct RecvMsg<'a, 's, S> {
pub bytes: usize,
cmsghdr: Option<&'a cmsghdr>,
pub address: Option<S>,
pub flags: MsgFlags,
iobufs: std::marker::PhantomData<& 's()>,
mhdr: msghdr,
}
impl<S> RecvMsg<'_, '_, S> {
/// Iterate over the valid control messages pointed to by this msghdr. If
/// allocated space for CMSGs was too small it is not safe to iterate,
/// instead return an `Error::ENOBUFS` error.
pub fn cmsgs(&self) -> Result<CmsgIterator> {
if self.mhdr.msg_flags & MSG_CTRUNC == MSG_CTRUNC {
return Err(Errno::ENOBUFS);
}
Ok(CmsgIterator {
cmsghdr: self.cmsghdr,
mhdr: &self.mhdr
})
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CmsgIterator<'a> {
/// Control message buffer to decode from. Must adhere to cmsg alignment.
cmsghdr: Option<&'a cmsghdr>,
mhdr: &'a msghdr
}
impl Iterator for CmsgIterator<'_> {
type Item = ControlMessageOwned;
fn next(&mut self) -> Option<ControlMessageOwned> {
match self.cmsghdr {
None => None, // No more messages
Some(hdr) => {
// Get the data.
// Safe if cmsghdr points to valid data returned by recvmsg(2)
let cm = unsafe { Some(ControlMessageOwned::decode_from(hdr))};
// Advance the internal pointer. Safe if mhdr and cmsghdr point
// to valid data returned by recvmsg(2)
self.cmsghdr = unsafe {
let p = CMSG_NXTHDR(self.mhdr as *const _, hdr as *const _);
p.as_ref()
};
cm
}
}
}
}
/// A type-safe wrapper around a single control message, as used with
/// [`recvmsg`].
///
/// [Further reading](https://man7.org/linux/man-pages/man3/cmsg.3.html)
// Nix version 0.13.0 and earlier used ControlMessage for both recvmsg and
// sendmsg. However, on some platforms the messages returned by recvmsg may be
// unaligned. ControlMessageOwned takes those messages by copy, obviating any
// alignment issues.
//
// See https://github.com/nix-rust/nix/issues/999
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ControlMessageOwned {
/// Received version of [`ControlMessage::ScmRights`]
ScmRights(Vec<RawFd>),
/// Received version of [`ControlMessage::ScmCredentials`]
#[cfg(linux_android)]
ScmCredentials(UnixCredentials),
/// Received version of [`ControlMessage::ScmCreds`]
#[cfg(freebsdlike)]
ScmCreds(UnixCredentials),
/// A message of type `SCM_TIMESTAMP`, containing the time the
/// packet was received by the kernel.
///
/// See the kernel's explanation in "SO_TIMESTAMP" of
/// [networking/timestamping](https://www.kernel.org/doc/Documentation/networking/timestamping.txt).
///
/// # Examples
///
/// ```
/// # #[macro_use] extern crate nix;
/// # use nix::sys::socket::*;
/// # use nix::sys::time::*;
/// # use std::io::{IoSlice, IoSliceMut};
/// # use std::time::*;
/// # use std::str::FromStr;
/// # use std::os::unix::io::AsRawFd;
/// # fn main() {
/// // Set up
/// let message = "Ohayō!".as_bytes();
/// let in_socket = socket(
/// AddressFamily::Inet,
/// SockType::Datagram,
/// SockFlag::empty(),
/// None).unwrap();
/// setsockopt(&in_socket, sockopt::ReceiveTimestamp, &true).unwrap();
/// let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap();
/// bind(in_socket.as_raw_fd(), &localhost).unwrap();
/// let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap();
/// // Get initial time
/// let time0 = SystemTime::now();
/// // Send the message
/// let iov = [IoSlice::new(message)];
/// let flags = MsgFlags::empty();
/// let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address)).unwrap();
/// assert_eq!(message.len(), l);
/// // Receive the message
/// let mut buffer = vec![0u8; message.len()];
/// let mut cmsgspace = cmsg_space!(TimeVal);
/// let mut iov = [IoSliceMut::new(&mut buffer)];
/// let r = recvmsg::<SockaddrIn>(in_socket.as_raw_fd(), &mut iov, Some(&mut cmsgspace), flags)
/// .unwrap();
/// let rtime = match r.cmsgs().unwrap().next() {
/// Some(ControlMessageOwned::ScmTimestamp(rtime)) => rtime,
/// Some(_) => panic!("Unexpected control message"),
/// None => panic!("No control message")
/// };
/// // Check the final time
/// let time1 = SystemTime::now();
/// // the packet's received timestamp should lie in-between the two system
/// // times, unless the system clock was adjusted in the meantime.
/// let rduration = Duration::new(rtime.tv_sec() as u64,
/// rtime.tv_usec() as u32 * 1000);
/// assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration);
/// assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap());
/// // Close socket
/// # }
/// ```
ScmTimestamp(TimeVal),
/// A set of nanosecond resolution timestamps
///
/// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html)
#[cfg(linux_android)]
ScmTimestampsns(Timestamps),
/// Nanoseconds resolution timestamp
///
/// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html)
#[cfg(linux_android)]
ScmTimestampns(TimeSpec),
/// Realtime clock timestamp
///
/// [Further reading](https://man.freebsd.org/cgi/man.cgi?setsockopt)
#[cfg(target_os = "freebsd")]
ScmRealtime(TimeSpec),
/// Monotonic clock timestamp
///
/// [Further reading](https://man.freebsd.org/cgi/man.cgi?setsockopt)
#[cfg(target_os = "freebsd")]
ScmMonotonic(TimeSpec),
#[cfg(any(linux_android, apple_targets, target_os = "netbsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4PacketInfo(libc::in_pktinfo),
#[cfg(any(linux_android, bsd))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv6PacketInfo(libc::in6_pktinfo),
#[cfg(bsd)]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4RecvIf(libc::sockaddr_dl),
#[cfg(bsd)]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4RecvDstAddr(libc::in_addr),
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4OrigDstAddr(libc::sockaddr_in),
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv6OrigDstAddr(libc::sockaddr_in6),
/// Time-to-Live (TTL) header field of the incoming IPv4 packet.
///
/// [Further reading](https://www.man7.org/linux/man-pages/man7/ip.7.html)
#[cfg(linux_android)]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4Ttl(i32),
/// Time-to-Live (TTL) header field of the incoming IPv4 packet.
///
/// [Further reading](https://datatracker.ietf.org/doc/html/rfc3542.html)
#[cfg(target_os = "freebsd")]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4Ttl(u8),
/// Hop Limit header field of the incoming IPv6 packet.
///
/// [Further reading for Linux](https://www.man7.org/linux/man-pages/man7/ip.7.html)
/// [Further reading for FreeBSD](https://datatracker.ietf.org/doc/html/rfc3542.html)
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv6HopLimit(i32),
/// Retrieve the DSCP (ToS) header field of the incoming IPv4 packet.
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4Tos(u8),
/// Retrieve the DSCP (Traffic Class) header field of the incoming IPv6 packet.
#[cfg(any(linux_android, target_os = "freebsd"))]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv6TClass(i32),
/// UDP Generic Receive Offload (GRO) allows receiving multiple UDP
/// packets from a single sender.
/// Fixed-size payloads are following one by one in a receive buffer.
/// This Control Message indicates the size of all smaller packets,
/// except, maybe, the last one.
///
/// `UdpGroSegment` socket option should be enabled on a socket
/// to allow receiving GRO packets.
#[cfg(target_os = "linux")]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
UdpGroSegments(i32),
/// SO_RXQ_OVFL indicates that an unsigned 32 bit value
/// ancilliary msg (cmsg) should be attached to recieved
/// skbs indicating the number of packets dropped by the
/// socket between the last recieved packet and this
/// received packet.
///
/// `RxqOvfl` socket option should be enabled on a socket
/// to allow receiving the drop counter.
#[cfg(any(linux_android, target_os = "fuchsia"))]
RxqOvfl(u32),
/// Socket error queue control messages read with the `MSG_ERRQUEUE` flag.
#[cfg(linux_android)]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv4RecvErr(libc::sock_extended_err, Option<sockaddr_in>),
/// Socket error queue control messages read with the `MSG_ERRQUEUE` flag.
#[cfg(linux_android)]
#[cfg(feature = "net")]
#[cfg_attr(docsrs, doc(cfg(feature = "net")))]
Ipv6RecvErr(libc::sock_extended_err, Option<sockaddr_in6>),
/// `SOL_TLS` messages of type `TLS_GET_RECORD_TYPE`
#[cfg(any(target_os = "linux"))]
TlsGetRecordType(TlsGetRecordType),
/// Catch-all variant for unimplemented cmsg types.
Unknown(UnknownCmsg),
}
/// For representing packet timestamps via `SO_TIMESTAMPING` interface
#[cfg(linux_android)]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Timestamps {
/// software based timestamp, usually one containing data
pub system: TimeSpec,
/// legacy timestamp, usually empty
pub hw_trans: TimeSpec,
/// hardware based timestamp
pub hw_raw: TimeSpec,
}
/// These constants correspond to TLS 1.2 message types, as defined in
/// RFC 5246, Appendix A.1
#[cfg(any(target_os = "linux"))]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
#[non_exhaustive]
pub enum TlsGetRecordType {
ChangeCipherSpec ,
Alert,
Handshake,
ApplicationData,
Unknown(u8),
}
#[cfg(any(target_os = "linux"))]
impl From<u8> for TlsGetRecordType {
fn from(x: u8) -> Self {
match x {
20 => TlsGetRecordType::ChangeCipherSpec,
21 => TlsGetRecordType::Alert,
22 => TlsGetRecordType::Handshake,
23 => TlsGetRecordType::ApplicationData,
_ => TlsGetRecordType::Unknown(x),
}
}
}
impl ControlMessageOwned {
/// Decodes a `ControlMessageOwned` from raw bytes.
///
/// This is only safe to call if the data is correct for the message type
/// specified in the header. Normally, the kernel ensures that this is the
/// case. "Correct" in this case includes correct length, alignment and
/// actual content.
// Clippy complains about the pointer alignment of `p`, not understanding
// that it's being fed to a function that can handle that.
#[allow(clippy::cast_ptr_alignment)]
unsafe fn decode_from(header: &cmsghdr) -> ControlMessageOwned
{
let p = unsafe { CMSG_DATA(header) };
// The cast is not unnecessary on all platforms.
#[allow(clippy::unnecessary_cast)]
let len = header as *const _ as usize + header.cmsg_len as usize
- p as usize;
match (header.cmsg_level, header.cmsg_type) {
(libc::SOL_SOCKET, libc::SCM_RIGHTS) => {
let n = len / mem::size_of::<RawFd>();
let mut fds = Vec::with_capacity(n);
for i in 0..n {
unsafe {
let fdp = (p as *const RawFd).add(i);
fds.push(ptr::read_unaligned(fdp));
}
}
ControlMessageOwned::ScmRights(fds)
},
#[cfg(linux_android)]
(libc::SOL_SOCKET, libc::SCM_CREDENTIALS) => {
let cred: libc::ucred = unsafe { ptr::read_unaligned(p as *const _) };