udp.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. use byteorder::{ByteOrder, NetworkEndian};
  2. use core::fmt;
  3. use super::{Error, Result};
  4. use crate::phy::ChecksumCapabilities;
  5. use crate::wire::ip::checksum;
  6. use crate::wire::{IpAddress, IpProtocol};
  7. /// A read/write wrapper around an User Datagram Protocol packet buffer.
  8. #[derive(Debug, PartialEq, Clone)]
  9. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  10. pub struct Packet<T: AsRef<[u8]>> {
  11. buffer: T,
  12. }
  13. mod field {
  14. #![allow(non_snake_case)]
  15. use crate::wire::field::*;
  16. pub const SRC_PORT: Field = 0..2;
  17. pub const DST_PORT: Field = 2..4;
  18. pub const LENGTH: Field = 4..6;
  19. pub const CHECKSUM: Field = 6..8;
  20. pub fn PAYLOAD(length: u16) -> Field {
  21. CHECKSUM.end..(length as usize)
  22. }
  23. }
  24. pub const HEADER_LEN: usize = field::CHECKSUM.end;
  25. #[allow(clippy::len_without_is_empty)]
  26. impl<T: AsRef<[u8]>> Packet<T> {
  27. /// Imbue a raw octet buffer with UDP packet structure.
  28. pub fn new_unchecked(buffer: T) -> Packet<T> {
  29. Packet { buffer }
  30. }
  31. /// Shorthand for a combination of [new_unchecked] and [check_len].
  32. ///
  33. /// [new_unchecked]: #method.new_unchecked
  34. /// [check_len]: #method.check_len
  35. pub fn new_checked(buffer: T) -> Result<Packet<T>> {
  36. let packet = Self::new_unchecked(buffer);
  37. packet.check_len()?;
  38. Ok(packet)
  39. }
  40. /// Ensure that no accessor method will panic if called.
  41. /// Returns `Err(Error)` if the buffer is too short.
  42. /// Returns `Err(Error)` if the length field has a value smaller
  43. /// than the header length.
  44. ///
  45. /// The result of this check is invalidated by calling [set_len].
  46. ///
  47. /// [set_len]: #method.set_len
  48. pub fn check_len(&self) -> Result<()> {
  49. let buffer_len = self.buffer.as_ref().len();
  50. if buffer_len < HEADER_LEN {
  51. Err(Error)
  52. } else {
  53. let field_len = self.len() as usize;
  54. if buffer_len < field_len || field_len < HEADER_LEN {
  55. Err(Error)
  56. } else {
  57. Ok(())
  58. }
  59. }
  60. }
  61. /// Consume the packet, returning the underlying buffer.
  62. pub fn into_inner(self) -> T {
  63. self.buffer
  64. }
  65. /// Return the source port field.
  66. #[inline]
  67. pub fn src_port(&self) -> u16 {
  68. let data = self.buffer.as_ref();
  69. NetworkEndian::read_u16(&data[field::SRC_PORT])
  70. }
  71. /// Return the destination port field.
  72. #[inline]
  73. pub fn dst_port(&self) -> u16 {
  74. let data = self.buffer.as_ref();
  75. NetworkEndian::read_u16(&data[field::DST_PORT])
  76. }
  77. /// Return the length field.
  78. #[inline]
  79. pub fn len(&self) -> u16 {
  80. let data = self.buffer.as_ref();
  81. NetworkEndian::read_u16(&data[field::LENGTH])
  82. }
  83. /// Return the checksum field.
  84. #[inline]
  85. pub fn checksum(&self) -> u16 {
  86. let data = self.buffer.as_ref();
  87. NetworkEndian::read_u16(&data[field::CHECKSUM])
  88. }
  89. /// Validate the packet checksum.
  90. ///
  91. /// # Panics
  92. /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
  93. /// and that family is IPv4 or IPv6.
  94. ///
  95. /// # Fuzzing
  96. /// This function always returns `true` when fuzzing.
  97. pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
  98. if cfg!(fuzzing) {
  99. return true;
  100. }
  101. // From the RFC:
  102. // > An all zero transmitted checksum value means that the transmitter
  103. // > generated no checksum (for debugging or for higher level protocols
  104. // > that don't care).
  105. if self.checksum() == 0 {
  106. return true;
  107. }
  108. let data = self.buffer.as_ref();
  109. checksum::combine(&[
  110. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Udp, self.len() as u32),
  111. checksum::data(&data[..self.len() as usize]),
  112. ]) == !0
  113. }
  114. }
  115. impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
  116. /// Return a pointer to the payload.
  117. #[inline]
  118. pub fn payload(&self) -> &'a [u8] {
  119. let length = self.len();
  120. let data = self.buffer.as_ref();
  121. &data[field::PAYLOAD(length)]
  122. }
  123. }
  124. impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
  125. /// Set the source port field.
  126. #[inline]
  127. pub fn set_src_port(&mut self, value: u16) {
  128. let data = self.buffer.as_mut();
  129. NetworkEndian::write_u16(&mut data[field::SRC_PORT], value)
  130. }
  131. /// Set the destination port field.
  132. #[inline]
  133. pub fn set_dst_port(&mut self, value: u16) {
  134. let data = self.buffer.as_mut();
  135. NetworkEndian::write_u16(&mut data[field::DST_PORT], value)
  136. }
  137. /// Set the length field.
  138. #[inline]
  139. pub fn set_len(&mut self, value: u16) {
  140. let data = self.buffer.as_mut();
  141. NetworkEndian::write_u16(&mut data[field::LENGTH], value)
  142. }
  143. /// Set the checksum field.
  144. #[inline]
  145. pub fn set_checksum(&mut self, value: u16) {
  146. let data = self.buffer.as_mut();
  147. NetworkEndian::write_u16(&mut data[field::CHECKSUM], value)
  148. }
  149. /// Compute and fill in the header checksum.
  150. ///
  151. /// # Panics
  152. /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
  153. /// and that family is IPv4 or IPv6.
  154. pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
  155. self.set_checksum(0);
  156. let checksum = {
  157. let data = self.buffer.as_ref();
  158. !checksum::combine(&[
  159. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Udp, self.len() as u32),
  160. checksum::data(&data[..self.len() as usize]),
  161. ])
  162. };
  163. // UDP checksum value of 0 means no checksum; if the checksum really is zero,
  164. // use all-ones, which indicates that the remote end must verify the checksum.
  165. // Arithmetically, RFC 1071 checksums of all-zeroes and all-ones behave identically,
  166. // so no action is necessary on the remote end.
  167. self.set_checksum(if checksum == 0 { 0xffff } else { checksum })
  168. }
  169. /// Return a mutable pointer to the payload.
  170. #[inline]
  171. pub fn payload_mut(&mut self) -> &mut [u8] {
  172. let length = self.len();
  173. let data = self.buffer.as_mut();
  174. &mut data[field::PAYLOAD(length)]
  175. }
  176. }
  177. impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
  178. fn as_ref(&self) -> &[u8] {
  179. self.buffer.as_ref()
  180. }
  181. }
  182. /// A high-level representation of an User Datagram Protocol packet.
  183. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  184. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  185. pub struct Repr {
  186. pub src_port: u16,
  187. pub dst_port: u16,
  188. }
  189. impl Repr {
  190. /// Parse an User Datagram Protocol packet and return a high-level representation.
  191. pub fn parse<T>(
  192. packet: &Packet<&T>,
  193. src_addr: &IpAddress,
  194. dst_addr: &IpAddress,
  195. checksum_caps: &ChecksumCapabilities,
  196. ) -> Result<Repr>
  197. where
  198. T: AsRef<[u8]> + ?Sized,
  199. {
  200. // Destination port cannot be omitted (but source port can be).
  201. if packet.dst_port() == 0 {
  202. return Err(Error);
  203. }
  204. // Valid checksum is expected...
  205. if checksum_caps.udp.rx() && !packet.verify_checksum(src_addr, dst_addr) {
  206. match (src_addr, dst_addr) {
  207. // ... except on UDP-over-IPv4, where it can be omitted.
  208. #[cfg(feature = "proto-ipv4")]
  209. (&IpAddress::Ipv4(_), &IpAddress::Ipv4(_)) if packet.checksum() == 0 => (),
  210. _ => return Err(Error),
  211. }
  212. }
  213. Ok(Repr {
  214. src_port: packet.src_port(),
  215. dst_port: packet.dst_port(),
  216. })
  217. }
  218. /// Return the length of the packet header that will be emitted from this high-level representation.
  219. pub fn header_len(&self) -> usize {
  220. HEADER_LEN
  221. }
  222. /// Emit a high-level representation into an User Datagram Protocol packet.
  223. pub fn emit<T: ?Sized>(
  224. &self,
  225. packet: &mut Packet<&mut T>,
  226. src_addr: &IpAddress,
  227. dst_addr: &IpAddress,
  228. payload_len: usize,
  229. emit_payload: impl FnOnce(&mut [u8]),
  230. checksum_caps: &ChecksumCapabilities,
  231. ) where
  232. T: AsRef<[u8]> + AsMut<[u8]>,
  233. {
  234. packet.set_src_port(self.src_port);
  235. packet.set_dst_port(self.dst_port);
  236. packet.set_len((HEADER_LEN + payload_len) as u16);
  237. emit_payload(packet.payload_mut());
  238. if checksum_caps.udp.tx() {
  239. packet.fill_checksum(src_addr, dst_addr)
  240. } else {
  241. // make sure we get a consistently zeroed checksum,
  242. // since implementations might rely on it
  243. packet.set_checksum(0);
  244. }
  245. }
  246. }
  247. impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Packet<&'a T> {
  248. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  249. // Cannot use Repr::parse because we don't have the IP addresses.
  250. write!(
  251. f,
  252. "UDP src={} dst={} len={}",
  253. self.src_port(),
  254. self.dst_port(),
  255. self.payload().len()
  256. )
  257. }
  258. }
  259. impl fmt::Display for Repr {
  260. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  261. write!(f, "UDP src={} dst={}", self.src_port, self.dst_port)
  262. }
  263. }
  264. use crate::wire::pretty_print::{PrettyIndent, PrettyPrint};
  265. impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
  266. fn pretty_print(
  267. buffer: &dyn AsRef<[u8]>,
  268. f: &mut fmt::Formatter,
  269. indent: &mut PrettyIndent,
  270. ) -> fmt::Result {
  271. match Packet::new_checked(buffer) {
  272. Err(err) => write!(f, "{}({})", indent, err),
  273. Ok(packet) => write!(f, "{}{}", indent, packet),
  274. }
  275. }
  276. }
  277. #[cfg(test)]
  278. mod test {
  279. use super::*;
  280. #[cfg(feature = "proto-ipv4")]
  281. use crate::wire::Ipv4Address;
  282. #[cfg(feature = "proto-ipv4")]
  283. const SRC_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 1]);
  284. #[cfg(feature = "proto-ipv4")]
  285. const DST_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 2]);
  286. #[cfg(feature = "proto-ipv4")]
  287. static PACKET_BYTES: [u8; 12] = [
  288. 0xbf, 0x00, 0x00, 0x35, 0x00, 0x0c, 0x12, 0x4d, 0xaa, 0x00, 0x00, 0xff,
  289. ];
  290. #[cfg(feature = "proto-ipv4")]
  291. static NO_CHECKSUM_PACKET: [u8; 12] = [
  292. 0xbf, 0x00, 0x00, 0x35, 0x00, 0x0c, 0x00, 0x00, 0xaa, 0x00, 0x00, 0xff,
  293. ];
  294. #[cfg(feature = "proto-ipv4")]
  295. static PAYLOAD_BYTES: [u8; 4] = [0xaa, 0x00, 0x00, 0xff];
  296. #[test]
  297. #[cfg(feature = "proto-ipv4")]
  298. fn test_deconstruct() {
  299. let packet = Packet::new_unchecked(&PACKET_BYTES[..]);
  300. assert_eq!(packet.src_port(), 48896);
  301. assert_eq!(packet.dst_port(), 53);
  302. assert_eq!(packet.len(), 12);
  303. assert_eq!(packet.checksum(), 0x124d);
  304. assert_eq!(packet.payload(), &PAYLOAD_BYTES[..]);
  305. assert!(packet.verify_checksum(&SRC_ADDR.into(), &DST_ADDR.into()));
  306. }
  307. #[test]
  308. #[cfg(feature = "proto-ipv4")]
  309. fn test_construct() {
  310. let mut bytes = vec![0xa5; 12];
  311. let mut packet = Packet::new_unchecked(&mut bytes);
  312. packet.set_src_port(48896);
  313. packet.set_dst_port(53);
  314. packet.set_len(12);
  315. packet.set_checksum(0xffff);
  316. packet.payload_mut().copy_from_slice(&PAYLOAD_BYTES[..]);
  317. packet.fill_checksum(&SRC_ADDR.into(), &DST_ADDR.into());
  318. assert_eq!(&packet.into_inner()[..], &PACKET_BYTES[..]);
  319. }
  320. #[test]
  321. fn test_impossible_len() {
  322. let mut bytes = vec![0; 12];
  323. let mut packet = Packet::new_unchecked(&mut bytes);
  324. packet.set_len(4);
  325. assert_eq!(packet.check_len(), Err(Error));
  326. }
  327. #[test]
  328. #[cfg(feature = "proto-ipv4")]
  329. fn test_zero_checksum() {
  330. let mut bytes = vec![0; 8];
  331. let mut packet = Packet::new_unchecked(&mut bytes);
  332. packet.set_src_port(1);
  333. packet.set_dst_port(31881);
  334. packet.set_len(8);
  335. packet.fill_checksum(&SRC_ADDR.into(), &DST_ADDR.into());
  336. assert_eq!(packet.checksum(), 0xffff);
  337. }
  338. #[test]
  339. #[cfg(feature = "proto-ipv4")]
  340. fn test_no_checksum() {
  341. let mut bytes = vec![0; 8];
  342. let mut packet = Packet::new_unchecked(&mut bytes);
  343. packet.set_src_port(1);
  344. packet.set_dst_port(31881);
  345. packet.set_len(8);
  346. packet.set_checksum(0);
  347. assert!(packet.verify_checksum(&SRC_ADDR.into(), &DST_ADDR.into()));
  348. }
  349. #[cfg(feature = "proto-ipv4")]
  350. fn packet_repr() -> Repr {
  351. Repr {
  352. src_port: 48896,
  353. dst_port: 53,
  354. }
  355. }
  356. #[test]
  357. #[cfg(feature = "proto-ipv4")]
  358. fn test_parse() {
  359. let packet = Packet::new_unchecked(&PACKET_BYTES[..]);
  360. let repr = Repr::parse(
  361. &packet,
  362. &SRC_ADDR.into(),
  363. &DST_ADDR.into(),
  364. &ChecksumCapabilities::default(),
  365. )
  366. .unwrap();
  367. assert_eq!(repr, packet_repr());
  368. }
  369. #[test]
  370. #[cfg(feature = "proto-ipv4")]
  371. fn test_emit() {
  372. let repr = packet_repr();
  373. let mut bytes = vec![0xa5; repr.header_len() + PAYLOAD_BYTES.len()];
  374. let mut packet = Packet::new_unchecked(&mut bytes);
  375. repr.emit(
  376. &mut packet,
  377. &SRC_ADDR.into(),
  378. &DST_ADDR.into(),
  379. PAYLOAD_BYTES.len(),
  380. |payload| payload.copy_from_slice(&PAYLOAD_BYTES),
  381. &ChecksumCapabilities::default(),
  382. );
  383. assert_eq!(&packet.into_inner()[..], &PACKET_BYTES[..]);
  384. }
  385. #[test]
  386. #[cfg(feature = "proto-ipv4")]
  387. fn test_checksum_omitted() {
  388. let packet = Packet::new_unchecked(&NO_CHECKSUM_PACKET[..]);
  389. let repr = Repr::parse(
  390. &packet,
  391. &SRC_ADDR.into(),
  392. &DST_ADDR.into(),
  393. &ChecksumCapabilities::default(),
  394. )
  395. .unwrap();
  396. assert_eq!(repr, packet_repr());
  397. }
  398. }