tcp.rs 43 KB

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