raw.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. use core::cmp::min;
  2. use managed::Managed;
  3. use {Error, Result};
  4. use phy::DeviceLimits;
  5. use wire::{IpVersion, IpProtocol, Ipv4Repr, Ipv4Packet};
  6. use socket::{IpRepr, IpPayload, Socket};
  7. use storage::{Resettable, RingBuffer};
  8. /// A buffered raw IP packet.
  9. #[derive(Debug)]
  10. pub struct PacketBuffer<'a> {
  11. size: usize,
  12. payload: Managed<'a, [u8]>,
  13. }
  14. impl<'a> PacketBuffer<'a> {
  15. /// Create a buffered packet.
  16. pub fn new<T>(payload: T) -> PacketBuffer<'a>
  17. where T: Into<Managed<'a, [u8]>> {
  18. PacketBuffer {
  19. size: 0,
  20. payload: payload.into(),
  21. }
  22. }
  23. fn as_ref<'b>(&'b self) -> &'b [u8] {
  24. &self.payload[..self.size]
  25. }
  26. fn as_mut<'b>(&'b mut self) -> &'b mut [u8] {
  27. &mut self.payload[..self.size]
  28. }
  29. fn resize<'b>(&'b mut self, size: usize) -> Result<&'b mut Self> {
  30. if self.payload.len() >= size {
  31. self.size = size;
  32. Ok(self)
  33. } else {
  34. Err(Error::Truncated)
  35. }
  36. }
  37. }
  38. impl<'a> Resettable for PacketBuffer<'a> {
  39. fn reset(&mut self) {
  40. self.size = 0;
  41. }
  42. }
  43. /// A raw IP packet ring buffer.
  44. pub type SocketBuffer<'a, 'b: 'a> = RingBuffer<'a, PacketBuffer<'b>>;
  45. /// A raw IP socket.
  46. ///
  47. /// A raw socket is bound to a specific IP protocol, and owns
  48. /// transmit and receive packet buffers.
  49. #[derive(Debug)]
  50. pub struct RawSocket<'a, 'b: 'a> {
  51. debug_id: usize,
  52. ip_version: IpVersion,
  53. ip_protocol: IpProtocol,
  54. rx_buffer: SocketBuffer<'a, 'b>,
  55. tx_buffer: SocketBuffer<'a, 'b>,
  56. }
  57. impl<'a, 'b> RawSocket<'a, 'b> {
  58. /// Create a raw IP socket bound to the given IP version and datagram protocol,
  59. /// with the given buffers.
  60. pub fn new(ip_version: IpVersion, ip_protocol: IpProtocol,
  61. rx_buffer: SocketBuffer<'a, 'b>,
  62. tx_buffer: SocketBuffer<'a, 'b>) -> Socket<'a, 'b> {
  63. Socket::Raw(RawSocket {
  64. debug_id: 0,
  65. ip_version,
  66. ip_protocol,
  67. rx_buffer,
  68. tx_buffer,
  69. })
  70. }
  71. /// Return the debug identifier.
  72. #[inline]
  73. pub fn debug_id(&self) -> usize {
  74. self.debug_id
  75. }
  76. /// Set the debug identifier.
  77. ///
  78. /// The debug identifier is a number printed in socket trace messages.
  79. /// It could as well be used by the user code.
  80. pub fn set_debug_id(&mut self, id: usize) {
  81. self.debug_id = id;
  82. }
  83. /// Return the IP version the socket is bound to.
  84. #[inline]
  85. pub fn ip_version(&self) -> IpVersion {
  86. self.ip_version
  87. }
  88. /// Return the IP protocol the socket is bound to.
  89. #[inline]
  90. pub fn ip_protocol(&self) -> IpProtocol {
  91. self.ip_protocol
  92. }
  93. /// Check whether the transmit buffer is full.
  94. #[inline]
  95. pub fn can_send(&self) -> bool {
  96. !self.tx_buffer.full()
  97. }
  98. /// Check whether the receive buffer is not empty.
  99. #[inline]
  100. pub fn can_recv(&self) -> bool {
  101. !self.rx_buffer.empty()
  102. }
  103. /// Enqueue a packet to send, and return a pointer to its payload.
  104. ///
  105. /// This function returns `Err(Error::Exhausted)` if the size is greater than
  106. /// the transmit packet buffer size.
  107. ///
  108. /// If the buffer is filled in a way that does not match the socket's
  109. /// IP version or protocol, the packet will be silently dropped.
  110. ///
  111. /// **Note:** The IP header is parsed and reserialized, and may not match
  112. /// the header actually transmitted bit for bit.
  113. pub fn send(&mut self, size: usize) -> Result<&mut [u8]> {
  114. let packet_buf = self.tx_buffer.try_enqueue(|buf| buf.resize(size))?;
  115. net_trace!("[{}]:{}:{}: buffer to send {} octets",
  116. self.debug_id, self.ip_version, self.ip_protocol,
  117. packet_buf.size);
  118. Ok(packet_buf.as_mut())
  119. }
  120. /// Enqueue a packet to send, and fill it from a slice.
  121. ///
  122. /// See also [send](#method.send).
  123. pub fn send_slice(&mut self, data: &[u8]) -> Result<()> {
  124. self.send(data.len())?.copy_from_slice(data);
  125. Ok(())
  126. }
  127. /// Dequeue a packet, and return a pointer to the payload.
  128. ///
  129. /// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
  130. ///
  131. /// **Note:** The IP header is parsed and reserialized, and may not match
  132. /// the header actually received bit for bit.
  133. pub fn recv(&mut self) -> Result<&[u8]> {
  134. let packet_buf = self.rx_buffer.dequeue()?;
  135. net_trace!("[{}]:{}:{}: receive {} buffered octets",
  136. self.debug_id, self.ip_version, self.ip_protocol,
  137. packet_buf.size);
  138. Ok(&packet_buf.as_ref())
  139. }
  140. /// Dequeue a packet, and copy the payload into the given slice.
  141. ///
  142. /// See also [recv](#method.recv).
  143. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  144. let buffer = self.recv()?;
  145. let length = min(data.len(), buffer.len());
  146. data[..length].copy_from_slice(&buffer[..length]);
  147. Ok(length)
  148. }
  149. pub(crate) fn process(&mut self, _timestamp: u64, ip_repr: &IpRepr,
  150. payload: &[u8]) -> Result<()> {
  151. if ip_repr.version() != self.ip_version { return Err(Error::Rejected) }
  152. if ip_repr.protocol() != self.ip_protocol { return Err(Error::Rejected) }
  153. let header_len = ip_repr.buffer_len();
  154. let total_len = header_len + payload.len();
  155. let packet_buf = self.rx_buffer.try_enqueue(|buf| buf.resize(total_len))?;
  156. ip_repr.emit(&mut packet_buf.as_mut()[..header_len]);
  157. packet_buf.as_mut()[header_len..].copy_from_slice(payload);
  158. net_trace!("[{}]:{}:{}: receiving {} octets",
  159. self.debug_id, self.ip_version, self.ip_protocol,
  160. packet_buf.size);
  161. Ok(())
  162. }
  163. pub(crate) fn dispatch<F, R>(&mut self, _timestamp: u64, _limits: &DeviceLimits,
  164. emit: F) -> Result<R>
  165. where F: FnOnce(&IpRepr, &IpPayload) -> Result<R> {
  166. fn prepare(protocol: IpProtocol, buffer: &mut [u8]) -> Result<(IpRepr, RawRepr)> {
  167. match IpVersion::of_packet(buffer.as_ref())? {
  168. IpVersion::Ipv4 => {
  169. let mut packet = Ipv4Packet::new_checked(buffer.as_mut())?;
  170. if packet.protocol() != protocol { return Err(Error::Unaddressable) }
  171. packet.fill_checksum();
  172. let packet = Ipv4Packet::new(&*packet.into_inner());
  173. let ipv4_repr = Ipv4Repr::parse(&packet)?;
  174. let raw_repr = RawRepr(packet.payload());
  175. Ok((IpRepr::Ipv4(ipv4_repr), raw_repr))
  176. }
  177. IpVersion::Unspecified => unreachable!(),
  178. IpVersion::__Nonexhaustive => unreachable!()
  179. }
  180. }
  181. let mut packet_buf = self.tx_buffer.dequeue()?;
  182. match prepare(self.ip_protocol, packet_buf.as_mut()) {
  183. Ok((ip_repr, raw_repr)) => {
  184. net_trace!("[{}]:{}:{}: sending {} octets",
  185. self.debug_id, self.ip_version, self.ip_protocol,
  186. ip_repr.buffer_len() + raw_repr.buffer_len());
  187. emit(&ip_repr, &raw_repr)
  188. }
  189. Err(error) => {
  190. net_trace!("[{}]:{}:{}: dropping outgoing packet ({})",
  191. self.debug_id, self.ip_version, self.ip_protocol,
  192. error);
  193. // This case is a bit special because in every other socket, no matter what data
  194. // is put into the socket, it can be sent, but it's possible to put data into
  195. // a raw socket that may not be, and we're generic over the result type, so
  196. // we can't possibly return Ok(()) here.
  197. Err(Error::Rejected)
  198. }
  199. }
  200. }
  201. }
  202. struct RawRepr<'a>(&'a [u8]);
  203. impl<'a> IpPayload for RawRepr<'a> {
  204. fn buffer_len(&self) -> usize {
  205. self.0.len()
  206. }
  207. fn emit(&self, _repr: &IpRepr, payload: &mut [u8]) {
  208. payload.copy_from_slice(self.0);
  209. }
  210. }
  211. #[cfg(test)]
  212. mod test {
  213. use wire::{Ipv4Address, IpRepr, Ipv4Repr};
  214. use super::*;
  215. fn buffer(packets: usize) -> SocketBuffer<'static, 'static> {
  216. let mut storage = vec![];
  217. for _ in 0..packets {
  218. storage.push(PacketBuffer::new(vec![0; 24]))
  219. }
  220. SocketBuffer::new(storage)
  221. }
  222. fn socket(rx_buffer: SocketBuffer<'static, 'static>,
  223. tx_buffer: SocketBuffer<'static, 'static>)
  224. -> RawSocket<'static, 'static> {
  225. match RawSocket::new(IpVersion::Ipv4, IpProtocol::Unknown(63),
  226. rx_buffer, tx_buffer) {
  227. Socket::Raw(socket) => socket,
  228. _ => unreachable!()
  229. }
  230. }
  231. const HEADER_REPR: IpRepr = IpRepr::Ipv4(Ipv4Repr {
  232. src_addr: Ipv4Address([10, 0, 0, 1]),
  233. dst_addr: Ipv4Address([10, 0, 0, 2]),
  234. protocol: IpProtocol::Unknown(63),
  235. payload_len: 4
  236. });
  237. const PACKET_BYTES: [u8; 24] = [
  238. 0x45, 0x00, 0x00, 0x18,
  239. 0x00, 0x00, 0x40, 0x00,
  240. 0x40, 0x3f, 0x00, 0x00,
  241. 0x0a, 0x00, 0x00, 0x01,
  242. 0x0a, 0x00, 0x00, 0x02,
  243. 0xaa, 0x00, 0x00, 0xff
  244. ];
  245. const PACKET_PAYLOAD: [u8; 4] = [
  246. 0xaa, 0x00, 0x00, 0xff
  247. ];
  248. #[test]
  249. fn test_send_truncated() {
  250. let mut socket = socket(buffer(0), buffer(1));
  251. assert_eq!(socket.send_slice(&[0; 32][..]), Err(Error::Truncated));
  252. }
  253. #[test]
  254. fn test_send_dispatch() {
  255. let limits = DeviceLimits::default();
  256. let mut socket = socket(buffer(0), buffer(1));
  257. assert!(socket.can_send());
  258. assert_eq!(socket.dispatch(0, &limits, |_ip_repr, _ip_payload| {
  259. unreachable!()
  260. }), Err(Error::Exhausted) as Result<()>);
  261. assert_eq!(socket.send_slice(&PACKET_BYTES[..]), Ok(()));
  262. assert_eq!(socket.send_slice(b""), Err(Error::Exhausted));
  263. assert!(!socket.can_send());
  264. macro_rules! assert_payload_eq {
  265. ($ip_repr:expr, $ip_payload:expr, $expected:expr) => {{
  266. let mut buffer = vec![0; $ip_payload.buffer_len()];
  267. $ip_payload.emit(&$ip_repr, &mut buffer);
  268. assert_eq!(&buffer[..], &$expected[$ip_repr.buffer_len()..]);
  269. }}
  270. }
  271. assert_eq!(socket.dispatch(0, &limits, |ip_repr, ip_payload| {
  272. assert_eq!(ip_repr, &HEADER_REPR);
  273. assert_payload_eq!(ip_repr, ip_payload, PACKET_BYTES);
  274. Err(Error::Unaddressable)
  275. }), Err(Error::Unaddressable) as Result<()>);
  276. /*assert!(!socket.can_send());*/
  277. assert_eq!(socket.dispatch(0, &limits, |ip_repr, ip_payload| {
  278. assert_eq!(ip_repr, &HEADER_REPR);
  279. assert_payload_eq!(ip_repr, ip_payload, PACKET_BYTES);
  280. Ok(())
  281. }), /*Ok(())*/ Err(Error::Exhausted));
  282. assert!(socket.can_send());
  283. }
  284. #[test]
  285. fn test_send_illegal() {
  286. let limits = DeviceLimits::default();
  287. let mut socket = socket(buffer(0), buffer(1));
  288. let mut wrong_version = PACKET_BYTES.clone();
  289. Ipv4Packet::new(&mut wrong_version).set_version(5);
  290. assert_eq!(socket.send_slice(&wrong_version[..]), Ok(()));
  291. assert_eq!(socket.dispatch(0, &limits, |_ip_repr, _ip_payload| {
  292. unreachable!()
  293. }), Err(Error::Rejected) as Result<()>);
  294. let mut wrong_protocol = PACKET_BYTES.clone();
  295. Ipv4Packet::new(&mut wrong_protocol).set_protocol(IpProtocol::Tcp);
  296. assert_eq!(socket.send_slice(&wrong_protocol[..]), Ok(()));
  297. assert_eq!(socket.dispatch(0, &limits, |_ip_repr, _ip_payload| {
  298. unreachable!()
  299. }), Err(Error::Rejected) as Result<()>);
  300. }
  301. #[test]
  302. fn test_recv_process() {
  303. let mut socket = socket(buffer(1), buffer(0));
  304. assert!(!socket.can_recv());
  305. let mut cksumd_packet = PACKET_BYTES.clone();
  306. Ipv4Packet::new(&mut cksumd_packet).fill_checksum();
  307. assert_eq!(socket.recv(), Err(Error::Exhausted));
  308. assert_eq!(socket.process(0, &HEADER_REPR, &PACKET_PAYLOAD),
  309. Ok(()));
  310. assert!(socket.can_recv());
  311. assert_eq!(socket.process(0, &HEADER_REPR, &PACKET_PAYLOAD),
  312. Err(Error::Exhausted));
  313. assert_eq!(socket.recv(), Ok(&cksumd_packet[..]));
  314. assert!(!socket.can_recv());
  315. }
  316. #[test]
  317. fn test_recv_truncated_slice() {
  318. let mut socket = socket(buffer(1), buffer(0));
  319. assert_eq!(socket.process(0, &HEADER_REPR, &PACKET_PAYLOAD),
  320. Ok(()));
  321. let mut slice = [0; 4];
  322. assert_eq!(socket.recv_slice(&mut slice[..]), Ok(4));
  323. assert_eq!(&slice, &PACKET_BYTES[..slice.len()]);
  324. }
  325. #[test]
  326. fn test_recv_truncated_packet() {
  327. let mut socket = socket(buffer(1), buffer(0));
  328. let mut buffer = vec![0; 128];
  329. buffer[..PACKET_BYTES.len()].copy_from_slice(&PACKET_BYTES[..]);
  330. assert_eq!(socket.process(0, &HEADER_REPR, &buffer),
  331. Err(Error::Truncated));
  332. }
  333. }