raw.rs 19 KB

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