raw.rs 13 KB

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