-
Notifications
You must be signed in to change notification settings - Fork 230
/
socket.rs
2183 lines (2047 loc) · 77.3 KB
/
socket.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
// Copyright 2015 The Rust Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::fmt;
use std::io::{self, Read, Write};
#[cfg(not(target_os = "redox"))]
use std::io::{IoSlice, IoSliceMut};
use std::mem::MaybeUninit;
#[cfg(not(target_os = "nto"))]
use std::net::Ipv6Addr;
use std::net::{self, Ipv4Addr, Shutdown};
#[cfg(unix)]
use std::os::unix::io::{FromRawFd, IntoRawFd};
#[cfg(windows)]
use std::os::windows::io::{FromRawSocket, IntoRawSocket};
use std::time::Duration;
use crate::sys::{self, c_int, getsockopt, setsockopt, Bool};
#[cfg(all(unix, not(target_os = "redox")))]
use crate::MsgHdrMut;
use crate::{Domain, Protocol, SockAddr, TcpKeepalive, Type};
#[cfg(not(target_os = "redox"))]
use crate::{MaybeUninitSlice, MsgHdr, RecvFlags};
/// Owned wrapper around a system socket.
///
/// This type simply wraps an instance of a file descriptor (`c_int`) on Unix
/// and an instance of `SOCKET` on Windows. This is the main type exported by
/// this crate and is intended to mirror the raw semantics of sockets on
/// platforms as closely as possible. Almost all methods correspond to
/// precisely one libc or OS API call which is essentially just a "Rustic
/// translation" of what's below.
///
/// ## Converting to and from other types
///
/// This type can be freely converted into the network primitives provided by
/// the standard library, such as [`TcpStream`] or [`UdpSocket`], using the
/// [`From`] trait, see the example below.
///
/// [`TcpStream`]: std::net::TcpStream
/// [`UdpSocket`]: std::net::UdpSocket
///
/// # Notes
///
/// Some methods that set options on `Socket` require two system calls to set
/// their options without overwriting previously set options. We do this by
/// first getting the current settings, applying the desired changes, and then
/// updating the settings. This means that the operation is **not** atomic. This
/// can lead to a data race when two threads are changing options in parallel.
///
/// # Examples
/// ```no_run
/// # fn main() -> std::io::Result<()> {
/// use std::net::{SocketAddr, TcpListener};
/// use socket2::{Socket, Domain, Type};
///
/// // create a TCP listener
/// let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
///
/// let address: SocketAddr = "[::1]:12345".parse().unwrap();
/// let address = address.into();
/// socket.bind(&address)?;
/// socket.listen(128)?;
///
/// let listener: TcpListener = socket.into();
/// // ...
/// # drop(listener);
/// # Ok(()) }
/// ```
pub struct Socket {
inner: Inner,
}
/// Store a `TcpStream` internally to take advantage of its niche optimizations on Unix platforms.
pub(crate) type Inner = std::net::TcpStream;
impl Socket {
/// # Safety
///
/// The caller must ensure `raw` is a valid file descriptor/socket. NOTE:
/// this should really be marked `unsafe`, but this being an internal
/// function, often passed as mapping function, it's makes it very
/// inconvenient to mark it as `unsafe`.
pub(crate) fn from_raw(raw: sys::Socket) -> Socket {
Socket {
inner: unsafe {
// SAFETY: the caller must ensure that `raw` is a valid file
// descriptor, but when it isn't it could return I/O errors, or
// potentially close a fd it doesn't own. All of that isn't
// memory unsafe, so it's not desired but never memory unsafe or
// causes UB.
//
// However there is one exception. We use `TcpStream` to
// represent the `Socket` internally (see `Inner` type),
// `TcpStream` has a layout optimisation that doesn't allow for
// negative file descriptors (as those are always invalid).
// Violating this assumption (fd never negative) causes UB,
// something we don't want. So check for that we have this
// `assert!`.
#[cfg(unix)]
assert!(raw >= 0, "tried to create a `Socket` with an invalid fd");
sys::socket_from_raw(raw)
},
}
}
pub(crate) fn as_raw(&self) -> sys::Socket {
sys::socket_as_raw(&self.inner)
}
pub(crate) fn into_raw(self) -> sys::Socket {
sys::socket_into_raw(self.inner)
}
/// Creates a new socket and sets common flags.
///
/// This function corresponds to `socket(2)` on Unix and `WSASocketW` on
/// Windows.
///
/// On Unix-like systems, the close-on-exec flag is set on the new socket.
/// Additionally, on Apple platforms `SOCK_NOSIGPIPE` is set. On Windows,
/// the socket is made non-inheritable.
///
/// [`Socket::new_raw`] can be used if you don't want these flags to be set.
#[doc = man_links!(socket(2))]
pub fn new(domain: Domain, ty: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
let ty = set_common_type(ty);
Socket::new_raw(domain, ty, protocol).and_then(set_common_flags)
}
/// Creates a new socket ready to be configured.
///
/// This function corresponds to `socket(2)` on Unix and `WSASocketW` on
/// Windows and simply creates a new socket, no other configuration is done.
pub fn new_raw(domain: Domain, ty: Type, protocol: Option<Protocol>) -> io::Result<Socket> {
let protocol = protocol.map_or(0, |p| p.0);
sys::socket(domain.0, ty.0, protocol).map(Socket::from_raw)
}
/// Creates a pair of sockets which are connected to each other.
///
/// This function corresponds to `socketpair(2)`.
///
/// This function sets the same flags as in done for [`Socket::new`],
/// [`Socket::pair_raw`] can be used if you don't want to set those flags.
#[doc = man_links!(unix: socketpair(2))]
#[cfg(all(feature = "all", unix))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
pub fn pair(
domain: Domain,
ty: Type,
protocol: Option<Protocol>,
) -> io::Result<(Socket, Socket)> {
let ty = set_common_type(ty);
let (a, b) = Socket::pair_raw(domain, ty, protocol)?;
let a = set_common_flags(a)?;
let b = set_common_flags(b)?;
Ok((a, b))
}
/// Creates a pair of sockets which are connected to each other.
///
/// This function corresponds to `socketpair(2)`.
#[cfg(all(feature = "all", unix))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
pub fn pair_raw(
domain: Domain,
ty: Type,
protocol: Option<Protocol>,
) -> io::Result<(Socket, Socket)> {
let protocol = protocol.map_or(0, |p| p.0);
sys::socketpair(domain.0, ty.0, protocol)
.map(|[a, b]| (Socket::from_raw(a), Socket::from_raw(b)))
}
/// Binds this socket to the specified address.
///
/// This function directly corresponds to the `bind(2)` function on Windows
/// and Unix.
#[doc = man_links!(bind(2))]
pub fn bind(&self, address: &SockAddr) -> io::Result<()> {
sys::bind(self.as_raw(), address)
}
/// Initiate a connection on this socket to the specified address.
///
/// This function directly corresponds to the `connect(2)` function on
/// Windows and Unix.
///
/// An error will be returned if `listen` or `connect` has already been
/// called on this builder.
#[doc = man_links!(connect(2))]
///
/// # Notes
///
/// When using a non-blocking connect (by setting the socket into
/// non-blocking mode before calling this function), socket option can't be
/// set *while connecting*. This will cause errors on Windows. Socket
/// options can be safely set before and after connecting the socket.
pub fn connect(&self, address: &SockAddr) -> io::Result<()> {
sys::connect(self.as_raw(), address)
}
/// Initiate a connection on this socket to the specified address, only
/// only waiting for a certain period of time for the connection to be
/// established.
///
/// Unlike many other methods on `Socket`, this does *not* correspond to a
/// single C function. It sets the socket to nonblocking mode, connects via
/// connect(2), and then waits for the connection to complete with poll(2)
/// on Unix and select on Windows. When the connection is complete, the
/// socket is set back to blocking mode. On Unix, this will loop over
/// `EINTR` errors.
///
/// # Warnings
///
/// The non-blocking state of the socket is overridden by this function -
/// it will be returned in blocking mode on success, and in an indeterminate
/// state on failure.
///
/// If the connection request times out, it may still be processing in the
/// background - a second call to `connect` or `connect_timeout` may fail.
pub fn connect_timeout(&self, addr: &SockAddr, timeout: Duration) -> io::Result<()> {
self.set_nonblocking(true)?;
let res = self.connect(addr);
self.set_nonblocking(false)?;
match res {
Ok(()) => return Ok(()),
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {}
#[cfg(unix)]
Err(ref e) if e.raw_os_error() == Some(libc::EINPROGRESS) => {}
Err(e) => return Err(e),
}
sys::poll_connect(self, timeout)
}
/// Mark a socket as ready to accept incoming connection requests using
/// [`Socket::accept()`].
///
/// This function directly corresponds to the `listen(2)` function on
/// Windows and Unix.
///
/// An error will be returned if `listen` or `connect` has already been
/// called on this builder.
#[doc = man_links!(listen(2))]
pub fn listen(&self, backlog: c_int) -> io::Result<()> {
sys::listen(self.as_raw(), backlog)
}
/// Accept a new incoming connection from this listener.
///
/// This function uses `accept4(2)` on platforms that support it and
/// `accept(2)` platforms that do not.
///
/// This function sets the same flags as in done for [`Socket::new`],
/// [`Socket::accept_raw`] can be used if you don't want to set those flags.
#[doc = man_links!(accept(2))]
pub fn accept(&self) -> io::Result<(Socket, SockAddr)> {
// Use `accept4` on platforms that support it.
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
))]
return self._accept4(libc::SOCK_CLOEXEC);
// Fall back to `accept` on platforms that do not support `accept4`.
#[cfg(not(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
)))]
{
let (socket, addr) = self.accept_raw()?;
let socket = set_common_flags(socket)?;
// `set_common_flags` does not disable inheritance on Windows because `Socket::new`
// unlike `accept` is able to create the socket with inheritance disabled.
#[cfg(windows)]
socket._set_no_inherit(true)?;
Ok((socket, addr))
}
}
/// Accept a new incoming connection from this listener.
///
/// This function directly corresponds to the `accept(2)` function on
/// Windows and Unix.
pub fn accept_raw(&self) -> io::Result<(Socket, SockAddr)> {
sys::accept(self.as_raw()).map(|(inner, addr)| (Socket::from_raw(inner), addr))
}
/// Returns the socket address of the local half of this socket.
///
/// This function directly corresponds to the `getsockname(2)` function on
/// Windows and Unix.
#[doc = man_links!(getsockname(2))]
///
/// # Notes
///
/// Depending on the OS this may return an error if the socket is not
/// [bound].
///
/// [bound]: Socket::bind
pub fn local_addr(&self) -> io::Result<SockAddr> {
sys::getsockname(self.as_raw())
}
/// Returns the socket address of the remote peer of this socket.
///
/// This function directly corresponds to the `getpeername(2)` function on
/// Windows and Unix.
#[doc = man_links!(getpeername(2))]
///
/// # Notes
///
/// This returns an error if the socket is not [`connect`ed].
///
/// [`connect`ed]: Socket::connect
pub fn peer_addr(&self) -> io::Result<SockAddr> {
sys::getpeername(self.as_raw())
}
/// Returns the [`Type`] of this socket by checking the `SO_TYPE` option on
/// this socket.
pub fn r#type(&self) -> io::Result<Type> {
unsafe { getsockopt::<c_int>(self.as_raw(), sys::SOL_SOCKET, sys::SO_TYPE).map(Type) }
}
/// Creates a new independently owned handle to the underlying socket.
///
/// # Notes
///
/// On Unix this uses `F_DUPFD_CLOEXEC` and thus sets the `FD_CLOEXEC` on
/// the returned socket.
///
/// On Windows this uses `WSA_FLAG_NO_HANDLE_INHERIT` setting inheriting to
/// false.
///
/// On Windows this can **not** be used function cannot be used on a
/// QOS-enabled socket, see
/// <https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaduplicatesocketw>.
pub fn try_clone(&self) -> io::Result<Socket> {
sys::try_clone(self.as_raw()).map(Socket::from_raw)
}
/// Returns true if this socket is set to nonblocking mode, false otherwise.
///
/// # Notes
///
/// On Unix this corresponds to calling `fcntl` returning the value of
/// `O_NONBLOCK`.
///
/// On Windows it is not possible retrieve the nonblocking mode status.
#[cfg(all(feature = "all", unix))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "all", unix))))]
pub fn nonblocking(&self) -> io::Result<bool> {
sys::nonblocking(self.as_raw())
}
/// Moves this socket into or out of nonblocking mode.
///
/// # Notes
///
/// On Unix this corresponds to calling `fcntl` (un)setting `O_NONBLOCK`.
///
/// On Windows this corresponds to calling `ioctlsocket` (un)setting
/// `FIONBIO`.
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
sys::set_nonblocking(self.as_raw(), nonblocking)
}
/// Shuts down the read, write, or both halves of this connection.
///
/// This function will cause all pending and future I/O on the specified
/// portions to return immediately with an appropriate value.
#[doc = man_links!(shutdown(2))]
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
sys::shutdown(self.as_raw(), how)
}
/// Receives data on the socket from the remote address to which it is
/// connected.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method might fail if the socket is not connected.
#[doc = man_links!(recv(2))]
///
/// [`connect`]: Socket::connect
///
/// # Safety
///
/// Normally casting a `&mut [u8]` to `&mut [MaybeUninit<u8>]` would be
/// unsound, as that allows us to write uninitialised bytes to the buffer.
/// However this implementation promises to not write uninitialised bytes to
/// the `buf`fer and passes it directly to `recv(2)` system call. This
/// promise ensures that this function can be called using a `buf`fer of
/// type `&mut [u8]`.
///
/// Note that the [`io::Read::read`] implementation calls this function with
/// a `buf`fer of type `&mut [u8]`, allowing initialised buffers to be used
/// without using `unsafe`.
pub fn recv(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
self.recv_with_flags(buf, 0)
}
/// Receives out-of-band (OOB) data on the socket from the remote address to
/// which it is connected by setting the `MSG_OOB` flag for this call.
///
/// For more information, see [`recv`], [`out_of_band_inline`].
///
/// [`recv`]: Socket::recv
/// [`out_of_band_inline`]: Socket::out_of_band_inline
#[cfg_attr(target_os = "redox", allow(rustdoc::broken_intra_doc_links))]
pub fn recv_out_of_band(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
self.recv_with_flags(buf, sys::MSG_OOB)
}
/// Identical to [`recv`] but allows for specification of arbitrary flags to
/// the underlying `recv` call.
///
/// [`recv`]: Socket::recv
pub fn recv_with_flags(
&self,
buf: &mut [MaybeUninit<u8>],
flags: sys::c_int,
) -> io::Result<usize> {
sys::recv(self.as_raw(), buf, flags)
}
/// Receives data on the socket from the remote address to which it is
/// connected. Unlike [`recv`] this allows passing multiple buffers.
///
/// The [`connect`] method will connect this socket to a remote address.
/// This method might fail if the socket is not connected.
///
/// In addition to the number of bytes read, this function returns the flags
/// for the received message. See [`RecvFlags`] for more information about
/// the returned flags.
#[doc = man_links!(recvmsg(2))]
///
/// [`recv`]: Socket::recv
/// [`connect`]: Socket::connect
///
/// # Safety
///
/// Normally casting a `IoSliceMut` to `MaybeUninitSlice` would be unsound,
/// as that allows us to write uninitialised bytes to the buffer. However
/// this implementation promises to not write uninitialised bytes to the
/// `bufs` and passes it directly to `recvmsg(2)` system call. This promise
/// ensures that this function can be called using `bufs` of type `&mut
/// [IoSliceMut]`.
///
/// Note that the [`io::Read::read_vectored`] implementation calls this
/// function with `buf`s of type `&mut [IoSliceMut]`, allowing initialised
/// buffers to be used without using `unsafe`.
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn recv_vectored(
&self,
bufs: &mut [MaybeUninitSlice<'_>],
) -> io::Result<(usize, RecvFlags)> {
self.recv_vectored_with_flags(bufs, 0)
}
/// Identical to [`recv_vectored`] but allows for specification of arbitrary
/// flags to the underlying `recvmsg`/`WSARecv` call.
///
/// [`recv_vectored`]: Socket::recv_vectored
///
/// # Safety
///
/// `recv_from_vectored` makes the same safety guarantees regarding `bufs`
/// as [`recv_vectored`].
///
/// [`recv_vectored`]: Socket::recv_vectored
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn recv_vectored_with_flags(
&self,
bufs: &mut [MaybeUninitSlice<'_>],
flags: c_int,
) -> io::Result<(usize, RecvFlags)> {
sys::recv_vectored(self.as_raw(), bufs, flags)
}
/// Receives data on the socket from the remote adress to which it is
/// connected, without removing that data from the queue. On success,
/// returns the number of bytes peeked.
///
/// Successive calls return the same data. This is accomplished by passing
/// `MSG_PEEK` as a flag to the underlying `recv` system call.
///
/// # Safety
///
/// `peek` makes the same safety guarantees regarding the `buf`fer as
/// [`recv`].
///
/// [`recv`]: Socket::recv
pub fn peek(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<usize> {
self.recv_with_flags(buf, sys::MSG_PEEK)
}
/// Receives data from the socket. On success, returns the number of bytes
/// read and the address from whence the data came.
#[doc = man_links!(recvfrom(2))]
///
/// # Safety
///
/// `recv_from` makes the same safety guarantees regarding the `buf`fer as
/// [`recv`].
///
/// [`recv`]: Socket::recv
pub fn recv_from(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<(usize, SockAddr)> {
self.recv_from_with_flags(buf, 0)
}
/// Identical to [`recv_from`] but allows for specification of arbitrary
/// flags to the underlying `recvfrom` call.
///
/// [`recv_from`]: Socket::recv_from
pub fn recv_from_with_flags(
&self,
buf: &mut [MaybeUninit<u8>],
flags: c_int,
) -> io::Result<(usize, SockAddr)> {
sys::recv_from(self.as_raw(), buf, flags)
}
/// Receives data from the socket. Returns the amount of bytes read, the
/// [`RecvFlags`] and the remote address from the data is coming. Unlike
/// [`recv_from`] this allows passing multiple buffers.
#[doc = man_links!(recvmsg(2))]
///
/// [`recv_from`]: Socket::recv_from
///
/// # Safety
///
/// `recv_from_vectored` makes the same safety guarantees regarding `bufs`
/// as [`recv_vectored`].
///
/// [`recv_vectored`]: Socket::recv_vectored
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn recv_from_vectored(
&self,
bufs: &mut [MaybeUninitSlice<'_>],
) -> io::Result<(usize, RecvFlags, SockAddr)> {
self.recv_from_vectored_with_flags(bufs, 0)
}
/// Identical to [`recv_from_vectored`] but allows for specification of
/// arbitrary flags to the underlying `recvmsg`/`WSARecvFrom` call.
///
/// [`recv_from_vectored`]: Socket::recv_from_vectored
///
/// # Safety
///
/// `recv_from_vectored` makes the same safety guarantees regarding `bufs`
/// as [`recv_vectored`].
///
/// [`recv_vectored`]: Socket::recv_vectored
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn recv_from_vectored_with_flags(
&self,
bufs: &mut [MaybeUninitSlice<'_>],
flags: c_int,
) -> io::Result<(usize, RecvFlags, SockAddr)> {
sys::recv_from_vectored(self.as_raw(), bufs, flags)
}
/// Receives data from the socket, without removing it from the queue.
///
/// Successive calls return the same data. This is accomplished by passing
/// `MSG_PEEK` as a flag to the underlying `recvfrom` system call.
///
/// On success, returns the number of bytes peeked and the address from
/// whence the data came.
///
/// # Safety
///
/// `peek_from` makes the same safety guarantees regarding the `buf`fer as
/// [`recv`].
///
/// # Note: Datagram Sockets
/// For datagram sockets, the behavior of this method when `buf` is smaller than
/// the datagram at the head of the receive queue differs between Windows and
/// Unix-like platforms (Linux, macOS, BSDs, etc: colloquially termed "*nix").
///
/// On *nix platforms, the datagram is truncated to the length of `buf`.
///
/// On Windows, an error corresponding to `WSAEMSGSIZE` will be returned.
///
/// For consistency between platforms, be sure to provide a sufficiently large buffer to avoid
/// truncation; the exact size required depends on the underlying protocol.
///
/// If you just want to know the sender of the data, try [`peek_sender`].
///
/// [`recv`]: Socket::recv
/// [`peek_sender`]: Socket::peek_sender
pub fn peek_from(&self, buf: &mut [MaybeUninit<u8>]) -> io::Result<(usize, SockAddr)> {
self.recv_from_with_flags(buf, sys::MSG_PEEK)
}
/// Retrieve the sender for the data at the head of the receive queue.
///
/// This is equivalent to calling [`peek_from`] with a zero-sized buffer,
/// but suppresses the `WSAEMSGSIZE` error on Windows.
///
/// [`peek_from`]: Socket::peek_from
pub fn peek_sender(&self) -> io::Result<SockAddr> {
sys::peek_sender(self.as_raw())
}
/// Receive a message from a socket using a message structure.
///
/// This is not supported on Windows as calling `WSARecvMsg` (the `recvmsg`
/// equivalent) is not straight forward on Windows. See
/// <https://github.com/microsoft/Windows-classic-samples/blob/7cbd99ac1d2b4a0beffbaba29ea63d024ceff700/Samples/Win7Samples/netds/winsock/recvmsg/rmmc.cpp>
/// for an example (in C++).
#[doc = man_links!(recvmsg(2))]
#[cfg(all(unix, not(target_os = "redox")))]
#[cfg_attr(docsrs, doc(cfg(all(unix, not(target_os = "redox")))))]
pub fn recvmsg(&self, msg: &mut MsgHdrMut<'_, '_, '_>, flags: sys::c_int) -> io::Result<usize> {
sys::recvmsg(self.as_raw(), msg, flags)
}
/// Sends data on the socket to a connected peer.
///
/// This is typically used on TCP sockets or datagram sockets which have
/// been connected.
///
/// On success returns the number of bytes that were sent.
#[doc = man_links!(send(2))]
pub fn send(&self, buf: &[u8]) -> io::Result<usize> {
self.send_with_flags(buf, 0)
}
/// Identical to [`send`] but allows for specification of arbitrary flags to the underlying
/// `send` call.
///
/// [`send`]: Socket::send
pub fn send_with_flags(&self, buf: &[u8], flags: c_int) -> io::Result<usize> {
sys::send(self.as_raw(), buf, flags)
}
/// Send data to the connected peer. Returns the amount of bytes written.
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn send_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
self.send_vectored_with_flags(bufs, 0)
}
/// Identical to [`send_vectored`] but allows for specification of arbitrary
/// flags to the underlying `sendmsg`/`WSASend` call.
#[doc = man_links!(sendmsg(2))]
///
/// [`send_vectored`]: Socket::send_vectored
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn send_vectored_with_flags(
&self,
bufs: &[IoSlice<'_>],
flags: c_int,
) -> io::Result<usize> {
sys::send_vectored(self.as_raw(), bufs, flags)
}
/// Sends out-of-band (OOB) data on the socket to connected peer
/// by setting the `MSG_OOB` flag for this call.
///
/// For more information, see [`send`], [`out_of_band_inline`].
///
/// [`send`]: Socket::send
/// [`out_of_band_inline`]: Socket::out_of_band_inline
#[cfg_attr(target_os = "redox", allow(rustdoc::broken_intra_doc_links))]
pub fn send_out_of_band(&self, buf: &[u8]) -> io::Result<usize> {
self.send_with_flags(buf, sys::MSG_OOB)
}
/// Sends data on the socket to the given address. On success, returns the
/// number of bytes written.
///
/// This is typically used on UDP or datagram-oriented sockets.
#[doc = man_links!(sendto(2))]
pub fn send_to(&self, buf: &[u8], addr: &SockAddr) -> io::Result<usize> {
self.send_to_with_flags(buf, addr, 0)
}
/// Identical to [`send_to`] but allows for specification of arbitrary flags
/// to the underlying `sendto` call.
///
/// [`send_to`]: Socket::send_to
pub fn send_to_with_flags(
&self,
buf: &[u8],
addr: &SockAddr,
flags: c_int,
) -> io::Result<usize> {
sys::send_to(self.as_raw(), buf, addr, flags)
}
/// Send data to a peer listening on `addr`. Returns the amount of bytes
/// written.
#[doc = man_links!(sendmsg(2))]
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn send_to_vectored(&self, bufs: &[IoSlice<'_>], addr: &SockAddr) -> io::Result<usize> {
self.send_to_vectored_with_flags(bufs, addr, 0)
}
/// Identical to [`send_to_vectored`] but allows for specification of
/// arbitrary flags to the underlying `sendmsg`/`WSASendTo` call.
///
/// [`send_to_vectored`]: Socket::send_to_vectored
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn send_to_vectored_with_flags(
&self,
bufs: &[IoSlice<'_>],
addr: &SockAddr,
flags: c_int,
) -> io::Result<usize> {
sys::send_to_vectored(self.as_raw(), bufs, addr, flags)
}
/// Send a message on a socket using a message structure.
#[doc = man_links!(sendmsg(2))]
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn sendmsg(&self, msg: &MsgHdr<'_, '_, '_>, flags: sys::c_int) -> io::Result<usize> {
sys::sendmsg(self.as_raw(), msg, flags)
}
}
/// Set `SOCK_CLOEXEC` and `NO_HANDLE_INHERIT` on the `ty`pe on platforms that
/// support it.
#[inline(always)]
const fn set_common_type(ty: Type) -> Type {
// On platforms that support it set `SOCK_CLOEXEC`.
#[cfg(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "hurd",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
))]
let ty = ty._cloexec();
// On windows set `NO_HANDLE_INHERIT`.
#[cfg(windows)]
let ty = ty._no_inherit();
ty
}
/// Set `FD_CLOEXEC` and `NOSIGPIPE` on the `socket` for platforms that need it.
#[inline(always)]
#[allow(clippy::unnecessary_wraps)]
fn set_common_flags(socket: Socket) -> io::Result<Socket> {
// On platforms that don't have `SOCK_CLOEXEC` use `FD_CLOEXEC`.
#[cfg(all(
unix,
not(any(
target_os = "android",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "fuchsia",
target_os = "hurd",
target_os = "illumos",
target_os = "linux",
target_os = "netbsd",
target_os = "openbsd",
target_os = "espidf",
target_os = "vita",
))
))]
socket._set_cloexec(true)?;
// On Apple platforms set `NOSIGPIPE`.
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
))]
socket._set_nosigpipe(true)?;
Ok(socket)
}
/// A local interface specified by its index or an address assigned to it.
///
/// `Index(0)` and `Address(Ipv4Addr::UNSPECIFIED)` are equivalent and indicate
/// that an appropriate interface should be selected by the system.
#[cfg(not(any(
target_os = "haiku",
target_os = "illumos",
target_os = "netbsd",
target_os = "redox",
target_os = "solaris",
)))]
#[derive(Debug)]
pub enum InterfaceIndexOrAddress {
/// An interface index.
Index(u32),
/// An address assigned to an interface.
Address(Ipv4Addr),
}
/// Socket options get/set using `SOL_SOCKET`.
///
/// Additional documentation can be found in documentation of the OS.
/// * Linux: <https://man7.org/linux/man-pages/man7/socket.7.html>
/// * Windows: <https://docs.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options>
impl Socket {
/// Get the value of the `SO_BROADCAST` option for this socket.
///
/// For more information about this option, see [`set_broadcast`].
///
/// [`set_broadcast`]: Socket::set_broadcast
pub fn broadcast(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), sys::SOL_SOCKET, sys::SO_BROADCAST)
.map(|broadcast| broadcast != 0)
}
}
/// Set the value of the `SO_BROADCAST` option for this socket.
///
/// When enabled, this socket is allowed to send packets to a broadcast
/// address.
pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
sys::SOL_SOCKET,
sys::SO_BROADCAST,
broadcast as c_int,
)
}
}
/// Get the value of the `SO_ERROR` option on this socket.
///
/// This will retrieve the stored error in the underlying socket, clearing
/// the field in the process. This can be useful for checking errors between
/// calls.
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
match unsafe { getsockopt::<c_int>(self.as_raw(), sys::SOL_SOCKET, sys::SO_ERROR) } {
Ok(0) => Ok(None),
Ok(errno) => Ok(Some(io::Error::from_raw_os_error(errno))),
Err(err) => Err(err),
}
}
/// Get the value of the `SO_KEEPALIVE` option on this socket.
///
/// For more information about this option, see [`set_keepalive`].
///
/// [`set_keepalive`]: Socket::set_keepalive
pub fn keepalive(&self) -> io::Result<bool> {
unsafe {
getsockopt::<Bool>(self.as_raw(), sys::SOL_SOCKET, sys::SO_KEEPALIVE)
.map(|keepalive| keepalive != 0)
}
}
/// Set value for the `SO_KEEPALIVE` option on this socket.
///
/// Enable sending of keep-alive messages on connection-oriented sockets.
pub fn set_keepalive(&self, keepalive: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
sys::SOL_SOCKET,
sys::SO_KEEPALIVE,
keepalive as c_int,
)
}
}
/// Get the value of the `SO_LINGER` option on this socket.
///
/// For more information about this option, see [`set_linger`].
///
/// [`set_linger`]: Socket::set_linger
pub fn linger(&self) -> io::Result<Option<Duration>> {
unsafe {
getsockopt::<sys::linger>(self.as_raw(), sys::SOL_SOCKET, sys::SO_LINGER)
.map(from_linger)
}
}
/// Set value for the `SO_LINGER` option on this socket.
///
/// If `linger` is not `None`, a close(2) or shutdown(2) will not return
/// until all queued messages for the socket have been successfully sent or
/// the linger timeout has been reached. Otherwise, the call returns
/// immediately and the closing is done in the background. When the socket
/// is closed as part of exit(2), it always lingers in the background.
///
/// # Notes
///
/// On most OSs the duration only has a precision of seconds and will be
/// silently truncated.
///
/// On Apple platforms (e.g. macOS, iOS, etc) this uses `SO_LINGER_SEC`.
pub fn set_linger(&self, linger: Option<Duration>) -> io::Result<()> {
let linger = into_linger(linger);
unsafe { setsockopt(self.as_raw(), sys::SOL_SOCKET, sys::SO_LINGER, linger) }
}
/// Get value for the `SO_OOBINLINE` option on this socket.
///
/// For more information about this option, see [`set_out_of_band_inline`].
///
/// [`set_out_of_band_inline`]: Socket::set_out_of_band_inline
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn out_of_band_inline(&self) -> io::Result<bool> {
unsafe {
getsockopt::<c_int>(self.as_raw(), sys::SOL_SOCKET, sys::SO_OOBINLINE)
.map(|oob_inline| oob_inline != 0)
}
}
/// Set value for the `SO_OOBINLINE` option on this socket.
///
/// If this option is enabled, out-of-band data is directly placed into the
/// receive data stream. Otherwise, out-of-band data is passed only when the
/// `MSG_OOB` flag is set during receiving. As per RFC6093, TCP sockets
/// using the Urgent mechanism are encouraged to set this flag.
#[cfg(not(target_os = "redox"))]
#[cfg_attr(docsrs, doc(cfg(not(target_os = "redox"))))]
pub fn set_out_of_band_inline(&self, oob_inline: bool) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
sys::SOL_SOCKET,
sys::SO_OOBINLINE,
oob_inline as c_int,
)
}
}
/// Get value for the `SO_RCVBUF` option on this socket.
///
/// For more information about this option, see [`set_recv_buffer_size`].
///
/// [`set_recv_buffer_size`]: Socket::set_recv_buffer_size
pub fn recv_buffer_size(&self) -> io::Result<usize> {
unsafe {
getsockopt::<c_int>(self.as_raw(), sys::SOL_SOCKET, sys::SO_RCVBUF)
.map(|size| size as usize)
}
}
/// Set value for the `SO_RCVBUF` option on this socket.
///
/// Changes the size of the operating system's receive buffer associated
/// with the socket.
pub fn set_recv_buffer_size(&self, size: usize) -> io::Result<()> {
unsafe {
setsockopt(
self.as_raw(),
sys::SOL_SOCKET,
sys::SO_RCVBUF,
size as c_int,
)
}
}
/// Get value for the `SO_RCVTIMEO` option on this socket.
///
/// If the returned timeout is `None`, then `read` and `recv` calls will
/// block indefinitely.
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
sys::timeout_opt(self.as_raw(), sys::SOL_SOCKET, sys::SO_RCVTIMEO)