raw.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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>) -> Socket<'a, 'b> {
  67. Socket::Raw(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. #[cfg(test)]
  227. mod test {
  228. use wire::IpRepr;
  229. #[cfg(feature = "proto-ipv4")]
  230. use wire::{Ipv4Address, Ipv4Repr};
  231. #[cfg(feature = "proto-ipv6")]
  232. use wire::{Ipv6Address, Ipv6Repr};
  233. use super::*;
  234. fn buffer(packets: usize) -> SocketBuffer<'static, 'static> {
  235. let mut storage = vec![];
  236. for _ in 0..packets {
  237. storage.push(PacketBuffer::new(vec![0; 48]))
  238. }
  239. SocketBuffer::new(storage)
  240. }
  241. #[cfg(feature = "proto-ipv4")]
  242. mod ipv4_locals {
  243. use super::*;
  244. pub fn socket(rx_buffer: SocketBuffer<'static, 'static>,
  245. tx_buffer: SocketBuffer<'static, 'static>)
  246. -> RawSocket<'static, 'static> {
  247. match RawSocket::new(IpVersion::Ipv4, IpProtocol::Unknown(IP_PROTO),
  248. rx_buffer, tx_buffer) {
  249. Socket::Raw(socket) => socket,
  250. _ => unreachable!()
  251. }
  252. }
  253. pub const IP_PROTO: u8 = 63;
  254. pub const HEADER_REPR: IpRepr = IpRepr::Ipv4(Ipv4Repr {
  255. src_addr: Ipv4Address([10, 0, 0, 1]),
  256. dst_addr: Ipv4Address([10, 0, 0, 2]),
  257. protocol: IpProtocol::Unknown(IP_PROTO),
  258. payload_len: 4,
  259. hop_limit: 64
  260. });
  261. pub const PACKET_BYTES: [u8; 24] = [
  262. 0x45, 0x00, 0x00, 0x18,
  263. 0x00, 0x00, 0x40, 0x00,
  264. 0x40, 0x3f, 0x00, 0x00,
  265. 0x0a, 0x00, 0x00, 0x01,
  266. 0x0a, 0x00, 0x00, 0x02,
  267. 0xaa, 0x00, 0x00, 0xff
  268. ];
  269. pub const PACKET_PAYLOAD: [u8; 4] = [
  270. 0xaa, 0x00, 0x00, 0xff
  271. ];
  272. }
  273. #[cfg(feature = "proto-ipv6")]
  274. mod ipv6_locals {
  275. use super::*;
  276. pub fn socket(rx_buffer: SocketBuffer<'static, 'static>,
  277. tx_buffer: SocketBuffer<'static, 'static>)
  278. -> RawSocket<'static, 'static> {
  279. match RawSocket::new(IpVersion::Ipv6, IpProtocol::Unknown(IP_PROTO),
  280. rx_buffer, tx_buffer) {
  281. Socket::Raw(socket) => socket,
  282. _ => unreachable!()
  283. }
  284. }
  285. pub const IP_PROTO: u8 = 63;
  286. pub const HEADER_REPR: IpRepr = IpRepr::Ipv6(Ipv6Repr {
  287. src_addr: Ipv6Address([0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  288. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]),
  289. dst_addr: Ipv6Address([0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  290. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02]),
  291. next_header: IpProtocol::Unknown(IP_PROTO),
  292. payload_len: 4,
  293. hop_limit: 64
  294. });
  295. pub const PACKET_BYTES: [u8; 44] = [
  296. 0x60, 0x00, 0x00, 0x00,
  297. 0x00, 0x04, 0x3f, 0x40,
  298. 0xfe, 0x80, 0x00, 0x00,
  299. 0x00, 0x00, 0x00, 0x00,
  300. 0x00, 0x00, 0x00, 0x00,
  301. 0x00, 0x00, 0x00, 0x01,
  302. 0xfe, 0x80, 0x00, 0x00,
  303. 0x00, 0x00, 0x00, 0x00,
  304. 0x00, 0x00, 0x00, 0x00,
  305. 0x00, 0x00, 0x00, 0x02,
  306. 0xaa, 0x00, 0x00, 0xff
  307. ];
  308. pub const PACKET_PAYLOAD: [u8; 4] = [
  309. 0xaa, 0x00, 0x00, 0xff
  310. ];
  311. }
  312. macro_rules! reusable_ip_specific_tests {
  313. ($module:ident, $socket:path, $hdr:path, $packet:path, $payload:path) => {
  314. mod $module {
  315. use super::*;
  316. #[test]
  317. fn test_send_truncated() {
  318. let mut socket = $socket(buffer(0), buffer(1));
  319. assert_eq!(socket.send_slice(&[0; 56][..]), Err(Error::Truncated));
  320. }
  321. #[test]
  322. fn test_send_dispatch() {
  323. let checksum_caps = &ChecksumCapabilities::default();
  324. let mut socket = $socket(buffer(0), buffer(1));
  325. assert!(socket.can_send());
  326. assert_eq!(socket.dispatch(&checksum_caps, |_| unreachable!()),
  327. Err(Error::Exhausted));
  328. assert_eq!(socket.send_slice(&$packet[..]), Ok(()));
  329. assert_eq!(socket.send_slice(b""), Err(Error::Exhausted));
  330. assert!(!socket.can_send());
  331. assert_eq!(socket.dispatch(&checksum_caps, |(ip_repr, ip_payload)| {
  332. assert_eq!(ip_repr, $hdr);
  333. assert_eq!(ip_payload, &$payload);
  334. Err(Error::Unaddressable)
  335. }), Err(Error::Unaddressable));
  336. assert!(!socket.can_send());
  337. assert_eq!(socket.dispatch(&checksum_caps, |(ip_repr, ip_payload)| {
  338. assert_eq!(ip_repr, $hdr);
  339. assert_eq!(ip_payload, &$payload);
  340. Ok(())
  341. }), Ok(()));
  342. assert!(socket.can_send());
  343. }
  344. #[test]
  345. fn test_recv_truncated_slice() {
  346. let mut socket = $socket(buffer(1), buffer(0));
  347. assert!(socket.accepts(&$hdr));
  348. assert_eq!(socket.process(&$hdr, &$payload,
  349. &ChecksumCapabilities::default()), Ok(()));
  350. let mut slice = [0; 4];
  351. assert_eq!(socket.recv_slice(&mut slice[..]), Ok(4));
  352. assert_eq!(&slice, &$packet[..slice.len()]);
  353. }
  354. #[test]
  355. fn test_recv_truncated_packet() {
  356. let mut socket = $socket(buffer(1), buffer(0));
  357. let mut buffer = vec![0; 128];
  358. buffer[..$packet.len()].copy_from_slice(&$packet[..]);
  359. assert!(socket.accepts(&$hdr));
  360. assert_eq!(socket.process(&$hdr, &buffer, &ChecksumCapabilities::default()),
  361. Err(Error::Truncated));
  362. }
  363. }
  364. }
  365. }
  366. #[cfg(feature = "proto-ipv4")]
  367. reusable_ip_specific_tests!(ipv4, ipv4_locals::socket, ipv4_locals::HEADER_REPR,
  368. ipv4_locals::PACKET_BYTES, ipv4_locals::PACKET_PAYLOAD);
  369. #[cfg(feature = "proto-ipv6")]
  370. reusable_ip_specific_tests!(ipv6, ipv6_locals::socket, ipv6_locals::HEADER_REPR,
  371. ipv6_locals::PACKET_BYTES, ipv6_locals::PACKET_PAYLOAD);
  372. #[test]
  373. #[cfg(feature = "proto-ipv4")]
  374. fn test_send_illegal() {
  375. let checksum_caps = &ChecksumCapabilities::default();
  376. #[cfg(feature = "proto-ipv4")]
  377. {
  378. let mut socket = ipv4_locals::socket(buffer(0), buffer(1));
  379. let mut wrong_version = ipv4_locals::PACKET_BYTES.clone();
  380. Ipv4Packet::new(&mut wrong_version).set_version(6);
  381. assert_eq!(socket.send_slice(&wrong_version[..]), Ok(()));
  382. assert_eq!(socket.dispatch(&checksum_caps, |_| unreachable!()),
  383. Ok(()));
  384. let mut wrong_protocol = ipv4_locals::PACKET_BYTES.clone();
  385. Ipv4Packet::new(&mut wrong_protocol).set_protocol(IpProtocol::Tcp);
  386. assert_eq!(socket.send_slice(&wrong_protocol[..]), Ok(()));
  387. assert_eq!(socket.dispatch(&checksum_caps, |_| unreachable!()),
  388. Ok(()));
  389. }
  390. #[cfg(feature = "proto-ipv6")]
  391. {
  392. let mut socket = ipv6_locals::socket(buffer(0), buffer(1));
  393. let mut wrong_version = ipv6_locals::PACKET_BYTES.clone();
  394. Ipv6Packet::new(&mut wrong_version[..]).set_version(4);
  395. assert_eq!(socket.send_slice(&wrong_version[..]), Ok(()));
  396. assert_eq!(socket.dispatch(&checksum_caps, |_| unreachable!()),
  397. Ok(()));
  398. let mut wrong_protocol = ipv6_locals::PACKET_BYTES.clone();
  399. Ipv6Packet::new(&mut wrong_protocol[..]).set_next_header(IpProtocol::Tcp);
  400. assert_eq!(socket.send_slice(&wrong_protocol[..]), Ok(()));
  401. assert_eq!(socket.dispatch(&checksum_caps, |_| unreachable!()),
  402. Ok(()));
  403. }
  404. }
  405. #[test]
  406. fn test_recv_process() {
  407. #[cfg(feature = "proto-ipv4")]
  408. {
  409. let mut socket = ipv4_locals::socket(buffer(1), buffer(0));
  410. assert!(!socket.can_recv());
  411. let mut cksumd_packet = ipv4_locals::PACKET_BYTES.clone();
  412. Ipv4Packet::new(&mut cksumd_packet).fill_checksum();
  413. assert_eq!(socket.recv(), Err(Error::Exhausted));
  414. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  415. assert_eq!(socket.process(&ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD,
  416. &ChecksumCapabilities::default()),
  417. Ok(()));
  418. assert!(socket.can_recv());
  419. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  420. assert_eq!(socket.process(&ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD,
  421. &ChecksumCapabilities::default()),
  422. Err(Error::Exhausted));
  423. assert_eq!(socket.recv(), Ok(&cksumd_packet[..]));
  424. assert!(!socket.can_recv());
  425. }
  426. #[cfg(feature = "proto-ipv6")]
  427. {
  428. let mut socket = ipv6_locals::socket(buffer(1), buffer(0));
  429. assert!(!socket.can_recv());
  430. assert_eq!(socket.recv(), Err(Error::Exhausted));
  431. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  432. assert_eq!(socket.process(&ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD,
  433. &ChecksumCapabilities::default()),
  434. Ok(()));
  435. assert!(socket.can_recv());
  436. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  437. assert_eq!(socket.process(&ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD,
  438. &ChecksumCapabilities::default()),
  439. Err(Error::Exhausted));
  440. assert_eq!(socket.recv(), Ok(&ipv6_locals::PACKET_BYTES[..]));
  441. assert!(!socket.can_recv());
  442. }
  443. }
  444. #[test]
  445. fn test_doesnt_accept_wrong_proto() {
  446. #[cfg(feature = "proto-ipv4")]
  447. {
  448. let socket = match RawSocket::new(IpVersion::Ipv4,
  449. IpProtocol::Unknown(ipv4_locals::IP_PROTO+1),
  450. buffer(1), buffer(1)) {
  451. Socket::Raw(socket) => socket,
  452. _ => unreachable!()
  453. };
  454. assert!(!socket.accepts(&ipv4_locals::HEADER_REPR));
  455. #[cfg(feature = "proto-ipv6")]
  456. assert!(!socket.accepts(&ipv6_locals::HEADER_REPR));
  457. }
  458. #[cfg(feature = "proto-ipv6")]
  459. {
  460. let socket = match RawSocket::new(IpVersion::Ipv6,
  461. IpProtocol::Unknown(ipv6_locals::IP_PROTO+1),
  462. buffer(1), buffer(1)) {
  463. Socket::Raw(socket) => socket,
  464. _ => unreachable!()
  465. };
  466. assert!(!socket.accepts(&ipv6_locals::HEADER_REPR));
  467. #[cfg(feature = "proto-ipv4")]
  468. assert!(!socket.accepts(&ipv4_locals::HEADER_REPR));
  469. }
  470. }
  471. }