renet/src/socket/udp.rs

210 lines
6.8 KiB
Rust
Raw Normal View History

2017-01-10 19:04:00 +08:00
use managed::Managed;
use {Error, Result};
use phy::DeviceLimits;
use wire::{IpProtocol, IpEndpoint};
use wire::{UdpPacket, UdpRepr};
use socket::{Socket, IpRepr, IpPayload};
2017-06-18 18:11:21 +08:00
use storage::{Resettable, RingBuffer};
2016-12-15 01:39:44 +08:00
2016-12-16 01:07:56 +08:00
/// A buffered UDP packet.
#[derive(Debug)]
pub struct PacketBuffer<'a> {
endpoint: IpEndpoint,
2016-12-16 01:07:56 +08:00
size: usize,
payload: Managed<'a, [u8]>
2016-12-16 01:07:56 +08:00
}
2016-12-15 01:39:44 +08:00
2017-06-18 18:11:21 +08:00
impl<'a> Resettable for PacketBuffer<'a> {
fn reset(&mut self) {
self.endpoint = Default::default();
self.size = 0;
}
}
impl<'a> PacketBuffer<'a> {
2016-12-16 01:07:56 +08:00
/// Create a buffered packet.
pub fn new<T>(payload: T) -> PacketBuffer<'a>
where T: Into<Managed<'a, [u8]>> {
PacketBuffer {
endpoint: IpEndpoint::default(),
2016-12-16 01:07:56 +08:00
size: 0,
payload: payload.into()
2016-12-16 01:07:56 +08:00
}
}
2016-12-17 13:12:45 +08:00
fn as_ref<'b>(&'b self) -> &'b [u8] {
&self.payload[..self.size]
}
fn as_mut<'b>(&'b mut self) -> &'b mut [u8] {
&mut self.payload[..self.size]
}
2016-12-15 01:39:44 +08:00
}
2016-12-19 03:40:11 +08:00
/// An UDP packet ring buffer.
2017-06-18 18:11:21 +08:00
pub type SocketBuffer<'a, 'b : 'a> = RingBuffer<'a, PacketBuffer<'b>>;
2016-12-15 01:39:44 +08:00
/// An User Datagram Protocol socket.
///
/// An UDP socket is bound to a specific endpoint, and owns transmit and receive
/// packet buffers.
2017-01-12 12:28:34 +08:00
#[derive(Debug)]
2016-12-17 14:27:08 +08:00
pub struct UdpSocket<'a, 'b: 'a> {
endpoint: IpEndpoint,
rx_buffer: SocketBuffer<'a, 'b>,
tx_buffer: SocketBuffer<'a, 'b>,
debug_id: usize
2016-12-15 01:39:44 +08:00
}
2016-12-17 14:27:08 +08:00
impl<'a, 'b> UdpSocket<'a, 'b> {
2016-12-15 01:39:44 +08:00
/// Create an UDP socket with the given buffers.
2017-01-11 13:25:54 +08:00
pub fn new(rx_buffer: SocketBuffer<'a, 'b>,
tx_buffer: SocketBuffer<'a, 'b>) -> Socket<'a, 'b> {
2016-12-23 15:30:57 +08:00
Socket::Udp(UdpSocket {
endpoint: IpEndpoint::default(),
2016-12-15 01:39:44 +08:00
rx_buffer: rx_buffer,
tx_buffer: tx_buffer,
debug_id: 0
2016-12-17 13:12:45 +08:00
})
2016-12-15 01:39:44 +08:00
}
/// Return the debug identifier.
#[inline]
pub fn debug_id(&self) -> usize {
self.debug_id
}
/// Set the debug identifier.
///
/// The debug identifier is a number printed in socket trace messages.
/// It could as well be used by the user code.
pub fn set_debug_id(&mut self, id: usize) {
self.debug_id = id
}
/// Return the bound endpoint.
#[inline]
pub fn endpoint(&self) -> IpEndpoint {
self.endpoint
}
/// Bind the socket to the given endpoint.
pub fn bind<T: Into<IpEndpoint>>(&mut self, endpoint: T) {
self.endpoint = endpoint.into()
}
/// Check whether the transmit buffer is full.
#[inline]
pub fn can_send(&self) -> bool {
!self.tx_buffer.full()
}
/// Check whether the receive buffer is not empty.
#[inline]
pub fn can_recv(&self) -> bool {
!self.rx_buffer.empty()
}
2016-12-16 01:07:56 +08:00
/// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
/// to its payload.
2016-12-15 01:39:44 +08:00
///
/// This function returns `Err(Error::Exhausted)` if the size is greater than
/// the transmit packet buffer size.
pub fn send(&mut self, size: usize, endpoint: IpEndpoint) -> Result<&mut [u8]> {
2017-06-25 00:34:32 +08:00
let packet_buf = self.tx_buffer.enqueue()?;
2016-12-16 01:07:56 +08:00
packet_buf.endpoint = endpoint;
packet_buf.size = size;
net_trace!("[{}]{}:{}: buffer to send {} octets",
self.debug_id, self.endpoint,
packet_buf.endpoint, packet_buf.size);
2016-12-17 13:12:45 +08:00
Ok(&mut packet_buf.as_mut()[..size])
}
/// Enqueue a packet to be sent to a given remote endpoint, and fill it from a slice.
2016-12-17 13:12:45 +08:00
///
/// See also [send](#method.send).
pub fn send_slice(&mut self, data: &[u8], endpoint: IpEndpoint) -> Result<usize> {
2017-06-25 00:34:32 +08:00
let buffer = self.send(data.len(), endpoint)?;
let data = &data[..buffer.len()];
buffer.copy_from_slice(data);
Ok(data.len())
2016-12-15 01:39:44 +08:00
}
2016-12-16 01:07:56 +08:00
/// Dequeue a packet received from a remote endpoint, and return the endpoint as well
/// as a pointer to the payload.
2016-12-15 01:39:44 +08:00
///
/// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
pub fn recv(&mut self) -> Result<(&[u8], IpEndpoint)> {
2017-06-25 00:34:32 +08:00
let packet_buf = self.rx_buffer.dequeue()?;
net_trace!("[{}]{}:{}: receive {} buffered octets",
self.debug_id, self.endpoint,
packet_buf.endpoint, packet_buf.size);
Ok((&packet_buf.as_ref()[..packet_buf.size], packet_buf.endpoint))
2016-12-17 13:12:45 +08:00
}
/// Dequeue a packet received from a remote endpoint, and return the endpoint as well
/// as copy the payload into the given slice.
///
/// See also [recv](#method.recv).
pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(usize, IpEndpoint)> {
2017-06-25 00:34:32 +08:00
let (buffer, endpoint) = self.recv()?;
2016-12-17 13:12:45 +08:00
data[..buffer.len()].copy_from_slice(buffer);
Ok((buffer.len(), endpoint))
2016-12-15 01:39:44 +08:00
}
pub(crate) fn process(&mut self, _timestamp: u64, ip_repr: &IpRepr,
payload: &[u8]) -> Result<()> {
debug_assert!(ip_repr.protocol() == IpProtocol::Udp);
2017-06-25 00:34:32 +08:00
let packet = UdpPacket::new_checked(&payload[..ip_repr.payload_len()])?;
let repr = UdpRepr::parse(&packet, &ip_repr.src_addr(), &ip_repr.dst_addr())?;
2016-12-15 01:39:44 +08:00
if repr.dst_port != self.endpoint.port { return Err(Error::Rejected) }
if !self.endpoint.addr.is_unspecified() {
if self.endpoint.addr != ip_repr.dst_addr() { return Err(Error::Rejected) }
2016-12-15 01:39:44 +08:00
}
let packet_buf = self.rx_buffer.enqueue()?;
packet_buf.endpoint = IpEndpoint { addr: ip_repr.src_addr(), port: repr.src_port };
2016-12-16 01:07:56 +08:00
packet_buf.size = repr.payload.len();
2016-12-17 13:12:45 +08:00
packet_buf.as_mut()[..repr.payload.len()].copy_from_slice(repr.payload);
net_trace!("[{}]{}:{}: receiving {} octets",
self.debug_id, self.endpoint,
packet_buf.endpoint, packet_buf.size);
2016-12-16 01:07:56 +08:00
Ok(())
2016-12-15 01:39:44 +08:00
}
pub(crate) fn dispatch<F, R>(&mut self, _timestamp: u64, _limits: &DeviceLimits,
emit: &mut F) -> Result<R>
where F: FnMut(&IpRepr, &IpPayload) -> Result<R> {
let packet_buf = self.tx_buffer.dequeue()?;
net_trace!("[{}]{}:{}: sending {} octets",
self.debug_id, self.endpoint,
packet_buf.endpoint, packet_buf.size);
let repr = UdpRepr {
src_port: self.endpoint.port,
dst_port: packet_buf.endpoint.port,
payload: &packet_buf.as_ref()[..]
};
let ip_repr = IpRepr::Unspecified {
src_addr: self.endpoint.addr,
dst_addr: packet_buf.endpoint.addr,
protocol: IpProtocol::Udp,
payload_len: repr.buffer_len()
};
emit(&ip_repr, &repr)
2016-12-15 01:39:44 +08:00
}
}
impl<'a> IpPayload for UdpRepr<'a> {
2016-12-20 07:50:04 +08:00
fn buffer_len(&self) -> usize {
self.buffer_len()
}
fn emit(&self, repr: &IpRepr, payload: &mut [u8]) {
let mut packet = UdpPacket::new(payload);
self.emit(&mut packet, &repr.src_addr(), &repr.dst_addr())
}
}