icmpv6.rs 31 KB

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