tcp.rs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  1. use core::{i32, ops, cmp, fmt};
  2. use byteorder::{ByteOrder, NetworkEndian};
  3. use crate::{Error, Result};
  4. use crate::phy::ChecksumCapabilities;
  5. use crate::wire::{IpProtocol, IpAddress};
  6. use crate::wire::ip::checksum;
  7. /// A TCP sequence number.
  8. ///
  9. /// A sequence number is a monotonically advancing integer modulo 2<sup>32</sup>.
  10. /// Sequence numbers do not have a discontiguity when compared pairwise across a signed overflow.
  11. #[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
  12. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  13. pub struct SeqNumber(pub i32);
  14. impl fmt::Display for SeqNumber {
  15. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  16. write!(f, "{}", self.0 as u32)
  17. }
  18. }
  19. impl ops::Add<usize> for SeqNumber {
  20. type Output = SeqNumber;
  21. fn add(self, rhs: usize) -> SeqNumber {
  22. if rhs > i32::MAX as usize {
  23. panic!("attempt to add to sequence number with unsigned overflow")
  24. }
  25. SeqNumber(self.0.wrapping_add(rhs as i32))
  26. }
  27. }
  28. impl ops::Sub<usize> for SeqNumber {
  29. type Output = SeqNumber;
  30. fn sub(self, rhs: usize) -> SeqNumber {
  31. if rhs > i32::MAX as usize {
  32. panic!("attempt to subtract to sequence number with unsigned overflow")
  33. }
  34. SeqNumber(self.0.wrapping_sub(rhs as i32))
  35. }
  36. }
  37. impl ops::AddAssign<usize> for SeqNumber {
  38. fn add_assign(&mut self, rhs: usize) {
  39. *self = *self + rhs;
  40. }
  41. }
  42. impl ops::Sub for SeqNumber {
  43. type Output = usize;
  44. fn sub(self, rhs: SeqNumber) -> usize {
  45. let result = self.0.wrapping_sub(rhs.0);
  46. if result < 0 {
  47. panic!("attempt to subtract sequence numbers with underflow")
  48. }
  49. result as usize
  50. }
  51. }
  52. impl cmp::PartialOrd for SeqNumber {
  53. fn partial_cmp(&self, other: &SeqNumber) -> Option<cmp::Ordering> {
  54. self.0.wrapping_sub(other.0).partial_cmp(&0)
  55. }
  56. }
  57. /// A read/write wrapper around a Transmission Control Protocol packet buffer.
  58. #[derive(Debug, PartialEq, Clone)]
  59. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  60. pub struct Packet<T: AsRef<[u8]>> {
  61. buffer: T
  62. }
  63. mod field {
  64. #![allow(non_snake_case)]
  65. use crate::wire::field::*;
  66. pub const SRC_PORT: Field = 0..2;
  67. pub const DST_PORT: Field = 2..4;
  68. pub const SEQ_NUM: Field = 4..8;
  69. pub const ACK_NUM: Field = 8..12;
  70. pub const FLAGS: Field = 12..14;
  71. pub const WIN_SIZE: Field = 14..16;
  72. pub const CHECKSUM: Field = 16..18;
  73. pub const URGENT: Field = 18..20;
  74. pub fn OPTIONS(length: u8) -> Field {
  75. URGENT.end..(length as usize)
  76. }
  77. pub const FLG_FIN: u16 = 0x001;
  78. pub const FLG_SYN: u16 = 0x002;
  79. pub const FLG_RST: u16 = 0x004;
  80. pub const FLG_PSH: u16 = 0x008;
  81. pub const FLG_ACK: u16 = 0x010;
  82. pub const FLG_URG: u16 = 0x020;
  83. pub const FLG_ECE: u16 = 0x040;
  84. pub const FLG_CWR: u16 = 0x080;
  85. pub const FLG_NS: u16 = 0x100;
  86. pub const OPT_END: u8 = 0x00;
  87. pub const OPT_NOP: u8 = 0x01;
  88. pub const OPT_MSS: u8 = 0x02;
  89. pub const OPT_WS: u8 = 0x03;
  90. pub const OPT_SACKPERM: u8 = 0x04;
  91. pub const OPT_SACKRNG: u8 = 0x05;
  92. }
  93. pub const HEADER_LEN: usize = field::URGENT.end;
  94. impl<T: AsRef<[u8]>> Packet<T> {
  95. /// Imbue a raw octet buffer with TCP packet structure.
  96. pub fn new_unchecked(buffer: T) -> Packet<T> {
  97. Packet { buffer }
  98. }
  99. /// Shorthand for a combination of [new_unchecked] and [check_len].
  100. ///
  101. /// [new_unchecked]: #method.new_unchecked
  102. /// [check_len]: #method.check_len
  103. pub fn new_checked(buffer: T) -> Result<Packet<T>> {
  104. let packet = Self::new_unchecked(buffer);
  105. packet.check_len()?;
  106. Ok(packet)
  107. }
  108. /// Ensure that no accessor method will panic if called.
  109. /// Returns `Err(Error::Truncated)` if the buffer is too short.
  110. /// Returns `Err(Error::Malformed)` if the header length field has a value smaller
  111. /// than the minimal header length.
  112. ///
  113. /// The result of this check is invalidated by calling [set_header_len].
  114. ///
  115. /// [set_header_len]: #method.set_header_len
  116. pub fn check_len(&self) -> Result<()> {
  117. let len = self.buffer.as_ref().len();
  118. if len < field::URGENT.end {
  119. Err(Error::Truncated)
  120. } else {
  121. let header_len = self.header_len() as usize;
  122. if len < header_len {
  123. Err(Error::Truncated)
  124. } else if header_len < field::URGENT.end {
  125. Err(Error::Malformed)
  126. } else {
  127. Ok(())
  128. }
  129. }
  130. }
  131. /// Consume the packet, returning the underlying buffer.
  132. pub fn into_inner(self) -> T {
  133. self.buffer
  134. }
  135. /// Return the source port field.
  136. #[inline]
  137. pub fn src_port(&self) -> u16 {
  138. let data = self.buffer.as_ref();
  139. NetworkEndian::read_u16(&data[field::SRC_PORT])
  140. }
  141. /// Return the destination port field.
  142. #[inline]
  143. pub fn dst_port(&self) -> u16 {
  144. let data = self.buffer.as_ref();
  145. NetworkEndian::read_u16(&data[field::DST_PORT])
  146. }
  147. /// Return the sequence number field.
  148. #[inline]
  149. pub fn seq_number(&self) -> SeqNumber {
  150. let data = self.buffer.as_ref();
  151. SeqNumber(NetworkEndian::read_i32(&data[field::SEQ_NUM]))
  152. }
  153. /// Return the acknowledgement number field.
  154. #[inline]
  155. pub fn ack_number(&self) -> SeqNumber {
  156. let data = self.buffer.as_ref();
  157. SeqNumber(NetworkEndian::read_i32(&data[field::ACK_NUM]))
  158. }
  159. /// Return the FIN flag.
  160. #[inline]
  161. pub fn fin(&self) -> bool {
  162. let data = self.buffer.as_ref();
  163. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  164. raw & field::FLG_FIN != 0
  165. }
  166. /// Return the SYN flag.
  167. #[inline]
  168. pub fn syn(&self) -> bool {
  169. let data = self.buffer.as_ref();
  170. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  171. raw & field::FLG_SYN != 0
  172. }
  173. /// Return the RST flag.
  174. #[inline]
  175. pub fn rst(&self) -> bool {
  176. let data = self.buffer.as_ref();
  177. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  178. raw & field::FLG_RST != 0
  179. }
  180. /// Return the PSH flag.
  181. #[inline]
  182. pub fn psh(&self) -> bool {
  183. let data = self.buffer.as_ref();
  184. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  185. raw & field::FLG_PSH != 0
  186. }
  187. /// Return the ACK flag.
  188. #[inline]
  189. pub fn ack(&self) -> bool {
  190. let data = self.buffer.as_ref();
  191. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  192. raw & field::FLG_ACK != 0
  193. }
  194. /// Return the URG flag.
  195. #[inline]
  196. pub fn urg(&self) -> bool {
  197. let data = self.buffer.as_ref();
  198. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  199. raw & field::FLG_URG != 0
  200. }
  201. /// Return the ECE flag.
  202. #[inline]
  203. pub fn ece(&self) -> bool {
  204. let data = self.buffer.as_ref();
  205. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  206. raw & field::FLG_ECE != 0
  207. }
  208. /// Return the CWR flag.
  209. #[inline]
  210. pub fn cwr(&self) -> bool {
  211. let data = self.buffer.as_ref();
  212. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  213. raw & field::FLG_CWR != 0
  214. }
  215. /// Return the NS flag.
  216. #[inline]
  217. pub fn ns(&self) -> bool {
  218. let data = self.buffer.as_ref();
  219. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  220. raw & field::FLG_NS != 0
  221. }
  222. /// Return the header length, in octets.
  223. #[inline]
  224. pub fn header_len(&self) -> u8 {
  225. let data = self.buffer.as_ref();
  226. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  227. ((raw >> 12) * 4) as u8
  228. }
  229. /// Return the window size field.
  230. #[inline]
  231. pub fn window_len(&self) -> u16 {
  232. let data = self.buffer.as_ref();
  233. NetworkEndian::read_u16(&data[field::WIN_SIZE])
  234. }
  235. /// Return the checksum field.
  236. #[inline]
  237. pub fn checksum(&self) -> u16 {
  238. let data = self.buffer.as_ref();
  239. NetworkEndian::read_u16(&data[field::CHECKSUM])
  240. }
  241. /// Return the urgent pointer field.
  242. #[inline]
  243. pub fn urgent_at(&self) -> u16 {
  244. let data = self.buffer.as_ref();
  245. NetworkEndian::read_u16(&data[field::URGENT])
  246. }
  247. /// Return the length of the segment, in terms of sequence space.
  248. pub fn segment_len(&self) -> usize {
  249. let data = self.buffer.as_ref();
  250. let mut length = data.len() - self.header_len() as usize;
  251. if self.syn() { length += 1 }
  252. if self.fin() { length += 1 }
  253. length
  254. }
  255. /// Returns whether the selective acknowledgement SYN flag is set or not.
  256. pub fn selective_ack_permitted(&self) -> Result<bool> {
  257. let data = self.buffer.as_ref();
  258. let mut options = &data[field::OPTIONS(self.header_len())];
  259. while !options.is_empty() {
  260. let (next_options, option) = TcpOption::parse(options)?;
  261. if option == TcpOption::SackPermitted {
  262. return Ok(true);
  263. }
  264. options = next_options;
  265. }
  266. Ok(false)
  267. }
  268. /// Return the selective acknowledgement ranges, if any. If there are none in the packet, an
  269. /// array of ``None`` values will be returned.
  270. ///
  271. pub fn selective_ack_ranges(&self) -> Result<[Option<(u32, u32)>; 3]> {
  272. let data = self.buffer.as_ref();
  273. let mut options = &data[field::OPTIONS(self.header_len())];
  274. while !options.is_empty() {
  275. let (next_options, option) = TcpOption::parse(options)?;
  276. if let TcpOption::SackRange(slice) = option {
  277. return Ok(slice);
  278. }
  279. options = next_options;
  280. }
  281. Ok([None, None, None])
  282. }
  283. /// Validate the packet checksum.
  284. ///
  285. /// # Panics
  286. /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
  287. /// and that family is IPv4 or IPv6.
  288. ///
  289. /// # Fuzzing
  290. /// This function always returns `true` when fuzzing.
  291. pub fn verify_checksum(&self, src_addr: &IpAddress, dst_addr: &IpAddress) -> bool {
  292. if cfg!(fuzzing) { return true }
  293. let data = self.buffer.as_ref();
  294. checksum::combine(&[
  295. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
  296. data.len() as u32),
  297. checksum::data(data)
  298. ]) == !0
  299. }
  300. }
  301. impl<'a, T: AsRef<[u8]> + ?Sized> Packet<&'a T> {
  302. /// Return a pointer to the options.
  303. #[inline]
  304. pub fn options(&self) -> &'a [u8] {
  305. let header_len = self.header_len();
  306. let data = self.buffer.as_ref();
  307. &data[field::OPTIONS(header_len)]
  308. }
  309. /// Return a pointer to the payload.
  310. #[inline]
  311. pub fn payload(&self) -> &'a [u8] {
  312. let header_len = self.header_len() as usize;
  313. let data = self.buffer.as_ref();
  314. &data[header_len..]
  315. }
  316. }
  317. impl<T: AsRef<[u8]> + AsMut<[u8]>> Packet<T> {
  318. /// Set the source port field.
  319. #[inline]
  320. pub fn set_src_port(&mut self, value: u16) {
  321. let data = self.buffer.as_mut();
  322. NetworkEndian::write_u16(&mut data[field::SRC_PORT], value)
  323. }
  324. /// Set the destination port field.
  325. #[inline]
  326. pub fn set_dst_port(&mut self, value: u16) {
  327. let data = self.buffer.as_mut();
  328. NetworkEndian::write_u16(&mut data[field::DST_PORT], value)
  329. }
  330. /// Set the sequence number field.
  331. #[inline]
  332. pub fn set_seq_number(&mut self, value: SeqNumber) {
  333. let data = self.buffer.as_mut();
  334. NetworkEndian::write_i32(&mut data[field::SEQ_NUM], value.0)
  335. }
  336. /// Set the acknowledgement number field.
  337. #[inline]
  338. pub fn set_ack_number(&mut self, value: SeqNumber) {
  339. let data = self.buffer.as_mut();
  340. NetworkEndian::write_i32(&mut data[field::ACK_NUM], value.0)
  341. }
  342. /// Clear the entire flags field.
  343. #[inline]
  344. pub fn clear_flags(&mut self) {
  345. let data = self.buffer.as_mut();
  346. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  347. let raw = raw & !0x0fff;
  348. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  349. }
  350. /// Set the FIN flag.
  351. #[inline]
  352. pub fn set_fin(&mut self, value: bool) {
  353. let data = self.buffer.as_mut();
  354. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  355. let raw = if value { raw | field::FLG_FIN } else { raw & !field::FLG_FIN };
  356. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  357. }
  358. /// Set the SYN flag.
  359. #[inline]
  360. pub fn set_syn(&mut self, value: bool) {
  361. let data = self.buffer.as_mut();
  362. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  363. let raw = if value { raw | field::FLG_SYN } else { raw & !field::FLG_SYN };
  364. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  365. }
  366. /// Set the RST flag.
  367. #[inline]
  368. pub fn set_rst(&mut self, value: bool) {
  369. let data = self.buffer.as_mut();
  370. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  371. let raw = if value { raw | field::FLG_RST } else { raw & !field::FLG_RST };
  372. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  373. }
  374. /// Set the PSH flag.
  375. #[inline]
  376. pub fn set_psh(&mut self, value: bool) {
  377. let data = self.buffer.as_mut();
  378. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  379. let raw = if value { raw | field::FLG_PSH } else { raw & !field::FLG_PSH };
  380. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  381. }
  382. /// Set the ACK flag.
  383. #[inline]
  384. pub fn set_ack(&mut self, value: bool) {
  385. let data = self.buffer.as_mut();
  386. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  387. let raw = if value { raw | field::FLG_ACK } else { raw & !field::FLG_ACK };
  388. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  389. }
  390. /// Set the URG flag.
  391. #[inline]
  392. pub fn set_urg(&mut self, value: bool) {
  393. let data = self.buffer.as_mut();
  394. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  395. let raw = if value { raw | field::FLG_URG } else { raw & !field::FLG_URG };
  396. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  397. }
  398. /// Set the ECE flag.
  399. #[inline]
  400. pub fn set_ece(&mut self, value: bool) {
  401. let data = self.buffer.as_mut();
  402. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  403. let raw = if value { raw | field::FLG_ECE } else { raw & !field::FLG_ECE };
  404. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  405. }
  406. /// Set the CWR flag.
  407. #[inline]
  408. pub fn set_cwr(&mut self, value: bool) {
  409. let data = self.buffer.as_mut();
  410. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  411. let raw = if value { raw | field::FLG_CWR } else { raw & !field::FLG_CWR };
  412. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  413. }
  414. /// Set the NS flag.
  415. #[inline]
  416. pub fn set_ns(&mut self, value: bool) {
  417. let data = self.buffer.as_mut();
  418. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  419. let raw = if value { raw | field::FLG_NS } else { raw & !field::FLG_NS };
  420. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  421. }
  422. /// Set the header length, in octets.
  423. #[inline]
  424. pub fn set_header_len(&mut self, value: u8) {
  425. let data = self.buffer.as_mut();
  426. let raw = NetworkEndian::read_u16(&data[field::FLAGS]);
  427. let raw = (raw & !0xf000) | ((value as u16) / 4) << 12;
  428. NetworkEndian::write_u16(&mut data[field::FLAGS], raw)
  429. }
  430. /// Return the window size field.
  431. #[inline]
  432. pub fn set_window_len(&mut self, value: u16) {
  433. let data = self.buffer.as_mut();
  434. NetworkEndian::write_u16(&mut data[field::WIN_SIZE], value)
  435. }
  436. /// Set the checksum field.
  437. #[inline]
  438. pub fn set_checksum(&mut self, value: u16) {
  439. let data = self.buffer.as_mut();
  440. NetworkEndian::write_u16(&mut data[field::CHECKSUM], value)
  441. }
  442. /// Set the urgent pointer field.
  443. #[inline]
  444. pub fn set_urgent_at(&mut self, value: u16) {
  445. let data = self.buffer.as_mut();
  446. NetworkEndian::write_u16(&mut data[field::URGENT], value)
  447. }
  448. /// Compute and fill in the header checksum.
  449. ///
  450. /// # Panics
  451. /// This function panics unless `src_addr` and `dst_addr` belong to the same family,
  452. /// and that family is IPv4 or IPv6.
  453. pub fn fill_checksum(&mut self, src_addr: &IpAddress, dst_addr: &IpAddress) {
  454. self.set_checksum(0);
  455. let checksum = {
  456. let data = self.buffer.as_ref();
  457. !checksum::combine(&[
  458. checksum::pseudo_header(src_addr, dst_addr, IpProtocol::Tcp,
  459. data.len() as u32),
  460. checksum::data(data)
  461. ])
  462. };
  463. self.set_checksum(checksum)
  464. }
  465. /// Return a pointer to the options.
  466. #[inline]
  467. pub fn options_mut(&mut self) -> &mut [u8] {
  468. let header_len = self.header_len();
  469. let data = self.buffer.as_mut();
  470. &mut data[field::OPTIONS(header_len)]
  471. }
  472. /// Return a mutable pointer to the payload data.
  473. #[inline]
  474. pub fn payload_mut(&mut self) -> &mut [u8] {
  475. let header_len = self.header_len() as usize;
  476. let data = self.buffer.as_mut();
  477. &mut data[header_len..]
  478. }
  479. }
  480. impl<T: AsRef<[u8]>> AsRef<[u8]> for Packet<T> {
  481. fn as_ref(&self) -> &[u8] {
  482. self.buffer.as_ref()
  483. }
  484. }
  485. /// A representation of a single TCP option.
  486. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  487. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  488. pub enum TcpOption<'a> {
  489. EndOfList,
  490. NoOperation,
  491. MaxSegmentSize(u16),
  492. WindowScale(u8),
  493. SackPermitted,
  494. SackRange([Option<(u32, u32)>; 3]),
  495. Unknown { kind: u8, data: &'a [u8] }
  496. }
  497. impl<'a> TcpOption<'a> {
  498. pub fn parse(buffer: &'a [u8]) -> Result<(&'a [u8], TcpOption<'a>)> {
  499. let (length, option);
  500. match *buffer.get(0).ok_or(Error::Truncated)? {
  501. field::OPT_END => {
  502. length = 1;
  503. option = TcpOption::EndOfList;
  504. }
  505. field::OPT_NOP => {
  506. length = 1;
  507. option = TcpOption::NoOperation;
  508. }
  509. kind => {
  510. length = *buffer.get(1).ok_or(Error::Truncated)? as usize;
  511. let data = buffer.get(2..length).ok_or(Error::Truncated)?;
  512. match (kind, length) {
  513. (field::OPT_END, _) |
  514. (field::OPT_NOP, _) =>
  515. unreachable!(),
  516. (field::OPT_MSS, 4) =>
  517. option = TcpOption::MaxSegmentSize(NetworkEndian::read_u16(data)),
  518. (field::OPT_MSS, _) =>
  519. return Err(Error::Malformed),
  520. (field::OPT_WS, 3) =>
  521. option = TcpOption::WindowScale(data[0]),
  522. (field::OPT_WS, _) =>
  523. return Err(Error::Malformed),
  524. (field::OPT_SACKPERM, 2) =>
  525. option = TcpOption::SackPermitted,
  526. (field::OPT_SACKPERM, _) =>
  527. return Err(Error::Malformed),
  528. (field::OPT_SACKRNG, n) => {
  529. if n < 10 || (n-2) % 8 != 0 {
  530. return Err(Error::Malformed)
  531. }
  532. if n > 26 {
  533. // It's possible for a remote to send 4 SACK blocks, but extremely rare.
  534. // Better to "lose" that 4th block and save the extra RAM and CPU
  535. // cycles in the vastly more common case.
  536. //
  537. // RFC 2018: SACK option that specifies n blocks will have a length of
  538. // 8*n+2 bytes, so the 40 bytes available for TCP options can specify a
  539. // maximum of 4 blocks. It is expected that SACK will often be used in
  540. // conjunction with the Timestamp option used for RTTM [...] thus a
  541. // maximum of 3 SACK blocks will be allowed in this case.
  542. net_debug!("sACK with >3 blocks, truncating to 3");
  543. }
  544. let mut sack_ranges: [Option<(u32, u32)>; 3] = [None; 3];
  545. // RFC 2018: Each contiguous block of data queued at the data receiver is
  546. // defined in the SACK option by two 32-bit unsigned integers in network
  547. // byte order[...]
  548. sack_ranges.iter_mut().enumerate().for_each(|(i, nmut)| {
  549. let left = i * 8;
  550. *nmut = if left < data.len() {
  551. let mid = left + 4;
  552. let right = mid + 4;
  553. let range_left = NetworkEndian::read_u32(
  554. &data[left..mid]);
  555. let range_right = NetworkEndian::read_u32(
  556. &data[mid..right]);
  557. Some((range_left, range_right))
  558. } else {
  559. None
  560. };
  561. });
  562. option = TcpOption::SackRange(sack_ranges);
  563. },
  564. (_, _) =>
  565. option = TcpOption::Unknown { kind, data }
  566. }
  567. }
  568. }
  569. Ok((&buffer[length..], option))
  570. }
  571. pub fn buffer_len(&self) -> usize {
  572. match *self {
  573. TcpOption::EndOfList => 1,
  574. TcpOption::NoOperation => 1,
  575. TcpOption::MaxSegmentSize(_) => 4,
  576. TcpOption::WindowScale(_) => 3,
  577. TcpOption::SackPermitted => 2,
  578. TcpOption::SackRange(s) => s.iter().filter(|s| s.is_some()).count() * 8 + 2,
  579. TcpOption::Unknown { data, .. } => 2 + data.len()
  580. }
  581. }
  582. pub fn emit<'b>(&self, buffer: &'b mut [u8]) -> &'b mut [u8] {
  583. let length;
  584. match *self {
  585. TcpOption::EndOfList => {
  586. length = 1;
  587. // There may be padding space which also should be initialized.
  588. for p in buffer.iter_mut() {
  589. *p = field::OPT_END;
  590. }
  591. }
  592. TcpOption::NoOperation => {
  593. length = 1;
  594. buffer[0] = field::OPT_NOP;
  595. }
  596. _ => {
  597. length = self.buffer_len();
  598. buffer[1] = length as u8;
  599. match self {
  600. &TcpOption::EndOfList |
  601. &TcpOption::NoOperation =>
  602. unreachable!(),
  603. &TcpOption::MaxSegmentSize(value) => {
  604. buffer[0] = field::OPT_MSS;
  605. NetworkEndian::write_u16(&mut buffer[2..], value)
  606. }
  607. &TcpOption::WindowScale(value) => {
  608. buffer[0] = field::OPT_WS;
  609. buffer[2] = value;
  610. }
  611. &TcpOption::SackPermitted => {
  612. buffer[0] = field::OPT_SACKPERM;
  613. }
  614. &TcpOption::SackRange(slice) => {
  615. buffer[0] = field::OPT_SACKRNG;
  616. slice.iter().filter(|s| s.is_some()).enumerate().for_each(|(i, s)| {
  617. let (first, second) = *s.as_ref().unwrap();
  618. let pos = i * 8 + 2;
  619. NetworkEndian::write_u32(&mut buffer[pos..], first);
  620. NetworkEndian::write_u32(&mut buffer[pos+4..], second);
  621. });
  622. }
  623. &TcpOption::Unknown { kind, data: provided } => {
  624. buffer[0] = kind;
  625. buffer[2..].copy_from_slice(provided)
  626. }
  627. }
  628. }
  629. }
  630. &mut buffer[length..]
  631. }
  632. }
  633. /// The possible control flags of a Transmission Control Protocol packet.
  634. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  635. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  636. pub enum Control {
  637. None,
  638. Psh,
  639. Syn,
  640. Fin,
  641. Rst
  642. }
  643. #[allow(clippy::len_without_is_empty)]
  644. impl Control {
  645. /// Return the length of a control flag, in terms of sequence space.
  646. pub fn len(self) -> usize {
  647. match self {
  648. Control::Syn | Control::Fin => 1,
  649. _ => 0
  650. }
  651. }
  652. /// Turn the PSH flag into no flag, and keep the rest as-is.
  653. pub fn quash_psh(self) -> Control {
  654. match self {
  655. Control::Psh => Control::None,
  656. _ => self
  657. }
  658. }
  659. }
  660. /// A high-level representation of a Transmission Control Protocol packet.
  661. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  662. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  663. pub struct Repr<'a> {
  664. pub src_port: u16,
  665. pub dst_port: u16,
  666. pub control: Control,
  667. pub seq_number: SeqNumber,
  668. pub ack_number: Option<SeqNumber>,
  669. pub window_len: u16,
  670. pub window_scale: Option<u8>,
  671. pub max_seg_size: Option<u16>,
  672. pub sack_permitted: bool,
  673. pub sack_ranges: [Option<(u32, u32)>; 3],
  674. pub payload: &'a [u8]
  675. }
  676. impl<'a> Repr<'a> {
  677. /// Parse a Transmission Control Protocol packet and return a high-level representation.
  678. pub fn parse<T>(packet: &Packet<&'a T>, src_addr: &IpAddress, dst_addr: &IpAddress,
  679. checksum_caps: &ChecksumCapabilities) -> Result<Repr<'a>>
  680. where T: AsRef<[u8]> + ?Sized {
  681. // Source and destination ports must be present.
  682. if packet.src_port() == 0 { return Err(Error::Malformed) }
  683. if packet.dst_port() == 0 { return Err(Error::Malformed) }
  684. // Valid checksum is expected.
  685. if checksum_caps.tcp.rx() && !packet.verify_checksum(src_addr, dst_addr) {
  686. return Err(Error::Checksum)
  687. }
  688. let control =
  689. match (packet.syn(), packet.fin(), packet.rst(), packet.psh()) {
  690. (false, false, false, false) => Control::None,
  691. (false, false, false, true) => Control::Psh,
  692. (true, false, false, _) => Control::Syn,
  693. (false, true, false, _) => Control::Fin,
  694. (false, false, true , _) => Control::Rst,
  695. _ => return Err(Error::Malformed)
  696. };
  697. let ack_number =
  698. match packet.ack() {
  699. true => Some(packet.ack_number()),
  700. false => None
  701. };
  702. // The PSH flag is ignored.
  703. // The URG flag and the urgent field is ignored. This behavior is standards-compliant,
  704. // however, most deployed systems (e.g. Linux) are *not* standards-compliant, and would
  705. // cut the byte at the urgent pointer from the stream.
  706. let mut max_seg_size = None;
  707. let mut window_scale = None;
  708. let mut options = packet.options();
  709. let mut sack_permitted = false;
  710. let mut sack_ranges = [None, None, None];
  711. while !options.is_empty() {
  712. let (next_options, option) = TcpOption::parse(options)?;
  713. match option {
  714. TcpOption::EndOfList => break,
  715. TcpOption::NoOperation => (),
  716. TcpOption::MaxSegmentSize(value) =>
  717. max_seg_size = Some(value),
  718. TcpOption::WindowScale(value) => {
  719. // RFC 1323: Thus, the shift count must be limited to 14 (which allows windows
  720. // of 2**30 = 1 Gbyte). If a Window Scale option is received with a shift.cnt
  721. // value exceeding 14, the TCP should log the error but use 14 instead of the
  722. // specified value.
  723. window_scale = if value > 14 {
  724. net_debug!("{}:{}:{}:{}: parsed window scaling factor >14, setting to 14", src_addr, packet.src_port(), dst_addr, packet.dst_port());
  725. Some(14)
  726. } else {
  727. Some(value)
  728. };
  729. },
  730. TcpOption::SackPermitted =>
  731. sack_permitted = true,
  732. TcpOption::SackRange(slice) =>
  733. sack_ranges = slice,
  734. _ => (),
  735. }
  736. options = next_options;
  737. }
  738. Ok(Repr {
  739. src_port: packet.src_port(),
  740. dst_port: packet.dst_port(),
  741. control: control,
  742. seq_number: packet.seq_number(),
  743. ack_number: ack_number,
  744. window_len: packet.window_len(),
  745. window_scale: window_scale,
  746. max_seg_size: max_seg_size,
  747. sack_permitted: sack_permitted,
  748. sack_ranges: sack_ranges,
  749. payload: packet.payload()
  750. })
  751. }
  752. /// Return the length of a header that will be emitted from this high-level representation.
  753. ///
  754. /// This should be used for buffer space calculations.
  755. /// The TCP header length is a multiple of 4.
  756. pub fn header_len(&self) -> usize {
  757. let mut length = field::URGENT.end;
  758. if self.max_seg_size.is_some() {
  759. length += 4
  760. }
  761. if self.window_scale.is_some() {
  762. length += 3
  763. }
  764. if self.sack_permitted {
  765. length += 2;
  766. }
  767. let sack_range_len: usize = self.sack_ranges.iter().map(
  768. |o| o.map(|_| 8).unwrap_or(0)
  769. ).sum();
  770. if sack_range_len > 0 {
  771. length += sack_range_len + 2;
  772. }
  773. if length % 4 != 0 {
  774. length += 4 - length % 4;
  775. }
  776. length
  777. }
  778. /// Return the length of a packet that will be emitted from this high-level representation.
  779. pub fn buffer_len(&self) -> usize {
  780. self.header_len() + self.payload.len()
  781. }
  782. /// Emit a high-level representation into a Transmission Control Protocol packet.
  783. pub fn emit<T>(&self, packet: &mut Packet<&mut T>, src_addr: &IpAddress, dst_addr: &IpAddress,
  784. checksum_caps: &ChecksumCapabilities)
  785. where T: AsRef<[u8]> + AsMut<[u8]> + ?Sized {
  786. packet.set_src_port(self.src_port);
  787. packet.set_dst_port(self.dst_port);
  788. packet.set_seq_number(self.seq_number);
  789. packet.set_ack_number(self.ack_number.unwrap_or(SeqNumber(0)));
  790. packet.set_window_len(self.window_len);
  791. packet.set_header_len(self.header_len() as u8);
  792. packet.clear_flags();
  793. match self.control {
  794. Control::None => (),
  795. Control::Psh => packet.set_psh(true),
  796. Control::Syn => packet.set_syn(true),
  797. Control::Fin => packet.set_fin(true),
  798. Control::Rst => packet.set_rst(true)
  799. }
  800. packet.set_ack(self.ack_number.is_some());
  801. {
  802. let mut options = packet.options_mut();
  803. if let Some(value) = self.max_seg_size {
  804. let tmp = options; options = TcpOption::MaxSegmentSize(value).emit(tmp);
  805. }
  806. if let Some(value) = self.window_scale {
  807. let tmp = options; options = TcpOption::WindowScale(value).emit(tmp);
  808. }
  809. if self.sack_permitted {
  810. let tmp = options; options = TcpOption::SackPermitted.emit(tmp);
  811. } else if self.ack_number.is_some() && self.sack_ranges.iter().any(|s| s.is_some()) {
  812. let tmp = options; options = TcpOption::SackRange(self.sack_ranges).emit(tmp);
  813. }
  814. if !options.is_empty() {
  815. TcpOption::EndOfList.emit(options);
  816. }
  817. }
  818. packet.set_urgent_at(0);
  819. packet.payload_mut()[..self.payload.len()].copy_from_slice(self.payload);
  820. if checksum_caps.tcp.tx() {
  821. packet.fill_checksum(src_addr, dst_addr)
  822. } else {
  823. // make sure we get a consistently zeroed checksum,
  824. // since implementations might rely on it
  825. packet.set_checksum(0);
  826. }
  827. }
  828. /// Return the length of the segment, in terms of sequence space.
  829. pub fn segment_len(&self) -> usize {
  830. self.payload.len() + self.control.len()
  831. }
  832. /// Return whether the segment has no flags set (except PSH) and no data.
  833. pub fn is_empty(&self) -> bool {
  834. match self.control {
  835. _ if !self.payload.is_empty() => false,
  836. Control::Syn | Control::Fin | Control::Rst => false,
  837. Control::None | Control::Psh => true
  838. }
  839. }
  840. }
  841. impl<'a, T: AsRef<[u8]> + ?Sized> fmt::Display for Packet<&'a T> {
  842. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  843. // Cannot use Repr::parse because we don't have the IP addresses.
  844. write!(f, "TCP src={} dst={}",
  845. self.src_port(), self.dst_port())?;
  846. if self.syn() { write!(f, " syn")? }
  847. if self.fin() { write!(f, " fin")? }
  848. if self.rst() { write!(f, " rst")? }
  849. if self.psh() { write!(f, " psh")? }
  850. if self.ece() { write!(f, " ece")? }
  851. if self.cwr() { write!(f, " cwr")? }
  852. if self.ns() { write!(f, " ns" )? }
  853. write!(f, " seq={}", self.seq_number())?;
  854. if self.ack() {
  855. write!(f, " ack={}", self.ack_number())?;
  856. }
  857. write!(f, " win={}", self.window_len())?;
  858. if self.urg() {
  859. write!(f, " urg={}", self.urgent_at())?;
  860. }
  861. write!(f, " len={}", self.payload().len())?;
  862. let mut options = self.options();
  863. while !options.is_empty() {
  864. let (next_options, option) =
  865. match TcpOption::parse(options) {
  866. Ok(res) => res,
  867. Err(err) => return write!(f, " ({})", err)
  868. };
  869. match option {
  870. TcpOption::EndOfList => break,
  871. TcpOption::NoOperation => (),
  872. TcpOption::MaxSegmentSize(value) =>
  873. write!(f, " mss={}", value)?,
  874. TcpOption::WindowScale(value) =>
  875. write!(f, " ws={}", value)?,
  876. TcpOption::SackPermitted =>
  877. write!(f, " sACK")?,
  878. TcpOption::SackRange(slice) =>
  879. write!(f, " sACKr{:?}", slice)?, // debug print conveniently includes the []s
  880. TcpOption::Unknown { kind, .. } =>
  881. write!(f, " opt({})", kind)?,
  882. }
  883. options = next_options;
  884. }
  885. Ok(())
  886. }
  887. }
  888. impl<'a> fmt::Display for Repr<'a> {
  889. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  890. write!(f, "TCP src={} dst={}",
  891. self.src_port, self.dst_port)?;
  892. match self.control {
  893. Control::Syn => write!(f, " syn")?,
  894. Control::Fin => write!(f, " fin")?,
  895. Control::Rst => write!(f, " rst")?,
  896. Control::Psh => write!(f, " psh")?,
  897. Control::None => ()
  898. }
  899. write!(f, " seq={}", self.seq_number)?;
  900. if let Some(ack_number) = self.ack_number {
  901. write!(f, " ack={}", ack_number)?;
  902. }
  903. write!(f, " win={}", self.window_len)?;
  904. write!(f, " len={}", self.payload.len())?;
  905. if let Some(max_seg_size) = self.max_seg_size {
  906. write!(f, " mss={}", max_seg_size)?;
  907. }
  908. Ok(())
  909. }
  910. }
  911. use crate::wire::pretty_print::{PrettyPrint, PrettyIndent};
  912. impl<T: AsRef<[u8]>> PrettyPrint for Packet<T> {
  913. fn pretty_print(buffer: &dyn AsRef<[u8]>, f: &mut fmt::Formatter,
  914. indent: &mut PrettyIndent) -> fmt::Result {
  915. match Packet::new_checked(buffer) {
  916. Err(err) => write!(f, "{}({})", indent, err),
  917. Ok(packet) => write!(f, "{}{}", indent, packet)
  918. }
  919. }
  920. }
  921. #[cfg(test)]
  922. mod test {
  923. #[cfg(feature = "proto-ipv4")]
  924. use crate::wire::Ipv4Address;
  925. use super::*;
  926. #[cfg(feature = "proto-ipv4")]
  927. const SRC_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 1]);
  928. #[cfg(feature = "proto-ipv4")]
  929. const DST_ADDR: Ipv4Address = Ipv4Address([192, 168, 1, 2]);
  930. #[cfg(feature = "proto-ipv4")]
  931. static PACKET_BYTES: [u8; 28] =
  932. [0xbf, 0x00, 0x00, 0x50,
  933. 0x01, 0x23, 0x45, 0x67,
  934. 0x89, 0xab, 0xcd, 0xef,
  935. 0x60, 0x35, 0x01, 0x23,
  936. 0x01, 0xb6, 0x02, 0x01,
  937. 0x03, 0x03, 0x0c, 0x01,
  938. 0xaa, 0x00, 0x00, 0xff];
  939. #[cfg(feature = "proto-ipv4")]
  940. static OPTION_BYTES: [u8; 4] =
  941. [0x03, 0x03, 0x0c, 0x01];
  942. #[cfg(feature = "proto-ipv4")]
  943. static PAYLOAD_BYTES: [u8; 4] =
  944. [0xaa, 0x00, 0x00, 0xff];
  945. #[test]
  946. #[cfg(feature = "proto-ipv4")]
  947. fn test_deconstruct() {
  948. let packet = Packet::new_unchecked(&PACKET_BYTES[..]);
  949. assert_eq!(packet.src_port(), 48896);
  950. assert_eq!(packet.dst_port(), 80);
  951. assert_eq!(packet.seq_number(), SeqNumber(0x01234567));
  952. assert_eq!(packet.ack_number(), SeqNumber(0x89abcdefu32 as i32));
  953. assert_eq!(packet.header_len(), 24);
  954. assert_eq!(packet.fin(), true);
  955. assert_eq!(packet.syn(), false);
  956. assert_eq!(packet.rst(), true);
  957. assert_eq!(packet.psh(), false);
  958. assert_eq!(packet.ack(), true);
  959. assert_eq!(packet.urg(), true);
  960. assert_eq!(packet.window_len(), 0x0123);
  961. assert_eq!(packet.urgent_at(), 0x0201);
  962. assert_eq!(packet.checksum(), 0x01b6);
  963. assert_eq!(packet.options(), &OPTION_BYTES[..]);
  964. assert_eq!(packet.payload(), &PAYLOAD_BYTES[..]);
  965. assert_eq!(packet.verify_checksum(&SRC_ADDR.into(), &DST_ADDR.into()), true);
  966. }
  967. #[test]
  968. #[cfg(feature = "proto-ipv4")]
  969. fn test_construct() {
  970. let mut bytes = vec![0xa5; PACKET_BYTES.len()];
  971. let mut packet = Packet::new_unchecked(&mut bytes);
  972. packet.set_src_port(48896);
  973. packet.set_dst_port(80);
  974. packet.set_seq_number(SeqNumber(0x01234567));
  975. packet.set_ack_number(SeqNumber(0x89abcdefu32 as i32));
  976. packet.set_header_len(24);
  977. packet.clear_flags();
  978. packet.set_fin(true);
  979. packet.set_syn(false);
  980. packet.set_rst(true);
  981. packet.set_psh(false);
  982. packet.set_ack(true);
  983. packet.set_urg(true);
  984. packet.set_window_len(0x0123);
  985. packet.set_urgent_at(0x0201);
  986. packet.set_checksum(0xEEEE);
  987. packet.options_mut().copy_from_slice(&OPTION_BYTES[..]);
  988. packet.payload_mut().copy_from_slice(&PAYLOAD_BYTES[..]);
  989. packet.fill_checksum(&SRC_ADDR.into(), &DST_ADDR.into());
  990. assert_eq!(&packet.into_inner()[..], &PACKET_BYTES[..]);
  991. }
  992. #[test]
  993. #[cfg(feature = "proto-ipv4")]
  994. fn test_truncated() {
  995. let packet = Packet::new_unchecked(&PACKET_BYTES[..23]);
  996. assert_eq!(packet.check_len(), Err(Error::Truncated));
  997. }
  998. #[test]
  999. fn test_impossible_len() {
  1000. let mut bytes = vec![0; 20];
  1001. let mut packet = Packet::new_unchecked(&mut bytes);
  1002. packet.set_header_len(10);
  1003. assert_eq!(packet.check_len(), Err(Error::Malformed));
  1004. }
  1005. #[cfg(feature = "proto-ipv4")]
  1006. static SYN_PACKET_BYTES: [u8; 24] =
  1007. [0xbf, 0x00, 0x00, 0x50,
  1008. 0x01, 0x23, 0x45, 0x67,
  1009. 0x00, 0x00, 0x00, 0x00,
  1010. 0x50, 0x02, 0x01, 0x23,
  1011. 0x7a, 0x8d, 0x00, 0x00,
  1012. 0xaa, 0x00, 0x00, 0xff];
  1013. #[cfg(feature = "proto-ipv4")]
  1014. fn packet_repr() -> Repr<'static> {
  1015. Repr {
  1016. src_port: 48896,
  1017. dst_port: 80,
  1018. seq_number: SeqNumber(0x01234567),
  1019. ack_number: None,
  1020. window_len: 0x0123,
  1021. window_scale: None,
  1022. control: Control::Syn,
  1023. max_seg_size: None,
  1024. sack_permitted: false,
  1025. sack_ranges: [None, None, None],
  1026. payload: &PAYLOAD_BYTES
  1027. }
  1028. }
  1029. #[test]
  1030. #[cfg(feature = "proto-ipv4")]
  1031. fn test_parse() {
  1032. let packet = Packet::new_unchecked(&SYN_PACKET_BYTES[..]);
  1033. let repr = Repr::parse(&packet, &SRC_ADDR.into(), &DST_ADDR.into(), &ChecksumCapabilities::default()).unwrap();
  1034. assert_eq!(repr, packet_repr());
  1035. }
  1036. #[test]
  1037. #[cfg(feature = "proto-ipv4")]
  1038. fn test_emit() {
  1039. let repr = packet_repr();
  1040. let mut bytes = vec![0xa5; repr.buffer_len()];
  1041. let mut packet = Packet::new_unchecked(&mut bytes);
  1042. repr.emit(&mut packet, &SRC_ADDR.into(), &DST_ADDR.into(), &ChecksumCapabilities::default());
  1043. assert_eq!(&packet.into_inner()[..], &SYN_PACKET_BYTES[..]);
  1044. }
  1045. #[test]
  1046. #[cfg(feature = "proto-ipv4")]
  1047. fn test_header_len_multiple_of_4() {
  1048. let mut repr = packet_repr();
  1049. repr.window_scale = Some(0); // This TCP Option needs 3 bytes.
  1050. assert_eq!(repr.header_len() % 4, 0); // Should e.g. be 28 instead of 27.
  1051. }
  1052. macro_rules! assert_option_parses {
  1053. ($opt:expr, $data:expr) => ({
  1054. assert_eq!(TcpOption::parse($data), Ok((&[][..], $opt)));
  1055. let buffer = &mut [0; 40][..$opt.buffer_len()];
  1056. assert_eq!($opt.emit(buffer), &mut []);
  1057. assert_eq!(&*buffer, $data);
  1058. })
  1059. }
  1060. #[test]
  1061. fn test_tcp_options() {
  1062. assert_option_parses!(TcpOption::EndOfList,
  1063. &[0x00]);
  1064. assert_option_parses!(TcpOption::NoOperation,
  1065. &[0x01]);
  1066. assert_option_parses!(TcpOption::MaxSegmentSize(1500),
  1067. &[0x02, 0x04, 0x05, 0xdc]);
  1068. assert_option_parses!(TcpOption::WindowScale(12),
  1069. &[0x03, 0x03, 0x0c]);
  1070. assert_option_parses!(TcpOption::SackPermitted,
  1071. &[0x4, 0x02]);
  1072. assert_option_parses!(TcpOption::SackRange([Some((500, 1500)), None, None]),
  1073. &[0x05, 0x0a,
  1074. 0x00, 0x00, 0x01, 0xf4, 0x00, 0x00, 0x05, 0xdc]);
  1075. assert_option_parses!(TcpOption::SackRange([Some((875, 1225)), Some((1500, 2500)), None]),
  1076. &[0x05, 0x12,
  1077. 0x00, 0x00, 0x03, 0x6b, 0x00, 0x00, 0x04, 0xc9,
  1078. 0x00, 0x00, 0x05, 0xdc, 0x00, 0x00, 0x09, 0xc4]);
  1079. assert_option_parses!(TcpOption::SackRange([Some((875000, 1225000)),
  1080. Some((1500000, 2500000)),
  1081. Some((876543210, 876654320))]),
  1082. &[0x05, 0x1a,
  1083. 0x00, 0x0d, 0x59, 0xf8, 0x00, 0x12, 0xb1, 0x28,
  1084. 0x00, 0x16, 0xe3, 0x60, 0x00, 0x26, 0x25, 0xa0,
  1085. 0x34, 0x3e, 0xfc, 0xea, 0x34, 0x40, 0xae, 0xf0]);
  1086. assert_option_parses!(TcpOption::Unknown { kind: 12, data: &[1, 2, 3][..] },
  1087. &[0x0c, 0x05, 0x01, 0x02, 0x03])
  1088. }
  1089. #[test]
  1090. fn test_malformed_tcp_options() {
  1091. assert_eq!(TcpOption::parse(&[]),
  1092. Err(Error::Truncated));
  1093. assert_eq!(TcpOption::parse(&[0xc]),
  1094. Err(Error::Truncated));
  1095. assert_eq!(TcpOption::parse(&[0xc, 0x05, 0x01, 0x02]),
  1096. Err(Error::Truncated));
  1097. assert_eq!(TcpOption::parse(&[0xc, 0x01]),
  1098. Err(Error::Truncated));
  1099. assert_eq!(TcpOption::parse(&[0x2, 0x02]),
  1100. Err(Error::Malformed));
  1101. assert_eq!(TcpOption::parse(&[0x3, 0x02]),
  1102. Err(Error::Malformed));
  1103. }
  1104. }