Skip to main content

viva_gige/
nic.rs

1//! Network interface utilities for GigE Vision streaming.
2//!
3//! This module provides helpers for querying network interface capabilities and
4//! constructing UDP sockets tuned for high-throughput GVSP traffic. The
5//! functionality is intentionally conservative so it can operate on most Unix
6//! like systems without additional privileges. Platform specific code paths are
7//! gated via conditional compilation and otherwise fall back to sane defaults.
8
9#[cfg(any(target_os = "linux", target_os = "android"))]
10use std::fs;
11use std::io;
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket as StdUdpSocket};
13use std::time::Duration;
14
15use if_addrs::IfAddr;
16use socket2::{Domain, Protocol, SockRef, Socket, Type};
17use tokio::net::UdpSocket;
18use tracing::{debug, info};
19
20#[cfg(any(target_os = "linux", target_os = "android", windows))]
21use tracing::warn;
22
23/// Default socket receive buffer size used when the caller does not provide a
24/// custom value. The number mirrors what many operating systems allow without
25/// requiring elevated privileges.
26pub const DEFAULT_RCVBUF_BYTES: usize = 4 << 20; // 4 MiB
27
28/// A socket receive buffer: what was asked for and what the kernel granted.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct RecvBuffer {
31    /// Bytes requested with `SO_RCVBUF`.
32    pub requested: usize,
33    /// Bytes the kernel holds for datagrams, read back after the request.
34    ///
35    /// Linux reports twice what it will queue — it doubles the request for
36    /// bookkeeping, `socket(7)` — so the read-back is halved there to compare
37    /// like with like.
38    pub granted: usize,
39}
40
41impl RecvBuffer {
42    /// Whether the kernel granted less than half of the request — the point at
43    /// which a burst the size of a frame no longer fits and the overflow is
44    /// dropped by the kernel, where no counter of ours can see it.
45    pub fn is_short(&self) -> bool {
46        self.granted < self.requested / 2
47    }
48
49    /// The system limit that capped the request, by name, for the warning.
50    pub fn limit_hint() -> &'static str {
51        if cfg!(any(target_os = "linux", target_os = "android")) {
52            "raise net.core.rmem_max (sysctl -w net.core.rmem_max=<bytes>)"
53        } else if cfg!(any(
54            target_os = "macos",
55            target_os = "ios",
56            target_os = "freebsd",
57            target_os = "openbsd",
58            target_os = "netbsd",
59            target_os = "dragonfly"
60        )) {
61            "raise kern.ipc.maxsockbuf (sysctl -w kern.ipc.maxsockbuf=<bytes>)"
62        } else {
63            "raise the system's socket receive-buffer limit"
64        }
65    }
66}
67
68/// Request `requested` bytes of `SO_RCVBUF` and read back what was granted.
69///
70/// An oversized request is normally capped silently — Linux at
71/// `net.core.rmem_max`, macOS at a limit derived from `kern.ipc.maxsockbuf` —
72/// which is why the granted size is read back rather than assumed. Should a
73/// system refuse instead (`ENOBUFS`), the request is retried at half the size
74/// down to 64 KiB, so the socket still gets the largest buffer allowed and a
75/// read-back that says how far short of the request it is.
76fn request_recv_buffer(socket: SockRef<'_>, requested: usize) -> io::Result<RecvBuffer> {
77    const FLOOR: usize = 64 * 1024;
78    let mut ask = requested;
79    loop {
80        match socket.set_recv_buffer_size(ask) {
81            Ok(()) => break,
82            Err(_) if ask > FLOOR => ask /= 2,
83            Err(err) => return Err(err),
84        }
85    }
86    let reported = socket.recv_buffer_size()?;
87    let granted = if cfg!(any(target_os = "linux", target_os = "android")) {
88        reported / 2
89    } else {
90        reported
91    };
92    Ok(RecvBuffer { requested, granted })
93}
94
95/// Size a stream socket's receive buffer and report what the kernel granted.
96///
97/// The caller decides what a shortfall means; [`RecvBuffer::is_short`] and
98/// [`RecvBuffer::limit_hint`] say whether to warn and what to raise.
99pub fn set_recv_buffer(socket: &StdUdpSocket, requested: usize) -> io::Result<RecvBuffer> {
100    request_recv_buffer(SockRef::from(socket), requested)
101}
102
103/// Maximum length for interface names. On Linux this matches `IFNAMSIZ - 1`
104/// (15). On Windows, interface names are GUIDs like
105/// `{F5DA665D-1913-11F1-9F17-806E6F6E6963}` (38 chars), so a larger limit
106/// is needed.
107#[cfg(not(target_os = "windows"))]
108const IFACE_NAME_MAX: usize = 15;
109#[cfg(target_os = "windows")]
110const IFACE_NAME_MAX: usize = 64;
111
112/// Resolve an interface index from its name using platform-specific APIs.
113#[cfg(any(target_os = "linux", target_os = "android"))]
114fn iface_name_to_index(name: &str) -> io::Result<u32> {
115    let index_path = format!("/sys/class/net/{name}/ifindex");
116    fs::read_to_string(&index_path)
117        .map_err(|err| io::Error::new(err.kind(), format!("{index_path}: {err}")))?
118        .trim()
119        .parse::<u32>()
120        .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
121}
122
123/// Resolve an interface index from its name using `if_nametoindex(3)`.
124#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
125fn iface_name_to_index(name: &str) -> io::Result<u32> {
126    use std::ffi::CString;
127
128    let c_name = CString::new(name).map_err(|_| {
129        io::Error::new(
130            io::ErrorKind::InvalidInput,
131            format!("interface name contains null byte: '{name}'"),
132        )
133    })?;
134    // SAFETY: `if_nametoindex` is a POSIX function that takes a valid C string.
135    let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) };
136    if index == 0 {
137        Err(io::Error::new(
138            io::ErrorKind::NotFound,
139            format!("interface '{name}' not found"),
140        ))
141    } else {
142        Ok(index)
143    }
144}
145
146/// Resolve an interface index from its name on Windows.
147#[cfg(target_os = "windows")]
148fn iface_name_to_index(name: &str) -> io::Result<u32> {
149    // Last resort only: `Iface::resolve` prefers `if_addrs`'s `index`, which
150    // on Windows comes from the adapter's real `IfIndex`. This positional
151    // fallback runs only when the OS reported index 0 ("unknown"), and its
152    // result is a guess rather than a kernel interface index.
153    for (idx, iface) in if_addrs::get_if_addrs()?.iter().enumerate() {
154        if iface.name == name {
155            return Ok((idx + 1) as u32);
156        }
157    }
158    Err(io::Error::new(
159        io::ErrorKind::NotFound,
160        format!("interface '{name}' not found"),
161    ))
162}
163
164/// Representation of a host network interface.
165#[derive(Debug, Clone, PartialEq, Eq)]
166pub struct Iface {
167    name: String,
168    index: u32,
169    ipv4: Option<Ipv4Addr>,
170    ipv6: Option<Ipv6Addr>,
171}
172
173impl Iface {
174    /// Resolve an interface from the operating system by its name.
175    ///
176    /// When the interface carries several IPv4 addresses the first one is
177    /// used; [`Iface::from_ipv4`] preserves the address that was asked for.
178    pub fn from_system(name: &str) -> io::Result<Self> {
179        Self::resolve(name, None)
180    }
181
182    /// Resolve an interface by one of its IPv4 addresses.
183    ///
184    /// The resulting [`Iface`] reports `addr` itself, not whichever address
185    /// the OS happens to list last for that interface. A multi-homed NIC —
186    /// a stale DHCP lease alongside a link-local address, say — would
187    /// otherwise resolve to a different address than the caller selected
188    /// and bind the socket to the wrong one (#57).
189    pub fn from_ipv4(addr: Ipv4Addr) -> io::Result<Self> {
190        for iface in if_addrs::get_if_addrs()? {
191            if let IfAddr::V4(v4) = iface.addr
192                && v4.ip == addr
193            {
194                return Self::resolve(&iface.name, Some(addr));
195            }
196        }
197        Err(io::Error::new(
198            io::ErrorKind::NotFound,
199            format!("no interface with IPv4 {addr}"),
200        ))
201    }
202
203    /// Resolve the local interface selected by the operating system for a
204    /// remote IPv4 address.
205    pub fn from_remote_ipv4(remote: Ipv4Addr) -> io::Result<Self> {
206        const GVCP_PORT: u16 = 3956;
207
208        let socket = StdUdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).map_err(|err| {
209            io::Error::new(
210                err.kind(),
211                format!("failed to create route probe for remote IPv4 {remote}: {err}"),
212            )
213        })?;
214        socket.connect((remote, GVCP_PORT)).map_err(|err| {
215            io::Error::new(
216                err.kind(),
217                format!("failed to resolve route to remote IPv4 {remote}: {err}"),
218            )
219        })?;
220        let local = match socket.local_addr()?.ip() {
221            IpAddr::V4(local) => local,
222            IpAddr::V6(_) => {
223                return Err(io::Error::new(
224                    io::ErrorKind::AddrNotAvailable,
225                    format!("route to remote IPv4 {remote} selected an IPv6 address"),
226                ));
227            }
228        };
229
230        Self::from_ipv4(local).map_err(|err| {
231            io::Error::new(
232                err.kind(),
233                format!(
234                    "route to remote IPv4 {remote} selected local IPv4 {local}, \
235                     but its interface could not be resolved: {err}"
236                ),
237            )
238        })
239    }
240
241    /// Every interface the operating system reports, one entry per name.
242    ///
243    /// This is the library's own view of the machine, which is the point: #57
244    /// was an interface that existed but that we could not see, and no amount
245    /// of `ipconfig` output would have shown that. Ordered by name so two
246    /// runs can be diffed.
247    pub fn list() -> io::Result<Vec<Self>> {
248        let mut names: Vec<String> = if_addrs::get_if_addrs()?
249            .into_iter()
250            .map(|iface| iface.name)
251            .collect();
252        names.sort();
253        names.dedup();
254        Ok(names
255            .into_iter()
256            .filter_map(|name| Self::from_system(&name).ok())
257            .collect())
258    }
259
260    /// Every IPv4 address assigned to this interface.
261    ///
262    /// [`Iface::ipv4`] reports the one the socket will bind to; a multi-homed
263    /// NIC has more, and which ones they are is exactly the question #57
264    /// turned on.
265    pub fn all_ipv4(&self) -> io::Result<Vec<Ipv4Addr>> {
266        Ok(if_addrs::get_if_addrs()?
267            .into_iter()
268            .filter(|iface| iface.name == self.name)
269            .filter_map(|iface| match iface.addr {
270                IfAddr::V4(v4) => Some(v4.ip),
271                IfAddr::V6(_) => None,
272            })
273            .collect())
274    }
275
276    fn resolve(name: &str, preferred: Option<Ipv4Addr>) -> io::Result<Self> {
277        if name.is_empty() || name.len() > IFACE_NAME_MAX {
278            return Err(io::Error::new(
279                io::ErrorKind::InvalidInput,
280                format!("invalid interface name '{name}'"),
281            ));
282        }
283
284        let mut ipv4: Option<Ipv4Addr> = None;
285        let mut ipv6 = None;
286        // `if_addrs` reports the kernel's own interface index where the
287        // platform exposes it, which is what multicast joins need.
288        let mut index: Option<u32> = None;
289        let mut found = false;
290        for iface in if_addrs::get_if_addrs()? {
291            if iface.name != name {
292                continue;
293            }
294            found = true;
295            index = index.or(iface.index);
296            match iface.addr {
297                IfAddr::V4(v4) => {
298                    // Take the requested address if we see it, otherwise the
299                    // first one, and never let a later address displace it.
300                    if Some(v4.ip) == preferred || ipv4.is_none() {
301                        ipv4 = Some(v4.ip);
302                    }
303                }
304                IfAddr::V6(v6) => {
305                    if ipv6.is_none() {
306                        ipv6 = Some(v6.ip);
307                    }
308                }
309            }
310        }
311
312        // An interface with no address at all is still resolvable by name.
313        let index = match index {
314            Some(index) => index,
315            None => iface_name_to_index(name)?,
316        };
317        if !found && ipv4.is_none() && ipv6.is_none() {
318            // `iface_name_to_index` already errors for an unknown name on
319            // every platform, so reaching here means the name is valid but
320            // unaddressed.
321            debug!(name, "interface has no assigned IP address");
322        }
323
324        Ok(Self {
325            name: name.to_string(),
326            index,
327            ipv4,
328            ipv6,
329        })
330    }
331
332    /// Interface name as provided by the operating system (e.g. `eth0`).
333    pub fn name(&self) -> &str {
334        &self.name
335    }
336
337    /// Interface index as reported by the kernel. The index is used by some
338    /// socket options (e.g. multicast subscriptions).
339    pub fn index(&self) -> u32 {
340        self.index
341    }
342
343    /// Primary IPv4 address associated with the interface, if any.
344    pub fn ipv4(&self) -> Option<Ipv4Addr> {
345        self.ipv4
346    }
347
348    /// Primary IPv6 address associated with the interface, if any.
349    #[allow(dead_code)]
350    pub fn ipv6(&self) -> Option<Ipv6Addr> {
351        self.ipv6
352    }
353}
354
355/// How a user names a host interface on a command line or in an API call.
356///
357/// Parsed as an IPv4 literal first and taken as an operating-system interface
358/// name otherwise. The two spellings cannot collide: an interface name that
359/// parses as an IPv4 address does not exist on any platform we support.
360///
361/// Both spellings are needed. A Windows interface name is a GUID
362/// (`{6394C55F-F630-4BC7-92D2-7AC320C73D1C}`), which a user has no easy way to
363/// obtain, so IPv4 has to work; and an interface that carries no address yet
364/// can only be named, so the name has to work too. Before this existed
365/// `viva-camctl` accepted only the address and `viva-service` only the name,
366/// and a user who had discovered a camera with one tool could not stream it
367/// with the other ([#109](https://github.com/VitalyVorobyev/viva-genicam/issues/109)).
368#[derive(Debug, Clone, PartialEq, Eq)]
369#[non_exhaustive]
370pub enum IfaceSelector {
371    /// One of the interface's own IPv4 addresses, e.g. `169.254.105.106`.
372    Ipv4(Ipv4Addr),
373    /// The name the operating system gives the interface, e.g. `en0`.
374    Name(String),
375}
376
377impl IfaceSelector {
378    /// Resolve the selector against the interfaces this host reports.
379    ///
380    /// Delegates to [`Iface::from_ipv4`] or [`Iface::from_system`]; the only
381    /// thing added here is the failure message, which lists what we can
382    /// actually see. That listing is the point rather than a nicety: the
383    /// Windows GUID a user needs is not discoverable from the error it
384    /// replaces, and `Iface::list` is already the library's own view of the
385    /// machine (#57).
386    pub fn resolve(&self) -> io::Result<Iface> {
387        let resolved = match self {
388            Self::Ipv4(addr) => Iface::from_ipv4(*addr),
389            Self::Name(name) => Iface::from_system(name),
390        };
391        resolved.map_err(|err| io::Error::new(err.kind(), format!("{err}{}", available())))
392    }
393}
394
395impl std::str::FromStr for IfaceSelector {
396    type Err = std::convert::Infallible;
397
398    fn from_str(s: &str) -> Result<Self, Self::Err> {
399        Ok(match s.parse::<Ipv4Addr>() {
400            Ok(addr) => Self::Ipv4(addr),
401            Err(_) => Self::Name(s.to_string()),
402        })
403    }
404}
405
406impl std::fmt::Display for IfaceSelector {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        match self {
409            Self::Ipv4(addr) => write!(f, "{addr}"),
410            Self::Name(name) => f.write_str(name),
411        }
412    }
413}
414
415/// The interfaces this host reports, formatted for appending to an error.
416///
417/// Returns an empty string when the enumeration itself fails, so a failure to
418/// explain never replaces the failure being explained.
419fn available() -> String {
420    let Ok(ifaces) = Iface::list() else {
421        return String::new();
422    };
423    if ifaces.is_empty() {
424        return String::new();
425    }
426    let mut out = String::from("\n  interfaces this host reports:");
427    for iface in ifaces {
428        let addrs = iface.all_ipv4().unwrap_or_default();
429        out.push_str(&format!("\n    {}", iface.name()));
430        if !addrs.is_empty() {
431            let list: Vec<String> = addrs.iter().map(|a| a.to_string()).collect();
432            out.push_str(&format!("  {}", list.join(", ")));
433        }
434    }
435    out
436}
437
438/// An interface MTU, and whether the operating system reported it.
439#[derive(Debug, Clone, Copy, PartialEq, Eq)]
440pub enum Mtu {
441    /// The operating system reported this MTU.
442    Measured(u32),
443    /// The lookup failed, or this platform has none: Ethernet's 1500 bytes,
444    /// [`ASSUMED_MTU`], stands in.
445    Assumed(u32),
446}
447
448/// The MTU assumed when the operating system does not report one.
449pub const ASSUMED_MTU: u32 = 1500;
450
451impl Mtu {
452    /// The MTU in bytes, measured or assumed.
453    pub fn bytes(self) -> u32 {
454        match self {
455            Mtu::Measured(bytes) | Mtu::Assumed(bytes) => bytes,
456        }
457    }
458
459    /// Whether the operating system reported it.
460    pub fn is_measured(self) -> bool {
461        matches!(self, Mtu::Measured(_))
462    }
463}
464
465impl std::fmt::Display for Mtu {
466    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467        match self {
468            Mtu::Measured(bytes) => write!(f, "{bytes}"),
469            Mtu::Assumed(bytes) => write!(f, "{bytes} (assumed)"),
470        }
471    }
472}
473
474/// Read the MTU configured for the provided interface.
475///
476/// Linux reads `/sys/class/net/<iface>/mtu`, Windows `GetIfEntry2`, macOS
477/// the link-layer entry's `if_data.ifi_mtu` from `getifaddrs(3)`. Anything
478/// else, or a failed lookup, is [`Mtu::Assumed`] at [`ASSUMED_MTU`].
479pub fn mtu(_iface: &Iface) -> Mtu {
480    #[cfg(target_os = "linux")]
481    {
482        let path = format!("/sys/class/net/{}/mtu", _iface.name());
483        match fs::read_to_string(path) {
484            Ok(contents) => match contents.trim().parse::<u32>() {
485                Ok(mtu) => {
486                    tracing::debug!(name = _iface.name(), mtu, "resolved interface MTU");
487                    return Mtu::Measured(mtu);
488                }
489                Err(err) => {
490                    warn!(name = _iface.name(), error = %err, "unreadable MTU, using default");
491                }
492            },
493            Err(err) => {
494                warn!(name = _iface.name(), error = %err, "failed to read MTU, using default");
495            }
496        }
497    }
498
499    #[cfg(windows)]
500    {
501        use windows_sys::Win32::NetworkManagement::IpHelper::{GetIfEntry2, MIB_IF_ROW2};
502
503        let mut row = MIB_IF_ROW2 {
504            InterfaceIndex: _iface.index(),
505            ..Default::default()
506        };
507        let status = unsafe { GetIfEntry2(&mut row) };
508        if status == 0 {
509            tracing::debug!(
510                name = _iface.name(),
511                mtu = row.Mtu,
512                "resolved interface MTU"
513            );
514            return Mtu::Measured(row.Mtu);
515        }
516
517        let err = io::Error::from_raw_os_error(status as i32);
518        warn!(
519            name = _iface.name(),
520            error = %err,
521            "failed to read MTU, using default"
522        );
523    }
524
525    #[cfg(any(target_os = "macos", target_os = "ios"))]
526    match link_mtu(_iface.name()) {
527        Some(mtu) => {
528            tracing::debug!(name = _iface.name(), mtu, "resolved interface MTU");
529            return Mtu::Measured(mtu);
530        }
531        None => {
532            debug!(
533                name = _iface.name(),
534                "no link-layer address entry for the interface; using an MTU of 1500"
535            );
536        }
537    }
538
539    Mtu::Assumed(ASSUMED_MTU)
540}
541
542/// The MTU of interface `name` from its `AF_LINK` entry in `getifaddrs(3)`,
543/// whose `ifa_data` is the interface's `struct if_data` (TC-11).
544#[cfg(any(target_os = "macos", target_os = "ios"))]
545fn link_mtu(name: &str) -> Option<u32> {
546    use std::ffi::CStr;
547
548    let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
549    // SAFETY: `getifaddrs` fills `list` with a linked list it allocates, which
550    // is released with `freeifaddrs` below on every path that got one.
551    if unsafe { libc::getifaddrs(&mut list) } != 0 {
552        return None;
553    }
554    let mut found = None;
555    let mut entry = list;
556    while !entry.is_null() {
557        // SAFETY: `entry` is a node of the list `getifaddrs` returned, not yet
558        // freed; its name is a NUL-terminated C string.
559        let ifa = unsafe { &*entry };
560        let is_link = !ifa.ifa_addr.is_null()
561            // SAFETY: `ifa_addr` was checked non-null and points at a sockaddr.
562            && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_LINK;
563        // SAFETY: as above, `ifa_name` is a valid C string for the list's lifetime.
564        let same_name = unsafe { CStr::from_ptr(ifa.ifa_name) }.to_bytes() == name.as_bytes();
565        if is_link && same_name && !ifa.ifa_data.is_null() {
566            // SAFETY: for an `AF_LINK` entry, `ifa_data` points at the
567            // interface's `struct if_data`.
568            let data = unsafe { &*(ifa.ifa_data as *const libc::if_data) };
569            found = Some(data.ifi_mtu);
570            break;
571        }
572        entry = ifa.ifa_next;
573    }
574    // SAFETY: `list` came from a successful `getifaddrs` and is freed once.
575    unsafe { libc::freeifaddrs(list) };
576    found
577}
578
579/// Largest packet an IPv4 datagram can carry.
580///
581/// The IPv4 total-length field is 16 bits, so no datagram can exceed this no
582/// matter how large the link MTU claims to be. Loopback interfaces routinely
583/// report more: Linux `lo` is 65536 and macOS `lo0` is 16384.
584const MAX_IPV4_PACKET_SIZE: u32 = 65535;
585
586/// Compute an optimal GVSP packet size from the link MTU.
587///
588/// `GevSCPSPacketSize` is the transmitted IP packet size, so it tracks the link
589/// MTU rather than subtracting Ethernet, IPv4, or UDP headers — corroborated by
590/// aravis, which derives its payload block size as
591/// `packet_size - (IP + UDP + GVSP headers)` and so excludes L2 from the
592/// negotiated value (`ARV_GVSP_PACKET_PROTOCOL_OVERHEAD`).
593///
594/// The MTU is clamped to 65535, the largest an IPv4 datagram can be, because an
595/// unclamped value is not merely suboptimal, it is unsendable: on Linux
596/// loopback (MTU 65536) the
597/// sender would build a `65536 - 36` byte payload and a 65508-byte UDP datagram,
598/// one byte past the 65507-byte maximum, and `send_to` fails for every packet.
599pub fn best_packet_size(mtu: u32) -> u32 {
600    mtu.min(MAX_IPV4_PACKET_SIZE)
601}
602
603/// Multicast socket options applied while binding.
604#[derive(Debug, Clone)]
605pub struct McOptions {
606    /// Whether multicast packets sent locally should be looped back (Unix;
607    /// Windows applies the option to receiving, and keeps it on).
608    pub loopback: bool,
609    /// IPv4 time-to-live for outbound multicast packets.
610    pub ttl: u32,
611    /// Receive buffer size in bytes.
612    pub rcvbuf_bytes: usize,
613    /// Whether to enable address/port reuse when binding.
614    pub reuse_addr: bool,
615}
616
617impl Default for McOptions {
618    fn default() -> Self {
619        Self {
620            loopback: false,
621            ttl: 1,
622            rcvbuf_bytes: DEFAULT_RCVBUF_BYTES,
623            reuse_addr: true,
624        }
625    }
626}
627
628/// Bind a UDP socket configured for GVSP traffic.
629///
630/// `port` 0 lets the operating system choose a free port; read it back with
631/// `local_addr`. The socket is bound without `SO_REUSEADDR` or
632/// `SO_REUSEPORT`: a unicast stream port is this socket's alone, and with
633/// either option a second stream on the same host could bind it too and take
634/// a share of the camera's datagrams (SR-03).
635pub async fn bind_udp(
636    bind: IpAddr,
637    port: u16,
638    iface: Option<Iface>,
639    recv_buffer: Option<usize>,
640) -> io::Result<UdpSocket> {
641    let recv_buffer = recv_buffer.unwrap_or(DEFAULT_RCVBUF_BYTES);
642    if let Some(ipv4) = iface.as_ref().and_then(|iface| iface.ipv4()) {
643        info!(name = iface.as_ref().map(Iface::name), %ipv4, port, "binding GVSP socket");
644    } else {
645        info!(%bind, port, "binding GVSP socket");
646    }
647
648    let domain = match bind {
649        IpAddr::V4(_) => Domain::IPV4,
650        IpAddr::V6(_) => Domain::IPV6,
651    };
652    let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
653
654    let granted = request_recv_buffer(SockRef::from(&socket), recv_buffer)?;
655    debug!(
656        requested_recv_buffer = granted.requested,
657        granted_recv_buffer = granted.granted,
658        "configured GVSP receive buffer"
659    );
660
661    #[cfg(any(target_os = "linux", target_os = "android"))]
662    if let Some(iface) = iface.as_ref()
663        && let Err(err) = socket.bind_device(Some(iface.name().as_bytes()))
664    {
665        warn!(name = iface.name(), error = %err, "SO_BINDTODEVICE failed");
666    }
667
668    let addr = SocketAddr::new(bind, port);
669    socket.bind(&addr.into())?;
670
671    let std_socket: std::net::UdpSocket = socket.into();
672    std_socket.set_nonblocking(true)?;
673    UdpSocket::from_std(std_socket)
674}
675
676fn validate_multicast_inputs(group: Ipv4Addr, ttl: u32) -> io::Result<()> {
677    if ttl > 255 {
678        return Err(io::Error::new(
679            io::ErrorKind::InvalidInput,
680            "multicast TTL must be <= 255",
681        ));
682    }
683    if (group.octets()[0] & 0xF0) != 0xE0 {
684        return Err(io::Error::new(
685            io::ErrorKind::InvalidInput,
686            "multicast group must be within 224.0.0.0/4",
687        ));
688    }
689    Ok(())
690}
691
692/// Bind a UDP socket subscribed to the provided multicast group on the interface.
693pub async fn bind_multicast(
694    iface: &Iface,
695    group: Ipv4Addr,
696    port: u16,
697    opts: &McOptions,
698) -> io::Result<UdpSocket> {
699    validate_multicast_inputs(group, opts.ttl)?;
700    let iface_addr = iface
701        .ipv4()
702        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "interface lacks IPv4"))?;
703
704    info!(name = iface.name(), %group, port, "binding multicast GVSP socket");
705
706    let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
707
708    // Several receivers on one host may watch the same group and port — a
709    // controller and a monitor, say — and each needs its own socket bound to
710    // it. Every one of them gets each datagram sent to the group, so sharing
711    // the port here splits nothing, unlike a unicast port (`bind_udp`).
712    if opts.reuse_addr {
713        socket.set_reuse_address(true)?;
714        #[cfg(all(unix, not(target_os = "solaris")))]
715        socket.set_reuse_port(true)?;
716    }
717
718    let granted = request_recv_buffer(SockRef::from(&socket), opts.rcvbuf_bytes)?;
719    debug!(
720        requested_recv_buffer = granted.requested,
721        granted_recv_buffer = granted.granted,
722        "configured multicast GVSP receive buffer"
723    );
724    // IP_MULTICAST_LOOP governs this socket's sends on Unix but its
725    // *receives* on Windows, where `false` drops every datagram another
726    // socket on this host sends to the group — a camera simulator on the same
727    // machine, or the fake camera in the tests. This socket only receives
728    // multicast, so Windows keeps its default (on).
729    #[cfg(not(windows))]
730    socket.set_multicast_loop_v4(opts.loopback)?;
731    socket.set_multicast_ttl_v4(opts.ttl)?;
732    socket.set_multicast_if_v4(&iface_addr)?;
733
734    #[cfg(any(target_os = "linux", target_os = "android"))]
735    if let Err(err) = socket.bind_device(Some(iface.name().as_bytes())) {
736        warn!(name = iface.name(), error = %err, "SO_BINDTODEVICE failed");
737    }
738
739    let bind_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port);
740    socket.bind(&bind_addr.into())?;
741    socket.join_multicast_v4(&group, &iface_addr)?;
742
743    let std_socket: std::net::UdpSocket = socket.into();
744    std_socket.set_nonblocking(true)?;
745    UdpSocket::from_std(std_socket)
746}
747
748/// Wait up to `timeout` for `socket` to have a datagram — or a pending error
749/// — to read. `Ok(false)` when the time ran out.
750///
751/// For a receive loop that must also wake on a timer: wait here, then read
752/// the socket non-blocking. A receive timeout (`SO_RCVTIMEO`) does the same
753/// in one call, but Windows documents the socket's state as indeterminate
754/// once a receive has timed out, and a datagram arriving as the timeout
755/// fires can be lost — which a stream that times out every 5 ms meets often
756/// enough to drop a frame now and then.
757pub fn wait_readable(socket: &StdUdpSocket, timeout: Duration) -> io::Result<bool> {
758    let millis = timeout.as_millis().clamp(0, i32::MAX as u128) as i32;
759    #[cfg(unix)]
760    {
761        use std::os::fd::AsRawFd;
762        let mut fd = libc::pollfd {
763            fd: socket.as_raw_fd(),
764            events: libc::POLLIN,
765            revents: 0,
766        };
767        // SAFETY: one valid `pollfd` for a descriptor `socket` keeps open
768        // for the duration of the call.
769        let ready = unsafe { libc::poll(&mut fd, 1, millis) };
770        match ready {
771            -1 => {
772                let err = io::Error::last_os_error();
773                if err.kind() == io::ErrorKind::Interrupted {
774                    Ok(false)
775                } else {
776                    Err(err)
777                }
778            }
779            0 => Ok(false),
780            _ => Ok(true),
781        }
782    }
783    #[cfg(windows)]
784    {
785        use std::os::windows::io::AsRawSocket;
786        use windows_sys::Win32::Networking::WinSock::{POLLRDNORM, WSAPOLLFD, WSAPoll};
787        let mut fd = WSAPOLLFD {
788            fd: socket.as_raw_socket() as _,
789            events: POLLRDNORM,
790            revents: 0,
791        };
792        // SAFETY: one valid `WSAPOLLFD` for a socket `socket` keeps open for
793        // the duration of the call.
794        let ready = unsafe { WSAPoll(&mut fd, 1, millis) };
795        match ready {
796            -1 => Err(io::Error::last_os_error()),
797            0 => Ok(false),
798            _ => Ok(true),
799        }
800    }
801}
802
803#[cfg(test)]
804mod tests {
805    use super::*;
806
807    #[test]
808    fn reject_invalid_ttl() {
809        let err = validate_multicast_inputs(Ipv4Addr::new(239, 0, 0, 1), 512).unwrap_err();
810        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
811    }
812
813    #[test]
814    fn reject_non_multicast_group() {
815        let err = validate_multicast_inputs(Ipv4Addr::new(192, 168, 1, 1), 1).unwrap_err();
816        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
817    }
818
819    #[test]
820    fn accept_valid_group() {
821        assert!(validate_multicast_inputs(Ipv4Addr::new(239, 192, 1, 10), 1).is_ok());
822    }
823
824    #[test]
825    #[cfg(not(target_os = "windows"))]
826    fn from_system_loopback() {
827        let lo_name = if cfg!(target_os = "macos") {
828            "lo0"
829        } else {
830            "lo"
831        };
832        let iface = Iface::from_system(lo_name).expect("loopback interface should exist");
833        assert!(iface.ipv4().unwrap().is_loopback());
834    }
835
836    #[test]
837    fn from_remote_ipv4_uses_route_selected_local_address() {
838        let remote = Ipv4Addr::new(127, 0, 0, 2);
839        let iface =
840            Iface::from_remote_ipv4(remote).expect("loopback route should select an interface");
841
842        assert_eq!(iface.ipv4(), Some(Ipv4Addr::LOCALHOST));
843        assert_ne!(iface.ipv4(), Some(remote));
844    }
845
846    /// TC-11: macOS reads the interface's MTU instead of assuming Ethernet's;
847    /// `lo0` is 16384 by default.
848    #[test]
849    #[cfg(target_os = "macos")]
850    fn loopback_mtu_is_read_on_macos() {
851        let lo0 = Iface::from_system("lo0").expect("lo0");
852        let mtu = mtu(&lo0);
853        assert!(mtu.is_measured(), "{mtu:?}");
854        assert!(mtu.bytes() > 1500, "{mtu}");
855    }
856
857    /// A wait with nothing to read times out; a datagram makes the socket
858    /// readable at once.
859    #[test]
860    fn wait_readable_reports_a_datagram_and_times_out_without_one() {
861        let rx = StdUdpSocket::bind("127.0.0.1:0").expect("bind");
862        let started = std::time::Instant::now();
863        assert!(!wait_readable(&rx, Duration::from_millis(20)).expect("wait"));
864        assert!(started.elapsed() >= Duration::from_millis(15));
865        let tx = StdUdpSocket::bind("127.0.0.1:0").expect("bind");
866        tx.send_to(b"x", rx.local_addr().unwrap()).expect("send");
867        assert!(wait_readable(&rx, Duration::from_secs(2)).expect("wait"));
868    }
869
870    /// An MTU the operating system did not report says so, rather than
871    /// passing Ethernet's 1500 off as measured (Codex review of #195).
872    #[test]
873    fn an_mtu_the_os_does_not_report_is_assumed() {
874        let unknown = Iface {
875            name: "viva-no-such-if0".to_string(),
876            index: 0,
877            ipv4: None,
878            ipv6: None,
879        };
880        assert_eq!(mtu(&unknown), Mtu::Assumed(ASSUMED_MTU));
881        assert_eq!(Mtu::Assumed(1500).to_string(), "1500 (assumed)");
882        assert_eq!(Mtu::Measured(9000).to_string(), "9000");
883    }
884
885    #[test]
886    fn packet_size_matches_link_mtu() {
887        let mtu = 1500;
888        let size = best_packet_size(mtu);
889        assert_eq!(size, mtu);
890    }
891
892    #[test]
893    fn packet_size_is_clamped_to_the_ipv4_maximum() {
894        // Linux loopback reports MTU 65536. Left unclamped the sender emits a
895        // 65508-byte UDP datagram — one past the 65507-byte maximum — and every
896        // `send_to` fails, so the stream delivers no frames at all.
897        assert_eq!(best_packet_size(65536), MAX_IPV4_PACKET_SIZE);
898        assert_eq!(best_packet_size(u32::MAX), MAX_IPV4_PACKET_SIZE);
899
900        // The clamped value must still leave the datagram inside the UDP limit.
901        const UDP_MAX_PAYLOAD: u32 = 65535 - 20 - 8;
902        let gvsp_payload = best_packet_size(65536) - 20 - 8 - 8;
903        assert!(gvsp_payload + 8 <= UDP_MAX_PAYLOAD);
904    }
905
906    #[test]
907    fn selector_parses_an_ipv4_literal_as_an_address_and_anything_else_as_a_name() {
908        use std::str::FromStr;
909
910        assert_eq!(
911            IfaceSelector::from_str("169.254.105.106").unwrap(),
912            IfaceSelector::Ipv4(Ipv4Addr::new(169, 254, 105, 106))
913        );
914        assert_eq!(
915            IfaceSelector::from_str("en0").unwrap(),
916            IfaceSelector::Name("en0".into())
917        );
918        // The spelling #109's reporter had to use on Windows.
919        let guid = "{6394C55F-F630-4BC7-92D2-7AC320C73D1C}";
920        assert_eq!(
921            IfaceSelector::from_str(guid).unwrap(),
922            IfaceSelector::Name(guid.into())
923        );
924        // Not an address, so a name — and rejected by `Iface::resolve`, which
925        // is where the length check lives.
926        assert_eq!(
927            IfaceSelector::from_str("").unwrap(),
928            IfaceSelector::Name(String::new())
929        );
930        // A partial address is a name, not a parse error: `from_str` cannot
931        // fail, so the diagnosis is deferred to `resolve`.
932        assert_eq!(
933            IfaceSelector::from_str("169.254").unwrap(),
934            IfaceSelector::Name("169.254".into())
935        );
936    }
937
938    #[test]
939    #[cfg(not(target_os = "windows"))]
940    fn both_spellings_of_loopback_resolve_to_the_same_interface() {
941        use std::str::FromStr;
942
943        let lo_name = if cfg!(target_os = "macos") {
944            "lo0"
945        } else {
946            "lo"
947        };
948        let by_name = IfaceSelector::from_str(lo_name).unwrap().resolve().unwrap();
949        let by_addr = IfaceSelector::from_str("127.0.0.1")
950            .unwrap()
951            .resolve()
952            .unwrap();
953
954        assert_eq!(by_name.name(), by_addr.name());
955        assert_eq!(by_addr.ipv4(), Some(Ipv4Addr::LOCALHOST));
956    }
957
958    #[test]
959    fn an_unresolvable_selector_names_the_interfaces_we_can_see() {
960        use std::str::FromStr;
961
962        // The whole reason the selector owns the error: #109's reporter could
963        // not have guessed their adapter's GUID from `no interface with IPv4
964        // 169.254.105.106`.
965        let err = IfaceSelector::from_str("no-such-iface")
966            .unwrap()
967            .resolve()
968            .expect_err("a name no host has must not resolve");
969        let msg = err.to_string();
970        assert!(
971            msg.contains("interfaces this host reports:"),
972            "expected the interface listing, got: {msg}"
973        );
974        assert!(
975            Iface::list()
976                .unwrap()
977                .iter()
978                .any(|iface| msg.contains(iface.name())),
979            "expected a real interface name in: {msg}"
980        );
981    }
982
983    #[test]
984    fn the_granted_receive_buffer_is_read_back() {
985        let socket = StdUdpSocket::bind("127.0.0.1:0").expect("bind");
986        let small = set_recv_buffer(&socket, 64 * 1024).expect("set");
987        assert_eq!(small.requested, 64 * 1024);
988        assert!(small.granted > 0);
989        // An absurd request is capped (or, refused, retried smaller); either way it
990        // must come back reported as short rather than silently believed.
991        // (Windows treats the value as a hint and reports it back as set.)
992        #[cfg(unix)]
993        {
994            let huge = set_recv_buffer(&socket, 1 << 30).expect("falls back, not fails");
995            assert!(huge.is_short(), "{huge:?}");
996        }
997    }
998}