diff --git a/Cargo.toml b/Cargo.toml index 54eb6c3b4..dd5a1adac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,12 +35,16 @@ alloc = ["managed/alloc"] verbose = [] "medium-ethernet" = ["socket"] "medium-ip" = ["socket"] -"phy-raw_socket" = ["std", "libc", "medium-ethernet"] +"medium-sixlowpan" = ["socket", "sixlowpan", "proto-sixlowpan"] +"phy-raw_socket" = ["std", "libc"] "phy-tuntap_interface" = ["std", "libc", "medium-ethernet"] +"ieee802154" = [] +"sixlowpan" = ["ieee802154"] "proto-ipv4" = [] "proto-igmp" = ["proto-ipv4"] "proto-dhcpv4" = ["proto-ipv4"] "proto-ipv6" = [] +"proto-sixlowpan" = [] "socket" = [] "socket-raw" = ["socket"] "socket-udp" = ["socket"] @@ -108,5 +112,9 @@ required-features = ["std", "medium-ethernet", "medium-ip", "phy-tuntap_interfac name = "dhcp_client" required-features = ["std", "medium-ethernet", "medium-ip", "phy-tuntap_interface", "proto-ipv4", "proto-dhcpv4", "socket-raw"] +[[example]] +name = "sixlowpan" +required-features = ["std", "medium-sixlowpan", "phy-raw_socket", "proto-ipv6", "socket-udp"] + [profile.release] debug = 2 diff --git a/examples/sixlowpan.rs b/examples/sixlowpan.rs new file mode 100644 index 000000000..5f14b7154 --- /dev/null +++ b/examples/sixlowpan.rs @@ -0,0 +1,117 @@ +/* + +# Setup + + modprobe mac802154_hwsim + + ip link set wpan0 down + iwpan dev wpan0 set pan_id 0xbeef + ip link add link wpan0 name lowpan0 type lowpan + ip link set wpan0 up + ip link set lowpan0 up + + iwpan dev wpan1 del + iwpan phy phy1 interface add monitor%d type monitor + +# Running + + sudo ./target/debug/examples/sixlowpan + +# Teardown + + rmmod mac802154_hwsim + + */ + +mod utils; + +use log::debug; +use std::collections::BTreeMap; +use std::fmt::Write; +use std::os::unix::io::AsRawFd; +use std::str; + +use smoltcp::iface::{InterfaceBuilder, NeighborCache}; +use smoltcp::phy::{wait as phy_wait, Device, Medium, RawSocket}; +use smoltcp::socket::SocketSet; +use smoltcp::socket::{UdpPacketMetadata, UdpSocket, UdpSocketBuffer}; +use smoltcp::time::{Duration, Instant}; +use smoltcp::wire::{IpAddress, IpCidr}; + +fn main() { + utils::setup_logging(""); + + let (mut opts, mut free) = utils::create_options(); + utils::add_middleware_options(&mut opts, &mut free); + + let mut matches = utils::parse_options(&opts, free); + + let device = RawSocket::new("monitor0", Medium::Sixlowpan).unwrap(); + + let fd = device.as_raw_fd(); + let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false); + + let neighbor_cache = NeighborCache::new(BTreeMap::new()); + + let udp_rx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 64]); + let udp_tx_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY], vec![0; 128]); + let udp_socket = UdpSocket::new(udp_rx_buffer, udp_tx_buffer); + + let ethernet_addr = smoltcp::wire::Ieee802154Address::Extended([ + 0x1a, 0x0b, 0x42, 0x42, 0x42, 0x42, 0x42, 0x42, + ]); + let ip_addrs = [IpCidr::new( + IpAddress::v6(0xfe80, 0, 0, 0, 0x180b, 0x4242, 0x4242, 0x4242), + 64, + )]; + + let medium = device.capabilities().medium; + let mut builder = InterfaceBuilder::new(device).ip_addrs(ip_addrs); + builder = builder + .ieee802154_addr(ethernet_addr) + .neighbor_cache(neighbor_cache); + let mut iface = builder.finalize(); + + let mut sockets = SocketSet::new(vec![]); + let udp_handle = sockets.add(udp_socket); + + loop { + let timestamp = Instant::now(); + match iface.poll(&mut sockets, timestamp) { + Ok(_) => {} + Err(e) => { + debug!("poll error: {}", e); + } + } + + // udp:6969: respond "hello" + { + let mut socket = sockets.get::(udp_handle); + if !socket.is_open() { + socket.bind(6969).unwrap() + } + + let client = match socket.recv() { + Ok((data, endpoint)) => { + debug!( + "udp:6969 recv data: {:?} from {}", + str::from_utf8(data).unwrap(), + endpoint + ); + Some(endpoint) + } + Err(_) => None, + }; + if let Some(endpoint) = client { + let data = b"hello\n"; + debug!( + "udp:6969 send data: {:?}", + str::from_utf8(data.as_ref()).unwrap() + ); + socket.send_slice(data, endpoint).unwrap(); + } + } + + phy_wait(fd, iface.poll_delay(&sockets, timestamp)).expect("wait error"); + } +} diff --git a/examples/tcpdump.rs b/examples/tcpdump.rs index 6bd0e8a0e..6bdf35975 100644 --- a/examples/tcpdump.rs +++ b/examples/tcpdump.rs @@ -7,7 +7,7 @@ use std::os::unix::io::AsRawFd; fn main() { let ifname = env::args().nth(1).unwrap(); - let mut socket = RawSocket::new(ifname.as_ref()).unwrap(); + let mut socket = RawSocket::new(ifname.as_ref(), smoltcp::phy::Medium::Ethernet).unwrap(); loop { phy_wait(socket.as_raw_fd(), None).unwrap(); let (rx_token, _) = socket.receive().unwrap(); diff --git a/examples/utils.rs b/examples/utils.rs index 93dc259df..3edcb71e3 100644 --- a/examples/utils.rs +++ b/examples/utils.rs @@ -14,7 +14,6 @@ use std::rc::Rc; use std::str::{self, FromStr}; use std::time::{SystemTime, UNIX_EPOCH}; -use smoltcp::phy::RawSocket; #[cfg(feature = "phy-tuntap_interface")] use smoltcp::phy::TunTapInterface; use smoltcp::phy::{Device, FaultInjector, Medium, Tracer}; @@ -114,11 +113,6 @@ pub fn parse_tuntap_options(matches: &mut Matches) -> TunTapInterface { } } -pub fn parse_raw_socket_options(matches: &mut Matches) -> RawSocket { - let interface = matches.free.remove(0); - RawSocket::new(&interface).unwrap() -} - pub fn add_middleware_options(opts: &mut Options, _free: &mut Vec<&str>) { opts.optopt("", "pcap", "Write a packet capture file", "FILE"); opts.optopt( diff --git a/src/dhcp/clientv4.rs b/src/dhcp/clientv4.rs new file mode 100644 index 000000000..d94dbe07c --- /dev/null +++ b/src/dhcp/clientv4.rs @@ -0,0 +1,468 @@ +use super::{UDP_CLIENT_PORT, UDP_SERVER_PORT}; +use crate::iface::Interface; +use crate::phy::{ChecksumCapabilities, Device}; +use crate::socket::{RawSocket, RawSocketBuffer, SocketHandle, SocketSet}; +use crate::time::{Duration, Instant}; +use crate::wire::dhcpv4::field as dhcpv4_field; +use crate::wire::{ + DhcpMessageType, DhcpPacket, DhcpRepr, IpAddress, IpEndpoint, IpProtocol, IpVersion, + Ipv4Address, Ipv4Cidr, Ipv4Packet, Ipv4Repr, UdpPacket, UdpRepr, +}; +use crate::{Error, Result}; + +const DISCOVER_TIMEOUT: u64 = 10; +const REQUEST_TIMEOUT: u64 = 1; +const REQUEST_RETRIES: u16 = 15; +const DEFAULT_RENEW_INTERVAL: u32 = 60; +const PARAMETER_REQUEST_LIST: &[u8] = &[ + dhcpv4_field::OPT_SUBNET_MASK, + dhcpv4_field::OPT_ROUTER, + dhcpv4_field::OPT_DOMAIN_NAME_SERVER, +]; + +/// IPv4 configuration data returned by `client.poll()` +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Config { + pub address: Option, + pub router: Option, + pub dns_servers: [Option; 3], +} + +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct RequestState { + retry: u16, + endpoint_ip: Ipv4Address, + server_identifier: Ipv4Address, + requested_ip: Ipv4Address, +} + +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct RenewState { + endpoint_ip: Ipv4Address, + server_identifier: Ipv4Address, +} + +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +enum ClientState { + /// Discovering the DHCP server + Discovering, + /// Requesting an address + Requesting(RequestState), + /// Having an address, refresh it periodically + Renew(RenewState), +} + +pub struct Client { + state: ClientState, + raw_handle: SocketHandle, + /// When to send next request + next_egress: Instant, + /// When any existing DHCP address will expire. + lease_expiration: Option, + transaction_id: u32, +} + +/// DHCP client with a RawSocket. +/// +/// To provide memory for the dynamic IP address, configure your +/// `Interface` with one of `ip_addrs` and the `ipv4_gateway` being +/// `Ipv4Address::UNSPECIFIED`. You must also assign this `0.0.0.0/0` +/// while the client's state is `Discovering`. Hence, the `poll()` +/// method returns a corresponding `Config` struct in this case. +/// +/// You must call `dhcp_client.poll()` after `iface.poll()` to send +/// and receive DHCP packets. +impl Client { + /// # Usage + /// ```rust + /// use smoltcp::socket::{SocketSet, RawSocketBuffer, RawPacketMetadata}; + /// use smoltcp::dhcp::Dhcpv4Client; + /// use smoltcp::time::Instant; + /// + /// let mut sockets = SocketSet::new(vec![]); + /// let dhcp_rx_buffer = RawSocketBuffer::new( + /// [RawPacketMetadata::EMPTY; 1], + /// vec![0; 600] + /// ); + /// let dhcp_tx_buffer = RawSocketBuffer::new( + /// [RawPacketMetadata::EMPTY; 1], + /// vec![0; 600] + /// ); + /// let mut dhcp = Dhcpv4Client::new( + /// &mut sockets, + /// dhcp_rx_buffer, dhcp_tx_buffer, + /// Instant::now() + /// ); + /// ``` + pub fn new<'a>( + sockets: &mut SocketSet<'a>, + rx_buffer: RawSocketBuffer<'a>, + tx_buffer: RawSocketBuffer<'a>, + now: Instant, + ) -> Self { + let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Udp, rx_buffer, tx_buffer); + let raw_handle = sockets.add(raw_socket); + + Client { + state: ClientState::Discovering, + raw_handle, + next_egress: now, + transaction_id: 1, + lease_expiration: None, + } + } + + /// When to send next packet + /// + /// Useful for suspending execution after polling. + pub fn next_poll(&self, now: Instant) -> Duration { + self.next_egress - now + } + + /// Process incoming packets on the contained RawSocket, and send + /// DHCP requests when timeouts are ready. + /// + /// Applying the obtained network configuration is left to the + /// user. + /// + /// A Config can be returned from any valid DHCP reply. The client + /// performs no bookkeeping on configuration or their changes. + pub fn poll( + &mut self, + iface: &mut Interface, + sockets: &mut SocketSet, + now: Instant, + ) -> Result> + where + DeviceT: for<'d> Device<'d>, + { + let checksum_caps = iface.device().capabilities().checksum; + let mut raw_socket = sockets.get::(self.raw_handle); + + // Process incoming + let config = { + match raw_socket + .recv() + .and_then(|packet| parse_udp(packet, &checksum_caps)) + { + Ok(( + IpEndpoint { + addr: IpAddress::Ipv4(src_ip), + port: UDP_SERVER_PORT, + }, + IpEndpoint { + addr: _, + port: UDP_CLIENT_PORT, + }, + payload, + )) => self.ingress(iface, now, payload, &src_ip), + Ok(_) => return Err(Error::Unrecognized), + Err(Error::Exhausted) => None, + Err(e) => return Err(e), + } + }; + + if config.is_some() { + // Return a new config immediately so that addresses can + // be configured that are required by egress(). + Ok(config) + } else { + // Send requests + if raw_socket.can_send() && now >= self.next_egress { + self.egress(iface, &mut *raw_socket, &checksum_caps, now) + } else { + Ok(None) + } + } + } + + fn ingress( + &mut self, + iface: &mut Interface, + now: Instant, + data: &[u8], + src_ip: &Ipv4Address, + ) -> Option + where + DeviceT: for<'d> Device<'d>, + { + let dhcp_packet = match DhcpPacket::new_checked(data) { + Ok(dhcp_packet) => dhcp_packet, + Err(e) => { + net_debug!("DHCP invalid pkt from {}: {:?}", src_ip, e); + return None; + } + }; + let dhcp_repr = match DhcpRepr::parse(&dhcp_packet) { + Ok(dhcp_repr) => dhcp_repr, + Err(e) => { + net_debug!("DHCP error parsing pkt from {}: {:?}", src_ip, e); + return None; + } + }; + let mac = iface.ethernet_addr(); + if dhcp_repr.client_hardware_address != mac { + return None; + } + if dhcp_repr.transaction_id != self.transaction_id { + return None; + } + let server_identifier = match dhcp_repr.server_identifier { + Some(server_identifier) => server_identifier, + None => return None, + }; + net_debug!( + "DHCP recv {:?} from {} ({})", + dhcp_repr.message_type, + src_ip, + server_identifier + ); + + // once we receive the ack, we can pass the config to the user + let config = if dhcp_repr.message_type == DhcpMessageType::Ack { + let lease_duration = dhcp_repr + .lease_duration + .unwrap_or(DEFAULT_RENEW_INTERVAL * 2); + self.lease_expiration = Some(now + Duration::from_secs(lease_duration.into())); + + // RFC 2131 indicates clients should renew a lease halfway through its expiration. + self.next_egress = now + Duration::from_secs((lease_duration / 2).into()); + + let address = dhcp_repr + .subnet_mask + .and_then(|mask| IpAddress::Ipv4(mask).to_prefix_len()) + .map(|prefix_len| Ipv4Cidr::new(dhcp_repr.your_ip, prefix_len)); + let router = dhcp_repr.router; + let dns_servers = dhcp_repr.dns_servers.unwrap_or([None; 3]); + Some(Config { + address, + router, + dns_servers, + }) + } else { + None + }; + + match self.state { + ClientState::Discovering if dhcp_repr.message_type == DhcpMessageType::Offer => { + self.next_egress = now; + let r_state = RequestState { + retry: 0, + endpoint_ip: *src_ip, + server_identifier, + requested_ip: dhcp_repr.your_ip, // use the offered ip + }; + Some(ClientState::Requesting(r_state)) + } + ClientState::Requesting(ref r_state) + if dhcp_repr.message_type == DhcpMessageType::Ack + && server_identifier == r_state.server_identifier => + { + let p_state = RenewState { + endpoint_ip: *src_ip, + server_identifier, + }; + Some(ClientState::Renew(p_state)) + } + _ => None, + } + .map(|new_state| self.state = new_state); + + config + } + + fn egress Device<'d>>( + &mut self, + iface: &mut Interface, + raw_socket: &mut RawSocket, + checksum_caps: &ChecksumCapabilities, + now: Instant, + ) -> Result> { + // Reset after maximum amount of retries + let retries_exceeded = match self.state { + ClientState::Requesting(ref mut r_state) if r_state.retry >= REQUEST_RETRIES => { + net_debug!("DHCP request retries exceeded, restarting discovery"); + true + } + _ => false, + }; + + let lease_expired = self + .lease_expiration + .map_or(false, |expiration| now >= expiration); + + if lease_expired || retries_exceeded { + self.reset(now); + // Return a config now so that user code assigns the + // 0.0.0.0/0 address, which will be used sending a DHCP + // discovery packet in the next call to egress(). + return Ok(Some(Config { + address: Some(Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0)), + router: None, + dns_servers: [None; 3], + })); + } + + // Prepare sending next packet + self.transaction_id += 1; + let mac = iface.ethernet_addr(); + + let mut dhcp_repr = DhcpRepr { + message_type: DhcpMessageType::Discover, + transaction_id: self.transaction_id, + client_hardware_address: mac, + client_ip: Ipv4Address::UNSPECIFIED, + your_ip: Ipv4Address::UNSPECIFIED, + server_ip: Ipv4Address::UNSPECIFIED, + router: None, + subnet_mask: None, + relay_agent_ip: Ipv4Address::UNSPECIFIED, + broadcast: true, + requested_ip: None, + client_identifier: Some(mac), + server_identifier: None, + parameter_request_list: Some(PARAMETER_REQUEST_LIST), + max_size: Some(raw_socket.payload_recv_capacity() as u16), + lease_duration: None, + dns_servers: None, + }; + let mut send_packet = |iface, endpoint, dhcp_repr| { + send_packet(iface, raw_socket, &endpoint, &dhcp_repr, checksum_caps).map(|()| None) + }; + + match self.state { + ClientState::Discovering => { + self.next_egress = now + Duration::from_secs(DISCOVER_TIMEOUT); + let endpoint = IpEndpoint { + addr: Ipv4Address::BROADCAST.into(), + port: UDP_SERVER_PORT, + }; + net_trace!("DHCP send discover to {}: {:?}", endpoint, dhcp_repr); + send_packet(iface, endpoint, dhcp_repr) + } + ClientState::Requesting(ref mut r_state) => { + r_state.retry += 1; + self.next_egress = now + Duration::from_secs(REQUEST_TIMEOUT); + + let endpoint = IpEndpoint { + addr: Ipv4Address::BROADCAST.into(), + port: UDP_SERVER_PORT, + }; + dhcp_repr.message_type = DhcpMessageType::Request; + dhcp_repr.broadcast = false; + dhcp_repr.requested_ip = Some(r_state.requested_ip); + dhcp_repr.server_identifier = Some(r_state.server_identifier); + net_trace!("DHCP send request to {} = {:?}", endpoint, dhcp_repr); + send_packet(iface, endpoint, dhcp_repr) + } + ClientState::Renew(ref mut p_state) => { + self.next_egress = now + Duration::from_secs(DEFAULT_RENEW_INTERVAL.into()); + + let endpoint = IpEndpoint { + addr: p_state.endpoint_ip.into(), + port: UDP_SERVER_PORT, + }; + let client_ip = iface.ipv4_addr().unwrap_or(Ipv4Address::UNSPECIFIED); + dhcp_repr.message_type = DhcpMessageType::Request; + dhcp_repr.client_ip = client_ip; + dhcp_repr.broadcast = false; + net_trace!("DHCP send renew to {}: {:?}", endpoint, dhcp_repr); + send_packet(iface, endpoint, dhcp_repr) + } + } + } + + /// Reset state and restart discovery phase. + /// + /// Use this to speed up acquisition of an address in a new + /// network if a link was down and it is now back up. + /// + /// You *must* configure a `0.0.0.0` address on your interface + /// before the next call to `poll()`! + pub fn reset(&mut self, now: Instant) { + net_trace!("DHCP reset"); + self.state = ClientState::Discovering; + self.next_egress = now; + self.lease_expiration = None; + } +} + +fn send_packet Device<'d>>( + iface: &mut Interface, + raw_socket: &mut RawSocket, + endpoint: &IpEndpoint, + dhcp_repr: &DhcpRepr, + checksum_caps: &ChecksumCapabilities, +) -> Result<()> { + let mut dhcp_payload_buf = [0; 320]; + assert!(dhcp_repr.buffer_len() <= dhcp_payload_buf.len()); + let dhcp_payload = &mut dhcp_payload_buf[0..dhcp_repr.buffer_len()]; + { + let mut dhcp_packet = DhcpPacket::new_checked(&mut dhcp_payload[..])?; + dhcp_repr.emit(&mut dhcp_packet)?; + } + + let udp_repr = UdpRepr { + src_port: UDP_CLIENT_PORT, + dst_port: endpoint.port, + payload: dhcp_payload, + }; + + let src_addr = iface.ipv4_addr().unwrap(); + let dst_addr = match endpoint.addr { + IpAddress::Ipv4(addr) => addr, + _ => return Err(Error::Illegal), + }; + let ipv4_repr = Ipv4Repr { + src_addr, + dst_addr, + protocol: IpProtocol::Udp, + payload_len: udp_repr.buffer_len(), + hop_limit: 64, + }; + + let mut packet = raw_socket.send(ipv4_repr.buffer_len() + udp_repr.buffer_len())?; + { + let mut ipv4_packet = Ipv4Packet::new_unchecked(&mut packet); + ipv4_repr.emit(&mut ipv4_packet, &checksum_caps); + } + { + let mut udp_packet = UdpPacket::new_unchecked(&mut packet[ipv4_repr.buffer_len()..]); + udp_repr.emit( + &mut udp_packet, + &src_addr.into(), + &dst_addr.into(), + checksum_caps, + ); + } + Ok(()) +} + +fn parse_udp<'a>( + data: &'a [u8], + checksum_caps: &ChecksumCapabilities, +) -> Result<(IpEndpoint, IpEndpoint, &'a [u8])> { + let ipv4_packet = Ipv4Packet::new_checked(data)?; + let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &checksum_caps)?; + let udp_packet = UdpPacket::new_checked(ipv4_packet.payload())?; + let udp_repr = UdpRepr::parse( + &udp_packet, + &ipv4_repr.src_addr.into(), + &ipv4_repr.dst_addr.into(), + checksum_caps, + )?; + let src = IpEndpoint { + addr: ipv4_repr.src_addr.into(), + port: udp_repr.src_port, + }; + let dst = IpEndpoint { + addr: ipv4_repr.dst_addr.into(), + port: udp_repr.dst_port, + }; + let data = udp_repr.payload; + Ok((src, dst, data)) +} diff --git a/src/iface/interface.rs b/src/iface/interface.rs index 314192359..e57102d9b 100644 --- a/src/iface/interface.rs +++ b/src/iface/interface.rs @@ -6,7 +6,7 @@ use core::cmp; use managed::{ManagedMap, ManagedSlice}; use crate::iface::Routes; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] use crate::iface::{NeighborAnswer, NeighborCache}; use crate::phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken}; use crate::socket::*; @@ -14,6 +14,9 @@ use crate::time::{Duration, Instant}; use crate::wire::*; use crate::{Error, Result}; +#[cfg(feature = "medium-sixlowpan")] +use crate::iface::interface::ieee802154::Pan; + /// A network interface. /// /// The network interface logically owns a number of other data structures; to avoid @@ -32,10 +35,18 @@ pub struct Interface<'a, DeviceT: for<'d> Device<'d>> { /// methods on the `Interface` in this time (since its `device` field is borrowed /// exclusively). However, it is still possible to call methods on its `inner` field. struct InterfaceInner<'a> { - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] neighbor_cache: Option>, #[cfg(feature = "medium-ethernet")] ethernet_addr: Option, + #[cfg(feature = "medium-sixlowpan")] + ieee802154_addr: Option, + #[cfg(feature = "medium-sixlowpan")] + sequence_no: u8, + #[cfg(feature = "medium-sixlowpan")] + src_pan_id: Option, + #[cfg(feature = "medium-sixlowpan")] + dst_pan_id: Option, ip_addrs: ManagedSlice<'a, IpCidr>, #[cfg(feature = "proto-ipv4")] any_ip: bool, @@ -52,8 +63,16 @@ pub struct InterfaceBuilder<'a, DeviceT: for<'d> Device<'d>> { device: DeviceT, #[cfg(feature = "medium-ethernet")] ethernet_addr: Option, - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] neighbor_cache: Option>, + #[cfg(feature = "medium-sixlowpan")] + ieee802154_addr: Option, + #[cfg(feature = "medium-sixlowpan")] + sequence_no: u8, + #[cfg(feature = "medium-sixlowpan")] + src_pan_id: Option, + #[cfg(feature = "medium-sixlowpan")] + dst_pan_id: Option, ip_addrs: ManagedSlice<'a, IpCidr>, #[cfg(feature = "proto-ipv4")] any_ip: bool, @@ -101,8 +120,16 @@ let iface = InterfaceBuilder::new(device) device: device, #[cfg(feature = "medium-ethernet")] ethernet_addr: None, - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] neighbor_cache: None, + #[cfg(feature = "medium-sixlowpan")] + ieee802154_addr: None, + #[cfg(feature = "medium-sixlowpan")] + sequence_no: 1, + #[cfg(feature = "medium-sixlowpan")] + src_pan_id: None, + #[cfg(feature = "medium-sixlowpan")] + dst_pan_id: None, ip_addrs: ManagedSlice::Borrowed(&mut []), #[cfg(feature = "proto-ipv4")] any_ip: false, @@ -126,6 +153,27 @@ let iface = InterfaceBuilder::new(device) self } + /// Set the IEEE802.15.4 address the interface will use. + #[cfg(feature = "medium-sixlowpan")] + pub fn ieee802154_addr(mut self, addr: Ieee802154Address) -> Self { + self.ieee802154_addr = Some(addr); + self + } + + /// Set the IEEE802.15.4 source PAN ID the interface will use. + #[cfg(feature = "medium-sixlowpan")] + pub fn src_pan_id(mut self, pan_id: Pan) -> Self { + self.src_pan_id = Some(pan_id); + self + } + + /// Set the IEEE802.15.4 destination PAN ID the interface will use. + #[cfg(feature = "medium-sixlowpan")] + pub fn dst_pan_id(mut self, pan_id: Pan) -> Self { + self.dst_pan_id = Some(pan_id); + self + } + /// Set the IP addresses the interface will use. See also /// [ip_addrs]. /// @@ -194,7 +242,7 @@ let iface = InterfaceBuilder::new(device) } /// Set the Neighbor Cache the interface will use. - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'a>) -> Self { self.neighbor_cache = Some(neighbor_cache); self @@ -214,8 +262,8 @@ let iface = InterfaceBuilder::new(device) pub fn finalize(self) -> Interface<'a, DeviceT> { let device_capabilities = self.device.capabilities(); - #[cfg(feature = "medium-ethernet")] - let (ethernet_addr, neighbor_cache) = match device_capabilities.medium { + let (hardware_addr, neighbor_cache) = match device_capabilities.medium { + #[cfg(feature = "medium-ethernet")] Medium::Ethernet => ( Some( self.ethernet_addr @@ -238,18 +286,37 @@ let iface = InterfaceBuilder::new(device) ); (None, None) } + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => ( + Some( + self.ieee802154_addr + .expect("ieee802154_addr required option was not set"), + ), + Some( + self.neighbor_cache + .expect("neighbor_cache required option was not set"), + ), + ), }; Interface { device: self.device, inner: InterfaceInner { #[cfg(feature = "medium-ethernet")] - ethernet_addr, + ethernet_addr: hardware_addr, + #[cfg(feature = "medium-sixlowpan")] + ieee802154_addr: hardware_addr, + #[cfg(feature = "medium-sixlowpan")] + sequence_no: self.sequence_no, + #[cfg(feature = "medium-sixlowpan")] + src_pan_id: self.src_pan_id, + #[cfg(feature = "medium-sixlowpan")] + dst_pan_id: self.dst_pan_id, ip_addrs: self.ip_addrs, #[cfg(feature = "proto-ipv4")] any_ip: self.any_ip, routes: self.routes, - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] neighbor_cache, #[cfg(feature = "proto-igmp")] ipv4_multicast_groups: self.ipv4_multicast_groups, @@ -687,8 +754,26 @@ where } Err(err) => net_debug!("cannot process ingress packet: {}", err), }, + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => inner + .process_sixlowpan(sockets, timestamp, &frame) + .map_err(|err| { + net_debug!("cannot process ingress packet: {}", err); + err + }) + .and_then(|response| { + processed_any = true; + match response { + Some(packet) => inner + .dispatch_ip(tx_token, timestamp, packet) + .map_err(|err| { + net_debug!("cannot dispatch response packet: {}", err); + err + }), + None => Ok(()), + } + }), } - Ok(()) }) { net_debug!("Failed to consume RX token: {}", err); @@ -958,7 +1043,7 @@ impl<'a> InterfaceInner<'a> { if self.in_same_network(&ip_addr) { self.neighbor_cache.as_mut().unwrap().fill( ip_addr, - eth_frame.src_addr(), + eth_frame.src_addr().into(), cx.now, ); } @@ -983,7 +1068,7 @@ impl<'a> InterfaceInner<'a> { { self.neighbor_cache.as_mut().unwrap().fill( ip_addr, - eth_frame.src_addr(), + eth_frame.src_addr().into(), cx.now, ); } @@ -1020,6 +1105,100 @@ impl<'a> InterfaceInner<'a> { } } + #[cfg(feature = "medium-sixlowpan")] + fn process_sixlowpan<'frame, T: AsRef<[u8]> + ?Sized>( + &mut self, + sockets: &mut SocketSet, + timestamp: Instant, + sixlowpan_payload: &'frame T, + ) -> Result>> { + let ieee802154_frame = Ieee802154Frame::new_checked(sixlowpan_payload)?; + let ieee802154_repr = Ieee802154Repr::parse(&ieee802154_frame)?; + + match ieee802154_frame.payload() { + Some(payload) => { + // The first header needs to be an IPHC header. + let iphc_packet = SixlowpanIphcPacket::new_checked(payload)?; + let iphc_repr = SixlowpanIphcRepr::parse( + &iphc_packet, + ieee802154_repr.src_addr, + ieee802154_repr.dst_addr, + )?; + + //if !iphc_repr.src_addr.is_unicast() { + //// Discard packets with non-unicast source addresses. + //net_debug!("non-unicast source address"); + //return Err(Error::Malformed) + //} + + let payload = iphc_packet.payload(); + let ip_repr = IpRepr::Sixlowpan(iphc_repr); + + // Currently we assume the next header is a UDP, so we mark all the rest with todo. + match iphc_repr.next_header { + SixlowpanNextHeader::Compressed => { + match SixlowpanNhcPacket::dispatch(payload)? { + SixlowpanNhcPacket::ExtensionHeader(ext_header) => { + todo!("{:?}", ext_header) + } + SixlowpanNhcPacket::UdpHeader(udp_packet) => { + // Handle the UDP + let udp_repr = SixlowpanUdpRepr::parse( + &udp_packet, + &iphc_repr.src_addr, + &iphc_repr.dst_addr, + udp_packet.checksum(), + )?; + + // Look for UDP sockets that will accept the UDP packet. + // If it does not accept the packet, then send an ICMP message. + for mut udp_socket in + sockets.iter_mut().filter_map(UdpSocket::downcast) + { + if !udp_socket.accepts(&ip_repr, &udp_repr) { + continue; + } + + match udp_socket.process(&ip_repr, &udp_repr) { + Ok(()) => return Ok(None), + Err(e) => return Err(e), + } + } + + // The packet wasn't handled by a socket, send an ICMP port unreachable packet. + match ip_repr { + #[cfg(feature = "proto-ipv6")] + IpRepr::Ipv6(ipv6_repr) => { + let payload_len = icmp_reply_payload_len( + payload.len(), + IPV6_MIN_MTU, + ipv6_repr.buffer_len(), + ); + let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable { + reason: Icmpv6DstUnreachable::PortUnreachable, + header: ipv6_repr, + data: &payload[0..payload_len], + }; + Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr)) + } + IpRepr::Unspecified { .. } => Err(Error::Unaddressable), + _ => unreachable!(), + } + } + } + } + SixlowpanNextHeader::Uncompressed(nxt_hdr) => match nxt_hdr { + IpProtocol::Icmpv6 => { + self.process_icmpv6(sockets, timestamp, ip_repr, iphc_packet.payload()) + } + hdr => todo!("{:?}", hdr), + }, + } + } + None => Ok(None), + } + } + #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv4"))] fn process_arp<'frame, T: AsRef<[u8]>>( &mut self, @@ -1043,7 +1222,7 @@ impl<'a> InterfaceInner<'a> { if source_protocol_addr.is_unicast() && source_hardware_addr.is_unicast() { self.neighbor_cache.as_mut().unwrap().fill( source_protocol_addr.into(), - source_hardware_addr, + source_hardware_addr.into(), timestamp, ); } else { @@ -1421,6 +1600,24 @@ impl<'a> InterfaceInner<'a> { }; Ok(self.icmpv6_reply(ipv6_repr, icmp_reply_repr)) } + #[cfg(feature = "medium-sixlowpan")] + IpRepr::Sixlowpan(sixlowpan_repr) => { + let icmp_reply_repr = Icmpv6Repr::EchoReply { + ident, + seq_no, + data, + }; + Ok(self.icmpv6_reply( + Ipv6Repr { + src_addr: sixlowpan_repr.src_addr, + dst_addr: sixlowpan_repr.dst_addr, + next_header: IpProtocol::Unknown(0), + payload_len: data.len(), + hop_limit: 64, + }, + icmp_reply_repr, + )) + } _ => Err(Error::Unrecognized), }, @@ -1428,9 +1625,23 @@ impl<'a> InterfaceInner<'a> { Icmpv6Repr::EchoReply { .. } => Ok(None), // Forward any NDISC packets to the ndisc packet handler - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] Icmpv6Repr::Ndisc(repr) if ip_repr.hop_limit() == 0xff => match ip_repr { IpRepr::Ipv6(ipv6_repr) => self.process_ndisc(cx.now, ipv6_repr, repr), + #[cfg(feature = "medium-sixlowpan")] + IpRepr::Sixlowpan(sixlowpan_repr) => { + self.process_ndisc( + _timestamp, + Ipv6Repr { + src_addr: sixlowpan_repr.src_addr, + dst_addr: sixlowpan_repr.dst_addr, + next_header: IpProtocol::Unknown(0), + payload_len: 10, // 2 + 8 + hop_limit: sixlowpan_repr.hop_limit, + }, + repr, + ) + } _ => Ok(None), }, @@ -1444,7 +1655,10 @@ impl<'a> InterfaceInner<'a> { } } - #[cfg(all(feature = "medium-ethernet", feature = "proto-ipv6"))] + #[cfg(all( + any(feature = "medium-ethernet", feature = "medium-sixlowpan"), + feature = "proto-ipv6" + ))] fn process_ndisc<'frame>( &mut self, timestamp: Instant, @@ -1495,7 +1709,10 @@ impl<'a> InterfaceInner<'a> { let advert = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert { flags: NdiscNeighborFlags::SOLICITED, target_addr: target_addr, - lladdr: Some(self.ethernet_addr.unwrap()), + #[cfg(feature = "medium-ethernet")] + lladdr: Some(self.ethernet_addr.unwrap().into()), + #[cfg(feature = "medium-sixlowpan")] + lladdr: Some(self.ieee802154_addr.unwrap().into()), }); let ip_repr = Ipv6Repr { src_addr: target_addr, @@ -1733,6 +1950,28 @@ impl<'a> InterfaceInner<'a> { }; Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr)) } + #[cfg(feature = "sixlowpan")] + IpRepr::Sixlowpan(sixlowpan_repr) => { + let ipv6_repr = Ipv6Repr { + src_addr: sixlowpan_repr.src_addr, + dst_addr: sixlowpan_repr.dst_addr, + next_header: IpProtocol::Udp, // XXX + payload_len: ip_payload.len(), + hop_limit: sixlowpan_repr.hop_limit, + }; + + let payload_len = icmp_reply_payload_len( + ip_payload.len(), + IPV6_MIN_MTU, + sixlowpan_repr.buffer_len(), + ); + let icmpv6_reply_repr = Icmpv6Repr::DstUnreachable { + reason: Icmpv6DstUnreachable::PortUnreachable, + header: ipv6_repr, + data: &ip_payload[0..payload_len], + }; + Ok(self.icmpv6_reply(ipv6_repr, icmpv6_reply_repr)) + } IpRepr::Unspecified { .. } => Err(Error::Unaddressable), } } @@ -1852,6 +2091,13 @@ impl<'a> InterfaceInner<'a> { .unwrap() .lookup(&_routed_addr, cx.now) .found(), + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => self + .neighbor_cache + .as_ref() + .unwrap() + .lookup(&_routed_addr, cx.now) + .found(), #[cfg(feature = "medium-ip")] Medium::Ip => true, }, @@ -1901,9 +2147,11 @@ impl<'a> InterfaceInner<'a> { .unwrap() .lookup(&dst_addr, cx.now) { - NeighborAnswer::Found(hardware_addr) => return Ok((hardware_addr, tx_token)), + NeighborAnswer::Found(HardwareAddress::Ethernet(hardware_addr)) => { + return Ok((hardware_addr, tx_token)) + } NeighborAnswer::RateLimited => return Err(Error::Unaddressable), - NeighborAnswer::NotFound => (), + _ => (), // XXX } match (src_addr, dst_addr) { @@ -1939,7 +2187,7 @@ impl<'a> InterfaceInner<'a> { let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit { target_addr: dst_addr, - lladdr: Some(self.ethernet_addr.unwrap()), + lladdr: Some(self.ethernet_addr.unwrap().into()), }); let packet = IpPacket::Icmpv6(( @@ -2008,6 +2256,127 @@ impl<'a> InterfaceInner<'a> { let payload = &mut tx_buffer[ip_repr.buffer_len()..]; packet.emit_payload(ip_repr, payload, &cx.caps); + Ok(()) + }) + } + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => { + let ll_dst_addr = match self + .neighbor_cache + .as_mut() + .unwrap() + .lookup(&ip_repr.dst_addr(), timestamp) + { + NeighborAnswer::Found(HardwareAddress::Ieee802154(addr)) => addr, + r => return Err(Error::Unaddressable), + }; + + let ack_request = ll_dst_addr.is_unicast(); + + let mut tx_len = 0; + + let ieee_repr = Ieee802154Repr { + frame_type: Ieee802154FrameType::Data, + security_enabled: false, + frame_pending: false, + ack_request, + sequence_number: Some(self.sequence_no), + pan_id_compression: true, + frame_version: Ieee802154FrameVersion::Ieee802154_2006, + dst_pan_id: self.dst_pan_id, + dst_addr: Some(ll_dst_addr), + src_pan_id: self.src_pan_id, + src_addr: self.ieee802154_addr, + }; + + self.sequence_no = self.sequence_no.wrapping_add(1); + + let (src_addr, dst_addr) = match (ip_repr.src_addr(), ip_repr.dst_addr()) { + (IpAddress::Ipv6(src_addr), IpAddress::Ipv6(dst_addr)) => (src_addr, dst_addr), + _ => return Err(Error::Unaddressable), + }; + + let next_header = match &packet { + IpPacket::Udp(_) => SixlowpanNextHeader::Compressed, + IpPacket::Icmpv6(_) => SixlowpanNextHeader::Uncompressed(IpProtocol::Icmpv6), + _ => return Err(Error::Unrecognized), + }; + + let hop_limit = match packet { + IpPacket::Icmpv6((_, Icmpv6Repr::Ndisc(_))) => 255, + IpPacket::Icmpv6((_, Icmpv6Repr::EchoReply { .. })) => 64, + IpPacket::Udp(..) => 64, + _ => return Err(Error::Unrecognized), + }; + + let iphc_repr = SixlowpanIphcRepr { + src_addr, + ll_src_addr: self.ieee802154_addr, + dst_addr, + ll_dst_addr: Some(ll_dst_addr), + next_header, + hop_limit, + }; + + tx_len += ieee_repr.buffer_len(); + tx_len += iphc_repr.buffer_len(); + + match &packet { + IpPacket::Udp((_, udp_repr)) => { + let udp_repr = SixlowpanUdpRepr(*udp_repr); + tx_len += udp_repr.buffer_len(); + } + IpPacket::Icmpv6((_, icmp)) => { + tx_len += icmp.buffer_len(); + } + _ => return Err(Error::Unrecognized), + } + + //tx_len += 2; // XXX: FCS calculation not needed when doing it in hardware + + tx_token.consume(timestamp, tx_len, |mut tx_buffer| { + // 1. Create the header of 802.15.4 + let mut ieee_packet = Ieee802154Frame::new_unchecked(&mut tx_buffer); + ieee_repr.emit(&mut ieee_packet); + + let mut start = ieee_repr.buffer_len(); + + // 2. Create the header for 6LoWPAN IPHC + let mut iphc_packet = + SixlowpanIphcPacket::new_unchecked(&mut tx_buffer[start..tx_len]); + iphc_repr.emit(&mut iphc_packet); + start = start + iphc_repr.buffer_len(); + + match packet { + IpPacket::Udp((_, udp_repr)) => { + // 3. Create the header for 6LoWPAN UDP + let mut udp_packet = + SixlowpanUdpPacket::new_unchecked(&mut tx_buffer[start..tx_len]); + SixlowpanUdpRepr(udp_repr).emit( + &mut udp_packet, + &iphc_repr.src_addr, + &iphc_repr.dst_addr, + ); + } + IpPacket::Icmpv6((_, icmp_repr)) => { + // 3. Create the header for ICMPv6 + let mut icmp_packet = + Icmpv6Packet::new_unchecked(&mut tx_buffer[start..tx_len]); + + icmp_repr.emit( + &iphc_repr.src_addr.into(), + &iphc_repr.dst_addr.into(), + &mut icmp_packet, + &self.device_capabilities.checksum, + ); + } + _ => return Err(Error::Unrecognized), + } + + //let fcs = crate::wire::ieee802154::calculate_crc(&tx_buffer[..tx_len-2]); + //tx_buffer[tx_len-1] = ((fcs >> 8) & 0xff) as u8; + //tx_buffer[tx_len-2] = (fcs & 0xff) as u8; + Ok(()) }) } @@ -2814,7 +3183,7 @@ mod test { let solicit = Icmpv6Repr::Ndisc(NdiscRepr::NeighborSolicit { target_addr: local_ip_addr, - lladdr: Some(remote_hw_addr), + lladdr: Some(remote_hw_addr.into()), }); let ip_repr = IpRepr::Ipv6(Ipv6Repr { src_addr: remote_ip_addr, @@ -2841,7 +3210,7 @@ mod test { let icmpv6_expected = Icmpv6Repr::Ndisc(NdiscRepr::NeighborAdvert { flags: NdiscNeighborFlags::SOLICITED, target_addr: local_ip_addr, - lladdr: Some(local_hw_addr), + lladdr: Some(local_hw_addr.into()), }); let ipv6_expected = Ipv6Repr { diff --git a/src/iface/mod.rs b/src/iface/mod.rs index 18f0b1227..901c08ad2 100644 --- a/src/iface/mod.rs +++ b/src/iface/mod.rs @@ -4,19 +4,27 @@ The `iface` module deals with the *network interfaces*. It filters incoming fram provides lookup and caching of hardware addresses, and handles management packets. */ -#[cfg(any(feature = "medium-ethernet", feature = "medium-ip"))] +#[cfg(any( + feature = "medium-ethernet", + feature = "medium-ip", + feature = "medium-sixlowpan" +))] mod interface; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] mod neighbor; mod route; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] pub(crate) use self::neighbor::Answer as NeighborAnswer; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] pub use self::neighbor::Cache as NeighborCache; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] pub use self::neighbor::Neighbor; pub use self::route::{Route, Routes}; -#[cfg(any(feature = "medium-ethernet", feature = "medium-ip"))] +#[cfg(any( + feature = "medium-ethernet", + feature = "medium-ip", + feature = "medium-sixlowpan" +))] pub use self::interface::{Interface, InterfaceBuilder}; diff --git a/src/iface/neighbor.rs b/src/iface/neighbor.rs index 64d239caf..c4421c3c2 100644 --- a/src/iface/neighbor.rs +++ b/src/iface/neighbor.rs @@ -4,7 +4,7 @@ use managed::ManagedMap; use crate::time::{Duration, Instant}; -use crate::wire::{EthernetAddress, IpAddress}; +use crate::wire::{HardwareAddress, IpAddress}; /// A cached neighbor. /// @@ -13,7 +13,7 @@ use crate::wire::{EthernetAddress, IpAddress}; #[derive(Debug, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Neighbor { - hardware_addr: EthernetAddress, + hardware_addr: HardwareAddress, expires_at: Instant, } @@ -22,7 +22,7 @@ pub struct Neighbor { #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub(crate) enum Answer { /// The neighbor address is in the cache and not expired. - Found(EthernetAddress), + Found(HardwareAddress), /// The neighbor address is not in the cache, or has expired. NotFound, /// The neighbor address is not in the cache, or has expired, @@ -104,7 +104,7 @@ impl<'a> Cache<'a> { pub fn fill( &mut self, protocol_addr: IpAddress, - hardware_addr: EthernetAddress, + hardware_addr: HardwareAddress, timestamp: Instant, ) { debug_assert!(protocol_addr.is_unicast()); @@ -186,7 +186,7 @@ impl<'a> Cache<'a> { pub(crate) fn lookup(&self, protocol_addr: &IpAddress, timestamp: Instant) -> Answer { if protocol_addr.is_broadcast() { - return Answer::Found(EthernetAddress::BROADCAST); + return Answer::Found(HardwareAddress::BROADCAST); } if let Some(&Neighbor { @@ -217,10 +217,12 @@ mod test { use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3, MOCK_IP_ADDR_4}; use std::collections::BTreeMap; - const HADDR_A: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 1]); - const HADDR_B: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 2]); - const HADDR_C: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 3]); - const HADDR_D: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 4]); + use crate::wire::EthernetAddress; + + const HADDR_A: HardwareAddress = HardwareAddress::Ethernet(EthernetAddress([0, 0, 0, 0, 0, 1])); + const HADDR_B: HardwareAddress = HardwareAddress::Ethernet(EthernetAddress([0, 0, 0, 0, 0, 2])); + const HADDR_C: HardwareAddress = HardwareAddress::Ethernet(EthernetAddress([0, 0, 0, 0, 0, 3])); + const HADDR_D: HardwareAddress = HardwareAddress::Ethernet(EthernetAddress([0, 0, 0, 0, 0, 4])); #[test] fn test_fill() { diff --git a/src/lib.rs b/src/lib.rs index c0fd0fac5..ad742813b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -100,6 +100,11 @@ extern crate alloc; #[cfg(not(any(feature = "proto-ipv4", feature = "proto-ipv6")))] compile_error!("You must enable at least one of the following features: proto-ipv4, proto-ipv6"); +#[cfg(all(feature = "medium-ethernet", feature = "medium-sixlowpan"))] +compile_error!( + "You must enable at most one of the following features: medium-ethernet, medium-sixlowpan" +); + #[cfg(all( feature = "socket", not(any( diff --git a/src/phy/mod.rs b/src/phy/mod.rs index c156d58b9..05f8cb25b 100644 --- a/src/phy/mod.rs +++ b/src/phy/mod.rs @@ -254,6 +254,8 @@ impl DeviceCapabilities { } #[cfg(feature = "medium-ip")] Medium::Ip => self.max_transmission_unit, + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => self.max_transmission_unit, // XXX check this value } } } @@ -275,6 +277,13 @@ pub enum Medium { /// Examples of devices of this type are the Linux `tun`, PPP interfaces, VPNs in tun (layer 3) mode. #[cfg(feature = "medium-ip")] Ip, + + /// 6LoWPAN medium. Devices of this type send and receive IPv6 frames encoded using 6LoWPAN. + /// They are transmitted over IEEE802.15.4 or BLE. + /// + /// Examples of devices of this type are found in the Internet of Things realm. + #[cfg(feature = "medium-sixlowpan")] + Sixlowpan, } impl Default for Medium { @@ -283,6 +292,12 @@ impl Default for Medium { return Medium::Ethernet; #[cfg(all(feature = "medium-ip", not(feature = "medium-ethernet")))] return Medium::Ip; + #[cfg(all( + feature = "medium-sixlowpan", + not(feature = "medium-ip"), + not(feature = "medium-ethernet") + ))] + return Medium::Sixlowpan; #[cfg(all(not(feature = "medium-ip"), not(feature = "medium-ethernet")))] panic!("No medium enabled"); } diff --git a/src/phy/pcap_writer.rs b/src/phy/pcap_writer.rs index 03fee45f6..9b7a12b93 100644 --- a/src/phy/pcap_writer.rs +++ b/src/phy/pcap_writer.rs @@ -16,6 +16,8 @@ enum_with_unknown! { Ethernet = 1, /// IPv4 or IPv6 packets (depending on the version field) Ip = 101, + /// IEEE 802.15.4 packets with FCS included. + Ieee802154WithFcs = 195, } } @@ -139,6 +141,8 @@ impl Device<'a>, S: PcapSink + Clone> PcapWriter { Medium::Ip => PcapLinkType::Ip, #[cfg(feature = "medium-ethernet")] Medium::Ethernet => PcapLinkType::Ethernet, + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => PcapLinkType::Ieee802154WithFcs, }; sink.global_header(link_type); PcapWriter { lower, sink, mode } diff --git a/src/phy/raw_socket.rs b/src/phy/raw_socket.rs index 4c12635f5..95b2dbc92 100644 --- a/src/phy/raw_socket.rs +++ b/src/phy/raw_socket.rs @@ -26,10 +26,19 @@ impl RawSocket { /// /// This requires superuser privileges or a corresponding capability bit /// set on the executable. - pub fn new(name: &str) -> io::Result { + pub fn new(name: &str, medium: Medium) -> io::Result { let mut lower = sys::RawSocketDesc::new(name)?; lower.bind_interface()?; - let mtu = lower.interface_mtu()?; + + let mut mtu = lower.interface_mtu()?; + + #[cfg(feature = "medium-ethernet")] + if medium == Medium::Ethernet { + // SIOCGIFMTU returns the IP MTU (typically 1500 bytes.) + // smoltcp counts the entire Ethernet packet in the MTU, so add the Ethernet header size to it. + mtu += crate::wire::EthernetFrame::<&[u8]>::header_len() + } + Ok(RawSocket { lower: Rc::new(RefCell::new(lower)), mtu: mtu, diff --git a/src/phy/sys/linux.rs b/src/phy/sys/linux.rs index 58d819c9b..f83ab5866 100644 --- a/src/phy/sys/linux.rs +++ b/src/phy/sys/linux.rs @@ -3,6 +3,7 @@ pub const SIOCGIFMTU: libc::c_ulong = 0x8921; pub const SIOCGIFINDEX: libc::c_ulong = 0x8933; pub const ETH_P_ALL: libc::c_short = 0x0003; +pub const ETH_P_IEEE802154: libc::c_short = 0x00F6; pub const TUNSETIFF: libc::c_ulong = 0x400454CA; pub const IFF_TUN: libc::c_int = 0x0001; diff --git a/src/phy/sys/raw_socket.rs b/src/phy/sys/raw_socket.rs index 8d28b82b4..8e87477fd 100644 --- a/src/phy/sys/raw_socket.rs +++ b/src/phy/sys/raw_socket.rs @@ -18,10 +18,16 @@ impl AsRawFd for RawSocketDesc { impl RawSocketDesc { pub fn new(name: &str) -> io::Result { let lower = unsafe { + #[cfg(feature = "medium-sixlowpan")] + let protocol = imp::ETH_P_IEEE802154; + + #[cfg(feature = "medium-ethernet")] + let protocol = imp::ETH_P_ALL; + let lower = libc::socket( libc::AF_PACKET, libc::SOCK_RAW | libc::SOCK_NONBLOCK, - imp::ETH_P_ALL.to_be() as i32, + protocol.to_be() as i32, ); if lower == -1 { return Err(io::Error::last_os_error()); @@ -44,9 +50,15 @@ impl RawSocketDesc { } pub fn bind_interface(&mut self) -> io::Result<()> { + #[cfg(feature = "medium-sixlowpan")] + let protocol = imp::ETH_P_IEEE802154; + + #[cfg(feature = "medium-ethernet")] + let protocol = imp::ETH_P_ALL; + let sockaddr = libc::sockaddr_ll { sll_family: libc::AF_PACKET as u16, - sll_protocol: imp::ETH_P_ALL.to_be() as u16, + sll_protocol: protocol.to_be() as u16, sll_ifindex: ifreq_ioctl(self.lower, &mut self.ifreq, imp::SIOCGIFINDEX)?, sll_hatype: 1, sll_pkttype: 0, diff --git a/src/phy/sys/tuntap_interface.rs b/src/phy/sys/tuntap_interface.rs index 54b9c3647..883e53987 100644 --- a/src/phy/sys/tuntap_interface.rs +++ b/src/phy/sys/tuntap_interface.rs @@ -42,6 +42,8 @@ impl TunTapInterfaceDesc { Medium::Ip => imp::IFF_TUN, #[cfg(feature = "medium-ethernet")] Medium::Ethernet => imp::IFF_TAP, + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => todo!(), }; self.ifreq.ifr_data = mode | imp::IFF_NO_PI; ifreq_ioctl(self.lower, &mut self.ifreq, imp::TUNSETIFF).map(|_| ()) @@ -72,6 +74,8 @@ impl TunTapInterfaceDesc { Medium::Ip => ip_mtu, #[cfg(feature = "medium-ethernet")] Medium::Ethernet => ip_mtu + EthernetFrame::<&[u8]>::header_len(), + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => todo!(), }; Ok(mtu) diff --git a/src/phy/tracer.rs b/src/phy/tracer.rs index 40b140b0b..da1c4b02e 100644 --- a/src/phy/tracer.rs +++ b/src/phy/tracer.rs @@ -190,6 +190,8 @@ impl<'a> fmt::Display for Packet<'a> { } _ => f.write_str("unrecognized IP version"), }, + #[cfg(feature = "medium-sixlowpan")] + Medium::Sixlowpan => Ok(()), // XXX } } } diff --git a/src/wire/icmpv6.rs b/src/wire/icmpv6.rs index e093243d4..992bc246f 100644 --- a/src/wire/icmpv6.rs +++ b/src/wire/icmpv6.rs @@ -4,7 +4,7 @@ use core::{cmp, fmt}; use crate::phy::ChecksumCapabilities; use crate::wire::ip::checksum; use crate::wire::MldRepr; -#[cfg(feature = "medium-ethernet")] +#[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] use crate::wire::NdiscRepr; use crate::wire::{IpAddress, IpProtocol, Ipv6Packet, Ipv6Repr}; use crate::{Error, Result}; @@ -532,7 +532,7 @@ pub enum Repr<'a> { seq_no: u16, data: &'a [u8], }, - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] Ndisc(NdiscRepr<'a>), Mld(MldRepr<'a>), } @@ -617,7 +617,7 @@ impl<'a> Repr<'a> { seq_no: packet.echo_seq_no(), data: packet.payload(), }), - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] (msg_type, 0) if msg_type.is_ndisc() => NdiscRepr::parse(packet).map(Repr::Ndisc), (msg_type, 0) if msg_type.is_mld() => MldRepr::parse(packet).map(Repr::Mld), _ => Err(Error::Unrecognized), @@ -636,7 +636,7 @@ impl<'a> Repr<'a> { &Repr::EchoRequest { data, .. } | &Repr::EchoReply { data, .. } => { field::ECHO_SEQNO.end + data.len() } - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] &Repr::Ndisc(ndisc) => ndisc.buffer_len(), &Repr::Mld(mld) => mld.buffer_len(), } @@ -730,7 +730,7 @@ impl<'a> Repr<'a> { packet.payload_mut()[..data_len].copy_from_slice(&data[..data_len]) } - #[cfg(feature = "medium-ethernet")] + #[cfg(any(feature = "medium-ethernet", feature = "medium-sixlowpan"))] Repr::Ndisc(ndisc) => ndisc.emit(packet), Repr::Mld(mld) => mld.emit(packet), diff --git a/src/wire/ieee802154.rs b/src/wire/ieee802154.rs new file mode 100644 index 000000000..c911b84ac --- /dev/null +++ b/src/wire/ieee802154.rs @@ -0,0 +1,935 @@ +use core::fmt; + +use byteorder::{ByteOrder, LittleEndian}; + +use crate::wire::ipv6::Address as Ipv6Address; +use crate::Error; +use crate::Result; + +const CRC_TABLE: [u16; 256] = [ + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, + 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, + 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, + 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, + 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, + 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, + 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, + 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, + 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, + 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, + 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, + 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, + 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, + 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, + 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, + 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, + 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, + 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, + 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, + 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, + 0x3de3, 0x2c6a, 0x1ef1, 0x0f78, +]; + +pub fn calculate_crc(buffer: &[u8]) -> u16 { + fn crc_byte(crc: u16, c: u8) -> u16 { + (crc >> 8) ^ CRC_TABLE[((crc ^ (c as u16)) & 0xff) as usize] + } + + let mut crc = 0; + + for b in buffer { + crc = crc_byte(crc, *b); + } + + crc +} + +enum_with_unknown! { + /// IEEE 802.15.4 frame type. + pub enum FrameType(u8) { + Beacon = 0b000, + Data = 0b001, + Acknowledgement = 0b010, + MacCommand = 0b011, + Multipurpose = 0b101, + FragmentOrFrak = 0b110, + Extended = 0b111, + } +} + +impl fmt::Display for FrameType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + FrameType::Beacon => write!(f, "Beacon"), + FrameType::Data => write!(f, "Data"), + FrameType::Acknowledgement => write!(f, "Ack"), + FrameType::MacCommand => write!(f, "MAC command"), + FrameType::Multipurpose => write!(f, "Multipurpose"), + FrameType::FragmentOrFrak => write!(f, "FragmentOrFrak"), + FrameType::Extended => write!(f, "Extended"), + FrameType::Unknown(id) => write!(f, "0b{:04b}", id), + } + } +} +enum_with_unknown! { + /// IEEE 802.15.4 addressing mode for destination and source addresses. + pub enum AddressingMode(u8) { + Absent = 0b00, + Short = 0b10, + Extended = 0b11, + } +} + +impl AddressingMode { + /// Return the size in octets of the address. + fn size(&self) -> usize { + match self { + AddressingMode::Absent => 0, + AddressingMode::Short => 2, + AddressingMode::Extended => 8, + _ => unreachable!(), + } + } +} + +impl fmt::Display for AddressingMode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + AddressingMode::Absent => write!(f, "Absent"), + AddressingMode::Short => write!(f, "Short"), + AddressingMode::Extended => write!(f, "Extended"), + AddressingMode::Unknown(id) => write!(f, "0b{:04b}", id), + } + } +} + +/// A IEEE 802.15.4 PAN. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +pub struct Pan(pub u16); + +impl Pan { + /// Return the PAN ID as bytes. + pub fn as_bytes(&self) -> [u8; 2] { + let mut pan = [0u8; 2]; + LittleEndian::write_u16(&mut pan, self.0); + pan + } +} + +/// A IEEE 802.15.4 address. +#[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] +pub enum Address { + Absent, + Short([u8; 2]), + Extended([u8; 8]), +} + +impl Address { + /// The broadcast address. + pub const BROADCAST: Address = Address::Short([0xff; 2]); + + /// Query whether the address is an unicast address. + pub fn is_unicast(&self) -> bool { + !self.is_broadcast() + } + + /// Query whether this address is the broadcast address. + pub fn is_broadcast(&self) -> bool { + *self == Self::BROADCAST + } + + fn short_from_bytes(a: [u8; 2]) -> Self { + Self::Short(a) + } + + fn extended_from_bytes(a: [u8; 8]) -> Self { + Self::Extended(a) + } + + pub fn from_bytes(a: &[u8]) -> Self { + if a.len() == 2 { + let mut b = [0u8; 2]; + b.copy_from_slice(a); + Address::Short(b) + } else if a.len() == 8 { + let mut b = [0u8; 8]; + b.copy_from_slice(a); + Address::Extended(b) + } else { + panic!("Not an IEEE802.15.4 address"); + } + } + + pub fn as_bytes(&self) -> &[u8] { + match self { + Address::Absent => &[], + Address::Short(value) => value, + Address::Extended(value) => value, + } + } + + /// Convert the extended address to an Extended Unique Identifier (EUI-64) + pub fn as_eui_64(&self) -> Option<[u8; 8]> { + match self { + Address::Absent | Address::Short(_) => None, + Address::Extended(value) => { + let mut bytes = [0; 8]; + bytes.copy_from_slice(&value[..]); + + bytes[0] ^= 1 << 1; + + Some(bytes) + } + } + } + + /// Convert an extended address to a link-local IPv6 address using the EUI-64 format from + /// RFC2464. + pub fn as_link_local_address(&self) -> Option { + let mut bytes = [0; 16]; + bytes[0] = 0xfe; + bytes[1] = 0x80; + bytes[8..].copy_from_slice(&self.as_eui_64()?); + + Some(Ipv6Address::from_bytes(&bytes)) + } +} + +impl fmt::Display for Address { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Self::Absent => write!(f, "not-present"), + Self::Short(bytes) => { + write!(f, "{:02x}-{:02x}", bytes[0], bytes[1]) + } + Self::Extended(bytes) => { + write!( + f, + "{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}-{:02x}", + bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7] + ) + } + } + } +} + +enum_with_unknown! { + /// IEEE 802.15.4 addressing mode for destination and source addresses. + pub enum FrameVersion(u8) { + Ieee802154_2003 = 0b00, + Ieee802154_2006 = 0b01, + Ieee802154 = 0b10, + } +} + +/// A read/write wrapper around an IEEE 802.15.4 frame buffer. +#[derive(Debug, Clone)] +pub struct Frame> { + buffer: T, +} + +mod field { + use crate::wire::field::*; + + pub const FRAMECONTROL: Field = 0..2; + pub const SEQUENCE_NUMBER: usize = 2; + pub const ADDRESSING: Rest = 3..; +} + +macro_rules! fc_bit_field { + ($field:ident, $bit:literal) => { + #[inline] + pub fn $field(&self) -> bool { + let data = self.buffer.as_ref(); + let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]); + + ((raw >> $bit) & 0b1) == 0b1 + } + }; +} + +macro_rules! set_fc_bit_field { + ($field:ident, $bit:literal) => { + #[inline] + pub fn $field(&mut self) { + let data = &mut self.buffer.as_mut()[field::FRAMECONTROL]; + let mut raw = LittleEndian::read_u16(data); + raw |= (0b1 << $bit); + + data.copy_from_slice(&raw.to_le_bytes()); + } + }; +} + +impl> Frame { + /// Input a raw octet buffer with Ethernet frame structure. + pub fn new_unchecked(buffer: T) -> Frame { + Frame { buffer } + } + + /// Shorthand for a combination of [new_unchecked] and [check_len]. + /// + /// [new_unchecked]: #method.new_unchecked + /// [check_len]: #method.check_len + pub fn new_checked(buffer: T) -> Result> { + let packet = Self::new_unchecked(buffer); + packet.check_len()?; + Ok(packet) + } + + /// Ensure that no accessor method will panic if called. + /// Returns `Err(Error::Truncated)` if the buffer is too short. + pub fn check_len(&self) -> Result<()> { + if self.buffer.as_ref().is_empty() { + Err(Error::Truncated) + } else { + Ok(()) + } + } + + /// Consumes the frame, returning the underlying buffer. + pub fn into_inner(self) -> T { + self.buffer + } + + /// Return the FrameType field. + #[inline] + pub fn frame_type(&self) -> FrameType { + let data = self.buffer.as_ref(); + let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]); + let ft = (raw & 0b11) as u8; + FrameType::from(ft) + } + + fc_bit_field!(security_enabled, 3); + fc_bit_field!(frame_pending, 4); + fc_bit_field!(ack_request, 5); + fc_bit_field!(pan_id_compression, 6); + + fc_bit_field!(sequence_number_suppression, 8); + fc_bit_field!(ie_present, 9); + + /// Return the destination addressing mode. + #[inline] + pub fn dst_addressing_mode(&self) -> AddressingMode { + let data = self.buffer.as_ref(); + let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]); + let am = ((raw >> 10) & 0b11) as u8; + AddressingMode::from(am) + } + + /// Return the frame version. + #[inline] + pub fn frame_version(&self) -> FrameVersion { + let data = self.buffer.as_ref(); + let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]); + let fv = ((raw >> 12) & 0b11) as u8; + FrameVersion::from(fv) + } + + /// Return the source addressing mode. + #[inline] + pub fn src_addressing_mode(&self) -> AddressingMode { + let data = self.buffer.as_ref(); + let raw = LittleEndian::read_u16(&data[field::FRAMECONTROL]); + let am = ((raw >> 14) & 0b11) as u8; + AddressingMode::from(am) + } + + /// Return the sequence number of the frame. + #[inline] + pub fn sequence_number(&self) -> Option { + match self.frame_type() { + FrameType::Beacon + | FrameType::Data + | FrameType::Acknowledgement + | FrameType::MacCommand + | FrameType::Multipurpose => { + let data = self.buffer.as_ref(); + let raw = data[field::SEQUENCE_NUMBER]; + Some(raw) + } + FrameType::Extended | FrameType::FragmentOrFrak | FrameType::Unknown(_) => None, + } + } + + /// Return the addressing fields. + #[inline] + fn addressing_fields(&self) -> Option<&[u8]> { + match self.frame_type() { + FrameType::Beacon + | FrameType::Data + | FrameType::MacCommand + | FrameType::Multipurpose => (), + FrameType::Acknowledgement if self.frame_version() == FrameVersion::Ieee802154 => (), + FrameType::Acknowledgement + | FrameType::Extended + | FrameType::FragmentOrFrak + | FrameType::Unknown(_) => return None, + } + + let mut offset = 2; + + // Calculate the size of the addressing field. + offset += self.dst_addressing_mode().size(); + offset += self.src_addressing_mode().size(); + + if !self.pan_id_compression() { + offset += 2; + } + + Some(&self.buffer.as_ref()[field::ADDRESSING][..offset]) + } + + /// Return the destination PAN field. + #[inline] + pub fn dst_pan_id(&self) -> Option { + let addressing_fields = self.addressing_fields()?; + match self.dst_addressing_mode() { + AddressingMode::Absent => None, + AddressingMode::Short | AddressingMode::Extended => { + Some(Pan(LittleEndian::read_u16(&addressing_fields[0..2]))) + } + AddressingMode::Unknown(_) => None, + } + } + + /// Return the destination address field. + #[inline] + pub fn dst_addr(&self) -> Option
{ + let addressing_fields = self.addressing_fields()?; + match self.dst_addressing_mode() { + AddressingMode::Absent => Some(Address::Absent), + AddressingMode::Short => { + let mut raw = [0u8; 2]; + raw.clone_from_slice(&addressing_fields[2..4]); + raw.reverse(); + Some(Address::short_from_bytes(raw)) + } + AddressingMode::Extended => { + let mut raw = [0u8; 8]; + raw.clone_from_slice(&addressing_fields[2..10]); + raw.reverse(); + Some(Address::extended_from_bytes(raw)) + } + AddressingMode::Unknown(_) => None, + } + } + + /// Return the destination PAN field. + #[inline] + pub fn src_pan_id(&self) -> Option { + if self.pan_id_compression() { + return None; + } + + let addressing_fields = self.addressing_fields()?; + let offset = self.dst_addressing_mode().size() + 2; + + match self.src_addressing_mode() { + AddressingMode::Absent => None, + AddressingMode::Short | AddressingMode::Extended => Some(Pan(LittleEndian::read_u16( + &addressing_fields[offset..offset + 2], + ))), + AddressingMode::Unknown(_) => None, + } + } + + /// Return the source address field. + #[inline] + pub fn src_addr(&self) -> Option
{ + let addressing_fields = self.addressing_fields()?; + let mut offset = match self.dst_addressing_mode() { + AddressingMode::Absent => 0, + AddressingMode::Short => 2, + AddressingMode::Extended => 8, + _ => unreachable!(), + } + 2; + + if !self.pan_id_compression() { + offset += 2; + } + + match self.src_addressing_mode() { + AddressingMode::Absent => Some(Address::Absent), + AddressingMode::Short => { + let mut raw = [0u8; 2]; + raw.clone_from_slice(&addressing_fields[offset..offset + 2]); + raw.reverse(); + Some(Address::short_from_bytes(raw)) + } + AddressingMode::Extended => { + let mut raw = [0u8; 8]; + raw.clone_from_slice(&addressing_fields[offset..offset + 8]); + raw.reverse(); + Some(Address::extended_from_bytes(raw)) + } + AddressingMode::Unknown(_) => None, + } + } + + /// Return the Auxilliary Security Header Field + #[inline] + pub fn aux_security_header(&self) -> Option<&[u8]> { + match self.frame_type() { + FrameType::Beacon + | FrameType::Data + | FrameType::MacCommand + | FrameType::Multipurpose => (), + FrameType::Acknowledgement if self.frame_version() == FrameVersion::Ieee802154 => (), + FrameType::Acknowledgement + | FrameType::Extended + | FrameType::FragmentOrFrak + | FrameType::Unknown(_) => return None, + } + + if !self.security_enabled() { + return None; + } + + todo!(); + } + + /// Return the IE field (the header as well as the payload IE) + #[inline] + pub fn ie_field(&self) -> Option<&[u8]> { + match self.frame_type() { + FrameType::Data | FrameType::MacCommand | FrameType::Multipurpose => (), + FrameType::Beacon | FrameType::Acknowledgement + if self.frame_version() == FrameVersion::Ieee802154 => + { + () + } + FrameType::Beacon + | FrameType::Acknowledgement + | FrameType::Extended + | FrameType::FragmentOrFrak + | FrameType::Unknown(_) => return None, + } + + if !self.ie_present() { + return None; + } + + todo!(); + } + + /// Return the FCS fields + #[inline] + pub fn fcs(&self) -> &[u8] { + &self.buffer.as_ref()[self.buffer.as_ref().len() - 2..] + } +} + +impl<'a, T: AsRef<[u8]> + ?Sized> Frame<&'a T> { + /// Return a pointer to the payload. + #[inline] + pub fn payload(&self) -> Option<&'a [u8]> { + match self.frame_type() { + FrameType::Data => { + let data = &self.buffer.as_ref()[field::ADDRESSING]; + let offset = self.addressing_fields().unwrap().len(); + + Some(&data[offset..data.len() - 2]) + } + _ => None, + } + } +} + +impl + AsMut<[u8]>> Frame { + /// Set the frame type. + #[inline] + pub fn set_frame_type(&mut self, frame_type: FrameType) { + let data = &mut self.buffer.as_mut()[field::FRAMECONTROL]; + let mut raw = LittleEndian::read_u16(data); + + raw = (raw & !(0b111)) | (u8::from(frame_type) as u16 & 0b111); + data.copy_from_slice(&raw.to_le_bytes()); + } + + set_fc_bit_field!(set_security_enabled, 3); + set_fc_bit_field!(set_frame_pending, 4); + set_fc_bit_field!(set_ack_request, 5); + set_fc_bit_field!(set_pan_id_compression, 6); + + /// Set the frame version. + #[inline] + pub fn set_frame_version(&mut self, version: FrameVersion) { + let data = &mut self.buffer.as_mut()[field::FRAMECONTROL]; + let mut raw = LittleEndian::read_u16(data); + + raw = (raw & !(0b11 << 12)) | ((u8::from(version) as u16 & 0b11) << 12); + data.copy_from_slice(&raw.to_le_bytes()); + } + + /// Set the frame sequence number. + #[inline] + pub fn set_sequence_number(&mut self, value: u8) { + let data = self.buffer.as_mut(); + data[field::SEQUENCE_NUMBER] = value; + } + + /// Set the destination PAN ID. + #[inline] + pub fn set_dst_pan_id(&mut self, value: Pan) { + // NOTE the destination addressing mode must be different than Absent. + // This is the reason why we set it to Extended. + self.set_dst_addressing_mode(AddressingMode::Extended); + + let data = self.buffer.as_mut(); + data[field::ADDRESSING][..2].copy_from_slice(&value.as_bytes()); + } + + /// Set the destination address. + #[inline] + pub fn set_dst_addr(&mut self, mut value: Address) { + match value { + Address::Absent => self.set_dst_addressing_mode(AddressingMode::Absent), + Address::Short(ref mut value) => { + value.reverse(); + self.set_dst_addressing_mode(AddressingMode::Short); + let data = self.buffer.as_mut(); + data[field::ADDRESSING][2..2 + 2].copy_from_slice(value); + value.reverse(); + } + Address::Extended(ref mut value) => { + value.reverse(); + self.set_dst_addressing_mode(AddressingMode::Extended); + let data = &mut self.buffer.as_mut()[field::ADDRESSING]; + data[2..2 + 8].copy_from_slice(value); + value.reverse(); + } + } + } + + /// Set the destination addressing mode. + #[inline] + fn set_dst_addressing_mode(&mut self, value: AddressingMode) { + let data = &mut self.buffer.as_mut()[field::FRAMECONTROL]; + let mut raw = LittleEndian::read_u16(data); + + raw = (raw & !(0b11 << 10)) | ((u8::from(value) as u16 & 0b11) << 10); + data.copy_from_slice(&raw.to_le_bytes()); + } + + /// Set the source PAN ID. + #[inline] + pub fn set_src_pan_id(&mut self, value: Pan) { + let offset = match self.dst_addressing_mode() { + AddressingMode::Absent => todo!("{}", self.dst_addressing_mode()), + AddressingMode::Short => 2, + AddressingMode::Extended => 8, + _ => unreachable!(), + } + 2; + + let data = &mut self.buffer.as_mut()[field::ADDRESSING]; + data[offset..offset + 2].copy_from_slice(&value.as_bytes()); + } + + /// Set the source address. + #[inline] + pub fn set_src_addr(&mut self, mut value: Address) { + let offset = match self.dst_addressing_mode() { + AddressingMode::Absent => todo!("{}", self.dst_addressing_mode()), + AddressingMode::Short => 2, + AddressingMode::Extended => 8, + _ => unreachable!(), + } + 2; + + let offset = offset + if self.pan_id_compression() { 0 } else { 2 }; + + match value { + Address::Absent => self.set_src_addressing_mode(AddressingMode::Absent), + Address::Short(ref mut value) => { + value.reverse(); + self.set_src_addressing_mode(AddressingMode::Short); + let data = &mut self.buffer.as_mut()[field::ADDRESSING]; + data[offset..offset + 2].copy_from_slice(value); + value.reverse(); + } + Address::Extended(ref mut value) => { + value.reverse(); + self.set_src_addressing_mode(AddressingMode::Extended); + let data = &mut self.buffer.as_mut()[field::ADDRESSING]; + data[offset..offset + 8].copy_from_slice(value); + value.reverse(); + } + } + } + + /// Set the source addressing mode. + #[inline] + fn set_src_addressing_mode(&mut self, value: AddressingMode) { + let data = &mut self.buffer.as_mut()[field::FRAMECONTROL]; + let mut raw = LittleEndian::read_u16(data); + + raw = (raw & !(0b11 << 14)) | ((u8::from(value) as u16 & 0b11) << 14); + data.copy_from_slice(&raw.to_le_bytes()); + } + + /// Return a mutable pointer to the payload. + #[inline] + pub fn payload_mut(&mut self) -> Option<&mut [u8]> { + match self.frame_type() { + FrameType::Data => { + let mut start_offset = 3; + start_offset += self.addressing_fields().unwrap().len(); + + let data = self.buffer.as_mut(); + let end_offset = start_offset + data.len() - 2; + Some(&mut data[start_offset..end_offset]) + } + _ => None, + } + } +} + +impl> fmt::Display for Frame { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!( + f, + "IEEE802.15.4 frame type={} seq={:2x?} dst_pan={:x?} dest={:x?} src_pan={:?} src={:x?} fcs={:x?}", + self.frame_type(), + self.sequence_number(), + self.dst_pan_id(), + self.dst_addr(), + self.src_pan_id(), + self.src_addr(), + self.fcs(), + ) + } +} + +/// A high-level representation of an IEEE802.15.4 frame. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub struct Repr { + pub frame_type: FrameType, + pub security_enabled: bool, + pub frame_pending: bool, + pub ack_request: bool, + pub sequence_number: Option, + pub pan_id_compression: bool, + pub frame_version: FrameVersion, + pub dst_pan_id: Option, + pub dst_addr: Option
, + pub src_pan_id: Option, + pub src_addr: Option
, +} + +impl Repr { + /// Parse an IEEE 802.15.4 frame and return a high-level representation. + pub fn parse + ?Sized>(packet: &Frame<&T>) -> Result { + // Ensure the basic accessors will work. + packet.check_len()?; + + Ok(Repr { + frame_type: packet.frame_type(), + security_enabled: packet.security_enabled(), + frame_pending: packet.frame_pending(), + ack_request: packet.ack_request(), + sequence_number: packet.sequence_number(), + pan_id_compression: packet.pan_id_compression(), + frame_version: packet.frame_version(), + dst_pan_id: packet.dst_pan_id(), + dst_addr: packet.dst_addr(), + src_pan_id: packet.src_pan_id(), + src_addr: packet.src_addr(), + }) + } + + /// Return the length of a buffer required to hold a packet with the payload of a given length. + #[inline] + pub fn buffer_len(&self) -> usize { + 3 + 2 + + match self.dst_addr { + Some(Address::Absent) | None => 0, + Some(Address::Short(_)) => 2, + Some(Address::Extended(_)) => 8, + } + + if !self.pan_id_compression { 2 } else { 0 } + + match self.src_addr { + Some(Address::Absent) | None => 0, + Some(Address::Short(_)) => 2, + Some(Address::Extended(_)) => 8, + } + } + + /// Emit a high-level representation into an IEEE802.15.4 frame. + pub fn emit + AsMut<[u8]>>(&self, frame: &mut Frame) { + frame.set_frame_type(self.frame_type); + if self.security_enabled { + frame.set_security_enabled(); + } + + if self.frame_pending { + frame.set_frame_pending(); + } + + if self.ack_request { + frame.set_ack_request(); + } + + if self.pan_id_compression { + frame.set_pan_id_compression(); + } + + frame.set_frame_version(self.frame_version); + + if let Some(sequence_number) = self.sequence_number { + frame.set_sequence_number(sequence_number); + } + + if let Some(dst_pan_id) = self.dst_pan_id { + frame.set_dst_pan_id(dst_pan_id); + } + if let Some(dst_addr) = self.dst_addr { + frame.set_dst_addr(dst_addr); + } + + if !self.pan_id_compression && self.src_pan_id.is_some() { + frame.set_src_pan_id(self.src_pan_id.unwrap()); + } + + if let Some(src_addr) = self.src_addr { + frame.set_src_addr(src_addr); + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use crate::Result; + + #[test] + fn test_broadcast() { + assert!(Address::BROADCAST.is_broadcast()); + assert!(!Address::BROADCAST.is_unicast()); + } + + #[test] + fn prepare_frame() { + let mut buffer = [0u8; 128]; + + let payload = 1234u32.to_le_bytes(); + let repr = Repr { + frame_type: FrameType::Data, + security_enabled: false, + frame_pending: false, + ack_request: true, + pan_id_compression: true, + frame_version: FrameVersion::Ieee802154, + sequence_number: Some(1), + dst_pan_id: Some(Pan(0xabcd)), + dst_addr: Some(Address::BROADCAST), + src_pan_id: None, + src_addr: Some(Address::Extended([ + 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00, + ])), + }; + + let buffer_len = repr.buffer_len(); + + let mut frame = Frame::new_unchecked(&mut buffer[..buffer_len]); + repr.emit(&mut frame); + + println!("{:2x?}", frame); + + assert_eq!(frame.frame_type(), FrameType::Data); + assert_eq!(frame.security_enabled(), false); + assert_eq!(frame.frame_pending(), false); + assert_eq!(frame.ack_request(), true); + assert_eq!(frame.pan_id_compression(), true); + assert_eq!(frame.frame_version(), FrameVersion::Ieee802154); + assert_eq!(frame.sequence_number(), Some(1)); + assert_eq!(frame.dst_pan_id(), Some(Pan(0xabcd))); + assert_eq!(frame.dst_addr(), Some(Address::BROADCAST)); + assert_eq!(frame.src_pan_id(), None); + assert_eq!( + frame.src_addr(), + Some(Address::Extended([ + 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00 + ])) + ); + } + + macro_rules! vector_test { + ($name:ident $bytes:expr ; $($test_method:ident -> $expected:expr,)*) => { + #[test] + fn $name() -> Result<()> { + let frame = &$bytes; + let frame = Frame::new_checked(frame)?; + + $( + let v = frame.$test_method(); + assert_eq!($expected, v, stringify!($test_method)); + )* + + Ok(()) + } + } + } + + vector_test! { + extended_addr + [ + 0b0000_0001, 0b1100_1100, // frame control + 0b0, // seq + 0xcd, 0xab, // pan id + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, // dst addr + 0x03, 0x04, // pan id + 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, // src addr + ]; + frame_type -> FrameType::Data, + dst_addr -> Some(Address::Extended([0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01])), + src_addr -> Some(Address::Extended([0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02])), + dst_pan_id -> Some(Pan(0xabcd)), + } + + vector_test! { + short_addr + [ + 0x01, 0x98, // frame control + 0x00, // sequence number + 0x34, 0x12, 0x78, 0x56, // PAN identifier and address of destination + 0x34, 0x12, 0xbc, 0x9a, // PAN identifier and address of source + ]; + frame_type -> FrameType::Data, + security_enabled -> false, + frame_pending -> false, + ack_request -> false, + pan_id_compression -> false, + dst_addressing_mode -> AddressingMode::Short, + frame_version -> FrameVersion::Ieee802154_2006, + src_addressing_mode -> AddressingMode::Short, + dst_pan_id -> Some(Pan(0x1234)), + dst_addr -> Some(Address::Short([0x78, 0x56])), + src_pan_id -> Some(Pan(0x1234)), + src_addr -> Some(Address::Short([0xbc, 0x9a])), + } + + vector_test! { + zolertia_remote + [ + 0x41, 0xd8, // frame control + 0x01, // sequence number + 0xcd, 0xab, // Destination PAN id + 0xff, 0xff, // Short destination address + 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00, // Extended source address + 0x2b, 0x00, 0x00, 0x00, // payload + 0xb3, 0x0d // FSM + ]; + frame_type -> FrameType::Data, + security_enabled -> false, + frame_pending -> false, + ack_request -> false, + pan_id_compression -> true, + dst_addressing_mode -> AddressingMode::Short, + frame_version -> FrameVersion::Ieee802154_2006, + src_addressing_mode -> AddressingMode::Extended, + //payload -> Some(&[0x2b, 0x00, 0x00, 0x00]), + fcs -> [0xb3, 0x0d], + } +} diff --git a/src/wire/ip.rs b/src/wire/ip.rs index 7f9f483c0..586b66857 100644 --- a/src/wire/ip.rs +++ b/src/wire/ip.rs @@ -6,6 +6,8 @@ use crate::phy::ChecksumCapabilities; use crate::wire::{Ipv4Address, Ipv4Cidr, Ipv4Packet, Ipv4Repr}; #[cfg(feature = "proto-ipv6")] use crate::wire::{Ipv6Address, Ipv6Cidr, Ipv6Packet, Ipv6Repr}; +#[cfg(feature = "sixlowpan")] +use crate::wire::{SixlowpanIphcPacket, SixlowpanIphcRepr}; use crate::{Error, Result}; /// Internet protocol version. @@ -500,6 +502,8 @@ pub enum Repr { Ipv4(Ipv4Repr), #[cfg(feature = "proto-ipv6")] Ipv6(Ipv6Repr), + #[cfg(feature = "proto-sixlowpan")] + Sixlowpan(SixlowpanIphcRepr), } #[cfg(feature = "proto-ipv4")] @@ -525,6 +529,8 @@ impl Repr { Repr::Ipv4(_) => Version::Ipv4, #[cfg(feature = "proto-ipv6")] Repr::Ipv6(_) => Version::Ipv6, + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(_) => Version::Ipv6, } } @@ -536,6 +542,8 @@ impl Repr { Repr::Ipv4(repr) => Address::Ipv4(repr.src_addr), #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => Address::Ipv6(repr.src_addr), + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => Address::Ipv6(repr.src_addr), } } @@ -547,6 +555,8 @@ impl Repr { Repr::Ipv4(repr) => Address::Ipv4(repr.dst_addr), #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => Address::Ipv6(repr.dst_addr), + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => Address::Ipv6(repr.dst_addr), } } @@ -558,6 +568,8 @@ impl Repr { Repr::Ipv4(repr) => repr.protocol, #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => repr.next_header, + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => todo!("{:?}", repr), } } @@ -569,6 +581,8 @@ impl Repr { Repr::Ipv4(repr) => repr.payload_len, #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => repr.payload_len, + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => todo!("{:?}", repr), } } @@ -589,6 +603,8 @@ impl Repr { ref mut payload_len, .. }) => *payload_len = length, + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(_) => todo!(), } } @@ -600,6 +616,8 @@ impl Repr { Repr::Ipv4(Ipv4Repr { hop_limit, .. }) => hop_limit, #[cfg(feature = "proto-ipv6")] Repr::Ipv6(Ipv6Repr { hop_limit, .. }) => hop_limit, + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(SixlowpanIphcRepr { hop_limit, .. }) => hop_limit, } } @@ -740,6 +758,9 @@ impl Repr { resolve_unspecified!(Repr::Ipv6, Address::Ipv6, repr, fallback_src_addrs) } + #[cfg(feature = "proto-sixlowpan")] + &Repr::Sixlowpan(_) => todo!(), + &Repr::Unspecified { .. } => { panic!("source and destination IP address families do not match") } @@ -757,6 +778,8 @@ impl Repr { Repr::Ipv4(repr) => repr.buffer_len(), #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => repr.buffer_len(), + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => repr.buffer_len(), } } @@ -775,6 +798,8 @@ impl Repr { Repr::Ipv4(repr) => repr.emit(&mut Ipv4Packet::new_unchecked(buffer), _checksum_caps), #[cfg(feature = "proto-ipv6")] Repr::Ipv6(repr) => repr.emit(&mut Ipv6Packet::new_unchecked(buffer)), + #[cfg(feature = "proto-sixlowpan")] + Repr::Sixlowpan(repr) => repr.emit(&mut SixlowpanIphcPacket::new_unchecked(buffer)), } } diff --git a/src/wire/mod.rs b/src/wire/mod.rs index e1dc18d32..115e28ee4 100644 --- a/src/wire/mod.rs +++ b/src/wire/mod.rs @@ -89,6 +89,8 @@ mod icmp; mod icmpv4; #[cfg(feature = "proto-ipv6")] mod icmpv6; +#[cfg(feature = "ieee802154")] +pub mod ieee802154; #[cfg(feature = "proto-igmp")] mod igmp; pub(crate) mod ip; @@ -106,10 +108,18 @@ mod ipv6option; mod ipv6routing; #[cfg(feature = "proto-ipv6")] mod mld; -#[cfg(all(feature = "proto-ipv6", feature = "medium-ethernet"))] +#[cfg(all( + feature = "proto-ipv6", + any(feature = "medium-ethernet", feature = "medium-sixlowpan") +))] mod ndisc; -#[cfg(all(feature = "proto-ipv6", feature = "medium-ethernet"))] +#[cfg(all( + feature = "proto-ipv6", + any(feature = "medium-ethernet", feature = "medium-sixlowpan") +))] mod ndiscoption; +#[cfg(feature = "sixlowpan")] +mod sixlowpan; mod tcp; mod udp; @@ -126,6 +136,24 @@ pub use self::arp::{ Hardware as ArpHardware, Operation as ArpOperation, Packet as ArpPacket, Repr as ArpRepr, }; +#[cfg(feature = "sixlowpan")] +pub use self::sixlowpan::{ + iphc::{Packet as SixlowpanIphcPacket, Repr as SixlowpanIphcRepr}, + nhc::{ + ExtensionHeaderPacket as SixlowpanExtHeaderPacket, + ExtensionHeaderRepr as SixlowpanExtHeaderRepr, Packet as SixlowpanNhcPacket, + UdpNhcRepr as SixlowpanUdpRepr, UdpPacket as SixlowpanUdpPacket, + }, + NextHeader as SixlowpanNextHeader, +}; + +#[cfg(feature = "ieee802154")] +pub use self::ieee802154::{ + Address as Ieee802154Address, AddressingMode as Ieee802154AddressingMode, + Frame as Ieee802154Frame, FrameType as Ieee802154FrameType, + FrameVersion as Ieee802154FrameVersion, Pan as Ieee802154Pan, Repr as Ieee802154Repr, +}; + pub use self::ip::{ Address as IpAddress, Cidr as IpCidr, Endpoint as IpEndpoint, Protocol as IpProtocol, Repr as IpRepr, Version as IpVersion, @@ -177,12 +205,18 @@ pub use self::icmpv6::{ #[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))] pub use self::icmp::Repr as IcmpRepr; -#[cfg(all(feature = "proto-ipv6", feature = "medium-ethernet"))] +#[cfg(all( + feature = "proto-ipv6", + any(feature = "medium-ethernet", feature = "medium-sixlowpan") +))] pub use self::ndisc::{ NeighborFlags as NdiscNeighborFlags, Repr as NdiscRepr, RouterFlags as NdiscRouterFlags, }; -#[cfg(all(feature = "proto-ipv6", feature = "medium-ethernet"))] +#[cfg(all( + feature = "proto-ipv6", + any(feature = "medium-ethernet", feature = "medium-sixlowpan") +))] pub use self::ndiscoption::{ NdiscOption, PrefixInfoFlags as NdiscPrefixInfoFlags, PrefixInformation as NdiscPrefixInformation, RedirectedHeader as NdiscRedirectedHeader, @@ -205,3 +239,73 @@ pub use self::dhcpv4::{ CLIENT_PORT as DHCP_CLIENT_PORT, MAX_DNS_SERVER_COUNT as DHCP_MAX_DNS_SERVER_COUNT, SERVER_PORT as DHCP_SERVER_PORT, }; + +/// Representation of an hardware address, such as an Ethernet address or an IEEE802.15.4 address. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HardwareAddress { + BROADCAST, + #[cfg(feature = "medium-ethernet")] + Ethernet(EthernetAddress), + #[cfg(feature = "medium-sixlowpan")] + Ieee802154(Ieee802154Address), +} + +impl HardwareAddress { + pub fn as_bytes(&self) -> &[u8] { + match self { + #[cfg(feature = "medium-ethernet")] + HardwareAddress::Ethernet(addr) => addr.as_bytes(), + #[cfg(feature = "medium-sixlowpan")] + HardwareAddress::Ieee802154(addr) => addr.as_bytes(), + _ => todo!(), + } + } + + /// Query wether the address is an unicast address. + pub fn is_unicast(&self) -> bool { + match self { + #[cfg(feature = "medium-ethernet")] + HardwareAddress::Ethernet(addr) => addr.is_unicast(), + #[cfg(feature = "medium-sixlowpan")] + HardwareAddress::Ieee802154(addr) => addr.is_unicast(), + _ => todo!(), + } + } + + /// Query wether the address is a broadcast address. + pub fn is_broadcast(&self) -> bool { + match self { + #[cfg(feature = "medium-ethernet")] + HardwareAddress::Ethernet(addr) => addr.is_broadcast(), + #[cfg(feature = "medium-sixlowpan")] + HardwareAddress::Ieee802154(addr) => addr.is_broadcast(), + _ => todo!(), + } + } +} + +impl core::fmt::Display for HardwareAddress { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + match self { + HardwareAddress::BROADCAST => write!(f, "BROADCAST"), + #[cfg(feature = "medium-ethernet")] + HardwareAddress::Ethernet(addr) => write!(f, "{}", addr), + #[cfg(feature = "medium-sixlowpan")] + HardwareAddress::Ieee802154(addr) => write!(f, "{}", addr), + } + } +} + +#[cfg(feature = "medium-ethernet")] +impl From for HardwareAddress { + fn from(addr: EthernetAddress) -> Self { + HardwareAddress::Ethernet(addr) + } +} + +#[cfg(feature = "medium-sixlowpan")] +impl From for HardwareAddress { + fn from(addr: Ieee802154Address) -> Self { + HardwareAddress::Ieee802154(addr) + } +} diff --git a/src/wire/ndisc.rs b/src/wire/ndisc.rs index 89c8c711b..8648991f6 100644 --- a/src/wire/ndisc.rs +++ b/src/wire/ndisc.rs @@ -4,10 +4,11 @@ use byteorder::{ByteOrder, NetworkEndian}; use crate::time::Duration; use crate::wire::icmpv6::{field, Message, Packet}; use crate::wire::Ipv6Address; -use crate::wire::{EthernetAddress, Ipv6Packet, Ipv6Repr}; +use crate::wire::{Ipv6Packet, Ipv6Repr}; use crate::wire::{NdiscOption, NdiscOptionRepr, NdiscOptionType}; use crate::wire::{NdiscPrefixInformation, NdiscRedirectedHeader}; use crate::{Error, Result}; +use crate::wire::HardwareAddress; bitflags! { #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -193,7 +194,7 @@ impl + AsMut<[u8]>> Packet { #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Repr<'a> { RouterSolicit { - lladdr: Option, + lladdr: Option, }, RouterAdvert { hop_limit: u8, @@ -201,23 +202,23 @@ pub enum Repr<'a> { router_lifetime: Duration, reachable_time: Duration, retrans_time: Duration, - lladdr: Option, + lladdr: Option, mtu: Option, prefix_info: Option, }, NeighborSolicit { target_addr: Ipv6Address, - lladdr: Option, + lladdr: Option, }, NeighborAdvert { flags: NeighborFlags, target_addr: Ipv6Address, - lladdr: Option, + lladdr: Option, }, Redirect { target_addr: Ipv6Address, dest_addr: Ipv6Address, - lladdr: Option, + lladdr: Option, redirected_hdr: Option>, }, } @@ -373,7 +374,21 @@ impl<'a> Repr<'a> { } &Repr::NeighborSolicit { lladdr, .. } | &Repr::NeighborAdvert { lladdr, .. } => { match lladdr { - Some(_) => field::TARGET_ADDR.end + 8, + Some(addr) => { + let mut len = field::TARGET_ADDR.end; + len += 2; + len += addr.as_bytes().len(); + + // A packet of len == 30 is a packet with an Ethernet address + if len > 30 { + // TODO: find out why this padding is +4 and not +6 + // WireShark wants a padding of +6, however, then the packet is not accepted when using ping + // When a padding of +4 is used, then WireShark complains and says that the packet is malformed, + // however, ping accepts this packet. + len += 4; // Padding + } + len + } None => field::TARGET_ADDR.end, } } @@ -509,6 +524,8 @@ mod test { use super::*; use crate::phy::ChecksumCapabilities; use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2}; + use crate::wire::EthernetAddress; + use crate::wire::HardwareAddress; use crate::wire::Icmpv6Repr; static ROUTER_ADVERT_BYTES: [u8; 24] = [ @@ -524,7 +541,9 @@ mod test { router_lifetime: Duration::from_secs(900), reachable_time: Duration::from_millis(900), retrans_time: Duration::from_millis(900), - lladdr: Some(EthernetAddress([0x52, 0x54, 0x00, 0x12, 0x34, 0x56])), + lladdr: Some(HardwareAddress::Ethernet(EthernetAddress([ + 0x52, 0x54, 0x00, 0x12, 0x34, 0x56, + ]))), mtu: None, prefix_info: None, }) diff --git a/src/wire/ndiscoption.rs b/src/wire/ndiscoption.rs index 6c79b5ff2..00f75f47c 100644 --- a/src/wire/ndiscoption.rs +++ b/src/wire/ndiscoption.rs @@ -3,9 +3,16 @@ use byteorder::{ByteOrder, NetworkEndian}; use core::fmt; use crate::time::Duration; -use crate::wire::{EthernetAddress, Ipv6Address, Ipv6Packet, Ipv6Repr}; +use crate::wire::{Ipv6Address, Ipv6Packet, Ipv6Repr}; use crate::{Error, Result}; +#[cfg(feature = "medium-ethernet")] +use crate::wire::EthernetAddress; +#[cfg(feature = "medium-sixlowpan")] +use crate::wire::Ieee802154Address; + +use crate::wire::HardwareAddress; + enum_with_unknown! { /// NDISC Option Type pub enum Type(u8) { @@ -83,7 +90,10 @@ mod field { // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ // Link-Layer Address + #[cfg(feature = "medium-ethernet")] pub const LL_ADDR: Field = 2..8; + #[cfg(feature = "medium-sixlowpan")] + pub const LL_ADDR: Field = 2..10; // Prefix Information Option fields. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ @@ -214,9 +224,19 @@ impl> NdiscOption { impl> NdiscOption { /// Return the Source/Target Link-layer Address. #[inline] - pub fn link_layer_addr(&self) -> EthernetAddress { + pub fn link_layer_addr(&self) -> HardwareAddress { let data = self.buffer.as_ref(); - EthernetAddress::from_bytes(&data[field::LL_ADDR]) + let addr = &data[field::LL_ADDR]; + + #[cfg(feature = "medium-ethernet")] + { + HardwareAddress::Ethernet(EthernetAddress::from_bytes(addr)) + } + + #[cfg(feature = "medium-sixlowpan")] + { + HardwareAddress::Ieee802154(Ieee802154Address::from_bytes(addr)) + } } } @@ -297,9 +317,10 @@ impl + AsMut<[u8]>> NdiscOption { impl + AsMut<[u8]>> NdiscOption { /// Set the Source/Target Link-layer Address. #[inline] - pub fn set_link_layer_addr(&mut self, addr: EthernetAddress) { + pub fn set_link_layer_addr(&mut self, addr: HardwareAddress) { let data = self.buffer.as_mut(); - data[field::LL_ADDR].copy_from_slice(addr.as_bytes()) + let data = &mut data[field::LL_ADDR]; + data.copy_from_slice(&addr.as_bytes()); } } @@ -409,8 +430,8 @@ pub struct RedirectedHeader<'a> { #[derive(Debug, PartialEq, Eq, Clone, Copy)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Repr<'a> { - SourceLinkLayerAddr(EthernetAddress), - TargetLinkLayerAddr(EthernetAddress), + SourceLinkLayerAddr(HardwareAddress), + TargetLinkLayerAddr(HardwareAddress), PrefixInformation(PrefixInformation), RedirectedHeader(RedirectedHeader<'a>), Mtu(u32), @@ -506,12 +527,26 @@ impl<'a> Repr<'a> { match *self { Repr::SourceLinkLayerAddr(addr) => { opt.set_option_type(Type::SourceLinkLayerAddr); - opt.set_data_len(1); + #[cfg(feature = "medium-ethernet")] + { + opt.set_data_len(1); + } + #[cfg(feature = "medium-sixlowpan")] + { + opt.set_data_len(2); + } opt.set_link_layer_addr(addr); } Repr::TargetLinkLayerAddr(addr) => { opt.set_option_type(Type::TargetLinkLayerAddr); - opt.set_data_len(1); + #[cfg(feature = "medium-ethernet")] + { + opt.set_data_len(1); + } + #[cfg(feature = "medium-sixlowpan")] + { + opt.set_data_len(2); + } opt.set_link_layer_addr(addr); } Repr::PrefixInformation(PrefixInformation { @@ -668,14 +703,14 @@ mod test { { assert_eq!( Repr::parse(&NdiscOption::new_unchecked(&bytes)), - Ok(Repr::SourceLinkLayerAddr(addr)) + Ok(Repr::SourceLinkLayerAddr(addr.into())) ); } bytes[0] = 0x02; { assert_eq!( Repr::parse(&NdiscOption::new_unchecked(&bytes)), - Ok(Repr::TargetLinkLayerAddr(addr)) + Ok(Repr::TargetLinkLayerAddr(addr.into())) ); } } diff --git a/src/wire/sixlowpan.rs b/src/wire/sixlowpan.rs new file mode 100644 index 000000000..42fd088d7 --- /dev/null +++ b/src/wire/sixlowpan.rs @@ -0,0 +1,1726 @@ +use crate::wire::ieee802154::Address as LlAddress; +use crate::wire::ipv6; +use crate::wire::IpProtocol; + +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum NextHeader { + Compressed, + Uncompressed(IpProtocol), +} + +/// A wrapper around the address provided in the 6LoWPAN_IPHC header. +/// This requires some context to convert it the an IPv6 address in some cases. +/// For 802.15.4 the context are the short/extended addresses. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub enum Address<'a> { + Complete(ipv6::Address), + WithContext(&'a [u8]), + Elided, + Reserved, +} + +impl<'a> Address<'a> { + /// Resolve the address provided by the IPHC encoding. + pub(crate) fn resolve(self, ll_addr: Option) -> ipv6::Address { + match self { + Address::Complete(addr) => addr, + Address::Elided => { + let mut bytes = [0; 16]; + bytes[0] = 0xfe; + bytes[1] = 0x80; + + match ll_addr { + Some(LlAddress::Short(ll)) => { + bytes[11] = 0xff; + bytes[12] = 0xfe; + bytes[14..].copy_from_slice(&ll); + } + Some(LlAddress::Extended(ll)) => { + bytes[8..].copy_from_slice(&LlAddress::Extended(ll).as_eui_64().unwrap()); + } + _ => unreachable!(), + } + + ipv6::Address::from_bytes(&bytes) + } + Address::Reserved => { + unreachable!() + } + Address::WithContext(_ctx) => { + // XXX this is incorrect + let mut bytes = [0; 16]; + bytes[0] = 0xfe; + bytes[1] = 0x80; + + match ll_addr { + Some(LlAddress::Short(ll)) => { + bytes[11] = 0xff; + bytes[12] = 0xfe; + + bytes[14..].copy_from_slice(&ll); + } + Some(LlAddress::Extended(ll)) => { + bytes[8..].copy_from_slice(&LlAddress::Extended(ll).as_eui_64().unwrap()); + } + _ => unreachable!(), + } + + ipv6::Address::from_bytes(&bytes) + } + } + } +} + +pub mod iphc { + use crate::wire::ieee802154::Address as LlAddress; + use crate::wire::ipv6; + use crate::wire::IpProtocol; + use crate::Error; + use crate::Result; + use byteorder::{ByteOrder, NetworkEndian}; + + use super::Address; + use super::NextHeader; + + mod field { + #![allow(non_snake_case)] + + use crate::wire::field::*; + + pub const IPHC_FIELD: Field = 0..2; + } + + const DISPATCH: u8 = 0b011; + + macro_rules! get_field { + ($name:ident, $mask:expr, $shift:expr) => { + fn $name(&self) -> u8 { + let data = self.buffer.as_ref(); + let raw = NetworkEndian::read_u16(&data[field::IPHC_FIELD]); + ((raw >> $shift) & $mask) as u8 + } + }; + } + + macro_rules! set_field { + ($name:ident, $mask:expr, $shift:expr) => { + fn $name(&mut self, val: u8) { + let data = &mut self.buffer.as_mut()[field::IPHC_FIELD]; + let mut raw = NetworkEndian::read_u16(data); + + raw = (raw & !($mask << $shift)) | ((val as u16) << $shift); + NetworkEndian::write_u16(data, raw); + } + }; + } + + /// A read/write wrapper around a LOWPAN_IPHC frame buffer. + #[derive(Debug, Clone)] + pub struct Packet> { + buffer: T, + } + + impl> Packet { + /// Input a raw octet buffer with a 6LoWPAN_IPHC frame structure. + pub fn new_unchecked(buffer: T) -> Packet { + Packet { buffer } + } + + /// Shorthand for a combination of [new_unchecked] and [check_len]. + /// + /// [new_unchecked]: #method.new_unchecked + /// [check_len]: #method.check_len + pub fn new_checked(buffer: T) -> Result> { + let packet = Self::new_unchecked(buffer); + packet.check_len()?; + Ok(packet) + } + + /// Ensure that no accessor method will panic if called. + /// Returns `Err(Error::Truncated)` if the buffer is too short. + pub fn check_len(&self) -> Result<()> { + let buffer = self.buffer.as_ref(); + if buffer.len() < 2 { + Err(Error::Truncated) + } else { + Ok(()) + } + } + + /// Consumes the frame, returning the underlying buffer. + pub fn into_inner(self) -> T { + self.buffer + } + + /// Parse the next header field. + pub fn next_header(&self) -> NextHeader { + let nh = self.nh_field(); + + if nh == 1 { + // The next header field is compressed. + // It is also encoded using LOWPAN_NHC. + NextHeader::Compressed + } else { + // The full 8 bits for Next Header are carried in-line. + let start = (self.ip_fields_start() + self.traffic_class_size()) as usize; + + let data = self.buffer.as_ref(); + let nh = data[start..start + 1][0]; + NextHeader::Uncompressed(IpProtocol::from(nh)) + } + } + + /// Parse the hop limit field. + pub fn hop_limit(&self) -> u8 { + match self.hlim_field() { + 0b00 => { + let start = (self.ip_fields_start() + + self.traffic_class_size() + + self.next_header_size()) as usize; + + let data = self.buffer.as_ref(); + data[start..start + 1][0] + } + 0b01 => 1, + 0b10 => 64, + 0b11 => 255, + _ => unreachable!(), + } + } + + /// Return the source context identifier. + pub fn src_context_id(&self) -> Option { + if self.cid_field() == 1 { + let data = self.buffer.as_ref(); + Some(data[1] >> 4) + } else { + None + } + } + + /// Return the destination context identifier. + pub fn dst_context_id(&self) -> Option { + if self.cid_field() == 1 { + let data = self.buffer.as_ref(); + Some(data[1] & 0x0f) + } else { + None + } + } + + /// Parse the source address field. + pub fn src_addr(&self) -> Address { + let start = (self.ip_fields_start() + + self.traffic_class_size() + + self.next_header_size() + + self.hop_limit_size()) as usize; + + match (self.sac_field(), self.sam_field()) { + (0, 0b00) => { + // The full address is carried in-line. + let data = self.buffer.as_ref(); + Address::Complete(ipv6::Address::from_bytes(&data[start..start + 16])) + } + (0, 0b01) => { + // The first 64-bits of the address is elided. + // The value of those bits is the link-local prefix padded with zeros. + // The remaining 64-bits are carried in-line. + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + // Link-local prefix + bytes[0] = 0xfe; + bytes[1] = 0x80; + + bytes[8..].copy_from_slice(&data[start..start + 8]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (0, 0b10) => { + // The first 112 bits of the address are elided. + // The value of the 64 bits is the link-local prefix padded with zeros. + // The following 64 bits are 0000:00ff:fe00:XXXX, + // where XXXX are the bits carried in-line. + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + // Link-local prefix + bytes[0] = 0xfe; + bytes[1] = 0x80; + + bytes[11] = 0xff; + bytes[12] = 0xfe; + + bytes[14..].copy_from_slice(&data[start..start + 2]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (0, 0b11) => { + // The address is fully elided. + // The first 64 bits of the address are the link-local prefix padded with zeros. + // The remaining 64 bits are computed from the encapsulating header. + Address::Elided + } + (1, 0b00) => Address::Complete(ipv6::Address::UNSPECIFIED), + (1, 0b01) => { + // The address is derived using context information and the 64 bits carried in-line. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + let data = self.buffer.as_ref(); + let bytes = &data[start..start + 8]; + + Address::WithContext(bytes) + } + (1, 0b10) => { + // The address is derived using context information and the 16 bits carried in-line. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + //let data = self.buffer.as_ref(); + //let bytes = &data[start..start + 2]; + Address::Reserved + } + (1, 0b11) => { + // The address is fully elided and is derived using context information and the encapsulating header. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + Address::WithContext(&[]) + } + _ => unreachable!(), + } + } + + /// Parse the destination address field. + pub fn dst_addr(&self) -> Address { + let start = (self.ip_fields_start() + + self.traffic_class_size() + + self.next_header_size() + + self.hop_limit_size() + + self.src_address_size()) as usize; + + match (self.m_field(), self.dac_field(), self.dam_field()) { + (0, 0, 0b00) => { + // The full address is carried in-line. + let data = self.buffer.as_ref(); + Address::Complete(ipv6::Address::from_bytes(&data[start..start + 16])) + } + (0, 0, 0b01) => { + // The first 64-bits of the address is elided. + // The value of those bits is the link-local prefix padded with zeros. + // The remaining 64-bits are carried in-line. + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + // Link-local prefix + bytes[0] = 0xfe; + bytes[1] = 0x80; + + bytes[8..].copy_from_slice(&data[start..start + 8]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (0, 0, 0b10) => { + // The first 112 bits of the address are elided. + // The value of the 64 bits is the link-local prefix padded with zeros. + // The following 64 bits are 0000:00ff:fe00:XXXX, + // where XXXX are the bits carried in-line. + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + // Link-local prefix + bytes[0] = 0xfe; + bytes[1] = 0x80; + + bytes[11] = 0xff; + bytes[12] = 0xfe; + + bytes[14..].copy_from_slice(&data[start..start + 2]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (0, 0, 0b11) => { + // The address is fully elided. + // The first 64 bits of the address are the link-local prefix padded with zeros. + // The remaining 64 bits are computed from the encapsulating header. + Address::Elided + } + (0, 1, 0b00) => Address::Reserved, + (0, 1, 0b01) => { + // The address is derived using context information and the 64 bits carried in-line. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + let data = self.buffer.as_ref(); + let bytes = &data[start..start + 8]; + + Address::WithContext(bytes) + } + (0, 1, 0b10) => { + // The address is derived using context information and the 16 bits carried in-line. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + let data = self.buffer.as_ref(); + let bytes = &data[start..start + 2]; + Address::Reserved + } + (0, 1, 0b11) => { + // The address is fully elided and is derived using context information and the encapsulating header. + // Bits covered by context information are always used. + // Any IID bits not covered by context information are always used. + // Any IID bits not covered by context information are directly from the corresponding bits carried in-line. + // Any remaining bits are zero. + Address::WithContext(&[]) + } + (1, 0, 0b00) => { + // The full address is carried in-line. + let data = self.buffer.as_ref(); + Address::Complete(ipv6::Address::from_bytes(&data[start..start + 16])) + } + (1, 0, 0b01) => { + // The address takes the form ffXX::00XX:XXXX:XXXX + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + bytes[0] = 0xff; + bytes[1] = data[start]; + + bytes[11..].copy_from_slice(&data[start + 1..start + 6]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (1, 0, 0b10) => { + // The address takes the form ffXX::00XX:XXXX + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + bytes[0] = 0xff; + bytes[1] = data[start]; + + bytes[13..].copy_from_slice(&data[start + 1..start + 4]); + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (1, 0, 0b11) => { + // The address takes the form ff02::00XX + let data = self.buffer.as_ref(); + let mut bytes = [0u8; 16]; + + bytes[0] = 0xff; + bytes[1] = 0x02; + + bytes[15] = data[start]; + + Address::Complete(ipv6::Address::from_bytes(&bytes)) + } + (1, 1, 0b00) => { + // This format is designed to match Unicast-Prefix-based IPv6 Multicast Addresses. + // The multicast takes the form ffXX:XXLL:PPPP:PPPP:PPPP:PPPP:XXXX:XXXX. + // X are octets that are carried in-line, in the order in which they appear. + // P are octets used to encode the prefix itself. + // L are octets used to encode the prefix length. + // The prefix information P and L is taken from the specified context. + todo!() + } + (1, 1, 0b01) => Address::Reserved, + (1, 1, 0b10) => Address::Reserved, + (1, 1, 0b11) => Address::Reserved, + _ => unreachable!(), + } + } + + get_field!(dispatch_field, 0b111, 13); + get_field!(tf_field, 0b11, 11); + get_field!(nh_field, 0b1, 10); + get_field!(hlim_field, 0b11, 8); + get_field!(cid_field, 0b1, 7); + get_field!(sac_field, 0b1, 6); + get_field!(sam_field, 0b11, 4); + get_field!(m_field, 0b1, 3); + get_field!(dac_field, 0b1, 2); + get_field!(dam_field, 0b11, 0); + + /// Return the start for the IP fields. + fn ip_fields_start(&self) -> u8 { + 2 + self.cid_size() + } + + /// Get the size in octets of the traffic class field. + fn traffic_class_size(&self) -> u8 { + match self.tf_field() { + 0b00 => 4, + 0b01 => 3, + 0b10 => 1, + 0b11 => 0, + _ => unreachable!(), + } + } + + /// Get the size in octets of the next header field. + fn next_header_size(&self) -> u8 { + !(self.nh_field() == 1) as u8 + } + + /// Get the size in octets of the hop limit field. + fn hop_limit_size(&self) -> u8 { + (self.hlim_field() == 0b00) as u8 + } + + /// Get the size in octets of the CID field. + fn cid_size(&self) -> u8 { + (self.cid_field() == 1) as u8 + } + + /// Get the size in octets of the source address. + fn src_address_size(&self) -> u8 { + match (self.sac_field(), self.sam_field()) { + (0, 0b00) => 16, // The full address is carried in-line. + (0, 0b01) => 8, // The first 64 bits are elided. + (0, 0b10) => 2, // The first 112 bits are elided. + (0, 0b11) => 0, // The address is fully elided. + (1, 0b00) => 0, // The UNSPECIFIED address. + (1, 0b01) => 8, // Address derived using context information. + (1, 0b10) => 2, // Address derived using context information. + (1, 0b11) => 0, // Address derived using context information. + _ => unreachable!(), + } + } + + /// Get the size in octets of the address address. + fn dst_address_size(&self) -> u8 { + match (self.m_field(), self.dac_field(), self.dam_field()) { + (0, 0, 0b00) => 16, // The full address is carried in-line. + (0, 0, 0b01) => 8, // The first 64 bits are elided. + (0, 0, 0b10) => 2, // The first 112 bits are elided. + (0, 0, 0b11) => 0, // The address is fully elided. + (0, 1, 0b00) => 0, // Reserved. + (0, 1, 0b01) => 8, // Address derived using context information. + (0, 1, 0b10) => 2, // Address derived using context information. + (0, 1, 0b11) => 0, // Address derived using context information. + (1, 0, 0b00) => 16, // The full address is carried in-line. + (1, 0, 0b01) => 6, // The address takes the form ffXX::00XX:XXXX:XXXX. + (1, 0, 0b10) => 4, // The address takes the form ffXX::00XX:XXXX. + (1, 0, 0b11) => 1, // The address takes the form ff02::00XX. + (1, 1, 0b00) => 6, // Match Unicast-Prefix-based IPv6. + (1, 1, 0b01) => 0, // Reserved. + (1, 1, 0b10) => 0, // Reserved. + (1, 1, 0b11) => 0, // Reserved. + _ => unreachable!(), + } + } + } + + impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> { + /// Return a pointer to the payload. + pub fn payload(&self) -> &'a [u8] { + let mut len = self.ip_fields_start(); + len += self.traffic_class_size(); + len += self.next_header_size(); + len += self.hop_limit_size(); + len += self.src_address_size(); + len += self.dst_address_size(); + + let len = len as usize; + + let data = self.buffer.as_ref(); + &data[len..] + } + } + + impl<'a, T: AsRef<[u8]> + AsMut<[u8]>> Packet { + /// Set the dispatch field to `0b011`. + fn set_dispatch_field(&mut self) { + let data = &mut self.buffer.as_mut()[field::IPHC_FIELD]; + let mut raw = NetworkEndian::read_u16(data); + + raw = (raw & !(0b111 << 13)) | (0b11 << 13); + NetworkEndian::write_u16(data, raw); + } + + set_field!(set_tf_field, 0b11, 11); + set_field!(set_nh_field, 0b1, 10); + set_field!(set_hlim_field, 0b11, 8); + set_field!(set_cid_field, 0b1, 7); + set_field!(set_sac_field, 0b1, 6); + set_field!(set_sam_field, 0b11, 4); + set_field!(set_m_field, 0b1, 3); + set_field!(set_dac_field, 0b1, 2); + set_field!(set_dam_field, 0b11, 0); + + fn set_field(&mut self, idx: usize, value: &[u8]) { + let raw = self.buffer.as_mut(); + raw[idx..idx + value.len()].copy_from_slice(value); + } + + /// Return a mutable pointer to the payload. + pub fn payload_mut(&mut self) -> &mut [u8] { + let mut len = self.ip_fields_start(); + + len += self.traffic_class_size(); + len += self.next_header_size(); + len += self.hop_limit_size(); + len += self.src_address_size(); + len += self.dst_address_size(); + + let len = len as usize; + + let data = self.buffer.as_mut(); + &mut data[len..] + } + + fn set_next_header(&mut self, nh: NextHeader, mut idx: usize) -> usize { + match nh { + NextHeader::Uncompressed(nh) => { + self.set_nh_field(0); + self.set_field(idx, &[nh.into()]); + idx += 1; + } + NextHeader::Compressed => self.set_nh_field(1), + } + + idx + } + + fn set_hop_limit(&mut self, hl: u8, mut idx: usize) -> usize { + match hl { + 255 => self.set_hlim_field(0b11), + 64 => self.set_hlim_field(0b10), + 1 => self.set_hlim_field(0b01), + _ => { + self.set_hlim_field(0b00); + self.set_field(idx, &[hl]); + idx += 1; + } + } + + idx + } + + /// Set the source address based on the IPv6 address and the Link-Local address. + fn set_src_address( + &mut self, + src_addr: ipv6::Address, + ll_src_addr: Option, + mut idx: usize, + ) -> usize { + let src = src_addr.as_bytes(); + if src_addr == ipv6::Address::UNSPECIFIED { + self.set_sac_field(1); + self.set_sam_field(0b00); + } else if src_addr.is_link_local() { + // We have a link local address. + // The remainder of the address can be elided when the context contains + // a 802.15.4 short address or a 802.15.4 extended address which can be + // converted to a eui64 address. + + if src[8..14] == [0, 0, 0, 0xff, 0xfe, 0] { + let ll = [src[14], src[15]]; + + if ll_src_addr == Some(LlAddress::Short(ll)) { + // We have the context from the 802.15.4 frame. + // The context contains the short address. + // We can elide the source address. + self.set_sam_field(0b11); + } else { + // We don't have the context from the 802.15.4 frame. + // We cannot elide the source address, however we can elide 112 bits. + self.set_sam_field(0b10); + + self.set_field(idx, &src[14..]); + idx += 2; + } + } else { + if ll_src_addr + .map(|addr| { + addr.as_eui_64() + .map(|addr| addr[..] == src[8..]) + .unwrap_or(false) + }) + .unwrap_or(false) + { + // We have the context from the 802.15.4 frame. + // The context contains the extended address. + // We can elide the source address. + self.set_sam_field(0b11); + } else { + // We cannot elide the source address, however we can elide 64 bits. + self.set_sam_field(0b01); + + self.set_field(idx, &src[8..]); + idx += 8; + } + } + } else { + // We cannot elide anything. + self.set_field(idx, src); + idx += 16; + } + + idx + } + + fn set_dst_address( + &mut self, + dst_addr: ipv6::Address, + ll_dst_addr: Option, + mut idx: usize, + ) -> usize { + let dst = dst_addr.as_bytes(); + if dst_addr.is_multicast() { + self.set_m_field(1); + + if dst[1] == 0x02 && dst[2..15] == [0; 13] { + self.set_dam_field(0b11); + + self.set_field(idx, &[dst[15]]); + idx += 1; + } else if dst[2..13] == [0; 11] { + self.set_dam_field(0b10); + + self.set_field(idx, &[dst[1]]); + idx += 1; + self.set_field(idx, &dst[13..]); + idx += 3; + } else if dst[2..11] == [0; 9] { + self.set_dam_field(0b01); + + self.set_field(idx, &[dst[1]]); + idx += 1; + self.set_field(idx, &dst[11..]); + idx += 5; + } else { + self.set_dam_field(0b11); + + self.set_field(idx, &dst); + idx += 16; + } + } else { + if dst_addr.is_link_local() { + if dst[8..14] == [0, 0, 0, 0xff, 0xfe, 0] { + let ll = [dst[14], dst[15]]; + + if ll_dst_addr == Some(LlAddress::Short(ll)) { + self.set_dam_field(0b11); + } else { + self.set_dam_field(0b10); + + self.set_field(idx, &dst[14..]); + idx += 2; + } + } else { + if ll_dst_addr + .map(|addr| { + addr.as_eui_64() + .map(|addr| addr[..] == dst[8..]) + .unwrap_or(false) + }) + .unwrap_or(false) + { + self.set_dam_field(0b11); + } else { + self.set_dam_field(0b01); + + self.set_field(idx, &dst[8..]); + idx += 8; + } + } + } else { + self.set_dam_field(0b00); + + self.set_field(idx, dst); + idx += 16; + } + } + + idx + } + } + + /// A high-level representation of a LOWPAN_IPHC header. + #[derive(Debug, PartialEq, Eq, Clone, Copy)] + pub struct Repr { + pub src_addr: ipv6::Address, + pub ll_src_addr: Option, + pub dst_addr: ipv6::Address, + pub ll_dst_addr: Option, + pub next_header: NextHeader, + pub hop_limit: u8, + } + + impl Repr { + /// Parse a LOWPAN_IPHC packet and return a high-level representation. + pub fn parse + ?Sized>( + packet: &Packet<&T>, + ll_src_addr: Option, + ll_dst_addr: Option, + ) -> Result { + // Ensure basic accessors will work. + packet.check_len()?; + + if packet.dispatch_field() != DISPATCH { + // This is not an LOWPAN_IPHC packet. + return Err(Error::Malformed); + } + + let src_addr = packet.src_addr().resolve(ll_src_addr); + let dst_addr = packet.dst_addr().resolve(ll_dst_addr); + + Ok(Repr { + src_addr, + ll_src_addr, + dst_addr, + ll_dst_addr, + next_header: packet.next_header(), + hop_limit: packet.hop_limit(), + }) + } + + /// Return the length of a header that will be emitted from this high-level representation. + pub fn buffer_len(&self) -> usize { + let mut len = 0; + len += 2; // The minimal header length + + len += if self.next_header == NextHeader::Compressed { + 0 // The next header is compressed (we don't need to inline what the next header is) + } else { + 1 // The next header field is inlined + }; + + // Add the lenght of the source address + len += if self.src_addr == ipv6::Address::UNSPECIFIED { + 0 + } else if self.src_addr.is_link_local() { + let src = self.src_addr.as_bytes(); + let ll = [src[14], src[15]]; + + if src[8..14] == [0, 0, 0, 0xff, 0xfe, 0] { + if self.ll_src_addr == Some(LlAddress::Short(ll)) { + 0 + } else { + 2 + } + } else { + if self + .ll_src_addr + .map(|addr| { + addr.as_eui_64() + .map(|addr| addr[..] == src[8..]) + .unwrap_or(false) + }) + .unwrap_or(false) + { + 0 + } else { + 8 + } + } + } else { + 16 + }; + + // Add the size of the destination header + len += if self.dst_addr.is_multicast() { + let dst = self.dst_addr.as_bytes(); + if dst[1] == 0x02 && dst[2..15] == [0; 13] { + 1 + } else if dst[2..13] == [0; 11] { + 4 + } else if dst[2..11] == [0; 9] { + 6 + } else { + 16 + } + } else { + let dst = self.dst_addr.as_bytes(); + if self.dst_addr.is_link_local() { + if dst[8..14] == [0, 0, 0, 0xff, 0xfe, 0] { + let ll = [dst[14], dst[15]]; + + if self.ll_dst_addr == Some(LlAddress::Short(ll)) { + 0 + } else { + 2 + } + } else { + if self + .ll_dst_addr + .map(|addr| { + addr.as_eui_64() + .map(|addr| addr[..] == dst[8..]) + .unwrap_or(false) + }) + .unwrap_or(false) + { + 0 + } else { + 8 + } + } + } else { + 16 + } + }; + + // Add the size of the traffic flow. + // TODO: implement traffic flow for sixlowpan + len += 0; + + len + } + + /// Emit a high-level representation into a LOWPAN_IPHC packet. + pub fn emit + AsMut<[u8]>>(&self, packet: &mut Packet) { + let idx = 2; + + packet.set_dispatch_field(); + + // SETTING THE TRAFIX FLOW + // TODO: needs more work. + packet.set_tf_field(0b11); + + let idx = packet.set_next_header(self.next_header, idx); + let idx = packet.set_hop_limit(self.hop_limit, idx); + let idx = packet.set_src_address(self.src_addr, self.ll_src_addr, idx); + packet.set_dst_address(self.dst_addr, self.ll_dst_addr, idx); + } + } + + #[cfg(test)] + mod test { + use super::*; + + #[test] + fn iphc_fields() { + let bytes = [ + 0x7a, 0x33, // IPHC + 0x3a, // Next header + ]; + + let packet = Packet::new_unchecked(bytes); + + assert_eq!(packet.dispatch_field(), 0b011); + assert_eq!(packet.tf_field(), 0b11); + assert_eq!(packet.nh_field(), 0b0); + assert_eq!(packet.hlim_field(), 0b10); + assert_eq!(packet.cid_field(), 0b0); + assert_eq!(packet.sac_field(), 0b0); + assert_eq!(packet.sam_field(), 0b11); + assert_eq!(packet.m_field(), 0b0); + assert_eq!(packet.dac_field(), 0b0); + assert_eq!(packet.dam_field(), 0b11); + + assert_eq!( + packet.next_header(), + NextHeader::Uncompressed(IpProtocol::Icmpv6) + ); + + assert_eq!(packet.src_address_size(), 0); + assert_eq!(packet.dst_address_size(), 0); + assert_eq!(packet.hop_limit(), 64); + + assert_eq!(packet.src_addr(), Address::Elided); + assert_eq!(packet.dst_addr(), Address::Elided); + + let bytes = [ + 0x7e, 0xf7, // IPHC, + 0x00, // CID + ]; + + let packet = Packet::new_unchecked(bytes); + + assert_eq!(packet.dispatch_field(), 0b011); + assert_eq!(packet.tf_field(), 0b11); + assert_eq!(packet.nh_field(), 0b1); + assert_eq!(packet.hlim_field(), 0b10); + assert_eq!(packet.cid_field(), 0b1); + assert_eq!(packet.sac_field(), 0b1); + assert_eq!(packet.sam_field(), 0b11); + assert_eq!(packet.m_field(), 0b0); + assert_eq!(packet.dac_field(), 0b1); + assert_eq!(packet.dam_field(), 0b11); + + assert_eq!(packet.next_header(), NextHeader::Compressed); + + assert_eq!(packet.src_address_size(), 0); + assert_eq!(packet.dst_address_size(), 0); + assert_eq!(packet.hop_limit(), 64); + + assert_eq!(packet.src_addr(), Address::WithContext(&[])); + assert_eq!(packet.dst_addr(), Address::WithContext(&[])); + } + } +} + +pub mod nhc { + use crate::wire::ip::checksum; + use crate::wire::ip::Address as IpAddress; + use crate::wire::ipv6; + use crate::wire::udp::Repr as UdpRepr; + use crate::wire::IpProtocol; + use crate::Error; + use crate::Result; + use byteorder::{ByteOrder, NetworkEndian}; + use ipv6::Address; + + use super::NextHeader; + + mod field { + #![allow(non_snake_case)] + + pub const NHC_FIELD: usize = 0; + pub const UDP_FIELD: usize = 0; + } + + macro_rules! get_field { + ($name:ident, $mask:expr, $shift:expr) => { + fn $name(&self) -> u8 { + let data = self.buffer.as_ref(); + let raw = &data[0]; + ((raw >> $shift) & $mask) as u8 + } + }; + } + + macro_rules! set_field { + ($name:ident, $mask:expr, $shift:expr) => { + fn $name(&mut self, val: u8) { + let data = self.buffer.as_mut(); + let mut raw = data[0]; + raw = (raw & !($mask << $shift)) | (val << $shift); + data[0] = raw; + } + }; + } + + /// A read/write wrapper around a LOWPAN_NHC frame buffer. + #[derive(Debug, Clone)] + pub enum Packet> { + ExtensionHeader(ExtensionHeaderPacket), + UdpHeader(UdpPacket), + } + + impl> Packet { + pub fn dispatch(buffer: T) -> Result> { + let raw = buffer.as_ref(); + + #[cfg(feature = "std")] + println!("{:02x?}", raw[0]); + + if raw[0] >> 4 == 0b1110 { + // We have a compressed IPv6 Extension Header. + Ok(Packet::ExtensionHeader(ExtensionHeaderPacket::new_checked( + buffer, + )?)) + } else if raw[0] >> 3 == 0b11110 { + // We have a compressed UDP header. + Ok(Packet::UdpHeader(UdpPacket::new_checked(buffer)?)) + } else { + Err(Error::Unrecognized) + } + } + } + + // /// A high-level representation of a 6LoWPAN_NHC. + // #[derive(Debug, PartialEq, Eq, Clone, Copy)] + // pub enum NhcRepr<'a> { + // UdpNhc(UdpNhcRepr<'a>), + // } + + // impl<'a> NhcRepr<'a> { + // /// Parse a 6LoWPAN_NHC packet and return a high-level representation. + // pub fn parse + ?Sized>(packet: &Packet<&'a T>) -> Result> { + // todo!(); + // } + // } + + #[derive(Debug, PartialEq, Eq, Clone, Copy)] + pub enum ExtensionHeaderId { + HopByHopHeader, + RoutingHeader, + FragmentHeader, + DestinationOptionsHeader, + MobilityHeader, + Header, + Reserved, + } + + impl Into for ExtensionHeaderId { + fn into(self) -> IpProtocol { + match self { + ExtensionHeaderId::HopByHopHeader => IpProtocol::HopByHop, + ExtensionHeaderId::RoutingHeader => IpProtocol::Ipv6Route, + ExtensionHeaderId::FragmentHeader => IpProtocol::Ipv6Frag, + ExtensionHeaderId::DestinationOptionsHeader => IpProtocol::Ipv6Opts, + ExtensionHeaderId::MobilityHeader => IpProtocol::Unknown(0), + ExtensionHeaderId::Header => IpProtocol::Unknown(0), + ExtensionHeaderId::Reserved => IpProtocol::Unknown(0), + } + } + } + + pub(crate) const EXT_HEADER_DISPATCH: u8 = 0b1110; + + /// A read/write wrapper around a LOWPAN_NHC Next Header frame buffer. + #[derive(Debug, Clone)] + pub struct ExtensionHeaderPacket> { + buffer: T, + } + + impl> ExtensionHeaderPacket { + /// Input a raw octet buffer with a LOWPAN_NHC Extension Header frame structure. + pub fn new_unchecked(buffer: T) -> ExtensionHeaderPacket { + ExtensionHeaderPacket { buffer } + } + + /// Shorthand for a combination of [new_unchecked] and [check_len]. + /// + /// [new_unchecked]: #method.new_unchecked + /// [check_len]: #method.check_len + pub fn new_checked(buffer: T) -> Result> { + let packet = Self::new_unchecked(buffer); + packet.check_len()?; + Ok(packet) + } + + /// Ensure that no accessor method will panic if called. + /// Returns `Err(Error::Truncated)` if the buffer is too short. + pub fn check_len(&self) -> Result<()> { + let buffer = self.buffer.as_ref(); + if buffer.is_empty() { + Err(Error::Truncated) + } else { + Ok(()) + } + } + + /// Consumes the frame, returning the underlying buffer. + pub fn into_inner(self) -> T { + self.buffer + } + + get_field!(dispatch_field, 0b1111, 4); + get_field!(eid_field, 0b111, 1); + get_field!(nh_field, 0b1, 0); + + /// Return the Extension Header ID. + pub fn extension_header_id(&self) -> ExtensionHeaderId { + match self.eid_field() { + 0 => ExtensionHeaderId::HopByHopHeader, + 1 => ExtensionHeaderId::RoutingHeader, + 2 => ExtensionHeaderId::FragmentHeader, + 3 => ExtensionHeaderId::DestinationOptionsHeader, + 4 => ExtensionHeaderId::MobilityHeader, + 5 | 6 => ExtensionHeaderId::Reserved, + 7 => ExtensionHeaderId::Header, + _ => unreachable!(), + } + } + + /// Return the length field. + pub fn length_field(&self) -> u8 { + let start = 1 + self.next_header_size(); + + let data = self.buffer.as_ref(); + data[start] + } + + /// Parse the next header field. + pub fn next_header(&self) -> NextHeader { + if self.nh_field() == 1 { + NextHeader::Compressed + } else { + // The full 8 bits for Next Header are carried in-line. + let start = 1; + + let data = self.buffer.as_ref(); + let nh = data[start]; + NextHeader::Uncompressed(IpProtocol::from(nh)) + } + } + + /// Return the size of the Next Header field. + fn next_header_size(&self) -> usize { + // If nh is set, then the Next Header is compressed using LOWPAN_NHC + if self.nh_field() == 1 { + 0 + } else { + 1 + } + } + } + + impl<'a, T: AsRef<[u8]> + ?Sized> ExtensionHeaderPacket<&'a T> { + /// Return a pointer to the payload. + pub fn payload(&self) -> &'a [u8] { + let start = 2 + self.next_header_size(); + &self.buffer.as_ref()[start..] + } + } + + impl<'a, T: AsRef<[u8]> + AsMut<[u8]>> ExtensionHeaderPacket { + /// Return a mutable pointer to the payload. + pub fn payload_mut(&mut self) -> &mut [u8] { + let start = 2 + self.next_header_size(); + &mut self.buffer.as_mut()[start..] + } + + /// Set the dispatch field to `0b1110`. + fn set_dispatch_field(&mut self) { + let data = self.buffer.as_mut(); + data[0] = (data[0] & !(0b1111 << 4)) | (EXT_HEADER_DISPATCH << 4); + } + + set_field!(set_eid_field, 0b111, 1); + set_field!(set_nh_field, 0b1, 0); + + /// Set the Extension Header ID field. + fn set_extension_header_id(&mut self, ext_header_id: ExtensionHeaderId) { + let id = match ext_header_id { + ExtensionHeaderId::HopByHopHeader => 0, + ExtensionHeaderId::RoutingHeader => 1, + ExtensionHeaderId::FragmentHeader => 2, + ExtensionHeaderId::DestinationOptionsHeader => 3, + ExtensionHeaderId::MobilityHeader => 4, + ExtensionHeaderId::Header => 7, + _ => unreachable!(), + }; + + self.set_eid_field(id); + } + + /// Set the Next Header. + fn set_next_header(&mut self, next_header: NextHeader) { + match next_header { + NextHeader::Compressed => self.set_nh_field(0b1), + NextHeader::Uncompressed(nh) => { + self.set_nh_field(0b0); + + let start = 1; + let data = self.buffer.as_mut(); + data[start] = nh.into(); + } + } + } + + /// Set the length. + fn set_length(&mut self, length: u8) { + let start = 1 + self.next_header_size(); + + let data = self.buffer.as_mut(); + data[start] = length; + } + } + + /// A high-level representation of an LOWPAN_NHC Extension Header header. + #[derive(Debug, PartialEq, Eq, Clone, Copy)] + pub struct ExtensionHeaderRepr { + ext_header_id: ExtensionHeaderId, + next_header: NextHeader, + length: u8, + } + + impl ExtensionHeaderRepr { + /// Parse a LOWPAN_NHC Extension Header packet and return a high-level representation. + pub fn parse + ?Sized>( + packet: &ExtensionHeaderPacket<&T>, + ) -> Result { + // Ensure basic accessors will work. + packet.check_len()?; + + if packet.dispatch_field() != EXT_HEADER_DISPATCH { + return Err(Error::Malformed); + } + + Ok(ExtensionHeaderRepr { + ext_header_id: packet.extension_header_id(), + next_header: packet.next_header(), + length: packet.payload().len() as u8, + }) + } + + /// Return the length of a header that will be emitted from this high-level representation. + pub fn buffer_len(&self) -> usize { + let mut len = 1; // The minimal header size + + if self.next_header != NextHeader::Compressed { + len += 1; + } + + len += 1; // The length + + len + } + + /// Emit a high-level representaiton into a LOWPAN_NHC Extension Header packet. + pub fn emit + AsMut<[u8]>>(&self, packet: &mut ExtensionHeaderPacket) { + packet.set_dispatch_field(); + packet.set_extension_header_id(self.ext_header_id); + packet.set_next_header(self.next_header); + packet.set_length(self.length); + } + } + + pub(crate) const UDP_DISPATCH: u8 = 0b11110; + + /// A read/write wrapper around a 6LoWPAN_NHC_UDP frame buffer. + #[derive(Debug, Clone)] + pub struct UdpPacket> { + buffer: T, + } + + impl> UdpPacket { + /// Input a raw octet buffer with a LOWPAN_NHC frame structure for UDP. + pub fn new_unchecked(buffer: T) -> UdpPacket { + UdpPacket { buffer } + } + + /// Shorthand for a combination of [new_unchecked] and [check_len]. + /// + /// [new_unchecked]: #method.new_unchecked + /// [check_len]: #method.check_len + pub fn new_checked(buffer: T) -> Result> { + let packet = Self::new_unchecked(buffer); + packet.check_len()?; + Ok(packet) + } + + /// Ensure that no accessor method will panic if called. + /// Returns `Err(Error::Truncated)` if the buffer is too short. + pub fn check_len(&self) -> Result<()> { + let buffer = self.buffer.as_ref(); + if buffer.is_empty() { + Err(Error::Truncated) + } else { + Ok(()) + } + } + + /// Consumes the frame, returning the underlying buffer. + pub fn into_inner(self) -> T { + self.buffer + } + + get_field!(dispatch_field, 0b11111, 3); + get_field!(checksum_field, 0b1, 2); + get_field!(ports_field, 0b11, 0); + + /// Returns the index of the start of the next header compressed fields. + fn nhc_fields_start(&self) -> usize { + 1 + } + + /// Return the source port number. + pub fn src_port(&self) -> u16 { + match self.ports_field() { + 0b00 | 0b01 => { + // The full 16 bits are carried in-line. + let data = self.buffer.as_ref(); + let start = self.nhc_fields_start(); + + NetworkEndian::read_u16(&data[start..start + 2]) + } + 0b10 => { + // The first 8 bits are elided. + let data = self.buffer.as_ref(); + let start = self.nhc_fields_start(); + + 0xf000 + data[start] as u16 + } + 0b11 => { + // The first 12 bits are elided. + let data = self.buffer.as_ref(); + let start = self.nhc_fields_start(); + + 0xf0b0 + (data[start] >> 4) as u16 + } + _ => unreachable!(), + } + } + + /// Return the destination port number. + pub fn dst_port(&self) -> u16 { + match self.ports_field() { + 0b00 => { + // The full 16 bits are carried in-line. + let data = self.buffer.as_ref(); + let idx = self.nhc_fields_start(); + + NetworkEndian::read_u16(&data[idx + 2..idx + 4]) + } + 0b01 => { + // The first 8 bits are elided. + let data = self.buffer.as_ref(); + let idx = self.nhc_fields_start(); + + 0xf000 + data[idx] as u16 + } + 0b10 => { + // The full 16 bits are carried in-line. + let data = self.buffer.as_ref(); + let idx = self.nhc_fields_start(); + + NetworkEndian::read_u16(&data[idx + 1..idx + 1 + 2]) + } + 0b11 => { + // The first 12 bits are elided. + let data = self.buffer.as_ref(); + let start = self.nhc_fields_start(); + + 0xf0b0 + (NetworkEndian::read_u16(&data[start..start + 1]) & 0xff) + } + _ => unreachable!(), + } + } + + /// Return the checksum. + pub fn checksum(&self) -> Option { + if self.checksum_field() == 0b0 { + // The first 12 bits are elided. + let data = self.buffer.as_ref(); + let start = self.nhc_fields_start() + self.ports_size(); + Some(NetworkEndian::read_u16(&data[start..start + 2])) + } else { + // The checksum is ellided and needs to be recomputed on the 6LoWPAN termination point. + None + } + } + + // Return the size of the checksum field. + fn checksum_size(&self) -> usize { + match self.checksum_field() { + 0b0 => 2, + 0b1 => 0, + _ => unreachable!(), + } + } + + /// Returns the total size of both port numbers. + fn ports_size(&self) -> usize { + match self.ports_field() { + 0b00 => 4, // 16 bits + 16 bits + 0b01 => 3, // 16 bits + 8 bits + 0b10 => 3, // 8 bits + 16 bits + 0b11 => 1, // 4 bits + 4 bits + _ => unreachable!(), + } + } + } + + impl<'a, T: AsRef<[u8]> + ?Sized> UdpPacket<&'a T> { + /// Return a pointer to the payload. + pub fn payload(&self) -> &'a [u8] { + let start = 1 + self.ports_size() + self.checksum_size(); + &self.buffer.as_ref()[start..] + } + } + + impl<'a, T: AsRef<[u8]> + AsMut<[u8]>> UdpPacket { + /// Return a mutable pointer to the payload. + pub fn payload_mut(&mut self) -> &mut [u8] { + let start = 1 + self.ports_size() + self.checksum_size(); + &mut self.buffer.as_mut()[start..] + } + + /// Set the dispatch field to `0b11110`. + fn set_dispatch_field(&mut self) { + let data = self.buffer.as_mut(); + data[0] = (data[0] & !(0b11111 << 3)) | (UDP_DISPATCH << 3); + } + + set_field!(set_checksum_field, 0b1, 2); + set_field!(set_ports_field, 0b11, 0); + + fn set_ports(&mut self, src_port: u16, dst_port: u16) { + let mut idx = 1; + + match (src_port, dst_port) { + (0xf0b0..=0xf0bf, 0xf0b0..=0xf0bf) => { + // We can compress both the source and destination ports. + self.set_ports_field(0b11); + let data = self.buffer.as_mut(); + data[idx] = (((src_port - 0xf0b0) as u8) << 4) & ((dst_port - 0xf0b0) as u8); + } + (0xf000..=0xf0ff, _) => { + // We can compress the source port, but not the destination port. + self.set_ports_field(0b10); + let data = self.buffer.as_mut(); + data[idx] = (src_port - 0xf000) as u8; + idx += 1; + + NetworkEndian::write_u16(&mut data[idx..idx + 2], dst_port); + } + (_, 0xf000..=0xf0ff) => { + // We can compress the destination port, but not the source port. + self.set_ports_field(0b01); + let data = self.buffer.as_mut(); + NetworkEndian::write_u16(&mut data[idx..idx + 2], src_port); + idx += 2; + data[idx] = (dst_port - 0xf000) as u8; + } + (_, _) => { + // We cannot compress any port. + self.set_ports_field(0b00); + let data = self.buffer.as_mut(); + NetworkEndian::write_u16(&mut data[idx..idx + 2], src_port); + idx += 2; + NetworkEndian::write_u16(&mut data[idx..idx + 2], dst_port); + } + }; + } + + fn set_checksum(&mut self, checksum: u16) { + self.set_checksum_field(0b0); + let idx = 1 + self.ports_size(); + let data = self.buffer.as_mut(); + NetworkEndian::write_u16(&mut data[idx..idx + 2], checksum); + } + } + + /// A high-level representation of a LOWPAN_NHC UDP header. + #[derive(Debug, PartialEq, Eq, Clone, Copy)] + pub struct UdpNhcRepr<'a>(pub UdpRepr<'a>); + + impl<'a> UdpNhcRepr<'a> { + /// Parse a LOWWPAN_NHC UDP packet and return a high-level representation. + pub fn parse + ?Sized>( + packet: &UdpPacket<&'a T>, + _src_addr: &ipv6::Address, + _dst_addr: &ipv6::Address, + _checksum: Option, + ) -> Result> { + // Ensure basic accessors will work. + packet.check_len()?; + + if packet.dispatch_field() != UDP_DISPATCH { + return Err(Error::Malformed); + } + + // TODO: Compute the checksum. + Ok(UdpNhcRepr(UdpRepr { + src_port: packet.src_port(), + dst_port: packet.dst_port(), + payload: packet.payload(), + })) + } + + /// Return the length of a packet that will be emitted from this high-level representation. + pub fn buffer_len(&self) -> usize { + let mut len = 1; // The minimal header size + + len += 2; // XXX We assume we will add the checksum at the end + + // Check if we can compress the source and destination ports + let len = match (self.src_port, self.dst_port) { + (0xf0b0..=0xf0bf, 0xf0b0..=0xf0bf) => len + 1, + (0xf000..=0xf0ff, _) | (_, 0xf000..=0xf0ff) => len + 3, + (_, _) => len + 4, + }; + + len + self.payload.len() + } + + /// Emit a high-level representation into a LOWPAN_NHC UDP header. + pub fn emit + AsMut<[u8]>>( + &self, + packet: &mut UdpPacket, + src_addr: &Address, + dst_addr: &Address, + ) { + packet.set_dispatch_field(); + packet.set_ports(self.src_port, self.dst_port); + + let chk_sum = checksum::combine(&[ + checksum::pseudo_header( + &IpAddress::Ipv6(*src_addr), + &IpAddress::Ipv6(*dst_addr), + crate::wire::ip::Protocol::Udp, + self.payload.len() as u32 + 8, + ), + self.dst_port, + self.src_port, + self.payload.len() as u16 + 8, + checksum::data(self.payload), + ]) ^ 0xffff; + + packet.set_checksum(chk_sum); + packet.payload_mut()[..self.payload.len()].copy_from_slice(self.payload); + } + } + + impl<'a> core::ops::Deref for UdpNhcRepr<'a> { + type Target = UdpRepr<'a>; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl<'a> core::ops::DerefMut for UdpNhcRepr<'a> { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } + } + + #[cfg(test)] + mod test { + use super::*; + + #[test] + fn ext_header_nhc_fields() { + let bytes = [0xe3, 0x06, 0x03, 0x00, 0xff, 0x00, 0x00, 0x00]; + + let packet = ExtensionHeaderPacket::new_checked(&bytes[..]).unwrap(); + assert_eq!(packet.dispatch_field(), EXT_HEADER_DISPATCH); + assert_eq!(packet.length_field(), 6); + assert_eq!( + packet.extension_header_id(), + ExtensionHeaderId::RoutingHeader + ); + + assert_eq!(packet.payload(), [0x03, 0x00, 0xff, 0x00, 0x00, 0x00]); + } + + #[test] + fn ext_header_emit() { + let ext_header = ExtensionHeaderRepr { + ext_header_id: ExtensionHeaderId::RoutingHeader, + next_header: NextHeader::Compressed, + length: 6, + }; + + let len = ext_header.buffer_len(); + let mut buffer = [0u8; 127]; + let mut packet = ExtensionHeaderPacket::new_unchecked(&mut buffer[..len]); + ext_header.emit(&mut packet); + + assert_eq!(packet.dispatch_field(), EXT_HEADER_DISPATCH); + assert_eq!(packet.next_header(), NextHeader::Compressed); + assert_eq!(packet.length_field(), 6); + assert_eq!( + packet.extension_header_id(), + ExtensionHeaderId::RoutingHeader + ); + } + + #[test] + fn udp_nhc_fields() { + let bytes = [0xf0, 0x16, 0x2e, 0x22, 0x3d, 0x28, 0xc4]; + + let packet = UdpPacket::new_checked(&bytes[..]).unwrap(); + assert_eq!(packet.dispatch_field(), UDP_DISPATCH); + assert_eq!(packet.checksum(), Some(0x28c4)); + assert_eq!(packet.src_port(), 5678); + assert_eq!(packet.dst_port(), 8765); + } + + #[test] + fn udp_emit() { + let udp = UdpNhcRepr(UdpRepr { + src_port: 0xf0b1, + dst_port: 0xf001, + payload: b"Hello World", + }); + + let len = udp.buffer_len(); + let mut buffer = [0u8; 127]; + let mut packet = UdpPacket::new_unchecked(&mut buffer[..len]); + udp.emit(&mut packet); + + assert_eq!(packet.dispatch_field(), UDP_DISPATCH); + assert_eq!(packet.src_port(), 0xf0b1); + assert_eq!(packet.dst_port(), 0xf001); + assert_eq!(packet.payload_mut(), b"Hello World"); + } + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn ieee802154_udp() { + use crate::wire::ieee802154::Frame as Ieee802154Frame; + use crate::wire::ieee802154::Repr as Ieee802154Repr; + use crate::wire::ipv6routing; + + // This data is captured using Wireshark from the communication between a RPL 6LoWPAN server + // and a RPL 6LoWPAN client. + // The frame is thus an IEEE802.15.4 frame, containing a 6LoWPAN packet, + // containing a RPL extension header and an UDP header. + let bytes: &[u8] = &[ + 0x61, 0xdc, 0xdd, 0xcd, 0xab, 0xc7, 0xd9, 0xb5, 0x14, 0x00, 0x4b, 0x12, 0x00, 0xbf, + 0x9b, 0x15, 0x06, 0x00, 0x4b, 0x12, 0x00, 0x7e, 0xf7, 0x00, 0xe3, 0x06, 0x03, 0x00, + 0xff, 0x00, 0x00, 0x00, 0xf0, 0x16, 0x2e, 0x22, 0x3d, 0x28, 0xc4, 0x68, 0x65, 0x6c, + 0x6c, 0x6f, 0x20, 0x36, 0x35, 0x18, 0xb9, + ]; + + let ieee802154_frame = Ieee802154Frame::new_checked(bytes).unwrap(); + let ieee802154_repr = Ieee802154Repr::parse(&ieee802154_frame).unwrap(); + + let iphc_frame = iphc::Packet::new_checked(ieee802154_frame.payload().unwrap()).unwrap(); + let iphc_repr = iphc::Repr::parse( + &iphc_frame, + ieee802154_repr.src_addr, + ieee802154_repr.dst_addr, + ) + .unwrap(); + + // The next header is compressed. + assert_eq!(iphc_repr.next_header, NextHeader::Compressed); + + // We dispatch the NHC packet. + let nhc_packet = nhc::Packet::dispatch(iphc_frame.payload()).unwrap(); + + let udp_payload = match nhc_packet { + nhc::Packet::ExtensionHeader(ext_packet) => { + // The next header is compressed (it is the UDP NHC compressed header). + assert_eq!(ext_packet.next_header(), NextHeader::Compressed); + assert_eq!(ext_packet.length_field(), 6); + let payload = ext_packet.payload(); + + let length = ext_packet.length_field() as usize; + let ext_packet_payload = &payload[..length]; + + match ext_packet.extension_header_id() { + nhc::ExtensionHeaderId::RoutingHeader => { + // We are not intersted in the Next Header protocol. + let proto = ipv6::Protocol::Unknown(0); + let mut new_payload = [0; 8]; + + new_payload[0] = proto.into(); + new_payload[1] = (2 + length - 8) as u8; + new_payload[2..].copy_from_slice(ext_packet_payload); + + let routing = ipv6routing::Header::new_checked(new_payload).unwrap(); + + assert_eq!(routing.routing_type(), ipv6routing::Type::Rpl); + assert_eq!(routing.segments_left(), 0); + assert_eq!(routing.cmpr_e(), 0xf); + assert_eq!(routing.cmpr_i(), 0xf); + } + _ => unreachable!(), + } + + &payload[length..] + } + _ => unreachable!(), + }; + + let udp_nhc_frame = nhc::UdpPacket::new_checked(udp_payload).unwrap(); + let udp_repr = nhc::UdpNhcRepr::parse( + &udp_nhc_frame, + &iphc_repr.src_addr, + &iphc_repr.dst_addr, + None, + ) + .unwrap(); + + assert_eq!(udp_repr.src_port, 5678); + assert_eq!(udp_repr.dst_port, 8765); + assert_eq!(udp_nhc_frame.checksum(), Some(0x28c4)); + } +}