raw.rs 14 KB

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