use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use socket2::{Domain, Protocol, Socket, Type};
use tokio::net::UdpSocket;
use crate::interface::Interface;
use crate::{Error, Result};
pub(crate) const MAX_DATAGRAM: usize = 65535;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Sharing {
Shared,
Exclusive,
}
pub(crate) fn bind(port: u16, interface: Option<&Interface>) -> Result<UdpSocket> {
bind_at(Ipv4Addr::UNSPECIFIED, port, interface)
}
pub(crate) fn send_once(interface: &Interface, to: SocketAddr, datagram: &[u8]) -> Result<()> {
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
.map_err(Error::io("creating a UDP socket"))?;
socket
.set_broadcast(true)
.map_err(Error::io("SO_BROADCAST"))?;
socket
.bind(&SocketAddr::V4(SocketAddrV4::new(interface.ip, 0)).into())
.map_err(Error::io("binding a UDP socket"))?;
pin_to_interface(&socket, interface)?;
socket
.send_to(datagram, &to.into())
.map_err(Error::io("sending a datagram"))?;
Ok(())
}
pub(crate) fn bind_at(
address: Ipv4Addr,
port: u16,
interface: Option<&Interface>,
) -> Result<UdpSocket> {
bind_sharing(address, port, interface, Sharing::Shared)
}
pub(crate) fn bind_exclusive(
address: Ipv4Addr,
port: u16,
interface: Option<&Interface>,
) -> Result<UdpSocket> {
bind_sharing(address, port, interface, Sharing::Exclusive)
}
fn bind_sharing(
address: Ipv4Addr,
port: u16,
interface: Option<&Interface>,
sharing: Sharing,
) -> Result<UdpSocket> {
let socket = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))
.map_err(Error::io("creating a UDP socket"))?;
if sharing == Sharing::Shared {
socket
.set_reuse_address(true)
.map_err(Error::io("SO_REUSEADDR"))?;
#[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
socket
.set_reuse_port(true)
.map_err(Error::io("SO_REUSEPORT"))?;
}
socket
.set_broadcast(true)
.map_err(Error::io("SO_BROADCAST"))?;
socket
.set_nonblocking(true)
.map_err(Error::io("O_NONBLOCK"))?;
socket
.bind(&SocketAddr::V4(SocketAddrV4::new(address, port)).into())
.map_err(Error::io("binding a UDP socket"))?;
if let Some(interface) = interface {
pin_to_interface(&socket, interface)?;
}
UdpSocket::from_std(socket.into()).map_err(Error::io("registering a UDP socket with tokio"))
}
fn pin_to_interface(socket: &Socket, interface: &Interface) -> Result<()> {
#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))]
{
socket
.bind_device(Some(interface.name.as_bytes()))
.map_err(Error::io("SO_BINDTODEVICE"))?;
}
#[cfg(any(
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
))]
{
socket
.bind_device_by_index_v4(std::num::NonZeroU32::new(interface.index))
.map_err(Error::io("IP_BOUND_IF"))?;
}
#[cfg(not(any(
target_os = "android",
target_os = "fuchsia",
target_os = "linux",
target_os = "ios",
target_os = "macos",
target_os = "tvos",
target_os = "watchos",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
)))]
{
let _ = interface;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn two_sockets_can_hold_the_same_port() {
let first = bind(0, None).expect("first bind");
let port = match first.local_addr().expect("local address") {
SocketAddr::V4(address) => address.port(),
SocketAddr::V6(_) => unreachable!("bound as IPv4"),
};
let second = bind(port, None);
assert!(
second.is_ok(),
"address reuse must be enabled: {:?}",
second.err()
);
}
#[tokio::test]
async fn an_rpc_port_is_not_shared() {
let first = bind_exclusive(Ipv4Addr::LOCALHOST, 0, None).expect("first bind");
let port = match first.local_addr().expect("local address") {
SocketAddr::V4(address) => address.port(),
SocketAddr::V6(_) => unreachable!("bound as IPv4"),
};
assert!(
bind_exclusive(Ipv4Addr::LOCALHOST, port, None).is_err(),
"a second exclusive bind must fail so the caller can say whose port it is",
);
}
#[tokio::test]
async fn a_bound_socket_can_broadcast() {
let socket = bind(0, None).expect("bind");
assert!(socket.broadcast().expect("SO_BROADCAST readable"));
}
}