tcp.rs 181 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076
  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, mem};
  5. #[cfg(feature = "async")]
  6. use core::task::Waker;
  7. use crate::{Error, Result};
  8. use crate::phy::DeviceCapabilities;
  9. use crate::time::{Duration, Instant};
  10. use crate::socket::{Socket, SocketMeta, SocketHandle, PollAt};
  11. use crate::storage::{Assembler, RingBuffer};
  12. #[cfg(feature = "async")]
  13. use crate::socket::WakerRegistration;
  14. use crate::wire::{IpProtocol, IpRepr, IpAddress, IpEndpoint, TcpSeqNumber, TcpRepr, TcpControl};
  15. /// A TCP socket ring buffer.
  16. pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
  17. /// The state of a TCP socket, according to [RFC 793].
  18. ///
  19. /// [RFC 793]: https://tools.ietf.org/html/rfc793
  20. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  21. pub enum State {
  22. Closed,
  23. Listen,
  24. SynSent,
  25. SynReceived,
  26. Established,
  27. FinWait1,
  28. FinWait2,
  29. CloseWait,
  30. Closing,
  31. LastAck,
  32. TimeWait
  33. }
  34. impl fmt::Display for State {
  35. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  36. match *self {
  37. State::Closed => write!(f, "CLOSED"),
  38. State::Listen => write!(f, "LISTEN"),
  39. State::SynSent => write!(f, "SYN-SENT"),
  40. State::SynReceived => write!(f, "SYN-RECEIVED"),
  41. State::Established => write!(f, "ESTABLISHED"),
  42. State::FinWait1 => write!(f, "FIN-WAIT-1"),
  43. State::FinWait2 => write!(f, "FIN-WAIT-2"),
  44. State::CloseWait => write!(f, "CLOSE-WAIT"),
  45. State::Closing => write!(f, "CLOSING"),
  46. State::LastAck => write!(f, "LAST-ACK"),
  47. State::TimeWait => write!(f, "TIME-WAIT")
  48. }
  49. }
  50. }
  51. #[derive(Debug, Clone, Copy, PartialEq)]
  52. enum Timer {
  53. Idle {
  54. keep_alive_at: Option<Instant>,
  55. },
  56. Retransmit {
  57. expires_at: Instant,
  58. delay: Duration
  59. },
  60. FastRetransmit,
  61. Close {
  62. expires_at: Instant
  63. }
  64. }
  65. const RETRANSMIT_DELAY: Duration = Duration { millis: 100 };
  66. const CLOSE_DELAY: Duration = Duration { millis: 10_000 };
  67. impl Default for Timer {
  68. fn default() -> Timer {
  69. Timer::Idle { keep_alive_at: None }
  70. }
  71. }
  72. impl Timer {
  73. fn should_keep_alive(&self, timestamp: Instant) -> bool {
  74. match *self {
  75. Timer::Idle { keep_alive_at: Some(keep_alive_at) }
  76. if timestamp >= keep_alive_at => {
  77. true
  78. }
  79. _ => false
  80. }
  81. }
  82. fn should_retransmit(&self, timestamp: Instant) -> Option<Duration> {
  83. match *self {
  84. Timer::Retransmit { expires_at, delay }
  85. if timestamp >= expires_at => {
  86. Some(timestamp - expires_at + delay)
  87. },
  88. Timer::FastRetransmit => Some(Duration::from_millis(0)),
  89. _ => None
  90. }
  91. }
  92. fn should_close(&self, timestamp: Instant) -> bool {
  93. match *self {
  94. Timer::Close { expires_at }
  95. if timestamp >= expires_at => {
  96. true
  97. }
  98. _ => false
  99. }
  100. }
  101. fn poll_at(&self) -> PollAt {
  102. match *self {
  103. Timer::Idle { keep_alive_at: Some(keep_alive_at) } => PollAt::Time(keep_alive_at),
  104. Timer::Idle { keep_alive_at: None } => PollAt::Ingress,
  105. Timer::Retransmit { expires_at, .. } => PollAt::Time(expires_at),
  106. Timer::FastRetransmit => PollAt::Now,
  107. Timer::Close { expires_at } => PollAt::Time(expires_at),
  108. }
  109. }
  110. fn set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>) {
  111. *self = Timer::Idle {
  112. keep_alive_at: interval.map(|interval| timestamp + interval)
  113. }
  114. }
  115. fn set_keep_alive(&mut self) {
  116. match *self {
  117. Timer::Idle { ref mut keep_alive_at }
  118. if keep_alive_at.is_none() => {
  119. *keep_alive_at = Some(Instant::from_millis(0))
  120. }
  121. _ => ()
  122. }
  123. }
  124. fn rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>) {
  125. match self {
  126. &mut Timer::Idle { ref mut keep_alive_at } => {
  127. *keep_alive_at = interval.map(|interval| timestamp + interval)
  128. }
  129. _ => ()
  130. }
  131. }
  132. fn set_for_retransmit(&mut self, timestamp: Instant) {
  133. match *self {
  134. Timer::Idle { .. } | Timer::FastRetransmit { .. } => {
  135. *self = Timer::Retransmit {
  136. expires_at: timestamp + RETRANSMIT_DELAY,
  137. delay: RETRANSMIT_DELAY,
  138. }
  139. }
  140. Timer::Retransmit { expires_at, delay }
  141. if timestamp >= expires_at => {
  142. *self = Timer::Retransmit {
  143. expires_at: timestamp + delay,
  144. delay: delay * 2
  145. }
  146. }
  147. Timer::Retransmit { .. } => (),
  148. Timer::Close { .. } => ()
  149. }
  150. }
  151. fn set_for_fast_retransmit(&mut self) {
  152. *self = Timer::FastRetransmit
  153. }
  154. fn set_for_close(&mut self, timestamp: Instant) {
  155. *self = Timer::Close {
  156. expires_at: timestamp + CLOSE_DELAY
  157. }
  158. }
  159. fn is_retransmit(&self) -> bool {
  160. match *self {
  161. Timer::Retransmit {..} | Timer::FastRetransmit => true,
  162. _ => false,
  163. }
  164. }
  165. }
  166. /// A Transmission Control Protocol socket.
  167. ///
  168. /// A TCP socket may passively listen for connections or actively connect to another endpoint.
  169. /// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
  170. /// accept several connections, as many sockets must be allocated, or any new connection
  171. /// attempts will be reset.
  172. #[derive(Debug)]
  173. pub struct TcpSocket<'a> {
  174. pub(crate) meta: SocketMeta,
  175. state: State,
  176. timer: Timer,
  177. assembler: Assembler,
  178. rx_buffer: SocketBuffer<'a>,
  179. rx_fin_received: bool,
  180. tx_buffer: SocketBuffer<'a>,
  181. /// Interval after which, if no inbound packets are received, the connection is aborted.
  182. timeout: Option<Duration>,
  183. /// Interval at which keep-alive packets will be sent.
  184. keep_alive: Option<Duration>,
  185. /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  186. hop_limit: Option<u8>,
  187. /// Address passed to listen(). Listen address is set when listen() is called and
  188. /// used every time the socket is reset back to the LISTEN state.
  189. listen_address: IpAddress,
  190. /// Current local endpoint. This is used for both filtering the incoming packets and
  191. /// setting the source address. When listening or initiating connection on/from
  192. /// an unspecified address, this field is updated with the chosen source address before
  193. /// any packets are sent.
  194. local_endpoint: IpEndpoint,
  195. /// Current remote endpoint. This is used for both filtering the incoming packets and
  196. /// setting the destination address. If the remote endpoint is unspecified, it means that
  197. /// aborting the connection will not send an RST, and, in TIME-WAIT state, will not
  198. /// send an ACK.
  199. remote_endpoint: IpEndpoint,
  200. /// The sequence number corresponding to the beginning of the transmit buffer.
  201. /// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
  202. local_seq_no: TcpSeqNumber,
  203. /// The sequence number corresponding to the beginning of the receive buffer.
  204. /// I.e. userspace reading n bytes adds n to remote_seq_no.
  205. remote_seq_no: TcpSeqNumber,
  206. /// The last sequence number sent.
  207. /// I.e. in an idle socket, local_seq_no+tx_buffer.len().
  208. remote_last_seq: TcpSeqNumber,
  209. /// The last acknowledgement number sent.
  210. /// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
  211. remote_last_ack: Option<TcpSeqNumber>,
  212. /// The last window length sent.
  213. remote_last_win: u16,
  214. /// The sending window scaling factor advertised to remotes which support RFC 1323.
  215. /// It is zero if the window <= 64KiB and/or the remote does not support it.
  216. remote_win_shift: u8,
  217. /// The remote window size, relative to local_seq_no
  218. /// I.e. we're allowed to send octets until local_seq_no+remote_win_len
  219. remote_win_len: usize,
  220. /// The receive window scaling factor for remotes which support RFC 1323, None if unsupported.
  221. remote_win_scale: Option<u8>,
  222. /// Whether or not the remote supports selective ACK as described in RFC 2018.
  223. remote_has_sack: bool,
  224. /// The maximum number of data octets that the remote side may receive.
  225. remote_mss: usize,
  226. /// The timestamp of the last packet received.
  227. remote_last_ts: Option<Instant>,
  228. /// The sequence number of the last packet recived, used for sACK
  229. local_rx_last_seq: Option<TcpSeqNumber>,
  230. /// The ACK number of the last packet recived.
  231. local_rx_last_ack: Option<TcpSeqNumber>,
  232. /// The number of packets recived directly after
  233. /// each other which have the same ACK number.
  234. local_rx_dup_acks: u8,
  235. #[cfg(feature = "async")]
  236. rx_waker: WakerRegistration,
  237. #[cfg(feature = "async")]
  238. tx_waker: WakerRegistration,
  239. }
  240. const DEFAULT_MSS: usize = 536;
  241. impl<'a> TcpSocket<'a> {
  242. #[allow(unused_comparisons)] // small usize platforms always pass rx_capacity check
  243. /// Create a socket using the given buffers.
  244. pub fn new<T>(rx_buffer: T, tx_buffer: T) -> TcpSocket<'a>
  245. where T: Into<SocketBuffer<'a>> {
  246. let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
  247. let rx_capacity = rx_buffer.capacity();
  248. // From RFC 1323:
  249. // [...] the above constraints imply that 2 * the max window size must be less
  250. // than 2**31 [...] Thus, the shift count must be limited to 14 (which allows
  251. // windows of 2**30 = 1 Gbyte).
  252. if rx_capacity > (1 << 30) {
  253. panic!("receiving buffer too large, cannot exceed 1 GiB")
  254. }
  255. let rx_cap_log2 = mem::size_of::<usize>() * 8 -
  256. rx_capacity.leading_zeros() as usize;
  257. TcpSocket {
  258. meta: SocketMeta::default(),
  259. state: State::Closed,
  260. timer: Timer::default(),
  261. assembler: Assembler::new(rx_buffer.capacity()),
  262. tx_buffer: tx_buffer,
  263. rx_buffer: rx_buffer,
  264. rx_fin_received: false,
  265. timeout: None,
  266. keep_alive: None,
  267. hop_limit: None,
  268. listen_address: IpAddress::default(),
  269. local_endpoint: IpEndpoint::default(),
  270. remote_endpoint: IpEndpoint::default(),
  271. local_seq_no: TcpSeqNumber::default(),
  272. remote_seq_no: TcpSeqNumber::default(),
  273. remote_last_seq: TcpSeqNumber::default(),
  274. remote_last_ack: None,
  275. remote_last_win: 0,
  276. remote_win_len: 0,
  277. remote_win_shift: rx_cap_log2.saturating_sub(16) as u8,
  278. remote_win_scale: None,
  279. remote_has_sack: false,
  280. remote_mss: DEFAULT_MSS,
  281. remote_last_ts: None,
  282. local_rx_last_ack: None,
  283. local_rx_last_seq: None,
  284. local_rx_dup_acks: 0,
  285. #[cfg(feature = "async")]
  286. rx_waker: WakerRegistration::new(),
  287. #[cfg(feature = "async")]
  288. tx_waker: WakerRegistration::new(),
  289. }
  290. }
  291. /// Register a waker for receive operations.
  292. ///
  293. /// The waker is woken on state changes that might affect the return value
  294. /// of `recv` method calls, such as receiving data, or the socket closing.
  295. ///
  296. /// Notes:
  297. ///
  298. /// - Only one waker can be registered at a time. If another waker was previously registered,
  299. /// it is overwritten and will no longer be woken.
  300. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  301. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
  302. /// necessarily changed.
  303. #[cfg(feature = "async")]
  304. pub fn register_recv_waker(&mut self, waker: &Waker) {
  305. self.rx_waker.register(waker)
  306. }
  307. /// Register a waker for send operations.
  308. ///
  309. /// The waker is woken on state changes that might affect the return value
  310. /// of `send` method calls, such as space becoming available in the transmit
  311. /// buffer, or the socket closing.
  312. ///
  313. /// Notes:
  314. ///
  315. /// - Only one waker can be registered at a time. If another waker was previously registered,
  316. /// it is overwritten and will no longer be woken.
  317. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  318. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
  319. /// necessarily changed.
  320. #[cfg(feature = "async")]
  321. pub fn register_send_waker(&mut self, waker: &Waker) {
  322. self.tx_waker.register(waker)
  323. }
  324. /// Return the socket handle.
  325. #[inline]
  326. pub fn handle(&self) -> SocketHandle {
  327. self.meta.handle
  328. }
  329. /// Return the timeout duration.
  330. ///
  331. /// See also the [set_timeout](#method.set_timeout) method.
  332. pub fn timeout(&self) -> Option<Duration> {
  333. self.timeout
  334. }
  335. /// Return the current window field value, including scaling according to RFC 1323.
  336. ///
  337. /// Used in internal calculations as well as packet generation.
  338. ///
  339. #[inline]
  340. fn scaled_window(&self) -> u16 {
  341. cmp::min(self.rx_buffer.window() >> self.remote_win_shift as usize,
  342. (1 << 16) - 1) as u16
  343. }
  344. /// Set the timeout duration.
  345. ///
  346. /// A socket with a timeout duration set will abort the connection if either of the following
  347. /// occurs:
  348. ///
  349. /// * After a [connect](#method.connect) call, the remote endpoint does not respond within
  350. /// the specified duration;
  351. /// * After establishing a connection, there is data in the transmit buffer and the remote
  352. /// endpoint exceeds the specified duration between any two packets it sends;
  353. /// * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
  354. /// the specified duration between any two packets it sends.
  355. pub fn set_timeout(&mut self, duration: Option<Duration>) {
  356. self.timeout = duration
  357. }
  358. /// Return the keep-alive interval.
  359. ///
  360. /// See also the [set_keep_alive](#method.set_keep_alive) method.
  361. pub fn keep_alive(&self) -> Option<Duration> {
  362. self.keep_alive
  363. }
  364. /// Set the keep-alive interval.
  365. ///
  366. /// An idle socket with a keep-alive interval set will transmit a "challenge ACK" packet
  367. /// every time it receives no communication during that interval. As a result, three things
  368. /// may happen:
  369. ///
  370. /// * The remote endpoint is fine and answers with an ACK packet.
  371. /// * The remote endpoint has rebooted and answers with an RST packet.
  372. /// * The remote endpoint has crashed and does not answer.
  373. ///
  374. /// The keep-alive functionality together with the timeout functionality allows to react
  375. /// to these error conditions.
  376. pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
  377. self.keep_alive = interval;
  378. if self.keep_alive.is_some() {
  379. // If the connection is idle and we've just set the option, it would not take effect
  380. // until the next packet, unless we wind up the timer explicitly.
  381. self.timer.set_keep_alive();
  382. }
  383. }
  384. /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  385. ///
  386. /// See also the [set_hop_limit](#method.set_hop_limit) method
  387. pub fn hop_limit(&self) -> Option<u8> {
  388. self.hop_limit
  389. }
  390. /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  391. ///
  392. /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
  393. /// value (64).
  394. ///
  395. /// # Panics
  396. ///
  397. /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
  398. ///
  399. /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
  400. /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
  401. pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
  402. // A host MUST NOT send a datagram with a hop limit value of 0
  403. if let Some(0) = hop_limit {
  404. panic!("the time-to-live value of a packet must not be zero")
  405. }
  406. self.hop_limit = hop_limit
  407. }
  408. /// Return the local endpoint.
  409. #[inline]
  410. pub fn local_endpoint(&self) -> IpEndpoint {
  411. self.local_endpoint
  412. }
  413. /// Return the remote endpoint.
  414. #[inline]
  415. pub fn remote_endpoint(&self) -> IpEndpoint {
  416. self.remote_endpoint
  417. }
  418. /// Return the connection state, in terms of the TCP state machine.
  419. #[inline]
  420. pub fn state(&self) -> State {
  421. self.state
  422. }
  423. fn reset(&mut self) {
  424. let rx_cap_log2 = mem::size_of::<usize>() * 8 -
  425. self.rx_buffer.capacity().leading_zeros() as usize;
  426. self.state = State::Closed;
  427. self.timer = Timer::default();
  428. self.assembler = Assembler::new(self.rx_buffer.capacity());
  429. self.tx_buffer.clear();
  430. self.rx_buffer.clear();
  431. self.rx_fin_received = false;
  432. self.keep_alive = None;
  433. self.timeout = None;
  434. self.hop_limit = None;
  435. self.listen_address = IpAddress::default();
  436. self.local_endpoint = IpEndpoint::default();
  437. self.remote_endpoint = IpEndpoint::default();
  438. self.local_seq_no = TcpSeqNumber::default();
  439. self.remote_seq_no = TcpSeqNumber::default();
  440. self.remote_last_seq = TcpSeqNumber::default();
  441. self.remote_last_ack = None;
  442. self.remote_last_win = 0;
  443. self.remote_win_len = 0;
  444. self.remote_win_scale = None;
  445. self.remote_win_shift = rx_cap_log2.saturating_sub(16) as u8;
  446. self.remote_mss = DEFAULT_MSS;
  447. self.remote_last_ts = None;
  448. #[cfg(feature = "async")]
  449. {
  450. self.rx_waker.wake();
  451. self.tx_waker.wake();
  452. }
  453. }
  454. /// Start listening on the given endpoint.
  455. ///
  456. /// This function returns `Err(Error::Illegal)` if the socket was already open
  457. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  458. /// if the port in the given endpoint is zero.
  459. pub fn listen<T>(&mut self, local_endpoint: T) -> Result<()>
  460. where T: Into<IpEndpoint> {
  461. let local_endpoint = local_endpoint.into();
  462. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  463. if self.is_open() { return Err(Error::Illegal) }
  464. self.reset();
  465. self.listen_address = local_endpoint.addr;
  466. self.local_endpoint = local_endpoint;
  467. self.remote_endpoint = IpEndpoint::default();
  468. self.set_state(State::Listen);
  469. Ok(())
  470. }
  471. /// Connect to a given endpoint.
  472. ///
  473. /// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
  474. /// allocates a port between 49152 and 65535, a connection may be established as follows:
  475. ///
  476. /// ```rust,ignore
  477. /// socket.connect((IpAddress::v4(10, 0, 0, 1), 80), get_ephemeral_port())
  478. /// ```
  479. ///
  480. /// The local address may optionally be provided.
  481. ///
  482. /// This function returns an error if the socket was open; see [is_open](#method.is_open).
  483. /// It also returns an error if the local or remote port is zero, or if the remote address
  484. /// is unspecified.
  485. pub fn connect<T, U>(&mut self, remote_endpoint: T, local_endpoint: U) -> Result<()>
  486. where T: Into<IpEndpoint>, U: Into<IpEndpoint> {
  487. let remote_endpoint = remote_endpoint.into();
  488. let local_endpoint = local_endpoint.into();
  489. if self.is_open() { return Err(Error::Illegal) }
  490. if !remote_endpoint.is_specified() { return Err(Error::Unaddressable) }
  491. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  492. // If local address is not provided, use an unspecified address but a specified protocol.
  493. // This lets us lower IpRepr later to determine IP header size and calculate MSS,
  494. // but without committing to a specific address right away.
  495. let local_addr = match local_endpoint.addr {
  496. IpAddress::Unspecified => remote_endpoint.addr.to_unspecified(),
  497. ip => ip,
  498. };
  499. let local_endpoint = IpEndpoint { addr: local_addr, ..local_endpoint };
  500. // Carry over the local sequence number.
  501. let local_seq_no = self.local_seq_no;
  502. self.reset();
  503. self.local_endpoint = local_endpoint;
  504. self.remote_endpoint = remote_endpoint;
  505. self.local_seq_no = local_seq_no;
  506. self.remote_last_seq = local_seq_no;
  507. self.set_state(State::SynSent);
  508. Ok(())
  509. }
  510. /// Close the transmit half of the full-duplex connection.
  511. ///
  512. /// Note that there is no corresponding function for the receive half of the full-duplex
  513. /// connection; only the remote end can close it. If you no longer wish to receive any
  514. /// data and would like to reuse the socket right away, use [abort](#method.abort).
  515. pub fn close(&mut self) {
  516. match self.state {
  517. // In the LISTEN state there is no established connection.
  518. State::Listen =>
  519. self.set_state(State::Closed),
  520. // In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
  521. // receiving an RST, will abort the connection.
  522. State::SynSent =>
  523. self.set_state(State::Closed),
  524. // In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
  525. // of the connection is open, and needs to be explicitly closed with a FIN.
  526. State::SynReceived | State::Established =>
  527. self.set_state(State::FinWait1),
  528. State::CloseWait =>
  529. self.set_state(State::LastAck),
  530. // In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
  531. // the transmit half of the connection is already closed, and no further
  532. // action is needed.
  533. State::FinWait1 | State::FinWait2 | State::Closing |
  534. State::TimeWait | State::LastAck | State::Closed => ()
  535. }
  536. }
  537. /// Aborts the connection, if any.
  538. ///
  539. /// This function instantly closes the socket. One reset packet will be sent to the remote
  540. /// endpoint.
  541. ///
  542. /// In terms of the TCP state machine, the socket may be in any state and is moved to
  543. /// the `CLOSED` state.
  544. pub fn abort(&mut self) {
  545. self.set_state(State::Closed);
  546. }
  547. /// Return whether the socket is passively listening for incoming connections.
  548. ///
  549. /// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
  550. #[inline]
  551. pub fn is_listening(&self) -> bool {
  552. match self.state {
  553. State::Listen => true,
  554. _ => false
  555. }
  556. }
  557. /// Return whether the socket is open.
  558. ///
  559. /// This function returns true if the socket will process incoming or dispatch outgoing
  560. /// packets. Note that this does not mean that it is possible to send or receive data through
  561. /// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
  562. ///
  563. /// In terms of the TCP state machine, the socket must not be in the `CLOSED`
  564. /// or `TIME-WAIT` states.
  565. #[inline]
  566. pub fn is_open(&self) -> bool {
  567. match self.state {
  568. State::Closed => false,
  569. State::TimeWait => false,
  570. _ => true
  571. }
  572. }
  573. /// Return whether a connection is active.
  574. ///
  575. /// This function returns true if the socket is actively exchanging packets with
  576. /// a remote endpoint. Note that this does not mean that it is possible to send or receive
  577. /// data through the socket; for that, use [can_send](#method.can_send) or
  578. /// [can_recv](#method.can_recv).
  579. ///
  580. /// If a connection is established, [abort](#method.close) will send a reset to
  581. /// the remote endpoint.
  582. ///
  583. /// In terms of the TCP state machine, the socket must be in the `CLOSED`, `TIME-WAIT`,
  584. /// or `LISTEN` state.
  585. #[inline]
  586. pub fn is_active(&self) -> bool {
  587. match self.state {
  588. State::Closed => false,
  589. State::TimeWait => false,
  590. State::Listen => false,
  591. _ => true
  592. }
  593. }
  594. /// Return whether the transmit half of the full-duplex connection is open.
  595. ///
  596. /// This function returns true if it's possible to send data and have it arrive
  597. /// to the remote endpoint. However, it does not make any guarantees about the state
  598. /// of the transmit buffer, and even if it returns true, [send](#method.send) may
  599. /// not be able to enqueue any octets.
  600. ///
  601. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
  602. /// `CLOSE-WAIT` state.
  603. #[inline]
  604. pub fn may_send(&self) -> bool {
  605. match self.state {
  606. State::Established => true,
  607. // In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
  608. // but we still can transmit indefinitely.
  609. State::CloseWait => true,
  610. _ => false
  611. }
  612. }
  613. /// Return whether the receive half of the full-duplex connection is open.
  614. ///
  615. /// This function returns true if it's possible to receive data from the remote endpoint.
  616. /// It will return true while there is data in the receive buffer, and if there isn't,
  617. /// as long as the remote endpoint has not closed the connection.
  618. ///
  619. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
  620. /// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
  621. #[inline]
  622. pub fn may_recv(&self) -> bool {
  623. match self.state {
  624. State::Established => true,
  625. // In FIN-WAIT-1/2, we have closed our transmit half of the connection but
  626. // we still can receive indefinitely.
  627. State::FinWait1 | State::FinWait2 => true,
  628. // If we have something in the receive buffer, we can receive that.
  629. _ if self.rx_buffer.len() > 0 => true,
  630. _ => false
  631. }
  632. }
  633. /// Check whether the transmit half of the full-duplex connection is open
  634. /// (see [may_send](#method.may_send), and the transmit buffer is not full.
  635. #[inline]
  636. pub fn can_send(&self) -> bool {
  637. if !self.may_send() { return false }
  638. !self.tx_buffer.is_full()
  639. }
  640. /// Return the maximum number of bytes inside the recv buffer.
  641. #[inline]
  642. pub fn recv_capacity(&self) -> usize {
  643. self.rx_buffer.capacity()
  644. }
  645. /// Return the maximum number of bytes inside the transmit buffer.
  646. #[inline]
  647. pub fn send_capacity(&self) -> usize {
  648. self.tx_buffer.capacity()
  649. }
  650. /// Check whether the receive half of the full-duplex connection buffer is open
  651. /// (see [may_recv](#method.may_recv), and the receive buffer is not empty.
  652. #[inline]
  653. pub fn can_recv(&self) -> bool {
  654. if !self.may_recv() { return false }
  655. !self.rx_buffer.is_empty()
  656. }
  657. fn send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  658. where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
  659. if !self.may_send() { return Err(Error::Illegal) }
  660. // The connection might have been idle for a long time, and so remote_last_ts
  661. // would be far in the past. Unless we clear it here, we'll abort the connection
  662. // down over in dispatch() by erroneously detecting it as timed out.
  663. if self.tx_buffer.is_empty() { self.remote_last_ts = None }
  664. let _old_length = self.tx_buffer.len();
  665. let (size, result) = f(&mut self.tx_buffer);
  666. if size > 0 {
  667. #[cfg(any(test, feature = "verbose"))]
  668. net_trace!("{}:{}:{}: tx buffer: enqueueing {} octets (now {})",
  669. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  670. size, _old_length + size);
  671. }
  672. Ok(result)
  673. }
  674. /// Call `f` with the largest contiguous slice of octets in the transmit buffer,
  675. /// and enqueue the amount of elements returned by `f`.
  676. ///
  677. /// This function returns `Err(Error::Illegal) if the transmit half of
  678. /// the connection is not open; see [may_send](#method.may_send).
  679. pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R>
  680. where F: FnOnce(&'b mut [u8]) -> (usize, R) {
  681. self.send_impl(|tx_buffer| {
  682. tx_buffer.enqueue_many_with(f)
  683. })
  684. }
  685. /// Enqueue a sequence of octets to be sent, and fill it from a slice.
  686. ///
  687. /// This function returns the amount of octets actually enqueued, which is limited
  688. /// by the amount of free space in the transmit buffer; down to zero.
  689. ///
  690. /// See also [send](#method.send).
  691. pub fn send_slice(&mut self, data: &[u8]) -> Result<usize> {
  692. self.send_impl(|tx_buffer| {
  693. let size = tx_buffer.enqueue_slice(data);
  694. (size, size)
  695. })
  696. }
  697. fn recv_error_check(&mut self) -> Result<()> {
  698. // We may have received some data inside the initial SYN, but until the connection
  699. // is fully open we must not dequeue any data, as it may be overwritten by e.g.
  700. // another (stale) SYN. (We do not support TCP Fast Open.)
  701. if !self.may_recv() {
  702. if self.rx_fin_received {
  703. return Err(Error::Finished)
  704. }
  705. return Err(Error::Illegal)
  706. }
  707. Ok(())
  708. }
  709. fn recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  710. where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
  711. self.recv_error_check()?;
  712. let _old_length = self.rx_buffer.len();
  713. let (size, result) = f(&mut self.rx_buffer);
  714. self.remote_seq_no += size;
  715. if size > 0 {
  716. #[cfg(any(test, feature = "verbose"))]
  717. net_trace!("{}:{}:{}: rx buffer: dequeueing {} octets (now {})",
  718. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  719. size, _old_length - size);
  720. }
  721. Ok(result)
  722. }
  723. /// Call `f` with the largest contiguous slice of octets in the receive buffer,
  724. /// and dequeue the amount of elements returned by `f`.
  725. ///
  726. /// This function errors if the receive half of the connection is not open.
  727. ///
  728. /// If the receive half has been gracefully closed (with a FIN packet), `Err(Error::Finished)`
  729. /// is returned. In this case, the previously received data is guaranteed to be complete.
  730. ///
  731. /// In all other cases, `Err(Error::Illegal)` is returned and previously received data (if any)
  732. /// may be incomplete (truncated).
  733. pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R>
  734. where F: FnOnce(&'b mut [u8]) -> (usize, R) {
  735. self.recv_impl(|rx_buffer| {
  736. rx_buffer.dequeue_many_with(f)
  737. })
  738. }
  739. /// Dequeue a sequence of received octets, and fill a slice from it.
  740. ///
  741. /// This function returns the amount of octets actually dequeued, which is limited
  742. /// by the amount of occupied space in the receive buffer; down to zero.
  743. ///
  744. /// See also [recv](#method.recv).
  745. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  746. self.recv_impl(|rx_buffer| {
  747. let size = rx_buffer.dequeue_slice(data);
  748. (size, size)
  749. })
  750. }
  751. /// Peek at a sequence of received octets without removing them from
  752. /// the receive buffer, and return a pointer to it.
  753. ///
  754. /// This function otherwise behaves identically to [recv](#method.recv).
  755. pub fn peek(&mut self, size: usize) -> Result<&[u8]> {
  756. self.recv_error_check()?;
  757. let buffer = self.rx_buffer.get_allocated(0, size);
  758. if buffer.len() > 0 {
  759. #[cfg(any(test, feature = "verbose"))]
  760. net_trace!("{}:{}:{}: rx buffer: peeking at {} octets",
  761. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  762. buffer.len());
  763. }
  764. Ok(buffer)
  765. }
  766. /// Peek at a sequence of received octets without removing them from
  767. /// the receive buffer, and fill a slice from it.
  768. ///
  769. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  770. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  771. let buffer = self.peek(data.len())?;
  772. let data = &mut data[..buffer.len()];
  773. data.copy_from_slice(buffer);
  774. Ok(buffer.len())
  775. }
  776. /// Return the amount of octets queued in the transmit buffer.
  777. ///
  778. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  779. pub fn send_queue(&self) -> usize {
  780. self.tx_buffer.len()
  781. }
  782. /// Return the amount of octets queued in the receive buffer. This value can be larger than
  783. /// the slice read by the next `recv` or `peek` call because it includes all queued octets,
  784. /// and not only the octets that may be returned as a contiguous slice.
  785. ///
  786. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  787. pub fn recv_queue(&self) -> usize {
  788. self.rx_buffer.len()
  789. }
  790. fn set_state(&mut self, state: State) {
  791. if self.state != state {
  792. if self.remote_endpoint.addr.is_unspecified() {
  793. net_trace!("{}:{}: state={}=>{}",
  794. self.meta.handle, self.local_endpoint,
  795. self.state, state);
  796. } else {
  797. net_trace!("{}:{}:{}: state={}=>{}",
  798. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  799. self.state, state);
  800. }
  801. }
  802. self.state = state;
  803. #[cfg(feature = "async")]
  804. {
  805. // Wake all tasks waiting. Even if we haven't received/sent data, this
  806. // is needed because return values of functions may change depending on the state.
  807. // For example, a pending read has to fail with an error if the socket is closed.
  808. self.rx_waker.wake();
  809. self.tx_waker.wake();
  810. }
  811. }
  812. pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  813. let reply_repr = TcpRepr {
  814. src_port: repr.dst_port,
  815. dst_port: repr.src_port,
  816. control: TcpControl::None,
  817. seq_number: TcpSeqNumber(0),
  818. ack_number: None,
  819. window_len: 0,
  820. window_scale: None,
  821. max_seg_size: None,
  822. sack_permitted: false,
  823. sack_ranges: [None, None, None],
  824. payload: &[]
  825. };
  826. let ip_reply_repr = IpRepr::Unspecified {
  827. src_addr: ip_repr.dst_addr(),
  828. dst_addr: ip_repr.src_addr(),
  829. protocol: IpProtocol::Tcp,
  830. payload_len: reply_repr.buffer_len(),
  831. hop_limit: 64
  832. };
  833. (ip_reply_repr, reply_repr)
  834. }
  835. pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  836. debug_assert!(repr.control != TcpControl::Rst);
  837. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  838. // See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
  839. // of why we sometimes send an RST and sometimes an RST|ACK
  840. reply_repr.control = TcpControl::Rst;
  841. reply_repr.seq_number = repr.ack_number.unwrap_or_default();
  842. if repr.control == TcpControl::Syn {
  843. reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
  844. }
  845. (ip_reply_repr, reply_repr)
  846. }
  847. fn ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  848. let (mut ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  849. // From RFC 793:
  850. // [...] an empty acknowledgment segment containing the current send-sequence number
  851. // and an acknowledgment indicating the next sequence number expected
  852. // to be received.
  853. reply_repr.seq_number = self.remote_last_seq;
  854. reply_repr.ack_number = Some(self.remote_seq_no + self.rx_buffer.len());
  855. self.remote_last_ack = reply_repr.ack_number;
  856. // From RFC 1323:
  857. // The window field [...] of every outgoing segment, with the exception of SYN
  858. // segments, is right-shifted by [advertised scale value] bits[...]
  859. reply_repr.window_len = self.scaled_window();
  860. self.remote_last_win = reply_repr.window_len;
  861. // If the remote supports selective acknowledgement, add the option to the outgoing
  862. // segment.
  863. if self.remote_has_sack {
  864. net_debug!("sending sACK option with current assembler ranges");
  865. // RFC 2018: The first SACK block (i.e., the one immediately following the kind and
  866. // length fields in the option) MUST specify the contiguous block of data containing
  867. // the segment which triggered this ACK, unless that segment advanced the
  868. // Acknowledgment Number field in the header.
  869. reply_repr.sack_ranges[0] = None;
  870. if let Some(last_seg_seq) = self.local_rx_last_seq.map(|s| s.0 as u32) {
  871. reply_repr.sack_ranges[0] = self.assembler.iter_data(
  872. reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
  873. .map(|(left, right)| (left as u32, right as u32))
  874. .skip_while(|(left, right)| *left > last_seg_seq || *right < last_seg_seq)
  875. .next();
  876. }
  877. if reply_repr.sack_ranges[0].is_none() {
  878. // The matching segment was removed from the assembler, meaning the acknowledgement
  879. // number has advanced, or there was no previous sACK.
  880. //
  881. // While the RFC says we SHOULD keep a list of reported sACK ranges, and iterate
  882. // through those, that is currently infeasable. Instead, we offer the range with
  883. // the lowest sequence number (if one exists) to hint at what segments would
  884. // most quickly advance the acknowledgement number.
  885. reply_repr.sack_ranges[0] = self.assembler.iter_data(
  886. reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
  887. .map(|(left, right)| (left as u32, right as u32))
  888. .next();
  889. }
  890. }
  891. // Since the sACK option may have changed the length of the payload, update that.
  892. ip_reply_repr.set_payload_len(reply_repr.buffer_len());
  893. (ip_reply_repr, reply_repr)
  894. }
  895. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
  896. if self.state == State::Closed { return false }
  897. // If we're still listening for SYNs and the packet has an ACK, it cannot
  898. // be destined to this socket, but another one may well listen on the same
  899. // local endpoint.
  900. if self.state == State::Listen && repr.ack_number.is_some() { return false }
  901. // Reject packets with a wrong destination.
  902. if self.local_endpoint.port != repr.dst_port { return false }
  903. if !self.local_endpoint.addr.is_unspecified() &&
  904. self.local_endpoint.addr != ip_repr.dst_addr() { return false }
  905. // Reject packets from a source to which we aren't connected.
  906. if self.remote_endpoint.port != 0 &&
  907. self.remote_endpoint.port != repr.src_port { return false }
  908. if !self.remote_endpoint.addr.is_unspecified() &&
  909. self.remote_endpoint.addr != ip_repr.src_addr() { return false }
  910. true
  911. }
  912. pub(crate) fn process(&mut self, timestamp: Instant, ip_repr: &IpRepr, repr: &TcpRepr) ->
  913. Result<Option<(IpRepr, TcpRepr<'static>)>> {
  914. debug_assert!(self.accepts(ip_repr, repr));
  915. // Consider how much the sequence number space differs from the transmit buffer space.
  916. let (sent_syn, sent_fin) = match self.state {
  917. // In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
  918. State::SynSent | State::SynReceived => (true, false),
  919. // In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
  920. State::FinWait1 | State::LastAck | State::Closing => (false, true),
  921. // In all other states we've already got acknowledgemetns for
  922. // all of the control flags we sent.
  923. _ => (false, false)
  924. };
  925. let control_len = (sent_syn as usize) + (sent_fin as usize);
  926. // Reject unacceptable acknowledgements.
  927. match (self.state, repr) {
  928. // An RST received in response to initial SYN is acceptable if it acknowledges
  929. // the initial SYN.
  930. (State::SynSent, &TcpRepr {
  931. control: TcpControl::Rst, ack_number: None, ..
  932. }) => {
  933. net_debug!("{}:{}:{}: unacceptable RST (expecting RST|ACK) \
  934. in response to initial SYN",
  935. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  936. return Err(Error::Dropped)
  937. }
  938. (State::SynSent, &TcpRepr {
  939. control: TcpControl::Rst, ack_number: Some(ack_number), ..
  940. }) => {
  941. if ack_number != self.local_seq_no + 1 {
  942. net_debug!("{}:{}:{}: unacceptable RST|ACK in response to initial SYN",
  943. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  944. return Err(Error::Dropped)
  945. }
  946. }
  947. // Any other RST need only have a valid sequence number.
  948. (_, &TcpRepr { control: TcpControl::Rst, .. }) => (),
  949. // The initial SYN cannot contain an acknowledgement.
  950. (State::Listen, &TcpRepr { ack_number: None, .. }) => (),
  951. // This case is handled above.
  952. (State::Listen, &TcpRepr { ack_number: Some(_), .. }) => unreachable!(),
  953. // Every packet after the initial SYN must be an acknowledgement.
  954. (_, &TcpRepr { ack_number: None, .. }) => {
  955. net_debug!("{}:{}:{}: expecting an ACK",
  956. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  957. return Err(Error::Dropped)
  958. }
  959. // Any ACK in the SYN-SENT state must have the SYN flag set.
  960. (State::SynSent, &TcpRepr {
  961. control: TcpControl::None, ack_number: Some(_), ..
  962. }) => {
  963. net_debug!("{}:{}:{}: expecting a SYN|ACK",
  964. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  965. self.abort();
  966. return Err(Error::Dropped)
  967. }
  968. // Every acknowledgement must be for transmitted but unacknowledged data.
  969. (_, &TcpRepr { ack_number: Some(ack_number), .. }) => {
  970. let unacknowledged = self.tx_buffer.len() + control_len;
  971. if ack_number < self.local_seq_no {
  972. net_debug!("{}:{}:{}: duplicate ACK ({} not in {}...{})",
  973. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  974. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  975. return Err(Error::Dropped)
  976. }
  977. if ack_number > self.local_seq_no + unacknowledged {
  978. net_debug!("{}:{}:{}: unacceptable ACK ({} not in {}...{})",
  979. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  980. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  981. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  982. }
  983. }
  984. }
  985. let window_start = self.remote_seq_no + self.rx_buffer.len();
  986. let window_end = self.remote_seq_no + self.rx_buffer.capacity();
  987. let segment_start = repr.seq_number;
  988. let segment_end = repr.seq_number + repr.segment_len();
  989. let payload_offset;
  990. match self.state {
  991. // In LISTEN and SYN-SENT states, we have not yet synchronized with the remote end.
  992. State::Listen | State::SynSent =>
  993. payload_offset = 0,
  994. // In all other states, segments must occupy a valid portion of the receive window.
  995. _ => {
  996. let mut segment_in_window = true;
  997. if window_start == window_end && segment_start != segment_end {
  998. net_debug!("{}:{}:{}: non-zero-length segment with zero receive window, \
  999. will only send an ACK",
  1000. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1001. segment_in_window = false;
  1002. }
  1003. if segment_start == segment_end && segment_end == window_start - 1 {
  1004. net_debug!("{}:{}:{}: received a keep-alive or window probe packet, \
  1005. will send an ACK",
  1006. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1007. segment_in_window = false;
  1008. } else if !((window_start <= segment_start && segment_start <= window_end) &&
  1009. (window_start <= segment_end && segment_end <= window_end)) {
  1010. net_debug!("{}:{}:{}: segment not in receive window \
  1011. ({}..{} not intersecting {}..{}), will send challenge ACK",
  1012. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1013. segment_start, segment_end, window_start, window_end);
  1014. segment_in_window = false;
  1015. }
  1016. if segment_in_window {
  1017. // We've checked that segment_start >= window_start above.
  1018. payload_offset = (segment_start - window_start) as usize;
  1019. self.local_rx_last_seq = Some(repr.seq_number);
  1020. } else {
  1021. // If we're in the TIME-WAIT state, restart the TIME-WAIT timeout, since
  1022. // the remote end may not have realized we've closed the connection.
  1023. if self.state == State::TimeWait {
  1024. self.timer.set_for_close(timestamp);
  1025. }
  1026. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  1027. }
  1028. }
  1029. }
  1030. // Compute the amount of acknowledged octets, removing the SYN and FIN bits
  1031. // from the sequence space.
  1032. let mut ack_len = 0;
  1033. let mut ack_of_fin = false;
  1034. if repr.control != TcpControl::Rst {
  1035. if let Some(ack_number) = repr.ack_number {
  1036. ack_len = ack_number - self.local_seq_no;
  1037. // There could have been no data sent before the SYN, so we always remove it
  1038. // from the sequence space.
  1039. if sent_syn {
  1040. ack_len -= 1
  1041. }
  1042. // We could've sent data before the FIN, so only remove FIN from the sequence
  1043. // space if all of that data is acknowledged.
  1044. if sent_fin && self.tx_buffer.len() + 1 == ack_len {
  1045. ack_len -= 1;
  1046. net_trace!("{}:{}:{}: received ACK of FIN",
  1047. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1048. ack_of_fin = true;
  1049. }
  1050. }
  1051. }
  1052. // Disregard control flags we don't care about or shouldn't act on yet.
  1053. let mut control = repr.control;
  1054. control = control.quash_psh();
  1055. // If a FIN is received at the end of the current segment but the start of the segment
  1056. // is not at the start of the receive window, disregard this FIN.
  1057. if control == TcpControl::Fin && window_start != segment_start {
  1058. control = TcpControl::None;
  1059. }
  1060. // Validate and update the state.
  1061. match (self.state, control) {
  1062. // RSTs are not accepted in the LISTEN state.
  1063. (State::Listen, TcpControl::Rst) =>
  1064. return Err(Error::Dropped),
  1065. // RSTs in SYN-RECEIVED flip the socket back to the LISTEN state.
  1066. (State::SynReceived, TcpControl::Rst) => {
  1067. net_trace!("{}:{}:{}: received RST",
  1068. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1069. self.local_endpoint.addr = self.listen_address;
  1070. self.remote_endpoint = IpEndpoint::default();
  1071. self.set_state(State::Listen);
  1072. return Ok(None)
  1073. }
  1074. // RSTs in any other state close the socket.
  1075. (_, TcpControl::Rst) => {
  1076. net_trace!("{}:{}:{}: received RST",
  1077. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1078. self.set_state(State::Closed);
  1079. self.local_endpoint = IpEndpoint::default();
  1080. self.remote_endpoint = IpEndpoint::default();
  1081. return Ok(None)
  1082. }
  1083. // SYN packets in the LISTEN state change it to SYN-RECEIVED.
  1084. (State::Listen, TcpControl::Syn) => {
  1085. net_trace!("{}:{}: received SYN",
  1086. self.meta.handle, self.local_endpoint);
  1087. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  1088. self.remote_endpoint = IpEndpoint::new(ip_repr.src_addr(), repr.src_port);
  1089. // FIXME: use something more secure here
  1090. self.local_seq_no = TcpSeqNumber(-repr.seq_number.0);
  1091. self.remote_seq_no = repr.seq_number + 1;
  1092. self.remote_last_seq = self.local_seq_no;
  1093. self.remote_has_sack = repr.sack_permitted;
  1094. if let Some(max_seg_size) = repr.max_seg_size {
  1095. self.remote_mss = max_seg_size as usize
  1096. }
  1097. self.remote_win_scale = repr.window_scale;
  1098. // No window scaling means don't do any window shifting
  1099. if self.remote_win_scale.is_none() {
  1100. self.remote_win_shift = 0;
  1101. }
  1102. self.set_state(State::SynReceived);
  1103. self.timer.set_for_idle(timestamp, self.keep_alive);
  1104. }
  1105. // ACK packets in the SYN-RECEIVED state change it to ESTABLISHED.
  1106. (State::SynReceived, TcpControl::None) => {
  1107. self.set_state(State::Established);
  1108. self.timer.set_for_idle(timestamp, self.keep_alive);
  1109. }
  1110. // FIN packets in the SYN-RECEIVED state change it to CLOSE-WAIT.
  1111. // It's not obvious from RFC 793 that this is permitted, but
  1112. // 7th and 8th steps in the "SEGMENT ARRIVES" event describe this behavior.
  1113. (State::SynReceived, TcpControl::Fin) => {
  1114. self.remote_seq_no += 1;
  1115. self.rx_fin_received = true;
  1116. self.set_state(State::CloseWait);
  1117. self.timer.set_for_idle(timestamp, self.keep_alive);
  1118. }
  1119. // SYN|ACK packets in the SYN-SENT state change it to ESTABLISHED.
  1120. (State::SynSent, TcpControl::Syn) => {
  1121. net_trace!("{}:{}:{}: received SYN|ACK",
  1122. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1123. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  1124. self.remote_seq_no = repr.seq_number + 1;
  1125. self.remote_last_seq = self.local_seq_no + 1;
  1126. self.remote_last_ack = Some(repr.seq_number);
  1127. if let Some(max_seg_size) = repr.max_seg_size {
  1128. self.remote_mss = max_seg_size as usize;
  1129. }
  1130. self.set_state(State::Established);
  1131. self.timer.set_for_idle(timestamp, self.keep_alive);
  1132. }
  1133. // ACK packets in ESTABLISHED state reset the retransmit timer,
  1134. // except for duplicate ACK packets which preserve it.
  1135. (State::Established, TcpControl::None) => {
  1136. if !self.timer.is_retransmit() || ack_len != 0 {
  1137. self.timer.set_for_idle(timestamp, self.keep_alive);
  1138. }
  1139. },
  1140. // FIN packets in ESTABLISHED state indicate the remote side has closed.
  1141. (State::Established, TcpControl::Fin) => {
  1142. self.remote_seq_no += 1;
  1143. self.rx_fin_received = true;
  1144. self.set_state(State::CloseWait);
  1145. self.timer.set_for_idle(timestamp, self.keep_alive);
  1146. }
  1147. // ACK packets in FIN-WAIT-1 state change it to FIN-WAIT-2, if we've already
  1148. // sent everything in the transmit buffer. If not, they reset the retransmit timer.
  1149. (State::FinWait1, TcpControl::None) => {
  1150. if ack_of_fin {
  1151. self.set_state(State::FinWait2);
  1152. }
  1153. self.timer.set_for_idle(timestamp, self.keep_alive);
  1154. }
  1155. // FIN packets in FIN-WAIT-1 state change it to CLOSING, or to TIME-WAIT
  1156. // if they also acknowledge our FIN.
  1157. (State::FinWait1, TcpControl::Fin) => {
  1158. self.remote_seq_no += 1;
  1159. self.rx_fin_received = true;
  1160. if ack_of_fin {
  1161. self.set_state(State::TimeWait);
  1162. self.timer.set_for_close(timestamp);
  1163. } else {
  1164. self.set_state(State::Closing);
  1165. self.timer.set_for_idle(timestamp, self.keep_alive);
  1166. }
  1167. }
  1168. // Data packets in FIN-WAIT-2 reset the idle timer.
  1169. (State::FinWait2, TcpControl::None) => {
  1170. self.timer.set_for_idle(timestamp, self.keep_alive);
  1171. }
  1172. // FIN packets in FIN-WAIT-2 state change it to TIME-WAIT.
  1173. (State::FinWait2, TcpControl::Fin) => {
  1174. self.remote_seq_no += 1;
  1175. self.rx_fin_received = true;
  1176. self.set_state(State::TimeWait);
  1177. self.timer.set_for_close(timestamp);
  1178. }
  1179. // ACK packets in CLOSING state change it to TIME-WAIT.
  1180. (State::Closing, TcpControl::None) => {
  1181. if ack_of_fin {
  1182. self.set_state(State::TimeWait);
  1183. self.timer.set_for_close(timestamp);
  1184. } else {
  1185. self.timer.set_for_idle(timestamp, self.keep_alive);
  1186. }
  1187. }
  1188. // ACK packets in CLOSE-WAIT state reset the retransmit timer.
  1189. (State::CloseWait, TcpControl::None) => {
  1190. self.timer.set_for_idle(timestamp, self.keep_alive);
  1191. }
  1192. // ACK packets in LAST-ACK state change it to CLOSED.
  1193. (State::LastAck, TcpControl::None) => {
  1194. // Clear the remote endpoint, or we'll send an RST there.
  1195. self.set_state(State::Closed);
  1196. self.local_endpoint = IpEndpoint::default();
  1197. self.remote_endpoint = IpEndpoint::default();
  1198. }
  1199. _ => {
  1200. net_debug!("{}:{}:{}: unexpected packet {}",
  1201. self.meta.handle, self.local_endpoint, self.remote_endpoint, repr);
  1202. return Err(Error::Dropped)
  1203. }
  1204. }
  1205. // Update remote state.
  1206. self.remote_last_ts = Some(timestamp);
  1207. // RFC 1323: The window field (SEG.WND) in the header of every incoming segment, with the
  1208. // exception of SYN segments, is left-shifted by Snd.Wind.Scale bits before updating SND.WND.
  1209. self.remote_win_len = (repr.window_len as usize) << (self.remote_win_scale.unwrap_or(0) as usize);
  1210. if ack_len > 0 {
  1211. // Dequeue acknowledged octets.
  1212. debug_assert!(self.tx_buffer.len() >= ack_len);
  1213. net_trace!("{}:{}:{}: tx buffer: dequeueing {} octets (now {})",
  1214. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1215. ack_len, self.tx_buffer.len() - ack_len);
  1216. self.tx_buffer.dequeue_allocated(ack_len);
  1217. // There's new room available in tx_buffer, wake the waiting task if any.
  1218. #[cfg(feature = "async")]
  1219. self.tx_waker.wake();
  1220. }
  1221. if let Some(ack_number) = repr.ack_number {
  1222. // TODO: When flow control is implemented,
  1223. // refractor the following block within that implementation
  1224. // Detect and react to duplicate ACKs by:
  1225. // 1. Check if duplicate ACK and change self.local_rx_dup_acks accordingly
  1226. // 2. If exactly 3 duplicate ACKs recived, set for fast retransmit
  1227. // 3. Update the last received ACK (self.local_rx_last_ack)
  1228. match self.local_rx_last_ack {
  1229. // Duplicate ACK if payload empty and ACK doesn't move send window ->
  1230. // Increment duplicate ACK count and set for retransmit if we just recived
  1231. // the third duplicate ACK
  1232. Some(ref last_rx_ack) if
  1233. repr.payload.len() == 0 &&
  1234. *last_rx_ack == ack_number &&
  1235. ack_number < self.remote_last_seq => {
  1236. // Increment duplicate ACK count
  1237. self.local_rx_dup_acks = self.local_rx_dup_acks.saturating_add(1);
  1238. net_debug!("{}:{}:{}: received duplicate ACK for seq {} (duplicate nr {}{})",
  1239. self.meta.handle, self.local_endpoint, self.remote_endpoint, ack_number,
  1240. self.local_rx_dup_acks, if self.local_rx_dup_acks == u8::max_value() { "+" } else { "" });
  1241. if self.local_rx_dup_acks == 3 {
  1242. self.timer.set_for_fast_retransmit();
  1243. net_debug!("{}:{}:{}: started fast retransmit",
  1244. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1245. }
  1246. },
  1247. // No duplicate ACK -> Reset state and update last recived ACK
  1248. _ => {
  1249. if self.local_rx_dup_acks > 0 {
  1250. self.local_rx_dup_acks = 0;
  1251. net_debug!("{}:{}:{}: reset duplicate ACK count",
  1252. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1253. }
  1254. self.local_rx_last_ack = Some(ack_number);
  1255. }
  1256. };
  1257. // We've processed everything in the incoming segment, so advance the local
  1258. // sequence number past it.
  1259. self.local_seq_no = ack_number;
  1260. // During retransmission, if an earlier segment got lost but later was
  1261. // successfully received, self.local_seq_no can move past self.remote_last_seq.
  1262. // Do not attempt to retransmit the latter segments; not only this is pointless
  1263. // in theory but also impossible in practice, since they have been already
  1264. // deallocated from the buffer.
  1265. if self.remote_last_seq < self.local_seq_no {
  1266. self.remote_last_seq = self.local_seq_no
  1267. }
  1268. }
  1269. let payload_len = repr.payload.len();
  1270. if payload_len == 0 { return Ok(None) }
  1271. let assembler_was_empty = self.assembler.is_empty();
  1272. // Try adding payload octets to the assembler.
  1273. match self.assembler.add(payload_offset, payload_len) {
  1274. Ok(()) => {
  1275. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1276. // Place payload octets into the buffer.
  1277. net_trace!("{}:{}:{}: rx buffer: receiving {} octets at offset {}",
  1278. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1279. payload_len, payload_offset);
  1280. self.rx_buffer.write_unallocated(payload_offset, repr.payload);
  1281. }
  1282. Err(()) => {
  1283. net_debug!("{}:{}:{}: assembler: too many holes to add {} octets at offset {}",
  1284. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1285. payload_len, payload_offset);
  1286. return Err(Error::Dropped)
  1287. }
  1288. }
  1289. if let Some(contig_len) = self.assembler.remove_front() {
  1290. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1291. // Enqueue the contiguous data octets in front of the buffer.
  1292. net_trace!("{}:{}:{}: rx buffer: enqueueing {} octets (now {})",
  1293. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1294. contig_len, self.rx_buffer.len() + contig_len);
  1295. self.rx_buffer.enqueue_unallocated(contig_len);
  1296. // There's new data in rx_buffer, notify waiting task if any.
  1297. #[cfg(feature = "async")]
  1298. self.rx_waker.wake();
  1299. }
  1300. if !self.assembler.is_empty() {
  1301. // Print the ranges recorded in the assembler.
  1302. net_trace!("{}:{}:{}: assembler: {}",
  1303. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1304. self.assembler);
  1305. }
  1306. // Per RFC 5681, we should send an immediate ACK when either:
  1307. // 1) an out-of-order segment is received, or
  1308. // 2) a segment arrives that fills in all or part of a gap in sequence space.
  1309. if !self.assembler.is_empty() || !assembler_was_empty {
  1310. // Note that we change the transmitter state here.
  1311. // This is fine because smoltcp assumes that it can always transmit zero or one
  1312. // packets for every packet it receives.
  1313. net_trace!("{}:{}:{}: ACKing incoming segment",
  1314. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1315. Ok(Some(self.ack_reply(ip_repr, &repr)))
  1316. } else {
  1317. Ok(None)
  1318. }
  1319. }
  1320. fn timed_out(&self, timestamp: Instant) -> bool {
  1321. match (self.remote_last_ts, self.timeout) {
  1322. (Some(remote_last_ts), Some(timeout)) =>
  1323. timestamp >= remote_last_ts + timeout,
  1324. (_, _) =>
  1325. false
  1326. }
  1327. }
  1328. fn seq_to_transmit(&self) -> bool {
  1329. // We can send data if we have data that:
  1330. // - hasn't been sent before
  1331. // - fits in the remote window
  1332. let can_data = self.remote_last_seq
  1333. < self.local_seq_no + core::cmp::min(self.remote_win_len, self.tx_buffer.len());
  1334. // Do we have to send a FIN?
  1335. let want_fin = match self.state {
  1336. State::FinWait1 => true,
  1337. State::Closing => true,
  1338. State::LastAck => true,
  1339. _ => false,
  1340. };
  1341. // Can we actually send the FIN? We can send it if:
  1342. // 1. We have unsent data that fits in the remote window.
  1343. // 2. We have no unsent data.
  1344. // This condition matches only if #2, because #1 is already covered by can_data and we're ORing them.
  1345. let can_fin =
  1346. want_fin && self.remote_last_seq == self.local_seq_no + self.tx_buffer.len();
  1347. can_data || can_fin
  1348. }
  1349. fn ack_to_transmit(&self) -> bool {
  1350. if let Some(remote_last_ack) = self.remote_last_ack {
  1351. remote_last_ack < self.remote_seq_no + self.rx_buffer.len()
  1352. } else {
  1353. false
  1354. }
  1355. }
  1356. fn window_to_update(&self) -> bool {
  1357. match self.state {
  1358. State::SynSent | State::SynReceived | State::Established | State::FinWait1 | State::FinWait2 =>
  1359. (self.rx_buffer.window() >> self.remote_win_shift) as u16 > self.remote_last_win,
  1360. _ => false,
  1361. }
  1362. }
  1363. pub(crate) fn dispatch<F>(&mut self, timestamp: Instant, caps: &DeviceCapabilities,
  1364. emit: F) -> Result<()>
  1365. where F: FnOnce((IpRepr, TcpRepr)) -> Result<()> {
  1366. if !self.remote_endpoint.is_specified() { return Err(Error::Exhausted) }
  1367. if self.remote_last_ts.is_none() {
  1368. // We get here in exactly two cases:
  1369. // 1) This socket just transitioned into SYN-SENT.
  1370. // 2) This socket had an empty transmit buffer and some data was added there.
  1371. // Both are similar in that the socket has been quiet for an indefinite
  1372. // period of time, it isn't anymore, and the local endpoint is talking.
  1373. // So, we start counting the timeout not from the last received packet
  1374. // but from the first transmitted one.
  1375. self.remote_last_ts = Some(timestamp);
  1376. }
  1377. // Check if any state needs to be changed because of a timer.
  1378. if self.timed_out(timestamp) {
  1379. // If a timeout expires, we should abort the connection.
  1380. net_debug!("{}:{}:{}: timeout exceeded",
  1381. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1382. self.set_state(State::Closed);
  1383. } else if !self.seq_to_transmit() {
  1384. if let Some(retransmit_delta) = self.timer.should_retransmit(timestamp) {
  1385. // If a retransmit timer expired, we should resend data starting at the last ACK.
  1386. net_debug!("{}:{}:{}: retransmitting at t+{}",
  1387. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1388. retransmit_delta);
  1389. self.remote_last_seq = self.local_seq_no;
  1390. }
  1391. }
  1392. // Decide whether we're sending a packet.
  1393. if self.seq_to_transmit() {
  1394. // If we have data to transmit and it fits into partner's window, do it.
  1395. net_trace!("{}:{}:{}: outgoing segment will send data or flags",
  1396. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1397. } else if self.ack_to_transmit() {
  1398. // If we have data to acknowledge, do it.
  1399. net_trace!("{}:{}:{}: outgoing segment will acknowledge",
  1400. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1401. } else if self.window_to_update() {
  1402. // If we have window length increase to advertise, do it.
  1403. net_trace!("{}:{}:{}: outgoing segment will update window",
  1404. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1405. } else if self.state == State::Closed {
  1406. // If we need to abort the connection, do it.
  1407. net_trace!("{}:{}:{}: outgoing segment will abort connection",
  1408. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1409. } else if self.timer.should_retransmit(timestamp).is_some() {
  1410. // If we have packets to retransmit, do it.
  1411. net_trace!("{}:{}:{}: retransmit timer expired",
  1412. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1413. } else if self.timer.should_keep_alive(timestamp) {
  1414. // If we need to transmit a keep-alive packet, do it.
  1415. net_trace!("{}:{}:{}: keep-alive timer expired",
  1416. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1417. } else if self.timer.should_close(timestamp) {
  1418. // If we have spent enough time in the TIME-WAIT state, close the socket.
  1419. net_trace!("{}:{}:{}: TIME-WAIT timer expired",
  1420. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1421. self.reset();
  1422. return Err(Error::Exhausted)
  1423. } else {
  1424. return Err(Error::Exhausted)
  1425. }
  1426. // Construct the lowered IP representation.
  1427. // We might need this to calculate the MSS, so do it early.
  1428. let mut ip_repr = IpRepr::Unspecified {
  1429. src_addr: self.local_endpoint.addr,
  1430. dst_addr: self.remote_endpoint.addr,
  1431. protocol: IpProtocol::Tcp,
  1432. hop_limit: self.hop_limit.unwrap_or(64),
  1433. payload_len: 0
  1434. }.lower(&[])?;
  1435. // Construct the basic TCP representation, an empty ACK packet.
  1436. // We'll adjust this to be more specific as needed.
  1437. let mut repr = TcpRepr {
  1438. src_port: self.local_endpoint.port,
  1439. dst_port: self.remote_endpoint.port,
  1440. control: TcpControl::None,
  1441. seq_number: self.remote_last_seq,
  1442. ack_number: Some(self.remote_seq_no + self.rx_buffer.len()),
  1443. window_len: self.scaled_window(),
  1444. window_scale: None,
  1445. max_seg_size: None,
  1446. sack_permitted: false,
  1447. sack_ranges: [None, None, None],
  1448. payload: &[]
  1449. };
  1450. match self.state {
  1451. // We transmit an RST in the CLOSED state. If we ended up in the CLOSED state
  1452. // with a specified endpoint, it means that the socket was aborted.
  1453. State::Closed => {
  1454. repr.control = TcpControl::Rst;
  1455. }
  1456. // We never transmit anything in the LISTEN state.
  1457. State::Listen => return Err(Error::Exhausted),
  1458. // We transmit a SYN in the SYN-SENT state.
  1459. // We transmit a SYN|ACK in the SYN-RECEIVED state.
  1460. State::SynSent | State::SynReceived => {
  1461. repr.control = TcpControl::Syn;
  1462. if self.state == State::SynSent {
  1463. repr.ack_number = None;
  1464. repr.window_scale = Some(self.remote_win_shift);
  1465. repr.sack_permitted = true;
  1466. } else {
  1467. repr.sack_permitted = self.remote_has_sack;
  1468. repr.window_scale = self.remote_win_scale.map(
  1469. |_| self.remote_win_shift);
  1470. }
  1471. }
  1472. // We transmit data in all states where we may have data in the buffer,
  1473. // or the transmit half of the connection is still open.
  1474. State::Established | State::FinWait1 | State::Closing | State::CloseWait | State::LastAck => {
  1475. // Extract as much data as the remote side can receive in this packet
  1476. // from the transmit buffer.
  1477. let offset = self.remote_last_seq - self.local_seq_no;
  1478. let win_limit = self.local_seq_no + self.remote_win_len - self.remote_last_seq;
  1479. let size = cmp::min(cmp::min(win_limit, self.remote_mss),
  1480. caps.max_transmission_unit - ip_repr.buffer_len() - repr.mss_header_len());
  1481. repr.payload = self.tx_buffer.get_allocated(offset, size);
  1482. // If we've sent everything we had in the buffer, follow it with the PSH or FIN
  1483. // flags, depending on whether the transmit half of the connection is open.
  1484. if offset + repr.payload.len() == self.tx_buffer.len() {
  1485. match self.state {
  1486. State::FinWait1 | State::LastAck | State::Closing =>
  1487. repr.control = TcpControl::Fin,
  1488. State::Established | State::CloseWait if repr.payload.len() > 0 =>
  1489. repr.control = TcpControl::Psh,
  1490. _ => ()
  1491. }
  1492. }
  1493. }
  1494. // In FIN-WAIT-2 and TIME-WAIT states we may only transmit ACKs for incoming data or FIN
  1495. State::FinWait2 | State::TimeWait => {}
  1496. }
  1497. // There might be more than one reason to send a packet. E.g. the keep-alive timer
  1498. // has expired, and we also have data in transmit buffer. Since any packet that occupies
  1499. // sequence space will elicit an ACK, we only need to send an explicit packet if we
  1500. // couldn't fill the sequence space with anything.
  1501. let is_keep_alive;
  1502. if self.timer.should_keep_alive(timestamp) && repr.is_empty() {
  1503. repr.seq_number = repr.seq_number - 1;
  1504. repr.payload = b"\x00"; // RFC 1122 says we should do this
  1505. is_keep_alive = true;
  1506. } else {
  1507. is_keep_alive = false;
  1508. }
  1509. // Trace a summary of what will be sent.
  1510. if is_keep_alive {
  1511. net_trace!("{}:{}:{}: sending a keep-alive",
  1512. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1513. } else if repr.payload.len() > 0 {
  1514. net_trace!("{}:{}:{}: tx buffer: sending {} octets at offset {}",
  1515. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1516. repr.payload.len(), self.remote_last_seq - self.local_seq_no);
  1517. }
  1518. if repr.control != TcpControl::None || repr.payload.len() == 0 {
  1519. let flags =
  1520. match (repr.control, repr.ack_number) {
  1521. (TcpControl::Syn, None) => "SYN",
  1522. (TcpControl::Syn, Some(_)) => "SYN|ACK",
  1523. (TcpControl::Fin, Some(_)) => "FIN|ACK",
  1524. (TcpControl::Rst, Some(_)) => "RST|ACK",
  1525. (TcpControl::Psh, Some(_)) => "PSH|ACK",
  1526. (TcpControl::None, Some(_)) => "ACK",
  1527. _ => "<unreachable>"
  1528. };
  1529. net_trace!("{}:{}:{}: sending {}",
  1530. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1531. flags);
  1532. }
  1533. if repr.control == TcpControl::Syn {
  1534. // Fill the MSS option. See RFC 6691 for an explanation of this calculation.
  1535. let mut max_segment_size = caps.max_transmission_unit;
  1536. max_segment_size -= ip_repr.buffer_len();
  1537. max_segment_size -= repr.mss_header_len();
  1538. repr.max_seg_size = Some(max_segment_size as u16);
  1539. }
  1540. // Actually send the packet. If this succeeds, it means the packet is in
  1541. // the device buffer, and its transmission is imminent. If not, we might have
  1542. // a number of problems, e.g. we need neighbor discovery.
  1543. //
  1544. // Bailing out if the packet isn't placed in the device buffer allows us
  1545. // to not waste time waiting for the retransmit timer on packets that we know
  1546. // for sure will not be successfully transmitted.
  1547. ip_repr.set_payload_len(repr.buffer_len());
  1548. emit((ip_repr, repr))?;
  1549. // We've sent something, whether useful data or a keep-alive packet, so rewind
  1550. // the keep-alive timer.
  1551. self.timer.rewind_keep_alive(timestamp, self.keep_alive);
  1552. // Leave the rest of the state intact if sending a keep-alive packet, since those
  1553. // carry a fake segment.
  1554. if is_keep_alive { return Ok(()) }
  1555. // We've sent a packet successfully, so we can update the internal state now.
  1556. self.remote_last_seq = repr.seq_number + repr.segment_len();
  1557. self.remote_last_ack = repr.ack_number;
  1558. self.remote_last_win = repr.window_len;
  1559. if !self.seq_to_transmit() && repr.segment_len() > 0 {
  1560. // If we've transmitted all data we could (and there was something at all,
  1561. // data or flag, to transmit, not just an ACK), wind up the retransmit timer.
  1562. self.timer.set_for_retransmit(timestamp);
  1563. }
  1564. if self.state == State::Closed {
  1565. // When aborting a connection, forget about it after sending a single RST packet.
  1566. self.local_endpoint = IpEndpoint::default();
  1567. self.remote_endpoint = IpEndpoint::default();
  1568. }
  1569. Ok(())
  1570. }
  1571. pub(crate) fn poll_at(&self) -> PollAt {
  1572. // The logic here mirrors the beginning of dispatch() closely.
  1573. if !self.remote_endpoint.is_specified() {
  1574. // No one to talk to, nothing to transmit.
  1575. PollAt::Ingress
  1576. } else if self.remote_last_ts.is_none() {
  1577. // Socket stopped being quiet recently, we need to acquire a timestamp.
  1578. PollAt::Now
  1579. } else if self.state == State::Closed {
  1580. // Socket was aborted, we have an RST packet to transmit.
  1581. PollAt::Now
  1582. } else if self.seq_to_transmit() || self.ack_to_transmit() || self.window_to_update() {
  1583. // We have a data or flag packet to transmit.
  1584. PollAt::Now
  1585. } else {
  1586. let timeout_poll_at = match (self.remote_last_ts, self.timeout) {
  1587. // If we're transmitting or retransmitting data, we need to poll at the moment
  1588. // when the timeout would expire.
  1589. (Some(remote_last_ts), Some(timeout)) => PollAt::Time(remote_last_ts + timeout),
  1590. // Otherwise we have no timeout.
  1591. (_, _) => PollAt::Ingress,
  1592. };
  1593. // We wait for the earliest of our timers to fire.
  1594. *[self.timer.poll_at(), timeout_poll_at]
  1595. .iter()
  1596. .filter(|x| !x.is_ingress())
  1597. .min().unwrap_or(&PollAt::Ingress)
  1598. }
  1599. }
  1600. }
  1601. impl<'a, 'b> Into<Socket<'a, 'b>> for TcpSocket<'a> {
  1602. fn into(self) -> Socket<'a, 'b> {
  1603. Socket::Tcp(self)
  1604. }
  1605. }
  1606. impl<'a> fmt::Write for TcpSocket<'a> {
  1607. fn write_str(&mut self, slice: &str) -> fmt::Result {
  1608. let slice = slice.as_bytes();
  1609. if self.send_slice(slice) == Ok(slice.len()) {
  1610. Ok(())
  1611. } else {
  1612. Err(fmt::Error)
  1613. }
  1614. }
  1615. }
  1616. #[cfg(test)]
  1617. mod test {
  1618. use core::i32;
  1619. use std::vec::Vec;
  1620. use crate::wire::{IpAddress, IpRepr, IpCidr};
  1621. use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3, MOCK_UNSPECIFIED};
  1622. use super::*;
  1623. // =========================================================================================//
  1624. // Constants
  1625. // =========================================================================================//
  1626. const LOCAL_PORT: u16 = 80;
  1627. const REMOTE_PORT: u16 = 49500;
  1628. const LOCAL_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_1, port: LOCAL_PORT };
  1629. const REMOTE_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_2, port: REMOTE_PORT };
  1630. const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
  1631. const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10000);
  1632. const SEND_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1633. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1634. protocol: IpProtocol::Tcp, payload_len: 20,
  1635. hop_limit: 64
  1636. };
  1637. const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
  1638. src_port: REMOTE_PORT, dst_port: LOCAL_PORT,
  1639. control: TcpControl::None,
  1640. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1641. window_len: 256, window_scale: None,
  1642. max_seg_size: None,
  1643. sack_permitted: false,
  1644. sack_ranges: [None, None, None],
  1645. payload: &[]
  1646. };
  1647. const _RECV_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1648. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1649. protocol: IpProtocol::Tcp, payload_len: 20,
  1650. hop_limit: 64
  1651. };
  1652. const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
  1653. src_port: LOCAL_PORT, dst_port: REMOTE_PORT,
  1654. control: TcpControl::None,
  1655. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1656. window_len: 64, window_scale: None,
  1657. max_seg_size: None,
  1658. sack_permitted: false,
  1659. sack_ranges: [None, None, None],
  1660. payload: &[]
  1661. };
  1662. #[cfg(feature = "proto-ipv6")]
  1663. const BASE_MSS: u16 = 1460;
  1664. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1665. const BASE_MSS: u16 = 1480;
  1666. // =========================================================================================//
  1667. // Helper functions
  1668. // =========================================================================================//
  1669. fn send(socket: &mut TcpSocket, timestamp: Instant, repr: &TcpRepr) ->
  1670. Result<Option<TcpRepr<'static>>> {
  1671. let ip_repr = IpRepr::Unspecified {
  1672. src_addr: MOCK_IP_ADDR_2,
  1673. dst_addr: MOCK_IP_ADDR_1,
  1674. protocol: IpProtocol::Tcp,
  1675. payload_len: repr.buffer_len(),
  1676. hop_limit: 64
  1677. };
  1678. net_trace!("send: {}", repr);
  1679. assert!(socket.accepts(&ip_repr, repr));
  1680. match socket.process(timestamp, &ip_repr, repr) {
  1681. Ok(Some((_ip_repr, repr))) => {
  1682. net_trace!("recv: {}", repr);
  1683. Ok(Some(repr))
  1684. }
  1685. Ok(None) => Ok(None),
  1686. Err(err) => Err(err)
  1687. }
  1688. }
  1689. fn recv<F>(socket: &mut TcpSocket, timestamp: Instant, mut f: F)
  1690. where F: FnMut(Result<TcpRepr>) {
  1691. let mut caps = DeviceCapabilities::default();
  1692. caps.max_transmission_unit = 1520;
  1693. let result = socket.dispatch(timestamp, &caps, |(ip_repr, tcp_repr)| {
  1694. let ip_repr = ip_repr.lower(&[IpCidr::new(LOCAL_END.addr, 24)]).unwrap();
  1695. assert_eq!(ip_repr.protocol(), IpProtocol::Tcp);
  1696. assert_eq!(ip_repr.src_addr(), MOCK_IP_ADDR_1);
  1697. assert_eq!(ip_repr.dst_addr(), MOCK_IP_ADDR_2);
  1698. assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
  1699. net_trace!("recv: {}", tcp_repr);
  1700. Ok(f(Ok(tcp_repr)))
  1701. });
  1702. match result {
  1703. Ok(()) => (),
  1704. Err(e) => f(Err(e))
  1705. }
  1706. }
  1707. macro_rules! send {
  1708. ($socket:ident, $repr:expr) =>
  1709. (send!($socket, time 0, $repr));
  1710. ($socket:ident, $repr:expr, $result:expr) =>
  1711. (send!($socket, time 0, $repr, $result));
  1712. ($socket:ident, time $time:expr, $repr:expr) =>
  1713. (send!($socket, time $time, $repr, Ok(None)));
  1714. ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
  1715. (assert_eq!(send(&mut $socket, Instant::from_millis($time), &$repr), $result));
  1716. }
  1717. macro_rules! recv {
  1718. ($socket:ident, [$( $repr:expr ),*]) => ({
  1719. $( recv!($socket, Ok($repr)); )*
  1720. recv!($socket, Err(Error::Exhausted))
  1721. });
  1722. ($socket:ident, $result:expr) =>
  1723. (recv!($socket, time 0, $result));
  1724. ($socket:ident, time $time:expr, $result:expr) =>
  1725. (recv(&mut $socket, Instant::from_millis($time), |result| {
  1726. // Most of the time we don't care about the PSH flag.
  1727. let result = result.map(|mut repr| {
  1728. repr.control = repr.control.quash_psh();
  1729. repr
  1730. });
  1731. assert_eq!(result, $result)
  1732. }));
  1733. ($socket:ident, time $time:expr, $result:expr, exact) =>
  1734. (recv(&mut $socket, Instant::from_millis($time), |repr| assert_eq!(repr, $result)));
  1735. }
  1736. macro_rules! sanity {
  1737. ($socket1:expr, $socket2:expr) => ({
  1738. let (s1, s2) = ($socket1, $socket2);
  1739. assert_eq!(s1.state, s2.state, "state");
  1740. assert_eq!(s1.listen_address, s2.listen_address, "listen_address");
  1741. assert_eq!(s1.local_endpoint, s2.local_endpoint, "local_endpoint");
  1742. assert_eq!(s1.remote_endpoint, s2.remote_endpoint, "remote_endpoint");
  1743. assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
  1744. assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
  1745. assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
  1746. assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
  1747. assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
  1748. assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
  1749. assert_eq!(s1.timer, s2.timer, "timer");
  1750. })
  1751. }
  1752. #[cfg(feature = "log")]
  1753. fn init_logger() {
  1754. struct Logger;
  1755. static LOGGER: Logger = Logger;
  1756. impl log::Log for Logger {
  1757. fn enabled(&self, _metadata: &log::Metadata) -> bool {
  1758. true
  1759. }
  1760. fn log(&self, record: &log::Record) {
  1761. println!("{}", record.args());
  1762. }
  1763. fn flush(&self) {
  1764. }
  1765. }
  1766. // If it fails, that just means we've already set it to the same value.
  1767. let _ = log::set_logger(&LOGGER);
  1768. log::set_max_level(log::LevelFilter::Trace);
  1769. println!();
  1770. }
  1771. fn socket() -> TcpSocket<'static> {
  1772. socket_with_buffer_sizes(64, 64)
  1773. }
  1774. fn socket_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  1775. #[cfg(feature = "log")]
  1776. init_logger();
  1777. let rx_buffer = SocketBuffer::new(vec![0; rx_len]);
  1778. let tx_buffer = SocketBuffer::new(vec![0; tx_len]);
  1779. TcpSocket::new(rx_buffer, tx_buffer)
  1780. }
  1781. fn socket_syn_received_with_buffer_sizes(
  1782. tx_len: usize,
  1783. rx_len: usize
  1784. ) -> TcpSocket<'static> {
  1785. let mut s = socket_with_buffer_sizes(tx_len, rx_len);
  1786. s.state = State::SynReceived;
  1787. s.local_endpoint = LOCAL_END;
  1788. s.remote_endpoint = REMOTE_END;
  1789. s.local_seq_no = LOCAL_SEQ;
  1790. s.remote_seq_no = REMOTE_SEQ + 1;
  1791. s.remote_last_seq = LOCAL_SEQ;
  1792. s.remote_win_len = 256;
  1793. s
  1794. }
  1795. fn socket_syn_received() -> TcpSocket<'static> {
  1796. socket_syn_received_with_buffer_sizes(64, 64)
  1797. }
  1798. fn socket_syn_sent() -> TcpSocket<'static> {
  1799. let mut s = socket();
  1800. s.state = State::SynSent;
  1801. s.local_endpoint = IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_PORT);
  1802. s.remote_endpoint = REMOTE_END;
  1803. s.local_seq_no = LOCAL_SEQ;
  1804. s.remote_last_seq = LOCAL_SEQ;
  1805. s
  1806. }
  1807. fn socket_syn_sent_with_local_ipendpoint(local: IpEndpoint) -> TcpSocket<'static> {
  1808. let mut s = socket();
  1809. s.state = State::SynSent;
  1810. s.local_endpoint = local;
  1811. s.remote_endpoint = REMOTE_END;
  1812. s.local_seq_no = LOCAL_SEQ;
  1813. s.remote_last_seq = LOCAL_SEQ;
  1814. s
  1815. }
  1816. fn socket_established_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  1817. let mut s = socket_syn_received_with_buffer_sizes(tx_len, rx_len);
  1818. s.state = State::Established;
  1819. s.local_seq_no = LOCAL_SEQ + 1;
  1820. s.remote_last_seq = LOCAL_SEQ + 1;
  1821. s.remote_last_ack = Some(REMOTE_SEQ + 1);
  1822. s.remote_last_win = 64;
  1823. s
  1824. }
  1825. fn socket_established() -> TcpSocket<'static> {
  1826. socket_established_with_buffer_sizes(64, 64)
  1827. }
  1828. fn socket_fin_wait_1() -> TcpSocket<'static> {
  1829. let mut s = socket_established();
  1830. s.state = State::FinWait1;
  1831. s
  1832. }
  1833. fn socket_fin_wait_2() -> TcpSocket<'static> {
  1834. let mut s = socket_fin_wait_1();
  1835. s.state = State::FinWait2;
  1836. s.local_seq_no = LOCAL_SEQ + 1 + 1;
  1837. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1838. s
  1839. }
  1840. fn socket_closing() -> TcpSocket<'static> {
  1841. let mut s = socket_fin_wait_1();
  1842. s.state = State::Closing;
  1843. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1844. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1845. s
  1846. }
  1847. fn socket_time_wait(from_closing: bool) -> TcpSocket<'static> {
  1848. let mut s = socket_fin_wait_2();
  1849. s.state = State::TimeWait;
  1850. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1851. if from_closing {
  1852. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  1853. }
  1854. s.timer = Timer::Close { expires_at: Instant::from_secs(1) + CLOSE_DELAY };
  1855. s
  1856. }
  1857. fn socket_close_wait() -> TcpSocket<'static> {
  1858. let mut s = socket_established();
  1859. s.state = State::CloseWait;
  1860. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1861. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  1862. s
  1863. }
  1864. fn socket_last_ack() -> TcpSocket<'static> {
  1865. let mut s = socket_close_wait();
  1866. s.state = State::LastAck;
  1867. s
  1868. }
  1869. fn socket_recved() -> TcpSocket<'static> {
  1870. let mut s = socket_established();
  1871. send!(s, TcpRepr {
  1872. seq_number: REMOTE_SEQ + 1,
  1873. ack_number: Some(LOCAL_SEQ + 1),
  1874. payload: &b"abcdef"[..],
  1875. ..SEND_TEMPL
  1876. });
  1877. recv!(s, [TcpRepr {
  1878. seq_number: LOCAL_SEQ + 1,
  1879. ack_number: Some(REMOTE_SEQ + 1 + 6),
  1880. window_len: 58,
  1881. ..RECV_TEMPL
  1882. }]);
  1883. s
  1884. }
  1885. // =========================================================================================//
  1886. // Tests for the CLOSED state.
  1887. // =========================================================================================//
  1888. #[test]
  1889. fn test_closed_reject() {
  1890. let s = socket();
  1891. assert_eq!(s.state, State::Closed);
  1892. let tcp_repr = TcpRepr {
  1893. control: TcpControl::Syn,
  1894. ..SEND_TEMPL
  1895. };
  1896. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1897. }
  1898. #[test]
  1899. fn test_closed_reject_after_listen() {
  1900. let mut s = socket();
  1901. s.listen(LOCAL_END).unwrap();
  1902. s.close();
  1903. let tcp_repr = TcpRepr {
  1904. control: TcpControl::Syn,
  1905. ..SEND_TEMPL
  1906. };
  1907. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1908. }
  1909. #[test]
  1910. fn test_closed_close() {
  1911. let mut s = socket();
  1912. s.close();
  1913. assert_eq!(s.state, State::Closed);
  1914. }
  1915. // =========================================================================================//
  1916. // Tests for the LISTEN state.
  1917. // =========================================================================================//
  1918. fn socket_listen() -> TcpSocket<'static> {
  1919. let mut s = socket();
  1920. s.state = State::Listen;
  1921. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  1922. s
  1923. }
  1924. #[test]
  1925. fn test_listen_sack_option() {
  1926. let mut s = socket_listen();
  1927. send!(s, TcpRepr {
  1928. control: TcpControl::Syn,
  1929. seq_number: REMOTE_SEQ,
  1930. ack_number: None,
  1931. sack_permitted: false,
  1932. ..SEND_TEMPL
  1933. });
  1934. assert!(!s.remote_has_sack);
  1935. recv!(s, [TcpRepr {
  1936. control: TcpControl::Syn,
  1937. seq_number: LOCAL_SEQ,
  1938. ack_number: Some(REMOTE_SEQ + 1),
  1939. max_seg_size: Some(BASE_MSS),
  1940. ..RECV_TEMPL
  1941. }]);
  1942. let mut s = socket_listen();
  1943. send!(s, TcpRepr {
  1944. control: TcpControl::Syn,
  1945. seq_number: REMOTE_SEQ,
  1946. ack_number: None,
  1947. sack_permitted: true,
  1948. ..SEND_TEMPL
  1949. });
  1950. assert!(s.remote_has_sack);
  1951. recv!(s, [TcpRepr {
  1952. control: TcpControl::Syn,
  1953. seq_number: LOCAL_SEQ,
  1954. ack_number: Some(REMOTE_SEQ + 1),
  1955. max_seg_size: Some(BASE_MSS),
  1956. sack_permitted: true,
  1957. ..RECV_TEMPL
  1958. }]);
  1959. }
  1960. #[test]
  1961. fn test_listen_syn_win_scale_buffers() {
  1962. for (buffer_size, shift_amt) in &[
  1963. (64, 0),
  1964. (128, 0),
  1965. (1024, 0),
  1966. (65535, 0),
  1967. (65536, 1),
  1968. (65537, 1),
  1969. (131071, 1),
  1970. (131072, 2),
  1971. (524287, 3),
  1972. (524288, 4),
  1973. (655350, 4),
  1974. (1048576, 5),
  1975. ] {
  1976. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  1977. s.state = State::Listen;
  1978. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  1979. assert_eq!(s.remote_win_shift, *shift_amt);
  1980. send!(s, TcpRepr {
  1981. control: TcpControl::Syn,
  1982. seq_number: REMOTE_SEQ,
  1983. ack_number: None,
  1984. window_scale: Some(0),
  1985. ..SEND_TEMPL
  1986. });
  1987. assert_eq!(s.remote_win_shift, *shift_amt);
  1988. recv!(s, [TcpRepr {
  1989. control: TcpControl::Syn,
  1990. seq_number: LOCAL_SEQ,
  1991. ack_number: Some(REMOTE_SEQ + 1),
  1992. max_seg_size: Some(BASE_MSS),
  1993. window_scale: Some(*shift_amt),
  1994. window_len: cmp::min(*buffer_size >> *shift_amt, 65535) as u16,
  1995. ..RECV_TEMPL
  1996. }]);
  1997. }
  1998. }
  1999. #[test]
  2000. fn test_listen_sanity() {
  2001. let mut s = socket();
  2002. s.listen(LOCAL_PORT).unwrap();
  2003. sanity!(s, socket_listen());
  2004. }
  2005. #[test]
  2006. fn test_listen_validation() {
  2007. let mut s = socket();
  2008. assert_eq!(s.listen(0), Err(Error::Unaddressable));
  2009. }
  2010. #[test]
  2011. fn test_listen_twice() {
  2012. let mut s = socket();
  2013. assert_eq!(s.listen(80), Ok(()));
  2014. assert_eq!(s.listen(80), Err(Error::Illegal));
  2015. }
  2016. #[test]
  2017. fn test_listen_syn() {
  2018. let mut s = socket_listen();
  2019. send!(s, TcpRepr {
  2020. control: TcpControl::Syn,
  2021. seq_number: REMOTE_SEQ,
  2022. ack_number: None,
  2023. ..SEND_TEMPL
  2024. });
  2025. sanity!(s, socket_syn_received());
  2026. }
  2027. #[test]
  2028. fn test_listen_syn_reject_ack() {
  2029. let s = socket_listen();
  2030. let tcp_repr = TcpRepr {
  2031. control: TcpControl::Syn,
  2032. seq_number: REMOTE_SEQ,
  2033. ack_number: Some(LOCAL_SEQ),
  2034. ..SEND_TEMPL
  2035. };
  2036. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2037. assert_eq!(s.state, State::Listen);
  2038. }
  2039. #[test]
  2040. fn test_listen_rst() {
  2041. let mut s = socket_listen();
  2042. send!(s, TcpRepr {
  2043. control: TcpControl::Rst,
  2044. seq_number: REMOTE_SEQ,
  2045. ack_number: None,
  2046. ..SEND_TEMPL
  2047. }, Err(Error::Dropped));
  2048. }
  2049. #[test]
  2050. fn test_listen_close() {
  2051. let mut s = socket_listen();
  2052. s.close();
  2053. assert_eq!(s.state, State::Closed);
  2054. }
  2055. // =========================================================================================//
  2056. // Tests for the SYN-RECEIVED state.
  2057. // =========================================================================================//
  2058. #[test]
  2059. fn test_syn_received_ack() {
  2060. let mut s = socket_syn_received();
  2061. recv!(s, [TcpRepr {
  2062. control: TcpControl::Syn,
  2063. seq_number: LOCAL_SEQ,
  2064. ack_number: Some(REMOTE_SEQ + 1),
  2065. max_seg_size: Some(BASE_MSS),
  2066. ..RECV_TEMPL
  2067. }]);
  2068. send!(s, TcpRepr {
  2069. seq_number: REMOTE_SEQ + 1,
  2070. ack_number: Some(LOCAL_SEQ + 1),
  2071. ..SEND_TEMPL
  2072. });
  2073. assert_eq!(s.state, State::Established);
  2074. sanity!(s, socket_established());
  2075. }
  2076. #[test]
  2077. fn test_syn_received_fin() {
  2078. let mut s = socket_syn_received();
  2079. recv!(s, [TcpRepr {
  2080. control: TcpControl::Syn,
  2081. seq_number: LOCAL_SEQ,
  2082. ack_number: Some(REMOTE_SEQ + 1),
  2083. max_seg_size: Some(BASE_MSS),
  2084. ..RECV_TEMPL
  2085. }]);
  2086. send!(s, TcpRepr {
  2087. control: TcpControl::Fin,
  2088. seq_number: REMOTE_SEQ + 1,
  2089. ack_number: Some(LOCAL_SEQ + 1),
  2090. payload: &b"abcdef"[..],
  2091. ..SEND_TEMPL
  2092. });
  2093. recv!(s, [TcpRepr {
  2094. seq_number: LOCAL_SEQ + 1,
  2095. ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
  2096. window_len: 58,
  2097. ..RECV_TEMPL
  2098. }]);
  2099. assert_eq!(s.state, State::CloseWait);
  2100. sanity!(s, TcpSocket {
  2101. remote_last_ack: Some(REMOTE_SEQ + 1 + 6 + 1),
  2102. remote_last_win: 58,
  2103. ..socket_close_wait()
  2104. });
  2105. }
  2106. #[test]
  2107. fn test_syn_received_rst() {
  2108. let mut s = socket_syn_received();
  2109. recv!(s, [TcpRepr {
  2110. control: TcpControl::Syn,
  2111. seq_number: LOCAL_SEQ,
  2112. ack_number: Some(REMOTE_SEQ + 1),
  2113. max_seg_size: Some(BASE_MSS),
  2114. ..RECV_TEMPL
  2115. }]);
  2116. send!(s, TcpRepr {
  2117. control: TcpControl::Rst,
  2118. seq_number: REMOTE_SEQ + 1,
  2119. ack_number: Some(LOCAL_SEQ),
  2120. ..SEND_TEMPL
  2121. });
  2122. assert_eq!(s.state, State::Listen);
  2123. assert_eq!(s.local_endpoint, IpEndpoint::new(IpAddress::Unspecified, LOCAL_END.port));
  2124. assert_eq!(s.remote_endpoint, IpEndpoint::default());
  2125. }
  2126. #[test]
  2127. fn test_syn_received_no_window_scaling() {
  2128. let mut s = socket_listen();
  2129. send!(s, TcpRepr {
  2130. control: TcpControl::Syn,
  2131. seq_number: REMOTE_SEQ,
  2132. ack_number: None,
  2133. ..SEND_TEMPL
  2134. });
  2135. assert_eq!(s.state(), State::SynReceived);
  2136. assert_eq!(s.local_endpoint(), LOCAL_END);
  2137. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2138. recv!(s, [TcpRepr {
  2139. control: TcpControl::Syn,
  2140. seq_number: LOCAL_SEQ,
  2141. ack_number: Some(REMOTE_SEQ + 1),
  2142. max_seg_size: Some(BASE_MSS),
  2143. window_scale: None,
  2144. ..RECV_TEMPL
  2145. }]);
  2146. send!(s, TcpRepr {
  2147. seq_number: REMOTE_SEQ + 1,
  2148. ack_number: Some(LOCAL_SEQ + 1),
  2149. window_scale: None,
  2150. ..SEND_TEMPL
  2151. });
  2152. assert_eq!(s.remote_win_scale, None);
  2153. }
  2154. #[test]
  2155. fn test_syn_received_window_scaling() {
  2156. for scale in 0..14 {
  2157. let mut s = socket_listen();
  2158. send!(s, TcpRepr {
  2159. control: TcpControl::Syn,
  2160. seq_number: REMOTE_SEQ,
  2161. ack_number: None,
  2162. window_scale: Some(scale),
  2163. ..SEND_TEMPL
  2164. });
  2165. assert_eq!(s.state(), State::SynReceived);
  2166. assert_eq!(s.local_endpoint(), LOCAL_END);
  2167. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2168. recv!(s, [TcpRepr {
  2169. control: TcpControl::Syn,
  2170. seq_number: LOCAL_SEQ,
  2171. ack_number: Some(REMOTE_SEQ + 1),
  2172. max_seg_size: Some(BASE_MSS),
  2173. window_scale: Some(0),
  2174. ..RECV_TEMPL
  2175. }]);
  2176. send!(s, TcpRepr {
  2177. seq_number: REMOTE_SEQ + 1,
  2178. ack_number: Some(LOCAL_SEQ + 1),
  2179. window_scale: None,
  2180. ..SEND_TEMPL
  2181. });
  2182. assert_eq!(s.remote_win_scale, Some(scale));
  2183. }
  2184. }
  2185. #[test]
  2186. fn test_syn_received_close() {
  2187. let mut s = socket_syn_received();
  2188. s.close();
  2189. assert_eq!(s.state, State::FinWait1);
  2190. }
  2191. // =========================================================================================//
  2192. // Tests for the SYN-SENT state.
  2193. // =========================================================================================//
  2194. #[test]
  2195. fn test_connect_validation() {
  2196. let mut s = socket();
  2197. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2198. Err(Error::Unaddressable));
  2199. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 0)),
  2200. Err(Error::Unaddressable));
  2201. assert_eq!(s.connect((MOCK_UNSPECIFIED, 0), LOCAL_END),
  2202. Err(Error::Unaddressable));
  2203. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2204. Err(Error::Unaddressable));
  2205. s.connect(REMOTE_END, LOCAL_END).expect("Connect failed with valid parameters");
  2206. assert_eq!(s.local_endpoint(), LOCAL_END);
  2207. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2208. }
  2209. #[test]
  2210. fn test_connect() {
  2211. let mut s = socket();
  2212. s.local_seq_no = LOCAL_SEQ;
  2213. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  2214. assert_eq!(s.local_endpoint, IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_END.port));
  2215. recv!(s, [TcpRepr {
  2216. control: TcpControl::Syn,
  2217. seq_number: LOCAL_SEQ,
  2218. ack_number: None,
  2219. max_seg_size: Some(BASE_MSS),
  2220. window_scale: Some(0),
  2221. sack_permitted: true,
  2222. ..RECV_TEMPL
  2223. }]);
  2224. send!(s, TcpRepr {
  2225. control: TcpControl::Syn,
  2226. seq_number: REMOTE_SEQ,
  2227. ack_number: Some(LOCAL_SEQ + 1),
  2228. max_seg_size: Some(BASE_MSS - 80),
  2229. window_scale: Some(0),
  2230. ..SEND_TEMPL
  2231. });
  2232. assert_eq!(s.local_endpoint, LOCAL_END);
  2233. }
  2234. #[test]
  2235. fn test_connect_unspecified_local() {
  2236. let mut s = socket();
  2237. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 80)),
  2238. Ok(()));
  2239. s.abort();
  2240. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2241. Ok(()));
  2242. s.abort();
  2243. }
  2244. #[test]
  2245. fn test_connect_specified_local() {
  2246. let mut s = socket();
  2247. assert_eq!(s.connect(REMOTE_END, (MOCK_IP_ADDR_2, 80)),
  2248. Ok(()));
  2249. }
  2250. #[test]
  2251. fn test_connect_twice() {
  2252. let mut s = socket();
  2253. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2254. Ok(()));
  2255. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2256. Err(Error::Illegal));
  2257. }
  2258. #[test]
  2259. fn test_syn_sent_sanity() {
  2260. let mut s = socket();
  2261. s.local_seq_no = LOCAL_SEQ;
  2262. s.connect(REMOTE_END, LOCAL_END).unwrap();
  2263. sanity!(s, socket_syn_sent_with_local_ipendpoint(LOCAL_END));
  2264. }
  2265. #[test]
  2266. fn test_syn_sent_syn_ack() {
  2267. let mut s = socket_syn_sent();
  2268. recv!(s, [TcpRepr {
  2269. control: TcpControl::Syn,
  2270. seq_number: LOCAL_SEQ,
  2271. ack_number: None,
  2272. max_seg_size: Some(BASE_MSS),
  2273. window_scale: Some(0),
  2274. sack_permitted: true,
  2275. ..RECV_TEMPL
  2276. }]);
  2277. send!(s, TcpRepr {
  2278. control: TcpControl::Syn,
  2279. seq_number: REMOTE_SEQ,
  2280. ack_number: Some(LOCAL_SEQ + 1),
  2281. max_seg_size: Some(BASE_MSS - 80),
  2282. window_scale: Some(0),
  2283. ..SEND_TEMPL
  2284. });
  2285. recv!(s, [TcpRepr {
  2286. seq_number: LOCAL_SEQ + 1,
  2287. ack_number: Some(REMOTE_SEQ + 1),
  2288. ..RECV_TEMPL
  2289. }]);
  2290. recv!(s, time 1000, Err(Error::Exhausted));
  2291. assert_eq!(s.state, State::Established);
  2292. sanity!(s, socket_established());
  2293. }
  2294. #[test]
  2295. fn test_syn_sent_rst() {
  2296. let mut s = socket_syn_sent();
  2297. send!(s, TcpRepr {
  2298. control: TcpControl::Rst,
  2299. seq_number: REMOTE_SEQ,
  2300. ack_number: Some(LOCAL_SEQ + 1),
  2301. ..SEND_TEMPL
  2302. });
  2303. assert_eq!(s.state, State::Closed);
  2304. }
  2305. #[test]
  2306. fn test_syn_sent_rst_no_ack() {
  2307. let mut s = socket_syn_sent();
  2308. send!(s, TcpRepr {
  2309. control: TcpControl::Rst,
  2310. seq_number: REMOTE_SEQ,
  2311. ack_number: None,
  2312. ..SEND_TEMPL
  2313. }, Err(Error::Dropped));
  2314. assert_eq!(s.state, State::SynSent);
  2315. }
  2316. #[test]
  2317. fn test_syn_sent_rst_bad_ack() {
  2318. let mut s = socket_syn_sent();
  2319. send!(s, TcpRepr {
  2320. control: TcpControl::Rst,
  2321. seq_number: REMOTE_SEQ,
  2322. ack_number: Some(TcpSeqNumber(1234)),
  2323. ..SEND_TEMPL
  2324. }, Err(Error::Dropped));
  2325. assert_eq!(s.state, State::SynSent);
  2326. }
  2327. #[test]
  2328. fn test_syn_sent_bad_ack() {
  2329. let mut s = socket_syn_sent();
  2330. send!(s, TcpRepr {
  2331. control: TcpControl::None,
  2332. ack_number: Some(TcpSeqNumber(1)),
  2333. ..SEND_TEMPL
  2334. }, Err(Error::Dropped));
  2335. assert_eq!(s.state, State::Closed);
  2336. }
  2337. #[test]
  2338. fn test_syn_sent_close() {
  2339. let mut s = socket();
  2340. s.close();
  2341. assert_eq!(s.state, State::Closed);
  2342. }
  2343. #[test]
  2344. fn test_syn_sent_win_scale_buffers() {
  2345. for (buffer_size, shift_amt) in &[
  2346. (64, 0),
  2347. (128, 0),
  2348. (1024, 0),
  2349. (65535, 0),
  2350. (65536, 1),
  2351. (65537, 1),
  2352. (131071, 1),
  2353. (131072, 2),
  2354. (524287, 3),
  2355. (524288, 4),
  2356. (655350, 4),
  2357. (1048576, 5),
  2358. ] {
  2359. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  2360. assert_eq!(s.remote_win_shift, *shift_amt);
  2361. s.connect(REMOTE_END, LOCAL_END).unwrap();
  2362. recv!(s, [TcpRepr {
  2363. control: TcpControl::Syn,
  2364. ack_number: None,
  2365. max_seg_size: Some(BASE_MSS),
  2366. window_scale: Some(*shift_amt),
  2367. window_len: cmp::min(*buffer_size >> *shift_amt, 65535) as u16,
  2368. sack_permitted: true,
  2369. ..RECV_TEMPL
  2370. }]);
  2371. }
  2372. }
  2373. // =========================================================================================//
  2374. // Tests for the ESTABLISHED state.
  2375. // =========================================================================================//
  2376. #[test]
  2377. fn test_established_recv() {
  2378. let mut s = socket_established();
  2379. send!(s, TcpRepr {
  2380. seq_number: REMOTE_SEQ + 1,
  2381. ack_number: Some(LOCAL_SEQ + 1),
  2382. payload: &b"abcdef"[..],
  2383. ..SEND_TEMPL
  2384. });
  2385. recv!(s, [TcpRepr {
  2386. seq_number: LOCAL_SEQ + 1,
  2387. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2388. window_len: 58,
  2389. ..RECV_TEMPL
  2390. }]);
  2391. assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
  2392. }
  2393. fn setup_rfc2018_cases() -> (TcpSocket<'static>, Vec<u8>) {
  2394. // This is a utility function used by the tests for RFC 2018 cases. It configures a socket
  2395. // in a particular way suitable for those cases.
  2396. //
  2397. // RFC 2018: Assume the left window edge is 5000 and that the data transmitter sends [...]
  2398. // segments, each containing 500 data bytes.
  2399. let mut s = socket_established_with_buffer_sizes(4000, 4000);
  2400. s.remote_has_sack = true;
  2401. // create a segment that is 500 bytes long
  2402. let mut segment: Vec<u8> = Vec::with_capacity(500);
  2403. // move the last ack to 5000 by sending ten of them
  2404. for _ in 0..50 { segment.extend_from_slice(b"abcdefghij") }
  2405. for offset in (0..5000).step_by(500) {
  2406. send!(s, TcpRepr {
  2407. seq_number: REMOTE_SEQ + 1 + offset,
  2408. ack_number: Some(LOCAL_SEQ + 1),
  2409. payload: &segment,
  2410. ..SEND_TEMPL
  2411. });
  2412. recv!(s, [TcpRepr {
  2413. seq_number: LOCAL_SEQ + 1,
  2414. ack_number: Some(REMOTE_SEQ + 1 + offset + 500),
  2415. window_len: 3500,
  2416. ..RECV_TEMPL
  2417. }]);
  2418. s.recv(|data| {
  2419. assert_eq!(data.len(), 500);
  2420. assert_eq!(data, segment.as_slice());
  2421. (500, ())
  2422. }).unwrap();
  2423. }
  2424. assert_eq!(s.remote_last_win, 3500);
  2425. (s, segment)
  2426. }
  2427. #[test]
  2428. fn test_established_rfc2018_cases() {
  2429. // This test case verifies the exact scenarios described on pages 8-9 of RFC 2018. Please
  2430. // ensure its behavior does not deviate from those scenarios.
  2431. let (mut s, segment) = setup_rfc2018_cases();
  2432. // RFC 2018:
  2433. //
  2434. // Case 2: The first segment is dropped but the remaining 7 are received.
  2435. //
  2436. // Upon receiving each of the last seven packets, the data receiver will return a TCP ACK
  2437. // segment that acknowledges sequence number 5000 and contains a SACK option specifying one
  2438. // block of queued data:
  2439. //
  2440. // Triggering ACK Left Edge Right Edge
  2441. // Segment
  2442. //
  2443. // 5000 (lost)
  2444. // 5500 5000 5500 6000
  2445. // 6000 5000 5500 6500
  2446. // 6500 5000 5500 7000
  2447. // 7000 5000 5500 7500
  2448. // 7500 5000 5500 8000
  2449. // 8000 5000 5500 8500
  2450. // 8500 5000 5500 9000
  2451. //
  2452. for offset in (500..3500).step_by(500) {
  2453. send!(s, TcpRepr {
  2454. seq_number: REMOTE_SEQ + 1 + offset + 5000,
  2455. ack_number: Some(LOCAL_SEQ + 1),
  2456. payload: &segment,
  2457. ..SEND_TEMPL
  2458. }, Ok(Some(TcpRepr {
  2459. seq_number: LOCAL_SEQ + 1,
  2460. ack_number: Some(REMOTE_SEQ + 1 + 5000),
  2461. window_len: 4000,
  2462. sack_ranges: [
  2463. Some((REMOTE_SEQ.0 as u32 + 1 + 5500,
  2464. REMOTE_SEQ.0 as u32 + 1 + 5500 + offset as u32)),
  2465. None, None],
  2466. ..RECV_TEMPL
  2467. })));
  2468. }
  2469. }
  2470. #[test]
  2471. fn test_established_sliding_window_recv() {
  2472. let mut s = socket_established();
  2473. // Update our scaling parameters for a TCP with a scaled buffer.
  2474. assert_eq!(s.rx_buffer.len(), 0);
  2475. s.rx_buffer = SocketBuffer::new(vec![0; 262143]);
  2476. s.assembler = Assembler::new(s.rx_buffer.capacity());
  2477. s.remote_win_scale = Some(0);
  2478. s.remote_last_win = 65535;
  2479. s.remote_win_shift = 2;
  2480. // Create a TCP segment that will mostly fill an IP frame.
  2481. let mut segment: Vec<u8> = Vec::with_capacity(1400);
  2482. for _ in 0..100 { segment.extend_from_slice(b"abcdefghijklmn") }
  2483. assert_eq!(segment.len(), 1400);
  2484. // Send the frame
  2485. send!(s, TcpRepr {
  2486. seq_number: REMOTE_SEQ + 1,
  2487. ack_number: Some(LOCAL_SEQ + 1),
  2488. payload: &segment,
  2489. ..SEND_TEMPL
  2490. });
  2491. // Ensure that the received window size is shifted right by 2.
  2492. recv!(s, [TcpRepr {
  2493. seq_number: LOCAL_SEQ + 1,
  2494. ack_number: Some(REMOTE_SEQ + 1 + 1400),
  2495. window_len: 65185,
  2496. ..RECV_TEMPL
  2497. }]);
  2498. }
  2499. #[test]
  2500. fn test_established_send() {
  2501. let mut s = socket_established();
  2502. // First roundtrip after establishing.
  2503. s.send_slice(b"abcdef").unwrap();
  2504. recv!(s, [TcpRepr {
  2505. seq_number: LOCAL_SEQ + 1,
  2506. ack_number: Some(REMOTE_SEQ + 1),
  2507. payload: &b"abcdef"[..],
  2508. ..RECV_TEMPL
  2509. }]);
  2510. assert_eq!(s.tx_buffer.len(), 6);
  2511. send!(s, TcpRepr {
  2512. seq_number: REMOTE_SEQ + 1,
  2513. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2514. ..SEND_TEMPL
  2515. });
  2516. assert_eq!(s.tx_buffer.len(), 0);
  2517. // Second roundtrip.
  2518. s.send_slice(b"foobar").unwrap();
  2519. recv!(s, [TcpRepr {
  2520. seq_number: LOCAL_SEQ + 1 + 6,
  2521. ack_number: Some(REMOTE_SEQ + 1),
  2522. payload: &b"foobar"[..],
  2523. ..RECV_TEMPL
  2524. }]);
  2525. send!(s, TcpRepr {
  2526. seq_number: REMOTE_SEQ + 1,
  2527. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2528. ..SEND_TEMPL
  2529. });
  2530. assert_eq!(s.tx_buffer.len(), 0);
  2531. }
  2532. #[test]
  2533. fn test_established_send_no_ack_send() {
  2534. let mut s = socket_established();
  2535. s.send_slice(b"abcdef").unwrap();
  2536. recv!(s, [TcpRepr {
  2537. seq_number: LOCAL_SEQ + 1,
  2538. ack_number: Some(REMOTE_SEQ + 1),
  2539. payload: &b"abcdef"[..],
  2540. ..RECV_TEMPL
  2541. }]);
  2542. s.send_slice(b"foobar").unwrap();
  2543. recv!(s, [TcpRepr {
  2544. seq_number: LOCAL_SEQ + 1 + 6,
  2545. ack_number: Some(REMOTE_SEQ + 1),
  2546. payload: &b"foobar"[..],
  2547. ..RECV_TEMPL
  2548. }]);
  2549. }
  2550. #[test]
  2551. fn test_established_send_buf_gt_win() {
  2552. let mut data = [0; 32];
  2553. for (i, elem) in data.iter_mut().enumerate() {
  2554. *elem = i as u8
  2555. }
  2556. let mut s = socket_established();
  2557. s.remote_win_len = 16;
  2558. s.send_slice(&data[..]).unwrap();
  2559. recv!(s, [TcpRepr {
  2560. seq_number: LOCAL_SEQ + 1,
  2561. ack_number: Some(REMOTE_SEQ + 1),
  2562. payload: &data[0..16],
  2563. ..RECV_TEMPL
  2564. }]);
  2565. }
  2566. #[test]
  2567. fn test_established_send_wrap() {
  2568. let mut s = socket_established();
  2569. let local_seq_start = TcpSeqNumber(i32::MAX - 1);
  2570. s.local_seq_no = local_seq_start + 1;
  2571. s.remote_last_seq = local_seq_start + 1;
  2572. s.send_slice(b"abc").unwrap();
  2573. recv!(s, time 1000, Ok(TcpRepr {
  2574. seq_number: local_seq_start + 1,
  2575. ack_number: Some(REMOTE_SEQ + 1),
  2576. payload: &b"abc"[..],
  2577. ..RECV_TEMPL
  2578. }));
  2579. }
  2580. #[test]
  2581. fn test_established_no_ack() {
  2582. let mut s = socket_established();
  2583. send!(s, TcpRepr {
  2584. seq_number: REMOTE_SEQ + 1,
  2585. ack_number: None,
  2586. ..SEND_TEMPL
  2587. }, Err(Error::Dropped));
  2588. }
  2589. #[test]
  2590. fn test_established_bad_ack() {
  2591. let mut s = socket_established();
  2592. // Already acknowledged data.
  2593. send!(s, TcpRepr {
  2594. seq_number: REMOTE_SEQ + 1,
  2595. ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
  2596. ..SEND_TEMPL
  2597. }, Err(Error::Dropped));
  2598. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2599. // Data not yet transmitted.
  2600. send!(s, TcpRepr {
  2601. seq_number: REMOTE_SEQ + 1,
  2602. ack_number: Some(LOCAL_SEQ + 10),
  2603. ..SEND_TEMPL
  2604. }, Ok(Some(TcpRepr {
  2605. seq_number: LOCAL_SEQ + 1,
  2606. ack_number: Some(REMOTE_SEQ + 1),
  2607. ..RECV_TEMPL
  2608. })));
  2609. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2610. }
  2611. #[test]
  2612. fn test_established_bad_seq() {
  2613. let mut s = socket_established();
  2614. // Data outside of receive window.
  2615. send!(s, TcpRepr {
  2616. seq_number: REMOTE_SEQ + 1 + 256,
  2617. ack_number: Some(LOCAL_SEQ + 1),
  2618. ..SEND_TEMPL
  2619. }, Ok(Some(TcpRepr {
  2620. seq_number: LOCAL_SEQ + 1,
  2621. ack_number: Some(REMOTE_SEQ + 1),
  2622. ..RECV_TEMPL
  2623. })));
  2624. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  2625. }
  2626. #[test]
  2627. fn test_established_fin() {
  2628. let mut s = socket_established();
  2629. send!(s, TcpRepr {
  2630. control: TcpControl::Fin,
  2631. seq_number: REMOTE_SEQ + 1,
  2632. ack_number: Some(LOCAL_SEQ + 1),
  2633. ..SEND_TEMPL
  2634. });
  2635. recv!(s, [TcpRepr {
  2636. seq_number: LOCAL_SEQ + 1,
  2637. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2638. ..RECV_TEMPL
  2639. }]);
  2640. assert_eq!(s.state, State::CloseWait);
  2641. sanity!(s, socket_close_wait());
  2642. }
  2643. #[test]
  2644. fn test_established_fin_after_missing() {
  2645. let mut s = socket_established();
  2646. send!(s, TcpRepr {
  2647. control: TcpControl::Fin,
  2648. seq_number: REMOTE_SEQ + 1 + 6,
  2649. ack_number: Some(LOCAL_SEQ + 1),
  2650. payload: &b"123456"[..],
  2651. ..SEND_TEMPL
  2652. }, Ok(Some(TcpRepr {
  2653. seq_number: LOCAL_SEQ + 1,
  2654. ack_number: Some(REMOTE_SEQ + 1),
  2655. ..RECV_TEMPL
  2656. })));
  2657. assert_eq!(s.state, State::Established);
  2658. send!(s, TcpRepr {
  2659. seq_number: REMOTE_SEQ + 1,
  2660. ack_number: Some(LOCAL_SEQ + 1),
  2661. payload: &b"abcdef"[..],
  2662. ..SEND_TEMPL
  2663. }, Ok(Some(TcpRepr {
  2664. seq_number: LOCAL_SEQ + 1,
  2665. ack_number: Some(REMOTE_SEQ + 1 + 6 + 6),
  2666. window_len: 52,
  2667. ..RECV_TEMPL
  2668. })));
  2669. assert_eq!(s.state, State::Established);
  2670. }
  2671. #[test]
  2672. fn test_established_send_fin() {
  2673. let mut s = socket_established();
  2674. s.send_slice(b"abcdef").unwrap();
  2675. send!(s, TcpRepr {
  2676. control: TcpControl::Fin,
  2677. seq_number: REMOTE_SEQ + 1,
  2678. ack_number: Some(LOCAL_SEQ + 1),
  2679. ..SEND_TEMPL
  2680. });
  2681. assert_eq!(s.state, State::CloseWait);
  2682. recv!(s, [TcpRepr {
  2683. seq_number: LOCAL_SEQ + 1,
  2684. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2685. payload: &b"abcdef"[..],
  2686. ..RECV_TEMPL
  2687. }]);
  2688. }
  2689. #[test]
  2690. fn test_established_rst() {
  2691. let mut s = socket_established();
  2692. send!(s, TcpRepr {
  2693. control: TcpControl::Rst,
  2694. seq_number: REMOTE_SEQ + 1,
  2695. ack_number: Some(LOCAL_SEQ + 1),
  2696. ..SEND_TEMPL
  2697. });
  2698. assert_eq!(s.state, State::Closed);
  2699. }
  2700. #[test]
  2701. fn test_established_rst_no_ack() {
  2702. let mut s = socket_established();
  2703. send!(s, TcpRepr {
  2704. control: TcpControl::Rst,
  2705. seq_number: REMOTE_SEQ + 1,
  2706. ack_number: None,
  2707. ..SEND_TEMPL
  2708. });
  2709. assert_eq!(s.state, State::Closed);
  2710. }
  2711. #[test]
  2712. fn test_established_close() {
  2713. let mut s = socket_established();
  2714. s.close();
  2715. assert_eq!(s.state, State::FinWait1);
  2716. sanity!(s, socket_fin_wait_1());
  2717. }
  2718. #[test]
  2719. fn test_established_abort() {
  2720. let mut s = socket_established();
  2721. s.abort();
  2722. assert_eq!(s.state, State::Closed);
  2723. recv!(s, [TcpRepr {
  2724. control: TcpControl::Rst,
  2725. seq_number: LOCAL_SEQ + 1,
  2726. ack_number: Some(REMOTE_SEQ + 1),
  2727. ..RECV_TEMPL
  2728. }]);
  2729. }
  2730. #[test]
  2731. fn test_established_rst_bad_seq() {
  2732. let mut s = socket_established();
  2733. send!(s, TcpRepr {
  2734. control: TcpControl::Rst,
  2735. seq_number: REMOTE_SEQ, // Wrong seq
  2736. ack_number: None,
  2737. ..SEND_TEMPL
  2738. }, Ok(Some(TcpRepr {
  2739. seq_number: LOCAL_SEQ + 1,
  2740. ack_number: Some(REMOTE_SEQ + 1),
  2741. ..RECV_TEMPL
  2742. })));
  2743. assert_eq!(s.state, State::Established);
  2744. // Send something to advance seq by 1
  2745. send!(s, TcpRepr {
  2746. seq_number: REMOTE_SEQ + 1, // correct seq
  2747. ack_number: Some(LOCAL_SEQ + 1),
  2748. payload: &b"a"[..],
  2749. ..SEND_TEMPL
  2750. });
  2751. // Send wrong rst again, check that the challenge ack is correctly updated
  2752. // The ack number must be updated even if we don't call dispatch on the socket
  2753. // See https://github.com/smoltcp-rs/smoltcp/issues/338
  2754. send!(s, TcpRepr {
  2755. control: TcpControl::Rst,
  2756. seq_number: REMOTE_SEQ, // Wrong seq
  2757. ack_number: None,
  2758. ..SEND_TEMPL
  2759. }, Ok(Some(TcpRepr {
  2760. seq_number: LOCAL_SEQ + 1,
  2761. ack_number: Some(REMOTE_SEQ + 2), // this has changed
  2762. window_len: 63,
  2763. ..RECV_TEMPL
  2764. })));
  2765. }
  2766. // =========================================================================================//
  2767. // Tests for the FIN-WAIT-1 state.
  2768. // =========================================================================================//
  2769. #[test]
  2770. fn test_fin_wait_1_fin_ack() {
  2771. let mut s = socket_fin_wait_1();
  2772. recv!(s, [TcpRepr {
  2773. control: TcpControl::Fin,
  2774. seq_number: LOCAL_SEQ + 1,
  2775. ack_number: Some(REMOTE_SEQ + 1),
  2776. ..RECV_TEMPL
  2777. }]);
  2778. send!(s, TcpRepr {
  2779. seq_number: REMOTE_SEQ + 1,
  2780. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2781. ..SEND_TEMPL
  2782. });
  2783. assert_eq!(s.state, State::FinWait2);
  2784. sanity!(s, socket_fin_wait_2());
  2785. }
  2786. #[test]
  2787. fn test_fin_wait_1_fin_fin() {
  2788. let mut s = socket_fin_wait_1();
  2789. recv!(s, [TcpRepr {
  2790. control: TcpControl::Fin,
  2791. seq_number: LOCAL_SEQ + 1,
  2792. ack_number: Some(REMOTE_SEQ + 1),
  2793. ..RECV_TEMPL
  2794. }]);
  2795. send!(s, TcpRepr {
  2796. control: TcpControl::Fin,
  2797. seq_number: REMOTE_SEQ + 1,
  2798. ack_number: Some(LOCAL_SEQ + 1),
  2799. ..SEND_TEMPL
  2800. });
  2801. assert_eq!(s.state, State::Closing);
  2802. sanity!(s, socket_closing());
  2803. }
  2804. #[test]
  2805. fn test_fin_wait_1_fin_with_data_queued() {
  2806. let mut s = socket_established();
  2807. s.remote_win_len = 6;
  2808. s.send_slice(b"abcdef123456").unwrap();
  2809. s.close();
  2810. recv!(s, Ok(TcpRepr {
  2811. seq_number: LOCAL_SEQ + 1,
  2812. ack_number: Some(REMOTE_SEQ + 1),
  2813. payload: &b"abcdef"[..],
  2814. ..RECV_TEMPL
  2815. }));
  2816. send!(s, TcpRepr {
  2817. seq_number: REMOTE_SEQ + 1,
  2818. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2819. ..SEND_TEMPL
  2820. });
  2821. assert_eq!(s.state, State::FinWait1);
  2822. }
  2823. #[test]
  2824. fn test_fin_wait_1_recv() {
  2825. let mut s = socket_fin_wait_1();
  2826. send!(s, TcpRepr {
  2827. seq_number: REMOTE_SEQ + 1,
  2828. ack_number: Some(LOCAL_SEQ + 1),
  2829. payload: &b"abc"[..],
  2830. ..SEND_TEMPL
  2831. });
  2832. assert_eq!(s.state, State::FinWait1);
  2833. s.recv(|data| {
  2834. assert_eq!(data, b"abc");
  2835. (3, ())
  2836. }).unwrap();
  2837. }
  2838. #[test]
  2839. fn test_fin_wait_1_close() {
  2840. let mut s = socket_fin_wait_1();
  2841. s.close();
  2842. assert_eq!(s.state, State::FinWait1);
  2843. }
  2844. // =========================================================================================//
  2845. // Tests for the FIN-WAIT-2 state.
  2846. // =========================================================================================//
  2847. #[test]
  2848. fn test_fin_wait_2_fin() {
  2849. let mut s = socket_fin_wait_2();
  2850. send!(s, time 1_000, TcpRepr {
  2851. control: TcpControl::Fin,
  2852. seq_number: REMOTE_SEQ + 1,
  2853. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2854. ..SEND_TEMPL
  2855. });
  2856. assert_eq!(s.state, State::TimeWait);
  2857. sanity!(s, socket_time_wait(false));
  2858. }
  2859. #[test]
  2860. fn test_fin_wait_2_recv() {
  2861. let mut s = socket_fin_wait_2();
  2862. send!(s, TcpRepr {
  2863. seq_number: REMOTE_SEQ + 1,
  2864. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2865. payload: &b"abc"[..],
  2866. ..SEND_TEMPL
  2867. });
  2868. assert_eq!(s.state, State::FinWait2);
  2869. s.recv(|data| {
  2870. assert_eq!(data, b"abc");
  2871. (3, ())
  2872. }).unwrap();
  2873. recv!(s, [TcpRepr {
  2874. seq_number: LOCAL_SEQ + 1 + 1,
  2875. ack_number: Some(REMOTE_SEQ + 1 + 3),
  2876. ..RECV_TEMPL
  2877. }]);
  2878. }
  2879. #[test]
  2880. fn test_fin_wait_2_close() {
  2881. let mut s = socket_fin_wait_2();
  2882. s.close();
  2883. assert_eq!(s.state, State::FinWait2);
  2884. }
  2885. // =========================================================================================//
  2886. // Tests for the CLOSING state.
  2887. // =========================================================================================//
  2888. #[test]
  2889. fn test_closing_ack_fin() {
  2890. let mut s = socket_closing();
  2891. recv!(s, [TcpRepr {
  2892. seq_number: LOCAL_SEQ + 1 + 1,
  2893. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2894. ..RECV_TEMPL
  2895. }]);
  2896. send!(s, time 1_000, TcpRepr {
  2897. seq_number: REMOTE_SEQ + 1 + 1,
  2898. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2899. ..SEND_TEMPL
  2900. });
  2901. assert_eq!(s.state, State::TimeWait);
  2902. sanity!(s, socket_time_wait(true));
  2903. }
  2904. #[test]
  2905. fn test_closing_close() {
  2906. let mut s = socket_closing();
  2907. s.close();
  2908. assert_eq!(s.state, State::Closing);
  2909. }
  2910. // =========================================================================================//
  2911. // Tests for the TIME-WAIT state.
  2912. // =========================================================================================//
  2913. #[test]
  2914. fn test_time_wait_from_fin_wait_2_ack() {
  2915. let mut s = socket_time_wait(false);
  2916. recv!(s, [TcpRepr {
  2917. seq_number: LOCAL_SEQ + 1 + 1,
  2918. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2919. ..RECV_TEMPL
  2920. }]);
  2921. }
  2922. #[test]
  2923. fn test_time_wait_from_closing_no_ack() {
  2924. let mut s = socket_time_wait(true);
  2925. recv!(s, []);
  2926. }
  2927. #[test]
  2928. fn test_time_wait_close() {
  2929. let mut s = socket_time_wait(false);
  2930. s.close();
  2931. assert_eq!(s.state, State::TimeWait);
  2932. }
  2933. #[test]
  2934. fn test_time_wait_retransmit() {
  2935. let mut s = socket_time_wait(false);
  2936. recv!(s, [TcpRepr {
  2937. seq_number: LOCAL_SEQ + 1 + 1,
  2938. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2939. ..RECV_TEMPL
  2940. }]);
  2941. send!(s, time 5_000, TcpRepr {
  2942. control: TcpControl::Fin,
  2943. seq_number: REMOTE_SEQ + 1,
  2944. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2945. ..SEND_TEMPL
  2946. }, Ok(Some(TcpRepr {
  2947. seq_number: LOCAL_SEQ + 1 + 1,
  2948. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2949. ..RECV_TEMPL
  2950. })));
  2951. assert_eq!(s.timer, Timer::Close { expires_at: Instant::from_secs(5) + CLOSE_DELAY });
  2952. }
  2953. #[test]
  2954. fn test_time_wait_timeout() {
  2955. let mut s = socket_time_wait(false);
  2956. recv!(s, [TcpRepr {
  2957. seq_number: LOCAL_SEQ + 1 + 1,
  2958. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2959. ..RECV_TEMPL
  2960. }]);
  2961. assert_eq!(s.state, State::TimeWait);
  2962. recv!(s, time 60_000, Err(Error::Exhausted));
  2963. assert_eq!(s.state, State::Closed);
  2964. }
  2965. // =========================================================================================//
  2966. // Tests for the CLOSE-WAIT state.
  2967. // =========================================================================================//
  2968. #[test]
  2969. fn test_close_wait_ack() {
  2970. let mut s = socket_close_wait();
  2971. s.send_slice(b"abcdef").unwrap();
  2972. recv!(s, [TcpRepr {
  2973. seq_number: LOCAL_SEQ + 1,
  2974. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2975. payload: &b"abcdef"[..],
  2976. ..RECV_TEMPL
  2977. }]);
  2978. send!(s, TcpRepr {
  2979. seq_number: REMOTE_SEQ + 1 + 1,
  2980. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2981. ..SEND_TEMPL
  2982. });
  2983. }
  2984. #[test]
  2985. fn test_close_wait_close() {
  2986. let mut s = socket_close_wait();
  2987. s.close();
  2988. assert_eq!(s.state, State::LastAck);
  2989. sanity!(s, socket_last_ack());
  2990. }
  2991. // =========================================================================================//
  2992. // Tests for the LAST-ACK state.
  2993. // =========================================================================================//
  2994. #[test]
  2995. fn test_last_ack_fin_ack() {
  2996. let mut s = socket_last_ack();
  2997. recv!(s, [TcpRepr {
  2998. control: TcpControl::Fin,
  2999. seq_number: LOCAL_SEQ + 1,
  3000. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3001. ..RECV_TEMPL
  3002. }]);
  3003. assert_eq!(s.state, State::LastAck);
  3004. send!(s, TcpRepr {
  3005. seq_number: REMOTE_SEQ + 1 + 1,
  3006. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3007. ..SEND_TEMPL
  3008. });
  3009. assert_eq!(s.state, State::Closed);
  3010. }
  3011. #[test]
  3012. fn test_last_ack_close() {
  3013. let mut s = socket_last_ack();
  3014. s.close();
  3015. assert_eq!(s.state, State::LastAck);
  3016. }
  3017. // =========================================================================================//
  3018. // Tests for transitioning through multiple states.
  3019. // =========================================================================================//
  3020. #[test]
  3021. fn test_listen() {
  3022. let mut s = socket();
  3023. s.listen(IpEndpoint::new(IpAddress::default(), LOCAL_PORT)).unwrap();
  3024. assert_eq!(s.state, State::Listen);
  3025. }
  3026. #[test]
  3027. fn test_three_way_handshake() {
  3028. let mut s = socket_listen();
  3029. send!(s, TcpRepr {
  3030. control: TcpControl::Syn,
  3031. seq_number: REMOTE_SEQ,
  3032. ack_number: None,
  3033. ..SEND_TEMPL
  3034. });
  3035. assert_eq!(s.state(), State::SynReceived);
  3036. assert_eq!(s.local_endpoint(), LOCAL_END);
  3037. assert_eq!(s.remote_endpoint(), REMOTE_END);
  3038. recv!(s, [TcpRepr {
  3039. control: TcpControl::Syn,
  3040. seq_number: LOCAL_SEQ,
  3041. ack_number: Some(REMOTE_SEQ + 1),
  3042. max_seg_size: Some(BASE_MSS),
  3043. ..RECV_TEMPL
  3044. }]);
  3045. send!(s, TcpRepr {
  3046. seq_number: REMOTE_SEQ + 1,
  3047. ack_number: Some(LOCAL_SEQ + 1),
  3048. ..SEND_TEMPL
  3049. });
  3050. assert_eq!(s.state(), State::Established);
  3051. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  3052. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  3053. }
  3054. #[test]
  3055. fn test_remote_close() {
  3056. let mut s = socket_established();
  3057. send!(s, TcpRepr {
  3058. control: TcpControl::Fin,
  3059. seq_number: REMOTE_SEQ + 1,
  3060. ack_number: Some(LOCAL_SEQ + 1),
  3061. ..SEND_TEMPL
  3062. });
  3063. assert_eq!(s.state, State::CloseWait);
  3064. recv!(s, [TcpRepr {
  3065. seq_number: LOCAL_SEQ + 1,
  3066. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3067. ..RECV_TEMPL
  3068. }]);
  3069. s.close();
  3070. assert_eq!(s.state, State::LastAck);
  3071. recv!(s, [TcpRepr {
  3072. control: TcpControl::Fin,
  3073. seq_number: LOCAL_SEQ + 1,
  3074. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3075. ..RECV_TEMPL
  3076. }]);
  3077. send!(s, TcpRepr {
  3078. seq_number: REMOTE_SEQ + 1 + 1,
  3079. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3080. ..SEND_TEMPL
  3081. });
  3082. assert_eq!(s.state, State::Closed);
  3083. }
  3084. #[test]
  3085. fn test_local_close() {
  3086. let mut s = socket_established();
  3087. s.close();
  3088. assert_eq!(s.state, State::FinWait1);
  3089. recv!(s, [TcpRepr {
  3090. control: TcpControl::Fin,
  3091. seq_number: LOCAL_SEQ + 1,
  3092. ack_number: Some(REMOTE_SEQ + 1),
  3093. ..RECV_TEMPL
  3094. }]);
  3095. send!(s, TcpRepr {
  3096. seq_number: REMOTE_SEQ + 1,
  3097. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3098. ..SEND_TEMPL
  3099. });
  3100. assert_eq!(s.state, State::FinWait2);
  3101. send!(s, TcpRepr {
  3102. control: TcpControl::Fin,
  3103. seq_number: REMOTE_SEQ + 1,
  3104. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3105. ..SEND_TEMPL
  3106. });
  3107. assert_eq!(s.state, State::TimeWait);
  3108. recv!(s, [TcpRepr {
  3109. seq_number: LOCAL_SEQ + 1 + 1,
  3110. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3111. ..RECV_TEMPL
  3112. }]);
  3113. }
  3114. #[test]
  3115. fn test_simultaneous_close() {
  3116. let mut s = socket_established();
  3117. s.close();
  3118. assert_eq!(s.state, State::FinWait1);
  3119. recv!(s, [TcpRepr { // due to reordering, this is logically located...
  3120. control: TcpControl::Fin,
  3121. seq_number: LOCAL_SEQ + 1,
  3122. ack_number: Some(REMOTE_SEQ + 1),
  3123. ..RECV_TEMPL
  3124. }]);
  3125. send!(s, TcpRepr {
  3126. control: TcpControl::Fin,
  3127. seq_number: REMOTE_SEQ + 1,
  3128. ack_number: Some(LOCAL_SEQ + 1),
  3129. ..SEND_TEMPL
  3130. });
  3131. assert_eq!(s.state, State::Closing);
  3132. recv!(s, [TcpRepr {
  3133. seq_number: LOCAL_SEQ + 1 + 1,
  3134. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3135. ..RECV_TEMPL
  3136. }]);
  3137. // ... at this point
  3138. send!(s, TcpRepr {
  3139. seq_number: REMOTE_SEQ + 1 + 1,
  3140. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3141. ..SEND_TEMPL
  3142. });
  3143. assert_eq!(s.state, State::TimeWait);
  3144. recv!(s, []);
  3145. }
  3146. #[test]
  3147. fn test_simultaneous_close_combined_fin_ack() {
  3148. let mut s = socket_established();
  3149. s.close();
  3150. assert_eq!(s.state, State::FinWait1);
  3151. recv!(s, [TcpRepr {
  3152. control: TcpControl::Fin,
  3153. seq_number: LOCAL_SEQ + 1,
  3154. ack_number: Some(REMOTE_SEQ + 1),
  3155. ..RECV_TEMPL
  3156. }]);
  3157. send!(s, TcpRepr {
  3158. control: TcpControl::Fin,
  3159. seq_number: REMOTE_SEQ + 1,
  3160. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3161. ..SEND_TEMPL
  3162. });
  3163. assert_eq!(s.state, State::TimeWait);
  3164. recv!(s, [TcpRepr {
  3165. seq_number: LOCAL_SEQ + 1 + 1,
  3166. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3167. ..RECV_TEMPL
  3168. }]);
  3169. }
  3170. #[test]
  3171. fn test_simultaneous_close_raced() {
  3172. let mut s = socket_established();
  3173. s.close();
  3174. assert_eq!(s.state, State::FinWait1);
  3175. // Socket receives FIN before it has a chance to send its own FIN
  3176. send!(s, TcpRepr {
  3177. control: TcpControl::Fin,
  3178. seq_number: REMOTE_SEQ + 1,
  3179. ack_number: Some(LOCAL_SEQ + 1),
  3180. ..SEND_TEMPL
  3181. });
  3182. assert_eq!(s.state, State::Closing);
  3183. // FIN + ack-of-FIN
  3184. recv!(s, [TcpRepr {
  3185. control: TcpControl::Fin,
  3186. seq_number: LOCAL_SEQ + 1,
  3187. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3188. ..RECV_TEMPL
  3189. }]);
  3190. assert_eq!(s.state, State::Closing);
  3191. send!(s, TcpRepr {
  3192. seq_number: REMOTE_SEQ + 1 + 1,
  3193. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3194. ..SEND_TEMPL
  3195. });
  3196. assert_eq!(s.state, State::TimeWait);
  3197. recv!(s, []);
  3198. }
  3199. #[test]
  3200. fn test_simultaneous_close_raced_with_data() {
  3201. let mut s = socket_established();
  3202. s.send_slice(b"abcdef").unwrap();
  3203. s.close();
  3204. assert_eq!(s.state, State::FinWait1);
  3205. // Socket receives FIN before it has a chance to send its own data+FIN
  3206. send!(s, TcpRepr {
  3207. control: TcpControl::Fin,
  3208. seq_number: REMOTE_SEQ + 1,
  3209. ack_number: Some(LOCAL_SEQ + 1),
  3210. ..SEND_TEMPL
  3211. });
  3212. assert_eq!(s.state, State::Closing);
  3213. // data + FIN + ack-of-FIN
  3214. recv!(s, [TcpRepr {
  3215. control: TcpControl::Fin,
  3216. seq_number: LOCAL_SEQ + 1,
  3217. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3218. payload: &b"abcdef"[..],
  3219. ..RECV_TEMPL
  3220. }]);
  3221. assert_eq!(s.state, State::Closing);
  3222. send!(s, TcpRepr {
  3223. seq_number: REMOTE_SEQ + 1 + 1,
  3224. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3225. ..SEND_TEMPL
  3226. });
  3227. assert_eq!(s.state, State::TimeWait);
  3228. recv!(s, []);
  3229. }
  3230. #[test]
  3231. fn test_fin_with_data() {
  3232. let mut s = socket_established();
  3233. s.send_slice(b"abcdef").unwrap();
  3234. s.close();
  3235. recv!(s, [TcpRepr {
  3236. control: TcpControl::Fin,
  3237. seq_number: LOCAL_SEQ + 1,
  3238. ack_number: Some(REMOTE_SEQ + 1),
  3239. payload: &b"abcdef"[..],
  3240. ..RECV_TEMPL
  3241. }])
  3242. }
  3243. #[test]
  3244. fn test_mutual_close_with_data_1() {
  3245. let mut s = socket_established();
  3246. s.send_slice(b"abcdef").unwrap();
  3247. s.close();
  3248. assert_eq!(s.state, State::FinWait1);
  3249. recv!(s, [TcpRepr {
  3250. control: TcpControl::Fin,
  3251. seq_number: LOCAL_SEQ + 1,
  3252. ack_number: Some(REMOTE_SEQ + 1),
  3253. payload: &b"abcdef"[..],
  3254. ..RECV_TEMPL
  3255. }]);
  3256. send!(s, TcpRepr {
  3257. control: TcpControl::Fin,
  3258. seq_number: REMOTE_SEQ + 1,
  3259. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3260. ..SEND_TEMPL
  3261. });
  3262. }
  3263. #[test]
  3264. fn test_mutual_close_with_data_2() {
  3265. let mut s = socket_established();
  3266. s.send_slice(b"abcdef").unwrap();
  3267. s.close();
  3268. assert_eq!(s.state, State::FinWait1);
  3269. recv!(s, [TcpRepr {
  3270. control: TcpControl::Fin,
  3271. seq_number: LOCAL_SEQ + 1,
  3272. ack_number: Some(REMOTE_SEQ + 1),
  3273. payload: &b"abcdef"[..],
  3274. ..RECV_TEMPL
  3275. }]);
  3276. send!(s, TcpRepr {
  3277. seq_number: REMOTE_SEQ + 1,
  3278. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3279. ..SEND_TEMPL
  3280. });
  3281. assert_eq!(s.state, State::FinWait2);
  3282. send!(s, TcpRepr {
  3283. control: TcpControl::Fin,
  3284. seq_number: REMOTE_SEQ + 1,
  3285. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3286. ..SEND_TEMPL
  3287. });
  3288. recv!(s, [TcpRepr {
  3289. seq_number: LOCAL_SEQ + 1 + 6 + 1,
  3290. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3291. ..RECV_TEMPL
  3292. }]);
  3293. assert_eq!(s.state, State::TimeWait);
  3294. }
  3295. // =========================================================================================//
  3296. // Tests for retransmission on packet loss.
  3297. // =========================================================================================//
  3298. #[test]
  3299. fn test_duplicate_seq_ack() {
  3300. let mut s = socket_recved();
  3301. // remote retransmission
  3302. send!(s, TcpRepr {
  3303. seq_number: REMOTE_SEQ + 1,
  3304. ack_number: Some(LOCAL_SEQ + 1),
  3305. payload: &b"abcdef"[..],
  3306. ..SEND_TEMPL
  3307. }, Ok(Some(TcpRepr {
  3308. seq_number: LOCAL_SEQ + 1,
  3309. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3310. window_len: 58,
  3311. ..RECV_TEMPL
  3312. })));
  3313. }
  3314. #[test]
  3315. fn test_data_retransmit() {
  3316. let mut s = socket_established();
  3317. s.send_slice(b"abcdef").unwrap();
  3318. recv!(s, time 1000, Ok(TcpRepr {
  3319. seq_number: LOCAL_SEQ + 1,
  3320. ack_number: Some(REMOTE_SEQ + 1),
  3321. payload: &b"abcdef"[..],
  3322. ..RECV_TEMPL
  3323. }));
  3324. recv!(s, time 1050, Err(Error::Exhausted));
  3325. recv!(s, time 1100, Ok(TcpRepr {
  3326. seq_number: LOCAL_SEQ + 1,
  3327. ack_number: Some(REMOTE_SEQ + 1),
  3328. payload: &b"abcdef"[..],
  3329. ..RECV_TEMPL
  3330. }));
  3331. }
  3332. #[test]
  3333. fn test_data_retransmit_bursts() {
  3334. let mut s = socket_established();
  3335. s.remote_mss = 6;
  3336. s.send_slice(b"abcdef012345").unwrap();
  3337. recv!(s, time 0, Ok(TcpRepr {
  3338. control: TcpControl::None,
  3339. seq_number: LOCAL_SEQ + 1,
  3340. ack_number: Some(REMOTE_SEQ + 1),
  3341. payload: &b"abcdef"[..],
  3342. ..RECV_TEMPL
  3343. }), exact);
  3344. recv!(s, time 0, Ok(TcpRepr {
  3345. control: TcpControl::Psh,
  3346. seq_number: LOCAL_SEQ + 1 + 6,
  3347. ack_number: Some(REMOTE_SEQ + 1),
  3348. payload: &b"012345"[..],
  3349. ..RECV_TEMPL
  3350. }), exact);
  3351. recv!(s, time 0, Err(Error::Exhausted));
  3352. recv!(s, time 50, Err(Error::Exhausted));
  3353. recv!(s, time 100, Ok(TcpRepr {
  3354. control: TcpControl::None,
  3355. seq_number: LOCAL_SEQ + 1,
  3356. ack_number: Some(REMOTE_SEQ + 1),
  3357. payload: &b"abcdef"[..],
  3358. ..RECV_TEMPL
  3359. }), exact);
  3360. recv!(s, time 150, Ok(TcpRepr {
  3361. control: TcpControl::Psh,
  3362. seq_number: LOCAL_SEQ + 1 + 6,
  3363. ack_number: Some(REMOTE_SEQ + 1),
  3364. payload: &b"012345"[..],
  3365. ..RECV_TEMPL
  3366. }), exact);
  3367. recv!(s, time 200, Err(Error::Exhausted));
  3368. }
  3369. #[test]
  3370. fn test_send_data_after_syn_ack_retransmit() {
  3371. let mut s = socket_syn_received();
  3372. recv!(s, time 50, Ok(TcpRepr {
  3373. control: TcpControl::Syn,
  3374. seq_number: LOCAL_SEQ,
  3375. ack_number: Some(REMOTE_SEQ + 1),
  3376. max_seg_size: Some(BASE_MSS),
  3377. ..RECV_TEMPL
  3378. }));
  3379. recv!(s, time 150, Ok(TcpRepr { // retransmit
  3380. control: TcpControl::Syn,
  3381. seq_number: LOCAL_SEQ,
  3382. ack_number: Some(REMOTE_SEQ + 1),
  3383. max_seg_size: Some(BASE_MSS),
  3384. ..RECV_TEMPL
  3385. }));
  3386. send!(s, TcpRepr {
  3387. seq_number: REMOTE_SEQ + 1,
  3388. ack_number: Some(LOCAL_SEQ + 1),
  3389. ..SEND_TEMPL
  3390. });
  3391. assert_eq!(s.state(), State::Established);
  3392. s.send_slice(b"abcdef").unwrap();
  3393. recv!(s, [TcpRepr {
  3394. seq_number: LOCAL_SEQ + 1,
  3395. ack_number: Some(REMOTE_SEQ + 1),
  3396. payload: &b"abcdef"[..],
  3397. ..RECV_TEMPL
  3398. }])
  3399. }
  3400. #[test]
  3401. fn test_established_retransmit_for_dup_ack() {
  3402. let mut s = socket_established();
  3403. // Duplicate ACKs do not replace the retransmission timer
  3404. s.send_slice(b"abc").unwrap();
  3405. recv!(s, time 1000, Ok(TcpRepr {
  3406. seq_number: LOCAL_SEQ + 1,
  3407. ack_number: Some(REMOTE_SEQ + 1),
  3408. payload: &b"abc"[..],
  3409. ..RECV_TEMPL
  3410. }));
  3411. // Retransmit timer is on because all data was sent
  3412. assert_eq!(s.tx_buffer.len(), 3);
  3413. // ACK nothing new
  3414. send!(s, TcpRepr {
  3415. seq_number: REMOTE_SEQ + 1,
  3416. ack_number: Some(LOCAL_SEQ + 1),
  3417. ..SEND_TEMPL
  3418. });
  3419. // Retransmit
  3420. recv!(s, time 4000, Ok(TcpRepr {
  3421. seq_number: LOCAL_SEQ + 1,
  3422. ack_number: Some(REMOTE_SEQ + 1),
  3423. payload: &b"abc"[..],
  3424. ..RECV_TEMPL
  3425. }));
  3426. }
  3427. #[test]
  3428. fn test_established_retransmit_reset_after_ack() {
  3429. let mut s = socket_established();
  3430. s.remote_win_len = 6;
  3431. s.send_slice(b"abcdef").unwrap();
  3432. s.send_slice(b"123456").unwrap();
  3433. s.send_slice(b"ABCDEF").unwrap();
  3434. recv!(s, time 1000, Ok(TcpRepr {
  3435. seq_number: LOCAL_SEQ + 1,
  3436. ack_number: Some(REMOTE_SEQ + 1),
  3437. payload: &b"abcdef"[..],
  3438. ..RECV_TEMPL
  3439. }));
  3440. send!(s, time 1005, TcpRepr {
  3441. seq_number: REMOTE_SEQ + 1,
  3442. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3443. window_len: 6,
  3444. ..SEND_TEMPL
  3445. });
  3446. recv!(s, time 1010, Ok(TcpRepr {
  3447. seq_number: LOCAL_SEQ + 1 + 6,
  3448. ack_number: Some(REMOTE_SEQ + 1),
  3449. payload: &b"123456"[..],
  3450. ..RECV_TEMPL
  3451. }));
  3452. send!(s, time 1015, TcpRepr {
  3453. seq_number: REMOTE_SEQ + 1,
  3454. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3455. window_len: 6,
  3456. ..SEND_TEMPL
  3457. });
  3458. recv!(s, time 1020, Ok(TcpRepr {
  3459. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3460. ack_number: Some(REMOTE_SEQ + 1),
  3461. payload: &b"ABCDEF"[..],
  3462. ..RECV_TEMPL
  3463. }));
  3464. }
  3465. #[test]
  3466. fn test_established_queue_during_retransmission() {
  3467. let mut s = socket_established();
  3468. s.remote_mss = 6;
  3469. s.send_slice(b"abcdef123456ABCDEF").unwrap();
  3470. recv!(s, time 1000, Ok(TcpRepr {
  3471. seq_number: LOCAL_SEQ + 1,
  3472. ack_number: Some(REMOTE_SEQ + 1),
  3473. payload: &b"abcdef"[..],
  3474. ..RECV_TEMPL
  3475. })); // this one is dropped
  3476. recv!(s, time 1005, Ok(TcpRepr {
  3477. seq_number: LOCAL_SEQ + 1 + 6,
  3478. ack_number: Some(REMOTE_SEQ + 1),
  3479. payload: &b"123456"[..],
  3480. ..RECV_TEMPL
  3481. })); // this one is received
  3482. recv!(s, time 1010, Ok(TcpRepr {
  3483. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3484. ack_number: Some(REMOTE_SEQ + 1),
  3485. payload: &b"ABCDEF"[..],
  3486. ..RECV_TEMPL
  3487. })); // also dropped
  3488. recv!(s, time 2000, Ok(TcpRepr {
  3489. seq_number: LOCAL_SEQ + 1,
  3490. ack_number: Some(REMOTE_SEQ + 1),
  3491. payload: &b"abcdef"[..],
  3492. ..RECV_TEMPL
  3493. })); // retransmission
  3494. send!(s, time 2005, TcpRepr {
  3495. seq_number: REMOTE_SEQ + 1,
  3496. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3497. ..SEND_TEMPL
  3498. }); // acknowledgement of both segments
  3499. recv!(s, time 2010, Ok(TcpRepr {
  3500. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3501. ack_number: Some(REMOTE_SEQ + 1),
  3502. payload: &b"ABCDEF"[..],
  3503. ..RECV_TEMPL
  3504. })); // retransmission of only unacknowledged data
  3505. }
  3506. #[test]
  3507. fn test_close_wait_retransmit_reset_after_ack() {
  3508. let mut s = socket_close_wait();
  3509. s.remote_win_len = 6;
  3510. s.send_slice(b"abcdef").unwrap();
  3511. s.send_slice(b"123456").unwrap();
  3512. s.send_slice(b"ABCDEF").unwrap();
  3513. recv!(s, time 1000, Ok(TcpRepr {
  3514. seq_number: LOCAL_SEQ + 1,
  3515. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3516. payload: &b"abcdef"[..],
  3517. ..RECV_TEMPL
  3518. }));
  3519. send!(s, time 1005, TcpRepr {
  3520. seq_number: REMOTE_SEQ + 1 + 1,
  3521. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3522. window_len: 6,
  3523. ..SEND_TEMPL
  3524. });
  3525. recv!(s, time 1010, Ok(TcpRepr {
  3526. seq_number: LOCAL_SEQ + 1 + 6,
  3527. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3528. payload: &b"123456"[..],
  3529. ..RECV_TEMPL
  3530. }));
  3531. send!(s, time 1015, TcpRepr {
  3532. seq_number: REMOTE_SEQ + 1 + 1,
  3533. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3534. window_len: 6,
  3535. ..SEND_TEMPL
  3536. });
  3537. recv!(s, time 1020, Ok(TcpRepr {
  3538. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3539. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3540. payload: &b"ABCDEF"[..],
  3541. ..RECV_TEMPL
  3542. }));
  3543. }
  3544. #[test]
  3545. fn test_fin_wait_1_retransmit_reset_after_ack() {
  3546. let mut s = socket_established();
  3547. s.remote_win_len = 6;
  3548. s.send_slice(b"abcdef").unwrap();
  3549. s.send_slice(b"123456").unwrap();
  3550. s.send_slice(b"ABCDEF").unwrap();
  3551. s.close();
  3552. recv!(s, time 1000, Ok(TcpRepr {
  3553. seq_number: LOCAL_SEQ + 1,
  3554. ack_number: Some(REMOTE_SEQ + 1),
  3555. payload: &b"abcdef"[..],
  3556. ..RECV_TEMPL
  3557. }));
  3558. send!(s, time 1005, TcpRepr {
  3559. seq_number: REMOTE_SEQ + 1,
  3560. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3561. window_len: 6,
  3562. ..SEND_TEMPL
  3563. });
  3564. recv!(s, time 1010, Ok(TcpRepr {
  3565. seq_number: LOCAL_SEQ + 1 + 6,
  3566. ack_number: Some(REMOTE_SEQ + 1),
  3567. payload: &b"123456"[..],
  3568. ..RECV_TEMPL
  3569. }));
  3570. send!(s, time 1015, TcpRepr {
  3571. seq_number: REMOTE_SEQ + 1,
  3572. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3573. window_len: 6,
  3574. ..SEND_TEMPL
  3575. });
  3576. recv!(s, time 1020, Ok(TcpRepr {
  3577. control: TcpControl::Fin,
  3578. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3579. ack_number: Some(REMOTE_SEQ + 1),
  3580. payload: &b"ABCDEF"[..],
  3581. ..RECV_TEMPL
  3582. }));
  3583. }
  3584. #[test]
  3585. fn test_fast_retransmit_after_triple_duplicate_ack() {
  3586. let mut s = socket_established();
  3587. s.remote_mss = 6;
  3588. // Normal ACK of previously recived segment
  3589. send!(s, time 0, TcpRepr {
  3590. seq_number: REMOTE_SEQ + 1,
  3591. ack_number: Some(LOCAL_SEQ + 1),
  3592. ..SEND_TEMPL
  3593. });
  3594. // Send a long string of text divided into several packets
  3595. // because of previously recieved "window_len"
  3596. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  3597. // This packet is lost
  3598. recv!(s, time 1000, Ok(TcpRepr {
  3599. seq_number: LOCAL_SEQ + 1,
  3600. ack_number: Some(REMOTE_SEQ + 1),
  3601. payload: &b"xxxxxx"[..],
  3602. ..RECV_TEMPL
  3603. }));
  3604. recv!(s, time 1005, Ok(TcpRepr {
  3605. seq_number: LOCAL_SEQ + 1 + 6,
  3606. ack_number: Some(REMOTE_SEQ + 1),
  3607. payload: &b"yyyyyy"[..],
  3608. ..RECV_TEMPL
  3609. }));
  3610. recv!(s, time 1010, Ok(TcpRepr {
  3611. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3612. ack_number: Some(REMOTE_SEQ + 1),
  3613. payload: &b"wwwwww"[..],
  3614. ..RECV_TEMPL
  3615. }));
  3616. recv!(s, time 1015, Ok(TcpRepr {
  3617. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3618. ack_number: Some(REMOTE_SEQ + 1),
  3619. payload: &b"zzzzzz"[..],
  3620. ..RECV_TEMPL
  3621. }));
  3622. // First duplicate ACK
  3623. send!(s, time 1050, TcpRepr {
  3624. seq_number: REMOTE_SEQ + 1,
  3625. ack_number: Some(LOCAL_SEQ + 1),
  3626. ..SEND_TEMPL
  3627. });
  3628. // Second duplicate ACK
  3629. send!(s, time 1055, TcpRepr {
  3630. seq_number: REMOTE_SEQ + 1,
  3631. ack_number: Some(LOCAL_SEQ + 1),
  3632. ..SEND_TEMPL
  3633. });
  3634. // Third duplicate ACK
  3635. // Should trigger a fast retransmit of dropped packet
  3636. send!(s, time 1060, TcpRepr {
  3637. seq_number: REMOTE_SEQ + 1,
  3638. ack_number: Some(LOCAL_SEQ + 1),
  3639. ..SEND_TEMPL
  3640. });
  3641. // Fast retransmit packet
  3642. recv!(s, time 1100, Ok(TcpRepr {
  3643. seq_number: LOCAL_SEQ + 1,
  3644. ack_number: Some(REMOTE_SEQ + 1),
  3645. payload: &b"xxxxxx"[..],
  3646. ..RECV_TEMPL
  3647. }));
  3648. recv!(s, time 1105, Ok(TcpRepr {
  3649. seq_number: LOCAL_SEQ + 1 + 6,
  3650. ack_number: Some(REMOTE_SEQ + 1),
  3651. payload: &b"yyyyyy"[..],
  3652. ..RECV_TEMPL
  3653. }));
  3654. recv!(s, time 1110, Ok(TcpRepr {
  3655. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3656. ack_number: Some(REMOTE_SEQ + 1),
  3657. payload: &b"wwwwww"[..],
  3658. ..RECV_TEMPL
  3659. }));
  3660. recv!(s, time 1115, Ok(TcpRepr {
  3661. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3662. ack_number: Some(REMOTE_SEQ + 1),
  3663. payload: &b"zzzzzz"[..],
  3664. ..RECV_TEMPL
  3665. }));
  3666. // After all was send out, enter *normal* retransmission,
  3667. // don't stay in fast retransmission.
  3668. assert!(match s.timer {
  3669. Timer::Retransmit { expires_at, .. } => expires_at > Instant::from_millis(1115),
  3670. _ => false,
  3671. });
  3672. // ACK all recived segments
  3673. send!(s, time 1120, TcpRepr {
  3674. seq_number: REMOTE_SEQ + 1,
  3675. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  3676. ..SEND_TEMPL
  3677. });
  3678. }
  3679. #[test]
  3680. fn test_fast_retransmit_duplicate_detection_with_data() {
  3681. let mut s = socket_established();
  3682. s.send_slice(b"abc").unwrap(); // This is lost
  3683. recv!(s, time 1000, Ok(TcpRepr {
  3684. seq_number: LOCAL_SEQ + 1,
  3685. ack_number: Some(REMOTE_SEQ + 1),
  3686. payload: &b"abc"[..],
  3687. ..RECV_TEMPL
  3688. }));
  3689. // Normal ACK of previously recieved segment
  3690. send!(s, TcpRepr {
  3691. seq_number: REMOTE_SEQ + 1,
  3692. ack_number: Some(LOCAL_SEQ + 1),
  3693. ..SEND_TEMPL
  3694. });
  3695. // First duplicate
  3696. send!(s, TcpRepr {
  3697. seq_number: REMOTE_SEQ + 1,
  3698. ack_number: Some(LOCAL_SEQ + 1),
  3699. ..SEND_TEMPL
  3700. });
  3701. // Second duplicate
  3702. send!(s, TcpRepr {
  3703. seq_number: REMOTE_SEQ + 1,
  3704. ack_number: Some(LOCAL_SEQ + 1),
  3705. ..SEND_TEMPL
  3706. });
  3707. assert_eq!(s.local_rx_dup_acks, 2,
  3708. "duplicate ACK counter is not set");
  3709. // This packet has content, hence should not be detected
  3710. // as a duplicate ACK and should reset the duplicate ACK count
  3711. send!(s, TcpRepr {
  3712. seq_number: REMOTE_SEQ + 1,
  3713. ack_number: Some(LOCAL_SEQ + 1),
  3714. payload: &b"xxxxxx"[..],
  3715. ..SEND_TEMPL
  3716. });
  3717. recv!(s, [TcpRepr {
  3718. seq_number: LOCAL_SEQ + 1 + 3,
  3719. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3720. window_len: 58,
  3721. ..RECV_TEMPL
  3722. }]);
  3723. assert_eq!(s.local_rx_dup_acks, 0,
  3724. "duplicate ACK counter is not reset when reciving data");
  3725. }
  3726. #[test]
  3727. fn test_fast_retransmit_duplicate_detection() {
  3728. let mut s = socket_established();
  3729. s.remote_mss = 6;
  3730. // Normal ACK of previously recived segment
  3731. send!(s, time 0, TcpRepr {
  3732. seq_number: REMOTE_SEQ + 1,
  3733. ack_number: Some(LOCAL_SEQ + 1),
  3734. ..SEND_TEMPL
  3735. });
  3736. // First duplicate, should not be counted as there is nothing to resend
  3737. send!(s, time 0, TcpRepr {
  3738. seq_number: REMOTE_SEQ + 1,
  3739. ack_number: Some(LOCAL_SEQ + 1),
  3740. ..SEND_TEMPL
  3741. });
  3742. assert_eq!(s.local_rx_dup_acks, 0,
  3743. "duplicate ACK counter is set but wound not transmit data");
  3744. // Send a long string of text divided into several packets
  3745. // because of small remote_mss
  3746. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  3747. // This packet is reordered in network
  3748. recv!(s, time 1000, Ok(TcpRepr {
  3749. seq_number: LOCAL_SEQ + 1,
  3750. ack_number: Some(REMOTE_SEQ + 1),
  3751. payload: &b"xxxxxx"[..],
  3752. ..RECV_TEMPL
  3753. }));
  3754. recv!(s, time 1005, Ok(TcpRepr {
  3755. seq_number: LOCAL_SEQ + 1 + 6,
  3756. ack_number: Some(REMOTE_SEQ + 1),
  3757. payload: &b"yyyyyy"[..],
  3758. ..RECV_TEMPL
  3759. }));
  3760. recv!(s, time 1010, Ok(TcpRepr {
  3761. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3762. ack_number: Some(REMOTE_SEQ + 1),
  3763. payload: &b"wwwwww"[..],
  3764. ..RECV_TEMPL
  3765. }));
  3766. recv!(s, time 1015, Ok(TcpRepr {
  3767. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3768. ack_number: Some(REMOTE_SEQ + 1),
  3769. payload: &b"zzzzzz"[..],
  3770. ..RECV_TEMPL
  3771. }));
  3772. // First duplicate ACK
  3773. send!(s, time 1050, TcpRepr {
  3774. seq_number: REMOTE_SEQ + 1,
  3775. ack_number: Some(LOCAL_SEQ + 1),
  3776. ..SEND_TEMPL
  3777. });
  3778. // Second duplicate ACK
  3779. send!(s, time 1055, TcpRepr {
  3780. seq_number: REMOTE_SEQ + 1,
  3781. ack_number: Some(LOCAL_SEQ + 1),
  3782. ..SEND_TEMPL
  3783. });
  3784. // Reordered packet arrives which should reset duplicate ACK count
  3785. send!(s, time 1060, TcpRepr {
  3786. seq_number: REMOTE_SEQ + 1,
  3787. ack_number: Some(LOCAL_SEQ + 1 + (6 * 3)),
  3788. ..SEND_TEMPL
  3789. });
  3790. assert_eq!(s.local_rx_dup_acks, 0,
  3791. "duplicate ACK counter is not reset when reciving ACK which updates send window");
  3792. // ACK all recived segments
  3793. send!(s, time 1120, TcpRepr {
  3794. seq_number: REMOTE_SEQ + 1,
  3795. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  3796. ..SEND_TEMPL
  3797. });
  3798. }
  3799. #[test]
  3800. fn test_fast_retransmit_dup_acks_counter() {
  3801. let mut s = socket_established();
  3802. s.send_slice(b"abc").unwrap(); // This is lost
  3803. recv!(s, time 0, Ok(TcpRepr {
  3804. seq_number: LOCAL_SEQ + 1,
  3805. ack_number: Some(REMOTE_SEQ + 1),
  3806. payload: &b"abc"[..],
  3807. ..RECV_TEMPL
  3808. }));
  3809. send!(s, time 0, TcpRepr {
  3810. seq_number: REMOTE_SEQ + 1,
  3811. ack_number: Some(LOCAL_SEQ + 1),
  3812. ..SEND_TEMPL
  3813. });
  3814. // A lot of retransmits happen here
  3815. s.local_rx_dup_acks = u8::max_value() - 1;
  3816. // Send 3 more ACKs, which could overflow local_rx_dup_acks,
  3817. // but intended behaviour is that we saturate the bounds
  3818. // of local_rx_dup_acks
  3819. send!(s, time 0, TcpRepr {
  3820. seq_number: REMOTE_SEQ + 1,
  3821. ack_number: Some(LOCAL_SEQ + 1),
  3822. ..SEND_TEMPL
  3823. });
  3824. send!(s, time 0, TcpRepr {
  3825. seq_number: REMOTE_SEQ + 1,
  3826. ack_number: Some(LOCAL_SEQ + 1),
  3827. ..SEND_TEMPL
  3828. });
  3829. send!(s, time 0, TcpRepr {
  3830. seq_number: REMOTE_SEQ + 1,
  3831. ack_number: Some(LOCAL_SEQ + 1),
  3832. ..SEND_TEMPL
  3833. });
  3834. assert_eq!(s.local_rx_dup_acks, u8::max_value(), "duplicate ACK count should not overflow but saturate");
  3835. }
  3836. // =========================================================================================//
  3837. // Tests for window management.
  3838. // =========================================================================================//
  3839. #[test]
  3840. fn test_maximum_segment_size() {
  3841. let mut s = socket_listen();
  3842. s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
  3843. send!(s, TcpRepr {
  3844. control: TcpControl::Syn,
  3845. seq_number: REMOTE_SEQ,
  3846. ack_number: None,
  3847. max_seg_size: Some(1000),
  3848. ..SEND_TEMPL
  3849. });
  3850. recv!(s, [TcpRepr {
  3851. control: TcpControl::Syn,
  3852. seq_number: LOCAL_SEQ,
  3853. ack_number: Some(REMOTE_SEQ + 1),
  3854. max_seg_size: Some(BASE_MSS),
  3855. ..RECV_TEMPL
  3856. }]);
  3857. send!(s, TcpRepr {
  3858. seq_number: REMOTE_SEQ + 1,
  3859. ack_number: Some(LOCAL_SEQ + 1),
  3860. window_len: 32767,
  3861. ..SEND_TEMPL
  3862. });
  3863. s.send_slice(&[0; 1200][..]).unwrap();
  3864. recv!(s, Ok(TcpRepr {
  3865. seq_number: LOCAL_SEQ + 1,
  3866. ack_number: Some(REMOTE_SEQ + 1),
  3867. payload: &[0; 1000][..],
  3868. ..RECV_TEMPL
  3869. }));
  3870. }
  3871. #[test]
  3872. fn test_close_wait_no_window_update() {
  3873. let mut s = socket_established();
  3874. send!(s, TcpRepr {
  3875. control: TcpControl::Fin,
  3876. seq_number: REMOTE_SEQ + 1,
  3877. ack_number: Some(LOCAL_SEQ + 1),
  3878. payload: &[1,2,3,4],
  3879. ..SEND_TEMPL
  3880. });
  3881. assert_eq!(s.state, State::CloseWait);
  3882. // we ack the FIN, with the reduced window size.
  3883. recv!(s, Ok(TcpRepr {
  3884. seq_number: LOCAL_SEQ + 1,
  3885. ack_number: Some(REMOTE_SEQ + 6),
  3886. window_len: 60,
  3887. ..RECV_TEMPL
  3888. }));
  3889. let rx_buf = &mut [0; 32];
  3890. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  3891. // check that we do NOT send a window update even if it has changed.
  3892. recv!(s, Err(Error::Exhausted));
  3893. }
  3894. #[test]
  3895. fn test_time_wait_no_window_update() {
  3896. let mut s = socket_fin_wait_2();
  3897. send!(s, TcpRepr {
  3898. control: TcpControl::Fin,
  3899. seq_number: REMOTE_SEQ + 1,
  3900. ack_number: Some(LOCAL_SEQ + 2),
  3901. payload: &[1,2,3,4],
  3902. ..SEND_TEMPL
  3903. });
  3904. assert_eq!(s.state, State::TimeWait);
  3905. // we ack the FIN, with the reduced window size.
  3906. recv!(s, Ok(TcpRepr {
  3907. seq_number: LOCAL_SEQ + 2,
  3908. ack_number: Some(REMOTE_SEQ + 6),
  3909. window_len: 60,
  3910. ..RECV_TEMPL
  3911. }));
  3912. let rx_buf = &mut [0; 32];
  3913. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  3914. // check that we do NOT send a window update even if it has changed.
  3915. recv!(s, Err(Error::Exhausted));
  3916. }
  3917. // =========================================================================================//
  3918. // Tests for flow control.
  3919. // =========================================================================================//
  3920. #[test]
  3921. fn test_psh_transmit() {
  3922. let mut s = socket_established();
  3923. s.remote_mss = 6;
  3924. s.send_slice(b"abcdef").unwrap();
  3925. s.send_slice(b"123456").unwrap();
  3926. recv!(s, time 0, Ok(TcpRepr {
  3927. control: TcpControl::None,
  3928. seq_number: LOCAL_SEQ + 1,
  3929. ack_number: Some(REMOTE_SEQ + 1),
  3930. payload: &b"abcdef"[..],
  3931. ..RECV_TEMPL
  3932. }), exact);
  3933. recv!(s, time 0, Ok(TcpRepr {
  3934. control: TcpControl::Psh,
  3935. seq_number: LOCAL_SEQ + 1 + 6,
  3936. ack_number: Some(REMOTE_SEQ + 1),
  3937. payload: &b"123456"[..],
  3938. ..RECV_TEMPL
  3939. }), exact);
  3940. }
  3941. #[test]
  3942. fn test_psh_receive() {
  3943. let mut s = socket_established();
  3944. send!(s, TcpRepr {
  3945. control: TcpControl::Psh,
  3946. seq_number: REMOTE_SEQ + 1,
  3947. ack_number: Some(LOCAL_SEQ + 1),
  3948. payload: &b"abcdef"[..],
  3949. ..SEND_TEMPL
  3950. });
  3951. recv!(s, [TcpRepr {
  3952. seq_number: LOCAL_SEQ + 1,
  3953. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3954. window_len: 58,
  3955. ..RECV_TEMPL
  3956. }]);
  3957. }
  3958. #[test]
  3959. fn test_zero_window_ack() {
  3960. let mut s = socket_established();
  3961. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3962. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3963. send!(s, TcpRepr {
  3964. seq_number: REMOTE_SEQ + 1,
  3965. ack_number: Some(LOCAL_SEQ + 1),
  3966. payload: &b"abcdef"[..],
  3967. ..SEND_TEMPL
  3968. });
  3969. recv!(s, [TcpRepr {
  3970. seq_number: LOCAL_SEQ + 1,
  3971. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3972. window_len: 0,
  3973. ..RECV_TEMPL
  3974. }]);
  3975. send!(s, TcpRepr {
  3976. seq_number: REMOTE_SEQ + 1 + 6,
  3977. ack_number: Some(LOCAL_SEQ + 1),
  3978. payload: &b"123456"[..],
  3979. ..SEND_TEMPL
  3980. }, Ok(Some(TcpRepr {
  3981. seq_number: LOCAL_SEQ + 1,
  3982. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3983. window_len: 0,
  3984. ..RECV_TEMPL
  3985. })));
  3986. }
  3987. #[test]
  3988. fn test_zero_window_ack_on_window_growth() {
  3989. let mut s = socket_established();
  3990. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3991. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3992. send!(s, TcpRepr {
  3993. seq_number: REMOTE_SEQ + 1,
  3994. ack_number: Some(LOCAL_SEQ + 1),
  3995. payload: &b"abcdef"[..],
  3996. ..SEND_TEMPL
  3997. });
  3998. recv!(s, [TcpRepr {
  3999. seq_number: LOCAL_SEQ + 1,
  4000. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4001. window_len: 0,
  4002. ..RECV_TEMPL
  4003. }]);
  4004. recv!(s, time 0, Err(Error::Exhausted));
  4005. s.recv(|buffer| {
  4006. assert_eq!(&buffer[..3], b"abc");
  4007. (3, ())
  4008. }).unwrap();
  4009. recv!(s, time 0, Ok(TcpRepr {
  4010. seq_number: LOCAL_SEQ + 1,
  4011. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4012. window_len: 3,
  4013. ..RECV_TEMPL
  4014. }));
  4015. recv!(s, time 0, Err(Error::Exhausted));
  4016. s.recv(|buffer| {
  4017. assert_eq!(buffer, b"def");
  4018. (buffer.len(), ())
  4019. }).unwrap();
  4020. recv!(s, time 0, Ok(TcpRepr {
  4021. seq_number: LOCAL_SEQ + 1,
  4022. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4023. window_len: 6,
  4024. ..RECV_TEMPL
  4025. }));
  4026. }
  4027. #[test]
  4028. fn test_fill_peer_window() {
  4029. let mut s = socket_established();
  4030. s.remote_mss = 6;
  4031. s.send_slice(b"abcdef123456!@#$%^").unwrap();
  4032. recv!(s, [TcpRepr {
  4033. seq_number: LOCAL_SEQ + 1,
  4034. ack_number: Some(REMOTE_SEQ + 1),
  4035. payload: &b"abcdef"[..],
  4036. ..RECV_TEMPL
  4037. }, TcpRepr {
  4038. seq_number: LOCAL_SEQ + 1 + 6,
  4039. ack_number: Some(REMOTE_SEQ + 1),
  4040. payload: &b"123456"[..],
  4041. ..RECV_TEMPL
  4042. }, TcpRepr {
  4043. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4044. ack_number: Some(REMOTE_SEQ + 1),
  4045. payload: &b"!@#$%^"[..],
  4046. ..RECV_TEMPL
  4047. }]);
  4048. }
  4049. #[test]
  4050. fn test_announce_window_after_read() {
  4051. let mut s = socket_established();
  4052. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4053. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4054. send!(s, TcpRepr {
  4055. seq_number: REMOTE_SEQ + 1,
  4056. ack_number: Some(LOCAL_SEQ + 1),
  4057. payload: &b"abc"[..],
  4058. ..SEND_TEMPL
  4059. });
  4060. recv!(s, [TcpRepr {
  4061. seq_number: LOCAL_SEQ + 1,
  4062. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4063. window_len: 3,
  4064. ..RECV_TEMPL
  4065. }]);
  4066. // Test that `dispatch` updates `remote_last_win`
  4067. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4068. s.recv(|buffer| {
  4069. (buffer.len(), ())
  4070. }).unwrap();
  4071. assert!(s.window_to_update());
  4072. recv!(s, [TcpRepr {
  4073. seq_number: LOCAL_SEQ + 1,
  4074. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4075. window_len: 6,
  4076. ..RECV_TEMPL
  4077. }]);
  4078. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4079. // Provoke immediate ACK to test that `process` updates `remote_last_win`
  4080. send!(s, TcpRepr {
  4081. seq_number: REMOTE_SEQ + 1 + 6,
  4082. ack_number: Some(LOCAL_SEQ + 1),
  4083. payload: &b"def"[..],
  4084. ..SEND_TEMPL
  4085. }, Ok(Some(TcpRepr {
  4086. seq_number: LOCAL_SEQ + 1,
  4087. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4088. window_len: 6,
  4089. ..RECV_TEMPL
  4090. })));
  4091. send!(s, TcpRepr {
  4092. seq_number: REMOTE_SEQ + 1 + 3,
  4093. ack_number: Some(LOCAL_SEQ + 1),
  4094. payload: &b"abc"[..],
  4095. ..SEND_TEMPL
  4096. }, Ok(Some(TcpRepr {
  4097. seq_number: LOCAL_SEQ + 1,
  4098. ack_number: Some(REMOTE_SEQ + 1 + 9),
  4099. window_len: 0,
  4100. ..RECV_TEMPL
  4101. })));
  4102. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4103. s.recv(|buffer| {
  4104. (buffer.len(), ())
  4105. }).unwrap();
  4106. assert!(s.window_to_update());
  4107. }
  4108. // =========================================================================================//
  4109. // Tests for timeouts.
  4110. // =========================================================================================//
  4111. #[test]
  4112. fn test_listen_timeout() {
  4113. let mut s = socket_listen();
  4114. s.set_timeout(Some(Duration::from_millis(100)));
  4115. assert_eq!(s.poll_at(), PollAt::Ingress);
  4116. }
  4117. #[test]
  4118. fn test_connect_timeout() {
  4119. let mut s = socket();
  4120. s.local_seq_no = LOCAL_SEQ;
  4121. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  4122. s.set_timeout(Some(Duration::from_millis(100)));
  4123. recv!(s, time 150, Ok(TcpRepr {
  4124. control: TcpControl::Syn,
  4125. seq_number: LOCAL_SEQ,
  4126. ack_number: None,
  4127. max_seg_size: Some(BASE_MSS),
  4128. window_scale: Some(0),
  4129. sack_permitted: true,
  4130. ..RECV_TEMPL
  4131. }));
  4132. assert_eq!(s.state, State::SynSent);
  4133. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(250)));
  4134. recv!(s, time 250, Ok(TcpRepr {
  4135. control: TcpControl::Rst,
  4136. seq_number: LOCAL_SEQ + 1,
  4137. ack_number: Some(TcpSeqNumber(0)),
  4138. window_scale: None,
  4139. ..RECV_TEMPL
  4140. }));
  4141. assert_eq!(s.state, State::Closed);
  4142. }
  4143. #[test]
  4144. fn test_established_timeout() {
  4145. let mut s = socket_established();
  4146. s.set_timeout(Some(Duration::from_millis(200)));
  4147. recv!(s, time 250, Err(Error::Exhausted));
  4148. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(450)));
  4149. s.send_slice(b"abcdef").unwrap();
  4150. assert_eq!(s.poll_at(), PollAt::Now);
  4151. recv!(s, time 255, Ok(TcpRepr {
  4152. seq_number: LOCAL_SEQ + 1,
  4153. ack_number: Some(REMOTE_SEQ + 1),
  4154. payload: &b"abcdef"[..],
  4155. ..RECV_TEMPL
  4156. }));
  4157. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(355)));
  4158. recv!(s, time 355, Ok(TcpRepr {
  4159. seq_number: LOCAL_SEQ + 1,
  4160. ack_number: Some(REMOTE_SEQ + 1),
  4161. payload: &b"abcdef"[..],
  4162. ..RECV_TEMPL
  4163. }));
  4164. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(455)));
  4165. recv!(s, time 500, Ok(TcpRepr {
  4166. control: TcpControl::Rst,
  4167. seq_number: LOCAL_SEQ + 1 + 6,
  4168. ack_number: Some(REMOTE_SEQ + 1),
  4169. ..RECV_TEMPL
  4170. }));
  4171. assert_eq!(s.state, State::Closed);
  4172. }
  4173. #[test]
  4174. fn test_established_keep_alive_timeout() {
  4175. let mut s = socket_established();
  4176. s.set_keep_alive(Some(Duration::from_millis(50)));
  4177. s.set_timeout(Some(Duration::from_millis(100)));
  4178. recv!(s, time 100, Ok(TcpRepr {
  4179. seq_number: LOCAL_SEQ,
  4180. ack_number: Some(REMOTE_SEQ + 1),
  4181. payload: &[0],
  4182. ..RECV_TEMPL
  4183. }));
  4184. recv!(s, time 100, Err(Error::Exhausted));
  4185. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(150)));
  4186. send!(s, time 105, TcpRepr {
  4187. seq_number: REMOTE_SEQ + 1,
  4188. ack_number: Some(LOCAL_SEQ + 1),
  4189. ..SEND_TEMPL
  4190. });
  4191. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(155)));
  4192. recv!(s, time 155, Ok(TcpRepr {
  4193. seq_number: LOCAL_SEQ,
  4194. ack_number: Some(REMOTE_SEQ + 1),
  4195. payload: &[0],
  4196. ..RECV_TEMPL
  4197. }));
  4198. recv!(s, time 155, Err(Error::Exhausted));
  4199. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(205)));
  4200. recv!(s, time 200, Err(Error::Exhausted));
  4201. recv!(s, time 205, Ok(TcpRepr {
  4202. control: TcpControl::Rst,
  4203. seq_number: LOCAL_SEQ + 1,
  4204. ack_number: Some(REMOTE_SEQ + 1),
  4205. ..RECV_TEMPL
  4206. }));
  4207. recv!(s, time 205, Err(Error::Exhausted));
  4208. assert_eq!(s.state, State::Closed);
  4209. }
  4210. #[test]
  4211. fn test_fin_wait_1_timeout() {
  4212. let mut s = socket_fin_wait_1();
  4213. s.set_timeout(Some(Duration::from_millis(200)));
  4214. recv!(s, time 100, Ok(TcpRepr {
  4215. control: TcpControl::Fin,
  4216. seq_number: LOCAL_SEQ + 1,
  4217. ack_number: Some(REMOTE_SEQ + 1),
  4218. ..RECV_TEMPL
  4219. }));
  4220. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  4221. recv!(s, time 400, Ok(TcpRepr {
  4222. control: TcpControl::Rst,
  4223. seq_number: LOCAL_SEQ + 1 + 1,
  4224. ack_number: Some(REMOTE_SEQ + 1),
  4225. ..RECV_TEMPL
  4226. }));
  4227. assert_eq!(s.state, State::Closed);
  4228. }
  4229. #[test]
  4230. fn test_last_ack_timeout() {
  4231. let mut s = socket_last_ack();
  4232. s.set_timeout(Some(Duration::from_millis(200)));
  4233. recv!(s, time 100, Ok(TcpRepr {
  4234. control: TcpControl::Fin,
  4235. seq_number: LOCAL_SEQ + 1,
  4236. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4237. ..RECV_TEMPL
  4238. }));
  4239. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  4240. recv!(s, time 400, Ok(TcpRepr {
  4241. control: TcpControl::Rst,
  4242. seq_number: LOCAL_SEQ + 1 + 1,
  4243. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4244. ..RECV_TEMPL
  4245. }));
  4246. assert_eq!(s.state, State::Closed);
  4247. }
  4248. #[test]
  4249. fn test_closed_timeout() {
  4250. let mut s = socket_established();
  4251. s.set_timeout(Some(Duration::from_millis(200)));
  4252. s.remote_last_ts = Some(Instant::from_millis(100));
  4253. s.abort();
  4254. assert_eq!(s.poll_at(), PollAt::Now);
  4255. recv!(s, time 100, Ok(TcpRepr {
  4256. control: TcpControl::Rst,
  4257. seq_number: LOCAL_SEQ + 1,
  4258. ack_number: Some(REMOTE_SEQ + 1),
  4259. ..RECV_TEMPL
  4260. }));
  4261. assert_eq!(s.poll_at(), PollAt::Ingress);
  4262. }
  4263. // =========================================================================================//
  4264. // Tests for keep-alive.
  4265. // =========================================================================================//
  4266. #[test]
  4267. fn test_responds_to_keep_alive() {
  4268. let mut s = socket_established();
  4269. send!(s, TcpRepr {
  4270. seq_number: REMOTE_SEQ,
  4271. ack_number: Some(LOCAL_SEQ + 1),
  4272. ..SEND_TEMPL
  4273. }, Ok(Some(TcpRepr {
  4274. seq_number: LOCAL_SEQ + 1,
  4275. ack_number: Some(REMOTE_SEQ + 1),
  4276. ..RECV_TEMPL
  4277. })));
  4278. }
  4279. #[test]
  4280. fn test_sends_keep_alive() {
  4281. let mut s = socket_established();
  4282. s.set_keep_alive(Some(Duration::from_millis(100)));
  4283. // drain the forced keep-alive packet
  4284. assert_eq!(s.poll_at(), PollAt::Now);
  4285. recv!(s, time 0, Ok(TcpRepr {
  4286. seq_number: LOCAL_SEQ,
  4287. ack_number: Some(REMOTE_SEQ + 1),
  4288. payload: &[0],
  4289. ..RECV_TEMPL
  4290. }));
  4291. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(100)));
  4292. recv!(s, time 95, Err(Error::Exhausted));
  4293. recv!(s, time 100, Ok(TcpRepr {
  4294. seq_number: LOCAL_SEQ,
  4295. ack_number: Some(REMOTE_SEQ + 1),
  4296. payload: &[0],
  4297. ..RECV_TEMPL
  4298. }));
  4299. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  4300. recv!(s, time 195, Err(Error::Exhausted));
  4301. recv!(s, time 200, Ok(TcpRepr {
  4302. seq_number: LOCAL_SEQ,
  4303. ack_number: Some(REMOTE_SEQ + 1),
  4304. payload: &[0],
  4305. ..RECV_TEMPL
  4306. }));
  4307. send!(s, time 250, TcpRepr {
  4308. seq_number: REMOTE_SEQ + 1,
  4309. ack_number: Some(LOCAL_SEQ + 1),
  4310. ..SEND_TEMPL
  4311. });
  4312. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(350)));
  4313. recv!(s, time 345, Err(Error::Exhausted));
  4314. recv!(s, time 350, Ok(TcpRepr {
  4315. seq_number: LOCAL_SEQ,
  4316. ack_number: Some(REMOTE_SEQ + 1),
  4317. payload: &b"\x00"[..],
  4318. ..RECV_TEMPL
  4319. }));
  4320. }
  4321. // =========================================================================================//
  4322. // Tests for time-to-live configuration.
  4323. // =========================================================================================//
  4324. #[test]
  4325. fn test_set_hop_limit() {
  4326. let mut s = socket_syn_received();
  4327. let mut caps = DeviceCapabilities::default();
  4328. caps.max_transmission_unit = 1520;
  4329. s.set_hop_limit(Some(0x2a));
  4330. assert_eq!(s.dispatch(Instant::from_millis(0), &caps, |(ip_repr, _)| {
  4331. assert_eq!(ip_repr.hop_limit(), 0x2a);
  4332. Ok(())
  4333. }), Ok(()));
  4334. }
  4335. #[test]
  4336. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  4337. fn test_set_hop_limit_zero() {
  4338. let mut s = socket_syn_received();
  4339. s.set_hop_limit(Some(0));
  4340. }
  4341. // =========================================================================================//
  4342. // Tests for reassembly.
  4343. // =========================================================================================//
  4344. #[test]
  4345. fn test_out_of_order() {
  4346. let mut s = socket_established();
  4347. send!(s, TcpRepr {
  4348. seq_number: REMOTE_SEQ + 1 + 3,
  4349. ack_number: Some(LOCAL_SEQ + 1),
  4350. payload: &b"def"[..],
  4351. ..SEND_TEMPL
  4352. }, Ok(Some(TcpRepr {
  4353. seq_number: LOCAL_SEQ + 1,
  4354. ack_number: Some(REMOTE_SEQ + 1),
  4355. ..RECV_TEMPL
  4356. })));
  4357. s.recv(|buffer| {
  4358. assert_eq!(buffer, b"");
  4359. (buffer.len(), ())
  4360. }).unwrap();
  4361. send!(s, TcpRepr {
  4362. seq_number: REMOTE_SEQ + 1,
  4363. ack_number: Some(LOCAL_SEQ + 1),
  4364. payload: &b"abcdef"[..],
  4365. ..SEND_TEMPL
  4366. }, Ok(Some(TcpRepr {
  4367. seq_number: LOCAL_SEQ + 1,
  4368. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4369. window_len: 58,
  4370. ..RECV_TEMPL
  4371. })));
  4372. s.recv(|buffer| {
  4373. assert_eq!(buffer, b"abcdef");
  4374. (buffer.len(), ())
  4375. }).unwrap();
  4376. }
  4377. #[test]
  4378. fn test_buffer_wraparound_rx() {
  4379. let mut s = socket_established();
  4380. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4381. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4382. send!(s, TcpRepr {
  4383. seq_number: REMOTE_SEQ + 1,
  4384. ack_number: Some(LOCAL_SEQ + 1),
  4385. payload: &b"abc"[..],
  4386. ..SEND_TEMPL
  4387. });
  4388. s.recv(|buffer| {
  4389. assert_eq!(buffer, b"abc");
  4390. (buffer.len(), ())
  4391. }).unwrap();
  4392. send!(s, TcpRepr {
  4393. seq_number: REMOTE_SEQ + 1 + 3,
  4394. ack_number: Some(LOCAL_SEQ + 1),
  4395. payload: &b"defghi"[..],
  4396. ..SEND_TEMPL
  4397. });
  4398. let mut data = [0; 6];
  4399. assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
  4400. assert_eq!(data, &b"defghi"[..]);
  4401. }
  4402. #[test]
  4403. fn test_buffer_wraparound_tx() {
  4404. let mut s = socket_established();
  4405. s.tx_buffer = SocketBuffer::new(vec![b'.'; 9]);
  4406. assert_eq!(s.send_slice(b"xxxyyy"), Ok(6));
  4407. assert_eq!(s.tx_buffer.dequeue_many(3), &b"xxx"[..]);
  4408. assert_eq!(s.tx_buffer.len(), 3);
  4409. // "abcdef" not contiguous in tx buffer
  4410. assert_eq!(s.send_slice(b"abcdef"), Ok(6));
  4411. recv!(s, Ok(TcpRepr {
  4412. seq_number: LOCAL_SEQ + 1,
  4413. ack_number: Some(REMOTE_SEQ + 1),
  4414. payload: &b"yyyabc"[..],
  4415. ..RECV_TEMPL
  4416. }));
  4417. recv!(s, Ok(TcpRepr {
  4418. seq_number: LOCAL_SEQ + 1 + 6,
  4419. ack_number: Some(REMOTE_SEQ + 1),
  4420. payload: &b"def"[..],
  4421. ..RECV_TEMPL
  4422. }));
  4423. }
  4424. // =========================================================================================//
  4425. // Tests for graceful vs ungraceful rx close
  4426. // =========================================================================================//
  4427. #[test]
  4428. fn test_rx_close_fin() {
  4429. let mut s = socket_established();
  4430. send!(s, TcpRepr {
  4431. control: TcpControl::Fin,
  4432. seq_number: REMOTE_SEQ + 1,
  4433. ack_number: Some(LOCAL_SEQ + 1),
  4434. payload: &b"abc"[..],
  4435. ..SEND_TEMPL
  4436. });
  4437. s.recv(|data| {
  4438. assert_eq!(data, b"abc");
  4439. (3, ())
  4440. }).unwrap();
  4441. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4442. }
  4443. #[test]
  4444. fn test_rx_close_fin_in_fin_wait_1() {
  4445. let mut s = socket_fin_wait_1();
  4446. send!(s, TcpRepr {
  4447. control: TcpControl::Fin,
  4448. seq_number: REMOTE_SEQ + 1,
  4449. ack_number: Some(LOCAL_SEQ + 1),
  4450. payload: &b"abc"[..],
  4451. ..SEND_TEMPL
  4452. });
  4453. assert_eq!(s.state, State::Closing);
  4454. s.recv(|data| {
  4455. assert_eq!(data, b"abc");
  4456. (3, ())
  4457. }).unwrap();
  4458. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4459. }
  4460. #[test]
  4461. fn test_rx_close_fin_in_fin_wait_2() {
  4462. let mut s = socket_fin_wait_2();
  4463. send!(s, TcpRepr {
  4464. control: TcpControl::Fin,
  4465. seq_number: REMOTE_SEQ + 1,
  4466. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4467. payload: &b"abc"[..],
  4468. ..SEND_TEMPL
  4469. });
  4470. assert_eq!(s.state, State::TimeWait);
  4471. s.recv(|data| {
  4472. assert_eq!(data, b"abc");
  4473. (3, ())
  4474. }).unwrap();
  4475. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4476. }
  4477. #[test]
  4478. fn test_rx_close_fin_with_hole() {
  4479. let mut s = socket_established();
  4480. send!(s, TcpRepr {
  4481. seq_number: REMOTE_SEQ + 1,
  4482. ack_number: Some(LOCAL_SEQ + 1),
  4483. payload: &b"abc"[..],
  4484. ..SEND_TEMPL
  4485. });
  4486. send!(s, TcpRepr {
  4487. control: TcpControl::Fin,
  4488. seq_number: REMOTE_SEQ + 1 + 6,
  4489. ack_number: Some(LOCAL_SEQ + 1),
  4490. payload: &b"ghi"[..],
  4491. ..SEND_TEMPL
  4492. }, Ok(Some(TcpRepr {
  4493. seq_number: LOCAL_SEQ + 1,
  4494. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4495. window_len: 61,
  4496. ..RECV_TEMPL
  4497. })));
  4498. s.recv(|data| {
  4499. assert_eq!(data, b"abc");
  4500. (3, ())
  4501. }).unwrap();
  4502. s.recv(|data| {
  4503. assert_eq!(data, b"");
  4504. (0, ())
  4505. }).unwrap();
  4506. send!(s, TcpRepr {
  4507. control: TcpControl::Rst,
  4508. seq_number: REMOTE_SEQ + 1 + 9,
  4509. ack_number: Some(LOCAL_SEQ + 1),
  4510. ..SEND_TEMPL
  4511. });
  4512. // Error must be `Illegal` even if we've received a FIN,
  4513. // because we are missing data.
  4514. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4515. }
  4516. #[test]
  4517. fn test_rx_close_rst() {
  4518. let mut s = socket_established();
  4519. send!(s, TcpRepr {
  4520. seq_number: REMOTE_SEQ + 1,
  4521. ack_number: Some(LOCAL_SEQ + 1),
  4522. payload: &b"abc"[..],
  4523. ..SEND_TEMPL
  4524. });
  4525. send!(s, TcpRepr {
  4526. control: TcpControl::Rst,
  4527. seq_number: REMOTE_SEQ + 1 + 3,
  4528. ack_number: Some(LOCAL_SEQ + 1),
  4529. ..SEND_TEMPL
  4530. });
  4531. s.recv(|data| {
  4532. assert_eq!(data, b"abc");
  4533. (3, ())
  4534. }).unwrap();
  4535. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4536. }
  4537. #[test]
  4538. fn test_rx_close_rst_with_hole() {
  4539. let mut s = socket_established();
  4540. send!(s, TcpRepr {
  4541. seq_number: REMOTE_SEQ + 1,
  4542. ack_number: Some(LOCAL_SEQ + 1),
  4543. payload: &b"abc"[..],
  4544. ..SEND_TEMPL
  4545. });
  4546. send!(s, TcpRepr {
  4547. seq_number: REMOTE_SEQ + 1 + 6,
  4548. ack_number: Some(LOCAL_SEQ + 1),
  4549. payload: &b"ghi"[..],
  4550. ..SEND_TEMPL
  4551. }, Ok(Some(TcpRepr {
  4552. seq_number: LOCAL_SEQ + 1,
  4553. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4554. window_len: 61,
  4555. ..RECV_TEMPL
  4556. })));
  4557. send!(s, TcpRepr {
  4558. control: TcpControl::Rst,
  4559. seq_number: REMOTE_SEQ + 1 + 9,
  4560. ack_number: Some(LOCAL_SEQ + 1),
  4561. ..SEND_TEMPL
  4562. });
  4563. s.recv(|data| {
  4564. assert_eq!(data, b"abc");
  4565. (3, ())
  4566. }).unwrap();
  4567. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4568. }
  4569. // =========================================================================================//
  4570. // Tests for packet filtering.
  4571. // =========================================================================================//
  4572. #[test]
  4573. fn test_doesnt_accept_wrong_port() {
  4574. let mut s = socket_established();
  4575. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4576. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4577. let tcp_repr = TcpRepr {
  4578. seq_number: REMOTE_SEQ + 1,
  4579. ack_number: Some(LOCAL_SEQ + 1),
  4580. dst_port: LOCAL_PORT + 1,
  4581. ..SEND_TEMPL
  4582. };
  4583. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  4584. let tcp_repr = TcpRepr {
  4585. seq_number: REMOTE_SEQ + 1,
  4586. ack_number: Some(LOCAL_SEQ + 1),
  4587. src_port: REMOTE_PORT + 1,
  4588. ..SEND_TEMPL
  4589. };
  4590. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  4591. }
  4592. #[test]
  4593. fn test_doesnt_accept_wrong_ip() {
  4594. let s = socket_established();
  4595. let tcp_repr = TcpRepr {
  4596. seq_number: REMOTE_SEQ + 1,
  4597. ack_number: Some(LOCAL_SEQ + 1),
  4598. payload: &b"abcdef"[..],
  4599. ..SEND_TEMPL
  4600. };
  4601. let ip_repr = IpRepr::Unspecified {
  4602. src_addr: MOCK_IP_ADDR_2,
  4603. dst_addr: MOCK_IP_ADDR_1,
  4604. protocol: IpProtocol::Tcp,
  4605. payload_len: tcp_repr.buffer_len(),
  4606. hop_limit: 64
  4607. };
  4608. assert!(s.accepts(&ip_repr, &tcp_repr));
  4609. let ip_repr_wrong_src = IpRepr::Unspecified {
  4610. src_addr: MOCK_IP_ADDR_3,
  4611. dst_addr: MOCK_IP_ADDR_1,
  4612. protocol: IpProtocol::Tcp,
  4613. payload_len: tcp_repr.buffer_len(),
  4614. hop_limit: 64
  4615. };
  4616. assert!(!s.accepts(&ip_repr_wrong_src, &tcp_repr));
  4617. let ip_repr_wrong_dst = IpRepr::Unspecified {
  4618. src_addr: MOCK_IP_ADDR_2,
  4619. dst_addr: MOCK_IP_ADDR_3,
  4620. protocol: IpProtocol::Tcp,
  4621. payload_len: tcp_repr.buffer_len(),
  4622. hop_limit: 64
  4623. };
  4624. assert!(!s.accepts(&ip_repr_wrong_dst, &tcp_repr));
  4625. }
  4626. // =========================================================================================//
  4627. // Timer tests
  4628. // =========================================================================================//
  4629. #[test]
  4630. fn test_timer_retransmit() {
  4631. let mut r = Timer::default();
  4632. assert_eq!(r.should_retransmit(Instant::from_secs(1)), None);
  4633. r.set_for_retransmit(Instant::from_millis(1000));
  4634. assert_eq!(r.should_retransmit(Instant::from_millis(1000)), None);
  4635. assert_eq!(r.should_retransmit(Instant::from_millis(1050)), None);
  4636. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), Some(Duration::from_millis(101)));
  4637. r.set_for_retransmit(Instant::from_millis(1101));
  4638. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), None);
  4639. assert_eq!(r.should_retransmit(Instant::from_millis(1150)), None);
  4640. assert_eq!(r.should_retransmit(Instant::from_millis(1200)), None);
  4641. assert_eq!(r.should_retransmit(Instant::from_millis(1301)), Some(Duration::from_millis(300)));
  4642. r.set_for_idle(Instant::from_millis(1301), None);
  4643. assert_eq!(r.should_retransmit(Instant::from_millis(1350)), None);
  4644. }
  4645. }