raw.rs 19 KB

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