icmpv6.rs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. use core::{cmp, fmt};
  2. use byteorder::{ByteOrder, NetworkEndian};
  3. use crate::{Error, Result};
  4. use crate::phy::ChecksumCapabilities;
  5. use crate::wire::ip::checksum;
  6. use crate::wire::{IpAddress, IpProtocol, Ipv6Packet, Ipv6Repr};
  7. use crate::wire::MldRepr;
  8. #[cfg(feature = "ethernet")]
  9. use crate::wire::NdiscRepr;
  10. enum_with_unknown! {
  11. /// Internet protocol control message type.
  12. pub enum Message(u8) {
  13. /// Destination Unreachable.
  14. DstUnreachable = 0x01,
  15. /// Packet Too Big.
  16. PktTooBig = 0x02,
  17. /// Time Exceeded.
  18. TimeExceeded = 0x03,
  19. /// Parameter Problem.
  20. ParamProblem = 0x04,
  21. /// Echo Request
  22. EchoRequest = 0x80,
  23. /// Echo Reply
  24. EchoReply = 0x81,
  25. /// Multicast Listener Query
  26. MldQuery = 0x82,
  27. /// Router Solicitation
  28. RouterSolicit = 0x85,
  29. /// Router Advertisement
  30. RouterAdvert = 0x86,
  31. /// Neighbor Solicitation
  32. NeighborSolicit = 0x87,
  33. /// Neighbor Advertisement
  34. NeighborAdvert = 0x88,
  35. /// Redirect
  36. Redirect = 0x89,
  37. /// Multicast Listener Report
  38. MldReport = 0x8f
  39. }
  40. }
  41. impl Message {
  42. /// Per [RFC 4443 § 2.1] ICMPv6 message types with the highest order
  43. /// bit set are informational messages while message types without
  44. /// the highest order bit set are error messages.
  45. ///
  46. /// [RFC 4443 § 2.1]: https://tools.ietf.org/html/rfc4443#section-2.1
  47. pub fn is_error(&self) -> bool {
  48. (u8::from(*self) & 0x80) != 0x80
  49. }
  50. /// Return a boolean value indicating if the given message type
  51. /// is an [NDISC] message type.
  52. ///
  53. /// [NDISC]: https://tools.ietf.org/html/rfc4861
  54. pub fn is_ndisc(&self) -> bool {
  55. match *self {
  56. Message::RouterSolicit | Message::RouterAdvert | Message::NeighborSolicit |
  57. Message::NeighborAdvert | Message::Redirect => true,
  58. _ => false,
  59. }
  60. }
  61. /// Return a boolean value indicating if the given message type
  62. /// is an [MLD] message type.
  63. ///
  64. /// [MLD]: https://tools.ietf.org/html/rfc3810
  65. pub fn is_mld(&self) -> bool {
  66. match *self {
  67. Message::MldQuery | Message::MldReport => true,
  68. _ => false,
  69. }
  70. }
  71. }
  72. impl fmt::Display for Message {
  73. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  74. match *self {
  75. Message::DstUnreachable => write!(f, "destination unreachable"),
  76. Message::PktTooBig => write!(f, "packet too big"),
  77. Message::TimeExceeded => write!(f, "time exceeded"),
  78. Message::ParamProblem => write!(f, "parameter problem"),
  79. Message::EchoReply => write!(f, "echo reply"),
  80. Message::EchoRequest => write!(f, "echo request"),
  81. Message::RouterSolicit => write!(f, "router solicitation"),
  82. Message::RouterAdvert => write!(f, "router advertisement"),
  83. Message::NeighborSolicit => write!(f, "neighbor solicitation"),
  84. Message::NeighborAdvert => write!(f, "neighbor advert"),
  85. Message::Redirect => write!(f, "redirect"),
  86. Message::MldQuery => write!(f, "multicast listener query"),
  87. Message::MldReport => write!(f, "multicast listener report"),
  88. Message::Unknown(id) => write!(f, "{}", id)
  89. }
  90. }
  91. }
  92. enum_with_unknown! {
  93. /// Internet protocol control message subtype for type "Destination Unreachable".
  94. pub enum DstUnreachable(u8) {
  95. /// No Route to destination.
  96. NoRoute = 0,
  97. /// Communication with destination administratively prohibited.
  98. AdminProhibit = 1,
  99. /// Beyond scope of source address.
  100. BeyondScope = 2,
  101. /// Address unreachable.
  102. AddrUnreachable = 3,
  103. /// Port unreachable.
  104. PortUnreachable = 4,
  105. /// Source address failed ingress/egress policy.
  106. FailedPolicy = 5,
  107. /// Reject route to destination.
  108. RejectRoute = 6
  109. }
  110. }
  111. impl fmt::Display for DstUnreachable {
  112. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  113. match *self {
  114. DstUnreachable::NoRoute =>
  115. write!(f, "no route to destination"),
  116. DstUnreachable::AdminProhibit =>
  117. write!(f, "communication with destination administratively prohibited"),
  118. DstUnreachable::BeyondScope =>
  119. write!(f, "beyond scope of source address"),
  120. DstUnreachable::AddrUnreachable =>
  121. write!(f, "address unreachable"),
  122. DstUnreachable::PortUnreachable =>
  123. write!(f, "port unreachable"),
  124. DstUnreachable::FailedPolicy =>
  125. write!(f, "source address failed ingress/egress policy"),
  126. DstUnreachable::RejectRoute =>
  127. write!(f, "reject route to destination"),
  128. DstUnreachable::Unknown(id) =>
  129. write!(f, "{}", id)
  130. }
  131. }
  132. }
  133. enum_with_unknown! {
  134. /// Internet protocol control message subtype for the type "Parameter Problem".
  135. pub enum ParamProblem(u8) {
  136. /// Erroneous header field encountered.
  137. ErroneousHdrField = 0,
  138. /// Unrecognized Next Header type encountered.
  139. UnrecognizedNxtHdr = 1,
  140. /// Unrecognized IPv6 option encountered.
  141. UnrecognizedOption = 2
  142. }
  143. }
  144. impl fmt::Display for ParamProblem {
  145. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  146. match *self {
  147. ParamProblem::ErroneousHdrField =>
  148. write!(f, "erroneous header field."),
  149. ParamProblem::UnrecognizedNxtHdr =>
  150. write!(f, "unrecognized next header type."),
  151. ParamProblem::UnrecognizedOption =>
  152. write!(f, "unrecognized IPv6 option."),
  153. ParamProblem::Unknown(id) =>
  154. write!(f, "{}", id)
  155. }
  156. }
  157. }
  158. enum_with_unknown! {
  159. /// Internet protocol control message subtype for the type "Time Exceeded".
  160. pub enum TimeExceeded(u8) {
  161. /// Hop limit exceeded in transit.
  162. HopLimitExceeded = 0,
  163. /// Fragment reassembly time exceeded.
  164. FragReassemExceeded = 1
  165. }
  166. }
  167. impl fmt::Display for TimeExceeded {
  168. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  169. match *self {
  170. TimeExceeded::HopLimitExceeded =>
  171. write!(f, "hop limit exceeded in transit"),
  172. TimeExceeded::FragReassemExceeded =>
  173. write!(f, "fragment reassembly time exceeded"),
  174. TimeExceeded::Unknown(id) =>
  175. write!(f, "{}", id)
  176. }
  177. }
  178. }
  179. /// A read/write wrapper around an Internet Control Message Protocol version 6 packet buffer.
  180. #[derive(Debug, PartialEq, Clone)]
  181. pub struct Packet<T: AsRef<[u8]>> {
  182. pub(super) buffer: T
  183. }
  184. // Ranges and constants describing key boundaries in the ICMPv6 header.
  185. pub(super) mod field {
  186. use crate::wire::field::*;
  187. // ICMPv6: See https://tools.ietf.org/html/rfc4443
  188. pub const TYPE: usize = 0;
  189. pub const CODE: usize = 1;
  190. pub const CHECKSUM: Field = 2..4;
  191. pub const UNUSED: Field = 4..8;
  192. pub const MTU: Field = 4..8;
  193. pub const POINTER: Field = 4..8;
  194. pub const ECHO_IDENT: Field = 4..6;
  195. pub const ECHO_SEQNO: Field = 6..8;
  196. pub const HEADER_END: usize = 8;
  197. // NDISC: See https://tools.ietf.org/html/rfc4861
  198. // Router Advertisement message offsets
  199. pub const CUR_HOP_LIMIT: usize = 4;
  200. pub const ROUTER_FLAGS: usize = 5;
  201. pub const ROUTER_LT: Field = 6..8;
  202. pub const REACHABLE_TM: Field = 8..12;
  203. pub const RETRANS_TM: Field = 12..16;
  204. // Neighbor Solicitation message offsets
  205. pub const TARGET_ADDR: Field = 8..24;
  206. // Neighbor Advertisement message offsets
  207. pub const NEIGH_FLAGS: usize = 4;
  208. // Redirected Header message offsets
  209. pub const DEST_ADDR: Field = 24..40;
  210. // MLD:
  211. // - https://tools.ietf.org/html/rfc3810
  212. // - https://tools.ietf.org/html/rfc3810
  213. // Multicast Listener Query message
  214. pub const MAX_RESP_CODE: Field = 4..6;
  215. pub const QUERY_RESV: Field = 6..8;
  216. pub const QUERY_MCAST_ADDR: Field = 8..24;
  217. pub const SQRV: usize = 24;
  218. pub const QQIC: usize = 25;
  219. pub const QUERY_NUM_SRCS: Field = 26..28;
  220. // Multicast Listener Report Message
  221. pub const RECORD_RESV: Field = 4..6;
  222. pub const NR_MCAST_RCRDS: Field = 6..8;
  223. // Multicast Address Record Offsets
  224. pub const RECORD_TYPE: usize = 0;
  225. pub const AUX_DATA_LEN: usize = 1;
  226. pub const RECORD_NUM_SRCS: Field = 2..4;
  227. pub const RECORD_MCAST_ADDR: Field = 4..20;
  228. }
  229. impl<T: AsRef<[u8]>> Packet<T> {
  230. /// Imbue a raw octet buffer with ICMPv6 packet structure.
  231. pub fn new_unchecked(buffer: T) -> Packet<T> {
  232. Packet { buffer }
  233. }
  234. /// Shorthand for a combination of [new_unchecked] and [check_len].
  235. ///
  236. /// [new_unchecked]: #method.new_unchecked
  237. /// [check_len]: #method.check_len
  238. pub fn new_checked(buffer: T) -> Result<Packet<T>> {
  239. let packet = Self::new_unchecked(buffer);
  240. packet.check_len()?;
  241. Ok(packet)
  242. }
  243. /// Ensure that no accessor method will panic if called.
  244. /// Returns `Err(Error::Truncated)` if the buffer is too short.
  245. pub fn check_len(&self) -> Result<()> {
  246. let len = self.buffer.as_ref().len();
  247. if len < field::HEADER_END || len < self.header_len() {
  248. Err(Error::Truncated)
  249. } else {
  250. Ok(())
  251. }
  252. }
  253. /// Consume the packet, returning the underlying buffer.
  254. pub fn into_inner(self) -> T {
  255. self.buffer
  256. }
  257. /// Return the message type field.
  258. #[inline]
  259. pub fn msg_type(&self) -> Message {
  260. let data = self.buffer.as_ref();
  261. Message::from(data[field::TYPE])
  262. }
  263. /// Return the message code field.
  264. #[inline]
  265. pub fn msg_code(&self) -> u8 {
  266. let data = self.buffer.as_ref();
  267. data[field::CODE]
  268. }
  269. /// Return the checksum field.
  270. #[inline]
  271. pub fn checksum(&self) -> u16 {
  272. let data = self.buffer.as_ref();
  273. NetworkEndian::read_u16(&data[field::CHECKSUM])
  274. }
  275. /// Return the identifier field (for echo request and reply packets).
  276. #[inline]
  277. pub fn echo_ident(&self) -> u16 {
  278. let data = self.buffer.as_ref();
  279. NetworkEndian::read_u16(&data[field::ECHO_IDENT])
  280. }
  281. /// Return the sequence number field (for echo request and reply packets).
  282. #[inline]
  283. pub fn echo_seq_no(&self) -> u16 {
  284. let data = self.buffer.as_ref();
  285. NetworkEndian::read_u16(&data[field::ECHO_SEQNO])
  286. }
  287. /// Return the MTU field (for packet too big messages).
  288. #[inline]
  289. pub fn pkt_too_big_mtu(&self) -> u32 {
  290. let data = self.buffer.as_ref();
  291. NetworkEndian::read_u32(&data[field::MTU])
  292. }
  293. /// Return the pointer field (for parameter problem messages).
  294. #[inline]
  295. pub fn param_problem_ptr(&self) -> u32 {
  296. let data = self.buffer.as_ref();
  297. NetworkEndian::read_u32(&data[field::POINTER])
  298. }
  299. /// Return the header length. The result depends on the value of
  300. /// the message type field.
  301. pub fn header_len(&self) -> usize {
  302. match self.msg_type() {
  303. Message::DstUnreachable => field::UNUSED.end,
  304. Message::PktTooBig => field::MTU.end,
  305. Message::TimeExceeded => field::UNUSED.end,
  306. Message::ParamProblem => field::POINTER.end,
  307. Message::EchoRequest => field::ECHO_SEQNO.end,
  308. Message::EchoReply => field::ECHO_SEQNO.end,
  309. Message::RouterSolicit => field::UNUSED.end,
  310. Message::RouterAdvert => field::RETRANS_TM.end,
  311. Message::NeighborSolicit => field::TARGET_ADDR.end,
  312. Message::NeighborAdvert => field::TARGET_ADDR.end,
  313. Message::Redirect => field::DEST_ADDR.end,
  314. Message::MldQuery => field::QUERY_NUM_SRCS.end,
  315. Message::MldReport => field::NR_MCAST_RCRDS.end,
  316. // For packets that are not included in RFC 4443, do not
  317. // include the last 32 bits of the ICMPv6 header in
  318. // `header_bytes`. This must be done so that these bytes
  319. // can be accessed in the `payload`.
  320. _ => field::CHECKSUM.end
  321. }
  322. }
  323. /// Validate the header checksum.
  324. ///
  325. /// # Fuzzing
  326. /// This function always returns `true` when fuzzing.
  327. pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
  328. if cfg!(fuzzing) { return true }
  329. let data = self.buffer.as_ref();
  330. checksum::combine(&[
  331. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Icmpv6,
  332. data.len() as u32),
  333. checksum::data(data)
  334. ]) == !0
  335. }
  336. }
  337. impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
  338. /// Return a pointer to the type-specific data.
  339. #[inline]
  340. pub fn payload(&self) -> &'a [u8] {
  341. let data = self.buffer.as_ref();
  342. &data[self.header_len()..]
  343. }
  344. }
  345. impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
  346. /// Set the message type field.
  347. #[inline]
  348. pub fn set_msg_type(&mut self, value: Message) {
  349. let data = self.buffer.as_mut();
  350. data[field::TYPE] = value.into()
  351. }
  352. /// Set the message code field.
  353. #[inline]
  354. pub fn set_msg_code(&mut self, value: u8) {
  355. let data = self.buffer.as_mut();
  356. data[field::CODE] = value
  357. }
  358. /// Clear any reserved fields in the message header.
  359. ///
  360. /// # Panics
  361. /// This function panics if the message type has not been set.
  362. /// See [set_msg_type].
  363. ///
  364. /// [set_msg_type]: #method.set_msg_type
  365. #[inline]
  366. pub fn clear_reserved(&mut self) {
  367. match self.msg_type() {
  368. Message::RouterSolicit | Message::NeighborSolicit |
  369. Message::NeighborAdvert | Message::Redirect => {
  370. let data = self.buffer.as_mut();
  371. NetworkEndian::write_u32(&mut data[field::UNUSED], 0);
  372. },
  373. Message::MldQuery => {
  374. let data = self.buffer.as_mut();
  375. NetworkEndian::write_u16(&mut data[field::QUERY_RESV], 0);
  376. data[field::SQRV] &= 0xf;
  377. },
  378. Message::MldReport => {
  379. let data = self.buffer.as_mut();
  380. NetworkEndian::write_u16(&mut data[field::RECORD_RESV], 0);
  381. }
  382. ty => panic!("Message type `{}` does not have any reserved fields.", ty),
  383. }
  384. }
  385. #[inline]
  386. pub fn set_checksum(&mut self, value: u16) {
  387. let data = self.buffer.as_mut();
  388. NetworkEndian::write_u16(&mut data[field::CHECKSUM], value)
  389. }
  390. /// Set the identifier field (for echo request and reply packets).
  391. ///
  392. /// # Panics
  393. /// This function may panic if this packet is not an echo request or reply packet.
  394. #[inline]
  395. pub fn set_echo_ident(&mut self, value: u16) {
  396. let data = self.buffer.as_mut();
  397. NetworkEndian::write_u16(&mut data[field::ECHO_IDENT], value)
  398. }
  399. /// Set the sequence number field (for echo request and reply packets).
  400. ///
  401. /// # Panics
  402. /// This function may panic if this packet is not an echo request or reply packet.
  403. #[inline]
  404. pub fn set_echo_seq_no(&mut self, value: u16) {
  405. let data = self.buffer.as_mut();
  406. NetworkEndian::write_u16(&mut data[field::ECHO_SEQNO], value)
  407. }
  408. /// Set the MTU field (for packet too big messages).
  409. ///
  410. /// # Panics
  411. /// This function may panic if this packet is not an packet too big packet.
  412. #[inline]
  413. pub fn set_pkt_too_big_mtu(&mut self, value: u32) {
  414. let data = self.buffer.as_mut();
  415. NetworkEndian::write_u32(&mut data[field::MTU], value)
  416. }
  417. /// Set the pointer field (for parameter problem messages).
  418. ///
  419. /// # Panics
  420. /// This function may panic if this packet is not a parameter problem message.
  421. #[inline]
  422. pub fn set_param_problem_ptr(&mut self, value: u32) {
  423. let data = self.buffer.as_mut();
  424. NetworkEndian::write_u32(&mut data[field::POINTER], value)
  425. }
  426. /// Compute and fill in the header checksum.
  427. pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
  428. self.set_checksum(0);
  429. let checksum = {
  430. let data = self.buffer.as_ref();
  431. !checksum::combine(&[
  432. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Icmpv6,
  433. data.len() as u32),
  434. checksum::data(data)
  435. ])
  436. };
  437. self.set_checksum(checksum)
  438. }
  439. /// Return a mutable pointer to the type-specific data.
  440. #[inline]
  441. pub fn payload_mut(&mut self) -> &mut [u8] {
  442. let range = self.header_len()..;
  443. let data = self.buffer.as_mut();
  444. &mut data[range]
  445. }
  446. }
  447. impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
  448. fn as_ref(&self) -> &[u8] {
  449. self.buffer.as_ref()
  450. }
  451. }
  452. /// A high-level representation of an Internet Control Message Protocol version 6 packet header.
  453. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  454. #[non_exhaustive]
  455. pub enum Repr<'a> {
  456. DstUnreachable {
  457. reason: DstUnreachable,
  458. header: Ipv6Repr,
  459. data: &'a [u8]
  460. },
  461. PktTooBig {
  462. mtu: u32,
  463. header: Ipv6Repr,
  464. data: &'a [u8]
  465. },
  466. TimeExceeded {
  467. reason: TimeExceeded,
  468. header: Ipv6Repr,
  469. data: &'a [u8]
  470. },
  471. ParamProblem {
  472. reason: ParamProblem,
  473. pointer: u32,
  474. header: Ipv6Repr,
  475. data: &'a [u8]
  476. },
  477. EchoRequest {
  478. ident: u16,
  479. seq_no: u16,
  480. data: &'a [u8]
  481. },
  482. EchoReply {
  483. ident: u16,
  484. seq_no: u16,
  485. data: &'a [u8]
  486. },
  487. #[cfg(feature = "ethernet")]
  488. Ndisc(NdiscRepr<'a>),
  489. Mld(MldRepr<'a>),
  490. }
  491. impl<'a> Repr<'a> {
  492. /// Parse an Internet Control Message Protocol version 6 packet and return
  493. /// a high-level representation.
  494. pub fn parse<T>(src_addr: &IpAddress, dst_addr: &IpAddress,
  495. packet: &Packet<&'a T>, checksum_caps: &ChecksumCapabilities)
  496. -> Result<Repr<'a>>
  497. where T: AsRef<[u8]> + ?Sized {
  498. fn create_packet_from_payload<'a, T>(packet: &Packet<&'a T>)
  499. -> Result<(&'a [u8], Ipv6Repr)>
  500. where T: AsRef<[u8]> + ?Sized {
  501. let ip_packet = Ipv6Packet::new_checked(packet.payload())?;
  502. let payload = &packet.payload()[ip_packet.header_len() as usize..];
  503. if payload.len() < 8 { return Err(Error::Truncated) }
  504. let repr = Ipv6Repr {
  505. src_addr: ip_packet.src_addr(),
  506. dst_addr: ip_packet.dst_addr(),
  507. next_header: ip_packet.next_header(),
  508. payload_len: payload.len(),
  509. hop_limit: ip_packet.hop_limit()
  510. };
  511. Ok((payload, repr))
  512. }
  513. // Valid checksum is expected.
  514. if checksum_caps.icmpv6.rx() && !packet.verify_checksum(src_addr, dst_addr) {
  515. return Err(Error::Checksum)
  516. }
  517. match (packet.msg_type(), packet.msg_code()) {
  518. (Message::DstUnreachable, code) => {
  519. let (payload, repr) = create_packet_from_payload(packet)?;
  520. Ok(Repr::DstUnreachable {
  521. reason: DstUnreachable::from(code),
  522. header: repr,
  523. data: payload
  524. })
  525. },
  526. (Message::PktTooBig, 0) => {
  527. let (payload, repr) = create_packet_from_payload(packet)?;
  528. Ok(Repr::PktTooBig {
  529. mtu: packet.pkt_too_big_mtu(),
  530. header: repr,
  531. data: payload
  532. })
  533. },
  534. (Message::TimeExceeded, code) => {
  535. let (payload, repr) = create_packet_from_payload(packet)?;
  536. Ok(Repr::TimeExceeded {
  537. reason: TimeExceeded::from(code),
  538. header: repr,
  539. data: payload
  540. })
  541. },
  542. (Message::ParamProblem, code) => {
  543. let (payload, repr) = create_packet_from_payload(packet)?;
  544. Ok(Repr::ParamProblem {
  545. reason: ParamProblem::from(code),
  546. pointer: packet.param_problem_ptr(),
  547. header: repr,
  548. data: payload
  549. })
  550. },
  551. (Message::EchoRequest, 0) => {
  552. Ok(Repr::EchoRequest {
  553. ident: packet.echo_ident(),
  554. seq_no: packet.echo_seq_no(),
  555. data: packet.payload()
  556. })
  557. },
  558. (Message::EchoReply, 0) => {
  559. Ok(Repr::EchoReply {
  560. ident: packet.echo_ident(),
  561. seq_no: packet.echo_seq_no(),
  562. data: packet.payload()
  563. })
  564. },
  565. #[cfg(feature = "ethernet")]
  566. (msg_type, 0) if msg_type.is_ndisc() => {
  567. NdiscRepr::parse(packet).map(Repr::Ndisc)
  568. },
  569. (msg_type, 0) if msg_type.is_mld() => {
  570. MldRepr::parse(packet).map(Repr::Mld)
  571. },
  572. _ => Err(Error::Unrecognized)
  573. }
  574. }
  575. /// Return the length of a packet that will be emitted from this high-level representation.
  576. pub fn buffer_len(&self) -> usize {
  577. match self {
  578. &Repr::DstUnreachable { header, data, .. } | &Repr::PktTooBig { header, data, .. } |
  579. &Repr::TimeExceeded { header, data, .. } | &Repr::ParamProblem { header, data, .. } => {
  580. field::UNUSED.end + header.buffer_len() + data.len()
  581. }
  582. &Repr::EchoRequest { data, .. } |
  583. &Repr::EchoReply { data, .. } => {
  584. field::ECHO_SEQNO.end + data.len()
  585. },
  586. #[cfg(feature = "ethernet")]
  587. &Repr::Ndisc(ndisc) => {
  588. ndisc.buffer_len()
  589. },
  590. &Repr::Mld(mld) => {
  591. mld.buffer_len()
  592. },
  593. }
  594. }
  595. /// Emit a high-level representation into an Internet Control Message Protocol version 6
  596. /// packet.
  597. pub fn emit<T>(&self, src_addr: &IpAddress, dst_addr: &IpAddress,
  598. packet: &mut Packet<&mut T>, checksum_caps: &ChecksumCapabilities)
  599. where T: AsRef<[u8]> + AsMut<[u8]> + ?Sized {
  600. fn emit_contained_packet(buffer: &mut [u8], header: Ipv6Repr, data: &[u8]) {
  601. let mut ip_packet = Ipv6Packet::new_unchecked(buffer);
  602. header.emit(&mut ip_packet);
  603. let payload = &mut ip_packet.into_inner()[header.buffer_len()..];
  604. payload.copy_from_slice(&data[..]);
  605. }
  606. match *self {
  607. Repr::DstUnreachable { reason, header, data } => {
  608. packet.set_msg_type(Message::DstUnreachable);
  609. packet.set_msg_code(reason.into());
  610. emit_contained_packet(packet.payload_mut(), header, &data);
  611. },
  612. Repr::PktTooBig { mtu, header, data } => {
  613. packet.set_msg_type(Message::PktTooBig);
  614. packet.set_msg_code(0);
  615. packet.set_pkt_too_big_mtu(mtu);
  616. emit_contained_packet(packet.payload_mut(), header, &data);
  617. },
  618. Repr::TimeExceeded { reason, header, data } => {
  619. packet.set_msg_type(Message::TimeExceeded);
  620. packet.set_msg_code(reason.into());
  621. emit_contained_packet(packet.payload_mut(), header, &data);
  622. },
  623. Repr::ParamProblem { reason, pointer, header, data } => {
  624. packet.set_msg_type(Message::ParamProblem);
  625. packet.set_msg_code(reason.into());
  626. packet.set_param_problem_ptr(pointer);
  627. emit_contained_packet(packet.payload_mut(), header, &data);
  628. },
  629. Repr::EchoRequest { ident, seq_no, data } => {
  630. packet.set_msg_type(Message::EchoRequest);
  631. packet.set_msg_code(0);
  632. packet.set_echo_ident(ident);
  633. packet.set_echo_seq_no(seq_no);
  634. let data_len = cmp::min(packet.payload_mut().len(), data.len());
  635. packet.payload_mut()[..data_len].copy_from_slice(&data[..data_len])
  636. },
  637. Repr::EchoReply { ident, seq_no, data } => {
  638. packet.set_msg_type(Message::EchoReply);
  639. packet.set_msg_code(0);
  640. packet.set_echo_ident(ident);
  641. packet.set_echo_seq_no(seq_no);
  642. let data_len = cmp::min(packet.payload_mut().len(), data.len());
  643. packet.payload_mut()[..data_len].copy_from_slice(&data[..data_len])
  644. },
  645. #[cfg(feature = "ethernet")]
  646. Repr::Ndisc(ndisc) => {
  647. ndisc.emit(packet)
  648. },
  649. Repr::Mld(mld) => {
  650. mld.emit(packet)
  651. },
  652. }
  653. if checksum_caps.icmpv6.tx() {
  654. packet.fill_checksum(src_addr, dst_addr);
  655. } else {
  656. // make sure we get a consistently zeroed checksum, since implementations might rely on it
  657. packet.set_checksum(0);
  658. }
  659. }
  660. }
  661. #[cfg(test)]
  662. mod test {
  663. use crate::wire::{Ipv6Address, Ipv6Repr, IpProtocol};
  664. use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2};
  665. use super::*;
  666. static ECHO_PACKET_BYTES: [u8; 12] =
  667. [0x80, 0x00, 0x19, 0xb3,
  668. 0x12, 0x34, 0xab, 0xcd,
  669. 0xaa, 0x00, 0x00, 0xff];
  670. static ECHO_PACKET_PAYLOAD: [u8; 4] =
  671. [0xaa, 0x00, 0x00, 0xff];
  672. static PKT_TOO_BIG_BYTES: [u8; 60] =
  673. [0x02, 0x00, 0x0f, 0xc9,
  674. 0x00, 0x00, 0x05, 0xdc,
  675. 0x60, 0x00, 0x00, 0x00,
  676. 0x00, 0x0c, 0x11, 0x40,
  677. 0xfe, 0x80, 0x00, 0x00,
  678. 0x00, 0x00, 0x00, 0x00,
  679. 0x00, 0x00, 0x00, 0x00,
  680. 0x00, 0x00, 0x00, 0x01,
  681. 0xfe, 0x80, 0x00, 0x00,
  682. 0x00, 0x00, 0x00, 0x00,
  683. 0x00, 0x00, 0x00, 0x00,
  684. 0x00, 0x00, 0x00, 0x02,
  685. 0xbf, 0x00, 0x00, 0x35,
  686. 0x00, 0x0c, 0x12, 0x4d,
  687. 0xaa, 0x00, 0x00, 0xff];
  688. static PKT_TOO_BIG_IP_PAYLOAD: [u8; 52] =
  689. [0x60, 0x00, 0x00, 0x00,
  690. 0x00, 0x0c, 0x11, 0x40,
  691. 0xfe, 0x80, 0x00, 0x00,
  692. 0x00, 0x00, 0x00, 0x00,
  693. 0x00, 0x00, 0x00, 0x00,
  694. 0x00, 0x00, 0x00, 0x01,
  695. 0xfe, 0x80, 0x00, 0x00,
  696. 0x00, 0x00, 0x00, 0x00,
  697. 0x00, 0x00, 0x00, 0x00,
  698. 0x00, 0x00, 0x00, 0x02,
  699. 0xbf, 0x00, 0x00, 0x35,
  700. 0x00, 0x0c, 0x12, 0x4d,
  701. 0xaa, 0x00, 0x00, 0xff];
  702. static PKT_TOO_BIG_UDP_PAYLOAD: [u8; 12] =
  703. [0xbf, 0x00, 0x00, 0x35,
  704. 0x00, 0x0c, 0x12, 0x4d,
  705. 0xaa, 0x00, 0x00, 0xff];
  706. fn echo_packet_repr() -> Repr<'static> {
  707. Repr::EchoRequest {
  708. ident: 0x1234,
  709. seq_no: 0xabcd,
  710. data: &ECHO_PACKET_PAYLOAD
  711. }
  712. }
  713. fn too_big_packet_repr() -> Repr<'static> {
  714. Repr::PktTooBig {
  715. mtu: 1500,
  716. header: Ipv6Repr {
  717. src_addr: Ipv6Address([0xfe, 0x80, 0x00, 0x00,
  718. 0x00, 0x00, 0x00, 0x00,
  719. 0x00, 0x00, 0x00, 0x00,
  720. 0x00, 0x00, 0x00, 0x01]),
  721. dst_addr: Ipv6Address([0xfe, 0x80, 0x00, 0x00,
  722. 0x00, 0x00, 0x00, 0x00,
  723. 0x00, 0x00, 0x00, 0x00,
  724. 0x00, 0x00, 0x00, 0x02]),
  725. next_header: IpProtocol::Udp,
  726. payload_len: 12,
  727. hop_limit: 0x40
  728. },
  729. data: &PKT_TOO_BIG_UDP_PAYLOAD,
  730. }
  731. }
  732. #[test]
  733. fn test_echo_deconstruct() {
  734. let packet = Packet::new_unchecked(&ECHO_PACKET_BYTES[..]);
  735. assert_eq!(packet.msg_type(), Message::EchoRequest);
  736. assert_eq!(packet.msg_code(), 0);
  737. assert_eq!(packet.checksum(), 0x19b3);
  738. assert_eq!(packet.echo_ident(), 0x1234);
  739. assert_eq!(packet.echo_seq_no(), 0xabcd);
  740. assert_eq!(packet.payload(), &ECHO_PACKET_PAYLOAD[..]);
  741. assert_eq!(packet.verify_checksum(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2), true);
  742. assert!(!packet.msg_type().is_error());
  743. }
  744. #[test]
  745. fn test_echo_construct() {
  746. let mut bytes = vec![0xa5; 12];
  747. let mut packet = Packet::new_unchecked(&mut bytes);
  748. packet.set_msg_type(Message::EchoRequest);
  749. packet.set_msg_code(0);
  750. packet.set_echo_ident(0x1234);
  751. packet.set_echo_seq_no(0xabcd);
  752. packet.payload_mut().copy_from_slice(&ECHO_PACKET_PAYLOAD[..]);
  753. packet.fill_checksum(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2);
  754. assert_eq!(&packet.into_inner()[..], &ECHO_PACKET_BYTES[..]);
  755. }
  756. #[test]
  757. fn test_echo_repr_parse() {
  758. let packet = Packet::new_unchecked(&ECHO_PACKET_BYTES[..]);
  759. let repr = Repr::parse(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2,
  760. &packet, &ChecksumCapabilities::default()).unwrap();
  761. assert_eq!(repr, echo_packet_repr());
  762. }
  763. #[test]
  764. fn test_echo_emit() {
  765. let repr = echo_packet_repr();
  766. let mut bytes = vec![0xa5; repr.buffer_len()];
  767. let mut packet = Packet::new_unchecked(&mut bytes);
  768. repr.emit(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2,
  769. &mut packet, &ChecksumCapabilities::default());
  770. assert_eq!(&packet.into_inner()[..], &ECHO_PACKET_BYTES[..]);
  771. }
  772. #[test]
  773. fn test_too_big_deconstruct() {
  774. let packet = Packet::new_unchecked(&PKT_TOO_BIG_BYTES[..]);
  775. assert_eq!(packet.msg_type(), Message::PktTooBig);
  776. assert_eq!(packet.msg_code(), 0);
  777. assert_eq!(packet.checksum(), 0x0fc9);
  778. assert_eq!(packet.pkt_too_big_mtu(), 1500);
  779. assert_eq!(packet.payload(), &PKT_TOO_BIG_IP_PAYLOAD[..]);
  780. assert_eq!(packet.verify_checksum(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2), true);
  781. assert!(packet.msg_type().is_error());
  782. }
  783. #[test]
  784. fn test_too_big_construct() {
  785. let mut bytes = vec![0xa5; 60];
  786. let mut packet = Packet::new_unchecked(&mut bytes);
  787. packet.set_msg_type(Message::PktTooBig);
  788. packet.set_msg_code(0);
  789. packet.set_pkt_too_big_mtu(1500);
  790. packet.payload_mut().copy_from_slice(&PKT_TOO_BIG_IP_PAYLOAD[..]);
  791. packet.fill_checksum(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2);
  792. assert_eq!(&packet.into_inner()[..], &PKT_TOO_BIG_BYTES[..]);
  793. }
  794. #[test]
  795. fn test_too_big_repr_parse() {
  796. let packet = Packet::new_unchecked(&PKT_TOO_BIG_BYTES[..]);
  797. let repr = Repr::parse(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2,
  798. &packet, &ChecksumCapabilities::default()).unwrap();
  799. assert_eq!(repr, too_big_packet_repr());
  800. }
  801. #[test]
  802. fn test_too_big_emit() {
  803. let repr = too_big_packet_repr();
  804. let mut bytes = vec![0xa5; repr.buffer_len()];
  805. let mut packet = Packet::new_unchecked(&mut bytes);
  806. repr.emit(&MOCK_IP_ADDR_1, &MOCK_IP_ADDR_2,
  807. &mut packet, &ChecksumCapabilities::default());
  808. assert_eq!(&packet.into_inner()[..], &PKT_TOO_BIG_BYTES[..]);
  809. }
  810. }