udp.rs 22 KB

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