use super::NdpPacket;
use crate::packets::icmp::v6::{Icmpv6, Icmpv6Message, Icmpv6Packet, Icmpv6Type, Icmpv6Types};
use crate::packets::ip::v6::Ipv6Packet;
use crate::packets::types::u32be;
use crate::packets::{Internal, Packet};
use crate::SizeOf;
use anyhow::Result;
use std::fmt;
use std::ptr::NonNull;
#[derive(Icmpv6Packet)]
pub struct RouterSolicitation<E: Ipv6Packet> {
icmp: Icmpv6<E>,
body: NonNull<RouterSolicitationBody>,
}
impl<E: Ipv6Packet> fmt::Debug for RouterSolicitation<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RouterSolicitation")
.field("type", &format!("{}", self.msg_type()))
.field("code", &self.code())
.field("checksum", &format!("0x{:04x}", self.checksum()))
.finish()
}
}
impl<E: Ipv6Packet> Icmpv6Message for RouterSolicitation<E> {
type Envelope = E;
#[inline]
fn msg_type() -> Icmpv6Type {
Icmpv6Types::RouterSolicitation
}
#[inline]
fn icmp(&self) -> &Icmpv6<Self::Envelope> {
&self.icmp
}
#[inline]
fn icmp_mut(&mut self) -> &mut Icmpv6<Self::Envelope> {
&mut self.icmp
}
#[inline]
fn into_icmp(self) -> Icmpv6<Self::Envelope> {
self.icmp
}
#[inline]
unsafe fn clone(&self, internal: Internal) -> Self {
RouterSolicitation {
icmp: self.icmp.clone(internal),
body: self.body,
}
}
#[inline]
fn try_parse(icmp: Icmpv6<Self::Envelope>, _internal: Internal) -> Result<Self> {
let mbuf = icmp.mbuf();
let offset = icmp.payload_offset();
let body = mbuf.read_data(offset)?;
Ok(RouterSolicitation { icmp, body })
}
#[inline]
fn try_push(mut icmp: Icmpv6<Self::Envelope>, _internal: Internal) -> Result<Self> {
let offset = icmp.payload_offset();
let mbuf = icmp.mbuf_mut();
mbuf.extend(offset, RouterSolicitationBody::size_of())?;
let body = mbuf.write_data(offset, &RouterSolicitationBody::default())?;
Ok(RouterSolicitation { icmp, body })
}
}
impl<E: Ipv6Packet> NdpPacket for RouterSolicitation<E> {
fn options_offset(&self) -> usize {
self.payload_offset() + RouterSolicitationBody::size_of()
}
}
#[derive(Clone, Copy, Debug, Default, SizeOf)]
#[repr(C, packed)]
struct RouterSolicitationBody {
_reserved: u32be,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::packets::ip::v6::Ipv6;
use crate::packets::Ethernet;
use crate::Mbuf;
#[test]
fn size_of_router_solicitation_body() {
assert_eq!(4, RouterSolicitationBody::size_of());
}
#[capsule::test]
fn push_and_set_router_solicitation() {
let packet = Mbuf::new().unwrap();
let ethernet = packet.push::<Ethernet>().unwrap();
let ipv6 = ethernet.push::<Ipv6>().unwrap();
let mut solicit = ipv6.push::<RouterSolicitation<Ipv6>>().unwrap();
assert_eq!(4, solicit.header_len());
assert_eq!(RouterSolicitationBody::size_of(), solicit.payload_len());
assert_eq!(Icmpv6Types::RouterSolicitation, solicit.msg_type());
assert_eq!(0, solicit.code());
solicit.reconcile_all();
assert!(solicit.checksum() != 0);
}
}