second-brain-sync 0.13.0

Bidirectional sync for second-brain: SSH transport, JSONL change log, conflict resolution
Documentation
use std::net::{Ipv4Addr, SocketAddr, UdpSocket};
use std::time::Duration;

use anyhow::{Context, Result};
use socket2::{Domain, Protocol, Socket, Type};

use super::{Adverts, Found, GROUP, MDNS_PORT, Responder};

/// Linux delivers to a socket bound to the group only datagrams sent to the
/// group, so unicast replies to 5353 still reach avahi, and a send from it
/// takes its source address from the route.
#[cfg(target_os = "linux")]
const LAN_BIND: Ipv4Addr = GROUP;
#[cfg(not(target_os = "linux"))]
const LAN_BIND: Ipv4Addr = Ipv4Addr::UNSPECIFIED;

pub(super) fn responder(adverts: Adverts) -> Result<Responder> {
    Responder::answering(
        responder_socket()?,
        Some(SocketAddr::from((GROUP, MDNS_PORT))),
        adverts,
    )
}

pub(super) fn browse(service: &str, window: Duration) -> Result<Vec<Found>> {
    let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).context("opening an mDNS socket")?;
    socket.set_multicast_ttl_v4(255)?;
    super::ask(
        &socket,
        SocketAddr::from((GROUP, MDNS_PORT)),
        service,
        window,
    )
}

/// Shares port 5353 with any other responder on the host (avahi), which
/// binds it with address and port reuse.
fn responder_socket() -> Result<UdpSocket> {
    let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
    socket.set_reuse_address(true)?;
    #[cfg(target_os = "linux")]
    socket.set_reuse_port(true)?;
    socket
        .bind(&SocketAddr::from((LAN_BIND, MDNS_PORT)).into())
        .context("binding the mDNS port 5353")?;
    socket
        .join_multicast_v4(&GROUP, &Ipv4Addr::UNSPECIFIED)
        .context("joining the mDNS group")?;
    socket.set_multicast_ttl_v4(255)?;
    Ok(socket.into())
}

#[cfg(test)]
mod tests {
    fn section_of<'a>(manifest: &'a str, line_start: &str) -> Option<&'a str> {
        let mut section = None;
        for line in manifest.lines() {
            if line.starts_with('[') {
                section = Some(line.trim());
            } else if line.starts_with(line_start) {
                return section;
            }
        }
        None
    }

    /// std has no way to set SO_REUSEPORT, so without socket2 no socket can
    /// share 5353 with mDNSResponder; this module, the only code that binds
    /// 5353, is not compiled for macOS either.
    #[test]
    fn macos_builds_neither_the_5353_socket_nor_its_socket_crate() {
        let manifest = include_str!("../../Cargo.toml").replace("\r\n", "\n");
        assert_eq!(
            section_of(&manifest, "socket2 "),
            Some(r#"[target.'cfg(not(target_os = "macos"))'.dependencies]"#)
        );
        let root = include_str!("../mdns.rs").replace("\r\n", "\n");
        assert!(root.contains("#[cfg(not(target_os = \"macos\"))]\nmod lan;"));
        assert!(root.contains("#[cfg(target_os = \"macos\")]\nuse dnssd as lan;"));
        for (file, source) in [
            ("mdns.rs", root.as_str()),
            ("mdns/dnssd.rs", include_str!("dnssd.rs")),
            ("mdns/system.rs", include_str!("system.rs")),
        ] {
            for needle in ["socket2", "set_reuse_port", "responder_socket"] {
                assert!(!source.contains(needle), "{file} names {needle}");
            }
        }
    }
}