raw.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. use core::cmp::min;
  2. #[cfg(feature = "async")]
  3. use core::task::Waker;
  4. use crate::iface::Context;
  5. use crate::socket::PollAt;
  6. #[cfg(feature = "async")]
  7. use crate::socket::WakerRegistration;
  8. use crate::storage::Empty;
  9. use crate::wire::{IpProtocol, IpRepr, IpVersion};
  10. #[cfg(feature = "proto-ipv4")]
  11. use crate::wire::{Ipv4Packet, Ipv4Repr};
  12. #[cfg(feature = "proto-ipv6")]
  13. use crate::wire::{Ipv6Packet, Ipv6Repr};
  14. /// Error returned by [`Socket::bind`]
  15. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  16. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  17. pub enum BindError {
  18. InvalidState,
  19. Unaddressable,
  20. }
  21. impl core::fmt::Display for BindError {
  22. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
  23. match self {
  24. BindError::InvalidState => write!(f, "invalid state"),
  25. BindError::Unaddressable => write!(f, "unaddressable"),
  26. }
  27. }
  28. }
  29. #[cfg(feature = "std")]
  30. impl std::error::Error for BindError {}
  31. /// Error returned by [`Socket::send`]
  32. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  33. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  34. pub enum SendError {
  35. BufferFull,
  36. }
  37. impl core::fmt::Display for SendError {
  38. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
  39. match self {
  40. SendError::BufferFull => write!(f, "buffer full"),
  41. }
  42. }
  43. }
  44. #[cfg(feature = "std")]
  45. impl std::error::Error for SendError {}
  46. /// Error returned by [`Socket::recv`]
  47. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  48. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  49. pub enum RecvError {
  50. Exhausted,
  51. Truncated,
  52. }
  53. impl core::fmt::Display for RecvError {
  54. fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
  55. match self {
  56. RecvError::Exhausted => write!(f, "exhausted"),
  57. RecvError::Truncated => write!(f, "truncated"),
  58. }
  59. }
  60. }
  61. #[cfg(feature = "std")]
  62. impl std::error::Error for RecvError {}
  63. /// A UDP packet metadata.
  64. pub type PacketMetadata = crate::storage::PacketMetadata<()>;
  65. /// A UDP packet ring buffer.
  66. pub type PacketBuffer<'a> = crate::storage::PacketBuffer<'a, ()>;
  67. /// A raw IP socket.
  68. ///
  69. /// A raw socket is bound to a specific IP protocol, and owns
  70. /// transmit and receive packet buffers.
  71. #[derive(Debug)]
  72. pub struct Socket<'a> {
  73. ip_version: IpVersion,
  74. ip_protocol: IpProtocol,
  75. rx_buffer: PacketBuffer<'a>,
  76. tx_buffer: PacketBuffer<'a>,
  77. #[cfg(feature = "async")]
  78. rx_waker: WakerRegistration,
  79. #[cfg(feature = "async")]
  80. tx_waker: WakerRegistration,
  81. }
  82. impl<'a> Socket<'a> {
  83. /// Create a raw IP socket bound to the given IP version and datagram protocol,
  84. /// with the given buffers.
  85. pub fn new(
  86. ip_version: IpVersion,
  87. ip_protocol: IpProtocol,
  88. rx_buffer: PacketBuffer<'a>,
  89. tx_buffer: PacketBuffer<'a>,
  90. ) -> Socket<'a> {
  91. Socket {
  92. ip_version,
  93. ip_protocol,
  94. rx_buffer,
  95. tx_buffer,
  96. #[cfg(feature = "async")]
  97. rx_waker: WakerRegistration::new(),
  98. #[cfg(feature = "async")]
  99. tx_waker: WakerRegistration::new(),
  100. }
  101. }
  102. /// Register a waker for receive operations.
  103. ///
  104. /// The waker is woken on state changes that might affect the return value
  105. /// of `recv` method calls, such as receiving data, or the socket closing.
  106. ///
  107. /// Notes:
  108. ///
  109. /// - Only one waker can be registered at a time. If another waker was previously registered,
  110. /// it is overwritten and will no longer be woken.
  111. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  112. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
  113. /// necessarily changed.
  114. #[cfg(feature = "async")]
  115. pub fn register_recv_waker(&mut self, waker: &Waker) {
  116. self.rx_waker.register(waker)
  117. }
  118. /// Register a waker for send operations.
  119. ///
  120. /// The waker is woken on state changes that might affect the return value
  121. /// of `send` method calls, such as space becoming available in the transmit
  122. /// buffer, or the socket closing.
  123. ///
  124. /// Notes:
  125. ///
  126. /// - Only one waker can be registered at a time. If another waker was previously registered,
  127. /// it is overwritten and will no longer be woken.
  128. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  129. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
  130. /// necessarily changed.
  131. #[cfg(feature = "async")]
  132. pub fn register_send_waker(&mut self, waker: &Waker) {
  133. self.tx_waker.register(waker)
  134. }
  135. /// Return the IP version the socket is bound to.
  136. #[inline]
  137. pub fn ip_version(&self) -> IpVersion {
  138. self.ip_version
  139. }
  140. /// Return the IP protocol the socket is bound to.
  141. #[inline]
  142. pub fn ip_protocol(&self) -> IpProtocol {
  143. self.ip_protocol
  144. }
  145. /// Check whether the transmit buffer is full.
  146. #[inline]
  147. pub fn can_send(&self) -> bool {
  148. !self.tx_buffer.is_full()
  149. }
  150. /// Check whether the receive buffer is not empty.
  151. #[inline]
  152. pub fn can_recv(&self) -> bool {
  153. !self.rx_buffer.is_empty()
  154. }
  155. /// Return the maximum number packets the socket can receive.
  156. #[inline]
  157. pub fn packet_recv_capacity(&self) -> usize {
  158. self.rx_buffer.packet_capacity()
  159. }
  160. /// Return the maximum number packets the socket can transmit.
  161. #[inline]
  162. pub fn packet_send_capacity(&self) -> usize {
  163. self.tx_buffer.packet_capacity()
  164. }
  165. /// Return the maximum number of bytes inside the recv buffer.
  166. #[inline]
  167. pub fn payload_recv_capacity(&self) -> usize {
  168. self.rx_buffer.payload_capacity()
  169. }
  170. /// Return the maximum number of bytes inside the transmit buffer.
  171. #[inline]
  172. pub fn payload_send_capacity(&self) -> usize {
  173. self.tx_buffer.payload_capacity()
  174. }
  175. /// Enqueue a packet to send, and return a pointer to its payload.
  176. ///
  177. /// This function returns `Err(Error::Exhausted)` if the transmit buffer is full,
  178. /// and `Err(Error::Truncated)` if there is not enough transmit buffer capacity
  179. /// to ever send this packet.
  180. ///
  181. /// If the buffer is filled in a way that does not match the socket's
  182. /// IP version or protocol, the packet will be silently dropped.
  183. ///
  184. /// **Note:** The IP header is parsed and re-serialized, and may not match
  185. /// the header actually transmitted bit for bit.
  186. pub fn send(&mut self, size: usize) -> Result<&mut [u8], SendError> {
  187. let packet_buf = self
  188. .tx_buffer
  189. .enqueue(size, ())
  190. .map_err(|_| SendError::BufferFull)?;
  191. net_trace!(
  192. "raw:{}:{}: buffer to send {} octets",
  193. self.ip_version,
  194. self.ip_protocol,
  195. packet_buf.len()
  196. );
  197. Ok(packet_buf)
  198. }
  199. /// Enqueue a packet to be send and pass the buffer to the provided closure.
  200. /// The closure then returns the size of the data written into the buffer.
  201. ///
  202. /// Also see [send](#method.send).
  203. pub fn send_with<F>(&mut self, max_size: usize, f: F) -> Result<usize, SendError>
  204. where
  205. F: FnOnce(&mut [u8]) -> usize,
  206. {
  207. let size = self
  208. .tx_buffer
  209. .enqueue_with_infallible(max_size, (), f)
  210. .map_err(|_| SendError::BufferFull)?;
  211. net_trace!(
  212. "raw:{}:{}: buffer to send {} octets",
  213. self.ip_version,
  214. self.ip_protocol,
  215. size
  216. );
  217. Ok(size)
  218. }
  219. /// Enqueue a packet to send, and fill it from a slice.
  220. ///
  221. /// See also [send](#method.send).
  222. pub fn send_slice(&mut self, data: &[u8]) -> Result<(), SendError> {
  223. self.send(data.len())?.copy_from_slice(data);
  224. Ok(())
  225. }
  226. /// Dequeue a packet, and return a pointer to the payload.
  227. ///
  228. /// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
  229. ///
  230. /// **Note:** The IP header is parsed and re-serialized, and may not match
  231. /// the header actually received bit for bit.
  232. pub fn recv(&mut self) -> Result<&[u8], RecvError> {
  233. let ((), packet_buf) = self.rx_buffer.dequeue().map_err(|_| RecvError::Exhausted)?;
  234. net_trace!(
  235. "raw:{}:{}: receive {} buffered octets",
  236. self.ip_version,
  237. self.ip_protocol,
  238. packet_buf.len()
  239. );
  240. Ok(packet_buf)
  241. }
  242. /// Dequeue a packet, and copy the payload into the given slice.
  243. ///
  244. /// **Note**: when the size of the provided buffer is smaller than the size of the payload,
  245. /// the packet is dropped and a `RecvError::Truncated` error is returned.
  246. ///
  247. /// See also [recv](#method.recv).
  248. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError> {
  249. let buffer = self.recv()?;
  250. if data.len() < buffer.len() {
  251. return Err(RecvError::Truncated);
  252. }
  253. let length = min(data.len(), buffer.len());
  254. data[..length].copy_from_slice(&buffer[..length]);
  255. Ok(length)
  256. }
  257. /// Peek at a packet in the receive buffer and return a pointer to the
  258. /// payload without removing the packet from the receive buffer.
  259. /// This function otherwise behaves identically to [recv](#method.recv).
  260. ///
  261. /// It returns `Err(Error::Exhausted)` if the receive buffer is empty.
  262. pub fn peek(&mut self) -> Result<&[u8], RecvError> {
  263. let ((), packet_buf) = self.rx_buffer.peek().map_err(|_| RecvError::Exhausted)?;
  264. net_trace!(
  265. "raw:{}:{}: receive {} buffered octets",
  266. self.ip_version,
  267. self.ip_protocol,
  268. packet_buf.len()
  269. );
  270. Ok(packet_buf)
  271. }
  272. /// Peek at a packet in the receive buffer, copy the payload into the given slice,
  273. /// and return the amount of octets copied without removing the packet from the receive buffer.
  274. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  275. ///
  276. /// **Note**: when the size of the provided buffer is smaller than the size of the payload,
  277. /// no data is copied into the provided buffer and a `RecvError::Truncated` error is returned.
  278. ///
  279. /// See also [peek](#method.peek).
  280. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize, RecvError> {
  281. let buffer = self.peek()?;
  282. if data.len() < buffer.len() {
  283. return Err(RecvError::Truncated);
  284. }
  285. let length = min(data.len(), buffer.len());
  286. data[..length].copy_from_slice(&buffer[..length]);
  287. Ok(length)
  288. }
  289. pub(crate) fn accepts(&self, ip_repr: &IpRepr) -> bool {
  290. if ip_repr.version() != self.ip_version {
  291. return false;
  292. }
  293. if ip_repr.next_header() != self.ip_protocol {
  294. return false;
  295. }
  296. true
  297. }
  298. pub(crate) fn process(&mut self, cx: &mut Context, ip_repr: &IpRepr, payload: &[u8]) {
  299. debug_assert!(self.accepts(ip_repr));
  300. let header_len = ip_repr.header_len();
  301. let total_len = header_len + payload.len();
  302. net_trace!(
  303. "raw:{}:{}: receiving {} octets",
  304. self.ip_version,
  305. self.ip_protocol,
  306. total_len
  307. );
  308. match self.rx_buffer.enqueue(total_len, ()) {
  309. Ok(buf) => {
  310. ip_repr.emit(&mut buf[..header_len], &cx.checksum_caps());
  311. buf[header_len..].copy_from_slice(payload);
  312. }
  313. Err(_) => net_trace!(
  314. "raw:{}:{}: buffer full, dropped incoming packet",
  315. self.ip_version,
  316. self.ip_protocol
  317. ),
  318. }
  319. #[cfg(feature = "async")]
  320. self.rx_waker.wake();
  321. }
  322. pub(crate) fn dispatch<F, E>(&mut self, cx: &mut Context, emit: F) -> Result<(), E>
  323. where
  324. F: FnOnce(&mut Context, (IpRepr, &[u8])) -> Result<(), E>,
  325. {
  326. let ip_protocol = self.ip_protocol;
  327. let ip_version = self.ip_version;
  328. let _checksum_caps = &cx.checksum_caps();
  329. let res = self.tx_buffer.dequeue_with(|&mut (), buffer| {
  330. match IpVersion::of_packet(buffer) {
  331. #[cfg(feature = "proto-ipv4")]
  332. Ok(IpVersion::Ipv4) => {
  333. let mut packet = match Ipv4Packet::new_checked(buffer) {
  334. Ok(x) => x,
  335. Err(_) => {
  336. net_trace!("raw: malformed ipv6 packet in queue, dropping.");
  337. return Ok(());
  338. }
  339. };
  340. if packet.next_header() != ip_protocol {
  341. net_trace!("raw: sent packet with wrong ip protocol, dropping.");
  342. return Ok(());
  343. }
  344. if _checksum_caps.ipv4.tx() {
  345. packet.fill_checksum();
  346. } else {
  347. // make sure we get a consistently zeroed checksum,
  348. // since implementations might rely on it
  349. packet.set_checksum(0);
  350. }
  351. let packet = Ipv4Packet::new_unchecked(&*packet.into_inner());
  352. let ipv4_repr = match Ipv4Repr::parse(&packet, _checksum_caps) {
  353. Ok(x) => x,
  354. Err(_) => {
  355. net_trace!("raw: malformed ipv4 packet in queue, dropping.");
  356. return Ok(());
  357. }
  358. };
  359. net_trace!("raw:{}:{}: sending", ip_version, ip_protocol);
  360. emit(cx, (IpRepr::Ipv4(ipv4_repr), packet.payload()))
  361. }
  362. #[cfg(feature = "proto-ipv6")]
  363. Ok(IpVersion::Ipv6) => {
  364. let packet = match Ipv6Packet::new_checked(buffer) {
  365. Ok(x) => x,
  366. Err(_) => {
  367. net_trace!("raw: malformed ipv6 packet in queue, dropping.");
  368. return Ok(());
  369. }
  370. };
  371. if packet.next_header() != ip_protocol {
  372. net_trace!("raw: sent ipv6 packet with wrong ip protocol, dropping.");
  373. return Ok(());
  374. }
  375. let packet = Ipv6Packet::new_unchecked(&*packet.into_inner());
  376. let ipv6_repr = match Ipv6Repr::parse(&packet) {
  377. Ok(x) => x,
  378. Err(_) => {
  379. net_trace!("raw: malformed ipv6 packet in queue, dropping.");
  380. return Ok(());
  381. }
  382. };
  383. net_trace!("raw:{}:{}: sending", ip_version, ip_protocol);
  384. emit(cx, (IpRepr::Ipv6(ipv6_repr), packet.payload()))
  385. }
  386. Err(_) => {
  387. net_trace!("raw: sent packet with invalid IP version, dropping.");
  388. Ok(())
  389. }
  390. }
  391. });
  392. match res {
  393. Err(Empty) => Ok(()),
  394. Ok(Err(e)) => Err(e),
  395. Ok(Ok(())) => {
  396. #[cfg(feature = "async")]
  397. self.tx_waker.wake();
  398. Ok(())
  399. }
  400. }
  401. }
  402. pub(crate) fn poll_at(&self, _cx: &mut Context) -> PollAt {
  403. if self.tx_buffer.is_empty() {
  404. PollAt::Ingress
  405. } else {
  406. PollAt::Now
  407. }
  408. }
  409. }
  410. #[cfg(test)]
  411. mod test {
  412. use crate::phy::Medium;
  413. use crate::tests::setup;
  414. use rstest::*;
  415. use super::*;
  416. use crate::wire::IpRepr;
  417. #[cfg(feature = "proto-ipv4")]
  418. use crate::wire::{Ipv4Address, Ipv4Repr};
  419. #[cfg(feature = "proto-ipv6")]
  420. use crate::wire::{Ipv6Address, Ipv6Repr};
  421. fn buffer(packets: usize) -> PacketBuffer<'static> {
  422. PacketBuffer::new(vec![PacketMetadata::EMPTY; packets], vec![0; 48 * packets])
  423. }
  424. #[cfg(feature = "proto-ipv4")]
  425. mod ipv4_locals {
  426. use super::*;
  427. pub fn socket(
  428. rx_buffer: PacketBuffer<'static>,
  429. tx_buffer: PacketBuffer<'static>,
  430. ) -> Socket<'static> {
  431. Socket::new(
  432. IpVersion::Ipv4,
  433. IpProtocol::Unknown(IP_PROTO),
  434. rx_buffer,
  435. tx_buffer,
  436. )
  437. }
  438. pub const IP_PROTO: u8 = 63;
  439. pub const HEADER_REPR: IpRepr = IpRepr::Ipv4(Ipv4Repr {
  440. src_addr: Ipv4Address::new(10, 0, 0, 1),
  441. dst_addr: Ipv4Address::new(10, 0, 0, 2),
  442. next_header: IpProtocol::Unknown(IP_PROTO),
  443. payload_len: 4,
  444. hop_limit: 64,
  445. });
  446. pub const PACKET_BYTES: [u8; 24] = [
  447. 0x45, 0x00, 0x00, 0x18, 0x00, 0x00, 0x40, 0x00, 0x40, 0x3f, 0x00, 0x00, 0x0a, 0x00,
  448. 0x00, 0x01, 0x0a, 0x00, 0x00, 0x02, 0xaa, 0x00, 0x00, 0xff,
  449. ];
  450. pub const PACKET_PAYLOAD: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  451. }
  452. #[cfg(feature = "proto-ipv6")]
  453. mod ipv6_locals {
  454. use super::*;
  455. pub fn socket(
  456. rx_buffer: PacketBuffer<'static>,
  457. tx_buffer: PacketBuffer<'static>,
  458. ) -> Socket<'static> {
  459. Socket::new(
  460. IpVersion::Ipv6,
  461. IpProtocol::Unknown(IP_PROTO),
  462. rx_buffer,
  463. tx_buffer,
  464. )
  465. }
  466. pub const IP_PROTO: u8 = 63;
  467. pub const HEADER_REPR: IpRepr = IpRepr::Ipv6(Ipv6Repr {
  468. src_addr: Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1),
  469. dst_addr: Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 2),
  470. next_header: IpProtocol::Unknown(IP_PROTO),
  471. payload_len: 4,
  472. hop_limit: 64,
  473. });
  474. pub const PACKET_BYTES: [u8; 44] = [
  475. 0x60, 0x00, 0x00, 0x00, 0x00, 0x04, 0x3f, 0x40, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00,
  476. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xfe, 0x80, 0x00, 0x00,
  477. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xaa, 0x00,
  478. 0x00, 0xff,
  479. ];
  480. pub const PACKET_PAYLOAD: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  481. }
  482. macro_rules! reusable_ip_specific_tests {
  483. ($module:ident, $socket:path, $hdr:path, $packet:path, $payload:path) => {
  484. mod $module {
  485. use super::*;
  486. #[test]
  487. fn test_send_truncated() {
  488. let mut socket = $socket(buffer(0), buffer(1));
  489. assert_eq!(socket.send_slice(&[0; 56][..]), Err(SendError::BufferFull));
  490. }
  491. #[rstest]
  492. #[case::ip(Medium::Ip)]
  493. #[cfg(feature = "medium-ip")]
  494. #[case::ethernet(Medium::Ethernet)]
  495. #[cfg(feature = "medium-ethernet")]
  496. #[case::ieee802154(Medium::Ieee802154)]
  497. #[cfg(feature = "medium-ieee802154")]
  498. fn test_send_dispatch(#[case] medium: Medium) {
  499. let (mut iface, _, _) = setup(medium);
  500. let mut cx = iface.context();
  501. let mut socket = $socket(buffer(0), buffer(1));
  502. assert!(socket.can_send());
  503. assert_eq!(
  504. socket.dispatch(&mut cx, |_, _| unreachable!()),
  505. Ok::<_, ()>(())
  506. );
  507. assert_eq!(socket.send_slice(&$packet[..]), Ok(()));
  508. assert_eq!(socket.send_slice(b""), Err(SendError::BufferFull));
  509. assert!(!socket.can_send());
  510. assert_eq!(
  511. socket.dispatch(&mut cx, |_, (ip_repr, ip_payload)| {
  512. assert_eq!(ip_repr, $hdr);
  513. assert_eq!(ip_payload, &$payload);
  514. Err(())
  515. }),
  516. Err(())
  517. );
  518. assert!(!socket.can_send());
  519. assert_eq!(
  520. socket.dispatch(&mut cx, |_, (ip_repr, ip_payload)| {
  521. assert_eq!(ip_repr, $hdr);
  522. assert_eq!(ip_payload, &$payload);
  523. Ok::<_, ()>(())
  524. }),
  525. Ok(())
  526. );
  527. assert!(socket.can_send());
  528. }
  529. #[rstest]
  530. #[case::ip(Medium::Ip)]
  531. #[cfg(feature = "medium-ip")]
  532. #[case::ethernet(Medium::Ethernet)]
  533. #[cfg(feature = "medium-ethernet")]
  534. #[case::ieee802154(Medium::Ieee802154)]
  535. #[cfg(feature = "medium-ieee802154")]
  536. fn test_recv_truncated_slice(#[case] medium: Medium) {
  537. let (mut iface, _, _) = setup(medium);
  538. let mut cx = iface.context();
  539. let mut socket = $socket(buffer(1), buffer(0));
  540. assert!(socket.accepts(&$hdr));
  541. socket.process(&mut cx, &$hdr, &$payload);
  542. let mut slice = [0; 4];
  543. assert_eq!(socket.recv_slice(&mut slice[..]), Err(RecvError::Truncated));
  544. }
  545. #[rstest]
  546. #[case::ip(Medium::Ip)]
  547. #[cfg(feature = "medium-ip")]
  548. #[case::ethernet(Medium::Ethernet)]
  549. #[cfg(feature = "medium-ethernet")]
  550. #[case::ieee802154(Medium::Ieee802154)]
  551. #[cfg(feature = "medium-ieee802154")]
  552. fn test_recv_truncated_packet(#[case] medium: Medium) {
  553. let (mut iface, _, _) = setup(medium);
  554. let mut cx = iface.context();
  555. let mut socket = $socket(buffer(1), buffer(0));
  556. let mut buffer = vec![0; 128];
  557. buffer[..$packet.len()].copy_from_slice(&$packet[..]);
  558. assert!(socket.accepts(&$hdr));
  559. socket.process(&mut cx, &$hdr, &buffer);
  560. }
  561. #[rstest]
  562. #[case::ip(Medium::Ip)]
  563. #[cfg(feature = "medium-ip")]
  564. #[case::ethernet(Medium::Ethernet)]
  565. #[cfg(feature = "medium-ethernet")]
  566. #[case::ieee802154(Medium::Ieee802154)]
  567. #[cfg(feature = "medium-ieee802154")]
  568. fn test_peek_truncated_slice(#[case] medium: Medium) {
  569. let (mut iface, _, _) = setup(medium);
  570. let mut cx = iface.context();
  571. let mut socket = $socket(buffer(1), buffer(0));
  572. assert!(socket.accepts(&$hdr));
  573. socket.process(&mut cx, &$hdr, &$payload);
  574. let mut slice = [0; 4];
  575. assert_eq!(socket.peek_slice(&mut slice[..]), Err(RecvError::Truncated));
  576. assert_eq!(socket.recv_slice(&mut slice[..]), Err(RecvError::Truncated));
  577. assert_eq!(socket.peek_slice(&mut slice[..]), Err(RecvError::Exhausted));
  578. }
  579. }
  580. };
  581. }
  582. #[cfg(feature = "proto-ipv4")]
  583. reusable_ip_specific_tests!(
  584. ipv4,
  585. ipv4_locals::socket,
  586. ipv4_locals::HEADER_REPR,
  587. ipv4_locals::PACKET_BYTES,
  588. ipv4_locals::PACKET_PAYLOAD
  589. );
  590. #[cfg(feature = "proto-ipv6")]
  591. reusable_ip_specific_tests!(
  592. ipv6,
  593. ipv6_locals::socket,
  594. ipv6_locals::HEADER_REPR,
  595. ipv6_locals::PACKET_BYTES,
  596. ipv6_locals::PACKET_PAYLOAD
  597. );
  598. #[rstest]
  599. #[case::ip(Medium::Ip)]
  600. #[case::ethernet(Medium::Ethernet)]
  601. #[cfg(feature = "medium-ethernet")]
  602. #[case::ieee802154(Medium::Ieee802154)]
  603. #[cfg(feature = "medium-ieee802154")]
  604. fn test_send_illegal(#[case] medium: Medium) {
  605. #[cfg(feature = "proto-ipv4")]
  606. {
  607. let (mut iface, _, _) = setup(medium);
  608. let cx = iface.context();
  609. let mut socket = ipv4_locals::socket(buffer(0), buffer(2));
  610. let mut wrong_version = ipv4_locals::PACKET_BYTES;
  611. Ipv4Packet::new_unchecked(&mut wrong_version).set_version(6);
  612. assert_eq!(socket.send_slice(&wrong_version[..]), Ok(()));
  613. assert_eq!(socket.dispatch(cx, |_, _| unreachable!()), Ok::<_, ()>(()));
  614. let mut wrong_protocol = ipv4_locals::PACKET_BYTES;
  615. Ipv4Packet::new_unchecked(&mut wrong_protocol).set_next_header(IpProtocol::Tcp);
  616. assert_eq!(socket.send_slice(&wrong_protocol[..]), Ok(()));
  617. assert_eq!(socket.dispatch(cx, |_, _| unreachable!()), Ok::<_, ()>(()));
  618. }
  619. #[cfg(feature = "proto-ipv6")]
  620. {
  621. let (mut iface, _, _) = setup(medium);
  622. let cx = iface.context();
  623. let mut socket = ipv6_locals::socket(buffer(0), buffer(2));
  624. let mut wrong_version = ipv6_locals::PACKET_BYTES;
  625. Ipv6Packet::new_unchecked(&mut wrong_version[..]).set_version(4);
  626. assert_eq!(socket.send_slice(&wrong_version[..]), Ok(()));
  627. assert_eq!(socket.dispatch(cx, |_, _| unreachable!()), Ok::<_, ()>(()));
  628. let mut wrong_protocol = ipv6_locals::PACKET_BYTES;
  629. Ipv6Packet::new_unchecked(&mut wrong_protocol[..]).set_next_header(IpProtocol::Tcp);
  630. assert_eq!(socket.send_slice(&wrong_protocol[..]), Ok(()));
  631. assert_eq!(socket.dispatch(cx, |_, _| unreachable!()), Ok::<_, ()>(()));
  632. }
  633. }
  634. #[rstest]
  635. #[case::ip(Medium::Ip)]
  636. #[cfg(feature = "medium-ip")]
  637. #[case::ethernet(Medium::Ethernet)]
  638. #[cfg(feature = "medium-ethernet")]
  639. #[case::ieee802154(Medium::Ieee802154)]
  640. #[cfg(feature = "medium-ieee802154")]
  641. fn test_recv_process(#[case] medium: Medium) {
  642. #[cfg(feature = "proto-ipv4")]
  643. {
  644. let (mut iface, _, _) = setup(medium);
  645. let cx = iface.context();
  646. let mut socket = ipv4_locals::socket(buffer(1), buffer(0));
  647. assert!(!socket.can_recv());
  648. let mut cksumd_packet = ipv4_locals::PACKET_BYTES;
  649. Ipv4Packet::new_unchecked(&mut cksumd_packet).fill_checksum();
  650. assert_eq!(socket.recv(), Err(RecvError::Exhausted));
  651. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  652. socket.process(cx, &ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD);
  653. assert!(socket.can_recv());
  654. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  655. socket.process(cx, &ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD);
  656. assert_eq!(socket.recv(), Ok(&cksumd_packet[..]));
  657. assert!(!socket.can_recv());
  658. }
  659. #[cfg(feature = "proto-ipv6")]
  660. {
  661. let (mut iface, _, _) = setup(medium);
  662. let cx = iface.context();
  663. let mut socket = ipv6_locals::socket(buffer(1), buffer(0));
  664. assert!(!socket.can_recv());
  665. assert_eq!(socket.recv(), Err(RecvError::Exhausted));
  666. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  667. socket.process(cx, &ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD);
  668. assert!(socket.can_recv());
  669. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  670. socket.process(cx, &ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD);
  671. assert_eq!(socket.recv(), Ok(&ipv6_locals::PACKET_BYTES[..]));
  672. assert!(!socket.can_recv());
  673. }
  674. }
  675. #[rstest]
  676. #[case::ip(Medium::Ip)]
  677. #[case::ethernet(Medium::Ethernet)]
  678. #[cfg(feature = "medium-ethernet")]
  679. #[case::ieee802154(Medium::Ieee802154)]
  680. #[cfg(feature = "medium-ieee802154")]
  681. fn test_peek_process(#[case] medium: Medium) {
  682. #[cfg(feature = "proto-ipv4")]
  683. {
  684. let (mut iface, _, _) = setup(medium);
  685. let cx = iface.context();
  686. let mut socket = ipv4_locals::socket(buffer(1), buffer(0));
  687. let mut cksumd_packet = ipv4_locals::PACKET_BYTES;
  688. Ipv4Packet::new_unchecked(&mut cksumd_packet).fill_checksum();
  689. assert_eq!(socket.peek(), Err(RecvError::Exhausted));
  690. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  691. socket.process(cx, &ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD);
  692. assert!(socket.accepts(&ipv4_locals::HEADER_REPR));
  693. socket.process(cx, &ipv4_locals::HEADER_REPR, &ipv4_locals::PACKET_PAYLOAD);
  694. assert_eq!(socket.peek(), Ok(&cksumd_packet[..]));
  695. assert_eq!(socket.recv(), Ok(&cksumd_packet[..]));
  696. assert_eq!(socket.peek(), Err(RecvError::Exhausted));
  697. }
  698. #[cfg(feature = "proto-ipv6")]
  699. {
  700. let (mut iface, _, _) = setup(medium);
  701. let cx = iface.context();
  702. let mut socket = ipv6_locals::socket(buffer(1), buffer(0));
  703. assert_eq!(socket.peek(), Err(RecvError::Exhausted));
  704. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  705. socket.process(cx, &ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD);
  706. assert!(socket.accepts(&ipv6_locals::HEADER_REPR));
  707. socket.process(cx, &ipv6_locals::HEADER_REPR, &ipv6_locals::PACKET_PAYLOAD);
  708. assert_eq!(socket.peek(), Ok(&ipv6_locals::PACKET_BYTES[..]));
  709. assert_eq!(socket.recv(), Ok(&ipv6_locals::PACKET_BYTES[..]));
  710. assert_eq!(socket.peek(), Err(RecvError::Exhausted));
  711. }
  712. }
  713. #[test]
  714. fn test_doesnt_accept_wrong_proto() {
  715. #[cfg(feature = "proto-ipv4")]
  716. {
  717. let socket = Socket::new(
  718. IpVersion::Ipv4,
  719. IpProtocol::Unknown(ipv4_locals::IP_PROTO + 1),
  720. buffer(1),
  721. buffer(1),
  722. );
  723. assert!(!socket.accepts(&ipv4_locals::HEADER_REPR));
  724. #[cfg(feature = "proto-ipv6")]
  725. assert!(!socket.accepts(&ipv6_locals::HEADER_REPR));
  726. }
  727. #[cfg(feature = "proto-ipv6")]
  728. {
  729. let socket = Socket::new(
  730. IpVersion::Ipv6,
  731. IpProtocol::Unknown(ipv6_locals::IP_PROTO + 1),
  732. buffer(1),
  733. buffer(1),
  734. );
  735. assert!(!socket.accepts(&ipv6_locals::HEADER_REPR));
  736. #[cfg(feature = "proto-ipv4")]
  737. assert!(!socket.accepts(&ipv4_locals::HEADER_REPR));
  738. }
  739. }
  740. }