raw.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. use managed::Managed;
  2. use Error;
  3. use phy::DeviceLimits;
  4. use wire::{IpVersion, IpProtocol, Ipv4Repr, Ipv4Packet};
  5. use socket::{IpRepr, IpPayload, Socket};
  6. use storage::{Resettable, RingBuffer};
  7. /// A buffered raw IP packet.
  8. #[derive(Debug)]
  9. pub struct PacketBuffer<'a> {
  10. size: usize,
  11. payload: Managed<'a, [u8]>,
  12. }
  13. impl<'a> PacketBuffer<'a> {
  14. /// Create a buffered packet.
  15. pub fn new<T>(payload: T) -> PacketBuffer<'a>
  16. where T: Into<Managed<'a, [u8]>> {
  17. PacketBuffer {
  18. size: 0,
  19. payload: payload.into(),
  20. }
  21. }
  22. fn as_ref<'b>(&'b self) -> &'b [u8] {
  23. &self.payload[..self.size]
  24. }
  25. fn as_mut<'b>(&'b mut self) -> &'b mut [u8] {
  26. &mut self.payload[..self.size]
  27. }
  28. }
  29. impl<'a> Resettable for PacketBuffer<'a> {
  30. fn reset(&mut self) {
  31. self.size = 0;
  32. }
  33. }
  34. /// A raw IP packet ring buffer.
  35. pub type SocketBuffer<'a, 'b: 'a> = RingBuffer<'a, PacketBuffer<'b>>;
  36. /// A raw IP socket.
  37. ///
  38. /// A raw socket is bound to a specific IP protocol, and owns
  39. /// transmit and receive packet buffers.
  40. #[derive(Debug)]
  41. pub struct RawSocket<'a, 'b: 'a> {
  42. ip_version: IpVersion,
  43. ip_protocol: IpProtocol,
  44. rx_buffer: SocketBuffer<'a, 'b>,
  45. tx_buffer: SocketBuffer<'a, 'b>,
  46. debug_id: usize,
  47. }
  48. impl<'a, 'b> RawSocket<'a, 'b> {
  49. /// Create a raw IP socket bound to the given IP version and datagram protocol,
  50. /// with the given buffers.
  51. pub fn new(ip_version: IpVersion, ip_protocol: IpProtocol,
  52. rx_buffer: SocketBuffer<'a, 'b>,
  53. tx_buffer: SocketBuffer<'a, 'b>) -> Socket<'a, 'b> {
  54. Socket::Raw(RawSocket {
  55. ip_version,
  56. ip_protocol,
  57. rx_buffer,
  58. tx_buffer,
  59. debug_id: 0,
  60. })
  61. }
  62. /// Return the debug identifier.
  63. #[inline]
  64. pub fn debug_id(&self) -> usize {
  65. self.debug_id
  66. }
  67. /// Set the debug identifier.
  68. ///
  69. /// The debug identifier is a number printed in socket trace messages.
  70. /// It could as well be used by the user code.
  71. pub fn set_debug_id(&mut self, id: usize) {
  72. self.debug_id = id;
  73. }
  74. /// Return the IP version the socket is bound to.
  75. #[inline]
  76. pub fn ip_version(&self) -> IpVersion {
  77. self.ip_version
  78. }
  79. /// Return the IP protocol the socket is bound to.
  80. #[inline]
  81. pub fn ip_protocol(&self) -> IpProtocol {
  82. self.ip_protocol
  83. }
  84. /// Check whether the transmit buffer is full.
  85. #[inline]
  86. pub fn can_send(&self) -> bool {
  87. !self.tx_buffer.full()
  88. }
  89. /// Check whether the receive buffer is not empty.
  90. #[inline]
  91. pub fn can_recv(&self) -> bool {
  92. !self.rx_buffer.empty()
  93. }
  94. /// Enqueue a packet to send, and return a pointer to its payload.
  95. ///
  96. /// This function returns `Err(())` if the size is greater than what
  97. /// the transmit buffer can accomodate.
  98. pub fn send(&mut self, size: usize) -> Result<&mut [u8], ()> {
  99. let packet_buf = self.tx_buffer.enqueue()?;
  100. packet_buf.size = size;
  101. net_trace!("[{}]:{}:{}: buffer to send {} octets",
  102. self.debug_id, self.ip_version, self.ip_protocol,
  103. packet_buf.size);
  104. Ok(&mut packet_buf.as_mut()[..size])
  105. }
  106. /// Enqueue a packet to send, and fill it from a slice.
  107. ///
  108. /// See also [send](#method.send).
  109. pub fn send_slice(&mut self, data: &[u8]) -> Result<usize, ()> {
  110. let buffer = self.send(data.len())?;
  111. let data = &data[..buffer.len()];
  112. buffer.copy_from_slice(data);
  113. Ok(data.len())
  114. }
  115. /// Dequeue a packet, and return a pointer to the payload.
  116. ///
  117. /// This function returns `Err(())` if the receive buffer is empty.
  118. pub fn recv(&mut self) -> Result<&[u8], ()> {
  119. let packet_buf = self.rx_buffer.dequeue()?;
  120. net_trace!("[{}]:{}:{}: receive {} buffered octets",
  121. self.debug_id, self.ip_version, self.ip_protocol,
  122. packet_buf.size);
  123. Ok(&packet_buf.as_ref()[..packet_buf.size])
  124. }
  125. /// Dequeue a packet, and copy the payload into the given slice.
  126. ///
  127. /// See also [recv](#method.recv).
  128. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize, ()> {
  129. let buffer = self.recv()?;
  130. data[..buffer.len()].copy_from_slice(buffer);
  131. Ok(buffer.len())
  132. }
  133. pub(crate) fn process(&mut self, _timestamp: u64, ip_repr: &IpRepr,
  134. payload: &[u8]) -> Result<(), Error> {
  135. match self.ip_version {
  136. IpVersion::Ipv4 => {
  137. if ip_repr.protocol() != self.ip_protocol {
  138. return Err(Error::Rejected);
  139. }
  140. let header_len = ip_repr.buffer_len();
  141. let packet_buf = self.rx_buffer.enqueue().map_err(|()| Error::Exhausted)?;
  142. packet_buf.size = header_len + payload.len();
  143. ip_repr.emit(&mut packet_buf.as_mut()[..header_len]);
  144. packet_buf.as_mut()[header_len..header_len + payload.len()]
  145. .copy_from_slice(payload);
  146. net_trace!("[{}]:{}:{}: receiving {} octets",
  147. self.debug_id, self.ip_version, self.ip_protocol,
  148. packet_buf.size);
  149. Ok(())
  150. }
  151. IpVersion::__Nonexhaustive => unreachable!()
  152. }
  153. }
  154. /// See [Socket::dispatch](enum.Socket.html#method.dispatch).
  155. pub(crate) fn dispatch<F, R>(&mut self, _timestamp: u64, _limits: &DeviceLimits,
  156. emit: &mut F) -> Result<R, Error>
  157. where F: FnMut(&IpRepr, &IpPayload) -> Result<R, Error> {
  158. let mut packet_buf = self.tx_buffer.dequeue().map_err(|()| Error::Exhausted)?;
  159. net_trace!("[{}]:{}:{}: sending {} octets",
  160. self.debug_id, self.ip_version, self.ip_protocol,
  161. packet_buf.size);
  162. match self.ip_version {
  163. IpVersion::Ipv4 => {
  164. let mut ipv4_packet = Ipv4Packet::new_checked(packet_buf.as_mut())?;
  165. ipv4_packet.fill_checksum();
  166. let ipv4_packet = Ipv4Packet::new(&*ipv4_packet.into_inner());
  167. let raw_repr = RawRepr(ipv4_packet.payload());
  168. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet)?;
  169. emit(&IpRepr::Ipv4(ipv4_repr), &raw_repr)
  170. }
  171. IpVersion::__Nonexhaustive => unreachable!()
  172. }
  173. }
  174. }
  175. struct RawRepr<'a>(&'a [u8]);
  176. impl<'a> IpPayload for RawRepr<'a> {
  177. fn buffer_len(&self) -> usize {
  178. self.0.len()
  179. }
  180. fn emit(&self, _repr: &IpRepr, payload: &mut [u8]) {
  181. payload.copy_from_slice(self.0);
  182. }
  183. }
  184. #[cfg(test)]
  185. mod test {
  186. use super::*;
  187. #[test]
  188. pub fn test_buffer() {
  189. let mut storage = vec![];
  190. for _ in 0..5 {
  191. storage.push(PacketBuffer::new(vec![0]))
  192. }
  193. let mut buffer = SocketBuffer::new(&mut storage[..]);
  194. assert_eq!(buffer.empty(), true);
  195. assert_eq!(buffer.full(), false);
  196. buffer.enqueue().unwrap().size = 1;
  197. assert_eq!(buffer.empty(), false);
  198. assert_eq!(buffer.full(), false);
  199. buffer.enqueue().unwrap().size = 2;
  200. buffer.enqueue().unwrap().size = 3;
  201. assert_eq!(buffer.dequeue().unwrap().size, 1);
  202. assert_eq!(buffer.dequeue().unwrap().size, 2);
  203. buffer.enqueue().unwrap().size = 4;
  204. buffer.enqueue().unwrap().size = 5;
  205. buffer.enqueue().unwrap().size = 6;
  206. buffer.enqueue().unwrap().size = 7;
  207. assert_eq!(buffer.enqueue().unwrap_err(), ());
  208. assert_eq!(buffer.empty(), false);
  209. assert_eq!(buffer.full(), true);
  210. assert_eq!(buffer.dequeue().unwrap().size, 3);
  211. assert_eq!(buffer.dequeue().unwrap().size, 4);
  212. assert_eq!(buffer.dequeue().unwrap().size, 5);
  213. assert_eq!(buffer.dequeue().unwrap().size, 6);
  214. assert_eq!(buffer.dequeue().unwrap().size, 7);
  215. assert_eq!(buffer.dequeue().unwrap_err(), ());
  216. assert_eq!(buffer.empty(), true);
  217. assert_eq!(buffer.full(), false);
  218. }
  219. }