ipv6fragment.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. use super::{Error, Result};
  2. use core::fmt;
  3. use byteorder::{ByteOrder, NetworkEndian};
  4. pub use super::IpProtocol as Protocol;
  5. /// A read/write wrapper around an IPv6 Fragment Header.
  6. #[derive(Debug, PartialEq, Eq)]
  7. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  8. pub struct Header<T: AsRef<[u8]>> {
  9. buffer: T,
  10. }
  11. // Format of the Fragment Header
  12. //
  13. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  14. // | Next Header | Reserved | Fragment Offset |Res|M|
  15. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  16. // | Identification |
  17. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  18. //
  19. // See https://tools.ietf.org/html/rfc8200#section-4.5 for details.
  20. //
  21. // **NOTE**: The fields start counting after the header length field.
  22. mod field {
  23. use crate::wire::field::*;
  24. // 16-bit field containing the fragment offset, reserved and more fragments values.
  25. pub const FR_OF_M: Field = 0..2;
  26. // 32-bit field identifying the fragmented packet
  27. pub const IDENT: Field = 2..6;
  28. /// 1 bit flag indicating if there are more fragments coming.
  29. pub const M: usize = 1;
  30. }
  31. impl<T: AsRef<[u8]>> Header<T> {
  32. /// Create a raw octet buffer with an IPv6 Fragment Header structure.
  33. pub const fn new_unchecked(buffer: T) -> Header<T> {
  34. Header { buffer }
  35. }
  36. /// Shorthand for a combination of [new_unchecked] and [check_len].
  37. ///
  38. /// [new_unchecked]: #method.new_unchecked
  39. /// [check_len]: #method.check_len
  40. pub fn new_checked(buffer: T) -> Result<Header<T>> {
  41. let header = Self::new_unchecked(buffer);
  42. header.check_len()?;
  43. Ok(header)
  44. }
  45. /// Ensure that no accessor method will panic if called.
  46. /// Returns `Err(Error)` if the buffer is too short.
  47. pub fn check_len(&self) -> Result<()> {
  48. let data = self.buffer.as_ref();
  49. let len = data.len();
  50. if len < field::IDENT.end {
  51. Err(Error)
  52. } else {
  53. Ok(())
  54. }
  55. }
  56. /// Consume the header, returning the underlying buffer.
  57. pub fn into_inner(self) -> T {
  58. self.buffer
  59. }
  60. /// Return the fragment offset field.
  61. #[inline]
  62. pub fn frag_offset(&self) -> u16 {
  63. let data = self.buffer.as_ref();
  64. NetworkEndian::read_u16(&data[field::FR_OF_M]) >> 3
  65. }
  66. /// Return more fragment flag field.
  67. #[inline]
  68. pub fn more_frags(&self) -> bool {
  69. let data = self.buffer.as_ref();
  70. (data[field::M] & 0x1) == 1
  71. }
  72. /// Return the fragment identification value field.
  73. #[inline]
  74. pub fn ident(&self) -> u32 {
  75. let data = self.buffer.as_ref();
  76. NetworkEndian::read_u32(&data[field::IDENT])
  77. }
  78. }
  79. impl<T: AsRef<[u8]> + AsMut<[u8]>> Header<T> {
  80. /// Set reserved fields.
  81. ///
  82. /// Set 8-bit reserved field after the next header field.
  83. /// Set 2-bit reserved field between fragment offset and more fragments.
  84. #[inline]
  85. pub fn clear_reserved(&mut self) {
  86. let data = self.buffer.as_mut();
  87. // Retain the higher order 5 bits and lower order 1 bit
  88. data[field::M] &= 0xf9;
  89. }
  90. /// Set the fragment offset field.
  91. #[inline]
  92. pub fn set_frag_offset(&mut self, value: u16) {
  93. let data = self.buffer.as_mut();
  94. // Retain the lower order 3 bits
  95. let raw = ((value & 0x1fff) << 3) | ((data[field::M] & 0x7) as u16);
  96. NetworkEndian::write_u16(&mut data[field::FR_OF_M], raw);
  97. }
  98. /// Set the more fragments flag field.
  99. #[inline]
  100. pub fn set_more_frags(&mut self, value: bool) {
  101. let data = self.buffer.as_mut();
  102. // Retain the high order 7 bits
  103. let raw = (data[field::M] & 0xfe) | (value as u8 & 0x1);
  104. data[field::M] = raw;
  105. }
  106. /// Set the fragmentation identification field.
  107. #[inline]
  108. pub fn set_ident(&mut self, value: u32) {
  109. let data = self.buffer.as_mut();
  110. NetworkEndian::write_u32(&mut data[field::IDENT], value);
  111. }
  112. }
  113. impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Header<&'a T> {
  114. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  115. match Repr::parse(self) {
  116. Ok(repr) => write!(f, "{repr}"),
  117. Err(err) => {
  118. write!(f, "IPv6 Fragment ({err})")?;
  119. Ok(())
  120. }
  121. }
  122. }
  123. }
  124. /// A high-level representation of an IPv6 Fragment header.
  125. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  126. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  127. pub struct Repr {
  128. /// The offset of the data following this header, relative to the start of the Fragmentable
  129. /// Part of the original packet.
  130. pub frag_offset: u16,
  131. /// When there are more fragments following this header
  132. pub more_frags: bool,
  133. /// The identification for every packet that is fragmented.
  134. pub ident: u32,
  135. }
  136. impl Repr {
  137. /// Parse an IPv6 Fragment Header and return a high-level representation.
  138. pub fn parse<T>(header: &Header<&T>) -> Result<Repr>
  139. where
  140. T: AsRef<[u8]> + ?Sized,
  141. {
  142. Ok(Repr {
  143. frag_offset: header.frag_offset(),
  144. more_frags: header.more_frags(),
  145. ident: header.ident(),
  146. })
  147. }
  148. /// Return the length, in bytes, of a header that will be emitted from this high-level
  149. /// representation.
  150. pub const fn buffer_len(&self) -> usize {
  151. field::IDENT.end
  152. }
  153. /// Emit a high-level representation into an IPv6 Fragment Header.
  154. pub fn emit<T: AsRef<[u8]> + AsMut<[u8]> + ?Sized>(&self, header: &mut Header<&mut T>) {
  155. header.clear_reserved();
  156. header.set_frag_offset(self.frag_offset);
  157. header.set_more_frags(self.more_frags);
  158. header.set_ident(self.ident);
  159. }
  160. }
  161. impl fmt::Display for Repr {
  162. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  163. write!(
  164. f,
  165. "IPv6 Fragment offset={} more={} ident={}",
  166. self.frag_offset, self.more_frags, self.ident
  167. )
  168. }
  169. }
  170. #[cfg(test)]
  171. mod test {
  172. use super::*;
  173. // A Fragment Header with more fragments remaining
  174. static BYTES_HEADER_MORE_FRAG: [u8; 6] = [0x0, 0x1, 0x0, 0x0, 0x30, 0x39];
  175. // A Fragment Header with no more fragments remaining
  176. static BYTES_HEADER_LAST_FRAG: [u8; 6] = [0xa, 0x0, 0x0, 0x1, 0x9, 0x32];
  177. #[test]
  178. fn test_check_len() {
  179. // less than 6 bytes
  180. assert_eq!(
  181. Err(Error),
  182. Header::new_unchecked(&BYTES_HEADER_MORE_FRAG[..5]).check_len()
  183. );
  184. // valid
  185. assert_eq!(
  186. Ok(()),
  187. Header::new_unchecked(&BYTES_HEADER_MORE_FRAG).check_len()
  188. );
  189. }
  190. #[test]
  191. fn test_header_deconstruct() {
  192. let header = Header::new_unchecked(&BYTES_HEADER_MORE_FRAG);
  193. assert_eq!(header.frag_offset(), 0);
  194. assert!(header.more_frags());
  195. assert_eq!(header.ident(), 12345);
  196. let header = Header::new_unchecked(&BYTES_HEADER_LAST_FRAG);
  197. assert_eq!(header.frag_offset(), 320);
  198. assert!(!header.more_frags());
  199. assert_eq!(header.ident(), 67890);
  200. }
  201. #[test]
  202. fn test_repr_parse_valid() {
  203. let header = Header::new_unchecked(&BYTES_HEADER_MORE_FRAG);
  204. let repr = Repr::parse(&header).unwrap();
  205. assert_eq!(
  206. repr,
  207. Repr {
  208. frag_offset: 0,
  209. more_frags: true,
  210. ident: 12345
  211. }
  212. );
  213. let header = Header::new_unchecked(&BYTES_HEADER_LAST_FRAG);
  214. let repr = Repr::parse(&header).unwrap();
  215. assert_eq!(
  216. repr,
  217. Repr {
  218. frag_offset: 320,
  219. more_frags: false,
  220. ident: 67890
  221. }
  222. );
  223. }
  224. #[test]
  225. fn test_repr_emit() {
  226. let repr = Repr {
  227. frag_offset: 0,
  228. more_frags: true,
  229. ident: 12345,
  230. };
  231. let mut bytes = [0u8; 6];
  232. let mut header = Header::new_unchecked(&mut bytes);
  233. repr.emit(&mut header);
  234. assert_eq!(header.into_inner(), &BYTES_HEADER_MORE_FRAG[0..6]);
  235. let repr = Repr {
  236. frag_offset: 320,
  237. more_frags: false,
  238. ident: 67890,
  239. };
  240. let mut bytes = [0u8; 6];
  241. let mut header = Header::new_unchecked(&mut bytes);
  242. repr.emit(&mut header);
  243. assert_eq!(header.into_inner(), &BYTES_HEADER_LAST_FRAG[0..6]);
  244. }
  245. #[test]
  246. fn test_buffer_len() {
  247. let header = Header::new_unchecked(&BYTES_HEADER_MORE_FRAG);
  248. let repr = Repr::parse(&header).unwrap();
  249. assert_eq!(repr.buffer_len(), BYTES_HEADER_MORE_FRAG.len());
  250. }
  251. }