ipv6.rs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. #![deny(missing_docs)]
  2. use byteorder::{ByteOrder, NetworkEndian};
  3. use core::fmt;
  4. use crate::wire::ip::pretty_print_ip_payload;
  5. #[cfg(feature = "proto-ipv4")]
  6. use crate::wire::ipv4;
  7. use crate::{Error, Result};
  8. pub use super::IpProtocol as Protocol;
  9. /// Minimum MTU required of all links supporting IPv6. See [RFC 8200 § 5].
  10. ///
  11. /// [RFC 8200 § 5]: https://tools.ietf.org/html/rfc8200#section-5
  12. pub const MIN_MTU: usize = 1280;
  13. /// A sixteen-octet IPv6 address.
  14. #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
  15. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  16. pub struct Address(pub [u8; 16]);
  17. impl Address {
  18. /// The [unspecified address].
  19. ///
  20. /// [unspecified address]: https://tools.ietf.org/html/rfc4291#section-2.5.2
  21. pub const UNSPECIFIED: Address = Address([0x00; 16]);
  22. /// The link-local [all routers multicast address].
  23. ///
  24. /// [all routers multicast address]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  25. pub const LINK_LOCAL_ALL_NODES: Address = Address([
  26. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  27. 0x01,
  28. ]);
  29. /// The link-local [all nodes multicast address].
  30. ///
  31. /// [all nodes multicast address]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  32. pub const LINK_LOCAL_ALL_ROUTERS: Address = Address([
  33. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  34. 0x02,
  35. ]);
  36. /// The [loopback address].
  37. ///
  38. /// [loopback address]: https://tools.ietf.org/html/rfc4291#section-2.5.3
  39. pub const LOOPBACK: Address = Address([
  40. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  41. 0x01,
  42. ]);
  43. /// Construct an IPv6 address from parts.
  44. #[allow(clippy::too_many_arguments)]
  45. pub fn new(a0: u16, a1: u16, a2: u16, a3: u16, a4: u16, a5: u16, a6: u16, a7: u16) -> Address {
  46. let mut addr = [0u8; 16];
  47. NetworkEndian::write_u16(&mut addr[0..2], a0);
  48. NetworkEndian::write_u16(&mut addr[2..4], a1);
  49. NetworkEndian::write_u16(&mut addr[4..6], a2);
  50. NetworkEndian::write_u16(&mut addr[6..8], a3);
  51. NetworkEndian::write_u16(&mut addr[8..10], a4);
  52. NetworkEndian::write_u16(&mut addr[10..12], a5);
  53. NetworkEndian::write_u16(&mut addr[12..14], a6);
  54. NetworkEndian::write_u16(&mut addr[14..16], a7);
  55. Address(addr)
  56. }
  57. /// Construct an IPv6 address from a sequence of octets, in big-endian.
  58. ///
  59. /// # Panics
  60. /// The function panics if `data` is not sixteen octets long.
  61. pub fn from_bytes(data: &[u8]) -> Address {
  62. let mut bytes = [0; 16];
  63. bytes.copy_from_slice(data);
  64. Address(bytes)
  65. }
  66. /// Construct an IPv6 address from a sequence of words, in big-endian.
  67. ///
  68. /// # Panics
  69. /// The function panics if `data` is not 8 words long.
  70. pub fn from_parts(data: &[u16]) -> Address {
  71. assert!(data.len() >= 8);
  72. let mut bytes = [0; 16];
  73. for (word_idx, chunk) in bytes.chunks_mut(2).enumerate() {
  74. NetworkEndian::write_u16(chunk, data[word_idx]);
  75. }
  76. Address(bytes)
  77. }
  78. /// Write a IPv6 address to the given slice.
  79. ///
  80. /// # Panics
  81. /// The function panics if `data` is not 8 words long.
  82. pub fn write_parts(&self, data: &mut [u16]) {
  83. assert!(data.len() >= 8);
  84. for (i, chunk) in self.0.chunks(2).enumerate() {
  85. data[i] = NetworkEndian::read_u16(chunk);
  86. }
  87. }
  88. /// Return an IPv6 address as a sequence of octets, in big-endian.
  89. pub fn as_bytes(&self) -> &[u8] {
  90. &self.0
  91. }
  92. /// Query whether the IPv6 address is an [unicast address].
  93. ///
  94. /// [unicast address]: https://tools.ietf.org/html/rfc4291#section-2.5
  95. pub fn is_unicast(&self) -> bool {
  96. !(self.is_multicast() || self.is_unspecified())
  97. }
  98. /// Query whether the IPv6 address is a [multicast address].
  99. ///
  100. /// [multicast address]: https://tools.ietf.org/html/rfc4291#section-2.7
  101. pub fn is_multicast(&self) -> bool {
  102. self.0[0] == 0xff
  103. }
  104. /// Query whether the IPv6 address is the [unspecified address].
  105. ///
  106. /// [unspecified address]: https://tools.ietf.org/html/rfc4291#section-2.5.2
  107. pub fn is_unspecified(&self) -> bool {
  108. self.0 == [0x00; 16]
  109. }
  110. /// Query whether the IPv6 address is in the [link-local] scope.
  111. ///
  112. /// [link-local]: https://tools.ietf.org/html/rfc4291#section-2.5.6
  113. pub fn is_link_local(&self) -> bool {
  114. self.0[0..8] == [0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
  115. }
  116. /// Query whether the IPv6 address is the [loopback address].
  117. ///
  118. /// [loopback address]: https://tools.ietf.org/html/rfc4291#section-2.5.3
  119. pub fn is_loopback(&self) -> bool {
  120. *self == Self::LOOPBACK
  121. }
  122. /// Query whether the IPv6 address is an [IPv4 mapped IPv6 address].
  123. ///
  124. /// [IPv4 mapped IPv6 address]: https://tools.ietf.org/html/rfc4291#section-2.5.5.2
  125. pub fn is_ipv4_mapped(&self) -> bool {
  126. self.0[0..12] == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff]
  127. }
  128. #[cfg(feature = "proto-ipv4")]
  129. /// Convert an IPv4 mapped IPv6 address to an IPv4 address.
  130. pub fn as_ipv4(&self) -> Option<ipv4::Address> {
  131. if self.is_ipv4_mapped() {
  132. Some(ipv4::Address::new(
  133. self.0[12], self.0[13], self.0[14], self.0[15],
  134. ))
  135. } else {
  136. None
  137. }
  138. }
  139. /// Helper function used to mask an addres given a prefix.
  140. ///
  141. /// # Panics
  142. /// This function panics if `mask` is greater than 128.
  143. pub(super) fn mask(&self, mask: u8) -> [u8; 16] {
  144. assert!(mask <= 128);
  145. let mut bytes = [0u8; 16];
  146. let idx = (mask as usize) / 8;
  147. let modulus = (mask as usize) % 8;
  148. let (first, second) = self.0.split_at(idx);
  149. bytes[0..idx].copy_from_slice(first);
  150. if idx < 16 {
  151. let part = second[0];
  152. bytes[idx] = part & (!(0xff >> modulus) as u8);
  153. }
  154. bytes
  155. }
  156. /// The solicited node for the given unicast address.
  157. ///
  158. /// # Panics
  159. /// This function panics if the given address is not
  160. /// unicast.
  161. pub fn solicited_node(&self) -> Address {
  162. assert!(self.is_unicast());
  163. Address([
  164. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFF,
  165. self.0[13], self.0[14], self.0[15],
  166. ])
  167. }
  168. }
  169. #[cfg(feature = "std")]
  170. impl From<::std::net::Ipv6Addr> for Address {
  171. fn from(x: ::std::net::Ipv6Addr) -> Address {
  172. Address(x.octets())
  173. }
  174. }
  175. #[cfg(feature = "std")]
  176. impl From<Address> for ::std::net::Ipv6Addr {
  177. fn from(Address(x): Address) -> ::std::net::Ipv6Addr {
  178. x.into()
  179. }
  180. }
  181. impl fmt::Display for Address {
  182. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  183. if self.is_ipv4_mapped() {
  184. return write!(
  185. f,
  186. "::ffff:{}.{}.{}.{}",
  187. self.0[12], self.0[13], self.0[14], self.0[15]
  188. );
  189. }
  190. // The string representation of an IPv6 address should
  191. // collapse a series of 16 bit sections that evaluate
  192. // to 0 to "::"
  193. //
  194. // See https://tools.ietf.org/html/rfc4291#section-2.2
  195. // for details.
  196. enum State {
  197. Head,
  198. HeadBody,
  199. Tail,
  200. TailBody,
  201. }
  202. let mut words = [0u16; 8];
  203. self.write_parts(&mut words);
  204. let mut state = State::Head;
  205. for word in words.iter() {
  206. state = match (*word, &state) {
  207. // Once a u16 equal to zero write a double colon and
  208. // skip to the next non-zero u16.
  209. (0, &State::Head) | (0, &State::HeadBody) => {
  210. write!(f, "::")?;
  211. State::Tail
  212. }
  213. // Continue iterating without writing any characters until
  214. // we hit anothing non-zero value.
  215. (0, &State::Tail) => State::Tail,
  216. // When the state is Head or Tail write a u16 in hexadecimal
  217. // without the leading colon if the value is not 0.
  218. (_, &State::Head) => {
  219. write!(f, "{:x}", word)?;
  220. State::HeadBody
  221. }
  222. (_, &State::Tail) => {
  223. write!(f, "{:x}", word)?;
  224. State::TailBody
  225. }
  226. // Write the u16 with a leading colon when parsing a value
  227. // that isn't the first in a section
  228. (_, &State::HeadBody) | (_, &State::TailBody) => {
  229. write!(f, ":{:x}", word)?;
  230. state
  231. }
  232. }
  233. }
  234. Ok(())
  235. }
  236. }
  237. #[cfg(feature = "proto-ipv4")]
  238. /// Convert the given IPv4 address into a IPv4-mapped IPv6 address
  239. impl From<ipv4::Address> for Address {
  240. fn from(address: ipv4::Address) -> Self {
  241. let octets = address.0;
  242. Address([
  243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, octets[0], octets[1], octets[2], octets[3],
  244. ])
  245. }
  246. }
  247. /// A specification of an IPv6 CIDR block, containing an address and a variable-length
  248. /// subnet masking prefix length.
  249. #[derive(Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default)]
  250. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  251. pub struct Cidr {
  252. address: Address,
  253. prefix_len: u8,
  254. }
  255. impl Cidr {
  256. /// The [solicited node prefix].
  257. ///
  258. /// [solicited node prefix]: https://tools.ietf.org/html/rfc4291#section-2.7.1
  259. pub const SOLICITED_NODE_PREFIX: Cidr = Cidr {
  260. address: Address([
  261. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00,
  262. 0x00, 0x00,
  263. ]),
  264. prefix_len: 104,
  265. };
  266. /// Create an IPv6 CIDR block from the given address and prefix length.
  267. ///
  268. /// # Panics
  269. /// This function panics if the prefix length is larger than 128.
  270. pub fn new(address: Address, prefix_len: u8) -> Cidr {
  271. assert!(prefix_len <= 128);
  272. Cidr {
  273. address,
  274. prefix_len,
  275. }
  276. }
  277. /// Return the address of this IPv6 CIDR block.
  278. pub fn address(&self) -> Address {
  279. self.address
  280. }
  281. /// Return the prefix length of this IPv6 CIDR block.
  282. pub fn prefix_len(&self) -> u8 {
  283. self.prefix_len
  284. }
  285. /// Query whether the subnetwork described by this IPv6 CIDR block contains
  286. /// the given address.
  287. pub fn contains_addr(&self, addr: &Address) -> bool {
  288. // right shift by 128 is not legal
  289. if self.prefix_len == 0 {
  290. return true;
  291. }
  292. let shift = 128 - self.prefix_len;
  293. self.address.mask(shift) == addr.mask(shift)
  294. }
  295. /// Query whether the subnetwork described by this IPV6 CIDR block contains
  296. /// the subnetwork described by the given IPv6 CIDR block.
  297. pub fn contains_subnet(&self, subnet: &Cidr) -> bool {
  298. self.prefix_len <= subnet.prefix_len && self.contains_addr(&subnet.address)
  299. }
  300. }
  301. impl fmt::Display for Cidr {
  302. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  303. // https://tools.ietf.org/html/rfc4291#section-2.3
  304. write!(f, "{}/{}", self.address, self.prefix_len)
  305. }
  306. }
  307. /// A read/write wrapper around an Internet Protocol version 6 packet buffer.
  308. #[derive(Debug, PartialEq, Clone)]
  309. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  310. pub struct Packet<T: AsRef<[u8]>> {
  311. buffer: T,
  312. }
  313. // Ranges and constants describing the IPv6 header
  314. //
  315. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  316. // |Version| Traffic Class | Flow Label |
  317. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  318. // | Payload Length | Next Header | Hop Limit |
  319. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  320. // | |
  321. // + +
  322. // | |
  323. // + Source Address +
  324. // | |
  325. // + +
  326. // | |
  327. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  328. // | |
  329. // + +
  330. // | |
  331. // + Destination Address +
  332. // | |
  333. // + +
  334. // | |
  335. // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  336. //
  337. // See https://tools.ietf.org/html/rfc2460#section-3 for details.
  338. mod field {
  339. use crate::wire::field::*;
  340. // 4-bit version number, 8-bit traffic class, and the
  341. // 20-bit flow label.
  342. pub const VER_TC_FLOW: Field = 0..4;
  343. // 16-bit value representing the length of the payload.
  344. // Note: Options are included in this length.
  345. pub const LENGTH: Field = 4..6;
  346. // 8-bit value identifying the type of header following this
  347. // one. Note: The same numbers are used in IPv4.
  348. pub const NXT_HDR: usize = 6;
  349. // 8-bit value decremented by each node that forwards this
  350. // packet. The packet is discarded when the value is 0.
  351. pub const HOP_LIMIT: usize = 7;
  352. // IPv6 address of the source node.
  353. pub const SRC_ADDR: Field = 8..24;
  354. // IPv6 address of the destination node.
  355. pub const DST_ADDR: Field = 24..40;
  356. }
  357. /// Length of an IPv6 header.
  358. pub const HEADER_LEN: usize = field::DST_ADDR.end;
  359. impl<T: AsRef<[u8]>> Packet<T> {
  360. /// Create a raw octet buffer with an IPv6 packet structure.
  361. #[inline]
  362. pub fn new_unchecked(buffer: T) -> Packet<T> {
  363. Packet { buffer }
  364. }
  365. /// Shorthand for a combination of [new_unchecked] and [check_len].
  366. ///
  367. /// [new_unchecked]: #method.new_unchecked
  368. /// [check_len]: #method.check_len
  369. #[inline]
  370. pub fn new_checked(buffer: T) -> Result<Packet<T>> {
  371. let packet = Self::new_unchecked(buffer);
  372. packet.check_len()?;
  373. Ok(packet)
  374. }
  375. /// Ensure that no accessor method will panic if called.
  376. /// Returns `Err(Error::Truncated)` if the buffer is too short.
  377. ///
  378. /// The result of this check is invalidated by calling [set_payload_len].
  379. ///
  380. /// [set_payload_len]: #method.set_payload_len
  381. #[inline]
  382. pub fn check_len(&self) -> Result<()> {
  383. let len = self.buffer.as_ref().len();
  384. if len < field::DST_ADDR.end || len < self.total_len() {
  385. Err(Error::Truncated)
  386. } else {
  387. Ok(())
  388. }
  389. }
  390. /// Consume the packet, returning the underlying buffer.
  391. #[inline]
  392. pub fn into_inner(self) -> T {
  393. self.buffer
  394. }
  395. /// Return the header length.
  396. #[inline]
  397. pub fn header_len(&self) -> usize {
  398. // This is not a strictly necessary function, but it makes
  399. // code more readable.
  400. field::DST_ADDR.end
  401. }
  402. /// Return the version field.
  403. #[inline]
  404. pub fn version(&self) -> u8 {
  405. let data = self.buffer.as_ref();
  406. data[field::VER_TC_FLOW.start] >> 4
  407. }
  408. /// Return the traffic class.
  409. #[inline]
  410. pub fn traffic_class(&self) -> u8 {
  411. let data = self.buffer.as_ref();
  412. ((NetworkEndian::read_u16(&data[0..2]) & 0x0ff0) >> 4) as u8
  413. }
  414. /// Return the flow label field.
  415. #[inline]
  416. pub fn flow_label(&self) -> u32 {
  417. let data = self.buffer.as_ref();
  418. NetworkEndian::read_u24(&data[1..4]) & 0x000fffff
  419. }
  420. /// Return the payload length field.
  421. #[inline]
  422. pub fn payload_len(&self) -> u16 {
  423. let data = self.buffer.as_ref();
  424. NetworkEndian::read_u16(&data[field::LENGTH])
  425. }
  426. /// Return the payload length added to the known header length.
  427. #[inline]
  428. pub fn total_len(&self) -> usize {
  429. self.header_len() + self.payload_len() as usize
  430. }
  431. /// Return the next header field.
  432. #[inline]
  433. pub fn next_header(&self) -> Protocol {
  434. let data = self.buffer.as_ref();
  435. Protocol::from(data[field::NXT_HDR])
  436. }
  437. /// Return the hop limit field.
  438. #[inline]
  439. pub fn hop_limit(&self) -> u8 {
  440. let data = self.buffer.as_ref();
  441. data[field::HOP_LIMIT]
  442. }
  443. /// Return the source address field.
  444. #[inline]
  445. pub fn src_addr(&self) -> Address {
  446. let data = self.buffer.as_ref();
  447. Address::from_bytes(&data[field::SRC_ADDR])
  448. }
  449. /// Return the destination address field.
  450. #[inline]
  451. pub fn dst_addr(&self) -> Address {
  452. let data = self.buffer.as_ref();
  453. Address::from_bytes(&data[field::DST_ADDR])
  454. }
  455. }
  456. impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
  457. /// Return a pointer to the payload.
  458. #[inline]
  459. pub fn payload(&self) -> &'a [u8] {
  460. let data = self.buffer.as_ref();
  461. let range = self.header_len()..self.total_len();
  462. &data[range]
  463. }
  464. }
  465. impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
  466. /// Set the version field.
  467. #[inline]
  468. pub fn set_version(&mut self, value: u8) {
  469. let data = self.buffer.as_mut();
  470. // Make sure to retain the lower order bits which contain
  471. // the higher order bits of the traffic class
  472. data[0] = (data[0] & 0x0f) | ((value & 0x0f) << 4);
  473. }
  474. /// Set the traffic class field.
  475. #[inline]
  476. pub fn set_traffic_class(&mut self, value: u8) {
  477. let data = self.buffer.as_mut();
  478. // Put the higher order 4-bits of value in the lower order
  479. // 4-bits of the first byte
  480. data[0] = (data[0] & 0xf0) | ((value & 0xf0) >> 4);
  481. // Put the lower order 4-bits of value in the higher order
  482. // 4-bits of the second byte
  483. data[1] = (data[1] & 0x0f) | ((value & 0x0f) << 4);
  484. }
  485. /// Set the flow label field.
  486. #[inline]
  487. pub fn set_flow_label(&mut self, value: u32) {
  488. let data = self.buffer.as_mut();
  489. // Retain the lower order 4-bits of the traffic class
  490. let raw = (((data[1] & 0xf0) as u32) << 16) | (value & 0x0fffff);
  491. NetworkEndian::write_u24(&mut data[1..4], raw);
  492. }
  493. /// Set the payload length field.
  494. #[inline]
  495. pub fn set_payload_len(&mut self, value: u16) {
  496. let data = self.buffer.as_mut();
  497. NetworkEndian::write_u16(&mut data[field::LENGTH], value);
  498. }
  499. /// Set the next header field.
  500. #[inline]
  501. pub fn set_next_header(&mut self, value: Protocol) {
  502. let data = self.buffer.as_mut();
  503. data[field::NXT_HDR] = value.into();
  504. }
  505. /// Set the hop limit field.
  506. #[inline]
  507. pub fn set_hop_limit(&mut self, value: u8) {
  508. let data = self.buffer.as_mut();
  509. data[field::HOP_LIMIT] = value;
  510. }
  511. /// Set the source address field.
  512. #[inline]
  513. pub fn set_src_addr(&mut self, value: Address) {
  514. let data = self.buffer.as_mut();
  515. data[field::SRC_ADDR].copy_from_slice(value.as_bytes());
  516. }
  517. /// Set the destination address field.
  518. #[inline]
  519. pub fn set_dst_addr(&mut self, value: Address) {
  520. let data = self.buffer.as_mut();
  521. data[field::DST_ADDR].copy_from_slice(value.as_bytes());
  522. }
  523. /// Return a mutable pointer to the payload.
  524. #[inline]
  525. pub fn payload_mut(&mut self) -> &mut [u8] {
  526. let range = self.header_len()..self.total_len();
  527. let data = self.buffer.as_mut();
  528. &mut data[range]
  529. }
  530. }
  531. impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Packet<&'a T> {
  532. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  533. match Repr::parse(self) {
  534. Ok(repr) => write!(f, "{}", repr),
  535. Err(err) => {
  536. write!(f, "IPv6 ({})", err)?;
  537. Ok(())
  538. }
  539. }
  540. }
  541. }
  542. impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
  543. fn as_ref(&self) -> &[u8] {
  544. self.buffer.as_ref()
  545. }
  546. }
  547. /// A high-level representation of an Internet Protocol version 6 packet header.
  548. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  549. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  550. pub struct Repr {
  551. /// IPv6 address of the source node.
  552. pub src_addr: Address,
  553. /// IPv6 address of the destination node.
  554. pub dst_addr: Address,
  555. /// Protocol contained in the next header.
  556. pub next_header: Protocol,
  557. /// Length of the payload including the extension headers.
  558. pub payload_len: usize,
  559. /// The 8-bit hop limit field.
  560. pub hop_limit: u8,
  561. }
  562. impl Repr {
  563. /// Parse an Internet Protocol version 6 packet and return a high-level representation.
  564. pub fn parse<T: AsRef<[u8]> + ?Sized>(packet: &Packet<&T>) -> Result<Repr> {
  565. // Ensure basic accessors will work
  566. packet.check_len()?;
  567. if packet.version() != 6 {
  568. return Err(Error::Malformed);
  569. }
  570. Ok(Repr {
  571. src_addr: packet.src_addr(),
  572. dst_addr: packet.dst_addr(),
  573. next_header: packet.next_header(),
  574. payload_len: packet.payload_len() as usize,
  575. hop_limit: packet.hop_limit(),
  576. })
  577. }
  578. /// Return the length of a header that will be emitted from this high-level representation.
  579. pub fn buffer_len(&self) -> usize {
  580. // This function is not strictly necessary, but it can make client code more readable.
  581. field::DST_ADDR.end
  582. }
  583. /// Emit a high-level representation into an Internet Protocol version 6 packet.
  584. pub fn emit<T: AsRef<[u8]> + AsMut<[u8]>>(&self, packet: &mut Packet<T>) {
  585. // Make no assumptions about the original state of the packet buffer.
  586. // Make sure to set every byte.
  587. packet.set_version(6);
  588. packet.set_traffic_class(0);
  589. packet.set_flow_label(0);
  590. packet.set_payload_len(self.payload_len as u16);
  591. packet.set_hop_limit(self.hop_limit);
  592. packet.set_next_header(self.next_header);
  593. packet.set_src_addr(self.src_addr);
  594. packet.set_dst_addr(self.dst_addr);
  595. }
  596. }
  597. impl fmt::Display for Repr {
  598. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  599. write!(
  600. f,
  601. "IPv6 src={} dst={} nxt_hdr={} hop_limit={}",
  602. self.src_addr, self.dst_addr, self.next_header, self.hop_limit
  603. )
  604. }
  605. }
  606. use crate::wire::pretty_print::{PrettyIndent, PrettyPrint};
  607. // TODO: This is very similar to the implementation for IPv4. Make
  608. // a way to have less copy and pasted code here.
  609. impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
  610. fn pretty_print(
  611. buffer: &dyn AsRef<[u8]>,
  612. f: &mut fmt::Formatter,
  613. indent: &mut PrettyIndent,
  614. ) -> fmt::Result {
  615. let (ip_repr, payload) = match Packet::new_checked(buffer) {
  616. Err(err) => return write!(f, "{}({})", indent, err),
  617. Ok(ip_packet) => match Repr::parse(&ip_packet) {
  618. Err(_) => return Ok(()),
  619. Ok(ip_repr) => {
  620. write!(f, "{}{}", indent, ip_repr)?;
  621. (ip_repr, ip_packet.payload())
  622. }
  623. },
  624. };
  625. pretty_print_ip_payload(f, indent, ip_repr, payload)
  626. }
  627. }
  628. #[cfg(test)]
  629. mod test {
  630. use super::{Address, Cidr};
  631. use super::{Packet, Protocol, Repr};
  632. use crate::wire::pretty_print::PrettyPrinter;
  633. use crate::Error;
  634. #[cfg(feature = "proto-ipv4")]
  635. use crate::wire::ipv4::Address as Ipv4Address;
  636. static LINK_LOCAL_ADDR: Address = Address([
  637. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  638. 0x01,
  639. ]);
  640. #[test]
  641. fn test_basic_multicast() {
  642. assert!(!Address::LINK_LOCAL_ALL_ROUTERS.is_unspecified());
  643. assert!(Address::LINK_LOCAL_ALL_ROUTERS.is_multicast());
  644. assert!(!Address::LINK_LOCAL_ALL_ROUTERS.is_link_local());
  645. assert!(!Address::LINK_LOCAL_ALL_ROUTERS.is_loopback());
  646. assert!(!Address::LINK_LOCAL_ALL_NODES.is_unspecified());
  647. assert!(Address::LINK_LOCAL_ALL_NODES.is_multicast());
  648. assert!(!Address::LINK_LOCAL_ALL_NODES.is_link_local());
  649. assert!(!Address::LINK_LOCAL_ALL_NODES.is_loopback());
  650. }
  651. #[test]
  652. fn test_basic_link_local() {
  653. assert!(!LINK_LOCAL_ADDR.is_unspecified());
  654. assert!(!LINK_LOCAL_ADDR.is_multicast());
  655. assert!(LINK_LOCAL_ADDR.is_link_local());
  656. assert!(!LINK_LOCAL_ADDR.is_loopback());
  657. }
  658. #[test]
  659. fn test_basic_loopback() {
  660. assert!(!Address::LOOPBACK.is_unspecified());
  661. assert!(!Address::LOOPBACK.is_multicast());
  662. assert!(!Address::LOOPBACK.is_link_local());
  663. assert!(Address::LOOPBACK.is_loopback());
  664. }
  665. #[test]
  666. fn test_address_format() {
  667. assert_eq!("ff02::1", format!("{}", Address::LINK_LOCAL_ALL_NODES));
  668. assert_eq!("fe80::1", format!("{}", LINK_LOCAL_ADDR));
  669. assert_eq!(
  670. "fe80::7f00:0:1",
  671. format!(
  672. "{}",
  673. Address::new(0xfe80, 0, 0, 0, 0, 0x7f00, 0x0000, 0x0001)
  674. )
  675. );
  676. assert_eq!("::", format!("{}", Address::UNSPECIFIED));
  677. assert_eq!("::1", format!("{}", Address::LOOPBACK));
  678. #[cfg(feature = "proto-ipv4")]
  679. assert_eq!(
  680. "::ffff:192.168.1.1",
  681. format!("{}", Address::from(Ipv4Address::new(192, 168, 1, 1)))
  682. );
  683. }
  684. #[test]
  685. fn test_new() {
  686. assert_eq!(
  687. Address::new(0xff02, 0, 0, 0, 0, 0, 0, 1),
  688. Address::LINK_LOCAL_ALL_NODES
  689. );
  690. assert_eq!(
  691. Address::new(0xff02, 0, 0, 0, 0, 0, 0, 2),
  692. Address::LINK_LOCAL_ALL_ROUTERS
  693. );
  694. assert_eq!(Address::new(0, 0, 0, 0, 0, 0, 0, 1), Address::LOOPBACK);
  695. assert_eq!(Address::new(0, 0, 0, 0, 0, 0, 0, 0), Address::UNSPECIFIED);
  696. assert_eq!(Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 1), LINK_LOCAL_ADDR);
  697. }
  698. #[test]
  699. fn test_from_parts() {
  700. assert_eq!(
  701. Address::from_parts(&[0xff02, 0, 0, 0, 0, 0, 0, 1]),
  702. Address::LINK_LOCAL_ALL_NODES
  703. );
  704. assert_eq!(
  705. Address::from_parts(&[0xff02, 0, 0, 0, 0, 0, 0, 2]),
  706. Address::LINK_LOCAL_ALL_ROUTERS
  707. );
  708. assert_eq!(
  709. Address::from_parts(&[0, 0, 0, 0, 0, 0, 0, 1]),
  710. Address::LOOPBACK
  711. );
  712. assert_eq!(
  713. Address::from_parts(&[0, 0, 0, 0, 0, 0, 0, 0]),
  714. Address::UNSPECIFIED
  715. );
  716. assert_eq!(
  717. Address::from_parts(&[0xfe80, 0, 0, 0, 0, 0, 0, 1]),
  718. LINK_LOCAL_ADDR
  719. );
  720. }
  721. #[test]
  722. fn test_write_parts() {
  723. let mut bytes = [0u16; 8];
  724. {
  725. Address::LOOPBACK.write_parts(&mut bytes);
  726. assert_eq!(Address::LOOPBACK, Address::from_parts(&bytes));
  727. }
  728. {
  729. Address::LINK_LOCAL_ALL_ROUTERS.write_parts(&mut bytes);
  730. assert_eq!(Address::LINK_LOCAL_ALL_ROUTERS, Address::from_parts(&bytes));
  731. }
  732. {
  733. LINK_LOCAL_ADDR.write_parts(&mut bytes);
  734. assert_eq!(LINK_LOCAL_ADDR, Address::from_parts(&bytes));
  735. }
  736. }
  737. #[test]
  738. fn test_mask() {
  739. let addr = Address::new(0x0123, 0x4567, 0x89ab, 0, 0, 0, 0, 1);
  740. assert_eq!(
  741. addr.mask(11),
  742. [0x01, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  743. );
  744. assert_eq!(
  745. addr.mask(15),
  746. [0x01, 0x22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  747. );
  748. assert_eq!(
  749. addr.mask(26),
  750. [0x01, 0x23, 0x45, 0x40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  751. );
  752. assert_eq!(
  753. addr.mask(128),
  754. [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
  755. );
  756. assert_eq!(
  757. addr.mask(127),
  758. [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
  759. );
  760. }
  761. #[cfg(feature = "proto-ipv4")]
  762. #[test]
  763. fn test_is_ipv4_mapped() {
  764. assert!(!Address::UNSPECIFIED.is_ipv4_mapped());
  765. assert!(Address::from(Ipv4Address::new(192, 168, 1, 1)).is_ipv4_mapped());
  766. }
  767. #[cfg(feature = "proto-ipv4")]
  768. #[test]
  769. fn test_as_ipv4() {
  770. assert_eq!(None, Address::UNSPECIFIED.as_ipv4());
  771. let ipv4 = Ipv4Address::new(192, 168, 1, 1);
  772. assert_eq!(Some(ipv4), Address::from(ipv4).as_ipv4());
  773. }
  774. #[cfg(feature = "proto-ipv4")]
  775. #[test]
  776. fn test_from_ipv4_address() {
  777. assert_eq!(
  778. Address([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 168, 1, 1]),
  779. Address::from(Ipv4Address::new(192, 168, 1, 1))
  780. );
  781. assert_eq!(
  782. Address([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 222, 1, 41, 90]),
  783. Address::from(Ipv4Address::new(222, 1, 41, 90))
  784. );
  785. }
  786. #[test]
  787. fn test_cidr() {
  788. let cidr = Cidr::new(LINK_LOCAL_ADDR, 64);
  789. let inside_subnet = [
  790. [
  791. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  792. 0x00, 0x02,
  793. ],
  794. [
  795. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
  796. 0x77, 0x88,
  797. ],
  798. [
  799. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00,
  800. 0x00, 0x00,
  801. ],
  802. [
  803. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  804. 0x00, 0xff,
  805. ],
  806. ];
  807. let outside_subnet = [
  808. [
  809. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  810. 0x00, 0x01,
  811. ],
  812. [
  813. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  814. 0x00, 0x01,
  815. ],
  816. [
  817. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  818. 0x00, 0x01,
  819. ],
  820. [
  821. 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  822. 0x00, 0x02,
  823. ],
  824. ];
  825. let subnets = [
  826. (
  827. [
  828. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
  829. 0xff, 0xff, 0xff,
  830. ],
  831. 65,
  832. ),
  833. (
  834. [
  835. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  836. 0x00, 0x00, 0x01,
  837. ],
  838. 128,
  839. ),
  840. (
  841. [
  842. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12,
  843. 0x34, 0x56, 0x78,
  844. ],
  845. 96,
  846. ),
  847. ];
  848. let not_subnets = [
  849. (
  850. [
  851. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
  852. 0xff, 0xff, 0xff,
  853. ],
  854. 63,
  855. ),
  856. (
  857. [
  858. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff,
  859. 0xff, 0xff, 0xff,
  860. ],
  861. 64,
  862. ),
  863. (
  864. [
  865. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff,
  866. 0xff, 0xff, 0xff,
  867. ],
  868. 65,
  869. ),
  870. (
  871. [
  872. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  873. 0x00, 0x00, 0x01,
  874. ],
  875. 128,
  876. ),
  877. ];
  878. for addr in inside_subnet.iter().map(|a| Address::from_bytes(a)) {
  879. assert!(cidr.contains_addr(&addr));
  880. }
  881. for addr in outside_subnet.iter().map(|a| Address::from_bytes(a)) {
  882. assert!(!cidr.contains_addr(&addr));
  883. }
  884. for subnet in subnets.iter().map(|&(a, p)| Cidr::new(Address(a), p)) {
  885. assert!(cidr.contains_subnet(&subnet));
  886. }
  887. for subnet in not_subnets.iter().map(|&(a, p)| Cidr::new(Address(a), p)) {
  888. assert!(!cidr.contains_subnet(&subnet));
  889. }
  890. let cidr_without_prefix = Cidr::new(LINK_LOCAL_ADDR, 0);
  891. assert!(cidr_without_prefix.contains_addr(&Address::LOOPBACK));
  892. }
  893. #[test]
  894. #[should_panic(expected = "length")]
  895. fn test_from_bytes_too_long() {
  896. let _ = Address::from_bytes(&[0u8; 15]);
  897. }
  898. #[test]
  899. #[should_panic(expected = "data.len() >= 8")]
  900. fn test_from_parts_too_long() {
  901. let _ = Address::from_parts(&[0u16; 7]);
  902. }
  903. static REPR_PACKET_BYTES: [u8; 52] = [
  904. 0x60, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x11, 0x40, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
  905. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00,
  906. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x02, 0x00,
  907. 0x0c, 0x02, 0x4e, 0xff, 0xff, 0xff, 0xff,
  908. ];
  909. static REPR_PAYLOAD_BYTES: [u8; 12] = [
  910. 0x00, 0x01, 0x00, 0x02, 0x00, 0x0c, 0x02, 0x4e, 0xff, 0xff, 0xff, 0xff,
  911. ];
  912. fn packet_repr() -> Repr {
  913. Repr {
  914. src_addr: Address([
  915. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  916. 0x00, 0x01,
  917. ]),
  918. dst_addr: Address::LINK_LOCAL_ALL_NODES,
  919. next_header: Protocol::Udp,
  920. payload_len: 12,
  921. hop_limit: 64,
  922. }
  923. }
  924. #[test]
  925. fn test_packet_deconstruction() {
  926. let packet = Packet::new_unchecked(&REPR_PACKET_BYTES[..]);
  927. assert_eq!(packet.check_len(), Ok(()));
  928. assert_eq!(packet.version(), 6);
  929. assert_eq!(packet.traffic_class(), 0);
  930. assert_eq!(packet.flow_label(), 0);
  931. assert_eq!(packet.total_len(), 0x34);
  932. assert_eq!(packet.payload_len() as usize, REPR_PAYLOAD_BYTES.len());
  933. assert_eq!(packet.next_header(), Protocol::Udp);
  934. assert_eq!(packet.hop_limit(), 0x40);
  935. assert_eq!(
  936. packet.src_addr(),
  937. Address([
  938. 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  939. 0x00, 0x01
  940. ])
  941. );
  942. assert_eq!(packet.dst_addr(), Address::LINK_LOCAL_ALL_NODES);
  943. assert_eq!(packet.payload(), &REPR_PAYLOAD_BYTES[..]);
  944. }
  945. #[test]
  946. fn test_packet_construction() {
  947. let mut bytes = [0xff; 52];
  948. let mut packet = Packet::new_unchecked(&mut bytes[..]);
  949. // Version, Traffic Class, and Flow Label are not
  950. // byte aligned. make sure the setters and getters
  951. // do not interfere with each other.
  952. packet.set_version(6);
  953. assert_eq!(packet.version(), 6);
  954. packet.set_traffic_class(0x99);
  955. assert_eq!(packet.version(), 6);
  956. assert_eq!(packet.traffic_class(), 0x99);
  957. packet.set_flow_label(0x54321);
  958. assert_eq!(packet.traffic_class(), 0x99);
  959. assert_eq!(packet.flow_label(), 0x54321);
  960. packet.set_payload_len(0xc);
  961. packet.set_next_header(Protocol::Udp);
  962. packet.set_hop_limit(0xfe);
  963. packet.set_src_addr(Address::LINK_LOCAL_ALL_ROUTERS);
  964. packet.set_dst_addr(Address::LINK_LOCAL_ALL_NODES);
  965. packet
  966. .payload_mut()
  967. .copy_from_slice(&REPR_PAYLOAD_BYTES[..]);
  968. let mut expected_bytes = [
  969. 0x69, 0x95, 0x43, 0x21, 0x00, 0x0c, 0x11, 0xfe, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00,
  970. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x02, 0x00, 0x00,
  971. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
  972. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  973. ];
  974. let start = expected_bytes.len() - REPR_PAYLOAD_BYTES.len();
  975. expected_bytes[start..].copy_from_slice(&REPR_PAYLOAD_BYTES[..]);
  976. assert_eq!(packet.check_len(), Ok(()));
  977. assert_eq!(&packet.into_inner()[..], &expected_bytes[..]);
  978. }
  979. #[test]
  980. fn test_overlong() {
  981. let mut bytes = vec![];
  982. bytes.extend(&REPR_PACKET_BYTES[..]);
  983. bytes.push(0);
  984. assert_eq!(
  985. Packet::new_unchecked(&bytes).payload().len(),
  986. REPR_PAYLOAD_BYTES.len()
  987. );
  988. assert_eq!(
  989. Packet::new_unchecked(&mut bytes).payload_mut().len(),
  990. REPR_PAYLOAD_BYTES.len()
  991. );
  992. }
  993. #[test]
  994. fn test_total_len_overflow() {
  995. let mut bytes = vec![];
  996. bytes.extend(&REPR_PACKET_BYTES[..]);
  997. Packet::new_unchecked(&mut bytes).set_payload_len(0x80);
  998. assert_eq!(Packet::new_checked(&bytes).unwrap_err(), Error::Truncated);
  999. }
  1000. #[test]
  1001. fn test_repr_parse_valid() {
  1002. let packet = Packet::new_unchecked(&REPR_PACKET_BYTES[..]);
  1003. let repr = Repr::parse(&packet).unwrap();
  1004. assert_eq!(repr, packet_repr());
  1005. }
  1006. #[test]
  1007. fn test_repr_parse_bad_version() {
  1008. let mut bytes = vec![0; 40];
  1009. let mut packet = Packet::new_unchecked(&mut bytes[..]);
  1010. packet.set_version(4);
  1011. packet.set_payload_len(0);
  1012. let packet = Packet::new_unchecked(&*packet.into_inner());
  1013. assert_eq!(Repr::parse(&packet), Err(Error::Malformed));
  1014. }
  1015. #[test]
  1016. fn test_repr_parse_smaller_than_header() {
  1017. let mut bytes = vec![0; 40];
  1018. let mut packet = Packet::new_unchecked(&mut bytes[..]);
  1019. packet.set_version(6);
  1020. packet.set_payload_len(39);
  1021. let packet = Packet::new_unchecked(&*packet.into_inner());
  1022. assert_eq!(Repr::parse(&packet), Err(Error::Truncated));
  1023. }
  1024. #[test]
  1025. fn test_repr_parse_smaller_than_payload() {
  1026. let mut bytes = vec![0; 40];
  1027. let mut packet = Packet::new_unchecked(&mut bytes[..]);
  1028. packet.set_version(6);
  1029. packet.set_payload_len(1);
  1030. let packet = Packet::new_unchecked(&*packet.into_inner());
  1031. assert_eq!(Repr::parse(&packet), Err(Error::Truncated));
  1032. }
  1033. #[test]
  1034. fn test_basic_repr_emit() {
  1035. let repr = packet_repr();
  1036. let mut bytes = vec![0xff; repr.buffer_len() + REPR_PAYLOAD_BYTES.len()];
  1037. let mut packet = Packet::new_unchecked(&mut bytes);
  1038. repr.emit(&mut packet);
  1039. packet.payload_mut().copy_from_slice(&REPR_PAYLOAD_BYTES);
  1040. assert_eq!(&packet.into_inner()[..], &REPR_PACKET_BYTES[..]);
  1041. }
  1042. #[test]
  1043. fn test_pretty_print() {
  1044. assert_eq!(
  1045. format!(
  1046. "{}",
  1047. PrettyPrinter::<Packet<&'static [u8]>>::new("\n", &&REPR_PACKET_BYTES[..])
  1048. ),
  1049. "\nIPv6 src=fe80::1 dst=ff02::1 nxt_hdr=UDP hop_limit=64\n \\ UDP src=1 dst=2 len=4"
  1050. );
  1051. }
  1052. }