use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use anyhow::{Context, Result};
use pnet::datalink::{Channel, DataLinkSender, NetworkInterface};
use pnet::packet::arp::{ArpHardwareTypes, ArpOperations, ArpPacket, MutableArpPacket};
use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::packet::icmpv6;
use pnet::packet::icmpv6::ndp::{
MutableNdpOptionPacket, MutableNeighborAdvertPacket, NdpOptionPacket, NdpOptionTypes, NeighborAdvertFlags,
NeighborAdvertPacket,
};
use pnet::packet::icmpv6::{Icmpv6Types, MutableIcmpv6Packet};
use pnet::packet::ip::IpNextHeaderProtocols;
use pnet::packet::ipv6::{Ipv6Packet, MutableIpv6Packet};
use pnet::util::MacAddr;
const ETHERNET_PACKET_SIZE: usize = EthernetPacket::minimum_packet_size();
const ARP_PACKET_SIZE: usize = ArpPacket::minimum_packet_size();
const IPV6_PACKET_SIZE: usize = Ipv6Packet::minimum_packet_size();
const NDP_ADV_PACKET_SIZE: usize = NeighborAdvertPacket::minimum_packet_size();
const NDP_OPT_PACKET_SIZE: usize = NdpOptionPacket::minimum_packet_size();
const MAC_PACKET_SIZE: usize = 6;
const ARP_PACKET_OFFSET: usize = ETHERNET_PACKET_SIZE;
const IPV6_PACKET_OFFSET: usize = ETHERNET_PACKET_SIZE;
const NDP_ADV_PACKET_OFFSET: usize = IPV6_PACKET_OFFSET + IPV6_PACKET_SIZE;
const NDP_OPT_PACKET_OFFSET: usize = NDP_ADV_PACKET_OFFSET + NDP_ADV_PACKET_SIZE;
pub struct AddressBroadcaster {
sender: Box<dyn DataLinkSender>,
packet: Vec<u8>,
}
impl AddressBroadcaster {
pub fn new(link_name: &str, address: IpAddr) -> Result<AddressBroadcaster> {
let interface = get_interface(link_name)?;
let interface_mac = interface
.mac
.with_context(|| format!("Could not find MAC of link {interface}"))?;
let packet = match address {
IpAddr::V4(v4) => get_arp_announcement(interface_mac, v4),
IpAddr::V6(v6) => get_ndp_advertisement(interface_mac, v6),
};
let config = pnet::datalink::Config::default();
let sender = match pnet::datalink::channel(&interface, config).with_context(|| {
format!("Failed to construct channel for {link_name}. Are you running with CAP_NET_RAW?")
})? {
Channel::Ethernet(sender, _) => sender,
_ => anyhow::bail!("Unknown channel type"),
};
Ok(AddressBroadcaster { sender, packet })
}
pub fn broadcast(&mut self) -> Result<()> {
self.sender
.send_to(&self.packet, None)
.context("No result sending broadcast packet")?
.context("Failed to send broadcast packet")
}
}
fn get_interface(link_name: &str) -> Result<NetworkInterface> {
let interfaces = pnet::datalink::interfaces();
let interface = interfaces
.into_iter()
.find(|iface| iface.name == link_name)
.with_context(|| format!("Failed to find link {link_name}"))?;
Ok(interface)
}
fn get_arp_announcement(source_mac: MacAddr, source_ip: Ipv4Addr) -> Vec<u8> {
let mut packet_buffer = [0u8; ETHERNET_PACKET_SIZE + ARP_PACKET_SIZE];
let mut ethernet_packet = MutableEthernetPacket::new(&mut packet_buffer).unwrap();
ethernet_packet.set_destination(MacAddr::broadcast());
ethernet_packet.set_source(source_mac);
ethernet_packet.set_ethertype(EtherTypes::Arp);
let mut arp_packet = MutableArpPacket::new(&mut packet_buffer[ARP_PACKET_OFFSET..]).unwrap();
arp_packet.set_hardware_type(ArpHardwareTypes::Ethernet);
arp_packet.set_protocol_type(EtherTypes::Ipv4);
arp_packet.set_hw_addr_len(6);
arp_packet.set_proto_addr_len(4);
arp_packet.set_operation(ArpOperations::Request);
arp_packet.set_sender_hw_addr(source_mac);
arp_packet.set_sender_proto_addr(source_ip);
arp_packet.set_target_hw_addr(MacAddr::zero());
arp_packet.set_target_proto_addr(source_ip);
packet_buffer.to_vec()
}
fn get_ndp_advertisement(source_mac: MacAddr, source_ip: Ipv6Addr) -> Vec<u8> {
let mut packet_buffer =
[0u8; ETHERNET_PACKET_SIZE + IPV6_PACKET_SIZE + NDP_ADV_PACKET_SIZE + NDP_OPT_PACKET_SIZE + MAC_PACKET_SIZE];
let all_nodes_multicast = Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1);
let mut ethernet_packet = MutableEthernetPacket::new(&mut packet_buffer).unwrap();
ethernet_packet.set_destination(MacAddr::broadcast());
ethernet_packet.set_source(source_mac);
ethernet_packet.set_ethertype(EtherTypes::Ipv6);
let mut ipv6_packet = MutableIpv6Packet::new(&mut packet_buffer[IPV6_PACKET_OFFSET..]).unwrap();
let payload_length = NDP_ADV_PACKET_SIZE + NDP_OPT_PACKET_SIZE + MAC_PACKET_SIZE;
ipv6_packet.set_version(0x06);
ipv6_packet.set_payload_length(payload_length.try_into().unwrap());
ipv6_packet.set_next_header(IpNextHeaderProtocols::Icmpv6);
ipv6_packet.set_hop_limit(u8::MAX);
ipv6_packet.set_source(source_ip);
ipv6_packet.set_destination(all_nodes_multicast);
let mut ndp_packet = MutableNeighborAdvertPacket::new(&mut packet_buffer[NDP_ADV_PACKET_OFFSET..]).unwrap();
ndp_packet.set_icmpv6_type(Icmpv6Types::NeighborAdvert);
ndp_packet.set_flags(NeighborAdvertFlags::Override);
ndp_packet.set_target_addr(source_ip);
let mut options_packet = MutableNdpOptionPacket::new(&mut packet_buffer[NDP_OPT_PACKET_OFFSET..]).unwrap();
options_packet.set_option_type(NdpOptionTypes::TargetLLAddr);
options_packet.set_length(1);
options_packet.set_data(&source_mac.octets());
let mut icmpv6_packet = MutableIcmpv6Packet::new(&mut packet_buffer[NDP_ADV_PACKET_OFFSET..]).unwrap();
let checksum = icmpv6::checksum(&icmpv6_packet.to_immutable(), &source_ip, &all_nodes_multicast);
icmpv6_packet.set_checksum(checksum);
packet_buffer.to_vec()
}