tcp.rs 43 KB

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