udp.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. use core::cmp::min;
  2. use {Error, Result};
  3. use socket::{Socket, SocketMeta, SocketHandle};
  4. use storage::{PacketBuffer, PacketMetadata};
  5. use time::Instant;
  6. use wire::{IpProtocol, IpRepr, IpEndpoint, UdpRepr};
  7. pub type UdpPacketMetadata = PacketMetadata<IpEndpoint>;
  8. pub type UdpSocketBuffer<'a, 'b> = PacketBuffer<'a, 'b, IpEndpoint>;
  9. /// An User Datagram Protocol socket.
  10. ///
  11. /// An UDP socket is bound to a specific endpoint, and owns transmit and receive
  12. /// packet buffers.
  13. #[derive(Debug)]
  14. pub struct UdpSocket<'a, 'b: 'a> {
  15. pub(crate) meta: SocketMeta,
  16. endpoint: IpEndpoint,
  17. rx_buffer: UdpSocketBuffer<'a, 'b>,
  18. tx_buffer: UdpSocketBuffer<'a, 'b>,
  19. /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  20. hop_limit: Option<u8>
  21. }
  22. impl<'a, 'b> UdpSocket<'a, 'b> {
  23. /// Create an UDP socket with the given buffers.
  24. pub fn new(rx_buffer: UdpSocketBuffer<'a, 'b>,
  25. tx_buffer: UdpSocketBuffer<'a, 'b>) -> UdpSocket<'a, 'b> {
  26. UdpSocket {
  27. meta: SocketMeta::default(),
  28. endpoint: IpEndpoint::default(),
  29. rx_buffer: rx_buffer,
  30. tx_buffer: tx_buffer,
  31. hop_limit: None
  32. }
  33. }
  34. /// Return the socket handle.
  35. #[inline]
  36. pub fn handle(&self) -> SocketHandle {
  37. self.meta.handle
  38. }
  39. /// Return the bound endpoint.
  40. #[inline]
  41. pub fn endpoint(&self) -> IpEndpoint {
  42. self.endpoint
  43. }
  44. /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  45. ///
  46. /// See also the [set_hop_limit](#method.set_hop_limit) method
  47. pub fn hop_limit(&self) -> Option<u8> {
  48. self.hop_limit
  49. }
  50. /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  51. ///
  52. /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
  53. /// value (64).
  54. ///
  55. /// # Panics
  56. ///
  57. /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
  58. ///
  59. /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
  60. /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
  61. pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
  62. // A host MUST NOT send a datagram with a hop limit value of 0
  63. if let Some(0) = hop_limit {
  64. panic!("the time-to-live value of a packet must not be zero")
  65. }
  66. self.hop_limit = hop_limit
  67. }
  68. /// Bind the socket to the given endpoint.
  69. ///
  70. /// This function returns `Err(Error::Illegal)` if the socket was open
  71. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  72. /// if the port in the given endpoint is zero.
  73. pub fn bind<T: Into<IpEndpoint>>(&mut self, endpoint: T) -> Result<()> {
  74. let endpoint = endpoint.into();
  75. if endpoint.port == 0 { return Err(Error::Unaddressable) }
  76. if self.is_open() { return Err(Error::Illegal) }
  77. self.endpoint = endpoint;
  78. Ok(())
  79. }
  80. /// Check whether the socket is open.
  81. #[inline]
  82. pub fn is_open(&self) -> bool {
  83. self.endpoint.port != 0
  84. }
  85. /// Check whether the transmit buffer is full.
  86. #[inline]
  87. pub fn can_send(&self) -> bool {
  88. !self.tx_buffer.is_full()
  89. }
  90. /// Check whether the receive buffer is not empty.
  91. #[inline]
  92. pub fn can_recv(&self) -> bool {
  93. !self.rx_buffer.is_empty()
  94. }
  95. /// Enqueue a packet to be sent to a given remote endpoint, and return a pointer
  96. /// to its payload.
  97. ///
  98. /// This function returns `Err(Error::Exhausted)` if the transmit buffer is full and
  99. /// `Err(Error::Unaddressable)` if local or remote port, or remote address are unspecified.
  100. pub fn send(&mut self, size: usize, endpoint: IpEndpoint) -> Result<&mut [u8]> {
  101. if self.endpoint.port == 0 { return Err(Error::Unaddressable) }
  102. if !endpoint.is_specified() { return Err(Error::Unaddressable) }
  103. let payload_buf = self.tx_buffer.enqueue(size, endpoint)?;
  104. net_trace!("{}:{}:{}: buffer to send {} octets",
  105. self.meta.handle, self.endpoint, endpoint, size);
  106. Ok(payload_buf)
  107. }
  108. /// Enqueue a packet to be sent to a given remote endpoint, and fill it from a slice.
  109. ///
  110. /// See also [send](#method.send).
  111. pub fn send_slice(&mut self, data: &[u8], endpoint: IpEndpoint) -> Result<()> {
  112. self.send(data.len(), endpoint)?.copy_from_slice(data);
  113. Ok(())
  114. }
  115. /// Dequeue a packet received from a remote endpoint, and return the endpoint as well
  116. /// as a pointer to the payload.
  117. ///
  118. /// This function returns `Err(Error::Exhausted)` if the receive buffer is empty.
  119. pub fn recv(&mut self) -> Result<(&[u8], IpEndpoint)> {
  120. let (endpoint, payload_buf) = self.rx_buffer.dequeue()?;
  121. net_trace!("{}:{}:{}: receive {} buffered octets",
  122. self.meta.handle, self.endpoint,
  123. endpoint, payload_buf.len());
  124. Ok((payload_buf, endpoint))
  125. }
  126. /// Dequeue a packet received from a remote endpoint, copy the payload into the given slice,
  127. /// and return the amount of octets copied as well as the endpoint.
  128. ///
  129. /// See also [recv](#method.recv).
  130. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<(usize, IpEndpoint)> {
  131. let (buffer, endpoint) = self.recv()?;
  132. let length = min(data.len(), buffer.len());
  133. data[..length].copy_from_slice(&buffer[..length]);
  134. Ok((length, endpoint))
  135. }
  136. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &UdpRepr) -> bool {
  137. if self.endpoint.port != repr.dst_port { return false }
  138. if !self.endpoint.addr.is_unspecified() &&
  139. self.endpoint.addr != ip_repr.dst_addr() { return false }
  140. true
  141. }
  142. pub(crate) fn process(&mut self, ip_repr: &IpRepr, repr: &UdpRepr) -> Result<()> {
  143. debug_assert!(self.accepts(ip_repr, repr));
  144. let size = repr.payload.len();
  145. let endpoint = IpEndpoint { addr: ip_repr.src_addr(), port: repr.src_port };
  146. let payload_buf = self.rx_buffer.enqueue(size, endpoint)?;
  147. assert_eq!(payload_buf.len(), size);
  148. payload_buf.copy_from_slice(repr.payload);
  149. net_trace!("{}:{}:{}: receiving {} octets",
  150. self.meta.handle, self.endpoint,
  151. endpoint, size);
  152. Ok(())
  153. }
  154. pub(crate) fn dispatch<F>(&mut self, emit: F) -> Result<()>
  155. where F: FnOnce((IpRepr, UdpRepr)) -> Result<()> {
  156. let handle = self.handle();
  157. let endpoint = self.endpoint;
  158. let hop_limit = self.hop_limit.unwrap_or(64);
  159. self.tx_buffer.dequeue_with(|remote_endpoint, payload_buf| {
  160. net_trace!("{}:{}:{}: sending {} octets",
  161. handle, endpoint,
  162. endpoint, payload_buf.len());
  163. let repr = UdpRepr {
  164. src_port: endpoint.port,
  165. dst_port: remote_endpoint.port,
  166. payload: payload_buf,
  167. };
  168. let ip_repr = IpRepr::Unspecified {
  169. src_addr: endpoint.addr,
  170. dst_addr: remote_endpoint.addr,
  171. protocol: IpProtocol::Udp,
  172. payload_len: repr.buffer_len(),
  173. hop_limit: hop_limit,
  174. };
  175. emit((ip_repr, repr))
  176. })
  177. }
  178. pub(crate) fn poll_at(&self) -> Option<Instant> {
  179. if self.tx_buffer.is_empty() {
  180. None
  181. } else {
  182. Some(Instant::from_millis(0))
  183. }
  184. }
  185. }
  186. impl<'a, 'b> Into<Socket<'a, 'b>> for UdpSocket<'a, 'b> {
  187. fn into(self) -> Socket<'a, 'b> {
  188. Socket::Udp(self)
  189. }
  190. }
  191. #[cfg(test)]
  192. mod test {
  193. use wire::{IpAddress, IpRepr, UdpRepr};
  194. #[cfg(feature = "proto-ipv4")]
  195. use wire::Ipv4Repr;
  196. #[cfg(feature = "proto-ipv6")]
  197. use wire::Ipv6Repr;
  198. use wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3};
  199. use super::*;
  200. fn buffer(packets: usize) -> UdpSocketBuffer<'static, 'static> {
  201. UdpSocketBuffer::new(vec![UdpPacketMetadata::empty(); packets], vec![0; 16 * packets])
  202. }
  203. fn socket(rx_buffer: UdpSocketBuffer<'static, 'static>,
  204. tx_buffer: UdpSocketBuffer<'static, 'static>)
  205. -> UdpSocket<'static, 'static> {
  206. UdpSocket::new(rx_buffer, tx_buffer)
  207. }
  208. const LOCAL_PORT: u16 = 53;
  209. const REMOTE_PORT: u16 = 49500;
  210. pub const LOCAL_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_1, port: LOCAL_PORT };
  211. pub const REMOTE_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_2, port: REMOTE_PORT };
  212. pub const LOCAL_IP_REPR: IpRepr = IpRepr::Unspecified {
  213. src_addr: MOCK_IP_ADDR_1,
  214. dst_addr: MOCK_IP_ADDR_2,
  215. protocol: IpProtocol::Udp,
  216. payload_len: 8 + 6,
  217. hop_limit: 64,
  218. };
  219. const LOCAL_UDP_REPR: UdpRepr = UdpRepr {
  220. src_port: LOCAL_PORT,
  221. dst_port: REMOTE_PORT,
  222. payload: b"abcdef"
  223. };
  224. const REMOTE_UDP_REPR: UdpRepr = UdpRepr {
  225. src_port: REMOTE_PORT,
  226. dst_port: LOCAL_PORT,
  227. payload: b"abcdef"
  228. };
  229. fn remote_ip_repr() -> IpRepr {
  230. match (MOCK_IP_ADDR_2, MOCK_IP_ADDR_1) {
  231. #[cfg(feature = "proto-ipv4")]
  232. (IpAddress::Ipv4(src), IpAddress::Ipv4(dst)) => IpRepr::Ipv4(Ipv4Repr {
  233. src_addr: src,
  234. dst_addr: dst,
  235. protocol: IpProtocol::Udp,
  236. payload_len: 8 + 6,
  237. hop_limit: 64
  238. }),
  239. #[cfg(feature = "proto-ipv6")]
  240. (IpAddress::Ipv6(src), IpAddress::Ipv6(dst)) => IpRepr::Ipv6(Ipv6Repr {
  241. src_addr: src,
  242. dst_addr: dst,
  243. next_header: IpProtocol::Udp,
  244. payload_len: 8 + 6,
  245. hop_limit: 64
  246. }),
  247. _ => unreachable!()
  248. }
  249. }
  250. #[test]
  251. fn test_bind_unaddressable() {
  252. let mut socket = socket(buffer(0), buffer(0));
  253. assert_eq!(socket.bind(0), Err(Error::Unaddressable));
  254. }
  255. #[test]
  256. fn test_bind_twice() {
  257. let mut socket = socket(buffer(0), buffer(0));
  258. assert_eq!(socket.bind(1), Ok(()));
  259. assert_eq!(socket.bind(2), Err(Error::Illegal));
  260. }
  261. #[test]
  262. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  263. fn test_set_hop_limit_zero() {
  264. let mut s = socket(buffer(0), buffer(1));
  265. s.set_hop_limit(Some(0));
  266. }
  267. #[test]
  268. fn test_send_unaddressable() {
  269. let mut socket = socket(buffer(0), buffer(1));
  270. assert_eq!(socket.send_slice(b"abcdef", REMOTE_END), Err(Error::Unaddressable));
  271. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  272. assert_eq!(socket.send_slice(b"abcdef",
  273. IpEndpoint { addr: IpAddress::Unspecified, ..REMOTE_END }),
  274. Err(Error::Unaddressable));
  275. assert_eq!(socket.send_slice(b"abcdef",
  276. IpEndpoint { port: 0, ..REMOTE_END }),
  277. Err(Error::Unaddressable));
  278. assert_eq!(socket.send_slice(b"abcdef", REMOTE_END), Ok(()));
  279. }
  280. #[test]
  281. fn test_send_dispatch() {
  282. let mut socket = socket(buffer(0), buffer(1));
  283. assert_eq!(socket.bind(LOCAL_END), Ok(()));
  284. assert!(socket.can_send());
  285. assert_eq!(socket.dispatch(|_| unreachable!()),
  286. Err(Error::Exhausted));
  287. assert_eq!(socket.send_slice(b"abcdef", REMOTE_END), Ok(()));
  288. assert_eq!(socket.send_slice(b"123456", REMOTE_END), Err(Error::Exhausted));
  289. assert!(!socket.can_send());
  290. assert_eq!(socket.dispatch(|(ip_repr, udp_repr)| {
  291. assert_eq!(ip_repr, LOCAL_IP_REPR);
  292. assert_eq!(udp_repr, LOCAL_UDP_REPR);
  293. Err(Error::Unaddressable)
  294. }), Err(Error::Unaddressable));
  295. assert!(!socket.can_send());
  296. assert_eq!(socket.dispatch(|(ip_repr, udp_repr)| {
  297. assert_eq!(ip_repr, LOCAL_IP_REPR);
  298. assert_eq!(udp_repr, LOCAL_UDP_REPR);
  299. Ok(())
  300. }), Ok(()));
  301. assert!(socket.can_send());
  302. }
  303. #[test]
  304. fn test_recv_process() {
  305. let mut socket = socket(buffer(1), buffer(0));
  306. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  307. assert!(!socket.can_recv());
  308. assert_eq!(socket.recv(), Err(Error::Exhausted));
  309. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  310. assert_eq!(socket.process(&remote_ip_repr(), &REMOTE_UDP_REPR),
  311. Ok(()));
  312. assert!(socket.can_recv());
  313. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  314. assert_eq!(socket.process(&remote_ip_repr(), &REMOTE_UDP_REPR),
  315. Err(Error::Exhausted));
  316. assert_eq!(socket.recv(), Ok((&b"abcdef"[..], REMOTE_END)));
  317. assert!(!socket.can_recv());
  318. }
  319. #[test]
  320. fn test_recv_truncated_slice() {
  321. let mut socket = socket(buffer(1), buffer(0));
  322. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  323. assert!(socket.accepts(&remote_ip_repr(), &REMOTE_UDP_REPR));
  324. assert_eq!(socket.process(&remote_ip_repr(), &REMOTE_UDP_REPR),
  325. Ok(()));
  326. let mut slice = [0; 4];
  327. assert_eq!(socket.recv_slice(&mut slice[..]), Ok((4, REMOTE_END)));
  328. assert_eq!(&slice, b"abcd");
  329. }
  330. #[test]
  331. fn test_set_hop_limit() {
  332. let mut s = socket(buffer(0), buffer(1));
  333. assert_eq!(s.bind(LOCAL_END), Ok(()));
  334. s.set_hop_limit(Some(0x2a));
  335. assert_eq!(s.send_slice(b"abcdef", REMOTE_END), Ok(()));
  336. assert_eq!(s.dispatch(|(ip_repr, _)| {
  337. assert_eq!(ip_repr, IpRepr::Unspecified{
  338. src_addr: MOCK_IP_ADDR_1,
  339. dst_addr: MOCK_IP_ADDR_2,
  340. protocol: IpProtocol::Udp,
  341. payload_len: 8 + 6,
  342. hop_limit: 0x2a,
  343. });
  344. Ok(())
  345. }), Ok(()));
  346. }
  347. #[test]
  348. fn test_doesnt_accept_wrong_port() {
  349. let mut socket = socket(buffer(1), buffer(0));
  350. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  351. let mut udp_repr = REMOTE_UDP_REPR;
  352. assert!(socket.accepts(&remote_ip_repr(), &udp_repr));
  353. udp_repr.dst_port += 1;
  354. assert!(!socket.accepts(&remote_ip_repr(), &udp_repr));
  355. }
  356. #[test]
  357. fn test_doesnt_accept_wrong_ip() {
  358. fn generate_bad_repr() -> IpRepr {
  359. match (MOCK_IP_ADDR_2, MOCK_IP_ADDR_3) {
  360. #[cfg(feature = "proto-ipv4")]
  361. (IpAddress::Ipv4(src), IpAddress::Ipv4(dst)) => IpRepr::Ipv4(Ipv4Repr {
  362. src_addr: src,
  363. dst_addr: dst,
  364. protocol: IpProtocol::Udp,
  365. payload_len: 8 + 6,
  366. hop_limit: 64
  367. }),
  368. #[cfg(feature = "proto-ipv6")]
  369. (IpAddress::Ipv6(src), IpAddress::Ipv6(dst)) => IpRepr::Ipv6(Ipv6Repr {
  370. src_addr: src,
  371. dst_addr: dst,
  372. next_header: IpProtocol::Udp,
  373. payload_len: 8 + 6,
  374. hop_limit: 64
  375. }),
  376. _ => unreachable!()
  377. }
  378. }
  379. let mut port_bound_socket = socket(buffer(1), buffer(0));
  380. assert_eq!(port_bound_socket.bind(LOCAL_PORT), Ok(()));
  381. assert!(port_bound_socket.accepts(&generate_bad_repr(), &REMOTE_UDP_REPR));
  382. let mut ip_bound_socket = socket(buffer(1), buffer(0));
  383. assert_eq!(ip_bound_socket.bind(LOCAL_END), Ok(()));
  384. assert!(!ip_bound_socket.accepts(&generate_bad_repr(), &REMOTE_UDP_REPR));
  385. }
  386. #[test]
  387. fn test_send_large_packet() {
  388. // buffer(4) creates a payload buffer of size 16*4
  389. let mut socket = socket(buffer(0), buffer(4));
  390. assert_eq!(socket.bind(LOCAL_END), Ok(()));
  391. let too_large = b"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdefx";
  392. assert_eq!(socket.send_slice(too_large, REMOTE_END), Err(Error::Exhausted));
  393. assert_eq!(socket.send_slice(&too_large[..16*4], REMOTE_END), Ok(()));
  394. }
  395. #[test]
  396. fn test_process_empty_payload() {
  397. let recv_buffer = UdpSocketBuffer::new(vec![UdpPacketMetadata::empty(); 1], vec![]);
  398. let mut socket = socket(recv_buffer, buffer(0));
  399. assert_eq!(socket.bind(LOCAL_PORT), Ok(()));
  400. let repr = UdpRepr {
  401. src_port: REMOTE_PORT,
  402. dst_port: LOCAL_PORT,
  403. payload: &[]
  404. };
  405. assert_eq!(socket.process(&remote_ip_repr(), &repr), Ok(()));
  406. assert_eq!(socket.recv(), Ok((&[][..], REMOTE_END)));
  407. }
  408. }