Debian Codegraph @

libs/gst/helpers/ptp/net.rs

raw
1 // GStreamer
2 //
3 // Copyright (C) 2015-2023 Sebastian Dröge <[email protected]>
4 //
5 // This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
6 // If a copy of the MPL was not distributed with this file, You can obtain one at
7 // <https://mozilla.org/MPL/2.0/>.
8 //
9 // SPDX-License-Identifier: MPL-2.0
10
11 use std::net::Ipv4Addr;
12
13 use crate::{bail, error::Error};
14
15 #[derive(Debug)]
16 /// Network interface information.
17 pub struct InterfaceInfo {
18 /// Name of the interface
19 pub name: String,
20 /// Other name of the interface, if any
21 pub other_name: Option<String>,
22 /// Interface index
23 pub index: usize,
24 /// Unicast IPv4 address of the interface
25 pub ip_addr: Ipv4Addr,
26 /// Physical MAC address of the interface, if any
27 pub hw_addr: Option<[u8; 6]>,
28 }
29
30 #[cfg(unix)]
31 mod imp {
32 use super::*;
33
34 use std::{ffi::CStr, io, marker, mem, net::UdpSocket, os::unix::io::AsRawFd, ptr};
35
36 use crate::{error::Context, ffi::unix::*};
37
38 /// Returns information for all non-loopback, multicast-capable network interfaces.
39 pub fn query_interfaces() -> Result<Vec<InterfaceInfo>, Error> {
40 struct Ifaddrs(*mut ifaddrs);
41
42 impl Ifaddrs {
43 fn new() -> io::Result<Self> {
44 loop {
45 // SAFETY: Requires passing valid storage for the returned ifaddrs pointer and
46 // returns -1 on errors. It might return NULL if there are no network interfaces.
47 //
48 // On error it might return EINTR in which case we should simply try again.
49 unsafe {
50 let mut ifaddrs = ptr::null_mut();
51 if getifaddrs(&mut ifaddrs) == -1 {
52 let err = io::Error::last_os_error();
53 if err.kind() == std::io::ErrorKind::Interrupted {
54 continue;
55 }
56
57 return Err(err);
58 } else {
59 return Ok(Self(ifaddrs));
60 }
61 }
62 }
63 }
64
65 fn iter(&self) -> IfaddrsIter<'_> {
66 IfaddrsIter {
67 ptr: ptr::NonNull::new(self.0),
68 phantom: marker::PhantomData,
69 }
70 }
71 }
72
73 impl Drop for Ifaddrs {
74 fn drop(&mut self) {
75 // SAFETY: The pointer is a valid ifaddrs pointer by construction and dropped only
76 // once, so freeing it here is OK. It might be NULL so check for that first.
77 unsafe {
78 if !self.0.is_null() {
79 freeifaddrs(self.0);
80 }
81 }
82 }
83 }
84
85 struct IfaddrsIter<'a> {
86 ptr: Option<ptr::NonNull<ifaddrs>>,
87 phantom: marker::PhantomData<&'a Ifaddrs>,
88 }
89
90 impl<'a> Iterator for IfaddrsIter<'a> {
91 type Item = &'a ifaddrs;
92
93 fn next(&mut self) -> Option<Self::Item> {
94 match self.ptr {
95 None => None,
96 Some(ptr) => {
97 // SAFETY: The pointer is a valid ifaddrs pointer by construction so
98 // creating a reference to it is OK.
99 let addr = unsafe { &*ptr.as_ptr() };
100 self.ptr = ptr::NonNull::new(addr.ifa_next);
101 Some(addr)
102 }
103 }
104 }
105 }
106
107 let ifaddrs = Ifaddrs::new().context("Failed getting interface addresses")?;
108
109 let mut if_infos = Vec::<InterfaceInfo>::new();
110
111 for ifaddr in ifaddrs.iter() {
112 // SAFETY: ifa_name points to a NUL-terminated interface name string that is valid as
113 // long as its struct is
114 let name = unsafe { CStr::from_ptr(ifaddr.ifa_name) }.to_str().unwrap();
115
116 // Skip loopback interfaces, interfaces that are not up and interfaces that can't do
117 // multicast. These are all unusable for PTP purposes.
118 let flags = ifaddr.ifa_flags;
119 if flags & IFF_LOOPBACK != 0 {
120 debug!("Interface {} is loopback interface", name);
121 continue;
122 }
123 if flags & IFF_UP == 0 {
124 debug!("Interface {} is not up", name);
125 continue;
126 }
127 if flags & IFF_MULTICAST == 0 {
128 debug!("Interface {} does not support multicast", name);
129 continue;
130 }
131
132 // If the interface has no address then skip it. Only interfaces with IPv4 addresses
133 // are usable for PTP purposes.
134 if ifaddr.ifa_addr.is_null() {
135 debug!("Interface {} has no IPv4 address", name);
136 continue;
137 }
138
139 // Get the interface index from its name. If it has none then we can't use it to join
140 // the PTP multicast group reliable for this interface.
141 //
142 // SAFETY: Must be called with a valid, NUL-terminated string which is provided by
143 // ifa_name and will return the interface index or zero on error.
144 //
145 // On error it can return EINTR in which case we should try again.
146 let index = loop {
147 let index = unsafe { if_nametoindex(ifaddr.ifa_name) } as usize;
148 if index == 0 {
149 let err = io::Error::last_os_error();
150 if err.kind() == io::ErrorKind::Interrupted {
151 continue;
152 }
153 }
154 break index;
155 };
156 if index == 0 {
157 debug!("Interface {} has no valid interface index", name);
158 continue;
159 }
160
161 // Interfaces are listed multiple times here, once per address. We collect all IPv4 and
162 // MAC addresses for interfaces below.
163
164 // SAFETY: ifa_addr is a valid sockaddr pointer and was checked to be not NULL further
165 // above.
166 let sa_family = unsafe { (*ifaddr.ifa_addr).sa_family };
167
168 // If this interface has an IPv4 address then retrieve and store it here.
169 if sa_family == AF_INET as _ {
170 // SAFETY: If the address family is AF_INET then it is actually a valid sockaddr_in
171 // pointer and can be used as such.
172 let addr = unsafe { &*(ifaddr.ifa_addr as *const sockaddr_in) };
173 let ip_addr = Ipv4Addr::from(addr.sin_addr.s_addr.to_ne_bytes());
174
175 debug!("Interface {} has IPv4 address {}", name, ip_addr);
176
177 if let Some(if_info) = if_infos.iter_mut().find(|info| info.name == name) {
178 if if_info.ip_addr.is_broadcast() {
179 if_info.ip_addr = ip_addr;
180 }
181 } else {
182 if_infos.push(InterfaceInfo {
183 name: String::from(name),
184 other_name: None,
185 index,
186 ip_addr,
187 hw_addr: None,
188 });
189 }
190 }
191
192 #[cfg(target_os = "linux")]
193 {
194 if sa_family == AF_PACKET as _ {
195 // SAFETY: If the address family is AF_PACKET then it is actually a valid sockaddr_ll
196 // pointer and can be used as such.
197 let addr = unsafe { &*(ifaddr.ifa_addr as *const sockaddr_ll) };
198 if addr.sll_halen == 6 {
199 let mut hw_addr = [0u8; 6];
200 hw_addr.copy_from_slice(&addr.sll_addr[0..6]);
201
202 debug!("Interface {} has MAC address {:?}", name, hw_addr);
203
204 if let Some(if_info) = if_infos.iter_mut().find(|info| info.name == name) {
205 if if_info.hw_addr.is_none() {
206 if_info.hw_addr = Some(hw_addr);
207 }
208 } else {
209 if_infos.push(InterfaceInfo {
210 name: String::from(name),
211 other_name: None,
212 index,
213 ip_addr: Ipv4Addr::BROADCAST,
214 hw_addr: Some(hw_addr),
215 });
216 }
217 }
218 }
219 }
220 #[cfg(not(any(target_os = "linux", target_os = "hurd")))]
221 {
222 use std::slice;
223
224 if sa_family == AF_LINK as _ {
225 // SAFETY: If the address family is AF_LINK then it is actually a valid sockaddr_dl
226 // pointer and can be used as such.
227 let addr = unsafe { &*(ifaddr.ifa_addr as *const sockaddr_dl) };
228 if addr.sdl_nlen <= IF_NAMESIZE as u8 && addr.sdl_alen == 6 {
229 let mut hw_addr = [0u8; 6];
230 // SAFETY: There can be more than the given number of bytes stored and
231 // this happens regularly on macOS at least. It is required that the
232 // interface name is at most IF_NAMESIZE (checked just above).
233 unsafe {
234 let sdl_addr_ptr = addr.sdl_data.as_ptr() as *const u8;
235 let sdl_addr =
236 slice::from_raw_parts(sdl_addr_ptr.add(addr.sdl_nlen as usize), 6);
237 hw_addr.copy_from_slice(sdl_addr);
238 }
239
240 debug!("Interface {} has MAC address {:?}", name, hw_addr);
241
242 if let Some(if_info) = if_infos.iter_mut().find(|info| info.name == name) {
243 if if_info.hw_addr.is_none() {
244 if_info.hw_addr = Some(hw_addr);
245 }
246 } else {
247 if_infos.push(InterfaceInfo {
248 name: String::from(name),
249 other_name: None,
250 index,
251 ip_addr: Ipv4Addr::BROADCAST,
252 hw_addr: Some(hw_addr),
253 });
254 }
255 }
256 }
257 }
258 }
259
260 if_infos.retain(|iface| !iface.ip_addr.is_broadcast());
261
262 Ok(if_infos)
263 }
264
265 /// Create an `UdpSocket` and bind it to the given address but set `SO_REUSEADDR` and/or
266 /// `SO_REUSEPORT` before doing so.
267 ///
268 /// `UdpSocket::bind()` does not allow setting custom options before binding.
269 pub fn create_udp_socket(
270 addr: &Ipv4Addr,
271 port: u16,
272 iface: Option<&InterfaceInfo>,
273 ) -> Result<UdpSocket, io::Error> {
274 use std::os::unix::io::FromRawFd;
275
276 /// Helper struct to keep a raw fd and close it on drop
277 struct Fd(i32);
278 impl Drop for Fd {
279 fn drop(&mut self) {
280 unsafe {
281 // SAFETY: The integer is a valid fd by construction.
282 let _ = close(self.0);
283 }
284 }
285 }
286
287 // SAFETY: Calling socket() is safe at any time and will simply fail if invalid parameters
288 // are passed.
289 let fd = unsafe {
290 #[cfg(any(
291 target_os = "linux",
292 target_os = "freebsd",
293 target_os = "openbsd",
294 target_os = "netbsd",
295 target_os = "dragonfly",
296 target_os = "solaris",
297 target_os = "illumos",
298 target_os = "hurd",
299 ))]
300 let ty = SOCK_DGRAM | SOCK_CLOEXEC;
301 #[cfg(target_os = "macos")]
302 let ty = SOCK_DGRAM;
303
304 let res = socket(AF_INET, ty, 0);
305 if res == -1 {
306 return Err(io::Error::last_os_error());
307 }
308 Fd(res)
309 };
310
311 // SAFETY: A valid socket fd is passed to ioctl() and setsockopt() and the parameters to
312 // setsockopt() are according to the type expected by SO_NOSIGPIPE.
313 #[cfg(target_os = "macos")]
314 unsafe {
315 let res = ioctl(fd.0, FIOCLEX);
316 if res == -1 {
317 return Err(io::Error::last_os_error());
318 }
319
320 let val = 1i32;
321 let res = setsockopt(
322 fd.0,
323 SOL_SOCKET,
324 SO_NOSIGPIPE,
325 &val as *const _ as *const _,
326 mem::size_of_val(&val) as _,
327 );
328 if res < 0 {
329 return Err(io::Error::last_os_error());
330 }
331 }
332
333 // SAFETY: A valid socket fd is passed here.
334 unsafe {
335 set_reuse(fd.0);
336 if let Some(iface) = iface {
337 bind_to_interface(fd.0, iface);
338 }
339 }
340
341 // SAFETY: A valid socket fd is passed together with a valid sockaddr_in and its size.
342 unsafe {
343 let addr = sockaddr_in {
344 sin_family: AF_INET as _,
345 sin_port: u16::to_be(port),
346 sin_addr: in_addr {
347 s_addr: u32::from_ne_bytes(addr.octets()),
348 },
349 sin_zero: [0u8; 8],
350 #[cfg(any(
351 target_os = "freebsd",
352 target_os = "openbsd",
353 target_os = "netbsd",
354 target_os = "dragonfly",
355 target_os = "macos",
356 target_os = "hurd",
357 ))]
358 sin_len: mem::size_of::<sockaddr_in>() as _,
359 };
360 let res = bind(
361 fd.0,
362 &addr as *const _ as *const _,
363 mem::size_of_val(&addr) as _,
364 );
365 if res < 0 {
366 return Err(io::Error::last_os_error());
367 }
368 }
369
370 unsafe { Ok(UdpSocket::from_raw_fd(mem::ManuallyDrop::new(fd).0)) }
371 }
372
373 /// Join multicast address for a given interface.
374 pub fn join_multicast_v4(
375 socket: &UdpSocket,
376 addr: &Ipv4Addr,
377 iface: &InterfaceInfo,
378 ) -> Result<(), Error> {
379 #[cfg(not(any(target_os = "solaris", target_os = "illumos", target_os = "macos")))]
380 {
381 let mreqn = ip_mreqn {
382 imr_multiaddr: in_addr {
383 s_addr: u32::from_ne_bytes(addr.octets()),
384 },
385 imr_address: in_addr {
386 s_addr: u32::from_ne_bytes(Ipv4Addr::UNSPECIFIED.octets()),
387 },
388 imr_ifindex: iface.index as _,
389 };
390
391 // SAFETY: Requires a valid ip_mreq or ip_mreqn struct to be passed together
392 // with its size for checking which of the two it is. On errors a negative
393 // integer is returned.
394 unsafe {
395 if setsockopt(
396 socket.as_raw_fd(),
397 IPPROTO_IP,
398 IP_ADD_MEMBERSHIP,
399 &mreqn as *const _ as *const _,
400 mem::size_of_val(&mreqn) as _,
401 ) < 0
402 {
403 bail!(
404 source: io::Error::last_os_error(),
405 "Failed joining multicast group for interface {}",
406 iface.name,
407 );
408 }
409 }
410
411 #[cfg(not(any(target_os = "openbsd", target_os = "dragonfly", target_os = "netbsd")))]
412 {
413 let mreqn = ip_mreqn {
414 imr_multiaddr: in_addr {
415 s_addr: u32::from_ne_bytes(Ipv4Addr::UNSPECIFIED.octets()),
416 },
417 imr_address: in_addr {
418 s_addr: u32::from_ne_bytes(Ipv4Addr::UNSPECIFIED.octets()),
419 },
420 imr_ifindex: iface.index as _,
421 };
422
423 // SAFETY: Requires a valid ip_mreq or ip_mreqn struct to be passed together
424 // with its size for checking which of the two it is. On errors a negative
425 // integer is returned.
426 unsafe {
427 if setsockopt(
428 socket.as_raw_fd(),
429 IPPROTO_IP,
430 IP_MULTICAST_IF,
431 &mreqn as *const _ as *const _,
432 mem::size_of_val(&mreqn) as _,
433 ) < 0
434 {
435 bail!(
436 source: io::Error::last_os_error(),
437 "Failed joining multicast group for interface {}",
438 iface.name,
439 );
440 }
441 }
442 }
443 #[cfg(any(target_os = "openbsd", target_os = "dragonfly"))]
444 {
445 let addr = in_addr {
446 s_addr: u32::from_ne_bytes(iface.ip_addr.octets()),
447 };
448
449 // SAFETY: Requires a valid in_addr struct to be passed together with its size for
450 // checking which of the two it is. On errors a negative integer is returned.
451 unsafe {
452 if setsockopt(
453 socket.as_raw_fd(),
454 IPPROTO_IP,
455 IP_MULTICAST_IF,
456 &addr as *const _ as *const _,
457 mem::size_of_val(&addr) as _,
458 ) < 0
459 {
460 bail!(
461 source: io::Error::last_os_error(),
462 "Failed joining multicast group for interface {}",
463 iface.name,
464 );
465 }
466 }
467 }
468 #[cfg(target_os = "netbsd")]
469 {
470 let idx = (iface.index as u32).to_be();
471
472 // SAFETY: Requires a valid in_addr struct or interface index in network byte order
473 // to be passed together with its size for checking which of the two it is. On
474 // errors a negative integer is returned.
475 unsafe {
476 if setsockopt(
477 socket.as_raw_fd(),
478 IPPROTO_IP,
479 IP_MULTICAST_IF,
480 &idx as *const _ as *const _,
481 mem::size_of_val(&idx) as _,
482 ) < 0
483 {
484 bail!(
485 source: io::Error::last_os_error(),
486 "Failed joining multicast group for interface {}",
487 iface.name,
488 );
489 }
490 }
491 }
492
493 Ok(())
494 }
495
496 #[cfg(any(target_os = "solaris", target_os = "illumos"))]
497 {
498 socket
499 .join_multicast_v4(addr, &iface.ip_addr)
500 .with_context(|| {
501 format!(
502 "Failed joining multicast group for interface {} at address {}",
503 iface.name, iface.ip_addr
504 )
505 })?;
506
507 let addr = in_addr {
508 s_addr: u32::from_ne_bytes(iface.ip_addr.octets()),
509 };
510
511 // SAFETY: Requires a valid in_addr struct to be passed together with its size for
512 // checking which of the two it is. On errors a negative integer is returned.
513 unsafe {
514 if setsockopt(
515 socket.as_raw_fd(),
516 IPPROTO_IP,
517 IP_MULTICAST_IF,
518 &addr as *const _ as *const _,
519 mem::size_of_val(&addr) as _,
520 ) < 0
521 {
522 bail!(
523 source: io::Error::last_os_error(),
524 "Failed setting multicast interface {}",
525 iface.name,
526 );
527 }
528 }
529
530 Ok(())
531 }
532
533 #[cfg(target_os = "macos")]
534 {
535 let mreq = ip_mreq {
536 imr_multiaddr: in_addr {
537 s_addr: u32::from_ne_bytes(addr.octets()),
538 },
539 imr_address: in_addr {
540 s_addr: u32::from_ne_bytes(iface.ip_addr.octets()),
541 },
542 };
543
544 let mreqn = ip_mreqn {
545 imr_multiaddr: in_addr {
546 s_addr: u32::from_ne_bytes(Ipv4Addr::UNSPECIFIED.octets()),
547 },
548 imr_address: in_addr {
549 s_addr: u32::from_ne_bytes(Ipv4Addr::UNSPECIFIED.octets()),
550 },
551 imr_ifindex: iface.index as _,
552 };
553
554 // SAFETY: Requires a valid ip_mreq struct to be passed together with its size for checking
555 // validity. On errors a negative integer is returned.
556 unsafe {
557 if setsockopt(
558 socket.as_raw_fd(),
559 IPPROTO_IP,
560 IP_ADD_MEMBERSHIP,
561 &mreq as *const _ as *const _,
562 mem::size_of_val(&mreq) as _,
563 ) < 0
564 {
565 bail!(
566 source: io::Error::last_os_error(),
567 "Failed joining multicast group for interface {}",
568 iface.name,
569 );
570 }
571 }
572
573 // SAFETY: Requires a valid ip_mreqn struct to be passed together
574 // with its size for checking which of the two it is. On errors a negative
575 // integer is returned.
576 unsafe {
577 if setsockopt(
578 socket.as_raw_fd(),
579 IPPROTO_IP,
580 IP_MULTICAST_IF,
581 &mreqn as *const _ as *const _,
582 mem::size_of_val(&mreqn) as _,
583 ) < 0
584 {
585 bail!(
586 source: io::Error::last_os_error(),
587 "Failed joining multicast group for interface {}",
588 iface.name,
589 );
590 }
591 }
592
593 Ok(())
594 }
595 }
596
597 /// Allow multiple sockets to bind to the same address / port.
598 ///
599 /// This is best-effort and might not actually do anything.
600 ///
601 /// SAFETY: Must be called with a valid socket fd.
602 unsafe fn set_reuse(socket: i32) {
603 // SAFETY: SO_REUSEADDR takes an i32 value that can be 0/false or 1/true and
604 // enables the given feature on the socket.
605 //
606 // We explicitly ignore errors here. If it works, good, if it doesn't then not much
607 // lost other than the ability to run multiple processes at once.
608 unsafe {
609 let v = 1i32;
610 let res = setsockopt(
611 socket,
612 SOL_SOCKET,
613 SO_REUSEADDR,
614 &v as *const _ as *const _,
615 mem::size_of_val(&v) as u32,
616 );
617 if res < 0 {
618 warn!("Failed to set SO_REUSEADDR on socket");
619 }
620 }
621
622 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
623 {
624 // SAFETY: SO_REUSEPORT takes an i32 value that can be 0/false or 1/true and
625 // enables the given feature on the socket.
626 //
627 // We explicitly ignore errors here. If it works, good, if it doesn't then not much
628 // lost other than the ability to run multiple processes at once.
629 unsafe {
630 let v = 1i32;
631 let res = setsockopt(
632 socket,
633 SOL_SOCKET,
634 SO_REUSEPORT,
635 &v as *const _ as *const _,
636 mem::size_of_val(&v) as u32,
637 );
638
639 if res < 0 {
640 warn!("Failed to set SO_REUSEPORT on socket");
641 }
642 }
643 }
644 }
645
646 /// Bind the socket to a specific interface.
647 ///
648 /// This is best-effort and might not actually do anything.
649 ///
650 /// SAFETY: Must be called with a valid socket fd.
651 #[cfg_attr(not(target_os = "linux"), allow(unused_variables))]
652 unsafe fn bind_to_interface(socket: i32, iface: &InterfaceInfo) {
653 // On Linux, go one step further and bind the socket completely to the socket if we
654 // can, i.e. have the relevant permissions.
655 #[cfg(target_os = "linux")]
656 {
657 // SAFETY: The socket passed in must be valid and the SO_BINDTOIFINDEX socket option
658 // takes an `i32` that represents the interface index as parameter.
659 let res = unsafe {
660 let v = iface.index as i32;
661 setsockopt(
662 socket,
663 SOL_SOCKET,
664 SO_BINDTOIFINDEX,
665 &v as *const _ as *const _,
666 mem::size_of_val(&v) as u32,
667 )
668 };
669
670 if res < 0 {
671 warn!("Failed to set SO_BINDTOIFINDEX on socket, trying SO_BINDTODEVICE");
672
673 if iface.name.len() >= 16 {
674 warn!(
675 "Interface name '{}' too long for SO_BINDTODEVICE",
676 iface.name
677 );
678 } else {
679 // SAFETY: The socket passed in must be valid and the SO_BINDTODEVICE socket option
680 // takes a NUL-terminated byte array of up to 16 bytes as parameter.
681 unsafe {
682 let mut v = [0u8; 16];
683
684 v[..iface.name.len()].copy_from_slice(iface.name.as_bytes());
685
686 let res = setsockopt(
687 socket,
688 SOL_SOCKET,
689 SO_BINDTODEVICE,
690 &v as *const _ as *const _,
691 (iface.name.len() + 1) as u32,
692 );
693
694 if res < 0 {
695 warn!("Failed to set SO_BINDTODEVICE on socket");
696 }
697 }
698 }
699 }
700 }
701 }
702 }
703
704 #[cfg(windows)]
705 mod imp {
706 use super::*;
707
708 use std::{
709 ffi::{CStr, OsString},
710 io, marker, mem,
711 net::{Ipv4Addr, SocketAddr, UdpSocket},
712 os::{
713 raw::*,
714 windows::{ffi::OsStringExt, io::AsRawSocket, raw::SOCKET},
715 },
716 ptr, slice,
717 };
718
719 use crate::{error::Context, ffi::windows::*};
720
721 /// Returns information for all non-loopback, multicast-capable network interfaces.
722 pub fn query_interfaces() -> Result<Vec<InterfaceInfo>, Error> {
723 struct AdapterAddresses {
724 addresses: ptr::NonNull<IP_ADAPTER_ADDRESSES_LH>,
725 heap: isize,
726 }
727
728 impl AdapterAddresses {
729 fn new() -> io::Result<Self> {
730 // SAFETY: Gets the process's default heap and is safe to be called at any time.
731 let heap = unsafe { GetProcessHeap() };
732
733 // SAFETY: GetAdaptersAddresses() requires allocated memory to be passed in.
734 // In the beginning 16kB are allocated via HeapAlloc() from the default process's
735 // heap (see above), then passed to GetAdaptersAddresses().
736 //
737 // If this returns ERROR_NOT_ENOUGH_MEMORY then this was not enough memory and the
738 // required amount is returned as out parameter. In that case we loop up to 10
739 // times, reallocate memory via HeapReAlloc() and try again.
740 //
741 // On other errors the memory is freed before returning via HeapFree(), or when 10
742 // iterations were reached.
743 unsafe {
744 let mut alloc_len = 16_384;
745 let mut tries = 0;
746 let mut addresses: *mut IP_ADAPTER_ADDRESSES_LH = ptr::null_mut();
747
748 loop {
749 if tries > 10 {
750 HeapFree(heap, 0, addresses as *mut _);
751 return Err(io::Error::from(io::ErrorKind::OutOfMemory));
752 }
753
754 if addresses.is_null() {
755 addresses = HeapAlloc(heap, 0, alloc_len as usize) as *mut _;
756 } else {
757 addresses =
758 HeapReAlloc(heap, 0, addresses as *mut _, alloc_len as usize)
759 as *mut _;
760 }
761 if addresses.is_null() {
762 return Err(io::Error::from(io::ErrorKind::OutOfMemory));
763 }
764
765 let res = GetAdaptersAddresses(
766 AF_INET,
767 GAA_FLAG_SKIP_ANYCAST
768 | GAA_FLAG_SKIP_MULTICAST
769 | GAA_FLAG_SKIP_DNS_SERVER,
770 ptr::null_mut(),
771 addresses,
772 &mut alloc_len,
773 );
774
775 if res == 0 {
776 return Ok(AdapterAddresses {
777 heap,
778 addresses: ptr::NonNull::new_unchecked(addresses),
779 });
780 } else if res == ERROR_NOT_ENOUGH_MEMORY {
781 tries += 1;
782 continue;
783 } else {
784 HeapFree(heap, 0, addresses as *mut _);
785 return Err(io::Error::from_raw_os_error(res as i32));
786 }
787 }
788 }
789 }
790
791 fn iter(&self) -> AdapterAddressesIter<'_> {
792 AdapterAddressesIter {
793 ptr: Some(self.addresses),
794 phantom: marker::PhantomData,
795 }
796 }
797 }
798
799 impl Drop for AdapterAddresses {
800 fn drop(&mut self) {
801 // SAFETY: The pointer is a valid IP_ADAPTER_ADDRESSES_LH pointer by construction
802 // and dropped only once, so freeing it here is OK. It might be NULL so check for
803 // that first.
804 //
805 // Heap is the process's heap as set in the constructor above.
806 unsafe {
807 HeapFree(self.heap, 0, self.addresses.as_ptr() as *mut _);
808 }
809 }
810 }
811
812 struct AdapterAddressesIter<'a> {
813 ptr: Option<ptr::NonNull<IP_ADAPTER_ADDRESSES_LH>>,
814 phantom: marker::PhantomData<&'a AdapterAddresses>,
815 }
816
817 impl<'a> Iterator for AdapterAddressesIter<'a> {
818 type Item = &'a IP_ADAPTER_ADDRESSES_LH;
819
820 fn next(&mut self) -> Option<Self::Item> {
821 match self.ptr {
822 None => None,
823 Some(ptr) => {
824 // SAFETY: The pointer is a valid IP_ADAPTER_ADDRESSES_LH pointer by
825 // construction so creating a reference to it is OK.
826 let addr = unsafe { &*ptr.as_ptr() };
827 self.ptr = ptr::NonNull::new(addr.next);
828 Some(addr)
829 }
830 }
831 }
832 }
833
834 struct UnicastAddressesIter<'a> {
835 ptr: Option<ptr::NonNull<IP_ADAPTER_UNICAST_ADDRESS_LH>>,
836 phantom: marker::PhantomData<&'a IP_ADAPTER_ADDRESSES_LH>,
837 }
838
839 impl<'a> UnicastAddressesIter<'a> {
840 fn new(addresses: &'a IP_ADAPTER_ADDRESSES_LH) -> Self {
841 Self {
842 ptr: ptr::NonNull::new(addresses.firstunicastaddress),
843 phantom: marker::PhantomData,
844 }
845 }
846 }
847
848 impl<'a> Iterator for UnicastAddressesIter<'a> {
849 type Item = &'a IP_ADAPTER_UNICAST_ADDRESS_LH;
850
851 fn next(&mut self) -> Option<Self::Item> {
852 match self.ptr {
853 None => None,
854 Some(ptr) => {
855 let addr = unsafe { &*ptr.as_ptr() };
856 self.ptr = ptr::NonNull::new(addr.next);
857 Some(addr)
858 }
859 }
860 }
861 }
862
863 let addresses = AdapterAddresses::new().context("Failed getting adapter addresses")?;
864 let mut if_infos = Vec::<InterfaceInfo>::new();
865 for address in addresses.iter() {
866 // SAFETY: adaptername points to a NUL-terminated ASCII name string that is valid
867 // as long as its struct is
868 let adaptername = unsafe { CStr::from_ptr(address.adaptername as *const c_char) }
869 .to_str()
870 .unwrap();
871
872 // Skip adapters that are receive-only, can't do multicast or don't have IPv4 support
873 // as they're not usable in a PTP context.
874 if address.flags & ADAPTER_FLAG_RECEIVE_ONLY != 0 {
875 debug!("Interface {} is receive-only interface", adaptername);
876 continue;
877 }
878 if address.flags & ADAPTER_FLAG_NO_MULTICAST != 0 {
879 debug!("Interface {} does not support multicast", adaptername);
880 continue;
881 }
882 if address.flags & ADAPTER_FLAG_IPV4_ENABLED == 0 {
883 debug!("Interface {} has no IPv4 address", adaptername);
884 continue;
885 }
886
887 // Skip adapters that are loopback or not up.
888 if address.iftype == IF_TYPE_SOFTWARE_LOOPBACK {
889 debug!("Interface {} is loopback interface", adaptername);
890 continue;
891 }
892 if address.operstatus != IF_OPER_STATUS_UP {
893 debug!("Interface {} is not up", adaptername);
894 continue;
895 }
896
897 // SAFETY: Both fields of the union are always valid
898 let index = unsafe { address.anonymous.anonymous.ifindex } as usize;
899 // Skip adapters that have no valid interface index as they can't be used to join the
900 // PTP multicast group reliably for this interface only.
901 if index == 0 {
902 debug!("Interface {} has no valid interface index", adaptername);
903 continue;
904 }
905
906 // SAFETY: friendlyname is a NUL-terminated UCS2/wide string or NULL.
907 let friendlyname = unsafe {
908 if !address.friendlyname.is_null() {
909 let len = {
910 let mut len = 0;
911 while *address.friendlyname.add(len) != 0 {
912 len += 1;
913 }
914 len
915 };
916
917 let f = slice::from_raw_parts(address.friendlyname, len);
918 let f = OsString::from_wide(f);
919 Some(String::from(f.to_str().unwrap()))
920 } else {
921 None
922 }
923 };
924
925 let mut hw_addr = None;
926 if address.physicaladdresslength == 6 {
927 let mut addr = [0u8; 6];
928 addr.copy_from_slice(&address.physicaladdress[..6]);
929 hw_addr = Some(addr);
930 }
931
932 let ip_addr = UnicastAddressesIter::new(address).find_map(|addr| {
933 if addr.address.lpsocketaddr.is_null() {
934 return None;
935 }
936
937 // SAFETY: lpsocketaddr is a valid, non-NULL socket address and its family
938 // field can be read to distinguish IPv4 and other socket addresses
939 if unsafe { (*addr.address.lpsocketaddr).sa_family } != AF_INET as u16 {
940 return None;
941 }
942
943 Some(Ipv4Addr::from(
944 // SAFETY: lpsocketaddr is a valid, non-NULL IPv4 socket address as checked
945 // above and can be dereferenced as such.
946 unsafe {
947 (*addr.address.lpsocketaddr)
948 .in_addr
949 .S_un
950 .S_addr
951 .to_ne_bytes()
952 },
953 ))
954 });
955
956 if let Some(ip_addr) = ip_addr {
957 if_infos.push(InterfaceInfo {
958 name: String::from(adaptername),
959 other_name: friendlyname,
960 index,
961 ip_addr,
962 hw_addr,
963 });
964 } else {
965 debug!("Interface {} has no IPv4 address", adaptername);
966 }
967 }
968
969 Ok(if_infos)
970 }
971
972 /// Create an `UdpSocket` and bind it to the given address but set `SO_REUSEADDR` and/or
973 /// `SO_REUSEPORT` before doing so.
974 ///
975 /// `UdpSocket::bind()` does not allow setting custom options before binding.
976 pub fn create_udp_socket(
977 addr: &Ipv4Addr,
978 port: u16,
979 _iface: Option<&InterfaceInfo>,
980 ) -> Result<UdpSocket, io::Error> {
981 use std::os::windows::io::FromRawSocket;
982
983 // XXX: Make sure Rust std is calling WSAStartup()
984 let _ = UdpSocket::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))?;
985
986 /// Helper struct to keep a raw socket and close it on drop
987 struct Socket(SOCKET);
988 impl Drop for Socket {
989 fn drop(&mut self) {
990 unsafe {
991 // SAFETY: The socket is valid by construction.
992 let _ = closesocket(self.0);
993 }
994 }
995 }
996
997 // SAFETY: Calling WSASocketW() is safe at any time and will simply fail if invalid parameters
998 // are passed or something else goes wrong.
999 let socket = unsafe {
1000 let res = WSASocketW(
1001 AF_INET as _,
1002 SOCK_DGRAM as _,
1003 0,
1004 ptr::null_mut(),
1005 0,
1006 WSA_FLAG_OVERLAPPED | WSA_FLAG_NO_HANDLE_INHERIT,
1007 );
1008 if res == INVALID_SOCKET {
1009 return Err(io::Error::from_raw_os_error(WSAGetLastError()));
1010 }
1011 Socket(res)
1012 };
1013
1014 // SAFETY: A valid socket is passed here.
1015 unsafe {
1016 set_reuse(socket.0);
1017 }
1018
1019 // SAFETY: A valid socket fd is passed together with a valid SOCKADDR and its size.
1020 unsafe {
1021 let addr = SOCKADDR {
1022 sa_family: AF_INET as _,
1023 sin_port: u16::to_be(port),
1024 in_addr: IN_ADDR {
1025 S_un: IN_ADDR_0 {
1026 S_addr: u32::from_ne_bytes(addr.octets()),
1027 },
1028 },
1029 sin_zero: [0; 8],
1030 };
1031 let res = bind(socket.0, &addr, mem::size_of_val(&addr) as _);
1032 if res < 0 {
1033 return Err(io::Error::from_raw_os_error(WSAGetLastError()));
1034 }
1035 }
1036
1037 unsafe { Ok(UdpSocket::from_raw_socket(mem::ManuallyDrop::new(socket).0)) }
1038 }
1039
1040 // Join multicast address for a given interface.
1041 pub fn join_multicast_v4(
1042 socket: &UdpSocket,
1043 addr: &Ipv4Addr,
1044 iface: &InterfaceInfo,
1045 ) -> Result<(), Error> {
1046 let mreq = IP_MREQ {
1047 imr_multiaddr: IN_ADDR {
1048 S_un: IN_ADDR_0 {
1049 S_addr: u32::from_ne_bytes(addr.octets()),
1050 },
1051 },
1052 imr_address: IN_ADDR {
1053 S_un: IN_ADDR_0 {
1054 S_addr: u32::from_ne_bytes(Ipv4Addr::new(0, 0, 0, iface.index as u8).octets()),
1055 },
1056 },
1057 };
1058
1059 // SAFETY: Requires a valid ip_mreq struct to be passed together with its size for checking
1060 // validity. On errors a negative integer is returned.
1061 unsafe {
1062 if setsockopt(
1063 socket.as_raw_socket(),
1064 IPPROTO_IP as i32,
1065 IP_ADD_MEMBERSHIP as i32,
1066 &mreq as *const _ as *const _,
1067 mem::size_of_val(&mreq) as _,
1068 ) < 0
1069 {
1070 bail!(
1071 source: io::Error::from_raw_os_error(WSAGetLastError()),
1072 "Failed joining multicast group for interface {}",
1073 iface.name,
1074 );
1075 }
1076 }
1077
1078 let addr = IN_ADDR {
1079 S_un: IN_ADDR_0 {
1080 S_addr: u32::from_ne_bytes(Ipv4Addr::new(0, 0, 0, iface.index as u8).octets()),
1081 },
1082 };
1083
1084 // SAFETY: Requires a valid IN_ADDR struct to be passed together with its size for checking
1085 // which of the two it is. On errors a negative integer is returned.
1086 unsafe {
1087 if setsockopt(
1088 socket.as_raw_socket(),
1089 IPPROTO_IP as i32,
1090 IP_MULTICAST_IF as i32,
1091 &addr as *const _ as *const _,
1092 mem::size_of_val(&addr) as _,
1093 ) < 0
1094 {
1095 bail!(
1096 source: io::Error::last_os_error(),
1097 "Failed joining multicast group for interface {}",
1098 iface.name,
1099 );
1100 }
1101 }
1102
1103 Ok(())
1104 }
1105
1106 /// Allow multiple sockets to bind to the same address / port.
1107 ///
1108 /// This is best-effort and might not actually do anything.
1109 ///
1110 /// SAFETY: Must be called with a valid socket.
1111 unsafe fn set_reuse(socket: SOCKET) {
1112 // SAFETY: SO_REUSEADDR takes an i32 value that can be 0/false or 1/true and
1113 // enables the given feature on the socket.
1114 //
1115 // We explicitly ignore errors here. If it works, good, if it doesn't then not much
1116 // lost other than the ability to run multiple processes at once.
1117 unsafe {
1118 let v = 1i32;
1119 let res = setsockopt(
1120 socket,
1121 SOL_SOCKET as i32,
1122 SO_REUSEADDR as i32,
1123 &v as *const _ as *const _,
1124 mem::size_of_val(&v) as _,
1125 );
1126 if res < 0 {
1127 warn!("Failed to set SO_REUSEADDR on socket");
1128 }
1129 }
1130 }
1131 }
1132
1133 pub use imp::*;
1134
1135 #[cfg(test)]
1136 mod test {
1137 #[test]
1138 fn test_query_interfaces() {
1139 let ifaces = super::query_interfaces().unwrap();
1140 for iface in ifaces {
1141 assert!(!iface.name.is_empty());
1142 assert_ne!(iface.index, 0);
1143 assert!(!iface.ip_addr.is_unspecified());
1144 }
1145 }
1146
1147 #[test]
1148 fn test_create_socket_join_multicast() {
1149 let ifaces = super::query_interfaces().unwrap();
1150 let iface = if ifaces.is_empty() {
1151 return;
1152 } else {
1153 &ifaces[0]
1154 };
1155
1156 let socket = super::create_udp_socket(&std::net::Ipv4Addr::UNSPECIFIED, 0, None).unwrap();
1157 super::join_multicast_v4(&socket, &std::net::Ipv4Addr::new(224, 0, 0, 1), iface).unwrap();
1158
1159 let local_addr = socket.local_addr().unwrap();
1160
1161 let socket2 = std::net::UdpSocket::bind(std::net::SocketAddr::from((
1162 std::net::Ipv4Addr::UNSPECIFIED,
1163 0,
1164 )))
1165 .unwrap();
1166 socket2
1167 .send_to(
1168 &[1, 2, 3, 4],
1169 std::net::SocketAddr::from((std::net::Ipv4Addr::LOCALHOST, local_addr.port())),
1170 )
1171 .unwrap();
1172 let mut buf = [0u8; 4];
1173 socket.recv(&mut buf).unwrap();
1174 assert_eq!(buf, [1, 2, 3, 4]);
1175 }
1176 }