udp.rs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. use core::cmp::min;
  2. #[cfg(feature = "async")]
  3. use core::task::Waker;
  4. #[cfg(feature = "async")]
  5. use crate::socket::WakerRegistration;
  6. use crate::socket::{Context, PollAt, Socket, SocketHandle, SocketMeta};
  7. use crate::storage::{PacketBuffer, PacketMetadata};
  8. use crate::wire::{IpEndpoint, IpProtocol, IpRepr, UdpRepr};
  9. use crate::{Error, Result};
  10. /// A UDP packet metadata.
  11. pub type UdpPacketMetadata = PacketMetadata<IpEndpoint>;
  12. /// A UDP packet ring buffer.
  13. pub type UdpSocketBuffer<'a> = PacketBuffer<'a, IpEndpoint>;
  14. /// A User Datagram Protocol socket.
  15. ///
  16. /// A UDP socket is bound to a specific endpoint, and owns transmit and receive
  17. /// packet buffers.
  18. #[derive(Debug)]
  19. pub struct UdpSocket<'a> {
  20. pub(crate) meta: SocketMeta,
  21. endpoint: IpEndpoint,
  22. rx_buffer: UdpSocketBuffer<'a>,
  23. tx_buffer: UdpSocketBuffer<'a>,
  24. /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  25. hop_limit: Option<u8>,
  26. #[cfg(feature = "async")]
  27. rx_waker: WakerRegistration,
  28. #[cfg(feature = "async")]
  29. tx_waker: WakerRegistration,
  30. }
  31. impl<'a> UdpSocket<'a> {
  32. /// Create an UDP socket with the given buffers.
  33. pub fn new(rx_buffer: UdpSocketBuffer<'a>, tx_buffer: UdpSocketBuffer<'a>) -> UdpSocket<'a> {
  34. UdpSocket {
  35. meta: SocketMeta::default(),
  36. endpoint: IpEndpoint::default(),
  37. rx_buffer: rx_buffer,
  38. tx_buffer: tx_buffer,
  39. hop_limit: None,
  40. #[cfg(feature = "async")]
  41. rx_waker: WakerRegistration::new(),
  42. #[cfg(feature = "async")]
  43. tx_waker: WakerRegistration::new(),
  44. }
  45. }
  46. /// Register a waker for receive operations.
  47. ///
  48. /// The waker is woken on state changes that might affect the return value
  49. /// of `recv` method calls, such as receiving data, or the socket closing.
  50. ///
  51. /// Notes:
  52. ///
  53. /// - Only one waker can be registered at a time. If another waker was previously registered,
  54. /// it is overwritten and will no longer be woken.
  55. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  56. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
  57. /// necessarily changed.
  58. #[cfg(feature = "async")]
  59. pub fn register_recv_waker(&mut self, waker: &Waker) {
  60. self.rx_waker.register(waker)
  61. }
  62. /// Register a waker for send operations.
  63. ///
  64. /// The waker is woken on state changes that might affect the return value
  65. /// of `send` method calls, such as space becoming available in the transmit
  66. /// buffer, or the socket closing.
  67. ///
  68. /// Notes:
  69. ///
  70. /// - Only one waker can be registered at a time. If another waker was previously registered,
  71. /// it is overwritten and will no longer be woken.
  72. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  73. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
  74. /// necessarily changed.
  75. #[cfg(feature = "async")]
  76. pub fn register_send_waker(&mut self, waker: &Waker) {
  77. self.tx_waker.register(waker)
  78. }
  79. /// Return the socket handle.
  80. #[inline]
  81. pub fn handle(&self) -> SocketHandle {
  82. self.meta.handle
  83. }
  84. /// Return the bound endpoint.
  85. #[inline]
  86. pub fn endpoint(&self) -> IpEndpoint {
  87. self.endpoint
  88. }
  89. /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  90. ///
  91. /// See also the [set_hop_limit](#method.set_hop_limit) method
  92. pub fn hop_limit(&self) -> Option<u8> {
  93. self.hop_limit
  94. }
  95. /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  96. ///
  97. /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
  98. /// value (64).
  99. ///
  100. /// # Panics
  101. ///
  102. /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
  103. ///
  104. /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
  105. /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
  106. pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
  107. // A host MUST NOT send a datagram with a hop limit value of 0
  108. if let Some(0) = hop_limit {
  109. panic!("the time-to-live value of a packet must not be zero")
  110. }
  111. self.hop_limit = hop_limit
  112. }
  113. /// Bind the socket to the given endpoint.
  114. ///
  115. /// This function returns `Err(Error::Illegal)` if the socket was open
  116. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  117. /// if the port in the given endpoint is zero.
  118. pub fn bind<T: Into<IpEndpoint>>(&mut self, endpoint: T) -> Result<()> {
  119. let endpoint = endpoint.into();
  120. if endpoint.port == 0 {
  121. return Err(Error::Unaddressable);
  122. }
  123. if self.is_open() {
  124. return Err(Error::Illegal);
  125. }
  126. self.endpoint = endpoint;
  127. #[cfg(feature = "async")]
  128. {
  129. self.rx_waker.wake();
  130. self.tx_waker.wake();
  131. }
  132. Ok(())
  133. }
  134. /// Close the socket.
  135. pub fn close(&mut self) {
  136. // Clear the bound endpoint of the socket.
  137. self.endpoint = IpEndpoint::default();
  138. // Reset the RX and TX buffers of the socket.
  139. self.tx_buffer.reset();
  140. self.rx_buffer.reset();
  141. #[cfg(feature = "async")]
  142. {
  143. self.rx_waker.wake();
  144. self.tx_waker.wake();
  145. }
  146. }
  147. /// Check whether the socket is open.
  148. #[inline]
  149. pub fn is_open(&self) -> bool {
  150. self.endpoint.port != 0
  151. }
  152. /// Check whether the transmit buffer is full.
  153. #[inline]
  154. pub fn can_send(&self) -> bool {
  155. !self.tx_buffer.is_full()
  156. }
  157. /// Check whether the receive buffer is not empty.
  158. #[inline]
  159. pub fn can_recv(&self) -> bool {
  160. !self.rx_buffer.is_empty()
  161. }
  162. /// Return the maximum number packets the socket can receive.
  163. #[inline]
  164. pub fn packet_recv_capacity(&self) -> usize {
  165. self.rx_buffer.packet_capacity()
  166. }
  167. /// Return the maximum number packets the socket can transmit.
  168. #[inline]
  169. pub fn packet_send_capacity(&self) -> usize {
  170. self.tx_buffer.packet_capacity()
  171. }
  172. /// Return the maximum number of bytes inside the recv buffer.
  173. #[inline]
  174. pub fn payload_recv_capacity(&self) -> usize {
  175. self.rx_buffer.payload_capacity()
  176. }
  177. /// Return the maximum number of bytes inside the transmit buffer.
  178. #[inline]
  179. pub fn payload_send_capacity(&self) -> usize {
  180. self.tx_buffer.payload_capacity()
  181. }
  182. /// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
  183. /// to its payload.
  184. ///
  185. /// This function returns `Err(Error::Exhausted)` if the transmit buffer is full,
  186. /// `Err(Error::Unaddressable)` if local or remote port, or remote address are unspecified,
  187. /// and `Err(Error::Truncated)` if there is not enough transmit buffer capacity
  188. /// to ever send this packet.
  189. pub fn send(&mut self, size: usize, endpoint: IpEndpoint) -> Result<&mut [u8]> {
  190. if self.endpoint.port == 0 {
  191. return Err(Error::Unaddressable);
  192. }
  193. if !endpoint.is_specified() {
  194. return Err(Error::Unaddressable);
  195. }
  196. let payload_buf = self.tx_buffer.enqueue(size, endpoint)?;
  197. net_trace!(
  198. "{}:{}:{}: buffer to send {} octets",
  199. self.meta.handle,
  200. self.endpoint,
  201. endpoint,
  202. size
  203. );
  204. Ok(payload_buf)
  205. }
  206. /// Enqueue a packet to be sent to a given remote endpoint, and fill it from a slice.
  207. ///
  208. /// See also [send](#method.send).
  209. pub fn send_slice(&mut self, data: &[u8], endpoint: IpEndpoint) -> Result<()> {
  210. self.send(data.len(), endpoint)?.copy_from_slice(data);
  211. Ok(())
  212. }
  213. /// Dequeue a packet received from a remote endpoint, and return the endpoint as well
  214. /// as a pointer to the payload.
  215. ///
  216. /// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
  217. pub fn recv(&mut self) -> Result<(&[u8], IpEndpoint)> {
  218. let (endpoint, payload_buf) = self.rx_buffer.dequeue()?;
  219. net_trace!(
  220. "{}:{}:{}: receive {} buffered octets",
  221. self.meta.handle,
  222. self.endpoint,
  223. endpoint,
  224. payload_buf.len()
  225. );
  226. Ok((payload_buf, endpoint))
  227. }
  228. /// Dequeue a packet received from a remote endpoint, copy the payload into the given slice,
  229. /// and return the amount of octets copied as well as the endpoint.
  230. ///
  231. /// See also [recv](#method.recv).
  232. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(usize, IpEndpoint)> {
  233. let (buffer, endpoint) = self.recv()?;
  234. let length = min(data.len(), buffer.len());
  235. data[..length].copy_from_slice(&buffer[..length]);
  236. Ok((length, endpoint))
  237. }
  238. /// Peek at a packet received from a remote endpoint, and return the endpoint as well
  239. /// as a pointer to the payload without removing the packet from the receive buffer.
  240. /// This function otherwise behaves identically to [recv](#method.recv).
  241. ///
  242. /// It returns `Err(Error::Exhausted)` if the receive buffer is empty.
  243. pub fn peek(&mut self) -> Result<(&[u8], &IpEndpoint)> {
  244. let handle = self.meta.handle;
  245. let endpoint = self.endpoint;
  246. self.rx_buffer.peek().map(|(remote_endpoint, payload_buf)| {
  247. net_trace!(
  248. "{}:{}:{}: peek {} buffered octets",
  249. handle,
  250. endpoint,
  251. remote_endpoint,
  252. payload_buf.len()
  253. );
  254. (payload_buf, remote_endpoint)
  255. })
  256. }
  257. /// Peek at a packet received from a remote endpoint, copy the payload into the given slice,
  258. /// and return the amount of octets copied as well as the endpoint without removing the
  259. /// packet from the receive buffer.
  260. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  261. ///
  262. /// See also [peek](#method.peek).
  263. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<(usize, &IpEndpoint)> {
  264. let (buffer, endpoint) = self.peek()?;
  265. let length = min(data.len(), buffer.len());
  266. data[..length].copy_from_slice(&buffer[..length]);
  267. Ok((length, endpoint))
  268. }
  269. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &UdpRepr) -> bool {
  270. if self.endpoint.port != repr.dst_port {
  271. return false;
  272. }
  273. if !self.endpoint.addr.is_unspecified()
  274. && self.endpoint.addr != ip_repr.dst_addr()
  275. && !ip_repr.dst_addr().is_broadcast()
  276. && !ip_repr.dst_addr().is_multicast()
  277. {
  278. return false;
  279. }
  280. true
  281. }
  282. pub(crate) fn process(
  283. &mut self,
  284. _cx: &Context,
  285. ip_repr: &IpRepr,
  286. repr: &UdpRepr,
  287. payload: &[u8],
  288. ) -> Result<()> {
  289. debug_assert!(self.accepts(ip_repr, repr));
  290. let size = payload.len();
  291. let endpoint = IpEndpoint {
  292. addr: ip_repr.src_addr(),
  293. port: repr.src_port,
  294. };
  295. self.rx_buffer
  296. .enqueue(size, endpoint)?
  297. .copy_from_slice(payload);
  298. net_trace!(
  299. "{}:{}:{}: receiving {} octets",
  300. self.meta.handle,
  301. self.endpoint,
  302. endpoint,
  303. size
  304. );
  305. #[cfg(feature = "async")]
  306. self.rx_waker.wake();
  307. Ok(())
  308. }
  309. pub(crate) fn dispatch<F>(&mut self, _cx: &Context, emit: F) -> Result<()>
  310. where
  311. F: FnOnce((IpRepr, UdpRepr, &[u8])) -> Result<()>,
  312. {
  313. let handle = self.handle();
  314. let endpoint = self.endpoint;
  315. let hop_limit = self.hop_limit.unwrap_or(64);
  316. self.tx_buffer
  317. .dequeue_with(|remote_endpoint, payload_buf| {
  318. net_trace!(
  319. "{}:{}:{}: sending {} octets",
  320. handle,
  321. endpoint,
  322. endpoint,
  323. payload_buf.len()
  324. );
  325. let repr = UdpRepr {
  326. src_port: endpoint.port,
  327. dst_port: remote_endpoint.port,
  328. };
  329. let ip_repr = IpRepr::Unspecified {
  330. src_addr: endpoint.addr,
  331. dst_addr: remote_endpoint.addr,
  332. protocol: IpProtocol::Udp,
  333. payload_len: repr.header_len() + payload_buf.len(),
  334. hop_limit: hop_limit,
  335. };
  336. emit((ip_repr, repr, payload_buf))
  337. })?;
  338. #[cfg(feature = "async")]
  339. self.tx_waker.wake();
  340. Ok(())
  341. }
  342. pub(crate) fn poll_at(&self, _cx: &Context) -> PollAt {
  343. if self.tx_buffer.is_empty() {
  344. PollAt::Ingress
  345. } else {
  346. PollAt::Now
  347. }
  348. }
  349. }
  350. impl<'a> Into<Socket<'a>> for UdpSocket<'a> {
  351. fn into(self) -> Socket<'a> {
  352. Socket::Udp(self)
  353. }
  354. }
  355. #[cfg(test)]
  356. mod test {
  357. use super::*;
  358. use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3};
  359. #[cfg(feature = "proto-ipv4")]
  360. use crate::wire::Ipv4Repr;
  361. #[cfg(feature = "proto-ipv6")]
  362. use crate::wire::Ipv6Repr;
  363. use crate::wire::{IpAddress, IpRepr, UdpRepr};
  364. fn buffer(packets: usize) -> UdpSocketBuffer<'static> {
  365. UdpSocketBuffer::new(
  366. vec![UdpPacketMetadata::EMPTY; packets],
  367. vec![0; 16 * packets],
  368. )
  369. }
  370. fn socket(
  371. rx_buffer: UdpSocketBuffer<'static>,
  372. tx_buffer: UdpSocketBuffer<'static>,
  373. ) -> UdpSocket<'static> {
  374. UdpSocket::new(rx_buffer, tx_buffer)
  375. }
  376. const LOCAL_PORT: u16 = 53;
  377. const REMOTE_PORT: u16 = 49500;
  378. pub const LOCAL_END: IpEndpoint = IpEndpoint {
  379. addr: MOCK_IP_ADDR_1,
  380. port: LOCAL_PORT,
  381. };
  382. pub const REMOTE_END: IpEndpoint = IpEndpoint {
  383. addr: MOCK_IP_ADDR_2,
  384. port: REMOTE_PORT,
  385. };
  386. pub const LOCAL_IP_REPR: IpRepr = IpRepr::Unspecified {
  387. src_addr: MOCK_IP_ADDR_1,
  388. dst_addr: MOCK_IP_ADDR_2,
  389. protocol: IpProtocol::Udp,
  390. payload_len: 8 + 6,
  391. hop_limit: 64,
  392. };
  393. const LOCAL_UDP_REPR: UdpRepr = UdpRepr {
  394. src_port: LOCAL_PORT,
  395. dst_port: REMOTE_PORT,
  396. };
  397. const REMOTE_UDP_REPR: UdpRepr = UdpRepr {
  398. src_port: REMOTE_PORT,
  399. dst_port: LOCAL_PORT,
  400. };
  401. const PAYLOAD: &[u8] = b"abcdef";
  402. fn remote_ip_repr() -> IpRepr {
  403. match (MOCK_IP_ADDR_2, MOCK_IP_ADDR_1) {
  404. #[cfg(feature = "proto-ipv4")]
  405. (IpAddress::Ipv4(src), IpAddress::Ipv4(dst)) => IpRepr::Ipv4(Ipv4Repr {
  406. src_addr: src,
  407. dst_addr: dst,
  408. protocol: IpProtocol::Udp,
  409. payload_len: 8 + 6,
  410. hop_limit: 64,
  411. }),
  412. #[cfg(feature = "proto-ipv6")]
  413. (IpAddress::Ipv6(src), IpAddress::Ipv6(dst)) => IpRepr::Ipv6(Ipv6Repr {
  414. src_addr: src,
  415. dst_addr: dst,
  416. next_header: IpProtocol::Udp,
  417. payload_len: 8 + 6,
  418. hop_limit: 64,
  419. }),
  420. _ => unreachable!(),
  421. }
  422. }
  423. #[test]
  424. fn test_bind_unaddressable() {
  425. let mut socket = socket(buffer(0), buffer(0));
  426. assert_eq!(socket.bind(0), Err(Error::Unaddressable));
  427. }
  428. #[test]
  429. fn test_bind_twice() {
  430. let mut socket = socket(buffer(0), buffer(0));
  431. assert_eq!(socket.bind(1), Ok(()));
  432. assert_eq!(socket.bind(2), Err(Error::Illegal));
  433. }
  434. #[test]
  435. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  436. fn test_set_hop_limit_zero() {
  437. let mut s = socket(buffer(0), buffer(1));
  438. s.set_hop_limit(Some(0));
  439. }
  440. #[test]
  441. fn test_send_unaddressable() {
  442. let mut socket = socket(buffer(0), buffer(1));
  443. assert_eq!(
  444. socket.send_slice(b"abcdef", REMOTE_END),
  445. Err(Error::Unaddressable)
  446. );
  447. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  448. assert_eq!(
  449. socket.send_slice(
  450. b"abcdef",
  451. IpEndpoint {
  452. addr: IpAddress::Unspecified,
  453. ..REMOTE_END
  454. }
  455. ),
  456. Err(Error::Unaddressable)
  457. );
  458. assert_eq!(
  459. socket.send_slice(
  460. b"abcdef",
  461. IpEndpoint {
  462. port: 0,
  463. ..REMOTE_END
  464. }
  465. ),
  466. Err(Error::Unaddressable)
  467. );
  468. assert_eq!(socket.send_slice(b"abcdef", REMOTE_END), Ok(()));
  469. }
  470. #[test]
  471. fn test_send_dispatch() {
  472. let mut socket = socket(buffer(0), buffer(1));
  473. assert_eq!(socket.bind(LOCAL_END), Ok(()));
  474. assert!(socket.can_send());
  475. assert_eq!(
  476. socket.dispatch(&Context::DUMMY, |_| unreachable!()),
  477. Err(Error::Exhausted)
  478. );
  479. assert_eq!(socket.send_slice(b"abcdef", REMOTE_END), Ok(()));
  480. assert_eq!(
  481. socket.send_slice(b"123456", REMOTE_END),
  482. Err(Error::Exhausted)
  483. );
  484. assert!(!socket.can_send());
  485. assert_eq!(
  486. socket.dispatch(&Context::DUMMY, |(ip_repr, udp_repr, payload)| {
  487. assert_eq!(ip_repr, LOCAL_IP_REPR);
  488. assert_eq!(udp_repr, LOCAL_UDP_REPR);
  489. assert_eq!(payload, PAYLOAD);
  490. Err(Error::Unaddressable)
  491. }),
  492. Err(Error::Unaddressable)
  493. );
  494. assert!(!socket.can_send());
  495. assert_eq!(
  496. socket.dispatch(&Context::DUMMY, |(ip_repr, udp_repr, payload)| {
  497. assert_eq!(ip_repr, LOCAL_IP_REPR);
  498. assert_eq!(udp_repr, LOCAL_UDP_REPR);
  499. assert_eq!(payload, PAYLOAD);
  500. Ok(())
  501. }),
  502. Ok(())
  503. );
  504. assert!(socket.can_send());
  505. }
  506. #[test]
  507. fn test_recv_process() {
  508. let mut socket = socket(buffer(1), buffer(0));
  509. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  510. assert!(!socket.can_recv());
  511. assert_eq!(socket.recv(), Err(Error::Exhausted));
  512. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  513. assert_eq!(
  514. socket.process(
  515. &Context::DUMMY,
  516. &remote_ip_repr(),
  517. &REMOTE_UDP_REPR,
  518. PAYLOAD
  519. ),
  520. Ok(())
  521. );
  522. assert!(socket.can_recv());
  523. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  524. assert_eq!(
  525. socket.process(
  526. &Context::DUMMY,
  527. &remote_ip_repr(),
  528. &REMOTE_UDP_REPR,
  529. PAYLOAD
  530. ),
  531. Err(Error::Exhausted)
  532. );
  533. assert_eq!(socket.recv(), Ok((&b"abcdef"[..], REMOTE_END)));
  534. assert!(!socket.can_recv());
  535. }
  536. #[test]
  537. fn test_peek_process() {
  538. let mut socket = socket(buffer(1), buffer(0));
  539. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  540. assert_eq!(socket.peek(), Err(Error::Exhausted));
  541. assert_eq!(
  542. socket.process(
  543. &Context::DUMMY,
  544. &remote_ip_repr(),
  545. &REMOTE_UDP_REPR,
  546. PAYLOAD
  547. ),
  548. Ok(())
  549. );
  550. assert_eq!(socket.peek(), Ok((&b"abcdef"[..], &REMOTE_END)));
  551. assert_eq!(socket.recv(), Ok((&b"abcdef"[..], REMOTE_END)));
  552. assert_eq!(socket.peek(), Err(Error::Exhausted));
  553. }
  554. #[test]
  555. fn test_recv_truncated_slice() {
  556. let mut socket = socket(buffer(1), buffer(0));
  557. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  558. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  559. assert_eq!(
  560. socket.process(
  561. &Context::DUMMY,
  562. &remote_ip_repr(),
  563. &REMOTE_UDP_REPR,
  564. PAYLOAD
  565. ),
  566. Ok(())
  567. );
  568. let mut slice = [0; 4];
  569. assert_eq!(socket.recv_slice(&mut slice[..]), Ok((4, REMOTE_END)));
  570. assert_eq!(&slice, b"abcd");
  571. }
  572. #[test]
  573. fn test_peek_truncated_slice() {
  574. let mut socket = socket(buffer(1), buffer(0));
  575. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  576. assert_eq!(
  577. socket.process(
  578. &Context::DUMMY,
  579. &remote_ip_repr(),
  580. &REMOTE_UDP_REPR,
  581. PAYLOAD
  582. ),
  583. Ok(())
  584. );
  585. let mut slice = [0; 4];
  586. assert_eq!(socket.peek_slice(&mut slice[..]), Ok((4, &REMOTE_END)));
  587. assert_eq!(&slice, b"abcd");
  588. assert_eq!(socket.recv_slice(&mut slice[..]), Ok((4, REMOTE_END)));
  589. assert_eq!(&slice, b"abcd");
  590. assert_eq!(socket.peek_slice(&mut slice[..]), Err(Error::Exhausted));
  591. }
  592. #[test]
  593. fn test_set_hop_limit() {
  594. let mut s = socket(buffer(0), buffer(1));
  595. assert_eq!(s.bind(LOCAL_END), Ok(()));
  596. s.set_hop_limit(Some(0x2a));
  597. assert_eq!(s.send_slice(b"abcdef", REMOTE_END), Ok(()));
  598. assert_eq!(
  599. s.dispatch(&Context::DUMMY, |(ip_repr, _, _)| {
  600. assert_eq!(
  601. ip_repr,
  602. IpRepr::Unspecified {
  603. src_addr: MOCK_IP_ADDR_1,
  604. dst_addr: MOCK_IP_ADDR_2,
  605. protocol: IpProtocol::Udp,
  606. payload_len: 8 + 6,
  607. hop_limit: 0x2a,
  608. }
  609. );
  610. Ok(())
  611. }),
  612. Ok(())
  613. );
  614. }
  615. #[test]
  616. fn test_doesnt_accept_wrong_port() {
  617. let mut socket = socket(buffer(1), buffer(0));
  618. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  619. let mut udp_repr = REMOTE_UDP_REPR;
  620. assert!(socket.accepts(&remote_ip_repr(), &udp_repr));
  621. udp_repr.dst_port += 1;
  622. assert!(!socket.accepts(&remote_ip_repr(), &udp_repr));
  623. }
  624. #[test]
  625. fn test_doesnt_accept_wrong_ip() {
  626. fn generate_bad_repr() -> IpRepr {
  627. match (MOCK_IP_ADDR_2, MOCK_IP_ADDR_3) {
  628. #[cfg(feature = "proto-ipv4")]
  629. (IpAddress::Ipv4(src), IpAddress::Ipv4(dst)) => IpRepr::Ipv4(Ipv4Repr {
  630. src_addr: src,
  631. dst_addr: dst,
  632. protocol: IpProtocol::Udp,
  633. payload_len: 8 + 6,
  634. hop_limit: 64,
  635. }),
  636. #[cfg(feature = "proto-ipv6")]
  637. (IpAddress::Ipv6(src), IpAddress::Ipv6(dst)) => IpRepr::Ipv6(Ipv6Repr {
  638. src_addr: src,
  639. dst_addr: dst,
  640. next_header: IpProtocol::Udp,
  641. payload_len: 8 + 6,
  642. hop_limit: 64,
  643. }),
  644. _ => unreachable!(),
  645. }
  646. }
  647. let mut port_bound_socket = socket(buffer(1), buffer(0));
  648. assert_eq!(port_bound_socket.bind(LOCAL_PORT), Ok(()));
  649. assert!(port_bound_socket.accepts(&generate_bad_repr(), &REMOTE_UDP_REPR));
  650. let mut ip_bound_socket = socket(buffer(1), buffer(0));
  651. assert_eq!(ip_bound_socket.bind(LOCAL_END), Ok(()));
  652. assert!(!ip_bound_socket.accepts(&generate_bad_repr(), &REMOTE_UDP_REPR));
  653. }
  654. #[test]
  655. fn test_send_large_packet() {
  656. // buffer(4) creates a payload buffer of size 16*4
  657. let mut socket = socket(buffer(0), buffer(4));
  658. assert_eq!(socket.bind(LOCAL_END), Ok(()));
  659. let too_large = b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefx";
  660. assert_eq!(
  661. socket.send_slice(too_large, REMOTE_END),
  662. Err(Error::Truncated)
  663. );
  664. assert_eq!(socket.send_slice(&too_large[..16 * 4], REMOTE_END), Ok(()));
  665. }
  666. #[test]
  667. fn test_process_empty_payload() {
  668. let recv_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 1], vec![]);
  669. let mut socket = socket(recv_buffer, buffer(0));
  670. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  671. let repr = UdpRepr {
  672. src_port: REMOTE_PORT,
  673. dst_port: LOCAL_PORT,
  674. };
  675. assert_eq!(
  676. socket.process(&Context::DUMMY, &remote_ip_repr(), &repr, &[]),
  677. Ok(())
  678. );
  679. assert_eq!(socket.recv(), Ok((&[][..], REMOTE_END)));
  680. }
  681. #[test]
  682. fn test_closing() {
  683. let recv_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::EMPTY; 1], vec![]);
  684. let mut socket = socket(recv_buffer, buffer(0));
  685. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  686. assert!(socket.is_open());
  687. socket.close();
  688. assert!(!socket.is_open());
  689. }
  690. }