Debian Codegraph @

debian/rust-vendor/nix/test/sys/test_socket.rs

raw
1 #[cfg(linux_android)]
2 use crate::*;
3 use libc::c_char;
4 use nix::sys::socket::{getsockname, AddressFamily, UnixAddr};
5 use std::collections::hash_map::DefaultHasher;
6 use std::hash::{Hash, Hasher};
7 use std::net::{SocketAddrV4, SocketAddrV6};
8 use std::os::unix::io::{AsRawFd, RawFd};
9 use std::path::Path;
10 use std::slice;
11 use std::str::FromStr;
12
13 #[cfg(target_os = "linux")]
14 #[cfg_attr(qemu, ignore)]
15 #[test]
16 pub fn test_timestamping() {
17 use nix::sys::socket::{
18 recvmsg, sendmsg, setsockopt, socket, sockopt::Timestamping,
19 ControlMessageOwned, MsgFlags, SockFlag, SockType, SockaddrIn,
20 TimestampingFlag,
21 };
22 use std::io::{IoSlice, IoSliceMut};
23
24 let sock_addr = SockaddrIn::from_str("127.0.0.1:6797").unwrap();
25
26 let ssock = socket(
27 AddressFamily::Inet,
28 SockType::Datagram,
29 SockFlag::empty(),
30 None,
31 )
32 .expect("send socket failed");
33
34 let rsock = socket(
35 AddressFamily::Inet,
36 SockType::Datagram,
37 SockFlag::empty(),
38 None,
39 )
40 .unwrap();
41 nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap();
42
43 setsockopt(&rsock, Timestamping, &TimestampingFlag::all()).unwrap();
44
45 let sbuf = [0u8; 2048];
46 let mut rbuf = [0u8; 2048];
47 let flags = MsgFlags::empty();
48 let iov1 = [IoSlice::new(&sbuf)];
49 let mut iov2 = [IoSliceMut::new(&mut rbuf)];
50
51 let mut cmsg = cmsg_space!(nix::sys::socket::Timestamps);
52 sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap();
53 let recv =
54 recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags)
55 .unwrap();
56
57 let mut ts = None;
58 for c in recv.cmsgs().unwrap() {
59 if let ControlMessageOwned::ScmTimestampsns(timestamps) = c {
60 ts = Some(timestamps.system);
61 }
62 }
63 let ts = ts.expect("ScmTimestampns is present");
64 let sys_time =
65 ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME)
66 .unwrap();
67 let diff = if ts > sys_time {
68 ts - sys_time
69 } else {
70 sys_time - ts
71 };
72 assert!(std::time::Duration::from(diff).as_secs() < 60);
73 }
74
75 #[cfg(target_os = "freebsd")]
76 #[test]
77 pub fn test_timestamping_realtime() {
78 use nix::sys::socket::{
79 recvmsg, sendmsg, setsockopt, socket, sockopt::ReceiveTimestamp,
80 sockopt::TsClock, ControlMessageOwned, MsgFlags, SockFlag, SockType,
81 SockaddrIn, SocketTimestamp,
82 };
83 use std::io::{IoSlice, IoSliceMut};
84
85 let sock_addr = SockaddrIn::from_str("127.0.0.1:6792").unwrap();
86
87 let ssock = socket(
88 AddressFamily::Inet,
89 SockType::Datagram,
90 SockFlag::empty(),
91 None,
92 )
93 .expect("send socket failed");
94
95 let rsock = socket(
96 AddressFamily::Inet,
97 SockType::Datagram,
98 SockFlag::empty(),
99 None,
100 )
101 .unwrap();
102 nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap();
103
104 setsockopt(&rsock, ReceiveTimestamp, &true).unwrap();
105 setsockopt(&rsock, TsClock, &SocketTimestamp::SO_TS_REALTIME).unwrap();
106
107 let sbuf = [0u8; 2048];
108 let mut rbuf = [0u8; 2048];
109 let flags = MsgFlags::empty();
110 let iov1 = [IoSlice::new(&sbuf)];
111 let mut iov2 = [IoSliceMut::new(&mut rbuf)];
112
113 let mut cmsg = cmsg_space!(nix::sys::time::TimeVal);
114 sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap();
115 let recv =
116 recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags)
117 .unwrap();
118
119 let mut ts = None;
120 for c in recv.cmsgs().unwrap() {
121 if let ControlMessageOwned::ScmRealtime(timeval) = c {
122 ts = Some(timeval);
123 }
124 }
125 let ts = ts.expect("ScmRealtime is present");
126 let sys_time =
127 ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME)
128 .unwrap();
129 let diff = if ts > sys_time {
130 ts - sys_time
131 } else {
132 sys_time - ts
133 };
134 assert!(std::time::Duration::from(diff).as_secs() < 60);
135 }
136
137 #[cfg(target_os = "freebsd")]
138 #[test]
139 pub fn test_timestamping_monotonic() {
140 use nix::sys::socket::{
141 recvmsg, sendmsg, setsockopt, socket, sockopt::ReceiveTimestamp,
142 sockopt::TsClock, ControlMessageOwned, MsgFlags, SockFlag, SockType,
143 SockaddrIn, SocketTimestamp,
144 };
145 use std::io::{IoSlice, IoSliceMut};
146
147 let sock_addr = SockaddrIn::from_str("127.0.0.1:6803").unwrap();
148
149 let ssock = socket(
150 AddressFamily::Inet,
151 SockType::Datagram,
152 SockFlag::empty(),
153 None,
154 )
155 .expect("send socket failed");
156
157 let rsock = socket(
158 AddressFamily::Inet,
159 SockType::Datagram,
160 SockFlag::empty(),
161 None,
162 )
163 .unwrap();
164 nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap();
165
166 setsockopt(&rsock, ReceiveTimestamp, &true).unwrap();
167 setsockopt(&rsock, TsClock, &SocketTimestamp::SO_TS_MONOTONIC).unwrap();
168
169 let sbuf = [0u8; 2048];
170 let mut rbuf = [0u8; 2048];
171 let flags = MsgFlags::empty();
172 let iov1 = [IoSlice::new(&sbuf)];
173 let mut iov2 = [IoSliceMut::new(&mut rbuf)];
174
175 let mut cmsg = cmsg_space!(nix::sys::time::TimeVal);
176 sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap();
177 let recv =
178 recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags)
179 .unwrap();
180
181 let mut ts = None;
182 for c in recv.cmsgs().unwrap() {
183 if let ControlMessageOwned::ScmMonotonic(timeval) = c {
184 ts = Some(timeval);
185 }
186 }
187 let ts = ts.expect("ScmMonotonic is present");
188 let sys_time =
189 ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_MONOTONIC)
190 .unwrap();
191 let diff = sys_time - ts; // Monotonic clock sys_time must be greater
192 assert!(std::time::Duration::from(diff).as_secs() < 60);
193 }
194
195 #[test]
196 pub fn test_path_to_sock_addr() {
197 let path = "/foo/bar";
198 let actual = Path::new(path);
199 let addr = UnixAddr::new(actual).unwrap();
200
201 let expect: &[c_char] =
202 unsafe { slice::from_raw_parts(path.as_ptr().cast(), path.len()) };
203 assert_eq!(unsafe { &(&(*addr.as_ptr()).sun_path)[..8] }, expect);
204
205 assert_eq!(addr.path(), Some(actual));
206 }
207
208 fn calculate_hash<T: Hash>(t: &T) -> u64 {
209 let mut s = DefaultHasher::new();
210 t.hash(&mut s);
211 s.finish()
212 }
213
214 #[test]
215 pub fn test_addr_equality_path() {
216 let path = "/foo/bar";
217 let actual = Path::new(path);
218 let addr1 = UnixAddr::new(actual).unwrap();
219 let mut addr2 = addr1;
220
221 unsafe { (*addr2.as_mut_ptr()).sun_path[10] = 127 };
222
223 assert_eq!(addr1, addr2);
224 assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2));
225 }
226
227 #[cfg(linux_android)]
228 #[test]
229 pub fn test_abstract_sun_path_too_long() {
230 let name = String::from("nix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0testttttnix\0abstract\0test\0make\0sure\0this\0is\0long\0enough");
231 let addr = UnixAddr::new_abstract(name.as_bytes());
232 addr.expect_err("assertion failed");
233 }
234
235 #[cfg(linux_android)]
236 #[test]
237 pub fn test_addr_equality_abstract() {
238 let name = String::from("nix\0abstract\0test");
239 let addr1 = UnixAddr::new_abstract(name.as_bytes()).unwrap();
240 let mut addr2 = addr1;
241
242 assert_eq!(addr1, addr2);
243 assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2));
244
245 unsafe { (*addr2.as_mut_ptr()).sun_path[17] = 127 };
246 assert_ne!(addr1, addr2);
247 assert_ne!(calculate_hash(&addr1), calculate_hash(&addr2));
248 }
249
250 // Test getting/setting abstract addresses (without unix socket creation)
251 #[cfg(linux_android)]
252 #[test]
253 pub fn test_abstract_uds_addr() {
254 let empty = String::new();
255 let addr = UnixAddr::new_abstract(empty.as_bytes()).unwrap();
256 let sun_path: [u8; 0] = [];
257 assert_eq!(addr.as_abstract(), Some(&sun_path[..]));
258
259 let name = String::from("nix\0abstract\0test");
260 let addr = UnixAddr::new_abstract(name.as_bytes()).unwrap();
261 let sun_path = [
262 110u8, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101,
263 115, 116,
264 ];
265 assert_eq!(addr.as_abstract(), Some(&sun_path[..]));
266 assert_eq!(addr.path(), None);
267
268 // Internally, name is null-prefixed (abstract namespace)
269 assert_eq!(unsafe { (*addr.as_ptr()).sun_path[0] }, 0);
270 }
271
272 // Test getting an unnamed address (without unix socket creation)
273 #[cfg(linux_android)]
274 #[test]
275 pub fn test_unnamed_uds_addr() {
276 use crate::nix::sys::socket::SockaddrLike;
277
278 let addr = UnixAddr::new_unnamed();
279
280 assert!(addr.is_unnamed());
281 assert_eq!(addr.len(), 2);
282 assert!(addr.path().is_none());
283 assert_eq!(addr.path_len(), 0);
284
285 assert!(addr.as_abstract().is_none());
286 }
287
288 #[test]
289 pub fn test_getsockname() {
290 use nix::sys::socket::bind;
291 use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
292
293 let tempdir = tempfile::tempdir().unwrap();
294 let sockname = tempdir.path().join("sock");
295 let sock = socket(
296 AddressFamily::Unix,
297 SockType::Stream,
298 SockFlag::empty(),
299 None,
300 )
301 .expect("socket failed");
302 let sockaddr = UnixAddr::new(&sockname).unwrap();
303 bind(sock.as_raw_fd(), &sockaddr).expect("bind failed");
304 assert_eq!(
305 sockaddr,
306 getsockname(sock.as_raw_fd()).expect("getsockname failed")
307 );
308 }
309
310 #[test]
311 pub fn test_socketpair() {
312 use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType};
313 use nix::unistd::{read, write};
314
315 let (fd1, fd2) = socketpair(
316 AddressFamily::Unix,
317 SockType::Stream,
318 None,
319 SockFlag::empty(),
320 )
321 .unwrap();
322 write(&fd1, b"hello").unwrap();
323 let mut buf = [0; 5];
324 read(&fd2, &mut buf).unwrap();
325
326 assert_eq!(&buf[..], b"hello");
327 }
328
329 #[test]
330 #[cfg_attr(target_os = "cygwin", ignore)]
331 pub fn test_recvmsg_sockaddr_un() {
332 use nix::sys::socket::{
333 self, bind, socket, AddressFamily, MsgFlags, SockFlag, SockType,
334 };
335
336 let tempdir = tempfile::tempdir().unwrap();
337 let sockname = tempdir.path().join("sock");
338 let sock = socket(
339 AddressFamily::Unix,
340 SockType::Datagram,
341 SockFlag::empty(),
342 None,
343 )
344 .expect("socket failed");
345 let sockaddr = UnixAddr::new(&sockname).unwrap();
346 bind(sock.as_raw_fd(), &sockaddr).expect("bind failed");
347
348 // Send a message
349 let send_buffer = "hello".as_bytes();
350 if let Err(e) = socket::sendmsg(
351 sock.as_raw_fd(),
352 &[std::io::IoSlice::new(send_buffer)],
353 &[],
354 MsgFlags::empty(),
355 Some(&sockaddr),
356 ) {
357 crate::skip!("Couldn't send ({e:?}), so skipping test");
358 }
359
360 // Receive the message
361 let mut recv_buffer = [0u8; 32];
362 let mut iov = [std::io::IoSliceMut::new(&mut recv_buffer)];
363 let received =
364 socket::recvmsg(sock.as_raw_fd(), &mut iov, None, MsgFlags::empty())
365 .unwrap();
366 // Check the address in the received message
367 assert_eq!(sockaddr, received.address.unwrap());
368 }
369
370 #[test]
371 pub fn test_std_conversions() {
372 use nix::sys::socket::*;
373
374 let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap();
375 let sock_addr = SockaddrIn::from(std_sa);
376 assert_eq!(std_sa, sock_addr.into());
377
378 let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap();
379 let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa);
380 assert_eq!(std_sa, sock_addr.into());
381 }
382
383 mod recvfrom {
384 use super::*;
385 use nix::sys::socket::*;
386 use nix::{errno::Errno, Result};
387 use std::thread;
388
389 const MSG: &[u8] = b"Hello, World!";
390
391 fn sendrecv<Fs, Fr>(
392 rsock: RawFd,
393 ssock: RawFd,
394 f_send: Fs,
395 mut f_recv: Fr,
396 ) -> Option<SockaddrStorage>
397 where
398 Fs: Fn(RawFd, &[u8], MsgFlags) -> Result<usize> + Send + 'static,
399 Fr: FnMut(usize, Option<SockaddrStorage>),
400 {
401 let mut buf: [u8; 13] = [0u8; 13];
402 let mut l = 0;
403 let mut from = None;
404
405 let send_thread = thread::spawn(move || {
406 let mut l = 0;
407 while l < std::mem::size_of_val(MSG) {
408 l += f_send(ssock, &MSG[l..], MsgFlags::empty()).unwrap();
409 }
410 });
411
412 while l < std::mem::size_of_val(MSG) {
413 let (len, from_) = recvfrom(rsock, &mut buf[l..]).unwrap();
414 f_recv(len, from_);
415 from = from_;
416 l += len;
417 }
418 assert_eq!(&buf, MSG);
419 send_thread.join().unwrap();
420 from
421 }
422
423 #[test]
424 pub fn stream() {
425 let (fd2, fd1) = socketpair(
426 AddressFamily::Unix,
427 SockType::Stream,
428 None,
429 SockFlag::empty(),
430 )
431 .unwrap();
432 // Ignore from for stream sockets
433 let _ = sendrecv(fd1.as_raw_fd(), fd2.as_raw_fd(), send, |_, _| {});
434 }
435
436 #[test]
437 pub fn udp() {
438 let std_sa = SocketAddrV4::from_str("127.0.0.1:6795").unwrap();
439 let sock_addr = SockaddrIn::from(std_sa);
440 let rsock = socket(
441 AddressFamily::Inet,
442 SockType::Datagram,
443 SockFlag::empty(),
444 None,
445 )
446 .unwrap();
447 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
448 let ssock = socket(
449 AddressFamily::Inet,
450 SockType::Datagram,
451 SockFlag::empty(),
452 None,
453 )
454 .expect("send socket failed");
455 let from = sendrecv(
456 rsock.as_raw_fd(),
457 ssock.as_raw_fd(),
458 move |s, m, flags| sendto(s.as_raw_fd(), m, &sock_addr, flags),
459 |_, _| {},
460 );
461 // UDP sockets should set the from address
462 assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap());
463 }
464
465 #[cfg(linux_android)]
466 mod udp_offload {
467 use super::*;
468 use nix::sys::socket::sockopt::{UdpGroSegment, UdpGsoSegment};
469 use std::io::IoSlice;
470
471 #[test]
472 // Disable the test under emulation because it fails in Cirrus-CI. Lack
473 // of QEMU support is suspected.
474 #[cfg_attr(qemu, ignore)]
475 pub fn gso() {
476 require_kernel_version!(udp_offload::gso, ">= 4.18");
477
478 // In this test, we send the data and provide a GSO segment size.
479 // Since we are sending the buffer of size 13, six UDP packets
480 // with size 2 and two UDP packet with size 1 will be sent.
481 let segment_size: u16 = 2;
482
483 let sock_addr = SockaddrIn::new(127, 0, 0, 1, 6791);
484 let rsock = socket(
485 AddressFamily::Inet,
486 SockType::Datagram,
487 SockFlag::empty(),
488 None,
489 )
490 .unwrap();
491
492 setsockopt(&rsock, UdpGsoSegment, &(segment_size as _))
493 .expect("setsockopt UDP_SEGMENT failed");
494
495 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
496 let ssock = socket(
497 AddressFamily::Inet,
498 SockType::Datagram,
499 SockFlag::empty(),
500 None,
501 )
502 .expect("send socket failed");
503
504 let mut num_packets_received: i32 = 0;
505
506 sendrecv(
507 rsock.as_raw_fd(),
508 ssock.as_raw_fd(),
509 move |s, m, flags| {
510 let iov = [IoSlice::new(m)];
511 let cmsg = ControlMessage::UdpGsoSegments(&segment_size);
512 sendmsg(
513 s.as_raw_fd(),
514 &iov,
515 &[cmsg],
516 flags,
517 Some(&sock_addr),
518 )
519 },
520 {
521 let num_packets_received_ref = &mut num_packets_received;
522
523 move |len, _| {
524 // check that we receive UDP packets with payload size
525 // less or equal to segment size
526 assert!(len <= segment_size as usize);
527 *num_packets_received_ref += 1;
528 }
529 },
530 );
531
532 // Buffer size is 13, we will receive six packets of size 2,
533 // and one packet of size 1.
534 assert_eq!(7, num_packets_received);
535 }
536
537 #[test]
538 // Disable the test on emulated platforms because it fails in Cirrus-CI.
539 // Lack of QEMU support is suspected.
540 #[cfg_attr(qemu, ignore)]
541 pub fn gro() {
542 require_kernel_version!(udp_offload::gro, ">= 5.3");
543
544 // It's hard to guarantee receiving GRO packets. Just checking
545 // that `setsockopt` doesn't fail with error
546
547 let rsock = socket(
548 AddressFamily::Inet,
549 SockType::Datagram,
550 SockFlag::empty(),
551 None,
552 )
553 .unwrap();
554
555 setsockopt(&rsock, UdpGroSegment, &true)
556 .expect("setsockopt UDP_GRO failed");
557 }
558 }
559
560 #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))]
561 #[test]
562 pub fn udp_sendmmsg() {
563 use std::io::IoSlice;
564
565 let std_sa = SocketAddrV4::from_str("127.0.0.1:6793").unwrap();
566 let std_sa2 = SocketAddrV4::from_str("127.0.0.1:6794").unwrap();
567 let sock_addr = SockaddrIn::from(std_sa);
568 let sock_addr2 = SockaddrIn::from(std_sa2);
569
570 let rsock = socket(
571 AddressFamily::Inet,
572 SockType::Datagram,
573 SockFlag::empty(),
574 None,
575 )
576 .unwrap();
577 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
578 let ssock = socket(
579 AddressFamily::Inet,
580 SockType::Datagram,
581 SockFlag::empty(),
582 None,
583 )
584 .expect("send socket failed");
585
586 let from = sendrecv(
587 rsock.as_raw_fd(),
588 ssock.as_raw_fd(),
589 move |s, m, flags| {
590 let batch_size = 15;
591 let mut iovs = Vec::with_capacity(1 + batch_size);
592 let mut addrs = Vec::with_capacity(1 + batch_size);
593 let mut data = MultiHeaders::preallocate(1 + batch_size, None);
594 let iov = IoSlice::new(m);
595 // first chunk:
596 iovs.push([iov]);
597 addrs.push(Some(sock_addr));
598
599 for _ in 0..batch_size {
600 iovs.push([iov]);
601 addrs.push(Some(sock_addr2));
602 }
603
604 let res = sendmmsg(s, &mut data, &iovs, addrs, [], flags)?;
605 let mut sent_messages = 0;
606 let mut sent_bytes = 0;
607 for item in res {
608 sent_messages += 1;
609 sent_bytes += item.bytes;
610 }
611 //
612 assert_eq!(sent_messages, iovs.len());
613 assert_eq!(sent_bytes, sent_messages * m.len());
614 Ok(sent_messages)
615 },
616 |_, _| {},
617 );
618 // UDP sockets should set the from address
619 assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap());
620 }
621
622 #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))]
623 #[test]
624 pub fn udp_recvmmsg() {
625 use nix::sys::socket::{recvmmsg, MsgFlags};
626 use std::io::IoSliceMut;
627
628 const NUM_MESSAGES_SENT: usize = 2;
629 const DATA: [u8; 2] = [1, 2];
630
631 let inet_addr = SocketAddrV4::from_str("127.0.0.1:6798").unwrap();
632 let sock_addr = SockaddrIn::from(inet_addr);
633
634 let rsock = socket(
635 AddressFamily::Inet,
636 SockType::Datagram,
637 SockFlag::empty(),
638 None,
639 )
640 .unwrap();
641 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
642 let ssock = socket(
643 AddressFamily::Inet,
644 SockType::Datagram,
645 SockFlag::empty(),
646 None,
647 )
648 .expect("send socket failed");
649
650 let send_thread = thread::spawn(move || {
651 for _ in 0..NUM_MESSAGES_SENT {
652 sendto(
653 ssock.as_raw_fd(),
654 &DATA[..],
655 &sock_addr,
656 MsgFlags::empty(),
657 )
658 .unwrap();
659 }
660 });
661
662 let mut msgs = std::collections::LinkedList::new();
663
664 // Buffers to receive exactly `NUM_MESSAGES_SENT` messages
665 let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT];
666 msgs.extend(
667 receive_buffers
668 .iter_mut()
669 .map(|buf| [IoSliceMut::new(&mut buf[..])]),
670 );
671
672 let mut data =
673 MultiHeaders::<SockaddrIn>::preallocate(msgs.len(), None);
674
675 let res: Vec<RecvMsg<SockaddrIn>> = recvmmsg(
676 rsock.as_raw_fd(),
677 &mut data,
678 msgs.iter_mut(),
679 MsgFlags::empty(),
680 None,
681 )
682 .expect("recvmmsg")
683 .collect();
684 assert_eq!(res.len(), DATA.len());
685
686 for RecvMsg { address, bytes, .. } in res.into_iter() {
687 assert_eq!(AddressFamily::Inet, address.unwrap().family().unwrap());
688 assert_eq!(DATA.len(), bytes);
689 }
690
691 for buf in &receive_buffers {
692 assert_eq!(&buf[..DATA.len()], DATA);
693 }
694
695 send_thread.join().unwrap();
696 }
697
698 #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))]
699 #[test]
700 pub fn udp_recvmmsg_dontwait_short_read() {
701 use nix::sys::socket::{recvmmsg, MsgFlags};
702 use std::io::IoSliceMut;
703
704 const NUM_MESSAGES_SENT: usize = 2;
705 const DATA: [u8; 4] = [1, 2, 3, 4];
706
707 let inet_addr = SocketAddrV4::from_str("127.0.0.1:6799").unwrap();
708 let sock_addr = SockaddrIn::from(inet_addr);
709
710 let rsock = socket(
711 AddressFamily::Inet,
712 SockType::Datagram,
713 SockFlag::empty(),
714 None,
715 )
716 .unwrap();
717 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
718 let ssock = socket(
719 AddressFamily::Inet,
720 SockType::Datagram,
721 SockFlag::empty(),
722 None,
723 )
724 .expect("send socket failed");
725
726 let send_thread = thread::spawn(move || {
727 for _ in 0..NUM_MESSAGES_SENT {
728 sendto(
729 ssock.as_raw_fd(),
730 &DATA[..],
731 &sock_addr,
732 MsgFlags::empty(),
733 )
734 .unwrap();
735 }
736 });
737 // Ensure we've sent all the messages before continuing so `recvmmsg`
738 // will return right away
739 send_thread.join().unwrap();
740
741 let mut msgs = std::collections::LinkedList::new();
742
743 // Buffers to receive >`NUM_MESSAGES_SENT` messages to ensure `recvmmsg`
744 // will return when there are fewer than requested messages in the
745 // kernel buffers when using `MSG_DONTWAIT`.
746 let mut receive_buffers = [[0u8; 32]; NUM_MESSAGES_SENT + 2];
747 msgs.extend(
748 receive_buffers
749 .iter_mut()
750 .map(|buf| [IoSliceMut::new(&mut buf[..])]),
751 );
752
753 let mut data = MultiHeaders::<SockaddrIn>::preallocate(
754 NUM_MESSAGES_SENT + 2,
755 None,
756 );
757
758 let res: Vec<RecvMsg<SockaddrIn>> = recvmmsg(
759 rsock.as_raw_fd(),
760 &mut data,
761 msgs.iter_mut(),
762 MsgFlags::MSG_DONTWAIT,
763 None,
764 )
765 .expect("recvmmsg")
766 .collect();
767 assert_eq!(res.len(), NUM_MESSAGES_SENT);
768
769 for RecvMsg { address, bytes, .. } in res.into_iter() {
770 assert_eq!(AddressFamily::Inet, address.unwrap().family().unwrap());
771 assert_eq!(DATA.len(), bytes);
772 }
773
774 for buf in &receive_buffers[..NUM_MESSAGES_SENT] {
775 assert_eq!(&buf[..DATA.len()], DATA);
776 }
777 }
778
779 #[test]
780 pub fn udp_inet6() {
781 let addr = std::net::Ipv6Addr::from_str("::1").unwrap();
782 let rport = 6796;
783 let rstd_sa = SocketAddrV6::new(addr, rport, 0, 0);
784 let raddr = SockaddrIn6::from(rstd_sa);
785 let sport = 6798;
786 let sstd_sa = SocketAddrV6::new(addr, sport, 0, 0);
787 let saddr = SockaddrIn6::from(sstd_sa);
788 let rsock = socket(
789 AddressFamily::Inet6,
790 SockType::Datagram,
791 SockFlag::empty(),
792 None,
793 )
794 .expect("receive socket failed");
795 match bind(rsock.as_raw_fd(), &raddr) {
796 Err(Errno::EADDRNOTAVAIL) => {
797 println!("IPv6 not available, skipping test.");
798 return;
799 }
800 Err(e) => panic!("bind: {e}"),
801 Ok(()) => (),
802 }
803 let ssock = socket(
804 AddressFamily::Inet6,
805 SockType::Datagram,
806 SockFlag::empty(),
807 None,
808 )
809 .expect("send socket failed");
810 bind(ssock.as_raw_fd(), &saddr).unwrap();
811 let from = sendrecv(
812 rsock.as_raw_fd(),
813 ssock.as_raw_fd(),
814 move |s, m, flags| sendto(s.as_raw_fd(), m, &raddr, flags),
815 |_, _| {},
816 );
817 assert_eq!(AddressFamily::Inet6, from.unwrap().family().unwrap());
818 let osent_addr = from.unwrap();
819 let sent_addr = osent_addr.as_sockaddr_in6().unwrap();
820 assert_eq!(sent_addr.ip(), addr);
821 assert_eq!(sent_addr.port(), sport);
822 }
823 }
824
825 // Test error handling of our recvmsg wrapper
826 #[test]
827 pub fn test_recvmsg_ebadf() {
828 use nix::errno::Errno;
829 use nix::sys::socket::{recvmsg, MsgFlags};
830 use std::io::IoSliceMut;
831
832 let mut buf = [0u8; 5];
833 let mut iov = [IoSliceMut::new(&mut buf[..])];
834
835 let fd = -1; // Bad file descriptor
836 let r = recvmsg::<()>(fd.as_raw_fd(), &mut iov, None, MsgFlags::empty());
837
838 assert_eq!(r.err().unwrap(), Errno::EBADF);
839 }
840
841 // Disable the test on emulated platforms due to a bug in QEMU versions <
842 // 2.12.0. https://bugs.launchpad.net/qemu/+bug/1701808
843 #[cfg_attr(qemu, ignore)]
844 #[test]
845 #[cfg_attr(target_os = "cygwin", ignore)]
846 pub fn test_scm_rights() {
847 use nix::sys::socket::{
848 recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage,
849 ControlMessageOwned, MsgFlags, SockFlag, SockType,
850 };
851 use nix::unistd::{close, pipe, read, write};
852 use std::io::{IoSlice, IoSliceMut};
853
854 let (fd1, fd2) = socketpair(
855 AddressFamily::Unix,
856 SockType::Stream,
857 None,
858 SockFlag::empty(),
859 )
860 .unwrap();
861 let (r, w) = pipe().unwrap();
862 let mut received_r: Option<RawFd> = None;
863
864 {
865 let iov = [IoSlice::new(b"hello")];
866 let fds = [r.as_raw_fd()];
867 let cmsg = ControlMessage::ScmRights(&fds);
868 assert_eq!(
869 sendmsg::<()>(
870 fd1.as_raw_fd(),
871 &iov,
872 &[cmsg],
873 MsgFlags::empty(),
874 None
875 )
876 .unwrap(),
877 5
878 );
879 }
880
881 {
882 let mut buf = [0u8; 5];
883
884 let mut iov = [IoSliceMut::new(&mut buf[..])];
885 let mut cmsgspace = cmsg_space!([RawFd; 1]);
886 let msg = recvmsg::<()>(
887 fd2.as_raw_fd(),
888 &mut iov,
889 Some(&mut cmsgspace),
890 MsgFlags::empty(),
891 )
892 .unwrap();
893
894 for cmsg in msg.cmsgs().unwrap() {
895 if let ControlMessageOwned::ScmRights(fd) = cmsg {
896 assert_eq!(received_r, None);
897 assert_eq!(fd.len(), 1);
898 received_r = Some(fd[0]);
899 } else {
900 panic!("unexpected cmsg");
901 }
902 }
903 assert_eq!(msg.bytes, 5);
904 assert!(!msg
905 .flags
906 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
907 }
908
909 let received_r = received_r.expect("Did not receive passed fd");
910 // Ensure that the received file descriptor works
911 write(&w, b"world").unwrap();
912 let mut buf = [0u8; 5];
913 // SAFETY:
914 // should be safe since we don't use it after close
915 let borrowed_received_r =
916 unsafe { std::os::fd::BorrowedFd::borrow_raw(received_r) };
917 read(borrowed_received_r, &mut buf).unwrap();
918 assert_eq!(&buf[..], b"world");
919 close(received_r).unwrap();
920 }
921
922 // 1. Disable the test on emulated platforms due to not enabled support of
923 // AF_ALG in QEMU from rust cross
924 // 2. Disable the test on aarch64/Linux, s390x/Linux, and powerpc64le/Linux
925 // because bind() fails with ENOENT:
926 // https://github.com/nix-rust/nix/issues/1352
927 #[cfg(linux_android)]
928 #[cfg_attr(
929 any(
930 qemu,
931 all(target_os = "linux", target_arch = "aarch64"),
932 all(target_os = "linux", target_arch = "s390x"),
933 all(
934 target_os = "linux",
935 target_arch = "powerpc64",
936 target_endian = "little"
937 ),
938 ),
939 ignore
940 )]
941 #[test]
942 pub fn test_af_alg_cipher() {
943 use nix::sys::socket::sockopt::AlgSetKey;
944 use nix::sys::socket::{
945 accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr,
946 ControlMessage, MsgFlags, SockFlag, SockType,
947 };
948 use nix::unistd::read;
949 use std::io::IoSlice;
950
951 let alg_type = "skcipher";
952 let alg_name = "ctr-aes-aesni";
953 // 256-bits secret key
954 let key = vec![0u8; 32];
955 // 16-bytes IV
956 let iv_len = 16;
957 let iv = vec![1u8; iv_len];
958 // 256-bytes plain payload
959 let payload_len = 256;
960 let payload = vec![2u8; payload_len];
961
962 let sock = socket(
963 AddressFamily::Alg,
964 SockType::SeqPacket,
965 SockFlag::empty(),
966 None,
967 )
968 .expect("socket failed");
969
970 let sockaddr = AlgAddr::new(alg_type, alg_name);
971 bind(sock.as_raw_fd(), &sockaddr).expect("bind failed");
972
973 assert_eq!(sockaddr.alg_name().to_string_lossy(), alg_name);
974 assert_eq!(sockaddr.alg_type().to_string_lossy(), alg_type);
975
976 setsockopt(&sock, AlgSetKey::default(), &key).expect("setsockopt");
977 let session_socket = accept(sock.as_raw_fd()).expect("accept failed");
978
979 let msgs = [
980 ControlMessage::AlgSetOp(&libc::ALG_OP_ENCRYPT),
981 ControlMessage::AlgSetIv(iv.as_slice()),
982 ];
983 let iov = IoSlice::new(&payload);
984 sendmsg::<()>(
985 session_socket.as_raw_fd(),
986 &[iov],
987 &msgs,
988 MsgFlags::empty(),
989 None,
990 )
991 .expect("sendmsg encrypt");
992
993 // allocate buffer for encrypted data
994 let mut encrypted = vec![0u8; payload_len];
995 // SAFETY:
996 // should be safe since session_socket won't be closed before the use of this borrowed one
997 let borrowed_session_socket =
998 unsafe { std::os::fd::BorrowedFd::borrow_raw(session_socket) };
999 let num_bytes =
1000 read(borrowed_session_socket, &mut encrypted).expect("read encrypt");
1001 assert_eq!(num_bytes, payload_len);
1002
1003 let iov = IoSlice::new(&encrypted);
1004
1005 let iv = vec![1u8; iv_len];
1006
1007 let msgs = [
1008 ControlMessage::AlgSetOp(&libc::ALG_OP_DECRYPT),
1009 ControlMessage::AlgSetIv(iv.as_slice()),
1010 ];
1011 sendmsg::<()>(
1012 session_socket.as_raw_fd(),
1013 &[iov],
1014 &msgs,
1015 MsgFlags::empty(),
1016 None,
1017 )
1018 .expect("sendmsg decrypt");
1019
1020 // allocate buffer for decrypted data
1021 let mut decrypted = vec![0u8; payload_len];
1022 // SAFETY:
1023 // should be safe since session_socket won't be closed before the use of this borrowed one
1024 let borrowed_session_socket =
1025 unsafe { std::os::fd::BorrowedFd::borrow_raw(session_socket) };
1026 let num_bytes =
1027 read(borrowed_session_socket, &mut decrypted).expect("read decrypt");
1028
1029 assert_eq!(num_bytes, payload_len);
1030 assert_eq!(decrypted, payload);
1031 }
1032
1033 // Disable the test on emulated platforms due to not enabled support of AF_ALG
1034 // in QEMU from rust cross
1035 #[cfg(linux_android)]
1036 #[cfg_attr(qemu, ignore)]
1037 #[test]
1038 pub fn test_af_alg_aead() {
1039 use libc::{ALG_OP_DECRYPT, ALG_OP_ENCRYPT};
1040 use nix::fcntl::{fcntl, FcntlArg, OFlag};
1041 use nix::sys::socket::sockopt::{AlgSetAeadAuthSize, AlgSetKey};
1042 use nix::sys::socket::{
1043 accept, bind, sendmsg, setsockopt, socket, AddressFamily, AlgAddr,
1044 ControlMessage, MsgFlags, SockFlag, SockType,
1045 };
1046 use nix::unistd::read;
1047 use std::io::IoSlice;
1048
1049 // Travis's seccomp profile blocks AF_ALG
1050 // https://docs.docker.com/engine/security/seccomp/
1051 skip_if_seccomp!(test_af_alg_aead);
1052
1053 let auth_size = 4usize;
1054 let assoc_size = 16u32;
1055
1056 let alg_type = "aead";
1057 let alg_name = "gcm(aes)";
1058 // 256-bits secret key
1059 let key = vec![0u8; 32];
1060 // 12-bytes IV
1061 let iv_len = 12;
1062 let iv = vec![1u8; iv_len];
1063 // 256-bytes plain payload
1064 let payload_len = 256;
1065 let mut payload =
1066 vec![2u8; payload_len + (assoc_size as usize) + auth_size];
1067
1068 for i in 0..assoc_size {
1069 payload[i as usize] = 10;
1070 }
1071
1072 let len = payload.len();
1073
1074 for i in 0..auth_size {
1075 payload[len - 1 - i] = 0;
1076 }
1077
1078 let sock = socket(
1079 AddressFamily::Alg,
1080 SockType::SeqPacket,
1081 SockFlag::empty(),
1082 None,
1083 )
1084 .expect("socket failed");
1085
1086 let sockaddr = AlgAddr::new(alg_type, alg_name);
1087 bind(sock.as_raw_fd(), &sockaddr).expect("bind failed");
1088
1089 setsockopt(&sock, AlgSetAeadAuthSize, &auth_size)
1090 .expect("setsockopt AlgSetAeadAuthSize");
1091 setsockopt(&sock, AlgSetKey::default(), &key)
1092 .expect("setsockopt AlgSetKey");
1093 let session_socket = accept(sock.as_raw_fd()).expect("accept failed");
1094
1095 let msgs = [
1096 ControlMessage::AlgSetOp(&ALG_OP_ENCRYPT),
1097 ControlMessage::AlgSetIv(iv.as_slice()),
1098 ControlMessage::AlgSetAeadAssoclen(&assoc_size),
1099 ];
1100
1101 let iov = IoSlice::new(&payload);
1102 sendmsg::<()>(
1103 session_socket.as_raw_fd(),
1104 &[iov],
1105 &msgs,
1106 MsgFlags::empty(),
1107 None,
1108 )
1109 .expect("sendmsg encrypt");
1110
1111 // allocate buffer for encrypted data
1112 let mut encrypted =
1113 vec![0u8; (assoc_size as usize) + payload_len + auth_size];
1114 // SAFETY:
1115 // should be safe since session_socket won't be closed before the use of this borrowed one
1116 let borrowed_session_socket =
1117 unsafe { std::os::fd::BorrowedFd::borrow_raw(session_socket) };
1118 let num_bytes =
1119 read(borrowed_session_socket, &mut encrypted).expect("read encrypt");
1120 assert_eq!(num_bytes, payload_len + auth_size + (assoc_size as usize));
1121
1122 for i in 0..assoc_size {
1123 encrypted[i as usize] = 10;
1124 }
1125
1126 let iov = IoSlice::new(&encrypted);
1127
1128 let iv = vec![1u8; iv_len];
1129
1130 let session_socket = accept(sock.as_raw_fd()).expect("accept failed");
1131
1132 let msgs = [
1133 ControlMessage::AlgSetOp(&ALG_OP_DECRYPT),
1134 ControlMessage::AlgSetIv(iv.as_slice()),
1135 ControlMessage::AlgSetAeadAssoclen(&assoc_size),
1136 ];
1137 sendmsg::<()>(
1138 session_socket.as_raw_fd(),
1139 &[iov],
1140 &msgs,
1141 MsgFlags::empty(),
1142 None,
1143 )
1144 .expect("sendmsg decrypt");
1145
1146 // allocate buffer for decrypted data
1147 let mut decrypted =
1148 vec![0u8; payload_len + (assoc_size as usize) + auth_size];
1149 // Starting with kernel 4.9, the interface changed slightly such that the
1150 // authentication tag memory is only needed in the output buffer for encryption
1151 // and in the input buffer for decryption.
1152 // Do not block on read, as we may have fewer bytes than buffer size
1153
1154 // SAFETY:
1155 //
1156 // `session_socket` will be valid for the lifetime of this test
1157 // TODO: remove this workaround when accept(2) becomes I/O-safe.
1158 let borrowed_fd =
1159 unsafe { std::os::fd::BorrowedFd::borrow_raw(session_socket) };
1160 fcntl(borrowed_fd, FcntlArg::F_SETFL(OFlag::O_NONBLOCK))
1161 .expect("fcntl non_blocking");
1162 let num_bytes = read(borrowed_fd, &mut decrypted).expect("read decrypt");
1163
1164 assert!(num_bytes >= payload_len + (assoc_size as usize));
1165 assert_eq!(
1166 decrypted[(assoc_size as usize)..(payload_len + (assoc_size as usize))],
1167 payload[(assoc_size as usize)..payload_len + (assoc_size as usize)]
1168 );
1169 }
1170
1171 // Verify `ControlMessage::Ipv4PacketInfo` for `sendmsg`.
1172 // This creates a (udp) socket bound to localhost, then sends a message to
1173 // itself but uses Ipv4PacketInfo to force the source address to be localhost.
1174 //
1175 // This would be a more interesting test if we could assume that the test host
1176 // has more than one IP address (since we could select a different address to
1177 // test from).
1178 #[cfg(any(target_os = "linux", apple_targets, target_os = "netbsd"))]
1179 #[test]
1180 pub fn test_sendmsg_ipv4packetinfo() {
1181 use cfg_if::cfg_if;
1182 use nix::sys::socket::{
1183 bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags,
1184 SockFlag, SockType, SockaddrIn,
1185 };
1186 use std::io::IoSlice;
1187
1188 let sock = socket(
1189 AddressFamily::Inet,
1190 SockType::Datagram,
1191 SockFlag::empty(),
1192 None,
1193 )
1194 .expect("socket failed");
1195
1196 let sock_addr = SockaddrIn::new(127, 0, 0, 1, 4000);
1197
1198 bind(sock.as_raw_fd(), &sock_addr).expect("bind failed");
1199
1200 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1201 let iov = [IoSlice::new(&slice)];
1202
1203 cfg_if! {
1204 if #[cfg(target_os = "netbsd")] {
1205 let pi = libc::in_pktinfo {
1206 ipi_ifindex: 0, /* Unspecified interface */
1207 ipi_addr: libc::in_addr { s_addr: 0 },
1208 };
1209 } else {
1210 let pi = libc::in_pktinfo {
1211 ipi_ifindex: 0, /* Unspecified interface */
1212 ipi_addr: libc::in_addr { s_addr: 0 },
1213 ipi_spec_dst: sock_addr.as_ref().sin_addr,
1214 };
1215 }
1216 }
1217
1218 let cmsg = [ControlMessage::Ipv4PacketInfo(&pi)];
1219
1220 sendmsg(
1221 sock.as_raw_fd(),
1222 &iov,
1223 &cmsg,
1224 MsgFlags::empty(),
1225 Some(&sock_addr),
1226 )
1227 .expect("sendmsg");
1228 }
1229
1230 // Verify `ControlMessage::Ipv6PacketInfo` for `sendmsg`.
1231 // This creates a (udp) socket bound to ip6-localhost, then sends a message to
1232 // itself but uses Ipv6PacketInfo to force the source address to be
1233 // ip6-localhost.
1234 //
1235 // This would be a more interesting test if we could assume that the test host
1236 // has more than one IP address (since we could select a different address to
1237 // test from).
1238 #[cfg(any(
1239 target_os = "linux",
1240 apple_targets,
1241 target_os = "netbsd",
1242 target_os = "freebsd"
1243 ))]
1244 #[test]
1245 pub fn test_sendmsg_ipv6packetinfo() {
1246 use nix::errno::Errno;
1247 use nix::sys::socket::{
1248 bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags,
1249 SockFlag, SockType, SockaddrIn6,
1250 };
1251 use std::io::IoSlice;
1252
1253 let sock = socket(
1254 AddressFamily::Inet6,
1255 SockType::Datagram,
1256 SockFlag::empty(),
1257 None,
1258 )
1259 .expect("socket failed");
1260
1261 let std_sa = SocketAddrV6::from_str("[::1]:6000").unwrap();
1262 let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa);
1263
1264 if let Err(Errno::EADDRNOTAVAIL) = bind(sock.as_raw_fd(), &sock_addr) {
1265 println!("IPv6 not available, skipping test.");
1266 return;
1267 }
1268
1269 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1270 let iov = [IoSlice::new(&slice)];
1271
1272 let pi = libc::in6_pktinfo {
1273 ipi6_ifindex: 0, /* Unspecified interface */
1274 ipi6_addr: sock_addr.as_ref().sin6_addr,
1275 };
1276
1277 let cmsg = [ControlMessage::Ipv6PacketInfo(&pi)];
1278
1279 sendmsg::<SockaddrIn6>(
1280 sock.as_raw_fd(),
1281 &iov,
1282 &cmsg,
1283 MsgFlags::empty(),
1284 Some(&sock_addr),
1285 )
1286 .expect("sendmsg");
1287 }
1288
1289 // Verify that ControlMessage::Ipv4SendSrcAddr works for sendmsg. This
1290 // creates a UDP socket bound to all local interfaces (0.0.0.0). It then
1291 // sends message to itself at 127.0.0.1 while explicitly specifying
1292 // 127.0.0.1 as the source address through an Ipv4SendSrcAddr
1293 // (IP_SENDSRCADDR) control message.
1294 //
1295 // Note that binding to 0.0.0.0 is *required* on FreeBSD; sendmsg
1296 // returns EINVAL otherwise. (See FreeBSD's ip(4) man page.)
1297 #[cfg(any(freebsdlike, netbsdlike))]
1298 #[test]
1299 pub fn test_sendmsg_ipv4sendsrcaddr() {
1300 use nix::sys::socket::{
1301 bind, sendmsg, socket, AddressFamily, ControlMessage, MsgFlags,
1302 SockFlag, SockType, SockaddrIn,
1303 };
1304 use std::io::IoSlice;
1305
1306 let sock = socket(
1307 AddressFamily::Inet,
1308 SockType::Datagram,
1309 SockFlag::empty(),
1310 None,
1311 )
1312 .expect("socket failed");
1313
1314 let unspec_sock_addr = SockaddrIn::new(0, 0, 0, 0, 0);
1315 bind(sock.as_raw_fd(), &unspec_sock_addr).expect("bind failed");
1316 let bound_sock_addr: SockaddrIn = getsockname(sock.as_raw_fd()).unwrap();
1317 let localhost_sock_addr: SockaddrIn =
1318 SockaddrIn::new(127, 0, 0, 1, bound_sock_addr.port());
1319
1320 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1321 let iov = [IoSlice::new(&slice)];
1322 let cmsg = [ControlMessage::Ipv4SendSrcAddr(
1323 &localhost_sock_addr.as_ref().sin_addr,
1324 )];
1325
1326 sendmsg(
1327 sock.as_raw_fd(),
1328 &iov,
1329 &cmsg,
1330 MsgFlags::empty(),
1331 Some(&localhost_sock_addr),
1332 )
1333 .expect("sendmsg");
1334 }
1335
1336 /// Tests that passing multiple fds using a single `ControlMessage` works.
1337 // Disable the test on emulated platforms due to a bug in QEMU versions <
1338 // 2.12.0. https://bugs.launchpad.net/qemu/+bug/1701808
1339 #[cfg_attr(qemu, ignore)]
1340 #[test]
1341 #[cfg_attr(target_os = "cygwin", ignore)]
1342 fn test_scm_rights_single_cmsg_multiple_fds() {
1343 use nix::sys::socket::{
1344 recvmsg, sendmsg, ControlMessage, ControlMessageOwned, MsgFlags,
1345 };
1346 use std::io::{IoSlice, IoSliceMut};
1347 use std::os::unix::io::{AsRawFd, RawFd};
1348 use std::os::unix::net::UnixDatagram;
1349 use std::thread;
1350
1351 let (send, receive) = UnixDatagram::pair().unwrap();
1352 let thread = thread::spawn(move || {
1353 let mut buf = [0u8; 8];
1354 let mut iovec = [IoSliceMut::new(&mut buf)];
1355
1356 let mut space = cmsg_space!([RawFd; 2]);
1357 let msg = recvmsg::<()>(
1358 receive.as_raw_fd(),
1359 &mut iovec,
1360 Some(&mut space),
1361 MsgFlags::empty(),
1362 )
1363 .unwrap();
1364 assert!(!msg
1365 .flags
1366 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1367
1368 let mut cmsgs = msg.cmsgs().unwrap();
1369 match cmsgs.next() {
1370 Some(ControlMessageOwned::ScmRights(fds)) => {
1371 assert_eq!(
1372 fds.len(),
1373 2,
1374 "unexpected fd count (expected 2 fds, got {})",
1375 fds.len()
1376 );
1377 }
1378 _ => panic!(),
1379 }
1380 assert!(cmsgs.next().is_none(), "unexpected control msg");
1381
1382 assert_eq!(msg.bytes, 8);
1383 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
1384 });
1385
1386 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1387 let iov = [IoSlice::new(&slice)];
1388 let fds = [libc::STDIN_FILENO, libc::STDOUT_FILENO]; // pass stdin and stdout
1389 let cmsg = [ControlMessage::ScmRights(&fds)];
1390 sendmsg::<()>(send.as_raw_fd(), &iov, &cmsg, MsgFlags::empty(), None)
1391 .unwrap();
1392 thread.join().unwrap();
1393 }
1394
1395 // Verify `sendmsg` builds a valid `msghdr` when passing an empty
1396 // `cmsgs` argument. This should result in a msghdr with a nullptr
1397 // msg_control field and a msg_controllen of 0 when calling into the
1398 // raw `sendmsg`.
1399 #[test]
1400 pub fn test_sendmsg_empty_cmsgs() {
1401 use nix::sys::socket::{
1402 recvmsg, sendmsg, socketpair, AddressFamily, MsgFlags, SockFlag,
1403 SockType,
1404 };
1405 use std::io::{IoSlice, IoSliceMut};
1406
1407 let (fd1, fd2) = socketpair(
1408 AddressFamily::Unix,
1409 SockType::Stream,
1410 None,
1411 SockFlag::empty(),
1412 )
1413 .unwrap();
1414
1415 {
1416 let iov = [IoSlice::new(b"hello")];
1417 assert_eq!(
1418 sendmsg::<()>(fd1.as_raw_fd(), &iov, &[], MsgFlags::empty(), None)
1419 .unwrap(),
1420 5
1421 );
1422 }
1423
1424 {
1425 let mut buf = [0u8; 5];
1426 let mut iov = [IoSliceMut::new(&mut buf[..])];
1427
1428 let mut cmsgspace = cmsg_space!([RawFd; 1]);
1429 let msg = recvmsg::<()>(
1430 fd2.as_raw_fd(),
1431 &mut iov,
1432 Some(&mut cmsgspace),
1433 MsgFlags::empty(),
1434 )
1435 .unwrap();
1436
1437 if msg.cmsgs().unwrap().next().is_some() {
1438 panic!("unexpected cmsg");
1439 }
1440 assert!(!msg
1441 .flags
1442 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1443 assert_eq!(msg.bytes, 5);
1444 }
1445 }
1446
1447 #[cfg(any(linux_android, freebsdlike))]
1448 #[test]
1449 fn test_scm_credentials() {
1450 use nix::sys::socket::{
1451 recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage,
1452 ControlMessageOwned, MsgFlags, SockFlag, SockType, UnixCredentials,
1453 };
1454 #[cfg(linux_android)]
1455 use nix::sys::socket::{setsockopt, sockopt::PassCred};
1456 use nix::unistd::{getgid, getpid, getuid};
1457 use std::io::{IoSlice, IoSliceMut};
1458
1459 let (send, recv) = socketpair(
1460 AddressFamily::Unix,
1461 SockType::Stream,
1462 None,
1463 SockFlag::empty(),
1464 )
1465 .unwrap();
1466 #[cfg(linux_android)]
1467 setsockopt(&recv, PassCred, &true).unwrap();
1468
1469 {
1470 let iov = [IoSlice::new(b"hello")];
1471 #[cfg(linux_android)]
1472 let cred = UnixCredentials::new();
1473 #[cfg(linux_android)]
1474 let cmsg = ControlMessage::ScmCredentials(&cred);
1475 #[cfg(freebsdlike)]
1476 let cmsg = ControlMessage::ScmCreds;
1477 assert_eq!(
1478 sendmsg::<()>(
1479 send.as_raw_fd(),
1480 &iov,
1481 &[cmsg],
1482 MsgFlags::empty(),
1483 None
1484 )
1485 .unwrap(),
1486 5
1487 );
1488 }
1489
1490 {
1491 let mut buf = [0u8; 5];
1492 let mut iov = [IoSliceMut::new(&mut buf[..])];
1493
1494 let mut cmsgspace = cmsg_space!(UnixCredentials);
1495 let msg = recvmsg::<()>(
1496 recv.as_raw_fd(),
1497 &mut iov,
1498 Some(&mut cmsgspace),
1499 MsgFlags::empty(),
1500 )
1501 .unwrap();
1502 let mut received_cred = None;
1503
1504 for cmsg in msg.cmsgs().unwrap() {
1505 let cred = match cmsg {
1506 #[cfg(linux_android)]
1507 ControlMessageOwned::ScmCredentials(cred) => cred,
1508 #[cfg(freebsdlike)]
1509 ControlMessageOwned::ScmCreds(cred) => cred,
1510 other => panic!("unexpected cmsg {other:?}"),
1511 };
1512 assert!(received_cred.is_none());
1513 assert_eq!(cred.pid(), getpid().as_raw());
1514 assert_eq!(cred.uid(), getuid().as_raw());
1515 assert_eq!(cred.gid(), getgid().as_raw());
1516 received_cred = Some(cred);
1517 }
1518 received_cred.expect("no creds received");
1519 assert_eq!(msg.bytes, 5);
1520 assert!(!msg
1521 .flags
1522 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1523 }
1524 }
1525
1526 /// Ensure that we can send `SCM_CREDENTIALS` and `SCM_RIGHTS` with a single
1527 /// `sendmsg` call.
1528 #[cfg(linux_android)]
1529 // qemu's handling of multiple cmsgs is bugged, ignore tests under emulation
1530 // see https://bugs.launchpad.net/qemu/+bug/1781280
1531 #[cfg_attr(qemu, ignore)]
1532 #[test]
1533 fn test_scm_credentials_and_rights() {
1534 let space = cmsg_space!(libc::ucred, RawFd);
1535 test_impl_scm_credentials_and_rights(space).unwrap();
1536 }
1537
1538 /// Ensure that passing a an oversized control message buffer to recvmsg
1539 /// still works.
1540 #[cfg(linux_android)]
1541 // qemu's handling of multiple cmsgs is bugged, ignore tests under emulation
1542 // see https://bugs.launchpad.net/qemu/+bug/1781280
1543 #[cfg_attr(qemu, ignore)]
1544 #[test]
1545 fn test_too_large_cmsgspace() {
1546 let space = vec![0u8; 1024];
1547 test_impl_scm_credentials_and_rights(space).unwrap();
1548 }
1549
1550 #[cfg(linux_android)]
1551 #[test]
1552 fn test_too_small_cmsgspace() {
1553 let space = vec![0u8; 4];
1554 assert_eq!(
1555 test_impl_scm_credentials_and_rights(space),
1556 Err(nix::errno::Errno::ENOBUFS)
1557 );
1558 }
1559
1560 #[cfg(linux_android)]
1561 fn test_impl_scm_credentials_and_rights(
1562 mut space: Vec<u8>,
1563 ) -> Result<(), nix::errno::Errno> {
1564 use libc::ucred;
1565 use nix::sys::socket::sockopt::PassCred;
1566 use nix::sys::socket::{
1567 recvmsg, sendmsg, setsockopt, socketpair, ControlMessage,
1568 ControlMessageOwned, MsgFlags, SockFlag, SockType,
1569 };
1570 use nix::unistd::{close, getgid, getpid, getuid, pipe, write};
1571 use std::io::{IoSlice, IoSliceMut};
1572
1573 let (send, recv) = socketpair(
1574 AddressFamily::Unix,
1575 SockType::Stream,
1576 None,
1577 SockFlag::empty(),
1578 )
1579 .unwrap();
1580 setsockopt(&recv, PassCred, &true).unwrap();
1581
1582 let (r, w) = pipe().unwrap();
1583 let mut received_r: Option<RawFd> = None;
1584
1585 {
1586 let iov = [IoSlice::new(b"hello")];
1587 let cred = ucred {
1588 pid: getpid().as_raw(),
1589 uid: getuid().as_raw(),
1590 gid: getgid().as_raw(),
1591 }
1592 .into();
1593 let fds = [r.as_raw_fd()];
1594 let cmsgs = [
1595 ControlMessage::ScmCredentials(&cred),
1596 ControlMessage::ScmRights(&fds),
1597 ];
1598 assert_eq!(
1599 sendmsg::<()>(
1600 send.as_raw_fd(),
1601 &iov,
1602 &cmsgs,
1603 MsgFlags::empty(),
1604 None
1605 )
1606 .unwrap(),
1607 5
1608 );
1609 }
1610
1611 {
1612 let mut buf = [0u8; 5];
1613 let mut iov = [IoSliceMut::new(&mut buf[..])];
1614 let msg = recvmsg::<()>(
1615 recv.as_raw_fd(),
1616 &mut iov,
1617 Some(&mut space),
1618 MsgFlags::empty(),
1619 )
1620 .unwrap();
1621 let mut received_cred = None;
1622
1623 assert_eq!(msg.cmsgs()?.count(), 2, "expected 2 cmsgs");
1624
1625 for cmsg in msg.cmsgs()? {
1626 match cmsg {
1627 ControlMessageOwned::ScmRights(fds) => {
1628 assert_eq!(received_r, None, "already received fd");
1629 assert_eq!(fds.len(), 1);
1630 received_r = Some(fds[0]);
1631 }
1632 ControlMessageOwned::ScmCredentials(cred) => {
1633 assert!(received_cred.is_none());
1634 assert_eq!(cred.pid(), getpid().as_raw());
1635 assert_eq!(cred.uid(), getuid().as_raw());
1636 assert_eq!(cred.gid(), getgid().as_raw());
1637 received_cred = Some(cred);
1638 }
1639 _ => panic!("unexpected cmsg"),
1640 }
1641 }
1642 received_cred.expect("no creds received");
1643 assert_eq!(msg.bytes, 5);
1644 assert!(!msg
1645 .flags
1646 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1647 }
1648
1649 let received_r = received_r.expect("Did not receive passed fd");
1650 // Ensure that the received file descriptor works
1651 write(&w, b"world").unwrap();
1652 let mut buf = [0u8; 5];
1653 // SAFETY:
1654 // It should be safe if we don't use this BorrowedFd after close.
1655 let received_r_borrowed =
1656 unsafe { std::os::fd::BorrowedFd::borrow_raw(received_r) };
1657 read(received_r_borrowed, &mut buf).unwrap();
1658 assert_eq!(&buf[..], b"world");
1659 close(received_r).unwrap();
1660
1661 Ok(())
1662 }
1663
1664 // Test creating and using named unix domain sockets
1665 #[test]
1666 pub fn test_named_unixdomain() {
1667 use nix::sys::socket::{
1668 accept, bind, connect, listen, socket, Backlog, UnixAddr,
1669 };
1670 use nix::sys::socket::{SockFlag, SockType};
1671 use nix::unistd::{read, write};
1672 use std::thread;
1673
1674 let tempdir = tempfile::tempdir().unwrap();
1675 let sockname = tempdir.path().join("sock");
1676 let s1 = socket(
1677 AddressFamily::Unix,
1678 SockType::Stream,
1679 SockFlag::empty(),
1680 None,
1681 )
1682 .expect("socket failed");
1683 let sockaddr = UnixAddr::new(&sockname).unwrap();
1684 bind(s1.as_raw_fd(), &sockaddr).expect("bind failed");
1685 listen(&s1, Backlog::new(10).unwrap()).expect("listen failed");
1686
1687 let thr = thread::spawn(move || {
1688 let s2 = socket(
1689 AddressFamily::Unix,
1690 SockType::Stream,
1691 SockFlag::empty(),
1692 None,
1693 )
1694 .expect("socket failed");
1695 connect(s2.as_raw_fd(), &sockaddr).expect("connect failed");
1696 write(&s2, b"hello").expect("write failed");
1697 });
1698
1699 let s3 = accept(s1.as_raw_fd()).expect("accept failed");
1700
1701 // SAFETY:
1702 // It should be safe considering that s3 will be open within this test
1703 let s3 = unsafe { std::os::fd::BorrowedFd::borrow_raw(s3) };
1704 let mut buf = [0; 5];
1705 read(s3, &mut buf).unwrap();
1706 thr.join().unwrap();
1707
1708 assert_eq!(&buf[..], b"hello");
1709 }
1710
1711 #[test]
1712 pub fn test_listen_maxbacklog() {
1713 use nix::sys::socket::Backlog;
1714
1715 assert!(Backlog::new(libc::SOMAXCONN).is_ok());
1716 }
1717
1718 #[test]
1719 pub fn test_listen_wrongbacklog() {
1720 use nix::sys::socket::Backlog;
1721
1722 #[cfg(not(target_os = "cygwin"))]
1723 assert!(Backlog::new(libc::SOMAXCONN + 1).is_err());
1724 assert!(Backlog::new(-2).is_err());
1725 }
1726
1727 // Test using unnamed unix domain addresses
1728 #[cfg(linux_android)]
1729 #[test]
1730 pub fn test_unnamed_unixdomain() {
1731 use nix::sys::socket::{getsockname, socketpair};
1732 use nix::sys::socket::{SockFlag, SockType};
1733
1734 let (fd_1, _fd_2) = socketpair(
1735 AddressFamily::Unix,
1736 SockType::Stream,
1737 None,
1738 SockFlag::empty(),
1739 )
1740 .expect("socketpair failed");
1741
1742 let addr_1: UnixAddr =
1743 getsockname(fd_1.as_raw_fd()).expect("getsockname failed");
1744 assert!(addr_1.is_unnamed());
1745 }
1746
1747 // Test creating and using unnamed unix domain addresses for autobinding sockets
1748 #[cfg(linux_android)]
1749 #[test]
1750 pub fn test_unnamed_unixdomain_autobind() {
1751 use nix::sys::socket::{bind, getsockname, socket};
1752 use nix::sys::socket::{SockFlag, SockType};
1753
1754 let fd = socket(
1755 AddressFamily::Unix,
1756 SockType::Stream,
1757 SockFlag::empty(),
1758 None,
1759 )
1760 .expect("socket failed");
1761
1762 // unix(7): "If a bind(2) call specifies addrlen as `sizeof(sa_family_t)`, or [...], then the
1763 // socket is autobound to an abstract address"
1764 bind(fd.as_raw_fd(), &UnixAddr::new_unnamed()).expect("bind failed");
1765
1766 let addr: UnixAddr =
1767 getsockname(fd.as_raw_fd()).expect("getsockname failed");
1768 let addr = addr.as_abstract().unwrap();
1769
1770 // changed from 8 to 5 bytes in Linux 2.3.15, and rust's minimum supported Linux version is 3.2
1771 // (as of 2022-11)
1772 assert_eq!(addr.len(), 5);
1773 }
1774
1775 // Test creating and using named system control sockets
1776 #[cfg(apple_targets)]
1777 #[test]
1778 pub fn test_syscontrol() {
1779 use nix::errno::Errno;
1780 use nix::sys::socket::{
1781 socket, SockFlag, SockProtocol, SockType, SysControlAddr,
1782 };
1783
1784 let fd = socket(
1785 AddressFamily::System,
1786 SockType::Datagram,
1787 SockFlag::empty(),
1788 SockProtocol::KextControl,
1789 )
1790 .expect("socket failed");
1791 SysControlAddr::from_name(fd.as_raw_fd(), "com.apple.net.utun_control", 0)
1792 .expect("resolving sys_control name failed");
1793 assert_eq!(
1794 SysControlAddr::from_name(fd.as_raw_fd(), "foo.bar.lol", 0).err(),
1795 Some(Errno::ENOENT)
1796 );
1797
1798 // requires root privileges
1799 // connect(fd.as_raw_fd(), &sockaddr).expect("connect failed");
1800 }
1801
1802 #[cfg(any(bsd, linux_android))]
1803 fn loopback_address(
1804 family: AddressFamily,
1805 ) -> Option<nix::ifaddrs::InterfaceAddress> {
1806 use nix::ifaddrs::getifaddrs;
1807 use nix::net::if_::*;
1808 use nix::sys::socket::SockaddrLike;
1809 use std::io;
1810 use std::io::Write;
1811
1812 let mut addrs = match getifaddrs() {
1813 Ok(iter) => iter,
1814 Err(e) => {
1815 let stdioerr = io::stderr();
1816 let mut handle = stdioerr.lock();
1817 writeln!(handle, "getifaddrs: {e:?}").unwrap();
1818 return None;
1819 }
1820 };
1821 // return first address matching family
1822 addrs.find(|ifaddr| {
1823 ifaddr.flags.contains(InterfaceFlags::IFF_LOOPBACK)
1824 && ifaddr.address.as_ref().and_then(SockaddrLike::family)
1825 == Some(family)
1826 })
1827 }
1828
1829 #[cfg(any(linux_android, apple_targets, target_os = "netbsd"))]
1830 // qemu doesn't seem to be emulating this correctly in these architectures
1831 #[cfg_attr(
1832 all(
1833 qemu,
1834 any(
1835 target_arch = "mips",
1836 target_arch = "mips32r6",
1837 target_arch = "mips64",
1838 target_arch = "mips64r6",
1839 target_arch = "powerpc64",
1840 )
1841 ),
1842 ignore
1843 )]
1844 #[test]
1845 pub fn test_recv_ipv4pktinfo() {
1846 use nix::net::if_::*;
1847 use nix::sys::socket::sockopt::Ipv4PacketInfo;
1848 use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn};
1849 use nix::sys::socket::{getsockname, setsockopt, socket};
1850 use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags};
1851 use std::io::{IoSlice, IoSliceMut};
1852
1853 let lo_ifaddr = loopback_address(AddressFamily::Inet);
1854 let (lo_name, lo) = match lo_ifaddr {
1855 Some(ifaddr) => (
1856 ifaddr.interface_name,
1857 ifaddr.address.expect("Expect IPv4 address on interface"),
1858 ),
1859 None => return,
1860 };
1861 let receive = socket(
1862 AddressFamily::Inet,
1863 SockType::Datagram,
1864 SockFlag::empty(),
1865 None,
1866 )
1867 .expect("receive socket failed");
1868 bind(receive.as_raw_fd(), &lo).expect("bind failed");
1869 let sa: SockaddrIn =
1870 getsockname(receive.as_raw_fd()).expect("getsockname failed");
1871 setsockopt(&receive, Ipv4PacketInfo, &true).expect("setsockopt failed");
1872
1873 {
1874 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1875 let iov = [IoSlice::new(&slice)];
1876
1877 let send = socket(
1878 AddressFamily::Inet,
1879 SockType::Datagram,
1880 SockFlag::empty(),
1881 None,
1882 )
1883 .expect("send socket failed");
1884 sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa))
1885 .expect("sendmsg failed");
1886 }
1887
1888 {
1889 let mut buf = [0u8; 8];
1890 let mut iovec = [IoSliceMut::new(&mut buf)];
1891
1892 let mut space = cmsg_space!(libc::in_pktinfo);
1893 let msg = recvmsg::<()>(
1894 receive.as_raw_fd(),
1895 &mut iovec,
1896 Some(&mut space),
1897 MsgFlags::empty(),
1898 )
1899 .expect("recvmsg failed");
1900 assert!(!msg
1901 .flags
1902 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1903
1904 let mut cmsgs = msg.cmsgs().unwrap();
1905 if let Some(ControlMessageOwned::Ipv4PacketInfo(pktinfo)) = cmsgs.next()
1906 {
1907 let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex");
1908 assert_eq!(
1909 pktinfo.ipi_ifindex as libc::c_uint, i,
1910 "unexpected ifindex (expected {}, got {})",
1911 i, pktinfo.ipi_ifindex
1912 );
1913 }
1914 assert!(cmsgs.next().is_none(), "unexpected additional control msg");
1915 assert_eq!(msg.bytes, 8);
1916 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
1917 }
1918 }
1919
1920 #[cfg(bsd)]
1921 // qemu doesn't seem to be emulating this correctly in these architectures
1922 #[cfg_attr(
1923 all(
1924 qemu,
1925 any(
1926 target_arch = "mips",
1927 target_arch = "mips32r6",
1928 target_arch = "mips64",
1929 target_arch = "mips64r6",
1930 target_arch = "powerpc64",
1931 )
1932 ),
1933 ignore
1934 )]
1935 #[test]
1936 pub fn test_recvif() {
1937 use nix::net::if_::*;
1938 use nix::sys::socket::sockopt::{Ipv4RecvDstAddr, Ipv4RecvIf};
1939 use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn};
1940 use nix::sys::socket::{getsockname, setsockopt, socket};
1941 use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags};
1942 use std::io::{IoSlice, IoSliceMut};
1943
1944 let lo_ifaddr = loopback_address(AddressFamily::Inet);
1945 let (lo_name, lo) = match lo_ifaddr {
1946 Some(ifaddr) => (
1947 ifaddr.interface_name,
1948 ifaddr.address.expect("Expect IPv4 address on interface"),
1949 ),
1950 None => return,
1951 };
1952 let receive = socket(
1953 AddressFamily::Inet,
1954 SockType::Datagram,
1955 SockFlag::empty(),
1956 None,
1957 )
1958 .expect("receive socket failed");
1959 bind(receive.as_raw_fd(), &lo).expect("bind failed");
1960 let sa: SockaddrIn =
1961 getsockname(receive.as_raw_fd()).expect("getsockname failed");
1962 setsockopt(&receive, Ipv4RecvIf, &true)
1963 .expect("setsockopt IP_RECVIF failed");
1964 setsockopt(&receive, Ipv4RecvDstAddr, &true)
1965 .expect("setsockopt IP_RECVDSTADDR failed");
1966
1967 {
1968 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
1969 let iov = [IoSlice::new(&slice)];
1970
1971 let send = socket(
1972 AddressFamily::Inet,
1973 SockType::Datagram,
1974 SockFlag::empty(),
1975 None,
1976 )
1977 .expect("send socket failed");
1978 sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa))
1979 .expect("sendmsg failed");
1980 }
1981
1982 {
1983 let mut buf = [0u8; 8];
1984 let mut iovec = [IoSliceMut::new(&mut buf)];
1985 let mut space = cmsg_space!(libc::sockaddr_dl, libc::in_addr);
1986 let msg = recvmsg::<()>(
1987 receive.as_raw_fd(),
1988 &mut iovec,
1989 Some(&mut space),
1990 MsgFlags::empty(),
1991 )
1992 .expect("recvmsg failed");
1993 assert!(!msg
1994 .flags
1995 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
1996 assert_eq!(msg.cmsgs().unwrap().count(), 2, "expected 2 cmsgs");
1997
1998 let mut rx_recvif = false;
1999 let mut rx_recvdstaddr = false;
2000 for cmsg in msg.cmsgs().unwrap() {
2001 match cmsg {
2002 ControlMessageOwned::Ipv4RecvIf(dl) => {
2003 rx_recvif = true;
2004 let i = if_nametoindex(lo_name.as_bytes())
2005 .expect("if_nametoindex");
2006 assert_eq!(
2007 dl.sdl_index as libc::c_uint, i,
2008 "unexpected ifindex (expected {}, got {})",
2009 i, dl.sdl_index
2010 );
2011 }
2012 ControlMessageOwned::Ipv4RecvDstAddr(addr) => {
2013 rx_recvdstaddr = true;
2014 if let Some(sin) = lo.as_sockaddr_in() {
2015 assert_eq!(sin.as_ref().sin_addr.s_addr,
2016 addr.s_addr,
2017 "unexpected destination address (expected {}, got {})",
2018 sin.as_ref().sin_addr.s_addr,
2019 addr.s_addr);
2020 } else {
2021 panic!("unexpected Sockaddr");
2022 }
2023 }
2024 _ => panic!("unexpected additional control msg"),
2025 }
2026 }
2027 assert!(rx_recvif);
2028 assert!(rx_recvdstaddr);
2029 assert_eq!(msg.bytes, 8);
2030 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
2031 }
2032 }
2033
2034 #[cfg(any(linux_android, target_os = "freebsd"))]
2035 #[cfg_attr(qemu, ignore)]
2036 #[test]
2037 pub fn test_recvif_ipv4() {
2038 use nix::sys::socket::sockopt::Ipv4OrigDstAddr;
2039 use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn};
2040 use nix::sys::socket::{getsockname, setsockopt, socket};
2041 use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags};
2042 use std::io::{IoSlice, IoSliceMut};
2043
2044 let lo_ifaddr = loopback_address(AddressFamily::Inet);
2045 let (_lo_name, lo) = match lo_ifaddr {
2046 Some(ifaddr) => (
2047 ifaddr.interface_name,
2048 ifaddr.address.expect("Expect IPv4 address on interface"),
2049 ),
2050 None => return,
2051 };
2052 let receive = socket(
2053 AddressFamily::Inet,
2054 SockType::Datagram,
2055 SockFlag::empty(),
2056 None,
2057 )
2058 .expect("receive socket failed");
2059 bind(receive.as_raw_fd(), &lo).expect("bind failed");
2060 let sa: SockaddrIn =
2061 getsockname(receive.as_raw_fd()).expect("getsockname failed");
2062 setsockopt(&receive, Ipv4OrigDstAddr, &true)
2063 .expect("setsockopt IP_ORIGDSTADDR failed");
2064
2065 {
2066 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
2067 let iov = [IoSlice::new(&slice)];
2068
2069 let send = socket(
2070 AddressFamily::Inet,
2071 SockType::Datagram,
2072 SockFlag::empty(),
2073 None,
2074 )
2075 .expect("send socket failed");
2076 sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa))
2077 .expect("sendmsg failed");
2078 }
2079
2080 {
2081 let mut buf = [0u8; 8];
2082 let mut iovec = [IoSliceMut::new(&mut buf)];
2083 let mut space = cmsg_space!(libc::sockaddr_in);
2084 let msg = recvmsg::<()>(
2085 receive.as_raw_fd(),
2086 &mut iovec,
2087 Some(&mut space),
2088 MsgFlags::empty(),
2089 )
2090 .expect("recvmsg failed");
2091 assert!(!msg
2092 .flags
2093 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
2094 assert_eq!(msg.cmsgs().unwrap().count(), 1, "expected 1 cmsgs");
2095
2096 let mut rx_recvorigdstaddr = false;
2097 for cmsg in msg.cmsgs().unwrap() {
2098 match cmsg {
2099 ControlMessageOwned::Ipv4OrigDstAddr(addr) => {
2100 rx_recvorigdstaddr = true;
2101 if let Some(sin) = lo.as_sockaddr_in() {
2102 assert_eq!(sin.as_ref().sin_addr.s_addr,
2103 addr.sin_addr.s_addr,
2104 "unexpected destination address (expected {}, got {})",
2105 sin.as_ref().sin_addr.s_addr,
2106 addr.sin_addr.s_addr);
2107 } else {
2108 panic!("unexpected Sockaddr");
2109 }
2110 }
2111 _ => panic!("unexpected additional control msg"),
2112 }
2113 }
2114 assert!(rx_recvorigdstaddr);
2115 assert_eq!(msg.bytes, 8);
2116 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
2117 }
2118 }
2119
2120 #[cfg(any(
2121 all(linux_android, not(target_env = "uclibc")),
2122 target_os = "freebsd"
2123 ))]
2124 #[cfg_attr(qemu, ignore)]
2125 #[test]
2126 pub fn test_recvif_ipv6() {
2127 use nix::sys::socket::sockopt::Ipv6OrigDstAddr;
2128 use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn6};
2129 use nix::sys::socket::{getsockname, setsockopt, socket};
2130 use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags};
2131 use std::io::{IoSlice, IoSliceMut};
2132
2133 let lo_ifaddr = loopback_address(AddressFamily::Inet6);
2134 let (_lo_name, lo) = match lo_ifaddr {
2135 Some(ifaddr) => (
2136 ifaddr.interface_name,
2137 ifaddr.address.expect("Expect IPv6 address on interface"),
2138 ),
2139 None => return,
2140 };
2141 let receive = socket(
2142 AddressFamily::Inet6,
2143 SockType::Datagram,
2144 SockFlag::empty(),
2145 None,
2146 )
2147 .expect("receive socket failed");
2148 bind(receive.as_raw_fd(), &lo).expect("bind failed");
2149 let sa: SockaddrIn6 =
2150 getsockname(receive.as_raw_fd()).expect("getsockname failed");
2151 setsockopt(&receive, Ipv6OrigDstAddr, &true)
2152 .expect("setsockopt IP_ORIGDSTADDR failed");
2153
2154 {
2155 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
2156 let iov = [IoSlice::new(&slice)];
2157
2158 let send = socket(
2159 AddressFamily::Inet6,
2160 SockType::Datagram,
2161 SockFlag::empty(),
2162 None,
2163 )
2164 .expect("send socket failed");
2165 sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa))
2166 .expect("sendmsg failed");
2167 }
2168
2169 {
2170 let mut buf = [0u8; 8];
2171 let mut iovec = [IoSliceMut::new(&mut buf)];
2172 let mut space = cmsg_space!(libc::sockaddr_in6);
2173 let msg = recvmsg::<()>(
2174 receive.as_raw_fd(),
2175 &mut iovec,
2176 Some(&mut space),
2177 MsgFlags::empty(),
2178 )
2179 .expect("recvmsg failed");
2180 assert!(!msg
2181 .flags
2182 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
2183 assert_eq!(msg.cmsgs().unwrap().count(), 1, "expected 1 cmsgs");
2184
2185 let mut rx_recvorigdstaddr = false;
2186 for cmsg in msg.cmsgs().unwrap() {
2187 match cmsg {
2188 ControlMessageOwned::Ipv6OrigDstAddr(addr) => {
2189 rx_recvorigdstaddr = true;
2190 if let Some(sin) = lo.as_sockaddr_in6() {
2191 assert_eq!(sin.as_ref().sin6_addr.s6_addr,
2192 addr.sin6_addr.s6_addr,
2193 "unexpected destination address (expected {:?}, got {:?})",
2194 sin.as_ref().sin6_addr.s6_addr,
2195 addr.sin6_addr.s6_addr);
2196 } else {
2197 panic!("unexpected Sockaddr");
2198 }
2199 }
2200 _ => panic!("unexpected additional control msg"),
2201 }
2202 }
2203 assert!(rx_recvorigdstaddr);
2204 assert_eq!(msg.bytes, 8);
2205 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
2206 }
2207 }
2208
2209 #[cfg(any(linux_android, target_os = "freebsd", apple_targets, netbsdlike))]
2210 // qemu doesn't seem to be emulating this correctly in these architectures
2211 #[cfg_attr(
2212 all(
2213 qemu,
2214 any(
2215 target_arch = "mips",
2216 target_arch = "mips32r6",
2217 target_arch = "mips64",
2218 target_arch = "mips64r6",
2219 target_arch = "powerpc64",
2220 )
2221 ),
2222 ignore
2223 )]
2224 #[test]
2225 pub fn test_recv_ipv6pktinfo() {
2226 use nix::net::if_::*;
2227 use nix::sys::socket::sockopt::Ipv6RecvPacketInfo;
2228 use nix::sys::socket::{bind, SockFlag, SockType, SockaddrIn6};
2229 use nix::sys::socket::{getsockname, setsockopt, socket};
2230 use nix::sys::socket::{recvmsg, sendmsg, ControlMessageOwned, MsgFlags};
2231 use std::io::{IoSlice, IoSliceMut};
2232
2233 let lo_ifaddr = loopback_address(AddressFamily::Inet6);
2234 let (lo_name, lo) = match lo_ifaddr {
2235 Some(ifaddr) => (
2236 ifaddr.interface_name,
2237 ifaddr.address.expect("Expect IPv6 address on interface"),
2238 ),
2239 None => return,
2240 };
2241 let receive = socket(
2242 AddressFamily::Inet6,
2243 SockType::Datagram,
2244 SockFlag::empty(),
2245 None,
2246 )
2247 .expect("receive socket failed");
2248 bind(receive.as_raw_fd(), &lo).expect("bind failed");
2249 let sa: SockaddrIn6 =
2250 getsockname(receive.as_raw_fd()).expect("getsockname failed");
2251 setsockopt(&receive, Ipv6RecvPacketInfo, &true).expect("setsockopt failed");
2252
2253 {
2254 let slice = [1u8, 2, 3, 4, 5, 6, 7, 8];
2255 let iov = [IoSlice::new(&slice)];
2256
2257 let send = socket(
2258 AddressFamily::Inet6,
2259 SockType::Datagram,
2260 SockFlag::empty(),
2261 None,
2262 )
2263 .expect("send socket failed");
2264 sendmsg(send.as_raw_fd(), &iov, &[], MsgFlags::empty(), Some(&sa))
2265 .expect("sendmsg failed");
2266 }
2267
2268 {
2269 let mut buf = [0u8; 8];
2270 let mut iovec = [IoSliceMut::new(&mut buf)];
2271
2272 let mut space = cmsg_space!(libc::in6_pktinfo);
2273 let msg = recvmsg::<()>(
2274 receive.as_raw_fd(),
2275 &mut iovec,
2276 Some(&mut space),
2277 MsgFlags::empty(),
2278 )
2279 .expect("recvmsg failed");
2280 assert!(!msg
2281 .flags
2282 .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC));
2283
2284 let mut cmsgs = msg.cmsgs().unwrap();
2285 if let Some(ControlMessageOwned::Ipv6PacketInfo(pktinfo)) = cmsgs.next()
2286 {
2287 let i = if_nametoindex(lo_name.as_bytes()).expect("if_nametoindex");
2288 assert_eq!(
2289 pktinfo.ipi6_ifindex as libc::c_uint, i,
2290 "unexpected ifindex (expected {}, got {})",
2291 i, pktinfo.ipi6_ifindex
2292 );
2293 }
2294 assert!(cmsgs.next().is_none(), "unexpected additional control msg");
2295 assert_eq!(msg.bytes, 8);
2296 assert_eq!(*iovec[0], [1u8, 2, 3, 4, 5, 6, 7, 8]);
2297 }
2298 }
2299
2300 #[cfg(linux_android)]
2301 #[test]
2302 pub fn test_vsock() {
2303 use nix::sys::socket::SockaddrLike;
2304 use nix::sys::socket::{AddressFamily, VsockAddr};
2305 use std::mem;
2306
2307 let port: u32 = 3000;
2308
2309 let addr_local = VsockAddr::new(libc::VMADDR_CID_LOCAL, port);
2310 assert_eq!(addr_local.cid(), libc::VMADDR_CID_LOCAL);
2311 assert_eq!(addr_local.port(), port);
2312
2313 let addr_any = VsockAddr::new(libc::VMADDR_CID_ANY, libc::VMADDR_PORT_ANY);
2314 assert_eq!(addr_any.cid(), libc::VMADDR_CID_ANY);
2315 assert_eq!(addr_any.port(), libc::VMADDR_PORT_ANY);
2316
2317 assert_ne!(addr_local, addr_any);
2318 assert_ne!(calculate_hash(&addr_local), calculate_hash(&addr_any));
2319
2320 let addr1 = VsockAddr::new(libc::VMADDR_CID_HOST, port);
2321 let addr2 = VsockAddr::new(libc::VMADDR_CID_HOST, port);
2322 assert_eq!(addr1, addr2);
2323 assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2));
2324
2325 let addr3 = unsafe {
2326 VsockAddr::from_raw(
2327 addr2.as_ref() as *const libc::sockaddr_vm as *const libc::sockaddr,
2328 Some(mem::size_of::<libc::sockaddr_vm>().try_into().unwrap()),
2329 )
2330 }
2331 .unwrap();
2332 assert_eq!(
2333 addr3.as_ref().svm_family,
2334 AddressFamily::Vsock as libc::sa_family_t
2335 );
2336 assert_eq!(addr3.as_ref().svm_cid, addr1.cid());
2337 assert_eq!(addr3.as_ref().svm_port, addr1.port());
2338 }
2339
2340 #[cfg(apple_targets)]
2341 #[test]
2342 pub fn test_vsock() {
2343 use nix::sys::socket::SockaddrLike;
2344 use nix::sys::socket::{AddressFamily, VsockAddr};
2345 use std::mem;
2346
2347 let port: u32 = 3000;
2348
2349 // macOS doesn't have a VMADDR_CID_LOCAL, so test with host again
2350 let addr_host = VsockAddr::new(libc::VMADDR_CID_HOST, port);
2351 assert_eq!(addr_host.cid(), libc::VMADDR_CID_HOST);
2352 assert_eq!(addr_host.port(), port);
2353
2354 let addr_any = VsockAddr::new(libc::VMADDR_CID_ANY, libc::VMADDR_PORT_ANY);
2355 assert_eq!(addr_any.cid(), libc::VMADDR_CID_ANY);
2356 assert_eq!(addr_any.port(), libc::VMADDR_PORT_ANY);
2357
2358 assert_ne!(addr_host, addr_any);
2359 assert_ne!(calculate_hash(&addr_host), calculate_hash(&addr_any));
2360
2361 let addr1 = VsockAddr::new(libc::VMADDR_CID_HOST, port);
2362 let addr2 = VsockAddr::new(libc::VMADDR_CID_HOST, port);
2363 assert_eq!(addr1, addr2);
2364 assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2));
2365
2366 let addr3 = unsafe {
2367 VsockAddr::from_raw(
2368 addr2.as_ref() as *const libc::sockaddr_vm as *const libc::sockaddr,
2369 Some(mem::size_of::<libc::sockaddr_vm>().try_into().unwrap()),
2370 )
2371 }
2372 .unwrap();
2373 assert_eq!(
2374 addr3.as_ref().svm_family,
2375 AddressFamily::Vsock as libc::sa_family_t
2376 );
2377 let cid = addr3.as_ref().svm_cid;
2378 let port = addr3.as_ref().svm_port;
2379 assert_eq!(cid, addr1.cid());
2380 assert_eq!(port, addr1.port());
2381 }
2382
2383 // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack
2384 // of QEMU support is suspected.
2385 #[cfg_attr(qemu, ignore)]
2386 #[cfg(target_os = "linux")]
2387 #[test]
2388 fn test_recvmsg_timestampns() {
2389 use nix::sys::socket::*;
2390 use nix::sys::time::*;
2391 use std::io::{IoSlice, IoSliceMut};
2392 use std::time::*;
2393
2394 // Set up
2395 let message = "Ohayō!".as_bytes();
2396 let in_socket = socket(
2397 AddressFamily::Inet,
2398 SockType::Datagram,
2399 SockFlag::empty(),
2400 None,
2401 )
2402 .unwrap();
2403 setsockopt(&in_socket, sockopt::ReceiveTimestampns, &true).unwrap();
2404 let localhost = SockaddrIn::new(127, 0, 0, 1, 0);
2405 bind(in_socket.as_raw_fd(), &localhost).unwrap();
2406 let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap();
2407 // Get initial time
2408 let time0 = SystemTime::now();
2409 // Send the message
2410 let iov = [IoSlice::new(message)];
2411 let flags = MsgFlags::empty();
2412 let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address))
2413 .unwrap();
2414 assert_eq!(message.len(), l);
2415 // Receive the message
2416 let mut buffer = vec![0u8; message.len()];
2417 let mut cmsgspace = nix::cmsg_space!(TimeSpec);
2418
2419 let mut iov = [IoSliceMut::new(&mut buffer)];
2420 let r = recvmsg::<()>(
2421 in_socket.as_raw_fd(),
2422 &mut iov,
2423 Some(&mut cmsgspace),
2424 flags,
2425 )
2426 .unwrap();
2427 let rtime = match r.cmsgs().unwrap().next() {
2428 Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime,
2429 Some(_) => panic!("Unexpected control message"),
2430 None => panic!("No control message"),
2431 };
2432 // Check the final time
2433 let time1 = SystemTime::now();
2434 // the packet's received timestamp should lie in-between the two system
2435 // times, unless the system clock was adjusted in the meantime.
2436 let rduration =
2437 Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32);
2438 assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration);
2439 assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap());
2440 }
2441
2442 // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack
2443 // of QEMU support is suspected.
2444 #[cfg_attr(qemu, ignore)]
2445 #[cfg(target_os = "linux")]
2446 #[test]
2447 fn test_recvmmsg_timestampns() {
2448 use nix::sys::socket::*;
2449 use nix::sys::time::*;
2450 use std::io::{IoSlice, IoSliceMut};
2451 use std::time::*;
2452
2453 // Set up
2454 let message = "Ohayō!".as_bytes();
2455 let in_socket = socket(
2456 AddressFamily::Inet,
2457 SockType::Datagram,
2458 SockFlag::empty(),
2459 None,
2460 )
2461 .unwrap();
2462 setsockopt(&in_socket, sockopt::ReceiveTimestampns, &true).unwrap();
2463 let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap();
2464 bind(in_socket.as_raw_fd(), &localhost).unwrap();
2465 let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap();
2466 // Get initial time
2467 let time0 = SystemTime::now();
2468 // Send the message
2469 let iov = [IoSlice::new(message)];
2470 let flags = MsgFlags::empty();
2471 let l = sendmsg(in_socket.as_raw_fd(), &iov, &[], flags, Some(&address))
2472 .unwrap();
2473 assert_eq!(message.len(), l);
2474 // Receive the message
2475 let mut buffer = vec![0u8; message.len()];
2476 let cmsgspace = nix::cmsg_space!(TimeSpec);
2477 let mut iov = [[IoSliceMut::new(&mut buffer)]];
2478 let mut data = MultiHeaders::preallocate(1, Some(cmsgspace));
2479 let r: Vec<RecvMsg<()>> = recvmmsg(
2480 in_socket.as_raw_fd(),
2481 &mut data,
2482 iov.iter_mut(),
2483 flags,
2484 None,
2485 )
2486 .unwrap()
2487 .collect();
2488 let rtime = match r[0].cmsgs().unwrap().next() {
2489 Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime,
2490 Some(_) => panic!("Unexpected control message"),
2491 None => panic!("No control message"),
2492 };
2493 // Check the final time
2494 let time1 = SystemTime::now();
2495 // the packet's received timestamp should lie in-between the two system
2496 // times, unless the system clock was adjusted in the meantime.
2497 let rduration =
2498 Duration::new(rtime.tv_sec() as u64, rtime.tv_nsec() as u32);
2499 assert!(time0.duration_since(UNIX_EPOCH).unwrap() <= rduration);
2500 assert!(rduration <= time1.duration_since(UNIX_EPOCH).unwrap());
2501 }
2502
2503 // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack
2504 // of QEMU support is suspected.
2505 #[cfg_attr(qemu, ignore)]
2506 #[cfg(any(linux_android, target_os = "fuchsia"))]
2507 #[test]
2508 fn test_recvmsg_rxq_ovfl() {
2509 use nix::sys::socket::sockopt::{RcvBuf, RxqOvfl};
2510 use nix::sys::socket::*;
2511 use nix::Error;
2512 use std::io::{IoSlice, IoSliceMut};
2513
2514 let message = [0u8; 2048];
2515 let bufsize = message.len() * 2;
2516
2517 let in_socket = socket(
2518 AddressFamily::Inet,
2519 SockType::Datagram,
2520 SockFlag::empty(),
2521 None,
2522 )
2523 .unwrap();
2524 let out_socket = socket(
2525 AddressFamily::Inet,
2526 SockType::Datagram,
2527 SockFlag::empty(),
2528 None,
2529 )
2530 .unwrap();
2531
2532 let localhost = SockaddrIn::from_str("127.0.0.1:0").unwrap();
2533 bind(in_socket.as_raw_fd(), &localhost).unwrap();
2534
2535 let address: SockaddrIn = getsockname(in_socket.as_raw_fd()).unwrap();
2536 connect(out_socket.as_raw_fd(), &address).unwrap();
2537
2538 // Set SO_RXQ_OVFL flag.
2539 setsockopt(&in_socket, RxqOvfl, &1).unwrap();
2540
2541 // Set the receiver buffer size to hold only 2 messages.
2542 setsockopt(&in_socket, RcvBuf, &bufsize).unwrap();
2543
2544 let mut drop_counter = 0;
2545
2546 for _ in 0..2 {
2547 let iov = [IoSlice::new(&message)];
2548 let flags = MsgFlags::empty();
2549
2550 // Send the 3 messages (the receiver buffer can only hold 2 messages)
2551 // to create an overflow.
2552 for _ in 0..3 {
2553 let l = sendmsg(
2554 out_socket.as_raw_fd(),
2555 &iov,
2556 &[],
2557 flags,
2558 Some(&address),
2559 )
2560 .unwrap();
2561 assert_eq!(message.len(), l);
2562 }
2563
2564 // Receive the message and check the drop counter if any.
2565 loop {
2566 let mut buffer = vec![0u8; message.len()];
2567 let mut cmsgspace = nix::cmsg_space!(u32);
2568
2569 let mut iov = [IoSliceMut::new(&mut buffer)];
2570
2571 match recvmsg::<()>(
2572 in_socket.as_raw_fd(),
2573 &mut iov,
2574 Some(&mut cmsgspace),
2575 MsgFlags::MSG_DONTWAIT,
2576 ) {
2577 Ok(r) => {
2578 drop_counter = match r.cmsgs().unwrap().next() {
2579 Some(ControlMessageOwned::RxqOvfl(drop_counter)) => {
2580 drop_counter
2581 }
2582 Some(_) => panic!("Unexpected control message"),
2583 None => 0,
2584 };
2585 }
2586 Err(Error::EAGAIN) => {
2587 break;
2588 }
2589 _ => {
2590 panic!("unknown recvmsg() error");
2591 }
2592 }
2593 }
2594 }
2595
2596 // One packet lost.
2597 assert_eq!(drop_counter, 1);
2598 }
2599
2600 #[cfg(any(linux_android, target_os = "freebsd"))]
2601 #[cfg(feature = "net")]
2602 // qemu doesn't seem to be emulating this correctly in these architectures
2603 #[cfg_attr(
2604 all(
2605 qemu,
2606 any(
2607 target_arch = "mips",
2608 target_arch = "mips32r6",
2609 target_arch = "mips64",
2610 target_arch = "mips64r6",
2611 )
2612 ),
2613 ignore
2614 )]
2615 #[test]
2616 pub fn test_ip_tos_udp() {
2617 use nix::sys::socket::ControlMessageOwned;
2618 use nix::sys::socket::{
2619 bind, recvmsg, sendmsg, setsockopt, socket, sockopt, ControlMessage,
2620 MsgFlags, SockFlag, SockType, SockaddrIn,
2621 };
2622
2623 let sock_addr = SockaddrIn::from_str("127.0.0.1:6909").unwrap();
2624 let rsock = socket(
2625 AddressFamily::Inet,
2626 SockType::Datagram,
2627 SockFlag::empty(),
2628 None,
2629 )
2630 .unwrap();
2631 setsockopt(&rsock, sockopt::IpRecvTos, &true).unwrap();
2632 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
2633
2634 let sbuf = [0u8; 2048];
2635 let iov1 = [std::io::IoSlice::new(&sbuf)];
2636
2637 let mut rbuf = [0u8; 2048];
2638 let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)];
2639 let mut rcmsg = cmsg_space!(libc::c_int);
2640
2641 let ssock = socket(
2642 AddressFamily::Inet,
2643 SockType::Datagram,
2644 SockFlag::empty(),
2645 None,
2646 )
2647 .expect("send socket failed");
2648 setsockopt(&ssock, sockopt::Ipv4Tos, &20).unwrap();
2649
2650 // Test the sendmsg control message and check the received packet has the same TOS.
2651 let scmsg = ControlMessage::Ipv4Tos(&20);
2652 sendmsg(
2653 ssock.as_raw_fd(),
2654 &iov1,
2655 &[scmsg],
2656 MsgFlags::empty(),
2657 Some(&sock_addr),
2658 )
2659 .unwrap();
2660
2661 // TODO: this test is weak, but testing for the actual ToS value results in sporadic
2662 // failures in CI where the ToS in the message header is not the one set by the
2663 // sender, so for now the test only checks for the presence of the ToS in the message
2664 // header.
2665 let mut tc = None;
2666 let recv = recvmsg::<()>(
2667 rsock.as_raw_fd(),
2668 &mut iov2,
2669 Some(&mut rcmsg),
2670 MsgFlags::empty(),
2671 )
2672 .unwrap();
2673 for c in recv.cmsgs().unwrap() {
2674 if let ControlMessageOwned::Ipv4Tos(t) = c {
2675 tc = Some(t);
2676 }
2677 }
2678 assert!(tc.is_some());
2679 }
2680
2681 #[cfg(target_os = "linux")]
2682 // qemu doesn't seem to be emulating this correctly in these architectures
2683 #[cfg_attr(
2684 all(
2685 qemu,
2686 any(
2687 target_arch = "mips",
2688 target_arch = "mips32r6",
2689 target_arch = "mips64",
2690 target_arch = "mips64r6",
2691 )
2692 ),
2693 ignore
2694 )]
2695 #[cfg(feature = "net")]
2696 #[test]
2697 pub fn test_ipv6_tclass_udp() {
2698 use nix::sys::socket::ControlMessageOwned;
2699 use nix::sys::socket::{
2700 bind, recvmsg, sendmsg, setsockopt, socket, sockopt, ControlMessage,
2701 MsgFlags, SockFlag, SockType, SockaddrIn6,
2702 };
2703
2704 let std_sa = SocketAddrV6::from_str("[::1]:6902").unwrap();
2705 let sock_addr: SockaddrIn6 = SockaddrIn6::from(std_sa);
2706 let rsock = socket(
2707 AddressFamily::Inet6,
2708 SockType::Datagram,
2709 SockFlag::empty(),
2710 None,
2711 )
2712 .unwrap();
2713 setsockopt(&rsock, sockopt::Ipv6RecvTClass, &true).unwrap();
2714 // This bind call with IPV6_RECVTCLASS fails on the Linux aarch64 target with EADDRNOTAVAIL,
2715 // so the test will only run if `bind` does not return an error..
2716 if bind(rsock.as_raw_fd(), &sock_addr).is_ok() {
2717 let sbuf = [0u8; 2048];
2718 let iov1 = [std::io::IoSlice::new(&sbuf)];
2719
2720 let mut rbuf = [0u8; 2048];
2721 let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)];
2722 let mut rcmsg = cmsg_space!(libc::c_int);
2723
2724 let ssock = socket(
2725 AddressFamily::Inet6,
2726 SockType::Datagram,
2727 SockFlag::empty(),
2728 None,
2729 )
2730 .expect("send socket failed");
2731 setsockopt(&ssock, sockopt::Ipv6TClass, &10).unwrap();
2732
2733 sendmsg(
2734 ssock.as_raw_fd(),
2735 &iov1,
2736 &[],
2737 MsgFlags::empty(),
2738 Some(&sock_addr),
2739 )
2740 .unwrap();
2741
2742 let mut tc = None;
2743 let recv = recvmsg::<()>(
2744 rsock.as_raw_fd(),
2745 &mut iov2,
2746 Some(&mut rcmsg),
2747 MsgFlags::empty(),
2748 )
2749 .unwrap();
2750 for c in recv.cmsgs().unwrap() {
2751 if let ControlMessageOwned::Ipv6TClass(t) = c {
2752 tc = Some(t);
2753 }
2754 }
2755 assert_eq!(tc, Some(10));
2756
2757 let scmsg = ControlMessage::Ipv6TClass(&20);
2758 sendmsg(
2759 ssock.as_raw_fd(),
2760 &iov1,
2761 &[scmsg],
2762 MsgFlags::empty(),
2763 Some(&sock_addr),
2764 )
2765 .unwrap();
2766
2767 let mut tc = None;
2768 let recv = recvmsg::<()>(
2769 rsock.as_raw_fd(),
2770 &mut iov2,
2771 Some(&mut rcmsg),
2772 MsgFlags::empty(),
2773 )
2774 .unwrap();
2775 for c in recv.cmsgs().unwrap() {
2776 if let ControlMessageOwned::Ipv6TClass(t) = c {
2777 tc = Some(t);
2778 }
2779 }
2780
2781 assert_eq!(tc, Some(20));
2782 }
2783 }
2784
2785 #[cfg(linux_android)]
2786 mod linux_errqueue {
2787 use super::FromStr;
2788 use nix::sys::socket::*;
2789 use std::os::unix::io::AsRawFd;
2790
2791 // Send a UDP datagram to a bogus destination address and observe an ICMP error (v4).
2792 //
2793 // Disable the test on QEMU because QEMU emulation of IP_RECVERR is broken (as documented on PR
2794 // #1514).
2795 #[cfg_attr(qemu, ignore)]
2796 #[test]
2797 fn test_recverr_v4() {
2798 #[repr(u8)]
2799 enum IcmpTypes {
2800 DestUnreach = 3, // ICMP_DEST_UNREACH
2801 }
2802 #[repr(u8)]
2803 enum IcmpUnreachCodes {
2804 PortUnreach = 3, // ICMP_PORT_UNREACH
2805 }
2806
2807 test_recverr_impl::<sockaddr_in, _, _>(
2808 "127.0.0.1:6800",
2809 AddressFamily::Inet,
2810 sockopt::Ipv4RecvErr,
2811 libc::SO_EE_ORIGIN_ICMP,
2812 IcmpTypes::DestUnreach as u8,
2813 IcmpUnreachCodes::PortUnreach as u8,
2814 // Closure handles protocol-specific testing and returns generic sock_extended_err for
2815 // protocol-independent test impl.
2816 |cmsg| {
2817 if let ControlMessageOwned::Ipv4RecvErr(ext_err, err_addr) =
2818 cmsg
2819 {
2820 if let Some(origin) = err_addr {
2821 // Validate that our network error originated from 127.0.0.1:0.
2822 assert_eq!(origin.sin_family, AddressFamily::Inet as _);
2823 assert_eq!(
2824 origin.sin_addr.s_addr,
2825 u32::from_be(0x7f000001)
2826 );
2827 assert_eq!(origin.sin_port, 0);
2828 } else {
2829 panic!("Expected some error origin");
2830 }
2831 *ext_err
2832 } else {
2833 panic!("Unexpected control message {cmsg:?}");
2834 }
2835 },
2836 )
2837 }
2838
2839 // Essentially the same test as v4.
2840 //
2841 // Disable the test on QEMU because QEMU emulation of IPV6_RECVERR is broken (as documented on
2842 // PR #1514).
2843 #[cfg_attr(qemu, ignore)]
2844 #[test]
2845 fn test_recverr_v6() {
2846 #[repr(u8)]
2847 enum IcmpV6Types {
2848 DestUnreach = 1, // ICMPV6_DEST_UNREACH
2849 }
2850 #[repr(u8)]
2851 enum IcmpV6UnreachCodes {
2852 PortUnreach = 4, // ICMPV6_PORT_UNREACH
2853 }
2854
2855 test_recverr_impl::<sockaddr_in6, _, _>(
2856 "[::1]:6801",
2857 AddressFamily::Inet6,
2858 sockopt::Ipv6RecvErr,
2859 libc::SO_EE_ORIGIN_ICMP6,
2860 IcmpV6Types::DestUnreach as u8,
2861 IcmpV6UnreachCodes::PortUnreach as u8,
2862 // Closure handles protocol-specific testing and returns generic sock_extended_err for
2863 // protocol-independent test impl.
2864 |cmsg| {
2865 if let ControlMessageOwned::Ipv6RecvErr(ext_err, err_addr) =
2866 cmsg
2867 {
2868 if let Some(origin) = err_addr {
2869 // Validate that our network error originated from localhost:0.
2870 assert_eq!(
2871 origin.sin6_family,
2872 AddressFamily::Inet6 as _
2873 );
2874 assert_eq!(
2875 origin.sin6_addr.s6_addr,
2876 std::net::Ipv6Addr::LOCALHOST.octets()
2877 );
2878 assert_eq!(origin.sin6_port, 0);
2879 } else {
2880 panic!("Expected some error origin");
2881 }
2882 *ext_err
2883 } else {
2884 panic!("Unexpected control message {cmsg:?}");
2885 }
2886 },
2887 )
2888 }
2889
2890 fn test_recverr_impl<SA, OPT, TESTF>(
2891 sa: &str,
2892 af: AddressFamily,
2893 opt: OPT,
2894 ee_origin: u8,
2895 ee_type: u8,
2896 ee_code: u8,
2897 testf: TESTF,
2898 ) where
2899 OPT: SetSockOpt<Val = bool>,
2900 TESTF: FnOnce(&ControlMessageOwned) -> libc::sock_extended_err,
2901 {
2902 use nix::errno::Errno;
2903 use std::io::IoSliceMut;
2904
2905 const MESSAGE_CONTENTS: &str = "ABCDEF";
2906 let std_sa = std::net::SocketAddr::from_str(sa).unwrap();
2907 let sock_addr = SockaddrStorage::from(std_sa);
2908 let sock = socket(af, SockType::Datagram, SockFlag::SOCK_CLOEXEC, None)
2909 .unwrap();
2910 setsockopt(&sock, opt, &true).unwrap();
2911 if let Err(e) = sendto(
2912 sock.as_raw_fd(),
2913 MESSAGE_CONTENTS.as_bytes(),
2914 &sock_addr,
2915 MsgFlags::empty(),
2916 ) {
2917 assert_eq!(e, Errno::EADDRNOTAVAIL);
2918 println!("{af:?} not available, skipping test.");
2919 return;
2920 }
2921
2922 let mut buf = [0u8; 8];
2923 let mut iovec = [IoSliceMut::new(&mut buf)];
2924 let mut cspace = cmsg_space!(libc::sock_extended_err, SA);
2925
2926 let msg = recvmsg(
2927 sock.as_raw_fd(),
2928 &mut iovec,
2929 Some(&mut cspace),
2930 MsgFlags::MSG_ERRQUEUE,
2931 )
2932 .unwrap();
2933 // The sent message / destination associated with the error is returned:
2934 assert_eq!(msg.bytes, MESSAGE_CONTENTS.len());
2935 // recvmsg(2): "The original destination address of the datagram that caused the error is
2936 // supplied via msg_name;" however, this is not literally true. E.g., an earlier version
2937 // of this test used 0.0.0.0 (::0) as the destination address, which was mutated into
2938 // 127.0.0.1 (::1).
2939 assert_eq!(msg.address, Some(sock_addr));
2940
2941 // Check for expected control message.
2942 let ext_err = match msg.cmsgs().unwrap().next() {
2943 Some(cmsg) => testf(&cmsg),
2944 None => panic!("No control message"),
2945 };
2946
2947 assert_eq!(ext_err.ee_errno, libc::ECONNREFUSED as u32);
2948 assert_eq!(ext_err.ee_origin, ee_origin);
2949 // ip(7): ee_type and ee_code are set from the type and code fields of the ICMP (ICMPv6)
2950 // header.
2951 assert_eq!(ext_err.ee_type, ee_type);
2952 assert_eq!(ext_err.ee_code, ee_code);
2953 // ip(7): ee_info contains the discovered MTU for EMSGSIZE errors.
2954 assert_eq!(ext_err.ee_info, 0);
2955
2956 let bytes = msg.bytes;
2957 assert_eq!(&buf[..bytes], MESSAGE_CONTENTS.as_bytes());
2958 }
2959 }
2960
2961 // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack
2962 // of QEMU support is suspected.
2963 #[cfg_attr(qemu, ignore)]
2964 #[cfg(target_os = "linux")]
2965 #[test]
2966 pub fn test_txtime() {
2967 use nix::sys::socket::{
2968 bind, recvmsg, sendmsg, setsockopt, socket, sockopt, ControlMessage,
2969 MsgFlags, SockFlag, SockType, SockaddrIn,
2970 };
2971 use nix::sys::time::TimeValLike;
2972 use nix::time::{clock_gettime, ClockId};
2973
2974 require_kernel_version!(test_txtime, ">= 5.8");
2975
2976 let sock_addr = SockaddrIn::from_str("127.0.0.1:6802").unwrap();
2977
2978 let ssock = socket(
2979 AddressFamily::Inet,
2980 SockType::Datagram,
2981 SockFlag::empty(),
2982 None,
2983 )
2984 .expect("send socket failed");
2985
2986 let txtime_cfg = libc::sock_txtime {
2987 clockid: libc::CLOCK_MONOTONIC,
2988 flags: 0,
2989 };
2990 setsockopt(&ssock, sockopt::TxTime, &txtime_cfg).unwrap();
2991
2992 let rsock = socket(
2993 AddressFamily::Inet,
2994 SockType::Datagram,
2995 SockFlag::empty(),
2996 None,
2997 )
2998 .unwrap();
2999 bind(rsock.as_raw_fd(), &sock_addr).unwrap();
3000
3001 let sbuf = [0u8; 2048];
3002 let iov1 = [std::io::IoSlice::new(&sbuf)];
3003
3004 let now = clock_gettime(ClockId::CLOCK_MONOTONIC).unwrap();
3005 let delay = std::time::Duration::from_secs(1).into();
3006 let txtime = (now + delay).num_nanoseconds() as u64;
3007
3008 let cmsg = ControlMessage::TxTime(&txtime);
3009 sendmsg(
3010 ssock.as_raw_fd(),
3011 &iov1,
3012 &[cmsg],
3013 MsgFlags::empty(),
3014 Some(&sock_addr),
3015 )
3016 .unwrap();
3017
3018 let mut rbuf = [0u8; 2048];
3019 let mut iov2 = [std::io::IoSliceMut::new(&mut rbuf)];
3020 recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, None, MsgFlags::empty())
3021 .unwrap();
3022 }
3023
3024 // cfg needed for capability check.
3025 #[cfg(linux_android)]
3026 #[test]
3027 fn test_icmp_protocol() {
3028 use nix::sys::socket::{
3029 sendto, socket, AddressFamily, MsgFlags, SockFlag, SockProtocol,
3030 SockType, SockaddrIn,
3031 };
3032
3033 require_capability!("test_icmp_protocol", CAP_NET_RAW);
3034
3035 let owned_fd = socket(
3036 AddressFamily::Inet,
3037 SockType::Raw,
3038 SockFlag::empty(),
3039 SockProtocol::Icmp,
3040 )
3041 .unwrap();
3042
3043 // Send a minimal ICMP packet with no payload.
3044 let packet = [
3045 0x08, // Type
3046 0x00, // Code
3047 0x84, 0x85, // Checksum
3048 0x73, 0x8a, // ID
3049 0x00, 0x00, // Sequence Number
3050 ];
3051
3052 let dest_addr = SockaddrIn::new(127, 0, 0, 1, 0);
3053 sendto(owned_fd.as_raw_fd(), &packet, &dest_addr, MsgFlags::empty())
3054 .unwrap();
3055 }
3056
3057 // test contains both recvmmsg and timestaping which is linux only
3058 // there are existing tests for recvmmsg only in tests/
3059 #[cfg_attr(qemu, ignore)]
3060 #[cfg(target_os = "linux")]
3061 #[test]
3062 fn test_recvmm2() -> nix::Result<()> {
3063 use nix::sys::{
3064 socket::{
3065 bind, recvmmsg, sendmsg, setsockopt, socket, sockopt::Timestamping,
3066 AddressFamily, ControlMessageOwned, MsgFlags, MultiHeaders,
3067 SockFlag, SockType, SockaddrIn, TimestampingFlag, Timestamps,
3068 },
3069 time::TimeSpec,
3070 };
3071 use std::io::{IoSlice, IoSliceMut};
3072 use std::os::unix::io::AsRawFd;
3073 use std::str::FromStr;
3074
3075 let sock_addr = SockaddrIn::from_str("127.0.0.1:6790").unwrap();
3076
3077 let ssock = socket(
3078 AddressFamily::Inet,
3079 SockType::Datagram,
3080 SockFlag::empty(),
3081 None,
3082 )?;
3083
3084 let rsock = socket(
3085 AddressFamily::Inet,
3086 SockType::Datagram,
3087 SockFlag::SOCK_NONBLOCK,
3088 None,
3089 )?;
3090
3091 bind(rsock.as_raw_fd(), &sock_addr)?;
3092
3093 setsockopt(&rsock, Timestamping, &TimestampingFlag::all())?;
3094
3095 let sbuf = (0..400).map(|i| i as u8).collect::<Vec<_>>();
3096
3097 let mut recv_buf = vec![0; 1024];
3098
3099 let mut recv_iovs = Vec::new();
3100 let mut pkt_iovs = Vec::new();
3101
3102 for (ix, chunk) in recv_buf.chunks_mut(256).enumerate() {
3103 pkt_iovs.push(IoSliceMut::new(chunk));
3104 if ix % 2 == 1 {
3105 recv_iovs.push(pkt_iovs);
3106 pkt_iovs = Vec::new();
3107 }
3108 }
3109 drop(pkt_iovs);
3110
3111 let flags = MsgFlags::empty();
3112 let iov1 = [IoSlice::new(&sbuf)];
3113
3114 let cmsg = cmsg_space!(Timestamps);
3115 sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap();
3116
3117 let mut data = MultiHeaders::<()>::preallocate(recv_iovs.len(), Some(cmsg));
3118
3119 let t = TimeSpec::from_duration(std::time::Duration::from_secs(10));
3120
3121 let recv = recvmmsg(
3122 rsock.as_raw_fd(),
3123 &mut data,
3124 recv_iovs.iter_mut(),
3125 flags,
3126 Some(t),
3127 )?;
3128
3129 for rmsg in recv {
3130 #[cfg(not(any(qemu, target_arch = "aarch64")))]
3131 let mut saw_time = false;
3132 let mut recvd = 0;
3133 for cmsg in rmsg.cmsgs().unwrap() {
3134 if let ControlMessageOwned::ScmTimestampsns(timestamps) = cmsg {
3135 let ts = timestamps.system;
3136
3137 let sys_time = nix::time::clock_gettime(
3138 nix::time::ClockId::CLOCK_REALTIME,
3139 )?;
3140 let diff = if ts > sys_time {
3141 ts - sys_time
3142 } else {
3143 sys_time - ts
3144 };
3145 assert!(std::time::Duration::from(diff).as_secs() < 60);
3146 #[cfg(not(any(qemu, target_arch = "aarch64")))]
3147 {
3148 saw_time = true;
3149 }
3150 }
3151 }
3152
3153 #[cfg(not(any(qemu, target_arch = "aarch64")))]
3154 assert!(saw_time);
3155
3156 for iov in rmsg.iovs() {
3157 recvd += iov.len();
3158 }
3159 assert_eq!(recvd, 400);
3160 }
3161
3162 Ok(())
3163 }
3164
3165 #[cfg(not(target_os = "redox"))]
3166 #[test]
3167 fn can_use_cmsg_space() {
3168 let _ = cmsg_space!(u8);
3169 }
3170
3171 #[cfg(not(any(
3172 linux_android,
3173 target_os = "redox",
3174 target_os = "haiku",
3175 target_os = "cygwin"
3176 )))]
3177 #[test]
3178 fn can_open_routing_socket() {
3179 use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
3180
3181 let _ =
3182 socket(AddressFamily::Route, SockType::Raw, SockFlag::empty(), None)
3183 .expect("Failed to open routing socket");
3184 }