udp.rs 17 KB

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