Add some sanity into enumeration names (avoid "*Type").

v0.7.x
whitequark 2016-12-20 13:54:11 +00:00
parent c562ea784d
commit 0d9a8a417d
12 changed files with 147 additions and 148 deletions

View File

@ -4,7 +4,7 @@ extern crate smoltcp;
use std::env;
use smoltcp::Error;
use smoltcp::phy::{Tracer, TapInterface};
use smoltcp::wire::{EthernetFrame, EthernetAddress, InternetAddress, InternetEndpoint};
use smoltcp::wire::{EthernetFrame, EthernetAddress, IpAddress, IpEndpoint};
use smoltcp::iface::{SliceArpCache, EthernetInterface};
use smoltcp::socket::{UdpSocket, AsSocket, UdpBuffer, UdpPacket};
@ -16,10 +16,10 @@ fn main() {
let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
let hardware_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
let mut protocol_addrs = [InternetAddress::ipv4([192, 168, 69, 1])];
let mut protocol_addrs = [IpAddress::v4(192, 168, 69, 1)];
let listen_address = InternetAddress::ipv4([0, 0, 0, 0]);
let endpoint = InternetEndpoint::new(listen_address, 6969);
let listen_address = IpAddress::v4(0, 0, 0, 0);
let endpoint = IpEndpoint::new(listen_address, 6969);
let udp_rx_buffer = UdpBuffer::new(vec![UdpPacket::new(vec![0; 2048])]);
let udp_tx_buffer = UdpBuffer::new(vec![UdpPacket::new(vec![0; 2048])]);

View File

@ -1,15 +1,15 @@
use Managed;
use wire::{EthernetAddress, InternetAddress};
use wire::{EthernetAddress, IpAddress};
/// An Address Resolution Protocol cache.
///
/// This interface maps protocol addresses to hardware addresses.
pub trait Cache {
/// Update the cache to map given protocol address to given hardware address.
fn fill(&mut self, protocol_addr: InternetAddress, hardware_addr: EthernetAddress);
fn fill(&mut self, protocol_addr: IpAddress, hardware_addr: EthernetAddress);
/// Look up the hardware address corresponding for the given protocol address.
fn lookup(&mut self, protocol_addr: InternetAddress) -> Option<EthernetAddress>;
fn lookup(&mut self, protocol_addr: IpAddress) -> Option<EthernetAddress>;
}
/// An Address Resolution Protocol cache backed by a slice.
@ -33,7 +33,7 @@ pub trait Cache {
/// ```
pub struct SliceCache<'a> {
storage: Managed<'a, [(InternetAddress, EthernetAddress, usize)]>,
storage: Managed<'a, [(IpAddress, EthernetAddress, usize)]>,
counter: usize
}
@ -43,7 +43,7 @@ impl<'a> SliceCache<'a> {
/// # Panics
/// This function panics if `storage.len() == 0`.
pub fn new<T>(storage: T) -> SliceCache<'a>
where T: Into<Managed<'a, [(InternetAddress, EthernetAddress, usize)]>> {
where T: Into<Managed<'a, [(IpAddress, EthernetAddress, usize)]>> {
let mut storage = storage.into();
if storage.len() == 0 {
panic!("ARP slice cache created with empty storage")
@ -59,9 +59,9 @@ impl<'a> SliceCache<'a> {
}
/// Find an entry for the given protocol address, if any.
fn find(&self, protocol_addr: InternetAddress) -> Option<usize> {
// The order of comparison is important: any valid InternetAddress should
// sort before InternetAddress::Invalid.
fn find(&self, protocol_addr: IpAddress) -> Option<usize> {
// The order of comparison is important: any valid IpAddress should
// sort before IpAddress::Invalid.
self.storage.binary_search_by_key(&protocol_addr, |&(key, _, _)| key).ok()
}
@ -77,7 +77,7 @@ impl<'a> SliceCache<'a> {
}
impl<'a> Cache for SliceCache<'a> {
fn fill(&mut self, protocol_addr: InternetAddress, hardware_addr: EthernetAddress) {
fn fill(&mut self, protocol_addr: IpAddress, hardware_addr: EthernetAddress) {
if let None = self.find(protocol_addr) {
let lru_index = self.lru();
self.storage[lru_index] =
@ -86,7 +86,7 @@ impl<'a> Cache for SliceCache<'a> {
}
}
fn lookup(&mut self, protocol_addr: InternetAddress) -> Option<EthernetAddress> {
fn lookup(&mut self, protocol_addr: IpAddress) -> Option<EthernetAddress> {
if let Some(index) = self.find(protocol_addr) {
let (_protocol_addr, hardware_addr, ref mut counter) =
self.storage[index];
@ -108,10 +108,10 @@ mod test {
const HADDR_C: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 3]);
const HADDR_D: EthernetAddress = EthernetAddress([0, 0, 0, 0, 0, 4]);
const PADDR_A: InternetAddress = InternetAddress::ipv4([0, 0, 0, 0]);
const PADDR_B: InternetAddress = InternetAddress::ipv4([0, 0, 0, 1]);
const PADDR_C: InternetAddress = InternetAddress::ipv4([0, 0, 0, 2]);
const PADDR_D: InternetAddress = InternetAddress::ipv4([0, 0, 0, 3]);
const PADDR_A: IpAddress = IpAddress::v4(0, 0, 0, 0);
const PADDR_B: IpAddress = IpAddress::v4(0, 0, 0, 1);
const PADDR_C: IpAddress = IpAddress::v4(0, 0, 0, 2);
const PADDR_D: IpAddress = IpAddress::v4(0, 0, 0, 3);
#[test]
fn test_slice_cache() {

View File

@ -3,9 +3,9 @@ use core::marker::PhantomData;
use Error;
use phy::Device;
use wire::{EthernetAddress, EthernetProtocolType, EthernetFrame};
use wire::{EthernetAddress, EthernetProtocol, EthernetFrame};
use wire::{ArpPacket, ArpRepr, ArpOperation};
use wire::{InternetAddress, InternetProtocolType};
use wire::{IpAddress, IpProtocol};
use wire::{Ipv4Packet, Ipv4Repr};
use wire::{Icmpv4Packet, Icmpv4Repr};
use socket::Socket;
@ -20,7 +20,7 @@ use super::{ArpCache};
pub struct Interface<'a, 'b: 'a,
DeviceT: Device,
ArpCacheT: ArpCache,
ProtocolAddrsT: BorrowMut<[InternetAddress]>,
ProtocolAddrsT: BorrowMut<[IpAddress]>,
SocketsT: BorrowMut<[Socket<'a, 'b>]>
> {
device: DeviceT,
@ -34,7 +34,7 @@ pub struct Interface<'a, 'b: 'a,
impl<'a, 'b: 'a,
DeviceT: Device,
ArpCacheT: ArpCache,
ProtocolAddrsT: BorrowMut<[InternetAddress]>,
ProtocolAddrsT: BorrowMut<[IpAddress]>,
SocketsT: BorrowMut<[Socket<'a, 'b>]>
> Interface<'a, 'b, DeviceT, ArpCacheT, ProtocolAddrsT, SocketsT> {
/// Create a network interface using the provided network device.
@ -77,7 +77,7 @@ impl<'a, 'b: 'a,
Self::check_hardware_addr(&self.hardware_addr);
}
fn check_protocol_addrs(addrs: &[InternetAddress]) {
fn check_protocol_addrs(addrs: &[IpAddress]) {
for addr in addrs {
if !addr.is_unicast() {
panic!("protocol address {} is not unicast", addr)
@ -86,7 +86,7 @@ impl<'a, 'b: 'a,
}
/// Get the protocol addresses of the interface.
pub fn protocol_addrs(&self) -> &[InternetAddress] {
pub fn protocol_addrs(&self) -> &[IpAddress] {
self.protocol_addrs.borrow()
}
@ -94,13 +94,13 @@ impl<'a, 'b: 'a,
///
/// # Panics
/// This function panics if any of the addresses is not unicast.
pub fn update_protocol_addrs<F: FnOnce(&mut [InternetAddress])>(&mut self, f: F) {
pub fn update_protocol_addrs<F: FnOnce(&mut [IpAddress])>(&mut self, f: F) {
f(self.protocol_addrs.borrow_mut());
Self::check_protocol_addrs(self.protocol_addrs.borrow())
}
/// Check whether the interface has the given protocol address assigned.
pub fn has_protocol_addr<T: Into<InternetAddress>>(&self, addr: T) -> bool {
pub fn has_protocol_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
let addr = addr.into();
self.protocol_addrs.borrow().iter().any(|&probe| probe == addr)
}
@ -130,7 +130,7 @@ impl<'a, 'b: 'a,
let mut response = Response::Nop;
match eth_frame.ethertype() {
// Snoop all ARP traffic, and respond to ARP packets directed at us.
EthernetProtocolType::Arp => {
EthernetProtocol::Arp => {
let arp_packet = try!(ArpPacket::new(eth_frame.payload()));
match try!(ArpRepr::parse(&arp_packet)) {
// Respond to ARP requests aimed at us, and fill the ARP cache
@ -166,14 +166,14 @@ impl<'a, 'b: 'a,
},
// Handle IP packets directed at us.
EthernetProtocolType::Ipv4 => {
EthernetProtocol::Ipv4 => {
let ip_packet = try!(Ipv4Packet::new(eth_frame.payload()));
match try!(Ipv4Repr::parse(&ip_packet)) {
// Ignore IP packets not directed at us.
Ipv4Repr { dst_addr, .. } if !self.has_protocol_addr(dst_addr) => (),
// Respond to ICMP packets.
Ipv4Repr { protocol: InternetProtocolType::Icmp, src_addr, dst_addr } => {
Ipv4Repr { protocol: IpProtocol::Icmp, src_addr, dst_addr } => {
let icmp_packet = try!(Icmpv4Packet::new(ip_packet.payload()));
let icmp_repr = try!(Icmpv4Repr::parse(&icmp_packet));
match icmp_repr {
@ -184,7 +184,7 @@ impl<'a, 'b: 'a,
let ip_reply_repr = Ipv4Repr {
src_addr: dst_addr,
dst_addr: src_addr,
protocol: InternetProtocolType::Icmp
protocol: IpProtocol::Icmp
};
let icmp_reply_repr = Icmpv4Repr::EchoReply {
ident: ident,
@ -232,7 +232,7 @@ impl<'a, 'b: 'a,
ArpRepr::EthernetIpv4 { target_hardware_addr, .. } => target_hardware_addr,
_ => unreachable!()
});
frame.set_ethertype(EthernetProtocolType::Arp);
frame.set_ethertype(EthernetProtocol::Arp);
let mut packet = try!(ArpPacket::new(frame.payload_mut()));
repr.emit(&mut packet);
@ -253,7 +253,7 @@ impl<'a, 'b: 'a,
let mut frame = try!(EthernetFrame::new(&mut tx_buffer));
frame.set_src_addr(self.hardware_addr);
frame.set_dst_addr(dst_hardware_addr);
frame.set_ethertype(EthernetProtocolType::Ipv4);
frame.set_ethertype(EthernetProtocol::Ipv4);
let mut ip_packet = try!(Ipv4Packet::new(frame.payload_mut()));
ip_repr.emit(&mut ip_packet, icmp_repr.buffer_len());
@ -283,11 +283,11 @@ impl<'a, 'b: 'a,
let result = socket.dispatch(&mut |src_addr, dst_addr, protocol, payload| {
let src_addr =
match src_addr {
&InternetAddress::Ipv4(_) if src_addr.is_unspecified() => {
&IpAddress::Ipv4(_) if src_addr.is_unspecified() => {
let mut assigned_addr = None;
for addr in src_protocol_addrs {
match addr {
addr @ &InternetAddress::Ipv4(_) => {
addr @ &IpAddress::Ipv4(_) => {
assigned_addr = Some(addr);
break
}
@ -304,8 +304,8 @@ impl<'a, 'b: 'a,
let ip_repr =
match (src_addr, dst_addr) {
(&InternetAddress::Ipv4(src_addr),
&InternetAddress::Ipv4(dst_addr)) => {
(&IpAddress::Ipv4(src_addr),
&IpAddress::Ipv4(dst_addr)) => {
Ipv4Repr {
src_addr: src_addr,
dst_addr: dst_addr,
@ -327,7 +327,7 @@ impl<'a, 'b: 'a,
let mut frame = try!(EthernetFrame::new(&mut tx_buffer));
frame.set_src_addr(src_hardware_addr);
frame.set_dst_addr(dst_hardware_addr);
frame.set_ethertype(EthernetProtocolType::Ipv4);
frame.set_ethertype(EthernetProtocol::Ipv4);
let mut ip_packet = try!(Ipv4Packet::new(frame.payload_mut()));
ip_repr.emit(&mut ip_packet, payload.buffer_len());

View File

@ -11,7 +11,7 @@
//! size for a buffer, allocate it, and let the networking stack use it.
use Error;
use wire::{InternetAddress as Address, InternetProtocolType as ProtocolType};
use wire::{IpAddress, IpProtocol};
mod udp;
mod tcp;
@ -31,7 +31,7 @@ pub trait PacketRepr {
fn buffer_len(&self) -> usize;
/// Emit this high-level representation into a sequence of octets.
fn emit(&self, src_addr: &Address, dst_addr: &Address, payload: &mut [u8]);
fn emit(&self, src_addr: &IpAddress, dst_addr: &IpAddress, payload: &mut [u8]);
}
/// A network socket.
@ -61,8 +61,8 @@ impl<'a, 'b> Socket<'a, 'b> {
/// is returned.
///
/// This function is used internally by the networking stack.
pub fn collect(&mut self, src_addr: &Address, dst_addr: &Address,
protocol: ProtocolType, payload: &[u8])
pub fn collect(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress,
protocol: IpProtocol, payload: &[u8])
-> Result<(), Error> {
match self {
&mut Socket::Udp(ref mut socket) =>
@ -78,8 +78,8 @@ impl<'a, 'b> Socket<'a, 'b> {
/// is returned.
///
/// This function is used internally by the networking stack.
pub fn dispatch(&mut self, f: &mut FnMut(&Address, &Address,
ProtocolType, &PacketRepr) -> Result<(), Error>)
pub fn dispatch(&mut self, f: &mut FnMut(&IpAddress, &IpAddress,
IpProtocol, &PacketRepr) -> Result<(), Error>)
-> Result<(), Error> {
match self {
&mut Socket::Udp(ref mut socket) =>

View File

@ -1,14 +1,13 @@
use Error;
use Managed;
use wire::{InternetAddress as Address, InternetProtocolType as ProtocolType};
use wire::{InternetEndpoint as Endpoint};
use wire::{IpAddress, IpProtocol, IpEndpoint};
use wire::{UdpPacket, UdpRepr};
use socket::{Socket, PacketRepr};
/// A buffered UDP packet.
#[derive(Debug)]
pub struct Packet<'a> {
endpoint: Endpoint,
endpoint: IpEndpoint,
size: usize,
payload: Managed<'a, [u8]>
}
@ -18,7 +17,7 @@ impl<'a> Packet<'a> {
pub fn new<T>(payload: T) -> Packet<'a>
where T: Into<Managed<'a, [u8]>> {
Packet {
endpoint: Endpoint::INVALID,
endpoint: IpEndpoint::INVALID,
size: 0,
payload: payload.into()
}
@ -106,14 +105,14 @@ impl<'a, 'b> Buffer<'a, 'b> {
/// An UDP socket is bound to a specific endpoint, and owns transmit and receive
/// packet buffers.
pub struct UdpSocket<'a, 'b: 'a> {
endpoint: Endpoint,
endpoint: IpEndpoint,
rx_buffer: Buffer<'a, 'b>,
tx_buffer: Buffer<'a, 'b>
}
impl<'a, 'b> UdpSocket<'a, 'b> {
/// Create an UDP socket with the given buffers.
pub fn new(endpoint: Endpoint, rx_buffer: Buffer<'a, 'b>, tx_buffer: Buffer<'a, 'b>)
pub fn new(endpoint: IpEndpoint, rx_buffer: Buffer<'a, 'b>, tx_buffer: Buffer<'a, 'b>)
-> Socket<'a, 'b> {
Socket::Udp(UdpSocket {
endpoint: endpoint,
@ -127,7 +126,7 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
///
/// This function returns `Err(Error::Exhausted)` if the size is greater than what
/// the transmit buffer can accomodate.
pub fn send(&mut self, endpoint: Endpoint, size: usize) -> Result<&mut [u8], Error> {
pub fn send(&mut self, endpoint: IpEndpoint, size: usize) -> Result<&mut [u8], Error> {
let packet_buf = try!(self.tx_buffer.enqueue());
packet_buf.endpoint = endpoint;
packet_buf.size = size;
@ -137,7 +136,7 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
/// Enqueue a packete to be sent to a given remote endpoint, and fill it from a slice.
///
/// See also [send](#method.send).
pub fn send_slice(&mut self, endpoint: Endpoint, data: &[u8]) -> Result<(), Error> {
pub fn send_slice(&mut self, endpoint: IpEndpoint, data: &[u8]) -> Result<(), Error> {
let buffer = try!(self.send(endpoint, data.len()));
Ok(buffer.copy_from_slice(data))
}
@ -146,7 +145,7 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
/// as a pointer to the payload.
///
/// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
pub fn recv(&mut self) -> Result<(Endpoint, &[u8]), Error> {
pub fn recv(&mut self) -> Result<(IpEndpoint, &[u8]), Error> {
let packet_buf = try!(self.rx_buffer.dequeue());
Ok((packet_buf.endpoint, &packet_buf.as_ref()[..packet_buf.size]))
}
@ -156,7 +155,7 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
///
/// This function returns `Err(Error::Exhausted)` if the received packet has payload
/// larger than the provided slice. See also [recv](#method.recv).
pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(Endpoint, usize), Error> {
pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(IpEndpoint, usize), Error> {
let (endpoint, buffer) = try!(self.recv());
if data.len() < buffer.len() { return Err(Error::Exhausted) }
data[..buffer.len()].copy_from_slice(buffer);
@ -164,10 +163,10 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
}
/// See [Socket::collect](enum.Socket.html#method.collect).
pub fn collect(&mut self, src_addr: &Address, dst_addr: &Address,
protocol: ProtocolType, payload: &[u8])
pub fn collect(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress,
protocol: IpProtocol, payload: &[u8])
-> Result<(), Error> {
if protocol != ProtocolType::Udp { return Err(Error::Rejected) }
if protocol != IpProtocol::Udp { return Err(Error::Rejected) }
let packet = try!(UdpPacket::new(payload));
let repr = try!(UdpRepr::parse(&packet, src_addr, dst_addr));
@ -178,20 +177,20 @@ impl<'a, 'b> UdpSocket<'a, 'b> {
}
let packet_buf = try!(self.rx_buffer.enqueue());
packet_buf.endpoint = Endpoint { addr: *src_addr, port: repr.src_port };
packet_buf.endpoint = IpEndpoint { addr: *src_addr, port: repr.src_port };
packet_buf.size = repr.payload.len();
packet_buf.as_mut()[..repr.payload.len()].copy_from_slice(repr.payload);
Ok(())
}
/// See [Socket::dispatch](enum.Socket.html#method.dispatch).
pub fn dispatch(&mut self, f: &mut FnMut(&Address, &Address,
ProtocolType, &PacketRepr) -> Result<(), Error>)
pub fn dispatch(&mut self, f: &mut FnMut(&IpAddress, &IpAddress,
IpProtocol, &PacketRepr) -> Result<(), Error>)
-> Result<(), Error> {
let packet_buf = try!(self.tx_buffer.dequeue());
f(&self.endpoint.addr,
&packet_buf.endpoint.addr,
ProtocolType::Udp,
IpProtocol::Udp,
&UdpRepr {
src_port: self.endpoint.port,
dst_port: packet_buf.endpoint.port,
@ -205,8 +204,8 @@ impl<'a> PacketRepr for UdpRepr<'a> {
self.buffer_len()
}
fn emit(&self, src_addr: &Address, dst_addr: &Address, payload: &mut [u8]) {
let mut packet = UdpPacket::new(payload).expect("undersized payload slice");
fn emit(&self, src_addr: &IpAddress, dst_addr: &IpAddress, payload: &mut [u8]) {
let mut packet = UdpPacket::new(payload).expect("undersized payload");
self.emit(&mut packet, src_addr, dst_addr)
}
}

View File

@ -2,11 +2,11 @@ use core::fmt;
use byteorder::{ByteOrder, NetworkEndian};
use Error;
pub use super::EthernetProtocolType as ProtocolType;
pub use super::EthernetProtocol as Protocol;
enum_with_unknown! {
/// ARP network protocol type.
pub enum HardwareType(u16) {
/// ARP hardware type.
pub enum Hardware(u16) {
Ethernet = 1
}
}
@ -85,18 +85,18 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// Return the hardware type field.
#[inline(always)]
pub fn hardware_type(&self) -> HardwareType {
pub fn hardware_type(&self) -> Hardware {
let data = self.buffer.as_ref();
let raw = NetworkEndian::read_u16(&data[field::HTYPE]);
HardwareType::from(raw)
Hardware::from(raw)
}
/// Return the protocol type field.
#[inline(always)]
pub fn protocol_type(&self) -> ProtocolType {
pub fn protocol_type(&self) -> Protocol {
let data = self.buffer.as_ref();
let raw = NetworkEndian::read_u16(&data[field::PTYPE]);
ProtocolType::from(raw)
Protocol::from(raw)
}
/// Return the hardware length field.
@ -149,14 +149,14 @@ impl<T: AsRef<[u8]>> Packet<T> {
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
/// Set the hardware type field.
#[inline(always)]
pub fn set_hardware_type(&mut self, value: HardwareType) {
pub fn set_hardware_type(&mut self, value: Hardware) {
let data = self.buffer.as_mut();
NetworkEndian::write_u16(&mut data[field::HTYPE], value.into())
}
/// Set the protocol type field.
#[inline(always)]
pub fn set_protocol_type(&mut self, value: ProtocolType) {
pub fn set_protocol_type(&mut self, value: Protocol) {
let data = self.buffer.as_mut();
NetworkEndian::write_u16(&mut data[field::PTYPE], value.into())
}
@ -246,7 +246,7 @@ impl Repr {
pub fn parse<T: AsRef<[u8]>>(packet: &Packet<T>) -> Result<Repr, Error> {
match (packet.hardware_type(), packet.protocol_type(),
packet.hardware_len(), packet.protocol_len()) {
(HardwareType::Ethernet, ProtocolType::Ipv4, 6, 4) => {
(Hardware::Ethernet, Protocol::Ipv4, 6, 4) => {
Ok(Repr::EthernetIpv4 {
operation: packet.operation(),
source_hardware_addr:
@ -279,8 +279,8 @@ impl Repr {
source_hardware_addr, source_protocol_addr,
target_hardware_addr, target_protocol_addr
} => {
packet.set_hardware_type(HardwareType::Ethernet);
packet.set_protocol_type(ProtocolType::Ipv4);
packet.set_hardware_type(Hardware::Ethernet);
packet.set_protocol_type(Protocol::Ipv4);
packet.set_hardware_len(6);
packet.set_protocol_len(4);
packet.set_operation(operation);
@ -361,8 +361,8 @@ mod test {
#[test]
fn test_deconstruct() {
let packet = Packet::new(&PACKET_BYTES[..]).unwrap();
assert_eq!(packet.hardware_type(), HardwareType::Ethernet);
assert_eq!(packet.protocol_type(), ProtocolType::Ipv4);
assert_eq!(packet.hardware_type(), Hardware::Ethernet);
assert_eq!(packet.protocol_type(), Protocol::Ipv4);
assert_eq!(packet.hardware_len(), 6);
assert_eq!(packet.protocol_len(), 4);
assert_eq!(packet.operation(), Operation::Request);
@ -376,8 +376,8 @@ mod test {
fn test_construct() {
let mut bytes = vec![0; 28];
let mut packet = Packet::new(&mut bytes).unwrap();
packet.set_hardware_type(HardwareType::Ethernet);
packet.set_protocol_type(ProtocolType::Ipv4);
packet.set_hardware_type(Hardware::Ethernet);
packet.set_protocol_type(Protocol::Ipv4);
packet.set_hardware_len(6);
packet.set_protocol_len(4);
packet.set_operation(Operation::Request);

View File

@ -6,7 +6,7 @@ use super::ip::checksum;
enum_with_unknown! {
/// Internet protocol control message type.
pub doc enum Type(u8) {
pub doc enum Message(u8) {
/// Echo reply
EchoReply = 0,
/// Destination unreachable
@ -30,20 +30,20 @@ enum_with_unknown! {
}
}
impl fmt::Display for Type {
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Type::EchoReply => write!(f, "echo reply"),
&Type::DstUnreachable => write!(f, "destination unreachable"),
&Type::Redirect => write!(f, "message redirect"),
&Type::EchoRequest => write!(f, "echo request"),
&Type::RouterAdvert => write!(f, "router advertisement"),
&Type::RouterSolicit => write!(f, "router solicitation"),
&Type::TimeExceeded => write!(f, "time exceeded"),
&Type::ParamProblem => write!(f, "parameter problem"),
&Type::Timestamp => write!(f, "timestamp"),
&Type::TimestampReply => write!(f, "timestamp reply"),
&Type::Unknown(id) => write!(f, "{}", id)
&Message::EchoReply => write!(f, "echo reply"),
&Message::DstUnreachable => write!(f, "destination unreachable"),
&Message::Redirect => write!(f, "message redirect"),
&Message::EchoRequest => write!(f, "echo request"),
&Message::RouterAdvert => write!(f, "router advertisement"),
&Message::RouterSolicit => write!(f, "router solicitation"),
&Message::TimeExceeded => write!(f, "time exceeded"),
&Message::ParamProblem => write!(f, "parameter problem"),
&Message::Timestamp => write!(f, "timestamp"),
&Message::TimestampReply => write!(f, "timestamp reply"),
&Message::Unknown(id) => write!(f, "{}", id)
}
}
}
@ -163,9 +163,9 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// Return the message type field.
#[inline(always)]
pub fn msg_type(&self) -> Type {
pub fn msg_type(&self) -> Message {
let data = self.buffer.as_ref();
Type::from(data[field::TYPE])
Message::from(data[field::TYPE])
}
/// Return the message code field.
@ -206,8 +206,8 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// The result depends on the value of the message type field.
pub fn header_len(&self) -> usize {
match self.msg_type() {
Type::EchoRequest => field::ECHO_SEQNO.end,
Type::EchoReply => field::ECHO_SEQNO.end,
Message::EchoRequest => field::ECHO_SEQNO.end,
Message::EchoReply => field::ECHO_SEQNO.end,
_ => field::CHECKSUM.end // make a conservative assumption
}
}
@ -231,7 +231,7 @@ impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
/// Set the message type field.
#[inline(always)]
pub fn set_msg_type(&mut self, value: Type) {
pub fn set_msg_type(&mut self, value: Message) {
let mut data = self.buffer.as_mut();
data[field::TYPE] = value.into()
}
@ -313,14 +313,14 @@ impl<'a> Repr<'a> {
/// a high-level representation.
pub fn parse<T: AsRef<[u8]> + ?Sized>(packet: &Packet<&'a T>) -> Result<Repr<'a>, Error> {
match (packet.msg_type(), packet.msg_code()) {
(Type::EchoRequest, 0) => {
(Message::EchoRequest, 0) => {
Ok(Repr::EchoRequest {
ident: packet.echo_ident(),
seq_no: packet.echo_seq_no(),
data: packet.data()
})
},
(Type::EchoReply, 0) => {
(Message::EchoReply, 0) => {
Ok(Repr::EchoReply {
ident: packet.echo_ident(),
seq_no: packet.echo_seq_no(),
@ -348,14 +348,14 @@ impl<'a> Repr<'a> {
packet.set_msg_code(0);
match self {
&Repr::EchoRequest { ident, seq_no, data } => {
packet.set_msg_type(Type::EchoRequest);
packet.set_msg_type(Message::EchoRequest);
packet.set_echo_ident(ident);
packet.set_echo_seq_no(seq_no);
let data_len = cmp::min(packet.data_mut().len(), data.len());
packet.data_mut()[..data_len].copy_from_slice(&data[..data_len])
},
&Repr::EchoReply { ident, seq_no, data } => {
packet.set_msg_type(Type::EchoReply);
packet.set_msg_type(Message::EchoReply);
packet.set_echo_ident(ident);
packet.set_echo_seq_no(seq_no);
let data_len = cmp::min(packet.data_mut().len(), data.len());
@ -423,7 +423,7 @@ mod test {
#[test]
fn test_echo_deconstruct() {
let packet = Packet::new(&ECHO_PACKET_BYTES[..]).unwrap();
assert_eq!(packet.msg_type(), Type::EchoRequest);
assert_eq!(packet.msg_type(), Message::EchoRequest);
assert_eq!(packet.msg_code(), 0);
assert_eq!(packet.checksum(), 0x8efe);
assert_eq!(packet.echo_ident(), 0x1234);
@ -436,7 +436,7 @@ mod test {
fn test_echo_construct() {
let mut bytes = vec![0; 12];
let mut packet = Packet::new(&mut bytes).unwrap();
packet.set_msg_type(Type::EchoRequest);
packet.set_msg_type(Message::EchoRequest);
packet.set_msg_code(0);
packet.set_echo_ident(0x1234);
packet.set_echo_seq_no(0xabcd);

View File

@ -3,21 +3,21 @@ use core::fmt;
use super::Ipv4Address;
enum_with_unknown! {
/// Internetworking protocol type.
pub enum ProtocolType(u8) {
/// Internetworking protocol.
pub enum Protocol(u8) {
Icmp = 0x01,
Tcp = 0x06,
Udp = 0x11
}
}
impl fmt::Display for ProtocolType {
impl fmt::Display for Protocol {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ProtocolType::Icmp => write!(f, "ICMP"),
&ProtocolType::Tcp => write!(f, "TCP"),
&ProtocolType::Udp => write!(f, "UDP"),
&ProtocolType::Unknown(id) => write!(f, "0x{:02x}", id)
&Protocol::Icmp => write!(f, "ICMP"),
&Protocol::Tcp => write!(f, "TCP"),
&Protocol::Udp => write!(f, "UDP"),
&Protocol::Unknown(id) => write!(f, "0x{:02x}", id)
}
}
}
@ -34,8 +34,8 @@ pub enum Address {
impl Address {
/// Create an address wrapping an IPv4 address with the given octets.
pub const fn ipv4(octets: [u8; 4]) -> Address {
Address::Ipv4(Ipv4Address(octets))
pub const fn v4(a0: u8, a1: u8, a2: u8, a3: u8) -> Address {
Address::Ipv4(Ipv4Address([a0, a1, a2, a3]))
}
/// Query whether the address is a valid unicast address.
@ -129,7 +129,7 @@ pub mod checksum {
/// Compute an IP pseudo header checksum.
pub fn pseudo_header(src_addr: &Address, dst_addr: &Address,
protocol: ProtocolType, length: u32) -> u16 {
protocol: Protocol, length: u32) -> u16 {
match (src_addr, dst_addr) {
(&Address::Ipv4(src_addr), &Address::Ipv4(dst_addr)) => {
let mut proto_len = [0u8; 4];

View File

@ -4,7 +4,7 @@ use byteorder::{ByteOrder, NetworkEndian};
use Error;
use super::ip::checksum;
pub use super::InternetProtocolType as ProtocolType;
pub use super::IpProtocol as Protocol;
/// A four-octet IPv4 address.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
@ -182,9 +182,9 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// Return the protocol field.
#[inline(always)]
pub fn protocol(&self) -> ProtocolType {
pub fn protocol(&self) -> Protocol {
let data = self.buffer.as_ref();
ProtocolType::from(data[field::PROTOCOL])
Protocol::from(data[field::PROTOCOL])
}
/// Return the header checksum field.
@ -311,7 +311,7 @@ impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
/// Set the protocol field.
#[inline(always)]
pub fn set_protocol(&mut self, value: ProtocolType) {
pub fn set_protocol(&mut self, value: Protocol) {
let data = self.buffer.as_mut();
data[field::PROTOCOL] = value.into()
}
@ -363,7 +363,7 @@ impl<'a, T: AsRef<[u8]> + AsMut<[u8]> + ?Sized> Packet<&'a mut T> {
pub struct Repr {
pub src_addr: Address,
pub dst_addr: Address,
pub protocol: ProtocolType
pub protocol: Protocol
}
impl Repr {
@ -478,11 +478,11 @@ impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
indent.increase();
match packet.protocol() {
ProtocolType::Icmp =>
Protocol::Icmp =>
super::Icmpv4Packet::<&[u8]>::pretty_print(&packet.payload(), f, indent),
ProtocolType::Udp =>
Protocol::Udp =>
super::UdpPacket::<&[u8]>::pretty_print(&packet.payload(), f, indent),
ProtocolType::Tcp =>
Protocol::Tcp =>
super::TcpPacket::<&[u8]>::pretty_print(&packet.payload(), f, indent),
_ => Ok(())
}
@ -521,7 +521,7 @@ mod test {
assert_eq!(packet.dont_frag(), true);
assert_eq!(packet.frag_offset(), 0x203 * 8);
assert_eq!(packet.ttl(), 0x1a);
assert_eq!(packet.protocol(), ProtocolType::Icmp);
assert_eq!(packet.protocol(), Protocol::Icmp);
assert_eq!(packet.checksum(), 0xd56e);
assert_eq!(packet.src_addr(), Address([0x11, 0x12, 0x13, 0x14]));
assert_eq!(packet.dst_addr(), Address([0x21, 0x22, 0x23, 0x24]));
@ -543,7 +543,7 @@ mod test {
packet.set_dont_frag(true);
packet.set_frag_offset(0x203 * 8);
packet.set_ttl(0x1a);
packet.set_protocol(ProtocolType::Icmp);
packet.set_protocol(Protocol::Icmp);
packet.set_src_addr(Address([0x11, 0x12, 0x13, 0x14]));
packet.set_dst_addr(Address([0x21, 0x22, 0x23, 0x24]));
packet.fill_checksum();
@ -566,7 +566,7 @@ mod test {
Repr {
src_addr: Address([0x11, 0x12, 0x13, 0x14]),
dst_addr: Address([0x21, 0x22, 0x23, 0x24]),
protocol: ProtocolType::Icmp
protocol: Protocol::Icmp
}
}

View File

@ -90,24 +90,24 @@ mod tcp;
pub use self::pretty_print::PrettyPrinter;
pub use self::ethernet::EtherType as EthernetProtocolType;
pub use self::ethernet::EtherType as EthernetProtocol;
pub use self::ethernet::Address as EthernetAddress;
pub use self::ethernet::Frame as EthernetFrame;
pub use self::arp::HardwareType as ArpHardwareType;
pub use self::arp::Hardware as ArpHardware;
pub use self::arp::Operation as ArpOperation;
pub use self::arp::Packet as ArpPacket;
pub use self::arp::Repr as ArpRepr;
pub use self::ip::ProtocolType as InternetProtocolType;
pub use self::ip::Address as InternetAddress;
pub use self::ip::Endpoint as InternetEndpoint;
pub use self::ip::Protocol as IpProtocol;
pub use self::ip::Address as IpAddress;
pub use self::ip::Endpoint as IpEndpoint;
pub use self::ipv4::Address as Ipv4Address;
pub use self::ipv4::Packet as Ipv4Packet;
pub use self::ipv4::Repr as Ipv4Repr;
pub use self::icmpv4::Type as Icmpv4Type;
pub use self::icmpv4::Message as Icmpv4Message;
pub use self::icmpv4::DstUnreachable as Icmpv4DstUnreachable;
pub use self::icmpv4::Redirect as Icmpv4Redirect;
pub use self::icmpv4::TimeExceeded as Icmpv4TimeExceeded;

View File

@ -2,7 +2,7 @@ use core::fmt;
use byteorder::{ByteOrder, NetworkEndian};
use Error;
use super::{InternetProtocolType, InternetAddress};
use super::{IpProtocol, IpAddress};
use super::ip::checksum;
/// A read/write wrapper around an Transmission Control Protocol packet buffer.
@ -187,10 +187,10 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// # Panics
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
/// and that family is IPv4 or IPv6.
pub fn verify_checksum(&self, src_addr: &InternetAddress, dst_addr: &InternetAddress) -> bool {
pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
let data = self.buffer.as_ref();
checksum::combine(&[
checksum::pseudo_header(src_addr, dst_addr, InternetProtocolType::Tcp,
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
data.len() as u32),
checksum::data(data)
]) == !0
@ -361,12 +361,12 @@ impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
/// # Panics
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
/// and that family is IPv4 or IPv6.
pub fn fill_checksum(&mut self, src_addr: &InternetAddress, dst_addr: &InternetAddress) {
pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
self.set_checksum(0);
let checksum = {
let data = self.buffer.as_ref();
!checksum::combine(&[
checksum::pseudo_header(src_addr, dst_addr, InternetProtocolType::Tcp,
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
data.len() as u32),
checksum::data(data)
])
@ -409,8 +409,8 @@ pub enum Control {
impl<'a> Repr<'a> {
/// Parse a Transmission Control Protocol packet and return a high-level representation.
pub fn parse<T: ?Sized>(packet: &Packet<&'a T>,
src_addr: &InternetAddress,
dst_addr: &InternetAddress) -> Result<Repr<'a>, Error>
src_addr: &IpAddress,
dst_addr: &IpAddress) -> Result<Repr<'a>, Error>
where T: AsRef<[u8]> {
// Source and destination ports must be present.
if packet.src_port() == 0 { return Err(Error::Malformed) }
@ -454,8 +454,8 @@ impl<'a> Repr<'a> {
/// Emit a high-level representation into a Transmission Control Protocol packet.
pub fn emit<T: ?Sized>(&self, packet: &mut Packet<&mut T>,
src_addr: &InternetAddress,
dst_addr: &InternetAddress)
src_addr: &IpAddress,
dst_addr: &IpAddress)
where T: AsRef<[u8]> + AsMut<[u8]> {
packet.set_src_port(self.src_port);
packet.set_dst_port(self.dst_port);

View File

@ -2,7 +2,7 @@ use core::fmt;
use byteorder::{ByteOrder, NetworkEndian};
use Error;
use super::{InternetProtocolType, InternetAddress};
use super::{IpProtocol, IpAddress};
use super::ip::checksum;
/// A read/write wrapper around an User Datagram Protocol packet buffer.
@ -81,10 +81,10 @@ impl<T: AsRef<[u8]>> Packet<T> {
/// # Panics
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
/// and that family is IPv4 or IPv6.
pub fn verify_checksum(&self, src_addr: &InternetAddress, dst_addr: &InternetAddress) -> bool {
pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
let data = self.buffer.as_ref();
checksum::combine(&[
checksum::pseudo_header(src_addr, dst_addr, InternetProtocolType::Udp,
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Udp,
self.len() as u32),
checksum::data(&data[..self.len() as usize])
]) == !0
@ -135,12 +135,12 @@ impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
/// # Panics
/// This function panics unless `src_addr` and `dst_addr` belong to the same family,
/// and that family is IPv4 or IPv6.
pub fn fill_checksum(&mut self, src_addr: &InternetAddress, dst_addr: &InternetAddress) {
pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
self.set_checksum(0);
let checksum = {
let data = self.buffer.as_ref();
!checksum::combine(&[
checksum::pseudo_header(src_addr, dst_addr, InternetProtocolType::Udp,
checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Udp,
self.len() as u32),
checksum::data(&data[..self.len() as usize])
])
@ -170,15 +170,15 @@ pub struct Repr<'a> {
impl<'a> Repr<'a> {
/// Parse an User Datagram Protocol packet and return a high-level representation.
pub fn parse<T: ?Sized>(packet: &Packet<&'a T>,
src_addr: &InternetAddress,
dst_addr: &InternetAddress) -> Result<Repr<'a>, Error>
src_addr: &IpAddress,
dst_addr: &IpAddress) -> Result<Repr<'a>, Error>
where T: AsRef<[u8]> {
// Destination port cannot be omitted (but source port can be).
if packet.dst_port() == 0 { return Err(Error::Malformed) }
// Valid checksum is expected...
if !packet.verify_checksum(src_addr, dst_addr) {
match (src_addr, dst_addr) {
(&InternetAddress::Ipv4(_), &InternetAddress::Ipv4(_))
(&IpAddress::Ipv4(_), &IpAddress::Ipv4(_))
if packet.checksum() != 0 => {
// ... except on UDP-over-IPv4, where it can be omitted.
return Err(Error::Checksum)
@ -203,8 +203,8 @@ impl<'a> Repr<'a> {
/// Emit a high-level representation into an User Datagram Protocol packet.
pub fn emit<T: ?Sized>(&self, packet: &mut Packet<&mut T>,
src_addr: &InternetAddress,
dst_addr: &InternetAddress)
src_addr: &IpAddress,
dst_addr: &IpAddress)
where T: AsRef<[u8]> + AsMut<[u8]> {
packet.set_src_port(self.src_port);
packet.set_dst_port(self.dst_port);