tcp.rs 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. // Heads up! Before working on this file you should read, at least, RFC 793 and
  2. // the parts of RFC 1122 that discuss TCP. Consult RFC 7414 when implementing
  3. // a new feature.
  4. use core::{cmp, fmt};
  5. use {Error, Result};
  6. use phy::DeviceCapabilities;
  7. use wire::{IpProtocol, IpAddress, IpEndpoint, TcpSeqNumber, TcpRepr, TcpControl};
  8. use socket::{Socket, IpRepr};
  9. use storage::{Assembler, RingBuffer};
  10. pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
  11. /// The state of a TCP socket, according to [RFC 793][rfc793].
  12. /// [rfc793]: https://tools.ietf.org/html/rfc793
  13. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  14. pub enum State {
  15. Closed,
  16. Listen,
  17. SynSent,
  18. SynReceived,
  19. Established,
  20. FinWait1,
  21. FinWait2,
  22. CloseWait,
  23. Closing,
  24. LastAck,
  25. TimeWait
  26. }
  27. impl fmt::Display for State {
  28. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  29. match self {
  30. &State::Closed => write!(f, "CLOSED"),
  31. &State::Listen => write!(f, "LISTEN"),
  32. &State::SynSent => write!(f, "SYN-SENT"),
  33. &State::SynReceived => write!(f, "SYN-RECEIVED"),
  34. &State::Established => write!(f, "ESTABLISHED"),
  35. &State::FinWait1 => write!(f, "FIN-WAIT-1"),
  36. &State::FinWait2 => write!(f, "FIN-WAIT-2"),
  37. &State::CloseWait => write!(f, "CLOSE-WAIT"),
  38. &State::Closing => write!(f, "CLOSING"),
  39. &State::LastAck => write!(f, "LAST-ACK"),
  40. &State::TimeWait => write!(f, "TIME-WAIT")
  41. }
  42. }
  43. }
  44. #[derive(Debug, Clone, Copy, PartialEq)]
  45. enum Timer {
  46. Idle {
  47. keep_alive_at: Option<u64>,
  48. },
  49. Retransmit {
  50. expires_at: u64,
  51. delay: u64
  52. },
  53. Close {
  54. expires_at: u64
  55. }
  56. }
  57. const RETRANSMIT_DELAY: u64 = 100;
  58. const CLOSE_DELAY: u64 = 10_000;
  59. impl Default for Timer {
  60. fn default() -> Timer {
  61. Timer::Idle { keep_alive_at: None }
  62. }
  63. }
  64. impl Timer {
  65. fn should_keep_alive(&self, timestamp: u64) -> bool {
  66. match *self {
  67. Timer::Idle { keep_alive_at: Some(keep_alive_at) }
  68. if timestamp >= keep_alive_at => {
  69. true
  70. }
  71. _ => false
  72. }
  73. }
  74. fn should_retransmit(&self, timestamp: u64) -> Option<u64> {
  75. match *self {
  76. Timer::Retransmit { expires_at, delay }
  77. if timestamp >= expires_at => {
  78. Some(timestamp - expires_at + delay)
  79. }
  80. _ => None
  81. }
  82. }
  83. fn should_close(&self, timestamp: u64) -> bool {
  84. match *self {
  85. Timer::Close { expires_at }
  86. if timestamp >= expires_at => {
  87. true
  88. }
  89. _ => false
  90. }
  91. }
  92. fn poll_at(&self) -> Option<u64> {
  93. match *self {
  94. Timer::Idle { keep_alive_at } => keep_alive_at,
  95. Timer::Retransmit { expires_at, .. } => Some(expires_at),
  96. Timer::Close { expires_at } => Some(expires_at),
  97. }
  98. }
  99. fn set_for_idle(&mut self, timestamp: u64, interval: Option<u64>) {
  100. *self = Timer::Idle {
  101. keep_alive_at: interval.map(|interval| timestamp + interval)
  102. }
  103. }
  104. fn set_keep_alive(&mut self) {
  105. match *self {
  106. Timer::Idle { ref mut keep_alive_at }
  107. if keep_alive_at.is_none() => {
  108. *keep_alive_at = Some(0)
  109. }
  110. _ => ()
  111. }
  112. }
  113. fn rewind_keep_alive(&mut self, timestamp: u64, interval: Option<u64>) {
  114. match self {
  115. &mut Timer::Idle { ref mut keep_alive_at } => {
  116. *keep_alive_at = interval.map(|interval| timestamp + interval)
  117. }
  118. _ => ()
  119. }
  120. }
  121. fn set_for_retransmit(&mut self, timestamp: u64) {
  122. match *self {
  123. Timer::Idle { .. } => {
  124. *self = Timer::Retransmit {
  125. expires_at: timestamp + RETRANSMIT_DELAY,
  126. delay: RETRANSMIT_DELAY,
  127. }
  128. }
  129. Timer::Retransmit { expires_at, delay }
  130. if timestamp >= expires_at => {
  131. *self = Timer::Retransmit {
  132. expires_at: timestamp + delay,
  133. delay: delay * 2
  134. }
  135. }
  136. Timer::Retransmit { .. } => (),
  137. Timer::Close { .. } => ()
  138. }
  139. }
  140. fn set_for_close(&mut self, timestamp: u64) {
  141. *self = Timer::Close {
  142. expires_at: timestamp + CLOSE_DELAY
  143. }
  144. }
  145. }
  146. /// A Transmission Control Protocol socket.
  147. ///
  148. /// A TCP socket may passively listen for connections or actively connect to another endpoint.
  149. /// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
  150. /// accept several connections, as many sockets must be allocated, or any new connection
  151. /// attempts will be reset.
  152. #[derive(Debug)]
  153. pub struct TcpSocket<'a> {
  154. debug_id: usize,
  155. state: State,
  156. timer: Timer,
  157. assembler: Assembler,
  158. rx_buffer: SocketBuffer<'a>,
  159. tx_buffer: SocketBuffer<'a>,
  160. /// Interval after which, if no inbound packets are received, the connection is aborted.
  161. timeout: Option<u64>,
  162. /// Interval at which keep-alive packets will be sent.
  163. keep_alive: Option<u64>,
  164. /// Address passed to listen(). Listen address is set when listen() is called and
  165. /// used every time the socket is reset back to the LISTEN state.
  166. listen_address: IpAddress,
  167. /// Current local endpoint. This is used for both filtering the incoming packets and
  168. /// setting the source address. When listening or initiating connection on/from
  169. /// an unspecified address, this field is updated with the chosen source address before
  170. /// any packets are sent.
  171. local_endpoint: IpEndpoint,
  172. /// Current remote endpoint. This is used for both filtering the incoming packets and
  173. /// setting the destination address. If the remote endpoint is unspecified, it means that
  174. /// aborting the connection will not send an RST, and, in TIME-WAIT state, will not
  175. /// send an ACK.
  176. remote_endpoint: IpEndpoint,
  177. /// The sequence number corresponding to the beginning of the transmit buffer.
  178. /// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
  179. local_seq_no: TcpSeqNumber,
  180. /// The sequence number corresponding to the beginning of the receive buffer.
  181. /// I.e. userspace reading n bytes adds n to remote_seq_no.
  182. remote_seq_no: TcpSeqNumber,
  183. /// The last sequence number sent.
  184. /// I.e. in an idle socket, local_seq_no+tx_buffer.len().
  185. remote_last_seq: TcpSeqNumber,
  186. /// The last acknowledgement number sent.
  187. /// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
  188. remote_last_ack: Option<TcpSeqNumber>,
  189. /// The last window length sent.
  190. remote_last_win: u16,
  191. /// The speculative remote window size.
  192. /// I.e. the actual remote window size minus the count of in-flight octets.
  193. remote_win_len: usize,
  194. /// The maximum number of data octets that the remote side may receive.
  195. remote_mss: usize,
  196. /// The timestamp of the last packet received.
  197. remote_last_ts: Option<u64>,
  198. }
  199. const DEFAULT_MSS: usize = 536;
  200. impl<'a> TcpSocket<'a> {
  201. /// Create a socket using the given buffers.
  202. pub fn new<T>(rx_buffer: T, tx_buffer: T) -> Socket<'a, 'static>
  203. where T: Into<SocketBuffer<'a>> {
  204. let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
  205. if rx_buffer.capacity() > <u16>::max_value() as usize {
  206. panic!("buffers larger than {} require window scaling, which is not implemented",
  207. <u16>::max_value())
  208. }
  209. Socket::Tcp(TcpSocket {
  210. debug_id: 0,
  211. state: State::Closed,
  212. timer: Timer::default(),
  213. assembler: Assembler::new(rx_buffer.capacity()),
  214. tx_buffer: tx_buffer,
  215. rx_buffer: rx_buffer,
  216. timeout: None,
  217. keep_alive: None,
  218. listen_address: IpAddress::default(),
  219. local_endpoint: IpEndpoint::default(),
  220. remote_endpoint: IpEndpoint::default(),
  221. local_seq_no: TcpSeqNumber::default(),
  222. remote_seq_no: TcpSeqNumber::default(),
  223. remote_last_seq: TcpSeqNumber::default(),
  224. remote_last_ack: None,
  225. remote_last_win: 0,
  226. remote_win_len: 0,
  227. remote_mss: DEFAULT_MSS,
  228. remote_last_ts: None,
  229. })
  230. }
  231. /// Return the debug identifier.
  232. #[inline]
  233. pub fn debug_id(&self) -> usize {
  234. self.debug_id
  235. }
  236. /// Set the debug identifier.
  237. ///
  238. /// The debug identifier is a number printed in socket trace messages.
  239. /// It could as well be used by the user code.
  240. pub fn set_debug_id(&mut self, id: usize) {
  241. self.debug_id = id
  242. }
  243. /// Return the timeout duration.
  244. ///
  245. /// See also the [set_timeout](#method.set_timeout) method.
  246. pub fn timeout(&self) -> Option<u64> {
  247. self.timeout
  248. }
  249. /// Set the timeout duration.
  250. ///
  251. /// A socket with a timeout duration set will abort the connection if either of the following
  252. /// occurs:
  253. ///
  254. /// * After a [connect](#method.connect) call, the remote endpoint does not respond within
  255. /// the specified duration;
  256. /// * After establishing a connection, there is data in the transmit buffer and the remote
  257. /// endpoint exceeds the specified duration between any two packets it sends;
  258. /// * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
  259. /// the specified duration between any two packets it sends.
  260. pub fn set_timeout(&mut self, duration: Option<u64>) {
  261. self.timeout = duration
  262. }
  263. /// Return the keep-alive interval.
  264. ///
  265. /// See also the [set_keep_alive](#method.set_keep_alive) method.
  266. pub fn keep_alive(&self) -> Option<u64> {
  267. self.keep_alive
  268. }
  269. /// Set the keep-alive interval.
  270. ///
  271. /// An idle socket with a keep-alive interval set will transmit a "challenge ACK" packet
  272. /// every time it receives no communication during that interval. As a result, three things
  273. /// may happen:
  274. ///
  275. /// * The remote endpoint is fine and answers with an ACK packet.
  276. /// * The remote endpoint has rebooted and answers with an RST packet.
  277. /// * The remote endpoint has crashed and does not answer.
  278. ///
  279. /// The keep-alive functionality together with the timeout functionality allows to react
  280. /// to these error conditions.
  281. pub fn set_keep_alive(&mut self, interval: Option<u64>) {
  282. self.keep_alive = interval;
  283. if self.keep_alive.is_some() {
  284. // If the connection is idle and we've just set the option, it would not take effect
  285. // until the next packet, unless we wind up the timer explicitly.
  286. self.timer.set_keep_alive();
  287. }
  288. }
  289. /// Return the local endpoint.
  290. #[inline]
  291. pub fn local_endpoint(&self) -> IpEndpoint {
  292. self.local_endpoint
  293. }
  294. /// Return the remote endpoint.
  295. #[inline]
  296. pub fn remote_endpoint(&self) -> IpEndpoint {
  297. self.remote_endpoint
  298. }
  299. /// Return the connection state, in terms of the TCP state machine.
  300. #[inline]
  301. pub fn state(&self) -> State {
  302. self.state
  303. }
  304. fn reset(&mut self) {
  305. self.state = State::Closed;
  306. self.timer = Timer::default();
  307. self.assembler = Assembler::new(self.rx_buffer.capacity());
  308. self.tx_buffer.clear();
  309. self.rx_buffer.clear();
  310. self.keep_alive = None;
  311. self.timeout = None;
  312. self.listen_address = IpAddress::default();
  313. self.local_endpoint = IpEndpoint::default();
  314. self.remote_endpoint = IpEndpoint::default();
  315. self.local_seq_no = TcpSeqNumber::default();
  316. self.remote_seq_no = TcpSeqNumber::default();
  317. self.remote_last_seq = TcpSeqNumber::default();
  318. self.remote_last_ack = None;
  319. self.remote_last_win = 0;
  320. self.remote_win_len = 0;
  321. self.remote_mss = DEFAULT_MSS;
  322. self.remote_last_ts = None;
  323. }
  324. /// Start listening on the given endpoint.
  325. ///
  326. /// This function returns `Err(Error::Illegal)` if the socket was already open
  327. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  328. /// if the port in the given endpoint is zero.
  329. pub fn listen<T>(&mut self, local_endpoint: T) -> Result<()>
  330. where T: Into<IpEndpoint> {
  331. let local_endpoint = local_endpoint.into();
  332. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  333. if self.is_open() { return Err(Error::Illegal) }
  334. self.reset();
  335. self.listen_address = local_endpoint.addr;
  336. self.local_endpoint = local_endpoint;
  337. self.remote_endpoint = IpEndpoint::default();
  338. self.set_state(State::Listen);
  339. Ok(())
  340. }
  341. /// Connect to a given endpoint.
  342. ///
  343. /// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
  344. /// allocates a port between 49152 and 65535, a connection may be established as follows:
  345. ///
  346. /// ```rust,ignore
  347. /// socket.connect((IpAddress::v4(10, 0, 0, 1), 80), get_ephemeral_port())
  348. /// ```
  349. ///
  350. /// The local address may optionally be provided.
  351. ///
  352. /// This function returns an error if the socket was open; see [is_open](#method.is_open).
  353. /// It also returns an error if the local or remote port is zero, or if the remote address
  354. /// is unspecified.
  355. pub fn connect<T, U>(&mut self, remote_endpoint: T, local_endpoint: U) -> Result<()>
  356. where T: Into<IpEndpoint>, U: Into<IpEndpoint> {
  357. let remote_endpoint = remote_endpoint.into();
  358. let local_endpoint = local_endpoint.into();
  359. if self.is_open() { return Err(Error::Illegal) }
  360. if !remote_endpoint.is_specified() { return Err(Error::Unaddressable) }
  361. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  362. // If local address is not provided, use an unspecified address but a specified protocol.
  363. // This lets us lower IpRepr later to determine IP header size and calculate MSS,
  364. // but without committing to a specific address right away.
  365. let local_addr = match remote_endpoint.addr {
  366. IpAddress::Unspecified => return Err(Error::Unaddressable),
  367. _ => remote_endpoint.addr.to_unspecified(),
  368. };
  369. let local_endpoint = IpEndpoint { addr: local_addr, ..local_endpoint };
  370. // Carry over the local sequence number.
  371. let local_seq_no = self.local_seq_no;
  372. self.reset();
  373. self.local_endpoint = local_endpoint;
  374. self.remote_endpoint = remote_endpoint;
  375. self.local_seq_no = local_seq_no;
  376. self.remote_last_seq = local_seq_no;
  377. self.set_state(State::SynSent);
  378. Ok(())
  379. }
  380. /// Close the transmit half of the full-duplex connection.
  381. ///
  382. /// Note that there is no corresponding function for the receive half of the full-duplex
  383. /// connection; only the remote end can close it. If you no longer wish to receive any
  384. /// data and would like to reuse the socket right away, use [abort](#method.abort).
  385. pub fn close(&mut self) {
  386. match self.state {
  387. // In the LISTEN state there is no established connection.
  388. State::Listen =>
  389. self.set_state(State::Closed),
  390. // In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
  391. // receiving an RST, will abort the connection.
  392. State::SynSent =>
  393. self.set_state(State::Closed),
  394. // In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
  395. // of the connection is open, and needs to be explicitly closed with a FIN.
  396. State::SynReceived | State::Established =>
  397. self.set_state(State::FinWait1),
  398. State::CloseWait =>
  399. self.set_state(State::LastAck),
  400. // In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
  401. // the transmit half of the connection is already closed, and no further
  402. // action is needed.
  403. State::FinWait1 | State::FinWait2 | State::Closing |
  404. State::TimeWait | State::LastAck | State::Closed => ()
  405. }
  406. }
  407. /// Aborts the connection, if any.
  408. ///
  409. /// This function instantly closes the socket. One reset packet will be sent to the remote
  410. /// endpoint.
  411. ///
  412. /// In terms of the TCP state machine, the socket may be in any state and is moved to
  413. /// the `CLOSED` state.
  414. pub fn abort(&mut self) {
  415. self.set_state(State::Closed);
  416. }
  417. /// Return whether the socket is passively listening for incoming connections.
  418. ///
  419. /// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
  420. #[inline]
  421. pub fn is_listening(&self) -> bool {
  422. match self.state {
  423. State::Listen => true,
  424. _ => false
  425. }
  426. }
  427. /// Return whether the socket is open.
  428. ///
  429. /// This function returns true if the socket will process incoming or dispatch outgoing
  430. /// packets. Note that this does not mean that it is possible to send or receive data through
  431. /// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
  432. ///
  433. /// In terms of the TCP state machine, the socket must not be in the `CLOSED`
  434. /// or `TIME-WAIT` states.
  435. #[inline]
  436. pub fn is_open(&self) -> bool {
  437. match self.state {
  438. State::Closed => false,
  439. State::TimeWait => false,
  440. _ => true
  441. }
  442. }
  443. /// Return whether a connection is active.
  444. ///
  445. /// This function returns true if the socket is actively exchanging packets with
  446. /// a remote endpoint. Note that this does not mean that it is possible to send or receive
  447. /// data through the socket; for that, use [can_send](#method.can_send) or
  448. /// [can_recv](#method.can_recv).
  449. ///
  450. /// If a connection is established, [abort](#method.close) will send a reset to
  451. /// the remote endpoint.
  452. ///
  453. /// In terms of the TCP state machine, the socket must be in the `CLOSED`, `TIME-WAIT`,
  454. /// or `LISTEN` state.
  455. #[inline]
  456. pub fn is_active(&self) -> bool {
  457. match self.state {
  458. State::Closed => false,
  459. State::TimeWait => false,
  460. State::Listen => false,
  461. _ => true
  462. }
  463. }
  464. /// Return whether the transmit half of the full-duplex connection is open.
  465. ///
  466. /// This function returns true if it's possible to send data and have it arrive
  467. /// to the remote endpoint. However, it does not make any guarantees about the state
  468. /// of the transmit buffer, and even if it returns true, [send](#method.send) may
  469. /// not be able to enqueue any octets.
  470. ///
  471. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
  472. /// `CLOSE-WAIT` state.
  473. #[inline]
  474. pub fn may_send(&self) -> bool {
  475. match self.state {
  476. State::Established => true,
  477. // In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
  478. // but we still can transmit indefinitely.
  479. State::CloseWait => true,
  480. _ => false
  481. }
  482. }
  483. /// Return whether the receive half of the full-duplex connection is open.
  484. ///
  485. /// This function returns true if it's possible to receive data from the remote endpoint.
  486. /// It will return true while there is data in the receive buffer, and if there isn't,
  487. /// as long as the remote endpoint has not closed the connection.
  488. ///
  489. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
  490. /// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
  491. #[inline]
  492. pub fn may_recv(&self) -> bool {
  493. match self.state {
  494. State::Established => true,
  495. // In FIN-WAIT-1/2, we have closed our transmit half of the connection but
  496. // we still can receive indefinitely.
  497. State::FinWait1 | State::FinWait2 => true,
  498. // If we have something in the receive buffer, we can receive that.
  499. _ if self.rx_buffer.len() > 0 => true,
  500. _ => false
  501. }
  502. }
  503. /// Check whether the transmit half of the full-duplex connection is open
  504. /// (see [may_send](#method.may_send), and the transmit buffer is not full.
  505. #[inline]
  506. pub fn can_send(&self) -> bool {
  507. if !self.may_send() { return false }
  508. !self.tx_buffer.is_full()
  509. }
  510. /// Check whether the receive half of the full-duplex connection buffer is open
  511. /// (see [may_recv](#method.may_recv), and the receive buffer is not empty.
  512. #[inline]
  513. pub fn can_recv(&self) -> bool {
  514. if !self.may_recv() { return false }
  515. !self.rx_buffer.is_empty()
  516. }
  517. /// Enqueue a sequence of octets to be sent, and return a pointer to it.
  518. ///
  519. /// This function may return a slice smaller than the requested size in case
  520. /// there is not enough contiguous free space in the transmit buffer, down to
  521. /// an empty slice.
  522. ///
  523. /// This function returns `Err(Error::Illegal) if the transmit half of
  524. /// the connection is not open; see [may_send](#method.may_send).
  525. pub fn send(&mut self, size: usize) -> Result<&mut [u8]> {
  526. if !self.may_send() { return Err(Error::Illegal) }
  527. // The connection might have been idle for a long time, and so remote_last_ts
  528. // would be far in the past. Unless we clear it here, we'll abort the connection
  529. // down over in dispatch() by erroneously detecting it as timed out.
  530. if self.tx_buffer.is_empty() { self.remote_last_ts = None }
  531. let _old_length = self.tx_buffer.len();
  532. let buffer = self.tx_buffer.enqueue_many(size);
  533. if buffer.len() > 0 {
  534. #[cfg(any(test, feature = "verbose"))]
  535. net_trace!("[{}]{}:{}: tx buffer: enqueueing {} octets (now {})",
  536. self.debug_id, self.local_endpoint, self.remote_endpoint,
  537. buffer.len(), _old_length + buffer.len());
  538. }
  539. Ok(buffer)
  540. }
  541. /// Enqueue a sequence of octets to be sent, and fill it from a slice.
  542. ///
  543. /// This function returns the amount of bytes actually enqueued, which is limited
  544. /// by the amount of free space in the transmit buffer; down to zero.
  545. ///
  546. /// See also [send](#method.send).
  547. pub fn send_slice(&mut self, data: &[u8]) -> Result<usize> {
  548. if !self.may_send() { return Err(Error::Illegal) }
  549. // See above.
  550. if self.tx_buffer.is_empty() { self.remote_last_ts = None }
  551. let _old_length = self.tx_buffer.len();
  552. let enqueued = self.tx_buffer.enqueue_slice(data);
  553. if enqueued != 0 {
  554. #[cfg(any(test, feature = "verbose"))]
  555. net_trace!("[{}]{}:{}: tx buffer: enqueueing {} octets (now {})",
  556. self.debug_id, self.local_endpoint, self.remote_endpoint,
  557. enqueued, _old_length + enqueued);
  558. }
  559. Ok(enqueued)
  560. }
  561. /// Dequeue a sequence of received octets, and return a pointer to it.
  562. ///
  563. /// This function may return a slice smaller than the requested size in case
  564. /// there are not enough octets queued in the receive buffer, down to
  565. /// an empty slice.
  566. ///
  567. /// This function returns `Err(Error::Illegal) if the receive half of
  568. /// the connection is not open; see [may_recv](#method.may_recv).
  569. pub fn recv(&mut self, size: usize) -> Result<&[u8]> {
  570. // We may have received some data inside the initial SYN, but until the connection
  571. // is fully open we must not dequeue any data, as it may be overwritten by e.g.
  572. // another (stale) SYN.
  573. if !self.may_recv() { return Err(Error::Illegal) }
  574. let _old_length = self.rx_buffer.len();
  575. let buffer = self.rx_buffer.dequeue_many(size);
  576. self.remote_seq_no += buffer.len();
  577. if buffer.len() > 0 {
  578. #[cfg(any(test, feature = "verbose"))]
  579. net_trace!("[{}]{}:{}: rx buffer: dequeueing {} octets (now {})",
  580. self.debug_id, self.local_endpoint, self.remote_endpoint,
  581. buffer.len(), _old_length - buffer.len());
  582. }
  583. Ok(buffer)
  584. }
  585. /// Dequeue a sequence of received octets, and fill a slice from it.
  586. ///
  587. /// This function returns the amount of bytes actually dequeued, which is limited
  588. /// by the amount of free space in the transmit buffer; down to zero.
  589. ///
  590. /// See also [recv](#method.recv).
  591. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  592. // See recv() above.
  593. if !self.may_recv() { return Err(Error::Illegal) }
  594. let _old_length = self.rx_buffer.len();
  595. let dequeued = self.rx_buffer.dequeue_slice(data);
  596. self.remote_seq_no += dequeued;
  597. if dequeued > 0 {
  598. #[cfg(any(test, feature = "verbose"))]
  599. net_trace!("[{}]{}:{}: rx buffer: dequeueing {} octets (now {})",
  600. self.debug_id, self.local_endpoint, self.remote_endpoint,
  601. dequeued, _old_length - dequeued);
  602. }
  603. Ok(dequeued)
  604. }
  605. /// Peek at a sequence of received octets without removing them from
  606. /// the receive buffer, and return a pointer to it.
  607. ///
  608. /// This function otherwise behaves identically to [recv](#method.recv).
  609. pub fn peek(&mut self, size: usize) -> Result<&[u8]> {
  610. // See recv() above.
  611. if !self.may_recv() { return Err(Error::Illegal) }
  612. let buffer = self.rx_buffer.get_allocated(0, size);
  613. if buffer.len() > 0 {
  614. #[cfg(any(test, feature = "verbose"))]
  615. net_trace!("[{}]{}:{}: rx buffer: peeking at {} octets",
  616. self.debug_id, self.local_endpoint, self.remote_endpoint,
  617. buffer.len());
  618. }
  619. Ok(buffer)
  620. }
  621. /// Peek at a sequence of received octets without removing them from
  622. /// the receive buffer, and fill a slice from it.
  623. ///
  624. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  625. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  626. let buffer = self.peek(data.len())?;
  627. let data = &mut data[..buffer.len()];
  628. data.copy_from_slice(buffer);
  629. Ok(buffer.len())
  630. }
  631. /// Return the amount of octets queued in the transmit buffer.
  632. ///
  633. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  634. pub fn send_queue(&self) -> usize {
  635. self.tx_buffer.len()
  636. }
  637. /// Return the amount of octets queued in the receive buffer.
  638. ///
  639. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  640. pub fn recv_queue(&self) -> usize {
  641. self.rx_buffer.len()
  642. }
  643. fn set_state(&mut self, state: State) {
  644. if self.state != state {
  645. if self.remote_endpoint.addr.is_unspecified() {
  646. net_trace!("[{}]{}: state={}=>{}",
  647. self.debug_id, self.local_endpoint,
  648. self.state, state);
  649. } else {
  650. net_trace!("[{}]{}:{}: state={}=>{}",
  651. self.debug_id, self.local_endpoint, self.remote_endpoint,
  652. self.state, state);
  653. }
  654. }
  655. self.state = state
  656. }
  657. pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  658. let reply_repr = TcpRepr {
  659. src_port: repr.dst_port,
  660. dst_port: repr.src_port,
  661. control: TcpControl::None,
  662. seq_number: TcpSeqNumber(0),
  663. ack_number: None,
  664. window_len: 0,
  665. max_seg_size: None,
  666. payload: &[]
  667. };
  668. let ip_reply_repr = IpRepr::Unspecified {
  669. src_addr: ip_repr.dst_addr(),
  670. dst_addr: ip_repr.src_addr(),
  671. protocol: IpProtocol::Tcp,
  672. payload_len: reply_repr.buffer_len()
  673. };
  674. (ip_reply_repr, reply_repr)
  675. }
  676. pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  677. debug_assert!(repr.control != TcpControl::Rst);
  678. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  679. // See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
  680. // of why we sometimes send an RST and sometimes an RST|ACK
  681. reply_repr.control = TcpControl::Rst;
  682. reply_repr.seq_number = repr.ack_number.unwrap_or_default();
  683. if repr.control == TcpControl::Syn {
  684. reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
  685. }
  686. (ip_reply_repr, reply_repr)
  687. }
  688. fn ack_reply(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  689. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  690. // From RFC 793:
  691. // [...] an empty acknowledgment segment containing the current send-sequence number
  692. // and an acknowledgment indicating the next sequence number expected
  693. // to be received.
  694. reply_repr.seq_number = self.remote_last_seq;
  695. reply_repr.ack_number = self.remote_last_ack;
  696. reply_repr.window_len = self.rx_buffer.window() as u16;
  697. (ip_reply_repr, reply_repr)
  698. }
  699. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
  700. if self.state == State::Closed { return false }
  701. // If we're still listening for SYNs and the packet has an ACK, it cannot
  702. // be destined to this socket, but another one may well listen on the same
  703. // local endpoint.
  704. if self.state == State::Listen && repr.ack_number.is_some() { return false }
  705. // Reject packets with a wrong destination.
  706. if self.local_endpoint.port != repr.dst_port { return false }
  707. if !self.local_endpoint.addr.is_unspecified() &&
  708. self.local_endpoint.addr != ip_repr.dst_addr() { return false }
  709. // Reject packets from a source to which we aren't connected.
  710. if self.remote_endpoint.port != 0 &&
  711. self.remote_endpoint.port != repr.src_port { return false }
  712. if !self.remote_endpoint.addr.is_unspecified() &&
  713. self.remote_endpoint.addr != ip_repr.src_addr() { return false }
  714. true
  715. }
  716. pub(crate) fn process(&mut self, timestamp: u64, ip_repr: &IpRepr, repr: &TcpRepr) ->
  717. Result<Option<(IpRepr, TcpRepr<'static>)>> {
  718. debug_assert!(self.accepts(ip_repr, repr));
  719. // Consider how much the sequence number space differs from the transmit buffer space.
  720. let (sent_syn, sent_fin) = match self.state {
  721. // In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
  722. State::SynSent | State::SynReceived => (true, false),
  723. // In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
  724. State::FinWait1 | State::LastAck | State::Closing => (false, true),
  725. // In all other states we've already got acknowledgemetns for
  726. // all of the control flags we sent.
  727. _ => (false, false)
  728. };
  729. let control_len = (sent_syn as usize) + (sent_fin as usize);
  730. // Reject unacceptable acknowledgements.
  731. match (self.state, repr) {
  732. // An RST received in response to initial SYN is acceptable if it acknowledges
  733. // the initial SYN.
  734. (State::SynSent, &TcpRepr {
  735. control: TcpControl::Rst, ack_number: None, ..
  736. }) => {
  737. net_debug!("[{}]{}:{}: unacceptable RST (expecting RST|ACK) \
  738. in response to initial SYN",
  739. self.debug_id, self.local_endpoint, self.remote_endpoint);
  740. return Err(Error::Dropped)
  741. }
  742. (State::SynSent, &TcpRepr {
  743. control: TcpControl::Rst, ack_number: Some(ack_number), ..
  744. }) => {
  745. if ack_number != self.local_seq_no + 1 {
  746. net_debug!("[{}]{}:{}: unacceptable RST|ACK in response to initial SYN",
  747. self.debug_id, self.local_endpoint, self.remote_endpoint);
  748. return Err(Error::Dropped)
  749. }
  750. }
  751. // Any other RST need only have a valid sequence number.
  752. (_, &TcpRepr { control: TcpControl::Rst, .. }) => (),
  753. // The initial SYN cannot contain an acknowledgement.
  754. (State::Listen, &TcpRepr { ack_number: None, .. }) => (),
  755. // This case is handled above.
  756. (State::Listen, &TcpRepr { ack_number: Some(_), .. }) => unreachable!(),
  757. // Every packet after the initial SYN must be an acknowledgement.
  758. (_, &TcpRepr { ack_number: None, .. }) => {
  759. net_debug!("[{}]{}:{}: expecting an ACK",
  760. self.debug_id, self.local_endpoint, self.remote_endpoint);
  761. return Err(Error::Dropped)
  762. }
  763. // Every acknowledgement must be for transmitted but unacknowledged data.
  764. (_, &TcpRepr { ack_number: Some(ack_number), .. }) => {
  765. let unacknowledged = self.tx_buffer.len() + control_len;
  766. if ack_number < self.local_seq_no {
  767. net_debug!("[{}]{}:{}: duplicate ACK ({} not in {}...{})",
  768. self.debug_id, self.local_endpoint, self.remote_endpoint,
  769. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  770. // FIXME: implement fast retransmit
  771. return Err(Error::Dropped)
  772. }
  773. if ack_number > self.local_seq_no + unacknowledged {
  774. net_debug!("[{}]{}:{}: unacceptable ACK ({} not in {}...{})",
  775. self.debug_id, self.local_endpoint, self.remote_endpoint,
  776. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  777. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  778. }
  779. }
  780. }
  781. let payload_offset;
  782. match self.state {
  783. // In LISTEN and SYN-SENT states, we have not yet synchronized with the remote end.
  784. State::Listen | State::SynSent =>
  785. payload_offset = 0,
  786. // In all other states, segments must occupy a valid portion of the receive window.
  787. _ => {
  788. let mut segment_in_window = true;
  789. let window_start = self.remote_seq_no + self.rx_buffer.len();
  790. let window_end = self.remote_seq_no + self.rx_buffer.capacity();
  791. let segment_start = repr.seq_number;
  792. let segment_end = repr.seq_number + repr.segment_len();
  793. if window_start == window_end && segment_start != segment_end {
  794. net_debug!("[{}]{}:{}: non-zero-length segment with zero receive window, \
  795. will only send an ACK",
  796. self.debug_id, self.local_endpoint, self.remote_endpoint);
  797. segment_in_window = false;
  798. }
  799. if !((window_start <= segment_start && segment_start <= window_end) &&
  800. (window_start <= segment_end && segment_end <= window_end)) {
  801. net_debug!("[{}]{}:{}: segment not in receive window \
  802. ({}..{} not intersecting {}..{}), will send challenge ACK",
  803. self.debug_id, self.local_endpoint, self.remote_endpoint,
  804. segment_start, segment_end, window_start, window_end);
  805. segment_in_window = false;
  806. }
  807. if segment_in_window {
  808. // We've checked that segment_start >= window_start above.
  809. payload_offset = (segment_start - window_start) as usize;
  810. } else {
  811. // If we're in the TIME-WAIT state, restart the TIME-WAIT timeout, since
  812. // the remote end may not have realized we've closed the connection.
  813. if self.state == State::TimeWait {
  814. self.timer.set_for_close(timestamp);
  815. }
  816. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  817. }
  818. }
  819. }
  820. // Compute the amount of acknowledged octets, removing the SYN and FIN bits
  821. // from the sequence space.
  822. let mut ack_len = 0;
  823. let mut ack_of_fin = false;
  824. if repr.control != TcpControl::Rst {
  825. if let Some(ack_number) = repr.ack_number {
  826. ack_len = ack_number - self.local_seq_no;
  827. // There could have been no data sent before the SYN, so we always remove it
  828. // from the sequence space.
  829. if sent_syn {
  830. ack_len -= 1
  831. }
  832. // We could've sent data before the FIN, so only remove FIN from the sequence
  833. // space if all of that data is acknowledged.
  834. if sent_fin && self.tx_buffer.len() + 1 == ack_len {
  835. ack_len -= 1;
  836. net_trace!("[{}]{}:{}: received ACK of FIN",
  837. self.debug_id, self.local_endpoint, self.remote_endpoint);
  838. ack_of_fin = true;
  839. }
  840. }
  841. }
  842. // Validate and update the state.
  843. match (self.state, repr.control.quash_psh()) {
  844. // RSTs are not accepted in the LISTEN state.
  845. (State::Listen, TcpControl::Rst) =>
  846. return Err(Error::Dropped),
  847. // RSTs in SYN-RECEIVED flip the socket back to the LISTEN state.
  848. (State::SynReceived, TcpControl::Rst) => {
  849. net_trace!("[{}]{}:{}: received RST",
  850. self.debug_id, self.local_endpoint, self.remote_endpoint);
  851. self.local_endpoint.addr = self.listen_address;
  852. self.remote_endpoint = IpEndpoint::default();
  853. self.set_state(State::Listen);
  854. return Ok(None)
  855. }
  856. // RSTs in any other state close the socket.
  857. (_, TcpControl::Rst) => {
  858. net_trace!("[{}]{}:{}: received RST",
  859. self.debug_id, self.local_endpoint, self.remote_endpoint);
  860. self.set_state(State::Closed);
  861. self.local_endpoint = IpEndpoint::default();
  862. self.remote_endpoint = IpEndpoint::default();
  863. return Ok(None)
  864. }
  865. // SYN packets in the LISTEN state change it to SYN-RECEIVED.
  866. (State::Listen, TcpControl::Syn) => {
  867. net_trace!("[{}]{}: received SYN",
  868. self.debug_id, self.local_endpoint);
  869. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  870. self.remote_endpoint = IpEndpoint::new(ip_repr.src_addr(), repr.src_port);
  871. // FIXME: use something more secure here
  872. self.local_seq_no = TcpSeqNumber(-repr.seq_number.0);
  873. self.remote_seq_no = repr.seq_number + 1;
  874. self.remote_last_seq = self.local_seq_no;
  875. if let Some(max_seg_size) = repr.max_seg_size {
  876. self.remote_mss = max_seg_size as usize
  877. }
  878. self.set_state(State::SynReceived);
  879. self.timer.set_for_idle(timestamp, self.keep_alive);
  880. }
  881. // ACK packets in the SYN-RECEIVED state change it to ESTABLISHED.
  882. (State::SynReceived, TcpControl::None) => {
  883. self.set_state(State::Established);
  884. self.timer.set_for_idle(timestamp, self.keep_alive);
  885. }
  886. // FIN packets in the SYN-RECEIVED state change it to CLOSE-WAIT.
  887. // It's not obvious from RFC 793 that this is permitted, but
  888. // 7th and 8th steps in the "SEGMENT ARRIVES" event describe this behavior.
  889. (State::SynReceived, TcpControl::Fin) => {
  890. self.remote_seq_no += 1;
  891. self.set_state(State::CloseWait);
  892. self.timer.set_for_idle(timestamp, self.keep_alive);
  893. }
  894. // SYN|ACK packets in the SYN-SENT state change it to ESTABLISHED.
  895. (State::SynSent, TcpControl::Syn) => {
  896. net_trace!("[{}]{}:{}: received SYN|ACK",
  897. self.debug_id, self.local_endpoint, self.remote_endpoint);
  898. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  899. self.remote_seq_no = repr.seq_number + 1;
  900. self.remote_last_seq = self.local_seq_no + 1;
  901. self.remote_last_ack = Some(repr.seq_number);
  902. if let Some(max_seg_size) = repr.max_seg_size {
  903. self.remote_mss = max_seg_size as usize;
  904. }
  905. self.set_state(State::Established);
  906. self.timer.set_for_idle(timestamp, self.keep_alive);
  907. }
  908. // ACK packets in ESTABLISHED state reset the retransmit timer.
  909. (State::Established, TcpControl::None) => {
  910. self.timer.set_for_idle(timestamp, self.keep_alive);
  911. },
  912. // FIN packets in ESTABLISHED state indicate the remote side has closed.
  913. (State::Established, TcpControl::Fin) => {
  914. self.remote_seq_no += 1;
  915. self.set_state(State::CloseWait);
  916. self.timer.set_for_idle(timestamp, self.keep_alive);
  917. }
  918. // ACK packets in FIN-WAIT-1 state change it to FIN-WAIT-2, if we've already
  919. // sent everything in the transmit buffer. If not, they reset the retransmit timer.
  920. (State::FinWait1, TcpControl::None) => {
  921. if ack_of_fin {
  922. self.set_state(State::FinWait2);
  923. }
  924. self.timer.set_for_idle(timestamp, self.keep_alive);
  925. }
  926. // FIN packets in FIN-WAIT-1 state change it to CLOSING, or to TIME-WAIT
  927. // if they also acknowledge our FIN.
  928. (State::FinWait1, TcpControl::Fin) => {
  929. self.remote_seq_no += 1;
  930. if ack_of_fin {
  931. self.set_state(State::TimeWait);
  932. self.timer.set_for_close(timestamp);
  933. } else {
  934. self.set_state(State::Closing);
  935. self.timer.set_for_idle(timestamp, self.keep_alive);
  936. }
  937. }
  938. // FIN packets in FIN-WAIT-2 state change it to TIME-WAIT.
  939. (State::FinWait2, TcpControl::Fin) => {
  940. self.remote_seq_no += 1;
  941. self.set_state(State::TimeWait);
  942. self.timer.set_for_close(timestamp);
  943. }
  944. // ACK packets in CLOSING state change it to TIME-WAIT.
  945. (State::Closing, TcpControl::None) => {
  946. if ack_of_fin {
  947. self.set_state(State::TimeWait);
  948. self.timer.set_for_close(timestamp);
  949. } else {
  950. self.timer.set_for_idle(timestamp, self.keep_alive);
  951. }
  952. }
  953. // ACK packets in CLOSE-WAIT state reset the retransmit timer.
  954. (State::CloseWait, TcpControl::None) => {
  955. self.timer.set_for_idle(timestamp, self.keep_alive);
  956. }
  957. // ACK packets in LAST-ACK state change it to CLOSED.
  958. (State::LastAck, TcpControl::None) => {
  959. // Clear the remote endpoint, or we'll send an RST there.
  960. self.set_state(State::Closed);
  961. self.local_endpoint = IpEndpoint::default();
  962. self.remote_endpoint = IpEndpoint::default();
  963. }
  964. _ => {
  965. net_debug!("[{}]{}:{}: unexpected packet {}",
  966. self.debug_id, self.local_endpoint, self.remote_endpoint, repr);
  967. return Err(Error::Dropped)
  968. }
  969. }
  970. // Update remote state.
  971. self.remote_last_ts = Some(timestamp);
  972. self.remote_win_len = repr.window_len as usize;
  973. if ack_len > 0 {
  974. // Dequeue acknowledged octets.
  975. debug_assert!(self.tx_buffer.len() >= ack_len);
  976. net_trace!("[{}]{}:{}: tx buffer: dequeueing {} octets (now {})",
  977. self.debug_id, self.local_endpoint, self.remote_endpoint,
  978. ack_len, self.tx_buffer.len() - ack_len);
  979. self.tx_buffer.dequeue_allocated(ack_len);
  980. }
  981. if let Some(ack_number) = repr.ack_number {
  982. // We've processed everything in the incoming segment, so advance the local
  983. // sequence number past it.
  984. self.local_seq_no = ack_number;
  985. }
  986. let payload_len = repr.payload.len();
  987. if payload_len == 0 { return Ok(None) }
  988. let assembler_was_empty = self.assembler.is_empty();
  989. // Try adding payload octets to the assembler.
  990. match self.assembler.add(payload_offset, payload_len) {
  991. Ok(()) => {
  992. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  993. // Place payload octets into the buffer.
  994. net_trace!("[{}]{}:{}: rx buffer: receiving {} octets at offset {}",
  995. self.debug_id, self.local_endpoint, self.remote_endpoint,
  996. payload_len, payload_offset);
  997. self.rx_buffer.write_unallocated(payload_offset, repr.payload);
  998. }
  999. Err(()) => {
  1000. net_debug!("[{}]{}:{}: assembler: too many holes to add {} octets at offset {}",
  1001. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1002. payload_len, payload_offset);
  1003. return Err(Error::Dropped)
  1004. }
  1005. }
  1006. if let Some(contig_len) = self.assembler.remove_front() {
  1007. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1008. // Enqueue the contiguous data octets in front of the buffer.
  1009. net_trace!("[{}]{}:{}: rx buffer: enqueueing {} octets (now {})",
  1010. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1011. contig_len, self.rx_buffer.len() + contig_len);
  1012. self.rx_buffer.enqueue_unallocated(contig_len);
  1013. }
  1014. if !self.assembler.is_empty() {
  1015. // Print the ranges recorded in the assembler.
  1016. net_trace!("[{}]{}:{}: assembler: {}",
  1017. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1018. self.assembler);
  1019. }
  1020. // Per RFC 5681, we should send an immediate ACK when either:
  1021. // 1) an out-of-order segment is received, or
  1022. // 2) a segment arrives that fills in all or part of a gap in sequence space.
  1023. if !self.assembler.is_empty() || !assembler_was_empty {
  1024. // Note that we change the transmitter state here.
  1025. // This is fine because smoltcp assumes that it can always transmit zero or one
  1026. // packets for every packet it receives.
  1027. self.remote_last_ack = Some(self.remote_seq_no + self.rx_buffer.len());
  1028. Ok(Some(self.ack_reply(ip_repr, &repr)))
  1029. } else {
  1030. Ok(None)
  1031. }
  1032. }
  1033. fn timed_out(&self, timestamp: u64) -> bool {
  1034. match (self.remote_last_ts, self.timeout) {
  1035. (Some(remote_last_ts), Some(timeout)) =>
  1036. timestamp >= remote_last_ts + timeout,
  1037. (_, _) =>
  1038. false
  1039. }
  1040. }
  1041. fn seq_to_transmit(&self) -> bool {
  1042. let control;
  1043. match self.state {
  1044. State::SynSent | State::SynReceived =>
  1045. control = TcpControl::Syn,
  1046. State::FinWait1 | State::LastAck =>
  1047. control = TcpControl::Fin,
  1048. _ => control = TcpControl::None
  1049. }
  1050. if self.remote_win_len > 0 {
  1051. self.remote_last_seq < self.local_seq_no + self.tx_buffer.len() + control.len()
  1052. } else {
  1053. false
  1054. }
  1055. }
  1056. fn ack_to_transmit(&self) -> bool {
  1057. if let Some(remote_last_ack) = self.remote_last_ack {
  1058. remote_last_ack < self.remote_seq_no + self.rx_buffer.len()
  1059. } else {
  1060. false
  1061. }
  1062. }
  1063. fn window_to_update(&self) -> bool {
  1064. self.rx_buffer.window() as u16 > self.remote_last_win
  1065. }
  1066. pub(crate) fn dispatch<F>(&mut self, timestamp: u64, caps: &DeviceCapabilities,
  1067. emit: F) -> Result<()>
  1068. where F: FnOnce((IpRepr, TcpRepr)) -> Result<()> {
  1069. if !self.remote_endpoint.is_specified() { return Err(Error::Exhausted) }
  1070. if self.remote_last_ts.is_none() {
  1071. // We get here in exactly two cases:
  1072. // 1) This socket just transitioned into SYN-SENT.
  1073. // 2) This socket had an empty transmit buffer and some data was added there.
  1074. // Both are similar in that the socket has been quiet for an indefinite
  1075. // period of time, it isn't anymore, and the local endpoint is talking.
  1076. // So, we start counting the timeout not from the last received packet
  1077. // but from the first transmitted one.
  1078. self.remote_last_ts = Some(timestamp);
  1079. }
  1080. // Check if any state needs to be changed because of a timer.
  1081. if self.timed_out(timestamp) {
  1082. // If a timeout expires, we should abort the connection.
  1083. net_debug!("[{}]{}:{}: timeout exceeded",
  1084. self.debug_id, self.local_endpoint, self.remote_endpoint);
  1085. self.set_state(State::Closed);
  1086. } else if !self.seq_to_transmit() {
  1087. if let Some(retransmit_delta) = self.timer.should_retransmit(timestamp) {
  1088. // If a retransmit timer expired, we should resend data starting at the last ACK.
  1089. net_debug!("[{}]{}:{}: retransmitting at t+{}ms",
  1090. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1091. retransmit_delta);
  1092. self.remote_last_seq = self.local_seq_no;
  1093. }
  1094. }
  1095. // Decide whether we're sending a packet.
  1096. if self.seq_to_transmit() {
  1097. // If we have data to transmit and it fits into partner's window, do it.
  1098. } else if self.ack_to_transmit() {
  1099. // If we have data to acknowledge, do it.
  1100. } else if self.window_to_update() {
  1101. // If we have window length increase to advertise, do it.
  1102. } else if self.state == State::Closed {
  1103. // If we need to abort the connection, do it.
  1104. } else if self.timer.should_retransmit(timestamp).is_some() {
  1105. // If we have packets to retransmit, do it.
  1106. } else if self.timer.should_keep_alive(timestamp) {
  1107. // If we need to transmit a keep-alive packet, do it.
  1108. } else if self.timer.should_close(timestamp) {
  1109. // If we have spent enough time in the TIME-WAIT state, close the socket.
  1110. } else {
  1111. return Err(Error::Exhausted)
  1112. }
  1113. // Construct the lowered IP representation.
  1114. // We might need this to calculate the MSS, so do it early.
  1115. let mut ip_repr = IpRepr::Unspecified {
  1116. src_addr: self.local_endpoint.addr,
  1117. dst_addr: self.remote_endpoint.addr,
  1118. protocol: IpProtocol::Tcp,
  1119. payload_len: 0
  1120. }.lower(&[])?;
  1121. // Construct the basic TCP representation, an empty ACK packet.
  1122. // We'll adjust this to be more specific as needed.
  1123. let mut repr = TcpRepr {
  1124. src_port: self.local_endpoint.port,
  1125. dst_port: self.remote_endpoint.port,
  1126. control: TcpControl::None,
  1127. seq_number: self.remote_last_seq,
  1128. ack_number: Some(self.remote_seq_no + self.rx_buffer.len()),
  1129. window_len: self.rx_buffer.window() as u16,
  1130. max_seg_size: None,
  1131. payload: &[]
  1132. };
  1133. match self.state {
  1134. // We transmit an RST in the CLOSED state. If we ended up in the CLOSED state
  1135. // with a specified endpoint, it means that the socket was aborted.
  1136. State::Closed => {
  1137. repr.control = TcpControl::Rst;
  1138. }
  1139. // We never transmit anything in the LISTEN state.
  1140. State::Listen => return Err(Error::Exhausted),
  1141. // We transmit a SYN in the SYN-SENT state.
  1142. // We transmit a SYN|ACK in the SYN-RECEIVED state.
  1143. State::SynSent | State::SynReceived => {
  1144. repr.control = TcpControl::Syn;
  1145. if self.state == State::SynSent {
  1146. repr.ack_number = None;
  1147. }
  1148. }
  1149. // We transmit data in all states where we may have data in the buffer,
  1150. // or the transmit half of the connection is still open:
  1151. // the ESTABLISHED, FIN-WAIT-1, CLOSE-WAIT and LAST-ACK states.
  1152. State::Established | State::FinWait1 | State::CloseWait | State::LastAck => {
  1153. // Extract as much data as the remote side can receive in this packet
  1154. // from the transmit buffer.
  1155. let offset = self.remote_last_seq - self.local_seq_no;
  1156. let size = cmp::min(self.remote_win_len, self.remote_mss);
  1157. repr.payload = self.tx_buffer.get_allocated(offset, size);
  1158. // If we've sent everything we had in the buffer, follow it with the PSH or FIN
  1159. // flags, depending on whether the transmit half of the connection is open.
  1160. if offset + repr.payload.len() == self.tx_buffer.len() {
  1161. match self.state {
  1162. State::FinWait1 | State::LastAck =>
  1163. repr.control = TcpControl::Fin,
  1164. State::Established | State::CloseWait if repr.payload.len() > 0 =>
  1165. repr.control = TcpControl::Psh,
  1166. _ => ()
  1167. }
  1168. }
  1169. }
  1170. // We do not transmit anything in the FIN-WAIT-2 state.
  1171. State::FinWait2 => return Err(Error::Exhausted),
  1172. // We do not transmit data or control flags in the CLOSING state, but we may
  1173. // retransmit an ACK.
  1174. State::Closing => (),
  1175. // Handling of the TIME-WAIT state is the same as for the CLOSING state, but also
  1176. // we wait for the timer to expire.
  1177. State::TimeWait => {
  1178. if self.timer.should_close(timestamp) {
  1179. net_trace!("[{}]{}:{}: TIME-WAIT timeout",
  1180. self.debug_id, self.local_endpoint, self.remote_endpoint);
  1181. self.reset();
  1182. return Err(Error::Exhausted)
  1183. }
  1184. }
  1185. }
  1186. // There might be more than one reason to send a packet. E.g. the keep-alive timer
  1187. // has expired, and we also have data in transmit buffer. Since any packet that occupies
  1188. // sequence space will elicit an ACK, we only need to send an explicit packet if we
  1189. // couldn't fill the sequence space with anything.
  1190. let is_keep_alive;
  1191. if self.timer.should_keep_alive(timestamp) && repr.is_empty() {
  1192. repr.seq_number = repr.seq_number - 1;
  1193. repr.payload = b"\x00"; // RFC 1122 says we should do this
  1194. is_keep_alive = true;
  1195. } else {
  1196. is_keep_alive = false;
  1197. }
  1198. // Trace a summary of what will be sent.
  1199. if is_keep_alive {
  1200. net_trace!("[{}]{}:{}: sending a keep-alive",
  1201. self.debug_id, self.local_endpoint, self.remote_endpoint);
  1202. } else if repr.payload.len() > 0 {
  1203. net_trace!("[{}]{}:{}: tx buffer: sending {} octets at offset {}",
  1204. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1205. repr.payload.len(), self.remote_last_seq - self.local_seq_no);
  1206. }
  1207. if repr.control != TcpControl::None || repr.payload.len() == 0 {
  1208. let flags =
  1209. match (repr.control, repr.ack_number) {
  1210. (TcpControl::Syn, None) => "SYN",
  1211. (TcpControl::Syn, Some(_)) => "SYN|ACK",
  1212. (TcpControl::Fin, Some(_)) => "FIN|ACK",
  1213. (TcpControl::Rst, Some(_)) => "RST|ACK",
  1214. (TcpControl::Psh, Some(_)) => "PSH|ACK",
  1215. (TcpControl::None, Some(_)) => "ACK",
  1216. _ => "<unreachable>"
  1217. };
  1218. net_trace!("[{}]{}:{}: sending {}",
  1219. self.debug_id, self.local_endpoint, self.remote_endpoint,
  1220. flags);
  1221. }
  1222. if repr.control == TcpControl::Syn {
  1223. // Fill the MSS option. See RFC 6691 for an explanation of this calculation.
  1224. let mut max_segment_size = caps.max_transmission_unit;
  1225. max_segment_size -= ip_repr.buffer_len();
  1226. max_segment_size -= repr.header_len();
  1227. repr.max_seg_size = Some(max_segment_size as u16);
  1228. }
  1229. // Actually send the packet. If this succeeds, it means the packet is in
  1230. // the device buffer, and its transmission is imminent. If not, we might have
  1231. // a number of problems, e.g. we need neighbor discovery.
  1232. //
  1233. // Bailing out if the packet isn't placed in the device buffer allows us
  1234. // to not waste time waiting for the retransmit timer on packets that we know
  1235. // for sure will not be successfully transmitted.
  1236. ip_repr.set_payload_len(repr.buffer_len());
  1237. emit((ip_repr, repr))?;
  1238. // We've sent something, whether useful data or a keep-alive packet, so rewind
  1239. // the keep-alive timer.
  1240. self.timer.rewind_keep_alive(timestamp, self.keep_alive);
  1241. // Leave the rest of the state intact if sending a keep-alive packet, since those
  1242. // carry a fake segment.
  1243. if is_keep_alive { return Ok(()) }
  1244. // We've sent a packet successfully, so we can update the internal state now.
  1245. self.remote_last_seq = repr.seq_number + repr.segment_len();
  1246. self.remote_last_ack = repr.ack_number;
  1247. self.remote_last_win = repr.window_len;
  1248. if !self.seq_to_transmit() && repr.segment_len() > 0 {
  1249. // If we've transmitted all data we could (and there was something at all,
  1250. // data or flag, to transmit, not just an ACK), wind up the retransmit timer.
  1251. self.timer.set_for_retransmit(timestamp);
  1252. }
  1253. if self.state == State::Closed {
  1254. // When aborting a connection, forget about it after sending a single RST packet.
  1255. self.local_endpoint = IpEndpoint::default();
  1256. self.remote_endpoint = IpEndpoint::default();
  1257. }
  1258. Ok(())
  1259. }
  1260. pub(crate) fn poll_at(&self) -> Option<u64> {
  1261. // The logic here mirrors the beginning of dispatch() closely.
  1262. if !self.remote_endpoint.is_specified() {
  1263. // No one to talk to, nothing to transmit.
  1264. None
  1265. } else if self.remote_last_ts.is_none() {
  1266. // Socket stopped being quiet recently, we need to acquire a timestamp.
  1267. Some(0)
  1268. } else if self.state == State::Closed {
  1269. // Socket was aborted, we have an RST packet to transmit.
  1270. Some(0)
  1271. } else if self.seq_to_transmit() || self.ack_to_transmit() || self.window_to_update() {
  1272. // We have a data or flag packet to transmit.
  1273. Some(0)
  1274. } else {
  1275. let timeout_poll_at;
  1276. match (self.remote_last_ts, self.timeout) {
  1277. // If we're transmitting or retransmitting data, we need to poll at the moment
  1278. // when the timeout would expire.
  1279. (Some(remote_last_ts), Some(timeout)) =>
  1280. timeout_poll_at = Some(remote_last_ts + timeout),
  1281. // Otherwise we have no timeout.
  1282. (_, _) =>
  1283. timeout_poll_at = None
  1284. }
  1285. // We wait for the earliest of our timers to fire.
  1286. [self.timer.poll_at(), timeout_poll_at]
  1287. .iter()
  1288. .filter_map(|x| *x)
  1289. .min()
  1290. }
  1291. }
  1292. }
  1293. impl<'a> fmt::Write for TcpSocket<'a> {
  1294. fn write_str(&mut self, slice: &str) -> fmt::Result {
  1295. let slice = slice.as_bytes();
  1296. if self.send_slice(slice) == Ok(slice.len()) {
  1297. Ok(())
  1298. } else {
  1299. Err(fmt::Error)
  1300. }
  1301. }
  1302. }
  1303. #[cfg(test)]
  1304. mod test {
  1305. use wire::{IpAddress, Ipv4Address};
  1306. use super::*;
  1307. #[test]
  1308. fn test_timer_retransmit() {
  1309. let mut r = Timer::default();
  1310. assert_eq!(r.should_retransmit(1000), None);
  1311. r.set_for_retransmit(1000);
  1312. assert_eq!(r.should_retransmit(1000), None);
  1313. assert_eq!(r.should_retransmit(1050), None);
  1314. assert_eq!(r.should_retransmit(1101), Some(101));
  1315. r.set_for_retransmit(1101);
  1316. assert_eq!(r.should_retransmit(1101), None);
  1317. assert_eq!(r.should_retransmit(1150), None);
  1318. assert_eq!(r.should_retransmit(1200), None);
  1319. assert_eq!(r.should_retransmit(1301), Some(300));
  1320. r.set_for_idle(1301, None);
  1321. assert_eq!(r.should_retransmit(1350), None);
  1322. }
  1323. const LOCAL_IP: IpAddress = IpAddress::Ipv4(Ipv4Address([10, 0, 0, 1]));
  1324. const REMOTE_IP: IpAddress = IpAddress::Ipv4(Ipv4Address([10, 0, 0, 2]));
  1325. const OTHER_IP: IpAddress = IpAddress::Ipv4(Ipv4Address([10, 0, 0, 3]));
  1326. const LOCAL_PORT: u16 = 80;
  1327. const REMOTE_PORT: u16 = 49500;
  1328. const LOCAL_END: IpEndpoint = IpEndpoint { addr: LOCAL_IP, port: LOCAL_PORT };
  1329. const REMOTE_END: IpEndpoint = IpEndpoint { addr: REMOTE_IP, port: REMOTE_PORT };
  1330. const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
  1331. const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10000);
  1332. const SEND_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1333. src_addr: LOCAL_IP, dst_addr: REMOTE_IP,
  1334. protocol: IpProtocol::Tcp, payload_len: 20
  1335. };
  1336. const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
  1337. src_port: REMOTE_PORT, dst_port: LOCAL_PORT,
  1338. control: TcpControl::None,
  1339. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1340. window_len: 256, max_seg_size: None,
  1341. payload: &[]
  1342. };
  1343. const _RECV_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1344. src_addr: REMOTE_IP, dst_addr: LOCAL_IP,
  1345. protocol: IpProtocol::Tcp, payload_len: 20
  1346. };
  1347. const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
  1348. src_port: LOCAL_PORT, dst_port: REMOTE_PORT,
  1349. control: TcpControl::None,
  1350. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1351. window_len: 64, max_seg_size: None,
  1352. payload: &[]
  1353. };
  1354. fn send(socket: &mut TcpSocket, timestamp: u64, repr: &TcpRepr) ->
  1355. Result<Option<TcpRepr<'static>>> {
  1356. let ip_repr = IpRepr::Unspecified {
  1357. src_addr: REMOTE_IP,
  1358. dst_addr: LOCAL_IP,
  1359. protocol: IpProtocol::Tcp,
  1360. payload_len: repr.buffer_len()
  1361. };
  1362. trace!("send: {}", repr);
  1363. assert!(socket.accepts(&ip_repr, repr));
  1364. match socket.process(timestamp, &ip_repr, repr) {
  1365. Ok(Some((_ip_repr, repr))) => {
  1366. trace!("recv: {}", repr);
  1367. Ok(Some(repr))
  1368. }
  1369. Ok(None) => Ok(None),
  1370. Err(err) => Err(err)
  1371. }
  1372. }
  1373. fn recv<F>(socket: &mut TcpSocket, timestamp: u64, mut f: F)
  1374. where F: FnMut(Result<TcpRepr>) {
  1375. let mut caps = DeviceCapabilities::default();
  1376. caps.max_transmission_unit = 1520;
  1377. let result = socket.dispatch(timestamp, &caps, |(ip_repr, tcp_repr)| {
  1378. let ip_repr = ip_repr.lower(&[LOCAL_END.addr.into()]).unwrap();
  1379. assert_eq!(ip_repr.protocol(), IpProtocol::Tcp);
  1380. assert_eq!(ip_repr.src_addr(), LOCAL_IP);
  1381. assert_eq!(ip_repr.dst_addr(), REMOTE_IP);
  1382. assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
  1383. trace!("recv: {}", tcp_repr);
  1384. Ok(f(Ok(tcp_repr)))
  1385. });
  1386. match result {
  1387. Ok(()) => (),
  1388. Err(e) => f(Err(e))
  1389. }
  1390. }
  1391. macro_rules! send {
  1392. ($socket:ident, $repr:expr) =>
  1393. (send!($socket, time 0, $repr));
  1394. ($socket:ident, $repr:expr, $result:expr) =>
  1395. (send!($socket, time 0, $repr, $result));
  1396. ($socket:ident, time $time:expr, $repr:expr) =>
  1397. (send!($socket, time $time, $repr, Ok(None)));
  1398. ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
  1399. (assert_eq!(send(&mut $socket, $time, &$repr), $result));
  1400. }
  1401. macro_rules! recv {
  1402. ($socket:ident, [$( $repr:expr ),*]) => ({
  1403. $( recv!($socket, Ok($repr)); )*
  1404. recv!($socket, Err(Error::Exhausted))
  1405. });
  1406. ($socket:ident, $result:expr) =>
  1407. (recv!($socket, time 0, $result));
  1408. ($socket:ident, time $time:expr, $result:expr) =>
  1409. (recv(&mut $socket, $time, |result| {
  1410. // Most of the time we don't care about the PSH flag.
  1411. let result = result.map(|mut repr| {
  1412. repr.control = repr.control.quash_psh();
  1413. repr
  1414. });
  1415. assert_eq!(result, $result)
  1416. }));
  1417. ($socket:ident, time $time:expr, $result:expr, exact) =>
  1418. (recv(&mut $socket, $time, |repr| assert_eq!(repr, $result)));
  1419. }
  1420. macro_rules! sanity {
  1421. ($socket1:expr, $socket2:expr) => ({
  1422. let (s1, s2) = ($socket1, $socket2);
  1423. assert_eq!(s1.state, s2.state, "state");
  1424. assert_eq!(s1.listen_address, s2.listen_address, "listen_address");
  1425. assert_eq!(s1.local_endpoint, s2.local_endpoint, "local_endpoint");
  1426. assert_eq!(s1.remote_endpoint, s2.remote_endpoint, "remote_endpoint");
  1427. assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
  1428. assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
  1429. assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
  1430. assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
  1431. assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
  1432. assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
  1433. assert_eq!(s1.timer, s2.timer, "timer");
  1434. })
  1435. }
  1436. fn init_logger() {
  1437. extern crate log;
  1438. use std::boxed::Box;
  1439. struct Logger(());
  1440. impl log::Log for Logger {
  1441. fn enabled(&self, _metadata: &log::LogMetadata) -> bool {
  1442. true
  1443. }
  1444. fn log(&self, record: &log::LogRecord) {
  1445. println!("{}", record.args());
  1446. }
  1447. }
  1448. let _ = log::set_logger(|max_level| {
  1449. max_level.set(log::LogLevelFilter::Trace);
  1450. Box::new(Logger(()))
  1451. });
  1452. println!("");
  1453. }
  1454. fn socket() -> TcpSocket<'static> {
  1455. init_logger();
  1456. let rx_buffer = SocketBuffer::new(vec![0; 64]);
  1457. let tx_buffer = SocketBuffer::new(vec![0; 64]);
  1458. match TcpSocket::new(rx_buffer, tx_buffer) {
  1459. Socket::Tcp(socket) => socket,
  1460. _ => unreachable!()
  1461. }
  1462. }
  1463. // =========================================================================================//
  1464. // Tests for the CLOSED state.
  1465. // =========================================================================================//
  1466. #[test]
  1467. fn test_closed_reject() {
  1468. let s = socket();
  1469. assert_eq!(s.state, State::Closed);
  1470. let tcp_repr = TcpRepr {
  1471. control: TcpControl::Syn,
  1472. ..SEND_TEMPL
  1473. };
  1474. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1475. }
  1476. #[test]
  1477. fn test_closed_reject_after_listen() {
  1478. let mut s = socket();
  1479. s.listen(LOCAL_END).unwrap();
  1480. s.close();
  1481. let tcp_repr = TcpRepr {
  1482. control: TcpControl::Syn,
  1483. ..SEND_TEMPL
  1484. };
  1485. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1486. }
  1487. #[test]
  1488. fn test_closed_close() {
  1489. let mut s = socket();
  1490. s.close();
  1491. assert_eq!(s.state, State::Closed);
  1492. }
  1493. // =========================================================================================//
  1494. // Tests for the LISTEN state.
  1495. // =========================================================================================//
  1496. fn socket_listen() -> TcpSocket<'static> {
  1497. let mut s = socket();
  1498. s.state = State::Listen;
  1499. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  1500. s
  1501. }
  1502. #[test]
  1503. fn test_listen_sanity() {
  1504. let mut s = socket();
  1505. s.listen(LOCAL_PORT).unwrap();
  1506. sanity!(s, socket_listen());
  1507. }
  1508. #[test]
  1509. fn test_listen_validation() {
  1510. let mut s = socket();
  1511. assert_eq!(s.listen(0), Err(Error::Unaddressable));
  1512. }
  1513. #[test]
  1514. fn test_listen_twice() {
  1515. let mut s = socket();
  1516. assert_eq!(s.listen(80), Ok(()));
  1517. assert_eq!(s.listen(80), Err(Error::Illegal));
  1518. }
  1519. #[test]
  1520. fn test_listen_syn() {
  1521. let mut s = socket_listen();
  1522. send!(s, TcpRepr {
  1523. control: TcpControl::Syn,
  1524. seq_number: REMOTE_SEQ,
  1525. ack_number: None,
  1526. ..SEND_TEMPL
  1527. });
  1528. sanity!(s, socket_syn_received());
  1529. }
  1530. #[test]
  1531. fn test_listen_syn_reject_ack() {
  1532. let s = socket_listen();
  1533. let tcp_repr = TcpRepr {
  1534. control: TcpControl::Syn,
  1535. seq_number: REMOTE_SEQ,
  1536. ack_number: Some(LOCAL_SEQ),
  1537. ..SEND_TEMPL
  1538. };
  1539. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1540. assert_eq!(s.state, State::Listen);
  1541. }
  1542. #[test]
  1543. fn test_listen_rst() {
  1544. let mut s = socket_listen();
  1545. send!(s, TcpRepr {
  1546. control: TcpControl::Rst,
  1547. seq_number: REMOTE_SEQ,
  1548. ack_number: None,
  1549. ..SEND_TEMPL
  1550. }, Err(Error::Dropped));
  1551. }
  1552. #[test]
  1553. fn test_listen_close() {
  1554. let mut s = socket_listen();
  1555. s.close();
  1556. assert_eq!(s.state, State::Closed);
  1557. }
  1558. // =========================================================================================//
  1559. // Tests for the SYN-RECEIVED state.
  1560. // =========================================================================================//
  1561. fn socket_syn_received() -> TcpSocket<'static> {
  1562. let mut s = socket();
  1563. s.state = State::SynReceived;
  1564. s.local_endpoint = LOCAL_END;
  1565. s.remote_endpoint = REMOTE_END;
  1566. s.local_seq_no = LOCAL_SEQ;
  1567. s.remote_seq_no = REMOTE_SEQ + 1;
  1568. s.remote_last_seq = LOCAL_SEQ;
  1569. s.remote_win_len = 256;
  1570. s
  1571. }
  1572. #[test]
  1573. fn test_syn_received_ack() {
  1574. let mut s = socket_syn_received();
  1575. recv!(s, [TcpRepr {
  1576. control: TcpControl::Syn,
  1577. seq_number: LOCAL_SEQ,
  1578. ack_number: Some(REMOTE_SEQ + 1),
  1579. max_seg_size: Some(1480),
  1580. ..RECV_TEMPL
  1581. }]);
  1582. send!(s, TcpRepr {
  1583. seq_number: REMOTE_SEQ + 1,
  1584. ack_number: Some(LOCAL_SEQ + 1),
  1585. ..SEND_TEMPL
  1586. });
  1587. assert_eq!(s.state, State::Established);
  1588. sanity!(s, socket_established());
  1589. }
  1590. #[test]
  1591. fn test_syn_received_fin() {
  1592. let mut s = socket_syn_received();
  1593. recv!(s, [TcpRepr {
  1594. control: TcpControl::Syn,
  1595. seq_number: LOCAL_SEQ,
  1596. ack_number: Some(REMOTE_SEQ + 1),
  1597. max_seg_size: Some(1480),
  1598. ..RECV_TEMPL
  1599. }]);
  1600. send!(s, TcpRepr {
  1601. control: TcpControl::Fin,
  1602. seq_number: REMOTE_SEQ + 1,
  1603. ack_number: Some(LOCAL_SEQ + 1),
  1604. payload: &b"abcdef"[..],
  1605. ..SEND_TEMPL
  1606. });
  1607. recv!(s, [TcpRepr {
  1608. seq_number: LOCAL_SEQ + 1,
  1609. ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
  1610. window_len: 58,
  1611. ..RECV_TEMPL
  1612. }]);
  1613. assert_eq!(s.state, State::CloseWait);
  1614. sanity!(s, TcpSocket {
  1615. remote_last_ack: Some(REMOTE_SEQ + 1 + 6 + 1),
  1616. remote_last_win: 58,
  1617. ..socket_close_wait()
  1618. });
  1619. }
  1620. #[test]
  1621. fn test_syn_received_rst() {
  1622. let mut s = socket_syn_received();
  1623. recv!(s, [TcpRepr {
  1624. control: TcpControl::Syn,
  1625. seq_number: LOCAL_SEQ,
  1626. ack_number: Some(REMOTE_SEQ + 1),
  1627. max_seg_size: Some(1480),
  1628. ..RECV_TEMPL
  1629. }]);
  1630. send!(s, TcpRepr {
  1631. control: TcpControl::Rst,
  1632. seq_number: REMOTE_SEQ + 1,
  1633. ack_number: Some(LOCAL_SEQ),
  1634. ..SEND_TEMPL
  1635. });
  1636. assert_eq!(s.state, State::Listen);
  1637. assert_eq!(s.local_endpoint, IpEndpoint::new(IpAddress::Unspecified, LOCAL_END.port));
  1638. assert_eq!(s.remote_endpoint, IpEndpoint::default());
  1639. }
  1640. #[test]
  1641. fn test_syn_received_close() {
  1642. let mut s = socket_syn_received();
  1643. s.close();
  1644. assert_eq!(s.state, State::FinWait1);
  1645. }
  1646. // =========================================================================================//
  1647. // Tests for the SYN-SENT state.
  1648. // =========================================================================================//
  1649. fn socket_syn_sent() -> TcpSocket<'static> {
  1650. let mut s = socket();
  1651. s.state = State::SynSent;
  1652. s.local_endpoint = IpEndpoint::new(IpAddress::v4(0, 0, 0, 0), LOCAL_PORT);
  1653. s.remote_endpoint = REMOTE_END;
  1654. s.local_seq_no = LOCAL_SEQ;
  1655. s.remote_last_seq = LOCAL_SEQ;
  1656. s
  1657. }
  1658. #[test]
  1659. fn test_connect_validation() {
  1660. let mut s = socket();
  1661. assert_eq!(s.connect((IpAddress::v4(0, 0, 0, 0), 80), LOCAL_END),
  1662. Err(Error::Unaddressable));
  1663. assert_eq!(s.connect(REMOTE_END, (IpAddress::v4(10, 0, 0, 0), 0)),
  1664. Err(Error::Unaddressable));
  1665. assert_eq!(s.connect((IpAddress::v4(10, 0, 0, 0), 0), LOCAL_END),
  1666. Err(Error::Unaddressable));
  1667. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  1668. Err(Error::Unaddressable));
  1669. }
  1670. #[test]
  1671. fn test_connect() {
  1672. let mut s = socket();
  1673. s.local_seq_no = LOCAL_SEQ;
  1674. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  1675. assert_eq!(s.local_endpoint, IpEndpoint::new(IpAddress::v4(0, 0, 0, 0), LOCAL_END.port));
  1676. recv!(s, [TcpRepr {
  1677. control: TcpControl::Syn,
  1678. seq_number: LOCAL_SEQ,
  1679. ack_number: None,
  1680. max_seg_size: Some(1480),
  1681. ..RECV_TEMPL
  1682. }]);
  1683. send!(s, TcpRepr {
  1684. control: TcpControl::Syn,
  1685. seq_number: REMOTE_SEQ,
  1686. ack_number: Some(LOCAL_SEQ + 1),
  1687. max_seg_size: Some(1400),
  1688. ..SEND_TEMPL
  1689. });
  1690. assert_eq!(s.local_endpoint, LOCAL_END);
  1691. }
  1692. #[test]
  1693. fn test_connect_unspecified_local() {
  1694. let mut s = socket();
  1695. assert_eq!(s.connect(REMOTE_END, (IpAddress::v4(0, 0, 0, 0), 80)),
  1696. Ok(()));
  1697. s.abort();
  1698. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1699. Ok(()));
  1700. s.abort();
  1701. }
  1702. #[test]
  1703. fn test_connect_specified_local() {
  1704. let mut s = socket();
  1705. assert_eq!(s.connect(REMOTE_END, (IpAddress::v4(10, 0, 0, 2), 80)),
  1706. Ok(()));
  1707. }
  1708. #[test]
  1709. fn test_connect_twice() {
  1710. let mut s = socket();
  1711. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1712. Ok(()));
  1713. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1714. Err(Error::Illegal));
  1715. }
  1716. #[test]
  1717. fn test_syn_sent_sanity() {
  1718. let mut s = socket();
  1719. s.local_seq_no = LOCAL_SEQ;
  1720. s.connect(REMOTE_END, LOCAL_END).unwrap();
  1721. sanity!(s, socket_syn_sent());
  1722. }
  1723. #[test]
  1724. fn test_syn_sent_syn_ack() {
  1725. let mut s = socket_syn_sent();
  1726. recv!(s, [TcpRepr {
  1727. control: TcpControl::Syn,
  1728. seq_number: LOCAL_SEQ,
  1729. ack_number: None,
  1730. max_seg_size: Some(1480),
  1731. ..RECV_TEMPL
  1732. }]);
  1733. send!(s, TcpRepr {
  1734. control: TcpControl::Syn,
  1735. seq_number: REMOTE_SEQ,
  1736. ack_number: Some(LOCAL_SEQ + 1),
  1737. max_seg_size: Some(1400),
  1738. ..SEND_TEMPL
  1739. });
  1740. recv!(s, [TcpRepr {
  1741. seq_number: LOCAL_SEQ + 1,
  1742. ack_number: Some(REMOTE_SEQ + 1),
  1743. ..RECV_TEMPL
  1744. }]);
  1745. recv!(s, time 1000, Err(Error::Exhausted));
  1746. assert_eq!(s.state, State::Established);
  1747. sanity!(s, socket_established());
  1748. }
  1749. #[test]
  1750. fn test_syn_sent_rst() {
  1751. let mut s = socket_syn_sent();
  1752. send!(s, TcpRepr {
  1753. control: TcpControl::Rst,
  1754. seq_number: REMOTE_SEQ,
  1755. ack_number: Some(LOCAL_SEQ + 1),
  1756. ..SEND_TEMPL
  1757. });
  1758. assert_eq!(s.state, State::Closed);
  1759. }
  1760. #[test]
  1761. fn test_syn_sent_rst_no_ack() {
  1762. let mut s = socket_syn_sent();
  1763. send!(s, TcpRepr {
  1764. control: TcpControl::Rst,
  1765. seq_number: REMOTE_SEQ,
  1766. ack_number: None,
  1767. ..SEND_TEMPL
  1768. }, Err(Error::Dropped));
  1769. assert_eq!(s.state, State::SynSent);
  1770. }
  1771. #[test]
  1772. fn test_syn_sent_rst_bad_ack() {
  1773. let mut s = socket_syn_sent();
  1774. send!(s, TcpRepr {
  1775. control: TcpControl::Rst,
  1776. seq_number: REMOTE_SEQ,
  1777. ack_number: Some(TcpSeqNumber(1234)),
  1778. ..SEND_TEMPL
  1779. }, Err(Error::Dropped));
  1780. assert_eq!(s.state, State::SynSent);
  1781. }
  1782. #[test]
  1783. fn test_syn_sent_close() {
  1784. let mut s = socket();
  1785. s.close();
  1786. assert_eq!(s.state, State::Closed);
  1787. }
  1788. // =========================================================================================//
  1789. // Tests for the ESTABLISHED state.
  1790. // =========================================================================================//
  1791. fn socket_established() -> TcpSocket<'static> {
  1792. let mut s = socket_syn_received();
  1793. s.state = State::Established;
  1794. s.local_seq_no = LOCAL_SEQ + 1;
  1795. s.remote_last_seq = LOCAL_SEQ + 1;
  1796. s.remote_last_ack = Some(REMOTE_SEQ + 1);
  1797. s.remote_last_win = 64;
  1798. s
  1799. }
  1800. #[test]
  1801. fn test_established_recv() {
  1802. let mut s = socket_established();
  1803. send!(s, TcpRepr {
  1804. seq_number: REMOTE_SEQ + 1,
  1805. ack_number: Some(LOCAL_SEQ + 1),
  1806. payload: &b"abcdef"[..],
  1807. ..SEND_TEMPL
  1808. });
  1809. recv!(s, [TcpRepr {
  1810. seq_number: LOCAL_SEQ + 1,
  1811. ack_number: Some(REMOTE_SEQ + 1 + 6),
  1812. window_len: 58,
  1813. ..RECV_TEMPL
  1814. }]);
  1815. assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
  1816. }
  1817. #[test]
  1818. fn test_established_send() {
  1819. let mut s = socket_established();
  1820. // First roundtrip after establishing.
  1821. s.send_slice(b"abcdef").unwrap();
  1822. recv!(s, [TcpRepr {
  1823. seq_number: LOCAL_SEQ + 1,
  1824. ack_number: Some(REMOTE_SEQ + 1),
  1825. payload: &b"abcdef"[..],
  1826. ..RECV_TEMPL
  1827. }]);
  1828. assert_eq!(s.tx_buffer.len(), 6);
  1829. send!(s, TcpRepr {
  1830. seq_number: REMOTE_SEQ + 1,
  1831. ack_number: Some(LOCAL_SEQ + 1 + 6),
  1832. ..SEND_TEMPL
  1833. });
  1834. assert_eq!(s.tx_buffer.len(), 0);
  1835. // Second roundtrip.
  1836. s.send_slice(b"foobar").unwrap();
  1837. recv!(s, [TcpRepr {
  1838. seq_number: LOCAL_SEQ + 1 + 6,
  1839. ack_number: Some(REMOTE_SEQ + 1),
  1840. payload: &b"foobar"[..],
  1841. ..RECV_TEMPL
  1842. }]);
  1843. send!(s, TcpRepr {
  1844. seq_number: REMOTE_SEQ + 1,
  1845. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  1846. ..SEND_TEMPL
  1847. });
  1848. assert_eq!(s.tx_buffer.len(), 0);
  1849. }
  1850. #[test]
  1851. fn test_established_send_no_ack_send() {
  1852. let mut s = socket_established();
  1853. s.send_slice(b"abcdef").unwrap();
  1854. recv!(s, [TcpRepr {
  1855. seq_number: LOCAL_SEQ + 1,
  1856. ack_number: Some(REMOTE_SEQ + 1),
  1857. payload: &b"abcdef"[..],
  1858. ..RECV_TEMPL
  1859. }]);
  1860. s.send_slice(b"foobar").unwrap();
  1861. recv!(s, [TcpRepr {
  1862. seq_number: LOCAL_SEQ + 1 + 6,
  1863. ack_number: Some(REMOTE_SEQ + 1),
  1864. payload: &b"foobar"[..],
  1865. ..RECV_TEMPL
  1866. }]);
  1867. }
  1868. #[test]
  1869. fn test_established_send_buf_gt_win() {
  1870. let mut data = [0; 32];
  1871. for (i, elem) in data.iter_mut().enumerate() {
  1872. *elem = i as u8
  1873. }
  1874. let mut s = socket_established();
  1875. s.remote_win_len = 16;
  1876. s.send_slice(&data[..]).unwrap();
  1877. recv!(s, [TcpRepr {
  1878. seq_number: LOCAL_SEQ + 1,
  1879. ack_number: Some(REMOTE_SEQ + 1),
  1880. payload: &data[0..16],
  1881. ..RECV_TEMPL
  1882. }, TcpRepr {
  1883. seq_number: LOCAL_SEQ + 1 + 16,
  1884. ack_number: Some(REMOTE_SEQ + 1),
  1885. payload: &data[16..32],
  1886. ..RECV_TEMPL
  1887. }]);
  1888. }
  1889. #[test]
  1890. fn test_established_no_ack() {
  1891. let mut s = socket_established();
  1892. send!(s, TcpRepr {
  1893. seq_number: REMOTE_SEQ + 1,
  1894. ack_number: None,
  1895. ..SEND_TEMPL
  1896. }, Err(Error::Dropped));
  1897. }
  1898. #[test]
  1899. fn test_established_bad_ack() {
  1900. let mut s = socket_established();
  1901. // Already acknowledged data.
  1902. send!(s, TcpRepr {
  1903. seq_number: REMOTE_SEQ + 1,
  1904. ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
  1905. ..SEND_TEMPL
  1906. }, Err(Error::Dropped));
  1907. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  1908. // Data not yet transmitted.
  1909. send!(s, TcpRepr {
  1910. seq_number: REMOTE_SEQ + 1,
  1911. ack_number: Some(LOCAL_SEQ + 10),
  1912. ..SEND_TEMPL
  1913. }, Ok(Some(TcpRepr {
  1914. seq_number: LOCAL_SEQ + 1,
  1915. ack_number: Some(REMOTE_SEQ + 1),
  1916. ..RECV_TEMPL
  1917. })));
  1918. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  1919. }
  1920. #[test]
  1921. fn test_established_bad_seq() {
  1922. let mut s = socket_established();
  1923. // Data outside of receive window.
  1924. send!(s, TcpRepr {
  1925. seq_number: REMOTE_SEQ + 1 + 256,
  1926. ack_number: Some(LOCAL_SEQ + 1),
  1927. ..SEND_TEMPL
  1928. }, Ok(Some(TcpRepr {
  1929. seq_number: LOCAL_SEQ + 1,
  1930. ack_number: Some(REMOTE_SEQ + 1),
  1931. ..RECV_TEMPL
  1932. })));
  1933. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  1934. }
  1935. #[test]
  1936. fn test_established_fin() {
  1937. let mut s = socket_established();
  1938. send!(s, TcpRepr {
  1939. control: TcpControl::Fin,
  1940. seq_number: REMOTE_SEQ + 1,
  1941. ack_number: Some(LOCAL_SEQ + 1),
  1942. ..SEND_TEMPL
  1943. });
  1944. recv!(s, [TcpRepr {
  1945. seq_number: LOCAL_SEQ + 1,
  1946. ack_number: Some(REMOTE_SEQ + 1 + 1),
  1947. ..RECV_TEMPL
  1948. }]);
  1949. assert_eq!(s.state, State::CloseWait);
  1950. sanity!(s, socket_close_wait());
  1951. }
  1952. #[test]
  1953. fn test_established_send_fin() {
  1954. let mut s = socket_established();
  1955. s.send_slice(b"abcdef").unwrap();
  1956. send!(s, TcpRepr {
  1957. control: TcpControl::Fin,
  1958. seq_number: REMOTE_SEQ + 1,
  1959. ack_number: Some(LOCAL_SEQ + 1),
  1960. ..SEND_TEMPL
  1961. });
  1962. assert_eq!(s.state, State::CloseWait);
  1963. recv!(s, [TcpRepr {
  1964. seq_number: LOCAL_SEQ + 1,
  1965. ack_number: Some(REMOTE_SEQ + 1 + 1),
  1966. payload: &b"abcdef"[..],
  1967. ..RECV_TEMPL
  1968. }]);
  1969. }
  1970. #[test]
  1971. fn test_established_rst() {
  1972. let mut s = socket_established();
  1973. send!(s, TcpRepr {
  1974. control: TcpControl::Rst,
  1975. seq_number: REMOTE_SEQ + 1,
  1976. ack_number: Some(LOCAL_SEQ + 1),
  1977. ..SEND_TEMPL
  1978. });
  1979. assert_eq!(s.state, State::Closed);
  1980. }
  1981. #[test]
  1982. fn test_established_rst_no_ack() {
  1983. let mut s = socket_established();
  1984. send!(s, TcpRepr {
  1985. control: TcpControl::Rst,
  1986. seq_number: REMOTE_SEQ + 1,
  1987. ack_number: None,
  1988. ..SEND_TEMPL
  1989. });
  1990. assert_eq!(s.state, State::Closed);
  1991. }
  1992. #[test]
  1993. fn test_established_close() {
  1994. let mut s = socket_established();
  1995. s.close();
  1996. assert_eq!(s.state, State::FinWait1);
  1997. sanity!(s, socket_fin_wait_1());
  1998. }
  1999. #[test]
  2000. fn test_established_abort() {
  2001. let mut s = socket_established();
  2002. s.abort();
  2003. assert_eq!(s.state, State::Closed);
  2004. recv!(s, [TcpRepr {
  2005. control: TcpControl::Rst,
  2006. seq_number: LOCAL_SEQ + 1,
  2007. ack_number: Some(REMOTE_SEQ + 1),
  2008. ..RECV_TEMPL
  2009. }]);
  2010. }
  2011. // =========================================================================================//
  2012. // Tests for the FIN-WAIT-1 state.
  2013. // =========================================================================================//
  2014. fn socket_fin_wait_1() -> TcpSocket<'static> {
  2015. let mut s = socket_established();
  2016. s.state = State::FinWait1;
  2017. s
  2018. }
  2019. #[test]
  2020. fn test_fin_wait_1_fin_ack() {
  2021. let mut s = socket_fin_wait_1();
  2022. recv!(s, [TcpRepr {
  2023. control: TcpControl::Fin,
  2024. seq_number: LOCAL_SEQ + 1,
  2025. ack_number: Some(REMOTE_SEQ + 1),
  2026. ..RECV_TEMPL
  2027. }]);
  2028. send!(s, TcpRepr {
  2029. seq_number: REMOTE_SEQ + 1,
  2030. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2031. ..SEND_TEMPL
  2032. });
  2033. assert_eq!(s.state, State::FinWait2);
  2034. sanity!(s, socket_fin_wait_2());
  2035. }
  2036. #[test]
  2037. fn test_fin_wait_1_fin_fin() {
  2038. let mut s = socket_fin_wait_1();
  2039. recv!(s, [TcpRepr {
  2040. control: TcpControl::Fin,
  2041. seq_number: LOCAL_SEQ + 1,
  2042. ack_number: Some(REMOTE_SEQ + 1),
  2043. ..RECV_TEMPL
  2044. }]);
  2045. send!(s, TcpRepr {
  2046. control: TcpControl::Fin,
  2047. seq_number: REMOTE_SEQ + 1,
  2048. ack_number: Some(LOCAL_SEQ + 1),
  2049. ..SEND_TEMPL
  2050. });
  2051. assert_eq!(s.state, State::Closing);
  2052. sanity!(s, socket_closing());
  2053. }
  2054. #[test]
  2055. fn test_fin_wait_1_fin_with_data_queued() {
  2056. let mut s = socket_established();
  2057. s.remote_win_len = 6;
  2058. s.send_slice(b"abcdef123456").unwrap();
  2059. s.close();
  2060. recv!(s, Ok(TcpRepr {
  2061. seq_number: LOCAL_SEQ + 1,
  2062. ack_number: Some(REMOTE_SEQ + 1),
  2063. payload: &b"abcdef"[..],
  2064. ..RECV_TEMPL
  2065. }));
  2066. send!(s, TcpRepr {
  2067. seq_number: REMOTE_SEQ + 1,
  2068. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2069. ..SEND_TEMPL
  2070. });
  2071. assert_eq!(s.state, State::FinWait1);
  2072. }
  2073. #[test]
  2074. fn test_fin_wait_1_close() {
  2075. let mut s = socket_fin_wait_1();
  2076. s.close();
  2077. assert_eq!(s.state, State::FinWait1);
  2078. }
  2079. // =========================================================================================//
  2080. // Tests for the FIN-WAIT-2 state.
  2081. // =========================================================================================//
  2082. fn socket_fin_wait_2() -> TcpSocket<'static> {
  2083. let mut s = socket_fin_wait_1();
  2084. s.state = State::FinWait2;
  2085. s.local_seq_no = LOCAL_SEQ + 1 + 1;
  2086. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  2087. s
  2088. }
  2089. #[test]
  2090. fn test_fin_wait_2_fin() {
  2091. let mut s = socket_fin_wait_2();
  2092. send!(s, time 1_000, TcpRepr {
  2093. control: TcpControl::Fin,
  2094. seq_number: REMOTE_SEQ + 1,
  2095. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2096. ..SEND_TEMPL
  2097. });
  2098. assert_eq!(s.state, State::TimeWait);
  2099. sanity!(s, socket_time_wait(false));
  2100. }
  2101. #[test]
  2102. fn test_fin_wait_2_close() {
  2103. let mut s = socket_fin_wait_2();
  2104. s.close();
  2105. assert_eq!(s.state, State::FinWait2);
  2106. }
  2107. // =========================================================================================//
  2108. // Tests for the CLOSING state.
  2109. // =========================================================================================//
  2110. fn socket_closing() -> TcpSocket<'static> {
  2111. let mut s = socket_fin_wait_1();
  2112. s.state = State::Closing;
  2113. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  2114. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2115. s
  2116. }
  2117. #[test]
  2118. fn test_closing_ack_fin() {
  2119. let mut s = socket_closing();
  2120. recv!(s, [TcpRepr {
  2121. seq_number: LOCAL_SEQ + 1 + 1,
  2122. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2123. ..RECV_TEMPL
  2124. }]);
  2125. send!(s, time 1_000, TcpRepr {
  2126. seq_number: REMOTE_SEQ + 1 + 1,
  2127. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2128. ..SEND_TEMPL
  2129. });
  2130. assert_eq!(s.state, State::TimeWait);
  2131. sanity!(s, socket_time_wait(true));
  2132. }
  2133. #[test]
  2134. fn test_closing_close() {
  2135. let mut s = socket_closing();
  2136. s.close();
  2137. assert_eq!(s.state, State::Closing);
  2138. }
  2139. // =========================================================================================//
  2140. // Tests for the TIME-WAIT state.
  2141. // =========================================================================================//
  2142. fn socket_time_wait(from_closing: bool) -> TcpSocket<'static> {
  2143. let mut s = socket_fin_wait_2();
  2144. s.state = State::TimeWait;
  2145. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2146. if from_closing {
  2147. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2148. }
  2149. s.timer = Timer::Close { expires_at: 1_000 + CLOSE_DELAY };
  2150. s
  2151. }
  2152. #[test]
  2153. fn test_time_wait_from_fin_wait_2_ack() {
  2154. let mut s = socket_time_wait(false);
  2155. recv!(s, [TcpRepr {
  2156. seq_number: LOCAL_SEQ + 1 + 1,
  2157. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2158. ..RECV_TEMPL
  2159. }]);
  2160. }
  2161. #[test]
  2162. fn test_time_wait_from_closing_no_ack() {
  2163. let mut s = socket_time_wait(true);
  2164. recv!(s, []);
  2165. }
  2166. #[test]
  2167. fn test_time_wait_close() {
  2168. let mut s = socket_time_wait(false);
  2169. s.close();
  2170. assert_eq!(s.state, State::TimeWait);
  2171. }
  2172. #[test]
  2173. fn test_time_wait_retransmit() {
  2174. let mut s = socket_time_wait(false);
  2175. recv!(s, [TcpRepr {
  2176. seq_number: LOCAL_SEQ + 1 + 1,
  2177. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2178. ..RECV_TEMPL
  2179. }]);
  2180. send!(s, time 5_000, TcpRepr {
  2181. control: TcpControl::Fin,
  2182. seq_number: REMOTE_SEQ + 1,
  2183. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2184. ..SEND_TEMPL
  2185. }, Ok(Some(TcpRepr {
  2186. seq_number: LOCAL_SEQ + 1 + 1,
  2187. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2188. ..RECV_TEMPL
  2189. })));
  2190. assert_eq!(s.timer, Timer::Close { expires_at: 5_000 + CLOSE_DELAY });
  2191. }
  2192. #[test]
  2193. fn test_time_wait_timeout() {
  2194. let mut s = socket_time_wait(false);
  2195. recv!(s, [TcpRepr {
  2196. seq_number: LOCAL_SEQ + 1 + 1,
  2197. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2198. ..RECV_TEMPL
  2199. }]);
  2200. assert_eq!(s.state, State::TimeWait);
  2201. recv!(s, time 60_000, Err(Error::Exhausted));
  2202. assert_eq!(s.state, State::Closed);
  2203. }
  2204. // =========================================================================================//
  2205. // Tests for the CLOSE-WAIT state.
  2206. // =========================================================================================//
  2207. fn socket_close_wait() -> TcpSocket<'static> {
  2208. let mut s = socket_established();
  2209. s.state = State::CloseWait;
  2210. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2211. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2212. s
  2213. }
  2214. #[test]
  2215. fn test_close_wait_ack() {
  2216. let mut s = socket_close_wait();
  2217. s.send_slice(b"abcdef").unwrap();
  2218. recv!(s, [TcpRepr {
  2219. seq_number: LOCAL_SEQ + 1,
  2220. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2221. payload: &b"abcdef"[..],
  2222. ..RECV_TEMPL
  2223. }]);
  2224. send!(s, TcpRepr {
  2225. seq_number: REMOTE_SEQ + 1 + 1,
  2226. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2227. ..SEND_TEMPL
  2228. });
  2229. }
  2230. #[test]
  2231. fn test_close_wait_close() {
  2232. let mut s = socket_close_wait();
  2233. s.close();
  2234. assert_eq!(s.state, State::LastAck);
  2235. sanity!(s, socket_last_ack());
  2236. }
  2237. // =========================================================================================//
  2238. // Tests for the LAST-ACK state.
  2239. // =========================================================================================//
  2240. fn socket_last_ack() -> TcpSocket<'static> {
  2241. let mut s = socket_close_wait();
  2242. s.state = State::LastAck;
  2243. s
  2244. }
  2245. #[test]
  2246. fn test_last_ack_fin_ack() {
  2247. let mut s = socket_last_ack();
  2248. recv!(s, [TcpRepr {
  2249. control: TcpControl::Fin,
  2250. seq_number: LOCAL_SEQ + 1,
  2251. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2252. ..RECV_TEMPL
  2253. }]);
  2254. assert_eq!(s.state, State::LastAck);
  2255. send!(s, TcpRepr {
  2256. seq_number: REMOTE_SEQ + 1 + 1,
  2257. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2258. ..SEND_TEMPL
  2259. });
  2260. assert_eq!(s.state, State::Closed);
  2261. }
  2262. #[test]
  2263. fn test_last_ack_close() {
  2264. let mut s = socket_last_ack();
  2265. s.close();
  2266. assert_eq!(s.state, State::LastAck);
  2267. }
  2268. // =========================================================================================//
  2269. // Tests for transitioning through multiple states.
  2270. // =========================================================================================//
  2271. #[test]
  2272. fn test_listen() {
  2273. let mut s = socket();
  2274. s.listen(IpEndpoint::new(IpAddress::default(), LOCAL_PORT)).unwrap();
  2275. assert_eq!(s.state, State::Listen);
  2276. }
  2277. #[test]
  2278. fn test_three_way_handshake() {
  2279. let mut s = socket_listen();
  2280. send!(s, TcpRepr {
  2281. control: TcpControl::Syn,
  2282. seq_number: REMOTE_SEQ,
  2283. ack_number: None,
  2284. ..SEND_TEMPL
  2285. });
  2286. assert_eq!(s.state(), State::SynReceived);
  2287. assert_eq!(s.local_endpoint(), LOCAL_END);
  2288. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2289. recv!(s, [TcpRepr {
  2290. control: TcpControl::Syn,
  2291. seq_number: LOCAL_SEQ,
  2292. ack_number: Some(REMOTE_SEQ + 1),
  2293. max_seg_size: Some(1480),
  2294. ..RECV_TEMPL
  2295. }]);
  2296. send!(s, TcpRepr {
  2297. seq_number: REMOTE_SEQ + 1,
  2298. ack_number: Some(LOCAL_SEQ + 1),
  2299. ..SEND_TEMPL
  2300. });
  2301. assert_eq!(s.state(), State::Established);
  2302. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2303. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  2304. }
  2305. #[test]
  2306. fn test_remote_close() {
  2307. let mut s = socket_established();
  2308. send!(s, TcpRepr {
  2309. control: TcpControl::Fin,
  2310. seq_number: REMOTE_SEQ + 1,
  2311. ack_number: Some(LOCAL_SEQ + 1),
  2312. ..SEND_TEMPL
  2313. });
  2314. assert_eq!(s.state, State::CloseWait);
  2315. recv!(s, [TcpRepr {
  2316. seq_number: LOCAL_SEQ + 1,
  2317. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2318. ..RECV_TEMPL
  2319. }]);
  2320. s.close();
  2321. assert_eq!(s.state, State::LastAck);
  2322. recv!(s, [TcpRepr {
  2323. control: TcpControl::Fin,
  2324. seq_number: LOCAL_SEQ + 1,
  2325. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2326. ..RECV_TEMPL
  2327. }]);
  2328. send!(s, TcpRepr {
  2329. seq_number: REMOTE_SEQ + 1 + 1,
  2330. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2331. ..SEND_TEMPL
  2332. });
  2333. assert_eq!(s.state, State::Closed);
  2334. }
  2335. #[test]
  2336. fn test_local_close() {
  2337. let mut s = socket_established();
  2338. s.close();
  2339. assert_eq!(s.state, State::FinWait1);
  2340. recv!(s, [TcpRepr {
  2341. control: TcpControl::Fin,
  2342. seq_number: LOCAL_SEQ + 1,
  2343. ack_number: Some(REMOTE_SEQ + 1),
  2344. ..RECV_TEMPL
  2345. }]);
  2346. send!(s, TcpRepr {
  2347. seq_number: REMOTE_SEQ + 1,
  2348. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2349. ..SEND_TEMPL
  2350. });
  2351. assert_eq!(s.state, State::FinWait2);
  2352. send!(s, TcpRepr {
  2353. control: TcpControl::Fin,
  2354. seq_number: REMOTE_SEQ + 1,
  2355. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2356. ..SEND_TEMPL
  2357. });
  2358. assert_eq!(s.state, State::TimeWait);
  2359. recv!(s, [TcpRepr {
  2360. seq_number: LOCAL_SEQ + 1 + 1,
  2361. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2362. ..RECV_TEMPL
  2363. }]);
  2364. }
  2365. #[test]
  2366. fn test_simultaneous_close() {
  2367. let mut s = socket_established();
  2368. s.close();
  2369. assert_eq!(s.state, State::FinWait1);
  2370. recv!(s, [TcpRepr { // due to reordering, this is logically located...
  2371. control: TcpControl::Fin,
  2372. seq_number: LOCAL_SEQ + 1,
  2373. ack_number: Some(REMOTE_SEQ + 1),
  2374. ..RECV_TEMPL
  2375. }]);
  2376. send!(s, TcpRepr {
  2377. control: TcpControl::Fin,
  2378. seq_number: REMOTE_SEQ + 1,
  2379. ack_number: Some(LOCAL_SEQ + 1),
  2380. ..SEND_TEMPL
  2381. });
  2382. assert_eq!(s.state, State::Closing);
  2383. recv!(s, [TcpRepr {
  2384. seq_number: LOCAL_SEQ + 1 + 1,
  2385. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2386. ..RECV_TEMPL
  2387. }]);
  2388. // ... at this point
  2389. send!(s, TcpRepr {
  2390. seq_number: REMOTE_SEQ + 1 + 1,
  2391. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2392. ..SEND_TEMPL
  2393. });
  2394. assert_eq!(s.state, State::TimeWait);
  2395. recv!(s, []);
  2396. }
  2397. #[test]
  2398. fn test_simultaneous_close_combined_fin_ack() {
  2399. let mut s = socket_established();
  2400. s.close();
  2401. assert_eq!(s.state, State::FinWait1);
  2402. recv!(s, [TcpRepr {
  2403. control: TcpControl::Fin,
  2404. seq_number: LOCAL_SEQ + 1,
  2405. ack_number: Some(REMOTE_SEQ + 1),
  2406. ..RECV_TEMPL
  2407. }]);
  2408. send!(s, TcpRepr {
  2409. control: TcpControl::Fin,
  2410. seq_number: REMOTE_SEQ + 1,
  2411. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2412. ..SEND_TEMPL
  2413. });
  2414. assert_eq!(s.state, State::TimeWait);
  2415. recv!(s, [TcpRepr {
  2416. seq_number: LOCAL_SEQ + 1 + 1,
  2417. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2418. ..RECV_TEMPL
  2419. }]);
  2420. }
  2421. #[test]
  2422. fn test_fin_with_data() {
  2423. let mut s = socket_established();
  2424. s.send_slice(b"abcdef").unwrap();
  2425. s.close();
  2426. recv!(s, [TcpRepr {
  2427. control: TcpControl::Fin,
  2428. seq_number: LOCAL_SEQ + 1,
  2429. ack_number: Some(REMOTE_SEQ + 1),
  2430. payload: &b"abcdef"[..],
  2431. ..RECV_TEMPL
  2432. }])
  2433. }
  2434. #[test]
  2435. fn test_mutual_close_with_data_1() {
  2436. let mut s = socket_established();
  2437. s.send_slice(b"abcdef").unwrap();
  2438. s.close();
  2439. assert_eq!(s.state, State::FinWait1);
  2440. recv!(s, [TcpRepr {
  2441. control: TcpControl::Fin,
  2442. seq_number: LOCAL_SEQ + 1,
  2443. ack_number: Some(REMOTE_SEQ + 1),
  2444. payload: &b"abcdef"[..],
  2445. ..RECV_TEMPL
  2446. }]);
  2447. send!(s, TcpRepr {
  2448. control: TcpControl::Fin,
  2449. seq_number: REMOTE_SEQ + 1,
  2450. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2451. ..SEND_TEMPL
  2452. });
  2453. }
  2454. #[test]
  2455. fn test_mutual_close_with_data_2() {
  2456. let mut s = socket_established();
  2457. s.send_slice(b"abcdef").unwrap();
  2458. s.close();
  2459. assert_eq!(s.state, State::FinWait1);
  2460. recv!(s, [TcpRepr {
  2461. control: TcpControl::Fin,
  2462. seq_number: LOCAL_SEQ + 1,
  2463. ack_number: Some(REMOTE_SEQ + 1),
  2464. payload: &b"abcdef"[..],
  2465. ..RECV_TEMPL
  2466. }]);
  2467. send!(s, TcpRepr {
  2468. seq_number: REMOTE_SEQ + 1,
  2469. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2470. ..SEND_TEMPL
  2471. });
  2472. assert_eq!(s.state, State::FinWait2);
  2473. send!(s, TcpRepr {
  2474. control: TcpControl::Fin,
  2475. seq_number: REMOTE_SEQ + 1,
  2476. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2477. ..SEND_TEMPL
  2478. });
  2479. recv!(s, [TcpRepr {
  2480. seq_number: LOCAL_SEQ + 1 + 6 + 1,
  2481. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2482. ..RECV_TEMPL
  2483. }]);
  2484. assert_eq!(s.state, State::TimeWait);
  2485. }
  2486. // =========================================================================================//
  2487. // Tests for retransmission on packet loss.
  2488. // =========================================================================================//
  2489. fn socket_recved() -> TcpSocket<'static> {
  2490. let mut s = socket_established();
  2491. send!(s, TcpRepr {
  2492. seq_number: REMOTE_SEQ + 1,
  2493. ack_number: Some(LOCAL_SEQ + 1),
  2494. payload: &b"abcdef"[..],
  2495. ..SEND_TEMPL
  2496. });
  2497. recv!(s, [TcpRepr {
  2498. seq_number: LOCAL_SEQ + 1,
  2499. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2500. window_len: 58,
  2501. ..RECV_TEMPL
  2502. }]);
  2503. s
  2504. }
  2505. #[test]
  2506. fn test_duplicate_seq_ack() {
  2507. let mut s = socket_recved();
  2508. // remote retransmission
  2509. send!(s, TcpRepr {
  2510. seq_number: REMOTE_SEQ + 1,
  2511. ack_number: Some(LOCAL_SEQ + 1),
  2512. payload: &b"abcdef"[..],
  2513. ..SEND_TEMPL
  2514. }, Ok(Some(TcpRepr {
  2515. seq_number: LOCAL_SEQ + 1,
  2516. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2517. window_len: 58,
  2518. ..RECV_TEMPL
  2519. })));
  2520. }
  2521. #[test]
  2522. fn test_data_retransmit() {
  2523. let mut s = socket_established();
  2524. s.send_slice(b"abcdef").unwrap();
  2525. recv!(s, time 1000, Ok(TcpRepr {
  2526. seq_number: LOCAL_SEQ + 1,
  2527. ack_number: Some(REMOTE_SEQ + 1),
  2528. payload: &b"abcdef"[..],
  2529. ..RECV_TEMPL
  2530. }));
  2531. recv!(s, time 1050, Err(Error::Exhausted));
  2532. recv!(s, time 1100, Ok(TcpRepr {
  2533. seq_number: LOCAL_SEQ + 1,
  2534. ack_number: Some(REMOTE_SEQ + 1),
  2535. payload: &b"abcdef"[..],
  2536. ..RECV_TEMPL
  2537. }));
  2538. }
  2539. #[test]
  2540. fn test_data_retransmit_bursts() {
  2541. let mut s = socket_established();
  2542. s.remote_win_len = 6;
  2543. s.send_slice(b"abcdef012345").unwrap();
  2544. recv!(s, time 0, Ok(TcpRepr {
  2545. control: TcpControl::None,
  2546. seq_number: LOCAL_SEQ + 1,
  2547. ack_number: Some(REMOTE_SEQ + 1),
  2548. payload: &b"abcdef"[..],
  2549. ..RECV_TEMPL
  2550. }), exact);
  2551. s.remote_win_len = 6;
  2552. recv!(s, time 0, Ok(TcpRepr {
  2553. control: TcpControl::Psh,
  2554. seq_number: LOCAL_SEQ + 1 + 6,
  2555. ack_number: Some(REMOTE_SEQ + 1),
  2556. payload: &b"012345"[..],
  2557. ..RECV_TEMPL
  2558. }), exact);
  2559. s.remote_win_len = 6;
  2560. recv!(s, time 0, Err(Error::Exhausted));
  2561. recv!(s, time 50, Err(Error::Exhausted));
  2562. recv!(s, time 100, Ok(TcpRepr {
  2563. control: TcpControl::None,
  2564. seq_number: LOCAL_SEQ + 1,
  2565. ack_number: Some(REMOTE_SEQ + 1),
  2566. payload: &b"abcdef"[..],
  2567. ..RECV_TEMPL
  2568. }), exact);
  2569. s.remote_win_len = 6;
  2570. recv!(s, time 150, Ok(TcpRepr {
  2571. control: TcpControl::Psh,
  2572. seq_number: LOCAL_SEQ + 1 + 6,
  2573. ack_number: Some(REMOTE_SEQ + 1),
  2574. payload: &b"012345"[..],
  2575. ..RECV_TEMPL
  2576. }), exact);
  2577. s.remote_win_len = 6;
  2578. recv!(s, time 200, Err(Error::Exhausted));
  2579. }
  2580. #[test]
  2581. fn test_send_data_after_syn_ack_retransmit() {
  2582. let mut s = socket_syn_received();
  2583. recv!(s, time 50, Ok(TcpRepr {
  2584. control: TcpControl::Syn,
  2585. seq_number: LOCAL_SEQ,
  2586. ack_number: Some(REMOTE_SEQ + 1),
  2587. max_seg_size: Some(1480),
  2588. ..RECV_TEMPL
  2589. }));
  2590. recv!(s, time 150, Ok(TcpRepr { // retransmit
  2591. control: TcpControl::Syn,
  2592. seq_number: LOCAL_SEQ,
  2593. ack_number: Some(REMOTE_SEQ + 1),
  2594. max_seg_size: Some(1480),
  2595. ..RECV_TEMPL
  2596. }));
  2597. send!(s, TcpRepr {
  2598. seq_number: REMOTE_SEQ + 1,
  2599. ack_number: Some(LOCAL_SEQ + 1),
  2600. ..SEND_TEMPL
  2601. });
  2602. assert_eq!(s.state(), State::Established);
  2603. s.send_slice(b"abcdef").unwrap();
  2604. recv!(s, [TcpRepr {
  2605. seq_number: LOCAL_SEQ + 1,
  2606. ack_number: Some(REMOTE_SEQ + 1),
  2607. payload: &b"abcdef"[..],
  2608. ..RECV_TEMPL
  2609. }])
  2610. }
  2611. #[test]
  2612. fn test_established_retransmit_reset_after_ack() {
  2613. let mut s = socket_established();
  2614. s.remote_win_len = 6;
  2615. s.send_slice(b"abcdef").unwrap();
  2616. s.send_slice(b"123456").unwrap();
  2617. s.send_slice(b"ABCDEF").unwrap();
  2618. recv!(s, time 1000, Ok(TcpRepr {
  2619. seq_number: LOCAL_SEQ + 1,
  2620. ack_number: Some(REMOTE_SEQ + 1),
  2621. payload: &b"abcdef"[..],
  2622. ..RECV_TEMPL
  2623. }));
  2624. send!(s, time 1005, TcpRepr {
  2625. seq_number: REMOTE_SEQ + 1,
  2626. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2627. window_len: 6,
  2628. ..SEND_TEMPL
  2629. });
  2630. recv!(s, time 1010, Ok(TcpRepr {
  2631. seq_number: LOCAL_SEQ + 1 + 6,
  2632. ack_number: Some(REMOTE_SEQ + 1),
  2633. payload: &b"123456"[..],
  2634. ..RECV_TEMPL
  2635. }));
  2636. send!(s, time 1015, TcpRepr {
  2637. seq_number: REMOTE_SEQ + 1,
  2638. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2639. window_len: 6,
  2640. ..SEND_TEMPL
  2641. });
  2642. recv!(s, time 1020, Ok(TcpRepr {
  2643. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2644. ack_number: Some(REMOTE_SEQ + 1),
  2645. payload: &b"ABCDEF"[..],
  2646. ..RECV_TEMPL
  2647. }));
  2648. }
  2649. #[test]
  2650. fn test_close_wait_retransmit_reset_after_ack() {
  2651. let mut s = socket_close_wait();
  2652. s.remote_win_len = 6;
  2653. s.send_slice(b"abcdef").unwrap();
  2654. s.send_slice(b"123456").unwrap();
  2655. s.send_slice(b"ABCDEF").unwrap();
  2656. recv!(s, time 1000, Ok(TcpRepr {
  2657. seq_number: LOCAL_SEQ + 1,
  2658. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2659. payload: &b"abcdef"[..],
  2660. ..RECV_TEMPL
  2661. }));
  2662. send!(s, time 1005, TcpRepr {
  2663. seq_number: REMOTE_SEQ + 1 + 1,
  2664. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2665. window_len: 6,
  2666. ..SEND_TEMPL
  2667. });
  2668. recv!(s, time 1010, Ok(TcpRepr {
  2669. seq_number: LOCAL_SEQ + 1 + 6,
  2670. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2671. payload: &b"123456"[..],
  2672. ..RECV_TEMPL
  2673. }));
  2674. send!(s, time 1015, TcpRepr {
  2675. seq_number: REMOTE_SEQ + 1 + 1,
  2676. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2677. window_len: 6,
  2678. ..SEND_TEMPL
  2679. });
  2680. recv!(s, time 1020, Ok(TcpRepr {
  2681. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2682. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2683. payload: &b"ABCDEF"[..],
  2684. ..RECV_TEMPL
  2685. }));
  2686. }
  2687. #[test]
  2688. fn test_fin_wait_1_retransmit_reset_after_ack() {
  2689. let mut s = socket_established();
  2690. s.remote_win_len = 6;
  2691. s.send_slice(b"abcdef").unwrap();
  2692. s.send_slice(b"123456").unwrap();
  2693. s.send_slice(b"ABCDEF").unwrap();
  2694. s.close();
  2695. recv!(s, time 1000, Ok(TcpRepr {
  2696. seq_number: LOCAL_SEQ + 1,
  2697. ack_number: Some(REMOTE_SEQ + 1),
  2698. payload: &b"abcdef"[..],
  2699. ..RECV_TEMPL
  2700. }));
  2701. send!(s, time 1005, TcpRepr {
  2702. seq_number: REMOTE_SEQ + 1,
  2703. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2704. window_len: 6,
  2705. ..SEND_TEMPL
  2706. });
  2707. recv!(s, time 1010, Ok(TcpRepr {
  2708. seq_number: LOCAL_SEQ + 1 + 6,
  2709. ack_number: Some(REMOTE_SEQ + 1),
  2710. payload: &b"123456"[..],
  2711. ..RECV_TEMPL
  2712. }));
  2713. send!(s, time 1015, TcpRepr {
  2714. seq_number: REMOTE_SEQ + 1,
  2715. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2716. window_len: 6,
  2717. ..SEND_TEMPL
  2718. });
  2719. recv!(s, time 1020, Ok(TcpRepr {
  2720. control: TcpControl::Fin,
  2721. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2722. ack_number: Some(REMOTE_SEQ + 1),
  2723. payload: &b"ABCDEF"[..],
  2724. ..RECV_TEMPL
  2725. }));
  2726. }
  2727. // =========================================================================================//
  2728. // Tests for window management.
  2729. // =========================================================================================//
  2730. #[test]
  2731. fn test_maximum_segment_size() {
  2732. let mut s = socket_listen();
  2733. s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
  2734. send!(s, TcpRepr {
  2735. control: TcpControl::Syn,
  2736. seq_number: REMOTE_SEQ,
  2737. ack_number: None,
  2738. max_seg_size: Some(1000),
  2739. ..SEND_TEMPL
  2740. });
  2741. recv!(s, [TcpRepr {
  2742. control: TcpControl::Syn,
  2743. seq_number: LOCAL_SEQ,
  2744. ack_number: Some(REMOTE_SEQ + 1),
  2745. max_seg_size: Some(1480),
  2746. ..RECV_TEMPL
  2747. }]);
  2748. send!(s, TcpRepr {
  2749. seq_number: REMOTE_SEQ + 1,
  2750. ack_number: Some(LOCAL_SEQ + 1),
  2751. window_len: 32767,
  2752. ..SEND_TEMPL
  2753. });
  2754. s.send_slice(&[0; 1200][..]).unwrap();
  2755. recv!(s, Ok(TcpRepr {
  2756. seq_number: LOCAL_SEQ + 1,
  2757. ack_number: Some(REMOTE_SEQ + 1),
  2758. payload: &[0; 1000][..],
  2759. ..RECV_TEMPL
  2760. }));
  2761. }
  2762. // =========================================================================================//
  2763. // Tests for flow control.
  2764. // =========================================================================================//
  2765. #[test]
  2766. fn test_psh_transmit() {
  2767. let mut s = socket_established();
  2768. s.remote_win_len = 6;
  2769. s.send_slice(b"abcdef").unwrap();
  2770. s.send_slice(b"123456").unwrap();
  2771. recv!(s, time 0, Ok(TcpRepr {
  2772. control: TcpControl::None,
  2773. seq_number: LOCAL_SEQ + 1,
  2774. ack_number: Some(REMOTE_SEQ + 1),
  2775. payload: &b"abcdef"[..],
  2776. ..RECV_TEMPL
  2777. }), exact);
  2778. recv!(s, time 0, Ok(TcpRepr {
  2779. control: TcpControl::Psh,
  2780. seq_number: LOCAL_SEQ + 1 + 6,
  2781. ack_number: Some(REMOTE_SEQ + 1),
  2782. payload: &b"123456"[..],
  2783. ..RECV_TEMPL
  2784. }), exact);
  2785. }
  2786. #[test]
  2787. fn test_psh_receive() {
  2788. let mut s = socket_established();
  2789. send!(s, TcpRepr {
  2790. control: TcpControl::Psh,
  2791. seq_number: REMOTE_SEQ + 1,
  2792. ack_number: Some(LOCAL_SEQ + 1),
  2793. payload: &b"abcdef"[..],
  2794. ..SEND_TEMPL
  2795. });
  2796. recv!(s, [TcpRepr {
  2797. seq_number: LOCAL_SEQ + 1,
  2798. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2799. window_len: 58,
  2800. ..RECV_TEMPL
  2801. }]);
  2802. }
  2803. #[test]
  2804. fn test_zero_window_ack() {
  2805. let mut s = socket_established();
  2806. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  2807. s.assembler = Assembler::new(s.rx_buffer.capacity());
  2808. send!(s, TcpRepr {
  2809. seq_number: REMOTE_SEQ + 1,
  2810. ack_number: Some(LOCAL_SEQ + 1),
  2811. payload: &b"abcdef"[..],
  2812. ..SEND_TEMPL
  2813. });
  2814. recv!(s, [TcpRepr {
  2815. seq_number: LOCAL_SEQ + 1,
  2816. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2817. window_len: 0,
  2818. ..RECV_TEMPL
  2819. }]);
  2820. send!(s, TcpRepr {
  2821. seq_number: REMOTE_SEQ + 1 + 6,
  2822. ack_number: Some(LOCAL_SEQ + 1),
  2823. payload: &b"123456"[..],
  2824. ..SEND_TEMPL
  2825. }, Ok(Some(TcpRepr {
  2826. seq_number: LOCAL_SEQ + 1,
  2827. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2828. window_len: 0,
  2829. ..RECV_TEMPL
  2830. })));
  2831. }
  2832. #[test]
  2833. fn test_zero_window_ack_on_window_growth() {
  2834. let mut s = socket_established();
  2835. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  2836. s.assembler = Assembler::new(s.rx_buffer.capacity());
  2837. send!(s, TcpRepr {
  2838. seq_number: REMOTE_SEQ + 1,
  2839. ack_number: Some(LOCAL_SEQ + 1),
  2840. payload: &b"abcdef"[..],
  2841. ..SEND_TEMPL
  2842. });
  2843. recv!(s, [TcpRepr {
  2844. seq_number: LOCAL_SEQ + 1,
  2845. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2846. window_len: 0,
  2847. ..RECV_TEMPL
  2848. }]);
  2849. recv!(s, time 0, Err(Error::Exhausted));
  2850. assert_eq!(s.recv(3), Ok(&b"abc"[..]));
  2851. recv!(s, time 0, Ok(TcpRepr {
  2852. seq_number: LOCAL_SEQ + 1,
  2853. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2854. window_len: 3,
  2855. ..RECV_TEMPL
  2856. }));
  2857. recv!(s, time 0, Err(Error::Exhausted));
  2858. assert_eq!(s.recv(3), Ok(&b"def"[..]));
  2859. recv!(s, time 0, Ok(TcpRepr {
  2860. seq_number: LOCAL_SEQ + 1,
  2861. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2862. window_len: 6,
  2863. ..RECV_TEMPL
  2864. }));
  2865. }
  2866. #[test]
  2867. fn test_fill_peer_window() {
  2868. let mut s = socket_established();
  2869. s.remote_mss = 6;
  2870. s.send_slice(b"abcdef123456!@#$%^").unwrap();
  2871. recv!(s, [TcpRepr {
  2872. seq_number: LOCAL_SEQ + 1,
  2873. ack_number: Some(REMOTE_SEQ + 1),
  2874. payload: &b"abcdef"[..],
  2875. ..RECV_TEMPL
  2876. }, TcpRepr {
  2877. seq_number: LOCAL_SEQ + 1 + 6,
  2878. ack_number: Some(REMOTE_SEQ + 1),
  2879. payload: &b"123456"[..],
  2880. ..RECV_TEMPL
  2881. }, TcpRepr {
  2882. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2883. ack_number: Some(REMOTE_SEQ + 1),
  2884. payload: &b"!@#$%^"[..],
  2885. ..RECV_TEMPL
  2886. }]);
  2887. }
  2888. // =========================================================================================//
  2889. // Tests for timeouts.
  2890. // =========================================================================================//
  2891. #[test]
  2892. fn test_listen_timeout() {
  2893. let mut s = socket_listen();
  2894. s.set_timeout(Some(100));
  2895. assert_eq!(s.poll_at(), None);
  2896. }
  2897. #[test]
  2898. fn test_connect_timeout() {
  2899. let mut s = socket();
  2900. s.local_seq_no = LOCAL_SEQ;
  2901. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  2902. s.set_timeout(Some(100));
  2903. recv!(s, time 150, Ok(TcpRepr {
  2904. control: TcpControl::Syn,
  2905. seq_number: LOCAL_SEQ,
  2906. ack_number: None,
  2907. max_seg_size: Some(1480),
  2908. ..RECV_TEMPL
  2909. }));
  2910. assert_eq!(s.state, State::SynSent);
  2911. assert_eq!(s.poll_at(), Some(250));
  2912. recv!(s, time 250, Ok(TcpRepr {
  2913. control: TcpControl::Rst,
  2914. seq_number: LOCAL_SEQ + 1,
  2915. ack_number: Some(TcpSeqNumber(0)),
  2916. ..RECV_TEMPL
  2917. }));
  2918. assert_eq!(s.state, State::Closed);
  2919. }
  2920. #[test]
  2921. fn test_established_timeout() {
  2922. let mut s = socket_established();
  2923. s.set_timeout(Some(200));
  2924. recv!(s, time 250, Err(Error::Exhausted));
  2925. assert_eq!(s.poll_at(), Some(450));
  2926. s.send_slice(b"abcdef").unwrap();
  2927. assert_eq!(s.poll_at(), Some(0));
  2928. recv!(s, time 255, Ok(TcpRepr {
  2929. seq_number: LOCAL_SEQ + 1,
  2930. ack_number: Some(REMOTE_SEQ + 1),
  2931. payload: &b"abcdef"[..],
  2932. ..RECV_TEMPL
  2933. }));
  2934. assert_eq!(s.poll_at(), Some(355));
  2935. recv!(s, time 355, Ok(TcpRepr {
  2936. seq_number: LOCAL_SEQ + 1,
  2937. ack_number: Some(REMOTE_SEQ + 1),
  2938. payload: &b"abcdef"[..],
  2939. ..RECV_TEMPL
  2940. }));
  2941. assert_eq!(s.poll_at(), Some(455));
  2942. recv!(s, time 500, Ok(TcpRepr {
  2943. control: TcpControl::Rst,
  2944. seq_number: LOCAL_SEQ + 1 + 6,
  2945. ack_number: Some(REMOTE_SEQ + 1),
  2946. ..RECV_TEMPL
  2947. }));
  2948. assert_eq!(s.state, State::Closed);
  2949. }
  2950. #[test]
  2951. fn test_established_keep_alive_timeout() {
  2952. let mut s = socket_established();
  2953. s.set_keep_alive(Some(50));
  2954. s.set_timeout(Some(100));
  2955. recv!(s, time 100, Ok(TcpRepr {
  2956. seq_number: LOCAL_SEQ,
  2957. ack_number: Some(REMOTE_SEQ + 1),
  2958. payload: &[0],
  2959. ..RECV_TEMPL
  2960. }));
  2961. recv!(s, time 100, Err(Error::Exhausted));
  2962. assert_eq!(s.poll_at(), Some(150));
  2963. send!(s, time 105, TcpRepr {
  2964. seq_number: REMOTE_SEQ + 1,
  2965. ack_number: Some(LOCAL_SEQ + 1),
  2966. ..SEND_TEMPL
  2967. });
  2968. assert_eq!(s.poll_at(), Some(155));
  2969. recv!(s, time 155, Ok(TcpRepr {
  2970. seq_number: LOCAL_SEQ,
  2971. ack_number: Some(REMOTE_SEQ + 1),
  2972. payload: &[0],
  2973. ..RECV_TEMPL
  2974. }));
  2975. recv!(s, time 155, Err(Error::Exhausted));
  2976. assert_eq!(s.poll_at(), Some(205));
  2977. recv!(s, time 200, Err(Error::Exhausted));
  2978. recv!(s, time 205, Ok(TcpRepr {
  2979. control: TcpControl::Rst,
  2980. seq_number: LOCAL_SEQ + 1,
  2981. ack_number: Some(REMOTE_SEQ + 1),
  2982. ..RECV_TEMPL
  2983. }));
  2984. recv!(s, time 205, Err(Error::Exhausted));
  2985. assert_eq!(s.state, State::Closed);
  2986. }
  2987. #[test]
  2988. fn test_fin_wait_1_timeout() {
  2989. let mut s = socket_fin_wait_1();
  2990. s.set_timeout(Some(200));
  2991. recv!(s, time 100, Ok(TcpRepr {
  2992. control: TcpControl::Fin,
  2993. seq_number: LOCAL_SEQ + 1,
  2994. ack_number: Some(REMOTE_SEQ + 1),
  2995. ..RECV_TEMPL
  2996. }));
  2997. assert_eq!(s.poll_at(), Some(200));
  2998. recv!(s, time 400, Ok(TcpRepr {
  2999. control: TcpControl::Rst,
  3000. seq_number: LOCAL_SEQ + 1 + 1,
  3001. ack_number: Some(REMOTE_SEQ + 1),
  3002. ..RECV_TEMPL
  3003. }));
  3004. assert_eq!(s.state, State::Closed);
  3005. }
  3006. #[test]
  3007. fn test_last_ack_timeout() {
  3008. let mut s = socket_last_ack();
  3009. s.set_timeout(Some(200));
  3010. recv!(s, time 100, Ok(TcpRepr {
  3011. control: TcpControl::Fin,
  3012. seq_number: LOCAL_SEQ + 1,
  3013. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3014. ..RECV_TEMPL
  3015. }));
  3016. assert_eq!(s.poll_at(), Some(200));
  3017. recv!(s, time 400, Ok(TcpRepr {
  3018. control: TcpControl::Rst,
  3019. seq_number: LOCAL_SEQ + 1 + 1,
  3020. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3021. ..RECV_TEMPL
  3022. }));
  3023. assert_eq!(s.state, State::Closed);
  3024. }
  3025. #[test]
  3026. fn test_closed_timeout() {
  3027. let mut s = socket_established();
  3028. s.set_timeout(Some(200));
  3029. s.remote_last_ts = Some(100);
  3030. s.abort();
  3031. assert_eq!(s.poll_at(), Some(0));
  3032. recv!(s, time 100, Ok(TcpRepr {
  3033. control: TcpControl::Rst,
  3034. seq_number: LOCAL_SEQ + 1,
  3035. ack_number: Some(REMOTE_SEQ + 1),
  3036. ..RECV_TEMPL
  3037. }));
  3038. assert_eq!(s.poll_at(), None);
  3039. }
  3040. // =========================================================================================//
  3041. // Tests for keep-alive.
  3042. // =========================================================================================//
  3043. #[test]
  3044. fn test_responds_to_keep_alive() {
  3045. let mut s = socket_established();
  3046. send!(s, TcpRepr {
  3047. seq_number: REMOTE_SEQ,
  3048. ack_number: Some(LOCAL_SEQ + 1),
  3049. ..SEND_TEMPL
  3050. }, Ok(Some(TcpRepr {
  3051. seq_number: LOCAL_SEQ + 1,
  3052. ack_number: Some(REMOTE_SEQ + 1),
  3053. ..RECV_TEMPL
  3054. })));
  3055. }
  3056. #[test]
  3057. fn test_sends_keep_alive() {
  3058. let mut s = socket_established();
  3059. s.set_keep_alive(Some(100));
  3060. // drain the forced keep-alive packet
  3061. assert_eq!(s.poll_at(), Some(0));
  3062. recv!(s, time 0, Ok(TcpRepr {
  3063. seq_number: LOCAL_SEQ,
  3064. ack_number: Some(REMOTE_SEQ + 1),
  3065. payload: &[0],
  3066. ..RECV_TEMPL
  3067. }));
  3068. assert_eq!(s.poll_at(), Some(100));
  3069. recv!(s, time 95, Err(Error::Exhausted));
  3070. recv!(s, time 100, Ok(TcpRepr {
  3071. seq_number: LOCAL_SEQ,
  3072. ack_number: Some(REMOTE_SEQ + 1),
  3073. payload: &[0],
  3074. ..RECV_TEMPL
  3075. }));
  3076. assert_eq!(s.poll_at(), Some(200));
  3077. recv!(s, time 195, Err(Error::Exhausted));
  3078. recv!(s, time 200, Ok(TcpRepr {
  3079. seq_number: LOCAL_SEQ,
  3080. ack_number: Some(REMOTE_SEQ + 1),
  3081. payload: &[0],
  3082. ..RECV_TEMPL
  3083. }));
  3084. send!(s, time 250, TcpRepr {
  3085. seq_number: REMOTE_SEQ + 1,
  3086. ack_number: Some(LOCAL_SEQ + 1),
  3087. ..SEND_TEMPL
  3088. });
  3089. assert_eq!(s.poll_at(), Some(350));
  3090. recv!(s, time 345, Err(Error::Exhausted));
  3091. recv!(s, time 350, Ok(TcpRepr {
  3092. seq_number: LOCAL_SEQ,
  3093. ack_number: Some(REMOTE_SEQ + 1),
  3094. payload: &b"\x00"[..],
  3095. ..RECV_TEMPL
  3096. }));
  3097. }
  3098. // =========================================================================================//
  3099. // Tests for reassembly.
  3100. // =========================================================================================//
  3101. #[test]
  3102. fn test_out_of_order() {
  3103. let mut s = socket_established();
  3104. send!(s, TcpRepr {
  3105. seq_number: REMOTE_SEQ + 1 + 3,
  3106. ack_number: Some(LOCAL_SEQ + 1),
  3107. payload: &b"def"[..],
  3108. ..SEND_TEMPL
  3109. }, Ok(Some(TcpRepr {
  3110. seq_number: LOCAL_SEQ + 1,
  3111. ack_number: Some(REMOTE_SEQ + 1),
  3112. ..RECV_TEMPL
  3113. })));
  3114. assert_eq!(s.recv(10), Ok(&b""[..]));
  3115. send!(s, TcpRepr {
  3116. seq_number: REMOTE_SEQ + 1,
  3117. ack_number: Some(LOCAL_SEQ + 1),
  3118. payload: &b"abcdef"[..],
  3119. ..SEND_TEMPL
  3120. }, Ok(Some(TcpRepr {
  3121. seq_number: LOCAL_SEQ + 1,
  3122. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3123. window_len: 58,
  3124. ..RECV_TEMPL
  3125. })));
  3126. assert_eq!(s.recv(10), Ok(&b"abcdef"[..]));
  3127. }
  3128. #[test]
  3129. fn test_buffer_wraparound() {
  3130. let mut s = socket_established();
  3131. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3132. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3133. send!(s, TcpRepr {
  3134. seq_number: REMOTE_SEQ + 1,
  3135. ack_number: Some(LOCAL_SEQ + 1),
  3136. payload: &b"abc"[..],
  3137. ..SEND_TEMPL
  3138. });
  3139. assert_eq!(s.recv(3), Ok(&b"abc"[..]));
  3140. send!(s, TcpRepr {
  3141. seq_number: REMOTE_SEQ + 1 + 3,
  3142. ack_number: Some(LOCAL_SEQ + 1),
  3143. payload: &b"defghi"[..],
  3144. ..SEND_TEMPL
  3145. });
  3146. let mut data = [0; 6];
  3147. assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
  3148. assert_eq!(data, &b"defghi"[..]);
  3149. }
  3150. // =========================================================================================//
  3151. // Tests for packet filtering.
  3152. // =========================================================================================//
  3153. #[test]
  3154. fn test_doesnt_accept_wrong_port() {
  3155. let mut s = socket_established();
  3156. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3157. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3158. let tcp_repr = TcpRepr {
  3159. seq_number: REMOTE_SEQ + 1,
  3160. ack_number: Some(LOCAL_SEQ + 1),
  3161. dst_port: LOCAL_PORT + 1,
  3162. ..SEND_TEMPL
  3163. };
  3164. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  3165. let tcp_repr = TcpRepr {
  3166. seq_number: REMOTE_SEQ + 1,
  3167. ack_number: Some(LOCAL_SEQ + 1),
  3168. src_port: REMOTE_PORT + 1,
  3169. ..SEND_TEMPL
  3170. };
  3171. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  3172. }
  3173. #[test]
  3174. fn test_doesnt_accept_wrong_ip() {
  3175. let s = socket_established();
  3176. let tcp_repr = TcpRepr {
  3177. seq_number: REMOTE_SEQ + 1,
  3178. ack_number: Some(LOCAL_SEQ + 1),
  3179. payload: &b"abcdef"[..],
  3180. ..SEND_TEMPL
  3181. };
  3182. let ip_repr = IpRepr::Unspecified {
  3183. src_addr: REMOTE_IP,
  3184. dst_addr: LOCAL_IP,
  3185. protocol: IpProtocol::Tcp,
  3186. payload_len: tcp_repr.buffer_len()
  3187. };
  3188. assert!(s.accepts(&ip_repr, &tcp_repr));
  3189. let ip_repr_wrong_src = IpRepr::Unspecified {
  3190. src_addr: OTHER_IP,
  3191. dst_addr: LOCAL_IP,
  3192. protocol: IpProtocol::Tcp,
  3193. payload_len: tcp_repr.buffer_len()
  3194. };
  3195. assert!(!s.accepts(&ip_repr_wrong_src, &tcp_repr));
  3196. let ip_repr_wrong_dst = IpRepr::Unspecified {
  3197. src_addr: REMOTE_IP,
  3198. dst_addr: OTHER_IP,
  3199. protocol: IpProtocol::Tcp,
  3200. payload_len: tcp_repr.buffer_len()
  3201. };
  3202. assert!(!s.accepts(&ip_repr_wrong_dst, &tcp_repr));
  3203. }
  3204. }