tcp.rs 230 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038
  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. #[cfg(feature = "async")]
  5. use core::task::Waker;
  6. use core::{cmp, fmt, mem};
  7. #[cfg(feature = "async")]
  8. use crate::socket::WakerRegistration;
  9. use crate::socket::{Context, PollAt, Socket, SocketHandle, SocketMeta};
  10. use crate::storage::{Assembler, RingBuffer};
  11. use crate::time::{Duration, Instant};
  12. use crate::wire::{
  13. IpAddress, IpEndpoint, IpProtocol, IpRepr, TcpControl, TcpRepr, TcpSeqNumber, TCP_HEADER_LEN,
  14. };
  15. use crate::{Error, Result};
  16. /// A TCP socket ring buffer.
  17. pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
  18. /// The state of a TCP socket, according to [RFC 793].
  19. ///
  20. /// [RFC 793]: https://tools.ietf.org/html/rfc793
  21. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  22. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  23. pub enum State {
  24. Closed,
  25. Listen,
  26. SynSent,
  27. SynReceived,
  28. Established,
  29. FinWait1,
  30. FinWait2,
  31. CloseWait,
  32. Closing,
  33. LastAck,
  34. TimeWait,
  35. }
  36. impl fmt::Display for State {
  37. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  38. match *self {
  39. State::Closed => write!(f, "CLOSED"),
  40. State::Listen => write!(f, "LISTEN"),
  41. State::SynSent => write!(f, "SYN-SENT"),
  42. State::SynReceived => write!(f, "SYN-RECEIVED"),
  43. State::Established => write!(f, "ESTABLISHED"),
  44. State::FinWait1 => write!(f, "FIN-WAIT-1"),
  45. State::FinWait2 => write!(f, "FIN-WAIT-2"),
  46. State::CloseWait => write!(f, "CLOSE-WAIT"),
  47. State::Closing => write!(f, "CLOSING"),
  48. State::LastAck => write!(f, "LAST-ACK"),
  49. State::TimeWait => write!(f, "TIME-WAIT"),
  50. }
  51. }
  52. }
  53. // Conservative initial RTT estimate.
  54. const RTTE_INITIAL_RTT: u32 = 300;
  55. const RTTE_INITIAL_DEV: u32 = 100;
  56. // Minimum "safety margin" for the RTO that kicks in when the
  57. // variance gets very low.
  58. const RTTE_MIN_MARGIN: u32 = 5;
  59. const RTTE_MIN_RTO: u32 = 10;
  60. const RTTE_MAX_RTO: u32 = 10000;
  61. #[derive(Debug, Clone, Copy)]
  62. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  63. struct RttEstimator {
  64. // Using u32 instead of Duration to save space (Duration is i64)
  65. rtt: u32,
  66. deviation: u32,
  67. timestamp: Option<(Instant, TcpSeqNumber)>,
  68. max_seq_sent: Option<TcpSeqNumber>,
  69. rto_count: u8,
  70. }
  71. impl Default for RttEstimator {
  72. fn default() -> Self {
  73. Self {
  74. rtt: RTTE_INITIAL_RTT,
  75. deviation: RTTE_INITIAL_DEV,
  76. timestamp: None,
  77. max_seq_sent: None,
  78. rto_count: 0,
  79. }
  80. }
  81. }
  82. impl RttEstimator {
  83. fn retransmission_timeout(&self) -> Duration {
  84. let margin = RTTE_MIN_MARGIN.max(self.deviation * 4);
  85. let ms = (self.rtt + margin).max(RTTE_MIN_RTO).min(RTTE_MAX_RTO);
  86. Duration::from_millis(ms as u64)
  87. }
  88. fn sample(&mut self, new_rtt: u32) {
  89. // "Congestion Avoidance and Control", Van Jacobson, Michael J. Karels, 1988
  90. self.rtt = (self.rtt * 7 + new_rtt + 7) / 8;
  91. let diff = (self.rtt as i32 - new_rtt as i32).abs() as u32;
  92. self.deviation = (self.deviation * 3 + diff + 3) / 4;
  93. self.rto_count = 0;
  94. let rto = self.retransmission_timeout().total_millis();
  95. net_trace!(
  96. "rtte: sample={:?} rtt={:?} dev={:?} rto={:?}",
  97. new_rtt,
  98. self.rtt,
  99. self.deviation,
  100. rto
  101. );
  102. }
  103. fn on_send(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
  104. if self
  105. .max_seq_sent
  106. .map(|max_seq_sent| seq > max_seq_sent)
  107. .unwrap_or(true)
  108. {
  109. self.max_seq_sent = Some(seq);
  110. if self.timestamp.is_none() {
  111. self.timestamp = Some((timestamp, seq));
  112. net_trace!("rtte: sampling at seq={:?}", seq);
  113. }
  114. }
  115. }
  116. fn on_ack(&mut self, timestamp: Instant, seq: TcpSeqNumber) {
  117. if let Some((sent_timestamp, sent_seq)) = self.timestamp {
  118. if seq >= sent_seq {
  119. self.sample((timestamp - sent_timestamp).total_millis() as u32);
  120. self.timestamp = None;
  121. }
  122. }
  123. }
  124. fn on_retransmit(&mut self) {
  125. if self.timestamp.is_some() {
  126. net_trace!("rtte: abort sampling due to retransmit");
  127. }
  128. self.timestamp = None;
  129. self.rto_count = self.rto_count.saturating_add(1);
  130. if self.rto_count >= 3 {
  131. // This happens in 2 scenarios:
  132. // - The RTT is higher than the initial estimate
  133. // - The network conditions change, suddenly making the RTT much higher
  134. // In these cases, the estimator can get stuck, because it can't sample because
  135. // all packets sent would incur a retransmit. To avoid this, force an estimate
  136. // increase if we see 3 consecutive retransmissions without any successful sample.
  137. self.rto_count = 0;
  138. self.rtt = RTTE_MAX_RTO.min(self.rtt * 2);
  139. let rto = self.retransmission_timeout().total_millis();
  140. net_trace!(
  141. "rtte: too many retransmissions, increasing: rtt={:?} dev={:?} rto={:?}",
  142. self.rtt,
  143. self.deviation,
  144. rto
  145. );
  146. }
  147. }
  148. }
  149. #[derive(Debug, Clone, Copy, PartialEq)]
  150. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  151. enum Timer {
  152. Idle {
  153. keep_alive_at: Option<Instant>,
  154. },
  155. Retransmit {
  156. expires_at: Instant,
  157. delay: Duration,
  158. },
  159. FastRetransmit,
  160. Close {
  161. expires_at: Instant,
  162. },
  163. }
  164. const ACK_DELAY_DEFAULT: Duration = Duration::from_millis(10);
  165. const CLOSE_DELAY: Duration = Duration::from_millis(10_000);
  166. impl Timer {
  167. fn new() -> Timer {
  168. Timer::Idle {
  169. keep_alive_at: None,
  170. }
  171. }
  172. fn should_keep_alive(&self, timestamp: Instant) -> bool {
  173. match *self {
  174. Timer::Idle {
  175. keep_alive_at: Some(keep_alive_at),
  176. } if timestamp >= keep_alive_at => true,
  177. _ => false,
  178. }
  179. }
  180. fn should_retransmit(&self, timestamp: Instant) -> Option<Duration> {
  181. match *self {
  182. Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
  183. Some(timestamp - expires_at + delay)
  184. }
  185. Timer::FastRetransmit => Some(Duration::from_millis(0)),
  186. _ => None,
  187. }
  188. }
  189. fn should_close(&self, timestamp: Instant) -> bool {
  190. match *self {
  191. Timer::Close { expires_at } if timestamp >= expires_at => true,
  192. _ => false,
  193. }
  194. }
  195. fn poll_at(&self) -> PollAt {
  196. match *self {
  197. Timer::Idle {
  198. keep_alive_at: Some(keep_alive_at),
  199. } => PollAt::Time(keep_alive_at),
  200. Timer::Idle {
  201. keep_alive_at: None,
  202. } => PollAt::Ingress,
  203. Timer::Retransmit { expires_at, .. } => PollAt::Time(expires_at),
  204. Timer::FastRetransmit => PollAt::Now,
  205. Timer::Close { expires_at } => PollAt::Time(expires_at),
  206. }
  207. }
  208. fn set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>) {
  209. *self = Timer::Idle {
  210. keep_alive_at: interval.map(|interval| timestamp + interval),
  211. }
  212. }
  213. fn set_keep_alive(&mut self) {
  214. if let Timer::Idle {
  215. ref mut keep_alive_at,
  216. } = *self
  217. {
  218. if keep_alive_at.is_none() {
  219. *keep_alive_at = Some(Instant::from_millis(0))
  220. }
  221. }
  222. }
  223. fn rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>) {
  224. if let Timer::Idle {
  225. ref mut keep_alive_at,
  226. } = *self
  227. {
  228. *keep_alive_at = interval.map(|interval| timestamp + interval)
  229. }
  230. }
  231. fn set_for_retransmit(&mut self, timestamp: Instant, delay: Duration) {
  232. match *self {
  233. Timer::Idle { .. } | Timer::FastRetransmit { .. } => {
  234. *self = Timer::Retransmit {
  235. expires_at: timestamp + delay,
  236. delay: delay,
  237. }
  238. }
  239. Timer::Retransmit { expires_at, delay } if timestamp >= expires_at => {
  240. *self = Timer::Retransmit {
  241. expires_at: timestamp + delay,
  242. delay: delay * 2,
  243. }
  244. }
  245. Timer::Retransmit { .. } => (),
  246. Timer::Close { .. } => (),
  247. }
  248. }
  249. fn set_for_fast_retransmit(&mut self) {
  250. *self = Timer::FastRetransmit
  251. }
  252. fn set_for_close(&mut self, timestamp: Instant) {
  253. *self = Timer::Close {
  254. expires_at: timestamp + CLOSE_DELAY,
  255. }
  256. }
  257. fn is_retransmit(&self) -> bool {
  258. match *self {
  259. Timer::Retransmit { .. } | Timer::FastRetransmit => true,
  260. _ => false,
  261. }
  262. }
  263. }
  264. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  265. enum AckDelayTimer {
  266. Idle,
  267. Waiting(Instant),
  268. Immediate,
  269. }
  270. /// A Transmission Control Protocol socket.
  271. ///
  272. /// A TCP socket may passively listen for connections or actively connect to another endpoint.
  273. /// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
  274. /// accept several connections, as many sockets must be allocated, or any new connection
  275. /// attempts will be reset.
  276. #[derive(Debug)]
  277. pub struct TcpSocket<'a> {
  278. pub(crate) meta: SocketMeta,
  279. state: State,
  280. timer: Timer,
  281. rtte: RttEstimator,
  282. assembler: Assembler,
  283. rx_buffer: SocketBuffer<'a>,
  284. rx_fin_received: bool,
  285. tx_buffer: SocketBuffer<'a>,
  286. /// Interval after which, if no inbound packets are received, the connection is aborted.
  287. timeout: Option<Duration>,
  288. /// Interval at which keep-alive packets will be sent.
  289. keep_alive: Option<Duration>,
  290. /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  291. hop_limit: Option<u8>,
  292. /// Address passed to listen(). Listen address is set when listen() is called and
  293. /// used every time the socket is reset back to the LISTEN state.
  294. listen_address: IpAddress,
  295. /// Current local endpoint. This is used for both filtering the incoming packets and
  296. /// setting the source address. When listening or initiating connection on/from
  297. /// an unspecified address, this field is updated with the chosen source address before
  298. /// any packets are sent.
  299. local_endpoint: IpEndpoint,
  300. /// Current remote endpoint. This is used for both filtering the incoming packets and
  301. /// setting the destination address. If the remote endpoint is unspecified, it means that
  302. /// aborting the connection will not send an RST, and, in TIME-WAIT state, will not
  303. /// send an ACK.
  304. remote_endpoint: IpEndpoint,
  305. /// The sequence number corresponding to the beginning of the transmit buffer.
  306. /// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
  307. local_seq_no: TcpSeqNumber,
  308. /// The sequence number corresponding to the beginning of the receive buffer.
  309. /// I.e. userspace reading n bytes adds n to remote_seq_no.
  310. remote_seq_no: TcpSeqNumber,
  311. /// The last sequence number sent.
  312. /// I.e. in an idle socket, local_seq_no+tx_buffer.len().
  313. remote_last_seq: TcpSeqNumber,
  314. /// The last acknowledgement number sent.
  315. /// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
  316. remote_last_ack: Option<TcpSeqNumber>,
  317. /// The last window length sent.
  318. remote_last_win: u16,
  319. /// The sending window scaling factor advertised to remotes which support RFC 1323.
  320. /// It is zero if the window <= 64KiB and/or the remote does not support it.
  321. remote_win_shift: u8,
  322. /// The remote window size, relative to local_seq_no
  323. /// I.e. we're allowed to send octets until local_seq_no+remote_win_len
  324. remote_win_len: usize,
  325. /// The receive window scaling factor for remotes which support RFC 1323, None if unsupported.
  326. remote_win_scale: Option<u8>,
  327. /// Whether or not the remote supports selective ACK as described in RFC 2018.
  328. remote_has_sack: bool,
  329. /// The maximum number of data octets that the remote side may receive.
  330. remote_mss: usize,
  331. /// The timestamp of the last packet received.
  332. remote_last_ts: Option<Instant>,
  333. /// The sequence number of the last packet recived, used for sACK
  334. local_rx_last_seq: Option<TcpSeqNumber>,
  335. /// The ACK number of the last packet recived.
  336. local_rx_last_ack: Option<TcpSeqNumber>,
  337. /// The number of packets recived directly after
  338. /// each other which have the same ACK number.
  339. local_rx_dup_acks: u8,
  340. /// Duration for Delayed ACK. If None no ACKs will be delayed.
  341. ack_delay: Option<Duration>,
  342. /// Delayed ack timer. If set, packets containing exclusively
  343. /// ACK or window updates (ie, no data) won't be sent until expiry.
  344. ack_delay_timer: AckDelayTimer,
  345. /// Used for rate-limiting: No more challenge ACKs will be sent until this instant.
  346. challenge_ack_timer: Instant,
  347. /// Nagle's Algorithm enabled.
  348. nagle: bool,
  349. #[cfg(feature = "async")]
  350. rx_waker: WakerRegistration,
  351. #[cfg(feature = "async")]
  352. tx_waker: WakerRegistration,
  353. }
  354. const DEFAULT_MSS: usize = 536;
  355. impl<'a> TcpSocket<'a> {
  356. #[allow(unused_comparisons)] // small usize platforms always pass rx_capacity check
  357. /// Create a socket using the given buffers.
  358. pub fn new<T>(rx_buffer: T, tx_buffer: T) -> TcpSocket<'a>
  359. where
  360. T: Into<SocketBuffer<'a>>,
  361. {
  362. let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
  363. let rx_capacity = rx_buffer.capacity();
  364. // From RFC 1323:
  365. // [...] the above constraints imply that 2 * the max window size must be less
  366. // than 2**31 [...] Thus, the shift count must be limited to 14 (which allows
  367. // windows of 2**30 = 1 Gbyte).
  368. if rx_capacity > (1 << 30) {
  369. panic!("receiving buffer too large, cannot exceed 1 GiB")
  370. }
  371. let rx_cap_log2 = mem::size_of::<usize>() * 8 - rx_capacity.leading_zeros() as usize;
  372. TcpSocket {
  373. meta: SocketMeta::default(),
  374. state: State::Closed,
  375. timer: Timer::new(),
  376. rtte: RttEstimator::default(),
  377. assembler: Assembler::new(rx_buffer.capacity()),
  378. tx_buffer: tx_buffer,
  379. rx_buffer: rx_buffer,
  380. rx_fin_received: false,
  381. timeout: None,
  382. keep_alive: None,
  383. hop_limit: None,
  384. listen_address: IpAddress::default(),
  385. local_endpoint: IpEndpoint::default(),
  386. remote_endpoint: IpEndpoint::default(),
  387. local_seq_no: TcpSeqNumber::default(),
  388. remote_seq_no: TcpSeqNumber::default(),
  389. remote_last_seq: TcpSeqNumber::default(),
  390. remote_last_ack: None,
  391. remote_last_win: 0,
  392. remote_win_len: 0,
  393. remote_win_shift: rx_cap_log2.saturating_sub(16) as u8,
  394. remote_win_scale: None,
  395. remote_has_sack: false,
  396. remote_mss: DEFAULT_MSS,
  397. remote_last_ts: None,
  398. local_rx_last_ack: None,
  399. local_rx_last_seq: None,
  400. local_rx_dup_acks: 0,
  401. ack_delay: Some(ACK_DELAY_DEFAULT),
  402. ack_delay_timer: AckDelayTimer::Idle,
  403. challenge_ack_timer: Instant::from_secs(0),
  404. nagle: true,
  405. #[cfg(feature = "async")]
  406. rx_waker: WakerRegistration::new(),
  407. #[cfg(feature = "async")]
  408. tx_waker: WakerRegistration::new(),
  409. }
  410. }
  411. /// Register a waker for receive operations.
  412. ///
  413. /// The waker is woken on state changes that might affect the return value
  414. /// of `recv` method calls, such as receiving data, or the socket closing.
  415. ///
  416. /// Notes:
  417. ///
  418. /// - Only one waker can be registered at a time. If another waker was previously registered,
  419. /// it is overwritten and will no longer be woken.
  420. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  421. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `recv` has
  422. /// necessarily changed.
  423. #[cfg(feature = "async")]
  424. pub fn register_recv_waker(&mut self, waker: &Waker) {
  425. self.rx_waker.register(waker)
  426. }
  427. /// Register a waker for send operations.
  428. ///
  429. /// The waker is woken on state changes that might affect the return value
  430. /// of `send` method calls, such as space becoming available in the transmit
  431. /// buffer, or the socket closing.
  432. ///
  433. /// Notes:
  434. ///
  435. /// - Only one waker can be registered at a time. If another waker was previously registered,
  436. /// it is overwritten and will no longer be woken.
  437. /// - The Waker is woken only once. Once woken, you must register it again to receive more wakes.
  438. /// - "Spurious wakes" are allowed: a wake doesn't guarantee the result of `send` has
  439. /// necessarily changed.
  440. #[cfg(feature = "async")]
  441. pub fn register_send_waker(&mut self, waker: &Waker) {
  442. self.tx_waker.register(waker)
  443. }
  444. /// Return the socket handle.
  445. #[inline]
  446. pub fn handle(&self) -> SocketHandle {
  447. self.meta.handle
  448. }
  449. /// Return the timeout duration.
  450. ///
  451. /// See also the [set_timeout](#method.set_timeout) method.
  452. pub fn timeout(&self) -> Option<Duration> {
  453. self.timeout
  454. }
  455. /// Return the ACK delay duration.
  456. ///
  457. /// See also the [set_ack_delay](#method.set_ack_delay) method.
  458. pub fn ack_delay(&self) -> Option<Duration> {
  459. self.ack_delay
  460. }
  461. /// Return whether Nagle's Algorithm is enabled.
  462. ///
  463. /// See also the [set_nagle_enabled](#method.set_nagle_enabled) method.
  464. pub fn nagle_enabled(&self) -> Option<Duration> {
  465. self.ack_delay
  466. }
  467. /// Return the current window field value, including scaling according to RFC 1323.
  468. ///
  469. /// Used in internal calculations as well as packet generation.
  470. ///
  471. #[inline]
  472. fn scaled_window(&self) -> u16 {
  473. cmp::min(
  474. self.rx_buffer.window() >> self.remote_win_shift as usize,
  475. (1 << 16) - 1,
  476. ) as u16
  477. }
  478. /// Set the timeout duration.
  479. ///
  480. /// A socket with a timeout duration set will abort the connection if either of the following
  481. /// occurs:
  482. ///
  483. /// * After a [connect](#method.connect) call, the remote endpoint does not respond within
  484. /// the specified duration;
  485. /// * After establishing a connection, there is data in the transmit buffer and the remote
  486. /// endpoint exceeds the specified duration between any two packets it sends;
  487. /// * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
  488. /// the specified duration between any two packets it sends.
  489. pub fn set_timeout(&mut self, duration: Option<Duration>) {
  490. self.timeout = duration
  491. }
  492. /// Set the ACK delay duration.
  493. ///
  494. /// By default, the ACK delay is set to 10ms.
  495. pub fn set_ack_delay(&mut self, duration: Option<Duration>) {
  496. self.ack_delay = duration
  497. }
  498. /// Enable or disable Nagle's Algorithm.
  499. ///
  500. /// Also known as "tinygram prevention". By default, it is enabled.
  501. /// Disabling it is equivalent to Linux's TCP_NODELAY flag.
  502. ///
  503. /// When enabled, Nagle's Algorithm prevents sending segments smaller than MSS if
  504. /// there is data in flight (sent but not acknowledged). In other words, it ensures
  505. /// at most only one segment smaller than MSS is in flight at a time.
  506. ///
  507. /// It ensures better network utilization by preventing sending many very small packets,
  508. /// at the cost of increased latency in some situations, particularly when the remote peer
  509. /// has ACK delay enabled.
  510. pub fn set_nagle_enabled(&mut self, enabled: bool) {
  511. self.nagle = enabled
  512. }
  513. /// Return the keep-alive interval.
  514. ///
  515. /// See also the [set_keep_alive](#method.set_keep_alive) method.
  516. pub fn keep_alive(&self) -> Option<Duration> {
  517. self.keep_alive
  518. }
  519. /// Set the keep-alive interval.
  520. ///
  521. /// An idle socket with a keep-alive interval set will transmit a "keep-alive ACK" packet
  522. /// every time it receives no communication during that interval. As a result, three things
  523. /// may happen:
  524. ///
  525. /// * The remote endpoint is fine and answers with an ACK packet.
  526. /// * The remote endpoint has rebooted and answers with an RST packet.
  527. /// * The remote endpoint has crashed and does not answer.
  528. ///
  529. /// The keep-alive functionality together with the timeout functionality allows to react
  530. /// to these error conditions.
  531. pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
  532. self.keep_alive = interval;
  533. if self.keep_alive.is_some() {
  534. // If the connection is idle and we've just set the option, it would not take effect
  535. // until the next packet, unless we wind up the timer explicitly.
  536. self.timer.set_keep_alive();
  537. }
  538. }
  539. /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  540. ///
  541. /// See also the [set_hop_limit](#method.set_hop_limit) method
  542. pub fn hop_limit(&self) -> Option<u8> {
  543. self.hop_limit
  544. }
  545. /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  546. ///
  547. /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
  548. /// value (64).
  549. ///
  550. /// # Panics
  551. ///
  552. /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
  553. ///
  554. /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
  555. /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
  556. pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
  557. // A host MUST NOT send a datagram with a hop limit value of 0
  558. if let Some(0) = hop_limit {
  559. panic!("the time-to-live value of a packet must not be zero")
  560. }
  561. self.hop_limit = hop_limit
  562. }
  563. /// Return the local endpoint.
  564. #[inline]
  565. pub fn local_endpoint(&self) -> IpEndpoint {
  566. self.local_endpoint
  567. }
  568. /// Return the remote endpoint.
  569. #[inline]
  570. pub fn remote_endpoint(&self) -> IpEndpoint {
  571. self.remote_endpoint
  572. }
  573. /// Return the connection state, in terms of the TCP state machine.
  574. #[inline]
  575. pub fn state(&self) -> State {
  576. self.state
  577. }
  578. fn reset(&mut self) {
  579. let rx_cap_log2 =
  580. mem::size_of::<usize>() * 8 - self.rx_buffer.capacity().leading_zeros() as usize;
  581. self.state = State::Closed;
  582. self.timer = Timer::new();
  583. self.rtte = RttEstimator::default();
  584. self.assembler = Assembler::new(self.rx_buffer.capacity());
  585. self.tx_buffer.clear();
  586. self.rx_buffer.clear();
  587. self.rx_fin_received = false;
  588. self.keep_alive = None;
  589. self.timeout = None;
  590. self.hop_limit = None;
  591. self.listen_address = IpAddress::default();
  592. self.local_endpoint = IpEndpoint::default();
  593. self.remote_endpoint = IpEndpoint::default();
  594. self.local_seq_no = TcpSeqNumber::default();
  595. self.remote_seq_no = TcpSeqNumber::default();
  596. self.remote_last_seq = TcpSeqNumber::default();
  597. self.remote_last_ack = None;
  598. self.remote_last_win = 0;
  599. self.remote_win_len = 0;
  600. self.remote_win_scale = None;
  601. self.remote_win_shift = rx_cap_log2.saturating_sub(16) as u8;
  602. self.remote_mss = DEFAULT_MSS;
  603. self.remote_last_ts = None;
  604. self.ack_delay = Some(ACK_DELAY_DEFAULT);
  605. self.ack_delay_timer = AckDelayTimer::Idle;
  606. self.challenge_ack_timer = Instant::from_secs(0);
  607. self.nagle = true;
  608. #[cfg(feature = "async")]
  609. {
  610. self.rx_waker.wake();
  611. self.tx_waker.wake();
  612. }
  613. }
  614. /// Start listening on the given endpoint.
  615. ///
  616. /// This function returns `Err(Error::Illegal)` if the socket was already open
  617. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  618. /// if the port in the given endpoint is zero.
  619. pub fn listen<T>(&mut self, local_endpoint: T) -> Result<()>
  620. where
  621. T: Into<IpEndpoint>,
  622. {
  623. let local_endpoint = local_endpoint.into();
  624. if local_endpoint.port == 0 {
  625. return Err(Error::Unaddressable);
  626. }
  627. if self.is_open() {
  628. return Err(Error::Illegal);
  629. }
  630. self.reset();
  631. self.listen_address = local_endpoint.addr;
  632. self.local_endpoint = local_endpoint;
  633. self.remote_endpoint = IpEndpoint::default();
  634. self.set_state(State::Listen);
  635. Ok(())
  636. }
  637. /// Connect to a given endpoint.
  638. ///
  639. /// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
  640. /// allocates a port between 49152 and 65535, a connection may be established as follows:
  641. ///
  642. /// ```rust,ignore
  643. /// socket.connect((IpAddress::v4(10, 0, 0, 1), 80), get_ephemeral_port())
  644. /// ```
  645. ///
  646. /// The local address may optionally be provided.
  647. ///
  648. /// This function returns an error if the socket was open; see [is_open](#method.is_open).
  649. /// It also returns an error if the local or remote port is zero, or if the remote address
  650. /// is unspecified.
  651. pub fn connect<T, U>(&mut self, remote_endpoint: T, local_endpoint: U) -> Result<()>
  652. where
  653. T: Into<IpEndpoint>,
  654. U: Into<IpEndpoint>,
  655. {
  656. let remote_endpoint = remote_endpoint.into();
  657. let local_endpoint = local_endpoint.into();
  658. if self.is_open() {
  659. return Err(Error::Illegal);
  660. }
  661. if !remote_endpoint.is_specified() {
  662. return Err(Error::Unaddressable);
  663. }
  664. if local_endpoint.port == 0 {
  665. return Err(Error::Unaddressable);
  666. }
  667. // If local address is not provided, use an unspecified address but a specified protocol.
  668. // This lets us lower IpRepr later to determine IP header size and calculate MSS,
  669. // but without committing to a specific address right away.
  670. let local_addr = match local_endpoint.addr {
  671. IpAddress::Unspecified => remote_endpoint.addr.as_unspecified(),
  672. ip => ip,
  673. };
  674. let local_endpoint = IpEndpoint {
  675. addr: local_addr,
  676. ..local_endpoint
  677. };
  678. self.reset();
  679. self.local_endpoint = local_endpoint;
  680. self.remote_endpoint = remote_endpoint;
  681. self.set_state(State::SynSent);
  682. let seq = Self::random_seq_no();
  683. self.local_seq_no = seq;
  684. self.remote_last_seq = seq;
  685. Ok(())
  686. }
  687. fn random_seq_no() -> TcpSeqNumber {
  688. #[cfg(test)]
  689. return TcpSeqNumber(10000);
  690. #[cfg(not(test))]
  691. return TcpSeqNumber(crate::rand::rand_u32() as i32);
  692. }
  693. /// Close the transmit half of the full-duplex connection.
  694. ///
  695. /// Note that there is no corresponding function for the receive half of the full-duplex
  696. /// connection; only the remote end can close it. If you no longer wish to receive any
  697. /// data and would like to reuse the socket right away, use [abort](#method.abort).
  698. pub fn close(&mut self) {
  699. match self.state {
  700. // In the LISTEN state there is no established connection.
  701. State::Listen => self.set_state(State::Closed),
  702. // In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
  703. // receiving an RST, will abort the connection.
  704. State::SynSent => self.set_state(State::Closed),
  705. // In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
  706. // of the connection is open, and needs to be explicitly closed with a FIN.
  707. State::SynReceived | State::Established => self.set_state(State::FinWait1),
  708. State::CloseWait => self.set_state(State::LastAck),
  709. // In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
  710. // the transmit half of the connection is already closed, and no further
  711. // action is needed.
  712. State::FinWait1
  713. | State::FinWait2
  714. | State::Closing
  715. | State::TimeWait
  716. | State::LastAck
  717. | State::Closed => (),
  718. }
  719. }
  720. /// Aborts the connection, if any.
  721. ///
  722. /// This function instantly closes the socket. One reset packet will be sent to the remote
  723. /// endpoint.
  724. ///
  725. /// In terms of the TCP state machine, the socket may be in any state and is moved to
  726. /// the `CLOSED` state.
  727. pub fn abort(&mut self) {
  728. self.set_state(State::Closed);
  729. }
  730. /// Return whether the socket is passively listening for incoming connections.
  731. ///
  732. /// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
  733. #[inline]
  734. pub fn is_listening(&self) -> bool {
  735. match self.state {
  736. State::Listen => true,
  737. _ => false,
  738. }
  739. }
  740. /// Return whether the socket is open.
  741. ///
  742. /// This function returns true if the socket will process incoming or dispatch outgoing
  743. /// packets. Note that this does not mean that it is possible to send or receive data through
  744. /// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
  745. ///
  746. /// In terms of the TCP state machine, the socket must not be in the `CLOSED`
  747. /// or `TIME-WAIT` states.
  748. #[inline]
  749. pub fn is_open(&self) -> bool {
  750. match self.state {
  751. State::Closed => false,
  752. State::TimeWait => false,
  753. _ => true,
  754. }
  755. }
  756. /// Return whether a connection is active.
  757. ///
  758. /// This function returns true if the socket is actively exchanging packets with
  759. /// a remote endpoint. Note that this does not mean that it is possible to send or receive
  760. /// data through the socket; for that, use [can_send](#method.can_send) or
  761. /// [can_recv](#method.can_recv).
  762. ///
  763. /// If a connection is established, [abort](#method.close) will send a reset to
  764. /// the remote endpoint.
  765. ///
  766. /// In terms of the TCP state machine, the socket must not be in the `CLOSED`, `TIME-WAIT`,
  767. /// or `LISTEN` state.
  768. #[inline]
  769. pub fn is_active(&self) -> bool {
  770. match self.state {
  771. State::Closed => false,
  772. State::TimeWait => false,
  773. State::Listen => false,
  774. _ => true,
  775. }
  776. }
  777. /// Return whether the transmit half of the full-duplex connection is open.
  778. ///
  779. /// This function returns true if it's possible to send data and have it arrive
  780. /// to the remote endpoint. However, it does not make any guarantees about the state
  781. /// of the transmit buffer, and even if it returns true, [send](#method.send) may
  782. /// not be able to enqueue any octets.
  783. ///
  784. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
  785. /// `CLOSE-WAIT` state.
  786. #[inline]
  787. pub fn may_send(&self) -> bool {
  788. match self.state {
  789. State::Established => true,
  790. // In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
  791. // but we still can transmit indefinitely.
  792. State::CloseWait => true,
  793. _ => false,
  794. }
  795. }
  796. /// Return whether the receive half of the full-duplex connection is open.
  797. ///
  798. /// This function returns true if it's possible to receive data from the remote endpoint.
  799. /// It will return true while there is data in the receive buffer, and if there isn't,
  800. /// as long as the remote endpoint has not closed the connection.
  801. ///
  802. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
  803. /// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
  804. #[inline]
  805. pub fn may_recv(&self) -> bool {
  806. match self.state {
  807. State::Established => true,
  808. // In FIN-WAIT-1/2, we have closed our transmit half of the connection but
  809. // we still can receive indefinitely.
  810. State::FinWait1 | State::FinWait2 => true,
  811. // If we have something in the receive buffer, we can receive that.
  812. _ if !self.rx_buffer.is_empty() => true,
  813. _ => false,
  814. }
  815. }
  816. /// Check whether the transmit half of the full-duplex connection is open
  817. /// (see [may_send](#method.may_send)), and the transmit buffer is not full.
  818. #[inline]
  819. pub fn can_send(&self) -> bool {
  820. if !self.may_send() {
  821. return false;
  822. }
  823. !self.tx_buffer.is_full()
  824. }
  825. /// Return the maximum number of bytes inside the recv buffer.
  826. #[inline]
  827. pub fn recv_capacity(&self) -> usize {
  828. self.rx_buffer.capacity()
  829. }
  830. /// Return the maximum number of bytes inside the transmit buffer.
  831. #[inline]
  832. pub fn send_capacity(&self) -> usize {
  833. self.tx_buffer.capacity()
  834. }
  835. /// Check whether the receive half of the full-duplex connection buffer is open
  836. /// (see [may_recv](#method.may_recv)), and the receive buffer is not empty.
  837. #[inline]
  838. pub fn can_recv(&self) -> bool {
  839. if !self.may_recv() {
  840. return false;
  841. }
  842. !self.rx_buffer.is_empty()
  843. }
  844. fn send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  845. where
  846. F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),
  847. {
  848. if !self.may_send() {
  849. return Err(Error::Illegal);
  850. }
  851. // The connection might have been idle for a long time, and so remote_last_ts
  852. // would be far in the past. Unless we clear it here, we'll abort the connection
  853. // down over in dispatch() by erroneously detecting it as timed out.
  854. if self.tx_buffer.is_empty() {
  855. self.remote_last_ts = None
  856. }
  857. let _old_length = self.tx_buffer.len();
  858. let (size, result) = f(&mut self.tx_buffer);
  859. if size > 0 {
  860. #[cfg(any(test, feature = "verbose"))]
  861. net_trace!(
  862. "{}:{}:{}: tx buffer: enqueueing {} octets (now {})",
  863. self.meta.handle,
  864. self.local_endpoint,
  865. self.remote_endpoint,
  866. size,
  867. _old_length + size
  868. );
  869. }
  870. Ok(result)
  871. }
  872. /// Call `f` with the largest contiguous slice of octets in the transmit buffer,
  873. /// and enqueue the amount of elements returned by `f`.
  874. ///
  875. /// This function returns `Err(Error::Illegal)` if the transmit half of
  876. /// the connection is not open; see [may_send](#method.may_send).
  877. pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R>
  878. where
  879. F: FnOnce(&'b mut [u8]) -> (usize, R),
  880. {
  881. self.send_impl(|tx_buffer| tx_buffer.enqueue_many_with(f))
  882. }
  883. /// Enqueue a sequence of octets to be sent, and fill it from a slice.
  884. ///
  885. /// This function returns the amount of octets actually enqueued, which is limited
  886. /// by the amount of free space in the transmit buffer; down to zero.
  887. ///
  888. /// See also [send](#method.send).
  889. pub fn send_slice(&mut self, data: &[u8]) -> Result<usize> {
  890. self.send_impl(|tx_buffer| {
  891. let size = tx_buffer.enqueue_slice(data);
  892. (size, size)
  893. })
  894. }
  895. fn recv_error_check(&mut self) -> Result<()> {
  896. // We may have received some data inside the initial SYN, but until the connection
  897. // is fully open we must not dequeue any data, as it may be overwritten by e.g.
  898. // another (stale) SYN. (We do not support TCP Fast Open.)
  899. if !self.may_recv() {
  900. if self.rx_fin_received {
  901. return Err(Error::Finished);
  902. }
  903. return Err(Error::Illegal);
  904. }
  905. Ok(())
  906. }
  907. fn recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  908. where
  909. F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R),
  910. {
  911. self.recv_error_check()?;
  912. let _old_length = self.rx_buffer.len();
  913. let (size, result) = f(&mut self.rx_buffer);
  914. self.remote_seq_no += size;
  915. if size > 0 {
  916. #[cfg(any(test, feature = "verbose"))]
  917. net_trace!(
  918. "{}:{}:{}: rx buffer: dequeueing {} octets (now {})",
  919. self.meta.handle,
  920. self.local_endpoint,
  921. self.remote_endpoint,
  922. size,
  923. _old_length - size
  924. );
  925. }
  926. Ok(result)
  927. }
  928. /// Call `f` with the largest contiguous slice of octets in the receive buffer,
  929. /// and dequeue the amount of elements returned by `f`.
  930. ///
  931. /// This function errors if the receive half of the connection is not open.
  932. ///
  933. /// If the receive half has been gracefully closed (with a FIN packet), `Err(Error::Finished)`
  934. /// is returned. In this case, the previously received data is guaranteed to be complete.
  935. ///
  936. /// In all other cases, `Err(Error::Illegal)` is returned and previously received data (if any)
  937. /// may be incomplete (truncated).
  938. pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R>
  939. where
  940. F: FnOnce(&'b mut [u8]) -> (usize, R),
  941. {
  942. self.recv_impl(|rx_buffer| rx_buffer.dequeue_many_with(f))
  943. }
  944. /// Dequeue a sequence of received octets, and fill a slice from it.
  945. ///
  946. /// This function returns the amount of octets actually dequeued, which is limited
  947. /// by the amount of occupied space in the receive buffer; down to zero.
  948. ///
  949. /// See also [recv](#method.recv).
  950. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  951. self.recv_impl(|rx_buffer| {
  952. let size = rx_buffer.dequeue_slice(data);
  953. (size, size)
  954. })
  955. }
  956. /// Peek at a sequence of received octets without removing them from
  957. /// the receive buffer, and return a pointer to it.
  958. ///
  959. /// This function otherwise behaves identically to [recv](#method.recv).
  960. pub fn peek(&mut self, size: usize) -> Result<&[u8]> {
  961. self.recv_error_check()?;
  962. let buffer = self.rx_buffer.get_allocated(0, size);
  963. if !buffer.is_empty() {
  964. #[cfg(any(test, feature = "verbose"))]
  965. net_trace!(
  966. "{}:{}:{}: rx buffer: peeking at {} octets",
  967. self.meta.handle,
  968. self.local_endpoint,
  969. self.remote_endpoint,
  970. buffer.len()
  971. );
  972. }
  973. Ok(buffer)
  974. }
  975. /// Peek at a sequence of received octets without removing them from
  976. /// the receive buffer, and fill a slice from it.
  977. ///
  978. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  979. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  980. let buffer = self.peek(data.len())?;
  981. let data = &mut data[..buffer.len()];
  982. data.copy_from_slice(buffer);
  983. Ok(buffer.len())
  984. }
  985. /// Return the amount of octets queued in the transmit buffer.
  986. ///
  987. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  988. pub fn send_queue(&self) -> usize {
  989. self.tx_buffer.len()
  990. }
  991. /// Return the amount of octets queued in the receive buffer. This value can be larger than
  992. /// the slice read by the next `recv` or `peek` call because it includes all queued octets,
  993. /// and not only the octets that may be returned as a contiguous slice.
  994. ///
  995. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  996. pub fn recv_queue(&self) -> usize {
  997. self.rx_buffer.len()
  998. }
  999. fn set_state(&mut self, state: State) {
  1000. if self.state != state {
  1001. if self.remote_endpoint.addr.is_unspecified() {
  1002. net_trace!(
  1003. "{}:{}: state={}=>{}",
  1004. self.meta.handle,
  1005. self.local_endpoint,
  1006. self.state,
  1007. state
  1008. );
  1009. } else {
  1010. net_trace!(
  1011. "{}:{}:{}: state={}=>{}",
  1012. self.meta.handle,
  1013. self.local_endpoint,
  1014. self.remote_endpoint,
  1015. self.state,
  1016. state
  1017. );
  1018. }
  1019. }
  1020. self.state = state;
  1021. #[cfg(feature = "async")]
  1022. {
  1023. // Wake all tasks waiting. Even if we haven't received/sent data, this
  1024. // is needed because return values of functions may change depending on the state.
  1025. // For example, a pending read has to fail with an error if the socket is closed.
  1026. self.rx_waker.wake();
  1027. self.tx_waker.wake();
  1028. }
  1029. }
  1030. pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  1031. let reply_repr = TcpRepr {
  1032. src_port: repr.dst_port,
  1033. dst_port: repr.src_port,
  1034. control: TcpControl::None,
  1035. seq_number: TcpSeqNumber(0),
  1036. ack_number: None,
  1037. window_len: 0,
  1038. window_scale: None,
  1039. max_seg_size: None,
  1040. sack_permitted: false,
  1041. sack_ranges: [None, None, None],
  1042. payload: &[],
  1043. };
  1044. let ip_reply_repr = IpRepr::Unspecified {
  1045. src_addr: ip_repr.dst_addr(),
  1046. dst_addr: ip_repr.src_addr(),
  1047. protocol: IpProtocol::Tcp,
  1048. payload_len: reply_repr.buffer_len(),
  1049. hop_limit: 64,
  1050. };
  1051. (ip_reply_repr, reply_repr)
  1052. }
  1053. pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  1054. debug_assert!(repr.control != TcpControl::Rst);
  1055. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  1056. // See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
  1057. // of why we sometimes send an RST and sometimes an RST|ACK
  1058. reply_repr.control = TcpControl::Rst;
  1059. reply_repr.seq_number = repr.ack_number.unwrap_or_default();
  1060. if repr.control == TcpControl::Syn && repr.ack_number.is_none() {
  1061. reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
  1062. }
  1063. (ip_reply_repr, reply_repr)
  1064. }
  1065. fn ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  1066. let (mut ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  1067. // From RFC 793:
  1068. // [...] an empty acknowledgment segment containing the current send-sequence number
  1069. // and an acknowledgment indicating the next sequence number expected
  1070. // to be received.
  1071. reply_repr.seq_number = self.remote_last_seq;
  1072. reply_repr.ack_number = Some(self.remote_seq_no + self.rx_buffer.len());
  1073. self.remote_last_ack = reply_repr.ack_number;
  1074. // From RFC 1323:
  1075. // The window field [...] of every outgoing segment, with the exception of SYN
  1076. // segments, is right-shifted by [advertised scale value] bits[...]
  1077. reply_repr.window_len = self.scaled_window();
  1078. self.remote_last_win = reply_repr.window_len;
  1079. // If the remote supports selective acknowledgement, add the option to the outgoing
  1080. // segment.
  1081. if self.remote_has_sack {
  1082. net_debug!("sending sACK option with current assembler ranges");
  1083. // RFC 2018: The first SACK block (i.e., the one immediately following the kind and
  1084. // length fields in the option) MUST specify the contiguous block of data containing
  1085. // the segment which triggered this ACK, unless that segment advanced the
  1086. // Acknowledgment Number field in the header.
  1087. reply_repr.sack_ranges[0] = None;
  1088. if let Some(last_seg_seq) = self.local_rx_last_seq.map(|s| s.0 as u32) {
  1089. reply_repr.sack_ranges[0] = self
  1090. .assembler
  1091. .iter_data(reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
  1092. .map(|(left, right)| (left as u32, right as u32))
  1093. .find(|(left, right)| *left <= last_seg_seq && *right >= last_seg_seq);
  1094. }
  1095. if reply_repr.sack_ranges[0].is_none() {
  1096. // The matching segment was removed from the assembler, meaning the acknowledgement
  1097. // number has advanced, or there was no previous sACK.
  1098. //
  1099. // While the RFC says we SHOULD keep a list of reported sACK ranges, and iterate
  1100. // through those, that is currently infeasable. Instead, we offer the range with
  1101. // the lowest sequence number (if one exists) to hint at what segments would
  1102. // most quickly advance the acknowledgement number.
  1103. reply_repr.sack_ranges[0] = self
  1104. .assembler
  1105. .iter_data(reply_repr.ack_number.map(|s| s.0 as usize).unwrap_or(0))
  1106. .map(|(left, right)| (left as u32, right as u32))
  1107. .next();
  1108. }
  1109. }
  1110. // Since the sACK option may have changed the length of the payload, update that.
  1111. ip_reply_repr.set_payload_len(reply_repr.buffer_len());
  1112. (ip_reply_repr, reply_repr)
  1113. }
  1114. fn challenge_ack_reply(
  1115. &mut self,
  1116. cx: &Context,
  1117. ip_repr: &IpRepr,
  1118. repr: &TcpRepr,
  1119. ) -> Option<(IpRepr, TcpRepr<'static>)> {
  1120. if cx.now < self.challenge_ack_timer {
  1121. return None;
  1122. }
  1123. // Rate-limit to 1 per second max.
  1124. self.challenge_ack_timer = cx.now + Duration::from_secs(1);
  1125. return Some(self.ack_reply(ip_repr, repr));
  1126. }
  1127. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
  1128. if self.state == State::Closed {
  1129. return false;
  1130. }
  1131. // If we're still listening for SYNs and the packet has an ACK, it cannot
  1132. // be destined to this socket, but another one may well listen on the same
  1133. // local endpoint.
  1134. if self.state == State::Listen && repr.ack_number.is_some() {
  1135. return false;
  1136. }
  1137. // Reject packets with a wrong destination.
  1138. if self.local_endpoint.port != repr.dst_port {
  1139. return false;
  1140. }
  1141. if !self.local_endpoint.addr.is_unspecified()
  1142. && self.local_endpoint.addr != ip_repr.dst_addr()
  1143. {
  1144. return false;
  1145. }
  1146. // Reject packets from a source to which we aren't connected.
  1147. if self.remote_endpoint.port != 0 && self.remote_endpoint.port != repr.src_port {
  1148. return false;
  1149. }
  1150. if !self.remote_endpoint.addr.is_unspecified()
  1151. && self.remote_endpoint.addr != ip_repr.src_addr()
  1152. {
  1153. return false;
  1154. }
  1155. true
  1156. }
  1157. pub(crate) fn process(
  1158. &mut self,
  1159. cx: &Context,
  1160. ip_repr: &IpRepr,
  1161. repr: &TcpRepr,
  1162. ) -> Result<Option<(IpRepr, TcpRepr<'static>)>> {
  1163. debug_assert!(self.accepts(ip_repr, repr));
  1164. // Consider how much the sequence number space differs from the transmit buffer space.
  1165. let (sent_syn, sent_fin) = match self.state {
  1166. // In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
  1167. State::SynSent | State::SynReceived => (true, false),
  1168. // In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
  1169. State::FinWait1 | State::LastAck | State::Closing => (false, true),
  1170. // In all other states we've already got acknowledgemetns for
  1171. // all of the control flags we sent.
  1172. _ => (false, false),
  1173. };
  1174. let control_len = (sent_syn as usize) + (sent_fin as usize);
  1175. // Reject unacceptable acknowledgements.
  1176. match (self.state, repr.control, repr.ack_number) {
  1177. // An RST received in response to initial SYN is acceptable if it acknowledges
  1178. // the initial SYN.
  1179. (State::SynSent, TcpControl::Rst, None) => {
  1180. net_debug!(
  1181. "{}:{}:{}: unacceptable RST (expecting RST|ACK) \
  1182. in response to initial SYN",
  1183. self.meta.handle,
  1184. self.local_endpoint,
  1185. self.remote_endpoint
  1186. );
  1187. return Err(Error::Dropped);
  1188. }
  1189. (State::SynSent, TcpControl::Rst, Some(ack_number)) => {
  1190. if ack_number != self.local_seq_no + 1 {
  1191. net_debug!(
  1192. "{}:{}:{}: unacceptable RST|ACK in response to initial SYN",
  1193. self.meta.handle,
  1194. self.local_endpoint,
  1195. self.remote_endpoint
  1196. );
  1197. return Err(Error::Dropped);
  1198. }
  1199. }
  1200. // Any other RST need only have a valid sequence number.
  1201. (_, TcpControl::Rst, _) => (),
  1202. // The initial SYN cannot contain an acknowledgement.
  1203. (State::Listen, _, None) => (),
  1204. // This case is handled in `accepts()`.
  1205. (State::Listen, _, Some(_)) => unreachable!(),
  1206. // Every packet after the initial SYN must be an acknowledgement.
  1207. (_, _, None) => {
  1208. net_debug!(
  1209. "{}:{}:{}: expecting an ACK",
  1210. self.meta.handle,
  1211. self.local_endpoint,
  1212. self.remote_endpoint
  1213. );
  1214. return Err(Error::Dropped);
  1215. }
  1216. // SYN|ACK in the SYN-SENT state must have the exact ACK number.
  1217. (State::SynSent, TcpControl::Syn, Some(ack_number)) => {
  1218. if ack_number != self.local_seq_no + 1 {
  1219. net_debug!(
  1220. "{}:{}:{}: unacceptable SYN|ACK in response to initial SYN",
  1221. self.meta.handle,
  1222. self.local_endpoint,
  1223. self.remote_endpoint
  1224. );
  1225. return Ok(Some(Self::rst_reply(ip_repr, repr)));
  1226. }
  1227. }
  1228. // ACKs in the SYN-SENT state are invalid.
  1229. (State::SynSent, TcpControl::None, Some(ack_number)) => {
  1230. // If the sequence number matches, ignore it instead of RSTing.
  1231. // I'm not sure why, I think it may be a workaround for broken TCP
  1232. // servers, or a defense against reordering. Either way, if Linux
  1233. // does it, we do too.
  1234. if ack_number == self.local_seq_no + 1 {
  1235. net_debug!(
  1236. "{}:{}:{}: expecting a SYN|ACK, received an ACK with the right ack_number, ignoring.",
  1237. self.meta.handle,
  1238. self.local_endpoint,
  1239. self.remote_endpoint
  1240. );
  1241. return Err(Error::Dropped);
  1242. }
  1243. net_debug!(
  1244. "{}:{}:{}: expecting a SYN|ACK, received an ACK with the wrong ack_number, sending RST.",
  1245. self.meta.handle,
  1246. self.local_endpoint,
  1247. self.remote_endpoint
  1248. );
  1249. return Ok(Some(Self::rst_reply(ip_repr, repr)));
  1250. }
  1251. // Anything else in the SYN-SENT state is invalid.
  1252. (State::SynSent, _, _) => {
  1253. net_debug!(
  1254. "{}:{}:{}: expecting a SYN|ACK",
  1255. self.meta.handle,
  1256. self.local_endpoint,
  1257. self.remote_endpoint
  1258. );
  1259. return Err(Error::Dropped);
  1260. }
  1261. // ACK in the SYN-RECEIVED state must have the exact ACK number, or we RST it.
  1262. (State::SynReceived, _, Some(ack_number)) => {
  1263. if ack_number != self.local_seq_no + 1 {
  1264. net_debug!(
  1265. "{}:{}:{}: unacceptable ACK in response to SYN|ACK",
  1266. self.meta.handle,
  1267. self.local_endpoint,
  1268. self.remote_endpoint
  1269. );
  1270. return Ok(Some(Self::rst_reply(ip_repr, repr)));
  1271. }
  1272. }
  1273. // Every acknowledgement must be for transmitted but unacknowledged data.
  1274. (_, _, Some(ack_number)) => {
  1275. let unacknowledged = self.tx_buffer.len() + control_len;
  1276. // Acceptable ACK range (both inclusive)
  1277. let mut ack_min = self.local_seq_no;
  1278. let ack_max = self.local_seq_no + unacknowledged;
  1279. // If we have sent a SYN, it MUST be acknowledged.
  1280. if sent_syn {
  1281. ack_min += 1;
  1282. }
  1283. if ack_number < ack_min {
  1284. net_debug!(
  1285. "{}:{}:{}: duplicate ACK ({} not in {}...{})",
  1286. self.meta.handle,
  1287. self.local_endpoint,
  1288. self.remote_endpoint,
  1289. ack_number,
  1290. ack_min,
  1291. ack_max
  1292. );
  1293. return Err(Error::Dropped);
  1294. }
  1295. if ack_number > ack_max {
  1296. net_debug!(
  1297. "{}:{}:{}: unacceptable ACK ({} not in {}...{})",
  1298. self.meta.handle,
  1299. self.local_endpoint,
  1300. self.remote_endpoint,
  1301. ack_number,
  1302. ack_min,
  1303. ack_max
  1304. );
  1305. return Ok(self.challenge_ack_reply(cx, ip_repr, repr));
  1306. }
  1307. }
  1308. }
  1309. let window_start = self.remote_seq_no + self.rx_buffer.len();
  1310. let window_end = self.remote_seq_no + self.rx_buffer.capacity();
  1311. let segment_start = repr.seq_number;
  1312. let segment_end = repr.seq_number + repr.segment_len();
  1313. let payload_offset;
  1314. match self.state {
  1315. // In LISTEN and SYN-SENT states, we have not yet synchronized with the remote end.
  1316. State::Listen | State::SynSent => payload_offset = 0,
  1317. // In all other states, segments must occupy a valid portion of the receive window.
  1318. _ => {
  1319. let mut segment_in_window = true;
  1320. if window_start == window_end && segment_start != segment_end {
  1321. net_debug!(
  1322. "{}:{}:{}: non-zero-length segment with zero receive window, \
  1323. will only send an ACK",
  1324. self.meta.handle,
  1325. self.local_endpoint,
  1326. self.remote_endpoint
  1327. );
  1328. segment_in_window = false;
  1329. }
  1330. if segment_start == segment_end && segment_end == window_start - 1 {
  1331. net_debug!(
  1332. "{}:{}:{}: received a keep-alive or window probe packet, \
  1333. will send an ACK",
  1334. self.meta.handle,
  1335. self.local_endpoint,
  1336. self.remote_endpoint
  1337. );
  1338. segment_in_window = false;
  1339. } else if !((window_start <= segment_start && segment_start <= window_end)
  1340. && (window_start <= segment_end && segment_end <= window_end))
  1341. {
  1342. net_debug!(
  1343. "{}:{}:{}: segment not in receive window \
  1344. ({}..{} not intersecting {}..{}), will send challenge ACK",
  1345. self.meta.handle,
  1346. self.local_endpoint,
  1347. self.remote_endpoint,
  1348. segment_start,
  1349. segment_end,
  1350. window_start,
  1351. window_end
  1352. );
  1353. segment_in_window = false;
  1354. }
  1355. if segment_in_window {
  1356. // We've checked that segment_start >= window_start above.
  1357. payload_offset = (segment_start - window_start) as usize;
  1358. self.local_rx_last_seq = Some(repr.seq_number);
  1359. } else {
  1360. // If we're in the TIME-WAIT state, restart the TIME-WAIT timeout, since
  1361. // the remote end may not have realized we've closed the connection.
  1362. if self.state == State::TimeWait {
  1363. self.timer.set_for_close(cx.now);
  1364. }
  1365. return Ok(self.challenge_ack_reply(cx, ip_repr, repr));
  1366. }
  1367. }
  1368. }
  1369. // Compute the amount of acknowledged octets, removing the SYN and FIN bits
  1370. // from the sequence space.
  1371. let mut ack_len = 0;
  1372. let mut ack_of_fin = false;
  1373. if repr.control != TcpControl::Rst {
  1374. if let Some(ack_number) = repr.ack_number {
  1375. // Sequence number corresponding to the first byte in `tx_buffer`.
  1376. // This normally equals `local_seq_no`, but is 1 higher if we ahve sent a SYN,
  1377. // as the SYN occupies 1 sequence number "before" the data.
  1378. let tx_buffer_start_seq = self.local_seq_no + (sent_syn as usize);
  1379. if ack_number >= tx_buffer_start_seq {
  1380. ack_len = ack_number - tx_buffer_start_seq;
  1381. // We could've sent data before the FIN, so only remove FIN from the sequence
  1382. // space if all of that data is acknowledged.
  1383. if sent_fin && self.tx_buffer.len() + 1 == ack_len {
  1384. ack_len -= 1;
  1385. net_trace!(
  1386. "{}:{}:{}: received ACK of FIN",
  1387. self.meta.handle,
  1388. self.local_endpoint,
  1389. self.remote_endpoint
  1390. );
  1391. ack_of_fin = true;
  1392. }
  1393. }
  1394. self.rtte.on_ack(cx.now, ack_number);
  1395. }
  1396. }
  1397. // Disregard control flags we don't care about or shouldn't act on yet.
  1398. let mut control = repr.control;
  1399. control = control.quash_psh();
  1400. // If a FIN is received at the end of the current segment but the start of the segment
  1401. // is not at the start of the receive window, disregard this FIN.
  1402. if control == TcpControl::Fin && window_start != segment_start {
  1403. control = TcpControl::None;
  1404. }
  1405. // Validate and update the state.
  1406. match (self.state, control) {
  1407. // RSTs are not accepted in the LISTEN state.
  1408. (State::Listen, TcpControl::Rst) => return Err(Error::Dropped),
  1409. // RSTs in SYN-RECEIVED flip the socket back to the LISTEN state.
  1410. (State::SynReceived, TcpControl::Rst) => {
  1411. net_trace!(
  1412. "{}:{}:{}: received RST",
  1413. self.meta.handle,
  1414. self.local_endpoint,
  1415. self.remote_endpoint
  1416. );
  1417. self.local_endpoint.addr = self.listen_address;
  1418. self.remote_endpoint = IpEndpoint::default();
  1419. self.set_state(State::Listen);
  1420. return Ok(None);
  1421. }
  1422. // RSTs in any other state close the socket.
  1423. (_, TcpControl::Rst) => {
  1424. net_trace!(
  1425. "{}:{}:{}: received RST",
  1426. self.meta.handle,
  1427. self.local_endpoint,
  1428. self.remote_endpoint
  1429. );
  1430. self.set_state(State::Closed);
  1431. self.local_endpoint = IpEndpoint::default();
  1432. self.remote_endpoint = IpEndpoint::default();
  1433. return Ok(None);
  1434. }
  1435. // SYN packets in the LISTEN state change it to SYN-RECEIVED.
  1436. (State::Listen, TcpControl::Syn) => {
  1437. net_trace!("{}:{}: received SYN", self.meta.handle, self.local_endpoint);
  1438. if let Some(max_seg_size) = repr.max_seg_size {
  1439. if max_seg_size == 0 {
  1440. net_trace!(
  1441. "{}:{}:{}: received SYNACK with zero MSS, ignoring",
  1442. self.meta.handle,
  1443. self.local_endpoint,
  1444. self.remote_endpoint
  1445. );
  1446. return Ok(None);
  1447. }
  1448. self.remote_mss = max_seg_size as usize
  1449. }
  1450. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  1451. self.remote_endpoint = IpEndpoint::new(ip_repr.src_addr(), repr.src_port);
  1452. self.local_seq_no = Self::random_seq_no();
  1453. self.remote_seq_no = repr.seq_number + 1;
  1454. self.remote_last_seq = self.local_seq_no;
  1455. self.remote_has_sack = repr.sack_permitted;
  1456. self.remote_win_scale = repr.window_scale;
  1457. // Remote doesn't support window scaling, don't do it.
  1458. if self.remote_win_scale.is_none() {
  1459. self.remote_win_shift = 0;
  1460. }
  1461. self.set_state(State::SynReceived);
  1462. self.timer.set_for_idle(cx.now, self.keep_alive);
  1463. }
  1464. // ACK packets in the SYN-RECEIVED state change it to ESTABLISHED.
  1465. (State::SynReceived, TcpControl::None) => {
  1466. self.set_state(State::Established);
  1467. self.timer.set_for_idle(cx.now, self.keep_alive);
  1468. }
  1469. // FIN packets in the SYN-RECEIVED state change it to CLOSE-WAIT.
  1470. // It's not obvious from RFC 793 that this is permitted, but
  1471. // 7th and 8th steps in the "SEGMENT ARRIVES" event describe this behavior.
  1472. (State::SynReceived, TcpControl::Fin) => {
  1473. self.remote_seq_no += 1;
  1474. self.rx_fin_received = true;
  1475. self.set_state(State::CloseWait);
  1476. self.timer.set_for_idle(cx.now, self.keep_alive);
  1477. }
  1478. // SYN|ACK packets in the SYN-SENT state change it to ESTABLISHED.
  1479. (State::SynSent, TcpControl::Syn) => {
  1480. net_trace!(
  1481. "{}:{}:{}: received SYN|ACK",
  1482. self.meta.handle,
  1483. self.local_endpoint,
  1484. self.remote_endpoint
  1485. );
  1486. if let Some(max_seg_size) = repr.max_seg_size {
  1487. if max_seg_size == 0 {
  1488. net_trace!(
  1489. "{}:{}:{}: received SYNACK with zero MSS, ignoring",
  1490. self.meta.handle,
  1491. self.local_endpoint,
  1492. self.remote_endpoint
  1493. );
  1494. return Ok(None);
  1495. }
  1496. self.remote_mss = max_seg_size as usize;
  1497. }
  1498. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  1499. self.remote_seq_no = repr.seq_number + 1;
  1500. self.remote_last_seq = self.local_seq_no + 1;
  1501. self.remote_last_ack = Some(repr.seq_number);
  1502. self.remote_win_scale = repr.window_scale;
  1503. // Remote doesn't support window scaling, don't do it.
  1504. if self.remote_win_scale.is_none() {
  1505. self.remote_win_shift = 0;
  1506. }
  1507. self.set_state(State::Established);
  1508. self.timer.set_for_idle(cx.now, self.keep_alive);
  1509. }
  1510. // ACK packets in ESTABLISHED state reset the retransmit timer,
  1511. // except for duplicate ACK packets which preserve it.
  1512. (State::Established, TcpControl::None) => {
  1513. if !self.timer.is_retransmit() || ack_len != 0 {
  1514. self.timer.set_for_idle(cx.now, self.keep_alive);
  1515. }
  1516. }
  1517. // FIN packets in ESTABLISHED state indicate the remote side has closed.
  1518. (State::Established, TcpControl::Fin) => {
  1519. self.remote_seq_no += 1;
  1520. self.rx_fin_received = true;
  1521. self.set_state(State::CloseWait);
  1522. self.timer.set_for_idle(cx.now, self.keep_alive);
  1523. }
  1524. // ACK packets in FIN-WAIT-1 state change it to FIN-WAIT-2, if we've already
  1525. // sent everything in the transmit buffer. If not, they reset the retransmit timer.
  1526. (State::FinWait1, TcpControl::None) => {
  1527. if ack_of_fin {
  1528. self.set_state(State::FinWait2);
  1529. }
  1530. self.timer.set_for_idle(cx.now, self.keep_alive);
  1531. }
  1532. // FIN packets in FIN-WAIT-1 state change it to CLOSING, or to TIME-WAIT
  1533. // if they also acknowledge our FIN.
  1534. (State::FinWait1, TcpControl::Fin) => {
  1535. self.remote_seq_no += 1;
  1536. self.rx_fin_received = true;
  1537. if ack_of_fin {
  1538. self.set_state(State::TimeWait);
  1539. self.timer.set_for_close(cx.now);
  1540. } else {
  1541. self.set_state(State::Closing);
  1542. self.timer.set_for_idle(cx.now, self.keep_alive);
  1543. }
  1544. }
  1545. // Data packets in FIN-WAIT-2 reset the idle timer.
  1546. (State::FinWait2, TcpControl::None) => {
  1547. self.timer.set_for_idle(cx.now, self.keep_alive);
  1548. }
  1549. // FIN packets in FIN-WAIT-2 state change it to TIME-WAIT.
  1550. (State::FinWait2, TcpControl::Fin) => {
  1551. self.remote_seq_no += 1;
  1552. self.rx_fin_received = true;
  1553. self.set_state(State::TimeWait);
  1554. self.timer.set_for_close(cx.now);
  1555. }
  1556. // ACK packets in CLOSING state change it to TIME-WAIT.
  1557. (State::Closing, TcpControl::None) => {
  1558. if ack_of_fin {
  1559. self.set_state(State::TimeWait);
  1560. self.timer.set_for_close(cx.now);
  1561. } else {
  1562. self.timer.set_for_idle(cx.now, self.keep_alive);
  1563. }
  1564. }
  1565. // ACK packets in CLOSE-WAIT state reset the retransmit timer.
  1566. (State::CloseWait, TcpControl::None) => {
  1567. self.timer.set_for_idle(cx.now, self.keep_alive);
  1568. }
  1569. // ACK packets in LAST-ACK state change it to CLOSED.
  1570. (State::LastAck, TcpControl::None) => {
  1571. if ack_of_fin {
  1572. // Clear the remote endpoint, or we'll send an RST there.
  1573. self.set_state(State::Closed);
  1574. self.local_endpoint = IpEndpoint::default();
  1575. self.remote_endpoint = IpEndpoint::default();
  1576. } else {
  1577. self.timer.set_for_idle(cx.now, self.keep_alive);
  1578. }
  1579. }
  1580. _ => {
  1581. net_debug!(
  1582. "{}:{}:{}: unexpected packet {}",
  1583. self.meta.handle,
  1584. self.local_endpoint,
  1585. self.remote_endpoint,
  1586. repr
  1587. );
  1588. return Err(Error::Dropped);
  1589. }
  1590. }
  1591. // Update remote state.
  1592. self.remote_last_ts = Some(cx.now);
  1593. // RFC 1323: The window field (SEG.WND) in the header of every incoming segment, with the
  1594. // exception of SYN segments, is left-shifted by Snd.Wind.Scale bits before updating SND.WND.
  1595. let scale = match repr.control {
  1596. TcpControl::Syn => 0,
  1597. _ => self.remote_win_scale.unwrap_or(0),
  1598. };
  1599. self.remote_win_len = (repr.window_len as usize) << (scale as usize);
  1600. if ack_len > 0 {
  1601. // Dequeue acknowledged octets.
  1602. debug_assert!(self.tx_buffer.len() >= ack_len);
  1603. net_trace!(
  1604. "{}:{}:{}: tx buffer: dequeueing {} octets (now {})",
  1605. self.meta.handle,
  1606. self.local_endpoint,
  1607. self.remote_endpoint,
  1608. ack_len,
  1609. self.tx_buffer.len() - ack_len
  1610. );
  1611. self.tx_buffer.dequeue_allocated(ack_len);
  1612. // There's new room available in tx_buffer, wake the waiting task if any.
  1613. #[cfg(feature = "async")]
  1614. self.tx_waker.wake();
  1615. }
  1616. if let Some(ack_number) = repr.ack_number {
  1617. // TODO: When flow control is implemented,
  1618. // refractor the following block within that implementation
  1619. // Detect and react to duplicate ACKs by:
  1620. // 1. Check if duplicate ACK and change self.local_rx_dup_acks accordingly
  1621. // 2. If exactly 3 duplicate ACKs recived, set for fast retransmit
  1622. // 3. Update the last received ACK (self.local_rx_last_ack)
  1623. match self.local_rx_last_ack {
  1624. // Duplicate ACK if payload empty and ACK doesn't move send window ->
  1625. // Increment duplicate ACK count and set for retransmit if we just recived
  1626. // the third duplicate ACK
  1627. Some(ref last_rx_ack)
  1628. if repr.payload.is_empty()
  1629. && *last_rx_ack == ack_number
  1630. && ack_number < self.remote_last_seq =>
  1631. {
  1632. // Increment duplicate ACK count
  1633. self.local_rx_dup_acks = self.local_rx_dup_acks.saturating_add(1);
  1634. net_debug!(
  1635. "{}:{}:{}: received duplicate ACK for seq {} (duplicate nr {}{})",
  1636. self.meta.handle,
  1637. self.local_endpoint,
  1638. self.remote_endpoint,
  1639. ack_number,
  1640. self.local_rx_dup_acks,
  1641. if self.local_rx_dup_acks == u8::max_value() {
  1642. "+"
  1643. } else {
  1644. ""
  1645. }
  1646. );
  1647. if self.local_rx_dup_acks == 3 {
  1648. self.timer.set_for_fast_retransmit();
  1649. net_debug!(
  1650. "{}:{}:{}: started fast retransmit",
  1651. self.meta.handle,
  1652. self.local_endpoint,
  1653. self.remote_endpoint
  1654. );
  1655. }
  1656. }
  1657. // No duplicate ACK -> Reset state and update last recived ACK
  1658. _ => {
  1659. if self.local_rx_dup_acks > 0 {
  1660. self.local_rx_dup_acks = 0;
  1661. net_debug!(
  1662. "{}:{}:{}: reset duplicate ACK count",
  1663. self.meta.handle,
  1664. self.local_endpoint,
  1665. self.remote_endpoint
  1666. );
  1667. }
  1668. self.local_rx_last_ack = Some(ack_number);
  1669. }
  1670. };
  1671. // We've processed everything in the incoming segment, so advance the local
  1672. // sequence number past it.
  1673. self.local_seq_no = ack_number;
  1674. // During retransmission, if an earlier segment got lost but later was
  1675. // successfully received, self.local_seq_no can move past self.remote_last_seq.
  1676. // Do not attempt to retransmit the latter segments; not only this is pointless
  1677. // in theory but also impossible in practice, since they have been already
  1678. // deallocated from the buffer.
  1679. if self.remote_last_seq < self.local_seq_no {
  1680. self.remote_last_seq = self.local_seq_no
  1681. }
  1682. }
  1683. let payload_len = repr.payload.len();
  1684. if payload_len == 0 {
  1685. return Ok(None);
  1686. }
  1687. let assembler_was_empty = self.assembler.is_empty();
  1688. // Try adding payload octets to the assembler.
  1689. match self.assembler.add(payload_offset, payload_len) {
  1690. Ok(()) => {
  1691. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1692. // Place payload octets into the buffer.
  1693. net_trace!(
  1694. "{}:{}:{}: rx buffer: receiving {} octets at offset {}",
  1695. self.meta.handle,
  1696. self.local_endpoint,
  1697. self.remote_endpoint,
  1698. payload_len,
  1699. payload_offset
  1700. );
  1701. let len_written = self
  1702. .rx_buffer
  1703. .write_unallocated(payload_offset, repr.payload);
  1704. debug_assert!(len_written == payload_len);
  1705. }
  1706. Err(_) => {
  1707. net_debug!(
  1708. "{}:{}:{}: assembler: too many holes to add {} octets at offset {}",
  1709. self.meta.handle,
  1710. self.local_endpoint,
  1711. self.remote_endpoint,
  1712. payload_len,
  1713. payload_offset
  1714. );
  1715. return Err(Error::Dropped);
  1716. }
  1717. }
  1718. if let Some(contig_len) = self.assembler.remove_front() {
  1719. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1720. // Enqueue the contiguous data octets in front of the buffer.
  1721. net_trace!(
  1722. "{}:{}:{}: rx buffer: enqueueing {} octets (now {})",
  1723. self.meta.handle,
  1724. self.local_endpoint,
  1725. self.remote_endpoint,
  1726. contig_len,
  1727. self.rx_buffer.len() + contig_len
  1728. );
  1729. self.rx_buffer.enqueue_unallocated(contig_len);
  1730. // There's new data in rx_buffer, notify waiting task if any.
  1731. #[cfg(feature = "async")]
  1732. self.rx_waker.wake();
  1733. }
  1734. if !self.assembler.is_empty() {
  1735. // Print the ranges recorded in the assembler.
  1736. net_trace!(
  1737. "{}:{}:{}: assembler: {}",
  1738. self.meta.handle,
  1739. self.local_endpoint,
  1740. self.remote_endpoint,
  1741. self.assembler
  1742. );
  1743. }
  1744. // Handle delayed acks
  1745. if let Some(ack_delay) = self.ack_delay {
  1746. if self.ack_to_transmit() || self.window_to_update() {
  1747. self.ack_delay_timer = match self.ack_delay_timer {
  1748. AckDelayTimer::Idle => {
  1749. net_trace!(
  1750. "{}:{}:{}: starting delayed ack timer",
  1751. self.meta.handle,
  1752. self.local_endpoint,
  1753. self.remote_endpoint
  1754. );
  1755. AckDelayTimer::Waiting(cx.now + ack_delay)
  1756. }
  1757. // RFC1122 says "in a stream of full-sized segments there SHOULD be an ACK
  1758. // for at least every second segment".
  1759. // For now, we send an ACK every second received packet, full-sized or not.
  1760. AckDelayTimer::Waiting(_) => {
  1761. net_trace!(
  1762. "{}:{}:{}: delayed ack timer already started, forcing expiry",
  1763. self.meta.handle,
  1764. self.local_endpoint,
  1765. self.remote_endpoint
  1766. );
  1767. AckDelayTimer::Immediate
  1768. }
  1769. AckDelayTimer::Immediate => {
  1770. net_trace!(
  1771. "{}:{}:{}: delayed ack timer already force-expired",
  1772. self.meta.handle,
  1773. self.local_endpoint,
  1774. self.remote_endpoint
  1775. );
  1776. AckDelayTimer::Immediate
  1777. }
  1778. };
  1779. }
  1780. }
  1781. // Per RFC 5681, we should send an immediate ACK when either:
  1782. // 1) an out-of-order segment is received, or
  1783. // 2) a segment arrives that fills in all or part of a gap in sequence space.
  1784. if !self.assembler.is_empty() || !assembler_was_empty {
  1785. // Note that we change the transmitter state here.
  1786. // This is fine because smoltcp assumes that it can always transmit zero or one
  1787. // packets for every packet it receives.
  1788. net_trace!(
  1789. "{}:{}:{}: ACKing incoming segment",
  1790. self.meta.handle,
  1791. self.local_endpoint,
  1792. self.remote_endpoint
  1793. );
  1794. Ok(Some(self.ack_reply(ip_repr, repr)))
  1795. } else {
  1796. Ok(None)
  1797. }
  1798. }
  1799. fn timed_out(&self, timestamp: Instant) -> bool {
  1800. match (self.remote_last_ts, self.timeout) {
  1801. (Some(remote_last_ts), Some(timeout)) => timestamp >= remote_last_ts + timeout,
  1802. (_, _) => false,
  1803. }
  1804. }
  1805. fn seq_to_transmit(&self, cx: &Context) -> bool {
  1806. let ip_header_len = match self.local_endpoint.addr {
  1807. #[cfg(feature = "proto-ipv4")]
  1808. IpAddress::Ipv4(_) => crate::wire::IPV4_HEADER_LEN,
  1809. #[cfg(feature = "proto-ipv6")]
  1810. IpAddress::Ipv6(_) => crate::wire::IPV6_HEADER_LEN,
  1811. IpAddress::Unspecified => unreachable!(),
  1812. };
  1813. // Max segment size we're able to send due to MTU limitations.
  1814. let local_mss = cx.caps.ip_mtu() - ip_header_len - TCP_HEADER_LEN;
  1815. // The effective max segment size, taking into account our and remote's limits.
  1816. let effective_mss = local_mss.min(self.remote_mss);
  1817. // Have we sent data that hasn't been ACKed yet?
  1818. let data_in_flight = self.remote_last_seq != self.local_seq_no;
  1819. // If we want to send a SYN and we haven't done so, do it!
  1820. if matches!(self.state, State::SynSent | State::SynReceived) && !data_in_flight {
  1821. return true;
  1822. }
  1823. // max sequence number we can send.
  1824. let max_send_seq =
  1825. self.local_seq_no + core::cmp::min(self.remote_win_len, self.tx_buffer.len());
  1826. // Max amount of octets we can send.
  1827. let max_send = if max_send_seq >= self.remote_last_seq {
  1828. max_send_seq - self.remote_last_seq
  1829. } else {
  1830. 0
  1831. };
  1832. // Can we send at least 1 octet?
  1833. let mut can_send = max_send != 0;
  1834. // Can we send at least 1 full segment?
  1835. let can_send_full = max_send >= effective_mss;
  1836. // Do we have to send a FIN?
  1837. let want_fin = match self.state {
  1838. State::FinWait1 => true,
  1839. State::Closing => true,
  1840. State::LastAck => true,
  1841. _ => false,
  1842. };
  1843. if self.nagle && data_in_flight && !can_send_full {
  1844. can_send = false;
  1845. }
  1846. // Can we actually send the FIN? We can send it if:
  1847. // 1. We have unsent data that fits in the remote window.
  1848. // 2. We have no unsent data.
  1849. // This condition matches only if #2, because #1 is already covered by can_data and we're ORing them.
  1850. let can_fin = want_fin && self.remote_last_seq == self.local_seq_no + self.tx_buffer.len();
  1851. can_send || can_fin
  1852. }
  1853. fn delayed_ack_expired(&self, timestamp: Instant) -> bool {
  1854. match self.ack_delay_timer {
  1855. AckDelayTimer::Idle => true,
  1856. AckDelayTimer::Waiting(t) => t <= timestamp,
  1857. AckDelayTimer::Immediate => true,
  1858. }
  1859. }
  1860. fn ack_to_transmit(&self) -> bool {
  1861. if let Some(remote_last_ack) = self.remote_last_ack {
  1862. remote_last_ack < self.remote_seq_no + self.rx_buffer.len()
  1863. } else {
  1864. false
  1865. }
  1866. }
  1867. fn window_to_update(&self) -> bool {
  1868. match self.state {
  1869. State::SynSent
  1870. | State::SynReceived
  1871. | State::Established
  1872. | State::FinWait1
  1873. | State::FinWait2 => self.scaled_window() > self.remote_last_win,
  1874. _ => false,
  1875. }
  1876. }
  1877. pub(crate) fn dispatch<F>(&mut self, cx: &Context, emit: F) -> Result<()>
  1878. where
  1879. F: FnOnce((IpRepr, TcpRepr)) -> Result<()>,
  1880. {
  1881. if !self.remote_endpoint.is_specified() {
  1882. return Err(Error::Exhausted);
  1883. }
  1884. if self.remote_last_ts.is_none() {
  1885. // We get here in exactly two cases:
  1886. // 1) This socket just transitioned into SYN-SENT.
  1887. // 2) This socket had an empty transmit buffer and some data was added there.
  1888. // Both are similar in that the socket has been quiet for an indefinite
  1889. // period of time, it isn't anymore, and the local endpoint is talking.
  1890. // So, we start counting the timeout not from the last received packet
  1891. // but from the first transmitted one.
  1892. self.remote_last_ts = Some(cx.now);
  1893. }
  1894. // Check if any state needs to be changed because of a timer.
  1895. if self.timed_out(cx.now) {
  1896. // If a timeout expires, we should abort the connection.
  1897. net_debug!(
  1898. "{}:{}:{}: timeout exceeded",
  1899. self.meta.handle,
  1900. self.local_endpoint,
  1901. self.remote_endpoint
  1902. );
  1903. self.set_state(State::Closed);
  1904. } else if !self.seq_to_transmit(cx) {
  1905. if let Some(retransmit_delta) = self.timer.should_retransmit(cx.now) {
  1906. // If a retransmit timer expired, we should resend data starting at the last ACK.
  1907. net_debug!(
  1908. "{}:{}:{}: retransmitting at t+{}",
  1909. self.meta.handle,
  1910. self.local_endpoint,
  1911. self.remote_endpoint,
  1912. retransmit_delta
  1913. );
  1914. // Rewind "last sequence number sent", as if we never
  1915. // had sent them. This will cause all data in the queue
  1916. // to be sent again.
  1917. self.remote_last_seq = self.local_seq_no;
  1918. // Clear the `should_retransmit` state. If we can't retransmit right
  1919. // now for whatever reason (like zero window), this avoids an
  1920. // infinite polling loop where `poll_at` returns `Now` but `dispatch`
  1921. // can't actually do anything.
  1922. self.timer.set_for_idle(cx.now, self.keep_alive);
  1923. // Inform RTTE, so that it can avoid bogus measurements.
  1924. self.rtte.on_retransmit();
  1925. }
  1926. }
  1927. // Decide whether we're sending a packet.
  1928. if self.seq_to_transmit(cx) {
  1929. // If we have data to transmit and it fits into partner's window, do it.
  1930. net_trace!(
  1931. "{}:{}:{}: outgoing segment will send data or flags",
  1932. self.meta.handle,
  1933. self.local_endpoint,
  1934. self.remote_endpoint
  1935. );
  1936. } else if self.ack_to_transmit() && self.delayed_ack_expired(cx.now) {
  1937. // If we have data to acknowledge, do it.
  1938. net_trace!(
  1939. "{}:{}:{}: outgoing segment will acknowledge",
  1940. self.meta.handle,
  1941. self.local_endpoint,
  1942. self.remote_endpoint
  1943. );
  1944. } else if self.window_to_update() && self.delayed_ack_expired(cx.now) {
  1945. // If we have window length increase to advertise, do it.
  1946. net_trace!(
  1947. "{}:{}:{}: outgoing segment will update window",
  1948. self.meta.handle,
  1949. self.local_endpoint,
  1950. self.remote_endpoint
  1951. );
  1952. } else if self.state == State::Closed {
  1953. // If we need to abort the connection, do it.
  1954. net_trace!(
  1955. "{}:{}:{}: outgoing segment will abort connection",
  1956. self.meta.handle,
  1957. self.local_endpoint,
  1958. self.remote_endpoint
  1959. );
  1960. } else if self.timer.should_keep_alive(cx.now) {
  1961. // If we need to transmit a keep-alive packet, do it.
  1962. net_trace!(
  1963. "{}:{}:{}: keep-alive timer expired",
  1964. self.meta.handle,
  1965. self.local_endpoint,
  1966. self.remote_endpoint
  1967. );
  1968. } else if self.timer.should_close(cx.now) {
  1969. // If we have spent enough time in the TIME-WAIT state, close the socket.
  1970. net_trace!(
  1971. "{}:{}:{}: TIME-WAIT timer expired",
  1972. self.meta.handle,
  1973. self.local_endpoint,
  1974. self.remote_endpoint
  1975. );
  1976. self.reset();
  1977. return Err(Error::Exhausted);
  1978. } else {
  1979. return Err(Error::Exhausted);
  1980. }
  1981. // Construct the lowered IP representation.
  1982. // We might need this to calculate the MSS, so do it early.
  1983. let mut ip_repr = IpRepr::Unspecified {
  1984. src_addr: self.local_endpoint.addr,
  1985. dst_addr: self.remote_endpoint.addr,
  1986. protocol: IpProtocol::Tcp,
  1987. hop_limit: self.hop_limit.unwrap_or(64),
  1988. payload_len: 0,
  1989. }
  1990. .lower(&[])?;
  1991. // Construct the basic TCP representation, an empty ACK packet.
  1992. // We'll adjust this to be more specific as needed.
  1993. let mut repr = TcpRepr {
  1994. src_port: self.local_endpoint.port,
  1995. dst_port: self.remote_endpoint.port,
  1996. control: TcpControl::None,
  1997. seq_number: self.remote_last_seq,
  1998. ack_number: Some(self.remote_seq_no + self.rx_buffer.len()),
  1999. window_len: self.scaled_window(),
  2000. window_scale: None,
  2001. max_seg_size: None,
  2002. sack_permitted: false,
  2003. sack_ranges: [None, None, None],
  2004. payload: &[],
  2005. };
  2006. match self.state {
  2007. // We transmit an RST in the CLOSED state. If we ended up in the CLOSED state
  2008. // with a specified endpoint, it means that the socket was aborted.
  2009. State::Closed => {
  2010. repr.control = TcpControl::Rst;
  2011. }
  2012. // We never transmit anything in the LISTEN state.
  2013. State::Listen => return Err(Error::Exhausted),
  2014. // We transmit a SYN in the SYN-SENT state.
  2015. // We transmit a SYN|ACK in the SYN-RECEIVED state.
  2016. State::SynSent | State::SynReceived => {
  2017. repr.control = TcpControl::Syn;
  2018. // window len must NOT be scaled in SYNs.
  2019. repr.window_len = self.rx_buffer.window().min((1 << 16) - 1) as u16;
  2020. if self.state == State::SynSent {
  2021. repr.ack_number = None;
  2022. repr.window_scale = Some(self.remote_win_shift);
  2023. repr.sack_permitted = true;
  2024. } else {
  2025. repr.sack_permitted = self.remote_has_sack;
  2026. repr.window_scale = self.remote_win_scale.map(|_| self.remote_win_shift);
  2027. }
  2028. }
  2029. // We transmit data in all states where we may have data in the buffer,
  2030. // or the transmit half of the connection is still open.
  2031. State::Established
  2032. | State::FinWait1
  2033. | State::Closing
  2034. | State::CloseWait
  2035. | State::LastAck => {
  2036. // Extract as much data as the remote side can receive in this packet
  2037. // from the transmit buffer.
  2038. // Right edge of window, ie the max sequence number we're allowed to send.
  2039. let win_right_edge = self.local_seq_no + self.remote_win_len;
  2040. // Max amount of octets we're allowed to send according to the remote window.
  2041. let win_limit = if win_right_edge >= self.remote_last_seq {
  2042. win_right_edge - self.remote_last_seq
  2043. } else {
  2044. // This can happen if we've sent some data and later the remote side
  2045. // has shrunk its window so that data is no longer inside the window.
  2046. // This should be very rare and is strongly discouraged by the RFCs,
  2047. // but it does happen in practice.
  2048. // http://www.tcpipguide.com/free/t_TCPWindowManagementIssues.htm
  2049. 0
  2050. };
  2051. // Maximum size we're allowed to send. This can be limited by 3 factors:
  2052. // 1. remote window
  2053. // 2. MSS the remote is willing to accept, probably determined by their MTU
  2054. // 3. MSS we can send, determined by our MTU.
  2055. let size = win_limit
  2056. .min(self.remote_mss)
  2057. .min(cx.caps.ip_mtu() - ip_repr.buffer_len() - TCP_HEADER_LEN);
  2058. let offset = self.remote_last_seq - self.local_seq_no;
  2059. repr.payload = self.tx_buffer.get_allocated(offset, size);
  2060. // If we've sent everything we had in the buffer, follow it with the PSH or FIN
  2061. // flags, depending on whether the transmit half of the connection is open.
  2062. if offset + repr.payload.len() == self.tx_buffer.len() {
  2063. match self.state {
  2064. State::FinWait1 | State::LastAck | State::Closing => {
  2065. repr.control = TcpControl::Fin
  2066. }
  2067. State::Established | State::CloseWait if !repr.payload.is_empty() => {
  2068. repr.control = TcpControl::Psh
  2069. }
  2070. _ => (),
  2071. }
  2072. }
  2073. }
  2074. // In FIN-WAIT-2 and TIME-WAIT states we may only transmit ACKs for incoming data or FIN
  2075. State::FinWait2 | State::TimeWait => {}
  2076. }
  2077. // There might be more than one reason to send a packet. E.g. the keep-alive timer
  2078. // has expired, and we also have data in transmit buffer. Since any packet that occupies
  2079. // sequence space will elicit an ACK, we only need to send an explicit packet if we
  2080. // couldn't fill the sequence space with anything.
  2081. let is_keep_alive;
  2082. if self.timer.should_keep_alive(cx.now) && repr.is_empty() {
  2083. repr.seq_number = repr.seq_number - 1;
  2084. repr.payload = b"\x00"; // RFC 1122 says we should do this
  2085. is_keep_alive = true;
  2086. } else {
  2087. is_keep_alive = false;
  2088. }
  2089. // Trace a summary of what will be sent.
  2090. if is_keep_alive {
  2091. net_trace!(
  2092. "{}:{}:{}: sending a keep-alive",
  2093. self.meta.handle,
  2094. self.local_endpoint,
  2095. self.remote_endpoint
  2096. );
  2097. } else if !repr.payload.is_empty() {
  2098. net_trace!(
  2099. "{}:{}:{}: tx buffer: sending {} octets at offset {}",
  2100. self.meta.handle,
  2101. self.local_endpoint,
  2102. self.remote_endpoint,
  2103. repr.payload.len(),
  2104. self.remote_last_seq - self.local_seq_no
  2105. );
  2106. }
  2107. if repr.control != TcpControl::None || repr.payload.is_empty() {
  2108. let flags = match (repr.control, repr.ack_number) {
  2109. (TcpControl::Syn, None) => "SYN",
  2110. (TcpControl::Syn, Some(_)) => "SYN|ACK",
  2111. (TcpControl::Fin, Some(_)) => "FIN|ACK",
  2112. (TcpControl::Rst, Some(_)) => "RST|ACK",
  2113. (TcpControl::Psh, Some(_)) => "PSH|ACK",
  2114. (TcpControl::None, Some(_)) => "ACK",
  2115. _ => "<unreachable>",
  2116. };
  2117. net_trace!(
  2118. "{}:{}:{}: sending {}",
  2119. self.meta.handle,
  2120. self.local_endpoint,
  2121. self.remote_endpoint,
  2122. flags
  2123. );
  2124. }
  2125. if repr.control == TcpControl::Syn {
  2126. // Fill the MSS option. See RFC 6691 for an explanation of this calculation.
  2127. let max_segment_size = cx.caps.ip_mtu() - ip_repr.buffer_len() - TCP_HEADER_LEN;
  2128. repr.max_seg_size = Some(max_segment_size as u16);
  2129. }
  2130. // Actually send the packet. If this succeeds, it means the packet is in
  2131. // the device buffer, and its transmission is imminent. If not, we might have
  2132. // a number of problems, e.g. we need neighbor discovery.
  2133. //
  2134. // Bailing out if the packet isn't placed in the device buffer allows us
  2135. // to not waste time waiting for the retransmit timer on packets that we know
  2136. // for sure will not be successfully transmitted.
  2137. ip_repr.set_payload_len(repr.buffer_len());
  2138. emit((ip_repr, repr))?;
  2139. // We've sent something, whether useful data or a keep-alive packet, so rewind
  2140. // the keep-alive timer.
  2141. self.timer.rewind_keep_alive(cx.now, self.keep_alive);
  2142. // Reset delayed-ack timer
  2143. match self.ack_delay_timer {
  2144. AckDelayTimer::Idle => {}
  2145. AckDelayTimer::Waiting(_) => {
  2146. net_trace!(
  2147. "{}:{}:{}: stop delayed ack timer",
  2148. self.meta.handle,
  2149. self.local_endpoint,
  2150. self.remote_endpoint
  2151. )
  2152. }
  2153. AckDelayTimer::Immediate => {
  2154. net_trace!(
  2155. "{}:{}:{}: stop delayed ack timer (was force-expired)",
  2156. self.meta.handle,
  2157. self.local_endpoint,
  2158. self.remote_endpoint
  2159. )
  2160. }
  2161. }
  2162. self.ack_delay_timer = AckDelayTimer::Idle;
  2163. // Leave the rest of the state intact if sending a keep-alive packet, since those
  2164. // carry a fake segment.
  2165. if is_keep_alive {
  2166. return Ok(());
  2167. }
  2168. // We've sent a packet successfully, so we can update the internal state now.
  2169. self.remote_last_seq = repr.seq_number + repr.segment_len();
  2170. self.remote_last_ack = repr.ack_number;
  2171. self.remote_last_win = repr.window_len;
  2172. if repr.segment_len() > 0 {
  2173. self.rtte
  2174. .on_send(cx.now, repr.seq_number + repr.segment_len());
  2175. }
  2176. if !self.seq_to_transmit(cx) && repr.segment_len() > 0 {
  2177. // If we've transmitted all data we could (and there was something at all,
  2178. // data or flag, to transmit, not just an ACK), wind up the retransmit timer.
  2179. self.timer
  2180. .set_for_retransmit(cx.now, self.rtte.retransmission_timeout());
  2181. }
  2182. if self.state == State::Closed {
  2183. // When aborting a connection, forget about it after sending a single RST packet.
  2184. self.local_endpoint = IpEndpoint::default();
  2185. self.remote_endpoint = IpEndpoint::default();
  2186. }
  2187. Ok(())
  2188. }
  2189. #[allow(clippy::if_same_then_else)]
  2190. pub(crate) fn poll_at(&self, cx: &Context) -> PollAt {
  2191. // The logic here mirrors the beginning of dispatch() closely.
  2192. if !self.remote_endpoint.is_specified() {
  2193. // No one to talk to, nothing to transmit.
  2194. PollAt::Ingress
  2195. } else if self.remote_last_ts.is_none() {
  2196. // Socket stopped being quiet recently, we need to acquire a timestamp.
  2197. PollAt::Now
  2198. } else if self.state == State::Closed {
  2199. // Socket was aborted, we have an RST packet to transmit.
  2200. PollAt::Now
  2201. } else if self.seq_to_transmit(cx) {
  2202. // We have a data or flag packet to transmit.
  2203. PollAt::Now
  2204. } else {
  2205. let want_ack = self.ack_to_transmit() || self.window_to_update();
  2206. let delayed_ack_poll_at = match (want_ack, self.ack_delay_timer) {
  2207. (false, _) => PollAt::Ingress,
  2208. (true, AckDelayTimer::Idle) => PollAt::Now,
  2209. (true, AckDelayTimer::Waiting(t)) => PollAt::Time(t),
  2210. (true, AckDelayTimer::Immediate) => PollAt::Now,
  2211. };
  2212. let timeout_poll_at = match (self.remote_last_ts, self.timeout) {
  2213. // If we're transmitting or retransmitting data, we need to poll at the moment
  2214. // when the timeout would expire.
  2215. (Some(remote_last_ts), Some(timeout)) => PollAt::Time(remote_last_ts + timeout),
  2216. // Otherwise we have no timeout.
  2217. (_, _) => PollAt::Ingress,
  2218. };
  2219. // We wait for the earliest of our timers to fire.
  2220. *[self.timer.poll_at(), timeout_poll_at, delayed_ack_poll_at]
  2221. .iter()
  2222. .min()
  2223. .unwrap_or(&PollAt::Ingress)
  2224. }
  2225. }
  2226. }
  2227. impl<'a> From<TcpSocket<'a>> for Socket<'a> {
  2228. fn from(val: TcpSocket<'a>) -> Self {
  2229. Socket::Tcp(val)
  2230. }
  2231. }
  2232. impl<'a> fmt::Write for TcpSocket<'a> {
  2233. fn write_str(&mut self, slice: &str) -> fmt::Result {
  2234. let slice = slice.as_bytes();
  2235. if self.send_slice(slice) == Ok(slice.len()) {
  2236. Ok(())
  2237. } else {
  2238. Err(fmt::Error)
  2239. }
  2240. }
  2241. }
  2242. #[cfg(test)]
  2243. mod test {
  2244. use super::*;
  2245. use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3, MOCK_UNSPECIFIED};
  2246. use crate::wire::{IpAddress, IpCidr, IpRepr};
  2247. use core::i32;
  2248. use std::vec::Vec;
  2249. // =========================================================================================//
  2250. // Constants
  2251. // =========================================================================================//
  2252. const LOCAL_PORT: u16 = 80;
  2253. const REMOTE_PORT: u16 = 49500;
  2254. const LOCAL_END: IpEndpoint = IpEndpoint {
  2255. addr: MOCK_IP_ADDR_1,
  2256. port: LOCAL_PORT,
  2257. };
  2258. const REMOTE_END: IpEndpoint = IpEndpoint {
  2259. addr: MOCK_IP_ADDR_2,
  2260. port: REMOTE_PORT,
  2261. };
  2262. const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
  2263. const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10001);
  2264. const SEND_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  2265. src_addr: MOCK_IP_ADDR_1,
  2266. dst_addr: MOCK_IP_ADDR_2,
  2267. protocol: IpProtocol::Tcp,
  2268. payload_len: 20,
  2269. hop_limit: 64,
  2270. };
  2271. const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
  2272. src_port: REMOTE_PORT,
  2273. dst_port: LOCAL_PORT,
  2274. control: TcpControl::None,
  2275. seq_number: TcpSeqNumber(0),
  2276. ack_number: Some(TcpSeqNumber(0)),
  2277. window_len: 256,
  2278. window_scale: None,
  2279. max_seg_size: None,
  2280. sack_permitted: false,
  2281. sack_ranges: [None, None, None],
  2282. payload: &[],
  2283. };
  2284. const _RECV_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  2285. src_addr: MOCK_IP_ADDR_1,
  2286. dst_addr: MOCK_IP_ADDR_2,
  2287. protocol: IpProtocol::Tcp,
  2288. payload_len: 20,
  2289. hop_limit: 64,
  2290. };
  2291. const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
  2292. src_port: LOCAL_PORT,
  2293. dst_port: REMOTE_PORT,
  2294. control: TcpControl::None,
  2295. seq_number: TcpSeqNumber(0),
  2296. ack_number: Some(TcpSeqNumber(0)),
  2297. window_len: 64,
  2298. window_scale: None,
  2299. max_seg_size: None,
  2300. sack_permitted: false,
  2301. sack_ranges: [None, None, None],
  2302. payload: &[],
  2303. };
  2304. #[cfg(feature = "proto-ipv6")]
  2305. const BASE_MSS: u16 = 1440;
  2306. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  2307. const BASE_MSS: u16 = 1460;
  2308. // =========================================================================================//
  2309. // Helper functions
  2310. // =========================================================================================//
  2311. fn send(
  2312. socket: &mut TcpSocket,
  2313. timestamp: Instant,
  2314. repr: &TcpRepr,
  2315. ) -> Result<Option<TcpRepr<'static>>> {
  2316. let ip_repr = IpRepr::Unspecified {
  2317. src_addr: MOCK_IP_ADDR_2,
  2318. dst_addr: MOCK_IP_ADDR_1,
  2319. protocol: IpProtocol::Tcp,
  2320. payload_len: repr.buffer_len(),
  2321. hop_limit: 64,
  2322. };
  2323. net_trace!("send: {}", repr);
  2324. assert!(socket.accepts(&ip_repr, repr));
  2325. let mut cx = Context::DUMMY.clone();
  2326. cx.now = timestamp;
  2327. match socket.process(&cx, &ip_repr, repr) {
  2328. Ok(Some((_ip_repr, repr))) => {
  2329. net_trace!("recv: {}", repr);
  2330. Ok(Some(repr))
  2331. }
  2332. Ok(None) => Ok(None),
  2333. Err(err) => Err(err),
  2334. }
  2335. }
  2336. fn recv<F>(socket: &mut TcpSocket, timestamp: Instant, mut f: F)
  2337. where
  2338. F: FnMut(Result<TcpRepr>),
  2339. {
  2340. let mut cx = Context::DUMMY.clone();
  2341. cx.now = timestamp;
  2342. let result = socket.dispatch(&cx, |(ip_repr, tcp_repr)| {
  2343. let ip_repr = ip_repr.lower(&[IpCidr::new(LOCAL_END.addr, 24)]).unwrap();
  2344. assert_eq!(ip_repr.protocol(), IpProtocol::Tcp);
  2345. assert_eq!(ip_repr.src_addr(), MOCK_IP_ADDR_1);
  2346. assert_eq!(ip_repr.dst_addr(), MOCK_IP_ADDR_2);
  2347. assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
  2348. net_trace!("recv: {}", tcp_repr);
  2349. Ok(f(Ok(tcp_repr)))
  2350. });
  2351. match result {
  2352. Ok(()) => (),
  2353. Err(e) => f(Err(e)),
  2354. }
  2355. }
  2356. macro_rules! send {
  2357. ($socket:ident, $repr:expr) =>
  2358. (send!($socket, time 0, $repr));
  2359. ($socket:ident, $repr:expr, $result:expr) =>
  2360. (send!($socket, time 0, $repr, $result));
  2361. ($socket:ident, time $time:expr, $repr:expr) =>
  2362. (send!($socket, time $time, $repr, Ok(None)));
  2363. ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
  2364. (assert_eq!(send(&mut $socket, Instant::from_millis($time), &$repr), $result));
  2365. }
  2366. macro_rules! recv {
  2367. ($socket:ident, [$( $repr:expr ),*]) => ({
  2368. $( recv!($socket, Ok($repr)); )*
  2369. recv!($socket, Err(Error::Exhausted))
  2370. });
  2371. ($socket:ident, $result:expr) =>
  2372. (recv!($socket, time 0, $result));
  2373. ($socket:ident, time $time:expr, $result:expr) =>
  2374. (recv(&mut $socket, Instant::from_millis($time), |result| {
  2375. // Most of the time we don't care about the PSH flag.
  2376. let result = result.map(|mut repr| {
  2377. repr.control = repr.control.quash_psh();
  2378. repr
  2379. });
  2380. assert_eq!(result, $result)
  2381. }));
  2382. ($socket:ident, time $time:expr, $result:expr, exact) =>
  2383. (recv(&mut $socket, Instant::from_millis($time), |repr| assert_eq!(repr, $result)));
  2384. }
  2385. macro_rules! sanity {
  2386. ($socket1:expr, $socket2:expr) => {{
  2387. let (s1, s2) = ($socket1, $socket2);
  2388. assert_eq!(s1.state, s2.state, "state");
  2389. assert_eq!(s1.listen_address, s2.listen_address, "listen_address");
  2390. assert_eq!(s1.local_endpoint, s2.local_endpoint, "local_endpoint");
  2391. assert_eq!(s1.remote_endpoint, s2.remote_endpoint, "remote_endpoint");
  2392. assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
  2393. assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
  2394. assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
  2395. assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
  2396. assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
  2397. assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
  2398. assert_eq!(s1.timer, s2.timer, "timer");
  2399. }};
  2400. }
  2401. fn socket() -> TcpSocket<'static> {
  2402. socket_with_buffer_sizes(64, 64)
  2403. }
  2404. fn socket_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  2405. let rx_buffer = SocketBuffer::new(vec![0; rx_len]);
  2406. let tx_buffer = SocketBuffer::new(vec![0; tx_len]);
  2407. let mut socket = TcpSocket::new(rx_buffer, tx_buffer);
  2408. socket.set_ack_delay(None);
  2409. socket
  2410. }
  2411. fn socket_syn_received_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  2412. let mut s = socket_with_buffer_sizes(tx_len, rx_len);
  2413. s.state = State::SynReceived;
  2414. s.local_endpoint = LOCAL_END;
  2415. s.remote_endpoint = REMOTE_END;
  2416. s.local_seq_no = LOCAL_SEQ;
  2417. s.remote_seq_no = REMOTE_SEQ + 1;
  2418. s.remote_last_seq = LOCAL_SEQ;
  2419. s.remote_win_len = 256;
  2420. s
  2421. }
  2422. fn socket_syn_received() -> TcpSocket<'static> {
  2423. socket_syn_received_with_buffer_sizes(64, 64)
  2424. }
  2425. fn socket_syn_sent_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  2426. let mut s = socket_with_buffer_sizes(tx_len, rx_len);
  2427. s.state = State::SynSent;
  2428. s.local_endpoint = IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_PORT);
  2429. s.remote_endpoint = REMOTE_END;
  2430. s.local_seq_no = LOCAL_SEQ;
  2431. s.remote_last_seq = LOCAL_SEQ;
  2432. s
  2433. }
  2434. fn socket_syn_sent() -> TcpSocket<'static> {
  2435. socket_syn_sent_with_buffer_sizes(64, 64)
  2436. }
  2437. fn socket_syn_sent_with_local_ipendpoint(local: IpEndpoint) -> TcpSocket<'static> {
  2438. let mut s = socket();
  2439. s.state = State::SynSent;
  2440. s.local_endpoint = local;
  2441. s.remote_endpoint = REMOTE_END;
  2442. s.local_seq_no = LOCAL_SEQ;
  2443. s.remote_last_seq = LOCAL_SEQ;
  2444. s
  2445. }
  2446. fn socket_established_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  2447. let mut s = socket_syn_received_with_buffer_sizes(tx_len, rx_len);
  2448. s.state = State::Established;
  2449. s.local_seq_no = LOCAL_SEQ + 1;
  2450. s.remote_last_seq = LOCAL_SEQ + 1;
  2451. s.remote_last_ack = Some(REMOTE_SEQ + 1);
  2452. s.remote_last_win = 64;
  2453. s
  2454. }
  2455. fn socket_established() -> TcpSocket<'static> {
  2456. socket_established_with_buffer_sizes(64, 64)
  2457. }
  2458. fn socket_fin_wait_1() -> TcpSocket<'static> {
  2459. let mut s = socket_established();
  2460. s.state = State::FinWait1;
  2461. s
  2462. }
  2463. fn socket_fin_wait_2() -> TcpSocket<'static> {
  2464. let mut s = socket_fin_wait_1();
  2465. s.state = State::FinWait2;
  2466. s.local_seq_no = LOCAL_SEQ + 1 + 1;
  2467. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  2468. s
  2469. }
  2470. fn socket_closing() -> TcpSocket<'static> {
  2471. let mut s = socket_fin_wait_1();
  2472. s.state = State::Closing;
  2473. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  2474. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2475. s
  2476. }
  2477. fn socket_time_wait(from_closing: bool) -> TcpSocket<'static> {
  2478. let mut s = socket_fin_wait_2();
  2479. s.state = State::TimeWait;
  2480. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2481. if from_closing {
  2482. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2483. }
  2484. s.timer = Timer::Close {
  2485. expires_at: Instant::from_secs(1) + CLOSE_DELAY,
  2486. };
  2487. s
  2488. }
  2489. fn socket_close_wait() -> TcpSocket<'static> {
  2490. let mut s = socket_established();
  2491. s.state = State::CloseWait;
  2492. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2493. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2494. s
  2495. }
  2496. fn socket_last_ack() -> TcpSocket<'static> {
  2497. let mut s = socket_close_wait();
  2498. s.state = State::LastAck;
  2499. s
  2500. }
  2501. fn socket_recved() -> TcpSocket<'static> {
  2502. let mut s = socket_established();
  2503. send!(
  2504. s,
  2505. TcpRepr {
  2506. seq_number: REMOTE_SEQ + 1,
  2507. ack_number: Some(LOCAL_SEQ + 1),
  2508. payload: &b"abcdef"[..],
  2509. ..SEND_TEMPL
  2510. }
  2511. );
  2512. recv!(
  2513. s,
  2514. [TcpRepr {
  2515. seq_number: LOCAL_SEQ + 1,
  2516. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2517. window_len: 58,
  2518. ..RECV_TEMPL
  2519. }]
  2520. );
  2521. s
  2522. }
  2523. // =========================================================================================//
  2524. // Tests for the CLOSED state.
  2525. // =========================================================================================//
  2526. #[test]
  2527. fn test_closed_reject() {
  2528. let s = socket();
  2529. assert_eq!(s.state, State::Closed);
  2530. let tcp_repr = TcpRepr {
  2531. control: TcpControl::Syn,
  2532. ..SEND_TEMPL
  2533. };
  2534. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2535. }
  2536. #[test]
  2537. fn test_closed_reject_after_listen() {
  2538. let mut s = socket();
  2539. s.listen(LOCAL_END).unwrap();
  2540. s.close();
  2541. let tcp_repr = TcpRepr {
  2542. control: TcpControl::Syn,
  2543. ..SEND_TEMPL
  2544. };
  2545. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2546. }
  2547. #[test]
  2548. fn test_closed_close() {
  2549. let mut s = socket();
  2550. s.close();
  2551. assert_eq!(s.state, State::Closed);
  2552. }
  2553. // =========================================================================================//
  2554. // Tests for the LISTEN state.
  2555. // =========================================================================================//
  2556. fn socket_listen() -> TcpSocket<'static> {
  2557. let mut s = socket();
  2558. s.state = State::Listen;
  2559. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  2560. s
  2561. }
  2562. #[test]
  2563. fn test_listen_sack_option() {
  2564. let mut s = socket_listen();
  2565. send!(
  2566. s,
  2567. TcpRepr {
  2568. control: TcpControl::Syn,
  2569. seq_number: REMOTE_SEQ,
  2570. ack_number: None,
  2571. sack_permitted: false,
  2572. ..SEND_TEMPL
  2573. }
  2574. );
  2575. assert!(!s.remote_has_sack);
  2576. recv!(
  2577. s,
  2578. [TcpRepr {
  2579. control: TcpControl::Syn,
  2580. seq_number: LOCAL_SEQ,
  2581. ack_number: Some(REMOTE_SEQ + 1),
  2582. max_seg_size: Some(BASE_MSS),
  2583. ..RECV_TEMPL
  2584. }]
  2585. );
  2586. let mut s = socket_listen();
  2587. send!(
  2588. s,
  2589. TcpRepr {
  2590. control: TcpControl::Syn,
  2591. seq_number: REMOTE_SEQ,
  2592. ack_number: None,
  2593. sack_permitted: true,
  2594. ..SEND_TEMPL
  2595. }
  2596. );
  2597. assert!(s.remote_has_sack);
  2598. recv!(
  2599. s,
  2600. [TcpRepr {
  2601. control: TcpControl::Syn,
  2602. seq_number: LOCAL_SEQ,
  2603. ack_number: Some(REMOTE_SEQ + 1),
  2604. max_seg_size: Some(BASE_MSS),
  2605. sack_permitted: true,
  2606. ..RECV_TEMPL
  2607. }]
  2608. );
  2609. }
  2610. #[test]
  2611. fn test_listen_syn_win_scale_buffers() {
  2612. for (buffer_size, shift_amt) in &[
  2613. (64, 0),
  2614. (128, 0),
  2615. (1024, 0),
  2616. (65535, 0),
  2617. (65536, 1),
  2618. (65537, 1),
  2619. (131071, 1),
  2620. (131072, 2),
  2621. (524287, 3),
  2622. (524288, 4),
  2623. (655350, 4),
  2624. (1048576, 5),
  2625. ] {
  2626. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  2627. s.state = State::Listen;
  2628. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  2629. assert_eq!(s.remote_win_shift, *shift_amt);
  2630. send!(
  2631. s,
  2632. TcpRepr {
  2633. control: TcpControl::Syn,
  2634. seq_number: REMOTE_SEQ,
  2635. ack_number: None,
  2636. window_scale: Some(0),
  2637. ..SEND_TEMPL
  2638. }
  2639. );
  2640. assert_eq!(s.remote_win_shift, *shift_amt);
  2641. recv!(
  2642. s,
  2643. [TcpRepr {
  2644. control: TcpControl::Syn,
  2645. seq_number: LOCAL_SEQ,
  2646. ack_number: Some(REMOTE_SEQ + 1),
  2647. max_seg_size: Some(BASE_MSS),
  2648. window_scale: Some(*shift_amt),
  2649. window_len: cmp::min(*buffer_size, 65535) as u16,
  2650. ..RECV_TEMPL
  2651. }]
  2652. );
  2653. }
  2654. }
  2655. #[test]
  2656. fn test_listen_sanity() {
  2657. let mut s = socket();
  2658. s.listen(LOCAL_PORT).unwrap();
  2659. sanity!(s, socket_listen());
  2660. }
  2661. #[test]
  2662. fn test_listen_validation() {
  2663. let mut s = socket();
  2664. assert_eq!(s.listen(0), Err(Error::Unaddressable));
  2665. }
  2666. #[test]
  2667. fn test_listen_twice() {
  2668. let mut s = socket();
  2669. assert_eq!(s.listen(80), Ok(()));
  2670. assert_eq!(s.listen(80), Err(Error::Illegal));
  2671. }
  2672. #[test]
  2673. fn test_listen_syn() {
  2674. let mut s = socket_listen();
  2675. send!(
  2676. s,
  2677. TcpRepr {
  2678. control: TcpControl::Syn,
  2679. seq_number: REMOTE_SEQ,
  2680. ack_number: None,
  2681. ..SEND_TEMPL
  2682. }
  2683. );
  2684. sanity!(s, socket_syn_received());
  2685. }
  2686. #[test]
  2687. fn test_listen_syn_reject_ack() {
  2688. let s = socket_listen();
  2689. let tcp_repr = TcpRepr {
  2690. control: TcpControl::Syn,
  2691. seq_number: REMOTE_SEQ,
  2692. ack_number: Some(LOCAL_SEQ),
  2693. ..SEND_TEMPL
  2694. };
  2695. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2696. assert_eq!(s.state, State::Listen);
  2697. }
  2698. #[test]
  2699. fn test_listen_rst() {
  2700. let mut s = socket_listen();
  2701. send!(
  2702. s,
  2703. TcpRepr {
  2704. control: TcpControl::Rst,
  2705. seq_number: REMOTE_SEQ,
  2706. ack_number: None,
  2707. ..SEND_TEMPL
  2708. },
  2709. Err(Error::Dropped)
  2710. );
  2711. }
  2712. #[test]
  2713. fn test_listen_close() {
  2714. let mut s = socket_listen();
  2715. s.close();
  2716. assert_eq!(s.state, State::Closed);
  2717. }
  2718. // =========================================================================================//
  2719. // Tests for the SYN-RECEIVED state.
  2720. // =========================================================================================//
  2721. #[test]
  2722. fn test_syn_received_ack() {
  2723. let mut s = socket_syn_received();
  2724. recv!(
  2725. s,
  2726. [TcpRepr {
  2727. control: TcpControl::Syn,
  2728. seq_number: LOCAL_SEQ,
  2729. ack_number: Some(REMOTE_SEQ + 1),
  2730. max_seg_size: Some(BASE_MSS),
  2731. ..RECV_TEMPL
  2732. }]
  2733. );
  2734. send!(
  2735. s,
  2736. TcpRepr {
  2737. seq_number: REMOTE_SEQ + 1,
  2738. ack_number: Some(LOCAL_SEQ + 1),
  2739. ..SEND_TEMPL
  2740. }
  2741. );
  2742. assert_eq!(s.state, State::Established);
  2743. sanity!(s, socket_established());
  2744. }
  2745. #[test]
  2746. fn test_syn_received_ack_too_low() {
  2747. let mut s = socket_syn_received();
  2748. recv!(
  2749. s,
  2750. [TcpRepr {
  2751. control: TcpControl::Syn,
  2752. seq_number: LOCAL_SEQ,
  2753. ack_number: Some(REMOTE_SEQ + 1),
  2754. max_seg_size: Some(BASE_MSS),
  2755. ..RECV_TEMPL
  2756. }]
  2757. );
  2758. send!(
  2759. s,
  2760. TcpRepr {
  2761. seq_number: REMOTE_SEQ + 1,
  2762. ack_number: Some(LOCAL_SEQ), // wrong
  2763. ..SEND_TEMPL
  2764. },
  2765. Ok(Some(TcpRepr {
  2766. control: TcpControl::Rst,
  2767. seq_number: LOCAL_SEQ,
  2768. ack_number: None,
  2769. window_len: 0,
  2770. ..RECV_TEMPL
  2771. }))
  2772. );
  2773. assert_eq!(s.state, State::SynReceived);
  2774. }
  2775. #[test]
  2776. fn test_syn_received_ack_too_high() {
  2777. let mut s = socket_syn_received();
  2778. recv!(
  2779. s,
  2780. [TcpRepr {
  2781. control: TcpControl::Syn,
  2782. seq_number: LOCAL_SEQ,
  2783. ack_number: Some(REMOTE_SEQ + 1),
  2784. max_seg_size: Some(BASE_MSS),
  2785. ..RECV_TEMPL
  2786. }]
  2787. );
  2788. send!(
  2789. s,
  2790. TcpRepr {
  2791. seq_number: REMOTE_SEQ + 1,
  2792. ack_number: Some(LOCAL_SEQ + 2), // wrong
  2793. ..SEND_TEMPL
  2794. },
  2795. Ok(Some(TcpRepr {
  2796. control: TcpControl::Rst,
  2797. seq_number: LOCAL_SEQ + 2,
  2798. ack_number: None,
  2799. window_len: 0,
  2800. ..RECV_TEMPL
  2801. }))
  2802. );
  2803. assert_eq!(s.state, State::SynReceived);
  2804. }
  2805. #[test]
  2806. fn test_syn_received_fin() {
  2807. let mut s = socket_syn_received();
  2808. recv!(
  2809. s,
  2810. [TcpRepr {
  2811. control: TcpControl::Syn,
  2812. seq_number: LOCAL_SEQ,
  2813. ack_number: Some(REMOTE_SEQ + 1),
  2814. max_seg_size: Some(BASE_MSS),
  2815. ..RECV_TEMPL
  2816. }]
  2817. );
  2818. send!(
  2819. s,
  2820. TcpRepr {
  2821. control: TcpControl::Fin,
  2822. seq_number: REMOTE_SEQ + 1,
  2823. ack_number: Some(LOCAL_SEQ + 1),
  2824. payload: &b"abcdef"[..],
  2825. ..SEND_TEMPL
  2826. }
  2827. );
  2828. recv!(
  2829. s,
  2830. [TcpRepr {
  2831. seq_number: LOCAL_SEQ + 1,
  2832. ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
  2833. window_len: 58,
  2834. ..RECV_TEMPL
  2835. }]
  2836. );
  2837. assert_eq!(s.state, State::CloseWait);
  2838. sanity!(
  2839. s,
  2840. TcpSocket {
  2841. remote_last_ack: Some(REMOTE_SEQ + 1 + 6 + 1),
  2842. remote_last_win: 58,
  2843. ..socket_close_wait()
  2844. }
  2845. );
  2846. }
  2847. #[test]
  2848. fn test_syn_received_rst() {
  2849. let mut s = socket_syn_received();
  2850. recv!(
  2851. s,
  2852. [TcpRepr {
  2853. control: TcpControl::Syn,
  2854. seq_number: LOCAL_SEQ,
  2855. ack_number: Some(REMOTE_SEQ + 1),
  2856. max_seg_size: Some(BASE_MSS),
  2857. ..RECV_TEMPL
  2858. }]
  2859. );
  2860. send!(
  2861. s,
  2862. TcpRepr {
  2863. control: TcpControl::Rst,
  2864. seq_number: REMOTE_SEQ + 1,
  2865. ack_number: Some(LOCAL_SEQ),
  2866. ..SEND_TEMPL
  2867. }
  2868. );
  2869. assert_eq!(s.state, State::Listen);
  2870. assert_eq!(
  2871. s.local_endpoint,
  2872. IpEndpoint::new(IpAddress::Unspecified, LOCAL_END.port)
  2873. );
  2874. assert_eq!(s.remote_endpoint, IpEndpoint::default());
  2875. }
  2876. #[test]
  2877. fn test_syn_received_no_window_scaling() {
  2878. let mut s = socket_listen();
  2879. send!(
  2880. s,
  2881. TcpRepr {
  2882. control: TcpControl::Syn,
  2883. seq_number: REMOTE_SEQ,
  2884. ack_number: None,
  2885. ..SEND_TEMPL
  2886. }
  2887. );
  2888. assert_eq!(s.state(), State::SynReceived);
  2889. assert_eq!(s.local_endpoint(), LOCAL_END);
  2890. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2891. recv!(
  2892. s,
  2893. [TcpRepr {
  2894. control: TcpControl::Syn,
  2895. seq_number: LOCAL_SEQ,
  2896. ack_number: Some(REMOTE_SEQ + 1),
  2897. max_seg_size: Some(BASE_MSS),
  2898. window_scale: None,
  2899. ..RECV_TEMPL
  2900. }]
  2901. );
  2902. send!(
  2903. s,
  2904. TcpRepr {
  2905. seq_number: REMOTE_SEQ + 1,
  2906. ack_number: Some(LOCAL_SEQ + 1),
  2907. window_scale: None,
  2908. ..SEND_TEMPL
  2909. }
  2910. );
  2911. assert_eq!(s.remote_win_shift, 0);
  2912. assert_eq!(s.remote_win_scale, None);
  2913. }
  2914. #[test]
  2915. fn test_syn_received_window_scaling() {
  2916. for scale in 0..14 {
  2917. let mut s = socket_listen();
  2918. send!(
  2919. s,
  2920. TcpRepr {
  2921. control: TcpControl::Syn,
  2922. seq_number: REMOTE_SEQ,
  2923. ack_number: None,
  2924. window_scale: Some(scale),
  2925. ..SEND_TEMPL
  2926. }
  2927. );
  2928. assert_eq!(s.state(), State::SynReceived);
  2929. assert_eq!(s.local_endpoint(), LOCAL_END);
  2930. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2931. recv!(
  2932. s,
  2933. [TcpRepr {
  2934. control: TcpControl::Syn,
  2935. seq_number: LOCAL_SEQ,
  2936. ack_number: Some(REMOTE_SEQ + 1),
  2937. max_seg_size: Some(BASE_MSS),
  2938. window_scale: Some(0),
  2939. ..RECV_TEMPL
  2940. }]
  2941. );
  2942. send!(
  2943. s,
  2944. TcpRepr {
  2945. seq_number: REMOTE_SEQ + 1,
  2946. ack_number: Some(LOCAL_SEQ + 1),
  2947. window_scale: None,
  2948. ..SEND_TEMPL
  2949. }
  2950. );
  2951. assert_eq!(s.remote_win_scale, Some(scale));
  2952. }
  2953. }
  2954. #[test]
  2955. fn test_syn_received_close() {
  2956. let mut s = socket_syn_received();
  2957. s.close();
  2958. assert_eq!(s.state, State::FinWait1);
  2959. }
  2960. // =========================================================================================//
  2961. // Tests for the SYN-SENT state.
  2962. // =========================================================================================//
  2963. #[test]
  2964. fn test_connect_validation() {
  2965. let mut s = socket();
  2966. assert_eq!(
  2967. s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2968. Err(Error::Unaddressable)
  2969. );
  2970. assert_eq!(
  2971. s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 0)),
  2972. Err(Error::Unaddressable)
  2973. );
  2974. assert_eq!(
  2975. s.connect((MOCK_UNSPECIFIED, 0), LOCAL_END),
  2976. Err(Error::Unaddressable)
  2977. );
  2978. assert_eq!(
  2979. s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2980. Err(Error::Unaddressable)
  2981. );
  2982. s.connect(REMOTE_END, LOCAL_END)
  2983. .expect("Connect failed with valid parameters");
  2984. assert_eq!(s.local_endpoint(), LOCAL_END);
  2985. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2986. }
  2987. #[test]
  2988. fn test_connect() {
  2989. let mut s = socket();
  2990. s.local_seq_no = LOCAL_SEQ;
  2991. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  2992. assert_eq!(
  2993. s.local_endpoint,
  2994. IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_END.port)
  2995. );
  2996. recv!(
  2997. s,
  2998. [TcpRepr {
  2999. control: TcpControl::Syn,
  3000. seq_number: LOCAL_SEQ,
  3001. ack_number: None,
  3002. max_seg_size: Some(BASE_MSS),
  3003. window_scale: Some(0),
  3004. sack_permitted: true,
  3005. ..RECV_TEMPL
  3006. }]
  3007. );
  3008. send!(
  3009. s,
  3010. TcpRepr {
  3011. control: TcpControl::Syn,
  3012. seq_number: REMOTE_SEQ,
  3013. ack_number: Some(LOCAL_SEQ + 1),
  3014. max_seg_size: Some(BASE_MSS - 80),
  3015. window_scale: Some(0),
  3016. ..SEND_TEMPL
  3017. }
  3018. );
  3019. assert_eq!(s.local_endpoint, LOCAL_END);
  3020. }
  3021. #[test]
  3022. fn test_connect_unspecified_local() {
  3023. let mut s = socket();
  3024. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 80)), Ok(()));
  3025. s.abort();
  3026. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)), Ok(()));
  3027. s.abort();
  3028. }
  3029. #[test]
  3030. fn test_connect_specified_local() {
  3031. let mut s = socket();
  3032. assert_eq!(s.connect(REMOTE_END, (MOCK_IP_ADDR_2, 80)), Ok(()));
  3033. }
  3034. #[test]
  3035. fn test_connect_twice() {
  3036. let mut s = socket();
  3037. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)), Ok(()));
  3038. assert_eq!(
  3039. s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  3040. Err(Error::Illegal)
  3041. );
  3042. }
  3043. #[test]
  3044. fn test_syn_sent_sanity() {
  3045. let mut s = socket();
  3046. s.local_seq_no = LOCAL_SEQ;
  3047. s.connect(REMOTE_END, LOCAL_END).unwrap();
  3048. sanity!(s, socket_syn_sent_with_local_ipendpoint(LOCAL_END));
  3049. }
  3050. #[test]
  3051. fn test_syn_sent_syn_ack() {
  3052. let mut s = socket_syn_sent();
  3053. recv!(
  3054. s,
  3055. [TcpRepr {
  3056. control: TcpControl::Syn,
  3057. seq_number: LOCAL_SEQ,
  3058. ack_number: None,
  3059. max_seg_size: Some(BASE_MSS),
  3060. window_scale: Some(0),
  3061. sack_permitted: true,
  3062. ..RECV_TEMPL
  3063. }]
  3064. );
  3065. send!(
  3066. s,
  3067. TcpRepr {
  3068. control: TcpControl::Syn,
  3069. seq_number: REMOTE_SEQ,
  3070. ack_number: Some(LOCAL_SEQ + 1),
  3071. max_seg_size: Some(BASE_MSS - 80),
  3072. window_scale: Some(0),
  3073. ..SEND_TEMPL
  3074. }
  3075. );
  3076. recv!(
  3077. s,
  3078. [TcpRepr {
  3079. seq_number: LOCAL_SEQ + 1,
  3080. ack_number: Some(REMOTE_SEQ + 1),
  3081. ..RECV_TEMPL
  3082. }]
  3083. );
  3084. recv!(s, time 1000, Err(Error::Exhausted));
  3085. assert_eq!(s.state, State::Established);
  3086. sanity!(s, socket_established());
  3087. }
  3088. #[test]
  3089. fn test_syn_sent_syn_ack_not_incremented() {
  3090. let mut s = socket_syn_sent();
  3091. recv!(
  3092. s,
  3093. [TcpRepr {
  3094. control: TcpControl::Syn,
  3095. seq_number: LOCAL_SEQ,
  3096. ack_number: None,
  3097. max_seg_size: Some(BASE_MSS),
  3098. window_scale: Some(0),
  3099. sack_permitted: true,
  3100. ..RECV_TEMPL
  3101. }]
  3102. );
  3103. send!(
  3104. s,
  3105. TcpRepr {
  3106. control: TcpControl::Syn,
  3107. seq_number: REMOTE_SEQ,
  3108. ack_number: Some(LOCAL_SEQ), // WRONG
  3109. max_seg_size: Some(BASE_MSS - 80),
  3110. window_scale: Some(0),
  3111. ..SEND_TEMPL
  3112. },
  3113. Ok(Some(TcpRepr {
  3114. control: TcpControl::Rst,
  3115. seq_number: LOCAL_SEQ,
  3116. ack_number: None,
  3117. window_len: 0,
  3118. ..RECV_TEMPL
  3119. }))
  3120. );
  3121. assert_eq!(s.state, State::SynSent);
  3122. }
  3123. #[test]
  3124. fn test_syn_sent_rst() {
  3125. let mut s = socket_syn_sent();
  3126. send!(
  3127. s,
  3128. TcpRepr {
  3129. control: TcpControl::Rst,
  3130. seq_number: REMOTE_SEQ,
  3131. ack_number: Some(LOCAL_SEQ + 1),
  3132. ..SEND_TEMPL
  3133. }
  3134. );
  3135. assert_eq!(s.state, State::Closed);
  3136. }
  3137. #[test]
  3138. fn test_syn_sent_rst_no_ack() {
  3139. let mut s = socket_syn_sent();
  3140. send!(
  3141. s,
  3142. TcpRepr {
  3143. control: TcpControl::Rst,
  3144. seq_number: REMOTE_SEQ,
  3145. ack_number: None,
  3146. ..SEND_TEMPL
  3147. },
  3148. Err(Error::Dropped)
  3149. );
  3150. assert_eq!(s.state, State::SynSent);
  3151. }
  3152. #[test]
  3153. fn test_syn_sent_rst_bad_ack() {
  3154. let mut s = socket_syn_sent();
  3155. send!(
  3156. s,
  3157. TcpRepr {
  3158. control: TcpControl::Rst,
  3159. seq_number: REMOTE_SEQ,
  3160. ack_number: Some(TcpSeqNumber(1234)),
  3161. ..SEND_TEMPL
  3162. },
  3163. Err(Error::Dropped)
  3164. );
  3165. assert_eq!(s.state, State::SynSent);
  3166. }
  3167. #[test]
  3168. fn test_syn_sent_bad_ack() {
  3169. let mut s = socket_syn_sent();
  3170. recv!(
  3171. s,
  3172. [TcpRepr {
  3173. control: TcpControl::Syn,
  3174. seq_number: LOCAL_SEQ,
  3175. ack_number: None,
  3176. max_seg_size: Some(BASE_MSS),
  3177. window_scale: Some(0),
  3178. sack_permitted: true,
  3179. ..RECV_TEMPL
  3180. }]
  3181. );
  3182. send!(
  3183. s,
  3184. TcpRepr {
  3185. control: TcpControl::None, // Unexpected
  3186. seq_number: REMOTE_SEQ,
  3187. ack_number: Some(LOCAL_SEQ + 1), // Correct
  3188. ..SEND_TEMPL
  3189. },
  3190. Err(Error::Dropped)
  3191. );
  3192. // It should trigger no response and change no state
  3193. recv!(s, []);
  3194. assert_eq!(s.state, State::SynSent);
  3195. }
  3196. #[test]
  3197. fn test_syn_sent_bad_ack_seq_1() {
  3198. let mut s = socket_syn_sent();
  3199. recv!(
  3200. s,
  3201. [TcpRepr {
  3202. control: TcpControl::Syn,
  3203. seq_number: LOCAL_SEQ,
  3204. ack_number: None,
  3205. max_seg_size: Some(BASE_MSS),
  3206. window_scale: Some(0),
  3207. sack_permitted: true,
  3208. ..RECV_TEMPL
  3209. }]
  3210. );
  3211. send!(
  3212. s,
  3213. TcpRepr {
  3214. control: TcpControl::None,
  3215. seq_number: REMOTE_SEQ,
  3216. ack_number: Some(LOCAL_SEQ), // WRONG
  3217. ..SEND_TEMPL
  3218. },
  3219. Ok(Some(TcpRepr {
  3220. control: TcpControl::Rst,
  3221. seq_number: LOCAL_SEQ, // matching the ack_number of the unexpected ack
  3222. ack_number: None,
  3223. window_len: 0,
  3224. ..RECV_TEMPL
  3225. }))
  3226. );
  3227. // It should trigger a RST, and change no state
  3228. assert_eq!(s.state, State::SynSent);
  3229. }
  3230. #[test]
  3231. fn test_syn_sent_bad_ack_seq_2() {
  3232. let mut s = socket_syn_sent();
  3233. recv!(
  3234. s,
  3235. [TcpRepr {
  3236. control: TcpControl::Syn,
  3237. seq_number: LOCAL_SEQ,
  3238. ack_number: None,
  3239. max_seg_size: Some(BASE_MSS),
  3240. window_scale: Some(0),
  3241. sack_permitted: true,
  3242. ..RECV_TEMPL
  3243. }]
  3244. );
  3245. send!(
  3246. s,
  3247. TcpRepr {
  3248. control: TcpControl::None,
  3249. seq_number: REMOTE_SEQ,
  3250. ack_number: Some(LOCAL_SEQ + 123456), // WRONG
  3251. ..SEND_TEMPL
  3252. },
  3253. Ok(Some(TcpRepr {
  3254. control: TcpControl::Rst,
  3255. seq_number: LOCAL_SEQ + 123456, // matching the ack_number of the unexpected ack
  3256. ack_number: None,
  3257. window_len: 0,
  3258. ..RECV_TEMPL
  3259. }))
  3260. );
  3261. // It should trigger a RST, and change no state
  3262. assert_eq!(s.state, State::SynSent);
  3263. }
  3264. #[test]
  3265. fn test_syn_sent_close() {
  3266. let mut s = socket();
  3267. s.close();
  3268. assert_eq!(s.state, State::Closed);
  3269. }
  3270. #[test]
  3271. fn test_syn_sent_win_scale_buffers() {
  3272. for (buffer_size, shift_amt) in &[
  3273. (64, 0),
  3274. (128, 0),
  3275. (1024, 0),
  3276. (65535, 0),
  3277. (65536, 1),
  3278. (65537, 1),
  3279. (131071, 1),
  3280. (131072, 2),
  3281. (524287, 3),
  3282. (524288, 4),
  3283. (655350, 4),
  3284. (1048576, 5),
  3285. ] {
  3286. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  3287. s.local_seq_no = LOCAL_SEQ;
  3288. assert_eq!(s.remote_win_shift, *shift_amt);
  3289. s.connect(REMOTE_END, LOCAL_END).unwrap();
  3290. recv!(
  3291. s,
  3292. [TcpRepr {
  3293. control: TcpControl::Syn,
  3294. seq_number: LOCAL_SEQ,
  3295. ack_number: None,
  3296. max_seg_size: Some(BASE_MSS),
  3297. window_scale: Some(*shift_amt),
  3298. window_len: cmp::min(*buffer_size, 65535) as u16,
  3299. sack_permitted: true,
  3300. ..RECV_TEMPL
  3301. }]
  3302. );
  3303. }
  3304. }
  3305. #[test]
  3306. fn test_syn_sent_syn_ack_no_window_scaling() {
  3307. let mut s = socket_syn_sent_with_buffer_sizes(1048576, 1048576);
  3308. recv!(
  3309. s,
  3310. [TcpRepr {
  3311. control: TcpControl::Syn,
  3312. seq_number: LOCAL_SEQ,
  3313. ack_number: None,
  3314. max_seg_size: Some(BASE_MSS),
  3315. // scaling does NOT apply to the window value in SYN packets
  3316. window_len: 65535,
  3317. window_scale: Some(5),
  3318. sack_permitted: true,
  3319. ..RECV_TEMPL
  3320. }]
  3321. );
  3322. assert_eq!(s.remote_win_shift, 5);
  3323. send!(
  3324. s,
  3325. TcpRepr {
  3326. control: TcpControl::Syn,
  3327. seq_number: REMOTE_SEQ,
  3328. ack_number: Some(LOCAL_SEQ + 1),
  3329. max_seg_size: Some(BASE_MSS - 80),
  3330. window_scale: None,
  3331. window_len: 42,
  3332. ..SEND_TEMPL
  3333. }
  3334. );
  3335. assert_eq!(s.state, State::Established);
  3336. assert_eq!(s.remote_win_shift, 0);
  3337. assert_eq!(s.remote_win_scale, None);
  3338. assert_eq!(s.remote_win_len, 42);
  3339. }
  3340. #[test]
  3341. fn test_syn_sent_syn_ack_window_scaling() {
  3342. let mut s = socket_syn_sent();
  3343. recv!(
  3344. s,
  3345. [TcpRepr {
  3346. control: TcpControl::Syn,
  3347. seq_number: LOCAL_SEQ,
  3348. ack_number: None,
  3349. max_seg_size: Some(BASE_MSS),
  3350. window_scale: Some(0),
  3351. sack_permitted: true,
  3352. ..RECV_TEMPL
  3353. }]
  3354. );
  3355. send!(
  3356. s,
  3357. TcpRepr {
  3358. control: TcpControl::Syn,
  3359. seq_number: REMOTE_SEQ,
  3360. ack_number: Some(LOCAL_SEQ + 1),
  3361. max_seg_size: Some(BASE_MSS - 80),
  3362. window_scale: Some(7),
  3363. window_len: 42,
  3364. ..SEND_TEMPL
  3365. }
  3366. );
  3367. assert_eq!(s.state, State::Established);
  3368. assert_eq!(s.remote_win_scale, Some(7));
  3369. // scaling does NOT apply to the window value in SYN packets
  3370. assert_eq!(s.remote_win_len, 42);
  3371. }
  3372. // =========================================================================================//
  3373. // Tests for the ESTABLISHED state.
  3374. // =========================================================================================//
  3375. #[test]
  3376. fn test_established_recv() {
  3377. let mut s = socket_established();
  3378. send!(
  3379. s,
  3380. TcpRepr {
  3381. seq_number: REMOTE_SEQ + 1,
  3382. ack_number: Some(LOCAL_SEQ + 1),
  3383. payload: &b"abcdef"[..],
  3384. ..SEND_TEMPL
  3385. }
  3386. );
  3387. recv!(
  3388. s,
  3389. [TcpRepr {
  3390. seq_number: LOCAL_SEQ + 1,
  3391. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3392. window_len: 58,
  3393. ..RECV_TEMPL
  3394. }]
  3395. );
  3396. assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
  3397. }
  3398. fn setup_rfc2018_cases() -> (TcpSocket<'static>, Vec<u8>) {
  3399. // This is a utility function used by the tests for RFC 2018 cases. It configures a socket
  3400. // in a particular way suitable for those cases.
  3401. //
  3402. // RFC 2018: Assume the left window edge is 5000 and that the data transmitter sends [...]
  3403. // segments, each containing 500 data bytes.
  3404. let mut s = socket_established_with_buffer_sizes(4000, 4000);
  3405. s.remote_has_sack = true;
  3406. // create a segment that is 500 bytes long
  3407. let mut segment: Vec<u8> = Vec::with_capacity(500);
  3408. // move the last ack to 5000 by sending ten of them
  3409. for _ in 0..50 {
  3410. segment.extend_from_slice(b"abcdefghij")
  3411. }
  3412. for offset in (0..5000).step_by(500) {
  3413. send!(
  3414. s,
  3415. TcpRepr {
  3416. seq_number: REMOTE_SEQ + 1 + offset,
  3417. ack_number: Some(LOCAL_SEQ + 1),
  3418. payload: &segment,
  3419. ..SEND_TEMPL
  3420. }
  3421. );
  3422. recv!(
  3423. s,
  3424. [TcpRepr {
  3425. seq_number: LOCAL_SEQ + 1,
  3426. ack_number: Some(REMOTE_SEQ + 1 + offset + 500),
  3427. window_len: 3500,
  3428. ..RECV_TEMPL
  3429. }]
  3430. );
  3431. s.recv(|data| {
  3432. assert_eq!(data.len(), 500);
  3433. assert_eq!(data, segment.as_slice());
  3434. (500, ())
  3435. })
  3436. .unwrap();
  3437. }
  3438. assert_eq!(s.remote_last_win, 3500);
  3439. (s, segment)
  3440. }
  3441. #[test]
  3442. fn test_established_rfc2018_cases() {
  3443. // This test case verifies the exact scenarios described on pages 8-9 of RFC 2018. Please
  3444. // ensure its behavior does not deviate from those scenarios.
  3445. let (mut s, segment) = setup_rfc2018_cases();
  3446. // RFC 2018:
  3447. //
  3448. // Case 2: The first segment is dropped but the remaining 7 are received.
  3449. //
  3450. // Upon receiving each of the last seven packets, the data receiver will return a TCP ACK
  3451. // segment that acknowledges sequence number 5000 and contains a SACK option specifying one
  3452. // block of queued data:
  3453. //
  3454. // Triggering ACK Left Edge Right Edge
  3455. // Segment
  3456. //
  3457. // 5000 (lost)
  3458. // 5500 5000 5500 6000
  3459. // 6000 5000 5500 6500
  3460. // 6500 5000 5500 7000
  3461. // 7000 5000 5500 7500
  3462. // 7500 5000 5500 8000
  3463. // 8000 5000 5500 8500
  3464. // 8500 5000 5500 9000
  3465. //
  3466. for offset in (500..3500).step_by(500) {
  3467. send!(
  3468. s,
  3469. TcpRepr {
  3470. seq_number: REMOTE_SEQ + 1 + offset + 5000,
  3471. ack_number: Some(LOCAL_SEQ + 1),
  3472. payload: &segment,
  3473. ..SEND_TEMPL
  3474. },
  3475. Ok(Some(TcpRepr {
  3476. seq_number: LOCAL_SEQ + 1,
  3477. ack_number: Some(REMOTE_SEQ + 1 + 5000),
  3478. window_len: 4000,
  3479. sack_ranges: [
  3480. Some((
  3481. REMOTE_SEQ.0 as u32 + 1 + 5500,
  3482. REMOTE_SEQ.0 as u32 + 1 + 5500 + offset as u32
  3483. )),
  3484. None,
  3485. None
  3486. ],
  3487. ..RECV_TEMPL
  3488. }))
  3489. );
  3490. }
  3491. }
  3492. #[test]
  3493. fn test_established_sliding_window_recv() {
  3494. let mut s = socket_established();
  3495. // Update our scaling parameters for a TCP with a scaled buffer.
  3496. assert_eq!(s.rx_buffer.len(), 0);
  3497. s.rx_buffer = SocketBuffer::new(vec![0; 262143]);
  3498. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3499. s.remote_win_scale = Some(0);
  3500. s.remote_last_win = 65535;
  3501. s.remote_win_shift = 2;
  3502. // Create a TCP segment that will mostly fill an IP frame.
  3503. let mut segment: Vec<u8> = Vec::with_capacity(1400);
  3504. for _ in 0..100 {
  3505. segment.extend_from_slice(b"abcdefghijklmn")
  3506. }
  3507. assert_eq!(segment.len(), 1400);
  3508. // Send the frame
  3509. send!(
  3510. s,
  3511. TcpRepr {
  3512. seq_number: REMOTE_SEQ + 1,
  3513. ack_number: Some(LOCAL_SEQ + 1),
  3514. payload: &segment,
  3515. ..SEND_TEMPL
  3516. }
  3517. );
  3518. // Ensure that the received window size is shifted right by 2.
  3519. recv!(
  3520. s,
  3521. [TcpRepr {
  3522. seq_number: LOCAL_SEQ + 1,
  3523. ack_number: Some(REMOTE_SEQ + 1 + 1400),
  3524. window_len: 65185,
  3525. ..RECV_TEMPL
  3526. }]
  3527. );
  3528. }
  3529. #[test]
  3530. fn test_established_send() {
  3531. let mut s = socket_established();
  3532. // First roundtrip after establishing.
  3533. s.send_slice(b"abcdef").unwrap();
  3534. recv!(
  3535. s,
  3536. [TcpRepr {
  3537. seq_number: LOCAL_SEQ + 1,
  3538. ack_number: Some(REMOTE_SEQ + 1),
  3539. payload: &b"abcdef"[..],
  3540. ..RECV_TEMPL
  3541. }]
  3542. );
  3543. assert_eq!(s.tx_buffer.len(), 6);
  3544. send!(
  3545. s,
  3546. TcpRepr {
  3547. seq_number: REMOTE_SEQ + 1,
  3548. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3549. ..SEND_TEMPL
  3550. }
  3551. );
  3552. assert_eq!(s.tx_buffer.len(), 0);
  3553. // Second roundtrip.
  3554. s.send_slice(b"foobar").unwrap();
  3555. recv!(
  3556. s,
  3557. [TcpRepr {
  3558. seq_number: LOCAL_SEQ + 1 + 6,
  3559. ack_number: Some(REMOTE_SEQ + 1),
  3560. payload: &b"foobar"[..],
  3561. ..RECV_TEMPL
  3562. }]
  3563. );
  3564. send!(
  3565. s,
  3566. TcpRepr {
  3567. seq_number: REMOTE_SEQ + 1,
  3568. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3569. ..SEND_TEMPL
  3570. }
  3571. );
  3572. assert_eq!(s.tx_buffer.len(), 0);
  3573. }
  3574. #[test]
  3575. fn test_established_send_no_ack_send() {
  3576. let mut s = socket_established();
  3577. s.set_nagle_enabled(false);
  3578. s.send_slice(b"abcdef").unwrap();
  3579. recv!(
  3580. s,
  3581. [TcpRepr {
  3582. seq_number: LOCAL_SEQ + 1,
  3583. ack_number: Some(REMOTE_SEQ + 1),
  3584. payload: &b"abcdef"[..],
  3585. ..RECV_TEMPL
  3586. }]
  3587. );
  3588. s.send_slice(b"foobar").unwrap();
  3589. recv!(
  3590. s,
  3591. [TcpRepr {
  3592. seq_number: LOCAL_SEQ + 1 + 6,
  3593. ack_number: Some(REMOTE_SEQ + 1),
  3594. payload: &b"foobar"[..],
  3595. ..RECV_TEMPL
  3596. }]
  3597. );
  3598. }
  3599. #[test]
  3600. fn test_established_send_buf_gt_win() {
  3601. let mut data = [0; 32];
  3602. for (i, elem) in data.iter_mut().enumerate() {
  3603. *elem = i as u8
  3604. }
  3605. let mut s = socket_established();
  3606. s.remote_win_len = 16;
  3607. s.send_slice(&data[..]).unwrap();
  3608. recv!(
  3609. s,
  3610. [TcpRepr {
  3611. seq_number: LOCAL_SEQ + 1,
  3612. ack_number: Some(REMOTE_SEQ + 1),
  3613. payload: &data[0..16],
  3614. ..RECV_TEMPL
  3615. }]
  3616. );
  3617. }
  3618. #[test]
  3619. fn test_established_send_window_shrink() {
  3620. let mut s = socket_established();
  3621. // 6 octets fit on the remote side's window, so we send them.
  3622. s.send_slice(b"abcdef").unwrap();
  3623. recv!(
  3624. s,
  3625. [TcpRepr {
  3626. seq_number: LOCAL_SEQ + 1,
  3627. ack_number: Some(REMOTE_SEQ + 1),
  3628. payload: &b"abcdef"[..],
  3629. ..RECV_TEMPL
  3630. }]
  3631. );
  3632. assert_eq!(s.tx_buffer.len(), 6);
  3633. println!(
  3634. "local_seq_no={} remote_win_len={} remote_last_seq={}",
  3635. s.local_seq_no, s.remote_win_len, s.remote_last_seq
  3636. );
  3637. // - Peer doesn't ack them yet
  3638. // - Sends data so we need to reply with an ACK
  3639. // - ...AND and sends a window announcement that SHRINKS the window, so data we've
  3640. // previously sent is now outside the window. Yes, this is allowed by TCP.
  3641. send!(
  3642. s,
  3643. TcpRepr {
  3644. seq_number: REMOTE_SEQ + 1,
  3645. ack_number: Some(LOCAL_SEQ + 1),
  3646. window_len: 3,
  3647. payload: &b"xyzxyz"[..],
  3648. ..SEND_TEMPL
  3649. }
  3650. );
  3651. assert_eq!(s.tx_buffer.len(), 6);
  3652. println!(
  3653. "local_seq_no={} remote_win_len={} remote_last_seq={}",
  3654. s.local_seq_no, s.remote_win_len, s.remote_last_seq
  3655. );
  3656. // More data should not get sent since it doesn't fit in the window
  3657. s.send_slice(b"foobar").unwrap();
  3658. recv!(
  3659. s,
  3660. [TcpRepr {
  3661. seq_number: LOCAL_SEQ + 1 + 6,
  3662. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3663. window_len: 64 - 6,
  3664. ..RECV_TEMPL
  3665. }]
  3666. );
  3667. }
  3668. #[test]
  3669. fn test_established_send_wrap() {
  3670. let mut s = socket_established();
  3671. let local_seq_start = TcpSeqNumber(i32::MAX - 1);
  3672. s.local_seq_no = local_seq_start + 1;
  3673. s.remote_last_seq = local_seq_start + 1;
  3674. s.send_slice(b"abc").unwrap();
  3675. recv!(s, time 1000, Ok(TcpRepr {
  3676. seq_number: local_seq_start + 1,
  3677. ack_number: Some(REMOTE_SEQ + 1),
  3678. payload: &b"abc"[..],
  3679. ..RECV_TEMPL
  3680. }));
  3681. }
  3682. #[test]
  3683. fn test_established_no_ack() {
  3684. let mut s = socket_established();
  3685. send!(
  3686. s,
  3687. TcpRepr {
  3688. seq_number: REMOTE_SEQ + 1,
  3689. ack_number: None,
  3690. ..SEND_TEMPL
  3691. },
  3692. Err(Error::Dropped)
  3693. );
  3694. }
  3695. #[test]
  3696. fn test_established_bad_ack() {
  3697. let mut s = socket_established();
  3698. // Already acknowledged data.
  3699. send!(
  3700. s,
  3701. TcpRepr {
  3702. seq_number: REMOTE_SEQ + 1,
  3703. ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
  3704. ..SEND_TEMPL
  3705. },
  3706. Err(Error::Dropped)
  3707. );
  3708. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  3709. // Data not yet transmitted.
  3710. send!(
  3711. s,
  3712. TcpRepr {
  3713. seq_number: REMOTE_SEQ + 1,
  3714. ack_number: Some(LOCAL_SEQ + 10),
  3715. ..SEND_TEMPL
  3716. },
  3717. Ok(Some(TcpRepr {
  3718. seq_number: LOCAL_SEQ + 1,
  3719. ack_number: Some(REMOTE_SEQ + 1),
  3720. ..RECV_TEMPL
  3721. }))
  3722. );
  3723. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  3724. }
  3725. #[test]
  3726. fn test_established_bad_seq() {
  3727. let mut s = socket_established();
  3728. // Data outside of receive window.
  3729. send!(
  3730. s,
  3731. TcpRepr {
  3732. seq_number: REMOTE_SEQ + 1 + 256,
  3733. ack_number: Some(LOCAL_SEQ + 1),
  3734. ..SEND_TEMPL
  3735. },
  3736. Ok(Some(TcpRepr {
  3737. seq_number: LOCAL_SEQ + 1,
  3738. ack_number: Some(REMOTE_SEQ + 1),
  3739. ..RECV_TEMPL
  3740. }))
  3741. );
  3742. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  3743. // Challenge ACKs are rate-limited, we don't get a second one immediately.
  3744. send!(
  3745. s,
  3746. time 100,
  3747. TcpRepr {
  3748. seq_number: REMOTE_SEQ + 1 + 256,
  3749. ack_number: Some(LOCAL_SEQ + 1),
  3750. ..SEND_TEMPL
  3751. },
  3752. Ok(None)
  3753. );
  3754. // If we wait a bit, we do get a new one.
  3755. send!(
  3756. s,
  3757. time 2000,
  3758. TcpRepr {
  3759. seq_number: REMOTE_SEQ + 1 + 256,
  3760. ack_number: Some(LOCAL_SEQ + 1),
  3761. ..SEND_TEMPL
  3762. },
  3763. Ok(Some(TcpRepr {
  3764. seq_number: LOCAL_SEQ + 1,
  3765. ack_number: Some(REMOTE_SEQ + 1),
  3766. ..RECV_TEMPL
  3767. }))
  3768. );
  3769. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  3770. }
  3771. #[test]
  3772. fn test_established_fin() {
  3773. let mut s = socket_established();
  3774. send!(
  3775. s,
  3776. TcpRepr {
  3777. control: TcpControl::Fin,
  3778. seq_number: REMOTE_SEQ + 1,
  3779. ack_number: Some(LOCAL_SEQ + 1),
  3780. ..SEND_TEMPL
  3781. }
  3782. );
  3783. recv!(
  3784. s,
  3785. [TcpRepr {
  3786. seq_number: LOCAL_SEQ + 1,
  3787. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3788. ..RECV_TEMPL
  3789. }]
  3790. );
  3791. assert_eq!(s.state, State::CloseWait);
  3792. sanity!(s, socket_close_wait());
  3793. }
  3794. #[test]
  3795. fn test_established_fin_after_missing() {
  3796. let mut s = socket_established();
  3797. send!(
  3798. s,
  3799. TcpRepr {
  3800. control: TcpControl::Fin,
  3801. seq_number: REMOTE_SEQ + 1 + 6,
  3802. ack_number: Some(LOCAL_SEQ + 1),
  3803. payload: &b"123456"[..],
  3804. ..SEND_TEMPL
  3805. },
  3806. Ok(Some(TcpRepr {
  3807. seq_number: LOCAL_SEQ + 1,
  3808. ack_number: Some(REMOTE_SEQ + 1),
  3809. ..RECV_TEMPL
  3810. }))
  3811. );
  3812. assert_eq!(s.state, State::Established);
  3813. send!(
  3814. s,
  3815. TcpRepr {
  3816. seq_number: REMOTE_SEQ + 1,
  3817. ack_number: Some(LOCAL_SEQ + 1),
  3818. payload: &b"abcdef"[..],
  3819. ..SEND_TEMPL
  3820. },
  3821. Ok(Some(TcpRepr {
  3822. seq_number: LOCAL_SEQ + 1,
  3823. ack_number: Some(REMOTE_SEQ + 1 + 6 + 6),
  3824. window_len: 52,
  3825. ..RECV_TEMPL
  3826. }))
  3827. );
  3828. assert_eq!(s.state, State::Established);
  3829. }
  3830. #[test]
  3831. fn test_established_send_fin() {
  3832. let mut s = socket_established();
  3833. s.send_slice(b"abcdef").unwrap();
  3834. send!(
  3835. s,
  3836. TcpRepr {
  3837. control: TcpControl::Fin,
  3838. seq_number: REMOTE_SEQ + 1,
  3839. ack_number: Some(LOCAL_SEQ + 1),
  3840. ..SEND_TEMPL
  3841. }
  3842. );
  3843. assert_eq!(s.state, State::CloseWait);
  3844. recv!(
  3845. s,
  3846. [TcpRepr {
  3847. seq_number: LOCAL_SEQ + 1,
  3848. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3849. payload: &b"abcdef"[..],
  3850. ..RECV_TEMPL
  3851. }]
  3852. );
  3853. }
  3854. #[test]
  3855. fn test_established_rst() {
  3856. let mut s = socket_established();
  3857. send!(
  3858. s,
  3859. TcpRepr {
  3860. control: TcpControl::Rst,
  3861. seq_number: REMOTE_SEQ + 1,
  3862. ack_number: Some(LOCAL_SEQ + 1),
  3863. ..SEND_TEMPL
  3864. }
  3865. );
  3866. assert_eq!(s.state, State::Closed);
  3867. }
  3868. #[test]
  3869. fn test_established_rst_no_ack() {
  3870. let mut s = socket_established();
  3871. send!(
  3872. s,
  3873. TcpRepr {
  3874. control: TcpControl::Rst,
  3875. seq_number: REMOTE_SEQ + 1,
  3876. ack_number: None,
  3877. ..SEND_TEMPL
  3878. }
  3879. );
  3880. assert_eq!(s.state, State::Closed);
  3881. }
  3882. #[test]
  3883. fn test_established_close() {
  3884. let mut s = socket_established();
  3885. s.close();
  3886. assert_eq!(s.state, State::FinWait1);
  3887. sanity!(s, socket_fin_wait_1());
  3888. }
  3889. #[test]
  3890. fn test_established_abort() {
  3891. let mut s = socket_established();
  3892. s.abort();
  3893. assert_eq!(s.state, State::Closed);
  3894. recv!(
  3895. s,
  3896. [TcpRepr {
  3897. control: TcpControl::Rst,
  3898. seq_number: LOCAL_SEQ + 1,
  3899. ack_number: Some(REMOTE_SEQ + 1),
  3900. ..RECV_TEMPL
  3901. }]
  3902. );
  3903. }
  3904. #[test]
  3905. fn test_established_rst_bad_seq() {
  3906. let mut s = socket_established();
  3907. send!(
  3908. s,
  3909. TcpRepr {
  3910. control: TcpControl::Rst,
  3911. seq_number: REMOTE_SEQ, // Wrong seq
  3912. ack_number: None,
  3913. ..SEND_TEMPL
  3914. },
  3915. Ok(Some(TcpRepr {
  3916. seq_number: LOCAL_SEQ + 1,
  3917. ack_number: Some(REMOTE_SEQ + 1),
  3918. ..RECV_TEMPL
  3919. }))
  3920. );
  3921. assert_eq!(s.state, State::Established);
  3922. // Send something to advance seq by 1
  3923. send!(
  3924. s,
  3925. TcpRepr {
  3926. seq_number: REMOTE_SEQ + 1, // correct seq
  3927. ack_number: Some(LOCAL_SEQ + 1),
  3928. payload: &b"a"[..],
  3929. ..SEND_TEMPL
  3930. }
  3931. );
  3932. // Send wrong rst again, check that the challenge ack is correctly updated
  3933. // The ack number must be updated even if we don't call dispatch on the socket
  3934. // See https://github.com/smoltcp-rs/smoltcp/issues/338
  3935. send!(
  3936. s,
  3937. time 2000,
  3938. TcpRepr {
  3939. control: TcpControl::Rst,
  3940. seq_number: REMOTE_SEQ, // Wrong seq
  3941. ack_number: None,
  3942. ..SEND_TEMPL
  3943. },
  3944. Ok(Some(TcpRepr {
  3945. seq_number: LOCAL_SEQ + 1,
  3946. ack_number: Some(REMOTE_SEQ + 2), // this has changed
  3947. window_len: 63,
  3948. ..RECV_TEMPL
  3949. }))
  3950. );
  3951. }
  3952. // =========================================================================================//
  3953. // Tests for the FIN-WAIT-1 state.
  3954. // =========================================================================================//
  3955. #[test]
  3956. fn test_fin_wait_1_fin_ack() {
  3957. let mut s = socket_fin_wait_1();
  3958. recv!(
  3959. s,
  3960. [TcpRepr {
  3961. control: TcpControl::Fin,
  3962. seq_number: LOCAL_SEQ + 1,
  3963. ack_number: Some(REMOTE_SEQ + 1),
  3964. ..RECV_TEMPL
  3965. }]
  3966. );
  3967. send!(
  3968. s,
  3969. TcpRepr {
  3970. seq_number: REMOTE_SEQ + 1,
  3971. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3972. ..SEND_TEMPL
  3973. }
  3974. );
  3975. assert_eq!(s.state, State::FinWait2);
  3976. sanity!(s, socket_fin_wait_2());
  3977. }
  3978. #[test]
  3979. fn test_fin_wait_1_fin_fin() {
  3980. let mut s = socket_fin_wait_1();
  3981. recv!(
  3982. s,
  3983. [TcpRepr {
  3984. control: TcpControl::Fin,
  3985. seq_number: LOCAL_SEQ + 1,
  3986. ack_number: Some(REMOTE_SEQ + 1),
  3987. ..RECV_TEMPL
  3988. }]
  3989. );
  3990. send!(
  3991. s,
  3992. TcpRepr {
  3993. control: TcpControl::Fin,
  3994. seq_number: REMOTE_SEQ + 1,
  3995. ack_number: Some(LOCAL_SEQ + 1),
  3996. ..SEND_TEMPL
  3997. }
  3998. );
  3999. assert_eq!(s.state, State::Closing);
  4000. sanity!(s, socket_closing());
  4001. }
  4002. #[test]
  4003. fn test_fin_wait_1_fin_with_data_queued() {
  4004. let mut s = socket_established();
  4005. s.remote_win_len = 6;
  4006. s.send_slice(b"abcdef123456").unwrap();
  4007. s.close();
  4008. recv!(
  4009. s,
  4010. Ok(TcpRepr {
  4011. seq_number: LOCAL_SEQ + 1,
  4012. ack_number: Some(REMOTE_SEQ + 1),
  4013. payload: &b"abcdef"[..],
  4014. ..RECV_TEMPL
  4015. })
  4016. );
  4017. send!(
  4018. s,
  4019. TcpRepr {
  4020. seq_number: REMOTE_SEQ + 1,
  4021. ack_number: Some(LOCAL_SEQ + 1 + 6),
  4022. ..SEND_TEMPL
  4023. }
  4024. );
  4025. assert_eq!(s.state, State::FinWait1);
  4026. }
  4027. #[test]
  4028. fn test_fin_wait_1_recv() {
  4029. let mut s = socket_fin_wait_1();
  4030. send!(
  4031. s,
  4032. TcpRepr {
  4033. seq_number: REMOTE_SEQ + 1,
  4034. ack_number: Some(LOCAL_SEQ + 1),
  4035. payload: &b"abc"[..],
  4036. ..SEND_TEMPL
  4037. }
  4038. );
  4039. assert_eq!(s.state, State::FinWait1);
  4040. s.recv(|data| {
  4041. assert_eq!(data, b"abc");
  4042. (3, ())
  4043. })
  4044. .unwrap();
  4045. }
  4046. #[test]
  4047. fn test_fin_wait_1_close() {
  4048. let mut s = socket_fin_wait_1();
  4049. s.close();
  4050. assert_eq!(s.state, State::FinWait1);
  4051. }
  4052. // =========================================================================================//
  4053. // Tests for the FIN-WAIT-2 state.
  4054. // =========================================================================================//
  4055. #[test]
  4056. fn test_fin_wait_2_fin() {
  4057. let mut s = socket_fin_wait_2();
  4058. send!(s, time 1_000, TcpRepr {
  4059. control: TcpControl::Fin,
  4060. seq_number: REMOTE_SEQ + 1,
  4061. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4062. ..SEND_TEMPL
  4063. });
  4064. assert_eq!(s.state, State::TimeWait);
  4065. sanity!(s, socket_time_wait(false));
  4066. }
  4067. #[test]
  4068. fn test_fin_wait_2_recv() {
  4069. let mut s = socket_fin_wait_2();
  4070. send!(
  4071. s,
  4072. TcpRepr {
  4073. seq_number: REMOTE_SEQ + 1,
  4074. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4075. payload: &b"abc"[..],
  4076. ..SEND_TEMPL
  4077. }
  4078. );
  4079. assert_eq!(s.state, State::FinWait2);
  4080. s.recv(|data| {
  4081. assert_eq!(data, b"abc");
  4082. (3, ())
  4083. })
  4084. .unwrap();
  4085. recv!(
  4086. s,
  4087. [TcpRepr {
  4088. seq_number: LOCAL_SEQ + 1 + 1,
  4089. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4090. ..RECV_TEMPL
  4091. }]
  4092. );
  4093. }
  4094. #[test]
  4095. fn test_fin_wait_2_close() {
  4096. let mut s = socket_fin_wait_2();
  4097. s.close();
  4098. assert_eq!(s.state, State::FinWait2);
  4099. }
  4100. // =========================================================================================//
  4101. // Tests for the CLOSING state.
  4102. // =========================================================================================//
  4103. #[test]
  4104. fn test_closing_ack_fin() {
  4105. let mut s = socket_closing();
  4106. recv!(
  4107. s,
  4108. [TcpRepr {
  4109. seq_number: LOCAL_SEQ + 1 + 1,
  4110. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4111. ..RECV_TEMPL
  4112. }]
  4113. );
  4114. send!(s, time 1_000, TcpRepr {
  4115. seq_number: REMOTE_SEQ + 1 + 1,
  4116. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4117. ..SEND_TEMPL
  4118. });
  4119. assert_eq!(s.state, State::TimeWait);
  4120. sanity!(s, socket_time_wait(true));
  4121. }
  4122. #[test]
  4123. fn test_closing_close() {
  4124. let mut s = socket_closing();
  4125. s.close();
  4126. assert_eq!(s.state, State::Closing);
  4127. }
  4128. // =========================================================================================//
  4129. // Tests for the TIME-WAIT state.
  4130. // =========================================================================================//
  4131. #[test]
  4132. fn test_time_wait_from_fin_wait_2_ack() {
  4133. let mut s = socket_time_wait(false);
  4134. recv!(
  4135. s,
  4136. [TcpRepr {
  4137. seq_number: LOCAL_SEQ + 1 + 1,
  4138. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4139. ..RECV_TEMPL
  4140. }]
  4141. );
  4142. }
  4143. #[test]
  4144. fn test_time_wait_from_closing_no_ack() {
  4145. let mut s = socket_time_wait(true);
  4146. recv!(s, []);
  4147. }
  4148. #[test]
  4149. fn test_time_wait_close() {
  4150. let mut s = socket_time_wait(false);
  4151. s.close();
  4152. assert_eq!(s.state, State::TimeWait);
  4153. }
  4154. #[test]
  4155. fn test_time_wait_retransmit() {
  4156. let mut s = socket_time_wait(false);
  4157. recv!(
  4158. s,
  4159. [TcpRepr {
  4160. seq_number: LOCAL_SEQ + 1 + 1,
  4161. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4162. ..RECV_TEMPL
  4163. }]
  4164. );
  4165. send!(s, time 5_000, TcpRepr {
  4166. control: TcpControl::Fin,
  4167. seq_number: REMOTE_SEQ + 1,
  4168. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4169. ..SEND_TEMPL
  4170. }, Ok(Some(TcpRepr {
  4171. seq_number: LOCAL_SEQ + 1 + 1,
  4172. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4173. ..RECV_TEMPL
  4174. })));
  4175. assert_eq!(
  4176. s.timer,
  4177. Timer::Close {
  4178. expires_at: Instant::from_secs(5) + CLOSE_DELAY
  4179. }
  4180. );
  4181. }
  4182. #[test]
  4183. fn test_time_wait_timeout() {
  4184. let mut s = socket_time_wait(false);
  4185. recv!(
  4186. s,
  4187. [TcpRepr {
  4188. seq_number: LOCAL_SEQ + 1 + 1,
  4189. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4190. ..RECV_TEMPL
  4191. }]
  4192. );
  4193. assert_eq!(s.state, State::TimeWait);
  4194. recv!(s, time 60_000, Err(Error::Exhausted));
  4195. assert_eq!(s.state, State::Closed);
  4196. }
  4197. // =========================================================================================//
  4198. // Tests for the CLOSE-WAIT state.
  4199. // =========================================================================================//
  4200. #[test]
  4201. fn test_close_wait_ack() {
  4202. let mut s = socket_close_wait();
  4203. s.send_slice(b"abcdef").unwrap();
  4204. recv!(
  4205. s,
  4206. [TcpRepr {
  4207. seq_number: LOCAL_SEQ + 1,
  4208. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4209. payload: &b"abcdef"[..],
  4210. ..RECV_TEMPL
  4211. }]
  4212. );
  4213. send!(
  4214. s,
  4215. TcpRepr {
  4216. seq_number: REMOTE_SEQ + 1 + 1,
  4217. ack_number: Some(LOCAL_SEQ + 1 + 6),
  4218. ..SEND_TEMPL
  4219. }
  4220. );
  4221. }
  4222. #[test]
  4223. fn test_close_wait_close() {
  4224. let mut s = socket_close_wait();
  4225. s.close();
  4226. assert_eq!(s.state, State::LastAck);
  4227. sanity!(s, socket_last_ack());
  4228. }
  4229. // =========================================================================================//
  4230. // Tests for the LAST-ACK state.
  4231. // =========================================================================================//
  4232. #[test]
  4233. fn test_last_ack_fin_ack() {
  4234. let mut s = socket_last_ack();
  4235. recv!(
  4236. s,
  4237. [TcpRepr {
  4238. control: TcpControl::Fin,
  4239. seq_number: LOCAL_SEQ + 1,
  4240. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4241. ..RECV_TEMPL
  4242. }]
  4243. );
  4244. assert_eq!(s.state, State::LastAck);
  4245. send!(
  4246. s,
  4247. TcpRepr {
  4248. seq_number: REMOTE_SEQ + 1 + 1,
  4249. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4250. ..SEND_TEMPL
  4251. }
  4252. );
  4253. assert_eq!(s.state, State::Closed);
  4254. }
  4255. #[test]
  4256. fn test_last_ack_ack_not_of_fin() {
  4257. let mut s = socket_last_ack();
  4258. recv!(
  4259. s,
  4260. [TcpRepr {
  4261. control: TcpControl::Fin,
  4262. seq_number: LOCAL_SEQ + 1,
  4263. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4264. ..RECV_TEMPL
  4265. }]
  4266. );
  4267. assert_eq!(s.state, State::LastAck);
  4268. // ACK received that doesn't ack the FIN: socket should stay in LastAck.
  4269. send!(
  4270. s,
  4271. TcpRepr {
  4272. seq_number: REMOTE_SEQ + 1 + 1,
  4273. ack_number: Some(LOCAL_SEQ + 1),
  4274. ..SEND_TEMPL
  4275. }
  4276. );
  4277. assert_eq!(s.state, State::LastAck);
  4278. // ACK received of fin: socket should change to Closed.
  4279. send!(
  4280. s,
  4281. TcpRepr {
  4282. seq_number: REMOTE_SEQ + 1 + 1,
  4283. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4284. ..SEND_TEMPL
  4285. }
  4286. );
  4287. assert_eq!(s.state, State::Closed);
  4288. }
  4289. #[test]
  4290. fn test_last_ack_close() {
  4291. let mut s = socket_last_ack();
  4292. s.close();
  4293. assert_eq!(s.state, State::LastAck);
  4294. }
  4295. // =========================================================================================//
  4296. // Tests for transitioning through multiple states.
  4297. // =========================================================================================//
  4298. #[test]
  4299. fn test_listen() {
  4300. let mut s = socket();
  4301. s.listen(IpEndpoint::new(IpAddress::default(), LOCAL_PORT))
  4302. .unwrap();
  4303. assert_eq!(s.state, State::Listen);
  4304. }
  4305. #[test]
  4306. fn test_three_way_handshake() {
  4307. let mut s = socket_listen();
  4308. send!(
  4309. s,
  4310. TcpRepr {
  4311. control: TcpControl::Syn,
  4312. seq_number: REMOTE_SEQ,
  4313. ack_number: None,
  4314. ..SEND_TEMPL
  4315. }
  4316. );
  4317. assert_eq!(s.state(), State::SynReceived);
  4318. assert_eq!(s.local_endpoint(), LOCAL_END);
  4319. assert_eq!(s.remote_endpoint(), REMOTE_END);
  4320. recv!(
  4321. s,
  4322. [TcpRepr {
  4323. control: TcpControl::Syn,
  4324. seq_number: LOCAL_SEQ,
  4325. ack_number: Some(REMOTE_SEQ + 1),
  4326. max_seg_size: Some(BASE_MSS),
  4327. ..RECV_TEMPL
  4328. }]
  4329. );
  4330. send!(
  4331. s,
  4332. TcpRepr {
  4333. seq_number: REMOTE_SEQ + 1,
  4334. ack_number: Some(LOCAL_SEQ + 1),
  4335. ..SEND_TEMPL
  4336. }
  4337. );
  4338. assert_eq!(s.state(), State::Established);
  4339. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  4340. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  4341. }
  4342. #[test]
  4343. fn test_remote_close() {
  4344. let mut s = socket_established();
  4345. send!(
  4346. s,
  4347. TcpRepr {
  4348. control: TcpControl::Fin,
  4349. seq_number: REMOTE_SEQ + 1,
  4350. ack_number: Some(LOCAL_SEQ + 1),
  4351. ..SEND_TEMPL
  4352. }
  4353. );
  4354. assert_eq!(s.state, State::CloseWait);
  4355. recv!(
  4356. s,
  4357. [TcpRepr {
  4358. seq_number: LOCAL_SEQ + 1,
  4359. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4360. ..RECV_TEMPL
  4361. }]
  4362. );
  4363. s.close();
  4364. assert_eq!(s.state, State::LastAck);
  4365. recv!(
  4366. s,
  4367. [TcpRepr {
  4368. control: TcpControl::Fin,
  4369. seq_number: LOCAL_SEQ + 1,
  4370. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4371. ..RECV_TEMPL
  4372. }]
  4373. );
  4374. send!(
  4375. s,
  4376. TcpRepr {
  4377. seq_number: REMOTE_SEQ + 1 + 1,
  4378. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4379. ..SEND_TEMPL
  4380. }
  4381. );
  4382. assert_eq!(s.state, State::Closed);
  4383. }
  4384. #[test]
  4385. fn test_local_close() {
  4386. let mut s = socket_established();
  4387. s.close();
  4388. assert_eq!(s.state, State::FinWait1);
  4389. recv!(
  4390. s,
  4391. [TcpRepr {
  4392. control: TcpControl::Fin,
  4393. seq_number: LOCAL_SEQ + 1,
  4394. ack_number: Some(REMOTE_SEQ + 1),
  4395. ..RECV_TEMPL
  4396. }]
  4397. );
  4398. send!(
  4399. s,
  4400. TcpRepr {
  4401. seq_number: REMOTE_SEQ + 1,
  4402. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4403. ..SEND_TEMPL
  4404. }
  4405. );
  4406. assert_eq!(s.state, State::FinWait2);
  4407. send!(
  4408. s,
  4409. TcpRepr {
  4410. control: TcpControl::Fin,
  4411. seq_number: REMOTE_SEQ + 1,
  4412. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4413. ..SEND_TEMPL
  4414. }
  4415. );
  4416. assert_eq!(s.state, State::TimeWait);
  4417. recv!(
  4418. s,
  4419. [TcpRepr {
  4420. seq_number: LOCAL_SEQ + 1 + 1,
  4421. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4422. ..RECV_TEMPL
  4423. }]
  4424. );
  4425. }
  4426. #[test]
  4427. fn test_simultaneous_close() {
  4428. let mut s = socket_established();
  4429. s.close();
  4430. assert_eq!(s.state, State::FinWait1);
  4431. recv!(
  4432. s,
  4433. [TcpRepr {
  4434. // due to reordering, this is logically located...
  4435. control: TcpControl::Fin,
  4436. seq_number: LOCAL_SEQ + 1,
  4437. ack_number: Some(REMOTE_SEQ + 1),
  4438. ..RECV_TEMPL
  4439. }]
  4440. );
  4441. send!(
  4442. s,
  4443. TcpRepr {
  4444. control: TcpControl::Fin,
  4445. seq_number: REMOTE_SEQ + 1,
  4446. ack_number: Some(LOCAL_SEQ + 1),
  4447. ..SEND_TEMPL
  4448. }
  4449. );
  4450. assert_eq!(s.state, State::Closing);
  4451. recv!(
  4452. s,
  4453. [TcpRepr {
  4454. seq_number: LOCAL_SEQ + 1 + 1,
  4455. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4456. ..RECV_TEMPL
  4457. }]
  4458. );
  4459. // ... at this point
  4460. send!(
  4461. s,
  4462. TcpRepr {
  4463. seq_number: REMOTE_SEQ + 1 + 1,
  4464. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4465. ..SEND_TEMPL
  4466. }
  4467. );
  4468. assert_eq!(s.state, State::TimeWait);
  4469. recv!(s, []);
  4470. }
  4471. #[test]
  4472. fn test_simultaneous_close_combined_fin_ack() {
  4473. let mut s = socket_established();
  4474. s.close();
  4475. assert_eq!(s.state, State::FinWait1);
  4476. recv!(
  4477. s,
  4478. [TcpRepr {
  4479. control: TcpControl::Fin,
  4480. seq_number: LOCAL_SEQ + 1,
  4481. ack_number: Some(REMOTE_SEQ + 1),
  4482. ..RECV_TEMPL
  4483. }]
  4484. );
  4485. send!(
  4486. s,
  4487. TcpRepr {
  4488. control: TcpControl::Fin,
  4489. seq_number: REMOTE_SEQ + 1,
  4490. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4491. ..SEND_TEMPL
  4492. }
  4493. );
  4494. assert_eq!(s.state, State::TimeWait);
  4495. recv!(
  4496. s,
  4497. [TcpRepr {
  4498. seq_number: LOCAL_SEQ + 1 + 1,
  4499. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4500. ..RECV_TEMPL
  4501. }]
  4502. );
  4503. }
  4504. #[test]
  4505. fn test_simultaneous_close_raced() {
  4506. let mut s = socket_established();
  4507. s.close();
  4508. assert_eq!(s.state, State::FinWait1);
  4509. // Socket receives FIN before it has a chance to send its own FIN
  4510. send!(
  4511. s,
  4512. TcpRepr {
  4513. control: TcpControl::Fin,
  4514. seq_number: REMOTE_SEQ + 1,
  4515. ack_number: Some(LOCAL_SEQ + 1),
  4516. ..SEND_TEMPL
  4517. }
  4518. );
  4519. assert_eq!(s.state, State::Closing);
  4520. // FIN + ack-of-FIN
  4521. recv!(
  4522. s,
  4523. [TcpRepr {
  4524. control: TcpControl::Fin,
  4525. seq_number: LOCAL_SEQ + 1,
  4526. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4527. ..RECV_TEMPL
  4528. }]
  4529. );
  4530. assert_eq!(s.state, State::Closing);
  4531. send!(
  4532. s,
  4533. TcpRepr {
  4534. seq_number: REMOTE_SEQ + 1 + 1,
  4535. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4536. ..SEND_TEMPL
  4537. }
  4538. );
  4539. assert_eq!(s.state, State::TimeWait);
  4540. recv!(s, []);
  4541. }
  4542. #[test]
  4543. fn test_simultaneous_close_raced_with_data() {
  4544. let mut s = socket_established();
  4545. s.send_slice(b"abcdef").unwrap();
  4546. s.close();
  4547. assert_eq!(s.state, State::FinWait1);
  4548. // Socket receives FIN before it has a chance to send its own data+FIN
  4549. send!(
  4550. s,
  4551. TcpRepr {
  4552. control: TcpControl::Fin,
  4553. seq_number: REMOTE_SEQ + 1,
  4554. ack_number: Some(LOCAL_SEQ + 1),
  4555. ..SEND_TEMPL
  4556. }
  4557. );
  4558. assert_eq!(s.state, State::Closing);
  4559. // data + FIN + ack-of-FIN
  4560. recv!(
  4561. s,
  4562. [TcpRepr {
  4563. control: TcpControl::Fin,
  4564. seq_number: LOCAL_SEQ + 1,
  4565. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4566. payload: &b"abcdef"[..],
  4567. ..RECV_TEMPL
  4568. }]
  4569. );
  4570. assert_eq!(s.state, State::Closing);
  4571. send!(
  4572. s,
  4573. TcpRepr {
  4574. seq_number: REMOTE_SEQ + 1 + 1,
  4575. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  4576. ..SEND_TEMPL
  4577. }
  4578. );
  4579. assert_eq!(s.state, State::TimeWait);
  4580. recv!(s, []);
  4581. }
  4582. #[test]
  4583. fn test_fin_with_data() {
  4584. let mut s = socket_established();
  4585. s.send_slice(b"abcdef").unwrap();
  4586. s.close();
  4587. recv!(
  4588. s,
  4589. [TcpRepr {
  4590. control: TcpControl::Fin,
  4591. seq_number: LOCAL_SEQ + 1,
  4592. ack_number: Some(REMOTE_SEQ + 1),
  4593. payload: &b"abcdef"[..],
  4594. ..RECV_TEMPL
  4595. }]
  4596. )
  4597. }
  4598. #[test]
  4599. fn test_mutual_close_with_data_1() {
  4600. let mut s = socket_established();
  4601. s.send_slice(b"abcdef").unwrap();
  4602. s.close();
  4603. assert_eq!(s.state, State::FinWait1);
  4604. recv!(
  4605. s,
  4606. [TcpRepr {
  4607. control: TcpControl::Fin,
  4608. seq_number: LOCAL_SEQ + 1,
  4609. ack_number: Some(REMOTE_SEQ + 1),
  4610. payload: &b"abcdef"[..],
  4611. ..RECV_TEMPL
  4612. }]
  4613. );
  4614. send!(
  4615. s,
  4616. TcpRepr {
  4617. control: TcpControl::Fin,
  4618. seq_number: REMOTE_SEQ + 1,
  4619. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  4620. ..SEND_TEMPL
  4621. }
  4622. );
  4623. }
  4624. #[test]
  4625. fn test_mutual_close_with_data_2() {
  4626. let mut s = socket_established();
  4627. s.send_slice(b"abcdef").unwrap();
  4628. s.close();
  4629. assert_eq!(s.state, State::FinWait1);
  4630. recv!(
  4631. s,
  4632. [TcpRepr {
  4633. control: TcpControl::Fin,
  4634. seq_number: LOCAL_SEQ + 1,
  4635. ack_number: Some(REMOTE_SEQ + 1),
  4636. payload: &b"abcdef"[..],
  4637. ..RECV_TEMPL
  4638. }]
  4639. );
  4640. send!(
  4641. s,
  4642. TcpRepr {
  4643. seq_number: REMOTE_SEQ + 1,
  4644. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  4645. ..SEND_TEMPL
  4646. }
  4647. );
  4648. assert_eq!(s.state, State::FinWait2);
  4649. send!(
  4650. s,
  4651. TcpRepr {
  4652. control: TcpControl::Fin,
  4653. seq_number: REMOTE_SEQ + 1,
  4654. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  4655. ..SEND_TEMPL
  4656. }
  4657. );
  4658. recv!(
  4659. s,
  4660. [TcpRepr {
  4661. seq_number: LOCAL_SEQ + 1 + 6 + 1,
  4662. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4663. ..RECV_TEMPL
  4664. }]
  4665. );
  4666. assert_eq!(s.state, State::TimeWait);
  4667. }
  4668. // =========================================================================================//
  4669. // Tests for retransmission on packet loss.
  4670. // =========================================================================================//
  4671. #[test]
  4672. fn test_duplicate_seq_ack() {
  4673. let mut s = socket_recved();
  4674. // remote retransmission
  4675. send!(
  4676. s,
  4677. TcpRepr {
  4678. seq_number: REMOTE_SEQ + 1,
  4679. ack_number: Some(LOCAL_SEQ + 1),
  4680. payload: &b"abcdef"[..],
  4681. ..SEND_TEMPL
  4682. },
  4683. Ok(Some(TcpRepr {
  4684. seq_number: LOCAL_SEQ + 1,
  4685. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4686. window_len: 58,
  4687. ..RECV_TEMPL
  4688. }))
  4689. );
  4690. }
  4691. #[test]
  4692. fn test_data_retransmit() {
  4693. let mut s = socket_established();
  4694. s.send_slice(b"abcdef").unwrap();
  4695. recv!(s, time 1000, Ok(TcpRepr {
  4696. seq_number: LOCAL_SEQ + 1,
  4697. ack_number: Some(REMOTE_SEQ + 1),
  4698. payload: &b"abcdef"[..],
  4699. ..RECV_TEMPL
  4700. }));
  4701. recv!(s, time 1050, Err(Error::Exhausted));
  4702. recv!(s, time 2000, Ok(TcpRepr {
  4703. seq_number: LOCAL_SEQ + 1,
  4704. ack_number: Some(REMOTE_SEQ + 1),
  4705. payload: &b"abcdef"[..],
  4706. ..RECV_TEMPL
  4707. }));
  4708. }
  4709. #[test]
  4710. fn test_data_retransmit_bursts() {
  4711. let mut s = socket_established();
  4712. s.remote_mss = 6;
  4713. s.send_slice(b"abcdef012345").unwrap();
  4714. recv!(s, time 0, Ok(TcpRepr {
  4715. control: TcpControl::None,
  4716. seq_number: LOCAL_SEQ + 1,
  4717. ack_number: Some(REMOTE_SEQ + 1),
  4718. payload: &b"abcdef"[..],
  4719. ..RECV_TEMPL
  4720. }), exact);
  4721. recv!(s, time 0, Ok(TcpRepr {
  4722. control: TcpControl::Psh,
  4723. seq_number: LOCAL_SEQ + 1 + 6,
  4724. ack_number: Some(REMOTE_SEQ + 1),
  4725. payload: &b"012345"[..],
  4726. ..RECV_TEMPL
  4727. }), exact);
  4728. recv!(s, time 0, Err(Error::Exhausted));
  4729. recv!(s, time 50, Err(Error::Exhausted));
  4730. recv!(s, time 1000, Ok(TcpRepr {
  4731. control: TcpControl::None,
  4732. seq_number: LOCAL_SEQ + 1,
  4733. ack_number: Some(REMOTE_SEQ + 1),
  4734. payload: &b"abcdef"[..],
  4735. ..RECV_TEMPL
  4736. }), exact);
  4737. recv!(s, time 1500, Ok(TcpRepr {
  4738. control: TcpControl::Psh,
  4739. seq_number: LOCAL_SEQ + 1 + 6,
  4740. ack_number: Some(REMOTE_SEQ + 1),
  4741. payload: &b"012345"[..],
  4742. ..RECV_TEMPL
  4743. }), exact);
  4744. recv!(s, time 1550, Err(Error::Exhausted));
  4745. }
  4746. #[test]
  4747. fn test_send_data_after_syn_ack_retransmit() {
  4748. let mut s = socket_syn_received();
  4749. recv!(s, time 50, Ok(TcpRepr {
  4750. control: TcpControl::Syn,
  4751. seq_number: LOCAL_SEQ,
  4752. ack_number: Some(REMOTE_SEQ + 1),
  4753. max_seg_size: Some(BASE_MSS),
  4754. ..RECV_TEMPL
  4755. }));
  4756. recv!(s, time 750, Ok(TcpRepr { // retransmit
  4757. control: TcpControl::Syn,
  4758. seq_number: LOCAL_SEQ,
  4759. ack_number: Some(REMOTE_SEQ + 1),
  4760. max_seg_size: Some(BASE_MSS),
  4761. ..RECV_TEMPL
  4762. }));
  4763. send!(
  4764. s,
  4765. TcpRepr {
  4766. seq_number: REMOTE_SEQ + 1,
  4767. ack_number: Some(LOCAL_SEQ + 1),
  4768. ..SEND_TEMPL
  4769. }
  4770. );
  4771. assert_eq!(s.state(), State::Established);
  4772. s.send_slice(b"abcdef").unwrap();
  4773. recv!(
  4774. s,
  4775. [TcpRepr {
  4776. seq_number: LOCAL_SEQ + 1,
  4777. ack_number: Some(REMOTE_SEQ + 1),
  4778. payload: &b"abcdef"[..],
  4779. ..RECV_TEMPL
  4780. }]
  4781. )
  4782. }
  4783. #[test]
  4784. fn test_established_retransmit_for_dup_ack() {
  4785. let mut s = socket_established();
  4786. // Duplicate ACKs do not replace the retransmission timer
  4787. s.send_slice(b"abc").unwrap();
  4788. recv!(s, time 1000, Ok(TcpRepr {
  4789. seq_number: LOCAL_SEQ + 1,
  4790. ack_number: Some(REMOTE_SEQ + 1),
  4791. payload: &b"abc"[..],
  4792. ..RECV_TEMPL
  4793. }));
  4794. // Retransmit timer is on because all data was sent
  4795. assert_eq!(s.tx_buffer.len(), 3);
  4796. // ACK nothing new
  4797. send!(
  4798. s,
  4799. TcpRepr {
  4800. seq_number: REMOTE_SEQ + 1,
  4801. ack_number: Some(LOCAL_SEQ + 1),
  4802. ..SEND_TEMPL
  4803. }
  4804. );
  4805. // Retransmit
  4806. recv!(s, time 4000, Ok(TcpRepr {
  4807. seq_number: LOCAL_SEQ + 1,
  4808. ack_number: Some(REMOTE_SEQ + 1),
  4809. payload: &b"abc"[..],
  4810. ..RECV_TEMPL
  4811. }));
  4812. }
  4813. #[test]
  4814. fn test_established_retransmit_reset_after_ack() {
  4815. let mut s = socket_established();
  4816. s.remote_win_len = 6;
  4817. s.send_slice(b"abcdef").unwrap();
  4818. s.send_slice(b"123456").unwrap();
  4819. s.send_slice(b"ABCDEF").unwrap();
  4820. recv!(s, time 1000, Ok(TcpRepr {
  4821. seq_number: LOCAL_SEQ + 1,
  4822. ack_number: Some(REMOTE_SEQ + 1),
  4823. payload: &b"abcdef"[..],
  4824. ..RECV_TEMPL
  4825. }));
  4826. send!(s, time 1005, TcpRepr {
  4827. seq_number: REMOTE_SEQ + 1,
  4828. ack_number: Some(LOCAL_SEQ + 1 + 6),
  4829. window_len: 6,
  4830. ..SEND_TEMPL
  4831. });
  4832. recv!(s, time 1010, Ok(TcpRepr {
  4833. seq_number: LOCAL_SEQ + 1 + 6,
  4834. ack_number: Some(REMOTE_SEQ + 1),
  4835. payload: &b"123456"[..],
  4836. ..RECV_TEMPL
  4837. }));
  4838. send!(s, time 1015, TcpRepr {
  4839. seq_number: REMOTE_SEQ + 1,
  4840. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  4841. window_len: 6,
  4842. ..SEND_TEMPL
  4843. });
  4844. recv!(s, time 1020, Ok(TcpRepr {
  4845. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4846. ack_number: Some(REMOTE_SEQ + 1),
  4847. payload: &b"ABCDEF"[..],
  4848. ..RECV_TEMPL
  4849. }));
  4850. }
  4851. #[test]
  4852. fn test_established_queue_during_retransmission() {
  4853. let mut s = socket_established();
  4854. s.remote_mss = 6;
  4855. s.send_slice(b"abcdef123456ABCDEF").unwrap();
  4856. recv!(s, time 1000, Ok(TcpRepr {
  4857. seq_number: LOCAL_SEQ + 1,
  4858. ack_number: Some(REMOTE_SEQ + 1),
  4859. payload: &b"abcdef"[..],
  4860. ..RECV_TEMPL
  4861. })); // this one is dropped
  4862. recv!(s, time 1005, Ok(TcpRepr {
  4863. seq_number: LOCAL_SEQ + 1 + 6,
  4864. ack_number: Some(REMOTE_SEQ + 1),
  4865. payload: &b"123456"[..],
  4866. ..RECV_TEMPL
  4867. })); // this one is received
  4868. recv!(s, time 1010, Ok(TcpRepr {
  4869. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4870. ack_number: Some(REMOTE_SEQ + 1),
  4871. payload: &b"ABCDEF"[..],
  4872. ..RECV_TEMPL
  4873. })); // also dropped
  4874. recv!(s, time 2000, Ok(TcpRepr {
  4875. seq_number: LOCAL_SEQ + 1,
  4876. ack_number: Some(REMOTE_SEQ + 1),
  4877. payload: &b"abcdef"[..],
  4878. ..RECV_TEMPL
  4879. })); // retransmission
  4880. send!(s, time 2005, TcpRepr {
  4881. seq_number: REMOTE_SEQ + 1,
  4882. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  4883. ..SEND_TEMPL
  4884. }); // acknowledgement of both segments
  4885. recv!(s, time 2010, Ok(TcpRepr {
  4886. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4887. ack_number: Some(REMOTE_SEQ + 1),
  4888. payload: &b"ABCDEF"[..],
  4889. ..RECV_TEMPL
  4890. })); // retransmission of only unacknowledged data
  4891. }
  4892. #[test]
  4893. fn test_close_wait_retransmit_reset_after_ack() {
  4894. let mut s = socket_close_wait();
  4895. s.remote_win_len = 6;
  4896. s.send_slice(b"abcdef").unwrap();
  4897. s.send_slice(b"123456").unwrap();
  4898. s.send_slice(b"ABCDEF").unwrap();
  4899. recv!(s, time 1000, Ok(TcpRepr {
  4900. seq_number: LOCAL_SEQ + 1,
  4901. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4902. payload: &b"abcdef"[..],
  4903. ..RECV_TEMPL
  4904. }));
  4905. send!(s, time 1005, TcpRepr {
  4906. seq_number: REMOTE_SEQ + 1 + 1,
  4907. ack_number: Some(LOCAL_SEQ + 1 + 6),
  4908. window_len: 6,
  4909. ..SEND_TEMPL
  4910. });
  4911. recv!(s, time 1010, Ok(TcpRepr {
  4912. seq_number: LOCAL_SEQ + 1 + 6,
  4913. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4914. payload: &b"123456"[..],
  4915. ..RECV_TEMPL
  4916. }));
  4917. send!(s, time 1015, TcpRepr {
  4918. seq_number: REMOTE_SEQ + 1 + 1,
  4919. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  4920. window_len: 6,
  4921. ..SEND_TEMPL
  4922. });
  4923. recv!(s, time 1020, Ok(TcpRepr {
  4924. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4925. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4926. payload: &b"ABCDEF"[..],
  4927. ..RECV_TEMPL
  4928. }));
  4929. }
  4930. #[test]
  4931. fn test_fin_wait_1_retransmit_reset_after_ack() {
  4932. let mut s = socket_established();
  4933. s.remote_win_len = 6;
  4934. s.send_slice(b"abcdef").unwrap();
  4935. s.send_slice(b"123456").unwrap();
  4936. s.send_slice(b"ABCDEF").unwrap();
  4937. s.close();
  4938. recv!(s, time 1000, Ok(TcpRepr {
  4939. seq_number: LOCAL_SEQ + 1,
  4940. ack_number: Some(REMOTE_SEQ + 1),
  4941. payload: &b"abcdef"[..],
  4942. ..RECV_TEMPL
  4943. }));
  4944. send!(s, time 1005, TcpRepr {
  4945. seq_number: REMOTE_SEQ + 1,
  4946. ack_number: Some(LOCAL_SEQ + 1 + 6),
  4947. window_len: 6,
  4948. ..SEND_TEMPL
  4949. });
  4950. recv!(s, time 1010, Ok(TcpRepr {
  4951. seq_number: LOCAL_SEQ + 1 + 6,
  4952. ack_number: Some(REMOTE_SEQ + 1),
  4953. payload: &b"123456"[..],
  4954. ..RECV_TEMPL
  4955. }));
  4956. send!(s, time 1015, TcpRepr {
  4957. seq_number: REMOTE_SEQ + 1,
  4958. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  4959. window_len: 6,
  4960. ..SEND_TEMPL
  4961. });
  4962. recv!(s, time 1020, Ok(TcpRepr {
  4963. control: TcpControl::Fin,
  4964. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4965. ack_number: Some(REMOTE_SEQ + 1),
  4966. payload: &b"ABCDEF"[..],
  4967. ..RECV_TEMPL
  4968. }));
  4969. }
  4970. #[test]
  4971. fn test_fast_retransmit_after_triple_duplicate_ack() {
  4972. let mut s = socket_established();
  4973. s.remote_mss = 6;
  4974. // Normal ACK of previously recived segment
  4975. send!(s, time 0, TcpRepr {
  4976. seq_number: REMOTE_SEQ + 1,
  4977. ack_number: Some(LOCAL_SEQ + 1),
  4978. ..SEND_TEMPL
  4979. });
  4980. // Send a long string of text divided into several packets
  4981. // because of previously recieved "window_len"
  4982. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  4983. // This packet is lost
  4984. recv!(s, time 1000, Ok(TcpRepr {
  4985. seq_number: LOCAL_SEQ + 1,
  4986. ack_number: Some(REMOTE_SEQ + 1),
  4987. payload: &b"xxxxxx"[..],
  4988. ..RECV_TEMPL
  4989. }));
  4990. recv!(s, time 1005, Ok(TcpRepr {
  4991. seq_number: LOCAL_SEQ + 1 + 6,
  4992. ack_number: Some(REMOTE_SEQ + 1),
  4993. payload: &b"yyyyyy"[..],
  4994. ..RECV_TEMPL
  4995. }));
  4996. recv!(s, time 1010, Ok(TcpRepr {
  4997. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  4998. ack_number: Some(REMOTE_SEQ + 1),
  4999. payload: &b"wwwwww"[..],
  5000. ..RECV_TEMPL
  5001. }));
  5002. recv!(s, time 1015, Ok(TcpRepr {
  5003. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  5004. ack_number: Some(REMOTE_SEQ + 1),
  5005. payload: &b"zzzzzz"[..],
  5006. ..RECV_TEMPL
  5007. }));
  5008. // First duplicate ACK
  5009. send!(s, time 1050, TcpRepr {
  5010. seq_number: REMOTE_SEQ + 1,
  5011. ack_number: Some(LOCAL_SEQ + 1),
  5012. ..SEND_TEMPL
  5013. });
  5014. // Second duplicate ACK
  5015. send!(s, time 1055, TcpRepr {
  5016. seq_number: REMOTE_SEQ + 1,
  5017. ack_number: Some(LOCAL_SEQ + 1),
  5018. ..SEND_TEMPL
  5019. });
  5020. // Third duplicate ACK
  5021. // Should trigger a fast retransmit of dropped packet
  5022. send!(s, time 1060, TcpRepr {
  5023. seq_number: REMOTE_SEQ + 1,
  5024. ack_number: Some(LOCAL_SEQ + 1),
  5025. ..SEND_TEMPL
  5026. });
  5027. // Fast retransmit packet
  5028. recv!(s, time 1100, Ok(TcpRepr {
  5029. seq_number: LOCAL_SEQ + 1,
  5030. ack_number: Some(REMOTE_SEQ + 1),
  5031. payload: &b"xxxxxx"[..],
  5032. ..RECV_TEMPL
  5033. }));
  5034. recv!(s, time 1105, Ok(TcpRepr {
  5035. seq_number: LOCAL_SEQ + 1 + 6,
  5036. ack_number: Some(REMOTE_SEQ + 1),
  5037. payload: &b"yyyyyy"[..],
  5038. ..RECV_TEMPL
  5039. }));
  5040. recv!(s, time 1110, Ok(TcpRepr {
  5041. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  5042. ack_number: Some(REMOTE_SEQ + 1),
  5043. payload: &b"wwwwww"[..],
  5044. ..RECV_TEMPL
  5045. }));
  5046. recv!(s, time 1115, Ok(TcpRepr {
  5047. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  5048. ack_number: Some(REMOTE_SEQ + 1),
  5049. payload: &b"zzzzzz"[..],
  5050. ..RECV_TEMPL
  5051. }));
  5052. // After all was send out, enter *normal* retransmission,
  5053. // don't stay in fast retransmission.
  5054. assert!(match s.timer {
  5055. Timer::Retransmit { expires_at, .. } => expires_at > Instant::from_millis(1115),
  5056. _ => false,
  5057. });
  5058. // ACK all recived segments
  5059. send!(s, time 1120, TcpRepr {
  5060. seq_number: REMOTE_SEQ + 1,
  5061. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  5062. ..SEND_TEMPL
  5063. });
  5064. }
  5065. #[test]
  5066. fn test_fast_retransmit_duplicate_detection_with_data() {
  5067. let mut s = socket_established();
  5068. s.send_slice(b"abc").unwrap(); // This is lost
  5069. recv!(s, time 1000, Ok(TcpRepr {
  5070. seq_number: LOCAL_SEQ + 1,
  5071. ack_number: Some(REMOTE_SEQ + 1),
  5072. payload: &b"abc"[..],
  5073. ..RECV_TEMPL
  5074. }));
  5075. // Normal ACK of previously recieved segment
  5076. send!(
  5077. s,
  5078. TcpRepr {
  5079. seq_number: REMOTE_SEQ + 1,
  5080. ack_number: Some(LOCAL_SEQ + 1),
  5081. ..SEND_TEMPL
  5082. }
  5083. );
  5084. // First duplicate
  5085. send!(
  5086. s,
  5087. TcpRepr {
  5088. seq_number: REMOTE_SEQ + 1,
  5089. ack_number: Some(LOCAL_SEQ + 1),
  5090. ..SEND_TEMPL
  5091. }
  5092. );
  5093. // Second duplicate
  5094. send!(
  5095. s,
  5096. TcpRepr {
  5097. seq_number: REMOTE_SEQ + 1,
  5098. ack_number: Some(LOCAL_SEQ + 1),
  5099. ..SEND_TEMPL
  5100. }
  5101. );
  5102. assert_eq!(s.local_rx_dup_acks, 2, "duplicate ACK counter is not set");
  5103. // This packet has content, hence should not be detected
  5104. // as a duplicate ACK and should reset the duplicate ACK count
  5105. send!(
  5106. s,
  5107. TcpRepr {
  5108. seq_number: REMOTE_SEQ + 1,
  5109. ack_number: Some(LOCAL_SEQ + 1),
  5110. payload: &b"xxxxxx"[..],
  5111. ..SEND_TEMPL
  5112. }
  5113. );
  5114. recv!(
  5115. s,
  5116. [TcpRepr {
  5117. seq_number: LOCAL_SEQ + 1 + 3,
  5118. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5119. window_len: 58,
  5120. ..RECV_TEMPL
  5121. }]
  5122. );
  5123. assert_eq!(
  5124. s.local_rx_dup_acks, 0,
  5125. "duplicate ACK counter is not reset when reciving data"
  5126. );
  5127. }
  5128. #[test]
  5129. fn test_fast_retransmit_duplicate_detection() {
  5130. let mut s = socket_established();
  5131. s.remote_mss = 6;
  5132. // Normal ACK of previously recived segment
  5133. send!(s, time 0, TcpRepr {
  5134. seq_number: REMOTE_SEQ + 1,
  5135. ack_number: Some(LOCAL_SEQ + 1),
  5136. ..SEND_TEMPL
  5137. });
  5138. // First duplicate, should not be counted as there is nothing to resend
  5139. send!(s, time 0, TcpRepr {
  5140. seq_number: REMOTE_SEQ + 1,
  5141. ack_number: Some(LOCAL_SEQ + 1),
  5142. ..SEND_TEMPL
  5143. });
  5144. assert_eq!(
  5145. s.local_rx_dup_acks, 0,
  5146. "duplicate ACK counter is set but wound not transmit data"
  5147. );
  5148. // Send a long string of text divided into several packets
  5149. // because of small remote_mss
  5150. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  5151. // This packet is reordered in network
  5152. recv!(s, time 1000, Ok(TcpRepr {
  5153. seq_number: LOCAL_SEQ + 1,
  5154. ack_number: Some(REMOTE_SEQ + 1),
  5155. payload: &b"xxxxxx"[..],
  5156. ..RECV_TEMPL
  5157. }));
  5158. recv!(s, time 1005, Ok(TcpRepr {
  5159. seq_number: LOCAL_SEQ + 1 + 6,
  5160. ack_number: Some(REMOTE_SEQ + 1),
  5161. payload: &b"yyyyyy"[..],
  5162. ..RECV_TEMPL
  5163. }));
  5164. recv!(s, time 1010, Ok(TcpRepr {
  5165. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  5166. ack_number: Some(REMOTE_SEQ + 1),
  5167. payload: &b"wwwwww"[..],
  5168. ..RECV_TEMPL
  5169. }));
  5170. recv!(s, time 1015, Ok(TcpRepr {
  5171. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  5172. ack_number: Some(REMOTE_SEQ + 1),
  5173. payload: &b"zzzzzz"[..],
  5174. ..RECV_TEMPL
  5175. }));
  5176. // First duplicate ACK
  5177. send!(s, time 1050, TcpRepr {
  5178. seq_number: REMOTE_SEQ + 1,
  5179. ack_number: Some(LOCAL_SEQ + 1),
  5180. ..SEND_TEMPL
  5181. });
  5182. // Second duplicate ACK
  5183. send!(s, time 1055, TcpRepr {
  5184. seq_number: REMOTE_SEQ + 1,
  5185. ack_number: Some(LOCAL_SEQ + 1),
  5186. ..SEND_TEMPL
  5187. });
  5188. // Reordered packet arrives which should reset duplicate ACK count
  5189. send!(s, time 1060, TcpRepr {
  5190. seq_number: REMOTE_SEQ + 1,
  5191. ack_number: Some(LOCAL_SEQ + 1 + (6 * 3)),
  5192. ..SEND_TEMPL
  5193. });
  5194. assert_eq!(
  5195. s.local_rx_dup_acks, 0,
  5196. "duplicate ACK counter is not reset when reciving ACK which updates send window"
  5197. );
  5198. // ACK all recived segments
  5199. send!(s, time 1120, TcpRepr {
  5200. seq_number: REMOTE_SEQ + 1,
  5201. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  5202. ..SEND_TEMPL
  5203. });
  5204. }
  5205. #[test]
  5206. fn test_fast_retransmit_dup_acks_counter() {
  5207. let mut s = socket_established();
  5208. s.send_slice(b"abc").unwrap(); // This is lost
  5209. recv!(s, time 0, Ok(TcpRepr {
  5210. seq_number: LOCAL_SEQ + 1,
  5211. ack_number: Some(REMOTE_SEQ + 1),
  5212. payload: &b"abc"[..],
  5213. ..RECV_TEMPL
  5214. }));
  5215. send!(s, time 0, TcpRepr {
  5216. seq_number: REMOTE_SEQ + 1,
  5217. ack_number: Some(LOCAL_SEQ + 1),
  5218. ..SEND_TEMPL
  5219. });
  5220. // A lot of retransmits happen here
  5221. s.local_rx_dup_acks = u8::max_value() - 1;
  5222. // Send 3 more ACKs, which could overflow local_rx_dup_acks,
  5223. // but intended behaviour is that we saturate the bounds
  5224. // of local_rx_dup_acks
  5225. send!(s, time 0, TcpRepr {
  5226. seq_number: REMOTE_SEQ + 1,
  5227. ack_number: Some(LOCAL_SEQ + 1),
  5228. ..SEND_TEMPL
  5229. });
  5230. send!(s, time 0, TcpRepr {
  5231. seq_number: REMOTE_SEQ + 1,
  5232. ack_number: Some(LOCAL_SEQ + 1),
  5233. ..SEND_TEMPL
  5234. });
  5235. send!(s, time 0, TcpRepr {
  5236. seq_number: REMOTE_SEQ + 1,
  5237. ack_number: Some(LOCAL_SEQ + 1),
  5238. ..SEND_TEMPL
  5239. });
  5240. assert_eq!(
  5241. s.local_rx_dup_acks,
  5242. u8::max_value(),
  5243. "duplicate ACK count should not overflow but saturate"
  5244. );
  5245. }
  5246. #[test]
  5247. fn test_fast_retransmit_zero_window() {
  5248. let mut s = socket_established();
  5249. send!(s, time 1000, TcpRepr {
  5250. seq_number: REMOTE_SEQ + 1,
  5251. ack_number: Some(LOCAL_SEQ + 1),
  5252. ..SEND_TEMPL
  5253. });
  5254. s.send_slice(b"abc").unwrap();
  5255. recv!(s, time 0, Ok(TcpRepr {
  5256. seq_number: LOCAL_SEQ + 1,
  5257. ack_number: Some(REMOTE_SEQ + 1),
  5258. payload: &b"abc"[..],
  5259. ..RECV_TEMPL
  5260. }));
  5261. // 3 dup acks
  5262. send!(s, time 1050, TcpRepr {
  5263. seq_number: REMOTE_SEQ + 1,
  5264. ack_number: Some(LOCAL_SEQ + 1),
  5265. ..SEND_TEMPL
  5266. });
  5267. send!(s, time 1050, TcpRepr {
  5268. seq_number: REMOTE_SEQ + 1,
  5269. ack_number: Some(LOCAL_SEQ + 1),
  5270. ..SEND_TEMPL
  5271. });
  5272. send!(s, time 1050, TcpRepr {
  5273. seq_number: REMOTE_SEQ + 1,
  5274. ack_number: Some(LOCAL_SEQ + 1),
  5275. window_len: 0, // boom
  5276. ..SEND_TEMPL
  5277. });
  5278. // even though we're in "fast retransmit", we shouldn't
  5279. // force-send anything because the remote's window is full.
  5280. recv!(s, Err(Error::Exhausted));
  5281. }
  5282. // =========================================================================================//
  5283. // Tests for window management.
  5284. // =========================================================================================//
  5285. #[test]
  5286. fn test_maximum_segment_size() {
  5287. let mut s = socket_listen();
  5288. s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
  5289. send!(
  5290. s,
  5291. TcpRepr {
  5292. control: TcpControl::Syn,
  5293. seq_number: REMOTE_SEQ,
  5294. ack_number: None,
  5295. max_seg_size: Some(1000),
  5296. ..SEND_TEMPL
  5297. }
  5298. );
  5299. recv!(
  5300. s,
  5301. [TcpRepr {
  5302. control: TcpControl::Syn,
  5303. seq_number: LOCAL_SEQ,
  5304. ack_number: Some(REMOTE_SEQ + 1),
  5305. max_seg_size: Some(BASE_MSS),
  5306. ..RECV_TEMPL
  5307. }]
  5308. );
  5309. send!(
  5310. s,
  5311. TcpRepr {
  5312. seq_number: REMOTE_SEQ + 1,
  5313. ack_number: Some(LOCAL_SEQ + 1),
  5314. window_len: 32767,
  5315. ..SEND_TEMPL
  5316. }
  5317. );
  5318. s.send_slice(&[0; 1200][..]).unwrap();
  5319. recv!(
  5320. s,
  5321. Ok(TcpRepr {
  5322. seq_number: LOCAL_SEQ + 1,
  5323. ack_number: Some(REMOTE_SEQ + 1),
  5324. payload: &[0; 1000][..],
  5325. ..RECV_TEMPL
  5326. })
  5327. );
  5328. }
  5329. #[test]
  5330. fn test_close_wait_no_window_update() {
  5331. let mut s = socket_established();
  5332. send!(
  5333. s,
  5334. TcpRepr {
  5335. control: TcpControl::Fin,
  5336. seq_number: REMOTE_SEQ + 1,
  5337. ack_number: Some(LOCAL_SEQ + 1),
  5338. payload: &[1, 2, 3, 4],
  5339. ..SEND_TEMPL
  5340. }
  5341. );
  5342. assert_eq!(s.state, State::CloseWait);
  5343. // we ack the FIN, with the reduced window size.
  5344. recv!(
  5345. s,
  5346. Ok(TcpRepr {
  5347. seq_number: LOCAL_SEQ + 1,
  5348. ack_number: Some(REMOTE_SEQ + 6),
  5349. window_len: 60,
  5350. ..RECV_TEMPL
  5351. })
  5352. );
  5353. let rx_buf = &mut [0; 32];
  5354. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  5355. // check that we do NOT send a window update even if it has changed.
  5356. recv!(s, Err(Error::Exhausted));
  5357. }
  5358. #[test]
  5359. fn test_time_wait_no_window_update() {
  5360. let mut s = socket_fin_wait_2();
  5361. send!(
  5362. s,
  5363. TcpRepr {
  5364. control: TcpControl::Fin,
  5365. seq_number: REMOTE_SEQ + 1,
  5366. ack_number: Some(LOCAL_SEQ + 2),
  5367. payload: &[1, 2, 3, 4],
  5368. ..SEND_TEMPL
  5369. }
  5370. );
  5371. assert_eq!(s.state, State::TimeWait);
  5372. // we ack the FIN, with the reduced window size.
  5373. recv!(
  5374. s,
  5375. Ok(TcpRepr {
  5376. seq_number: LOCAL_SEQ + 2,
  5377. ack_number: Some(REMOTE_SEQ + 6),
  5378. window_len: 60,
  5379. ..RECV_TEMPL
  5380. })
  5381. );
  5382. let rx_buf = &mut [0; 32];
  5383. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  5384. // check that we do NOT send a window update even if it has changed.
  5385. recv!(s, Err(Error::Exhausted));
  5386. }
  5387. // =========================================================================================//
  5388. // Tests for flow control.
  5389. // =========================================================================================//
  5390. #[test]
  5391. fn test_psh_transmit() {
  5392. let mut s = socket_established();
  5393. s.remote_mss = 6;
  5394. s.send_slice(b"abcdef").unwrap();
  5395. s.send_slice(b"123456").unwrap();
  5396. recv!(s, time 0, Ok(TcpRepr {
  5397. control: TcpControl::None,
  5398. seq_number: LOCAL_SEQ + 1,
  5399. ack_number: Some(REMOTE_SEQ + 1),
  5400. payload: &b"abcdef"[..],
  5401. ..RECV_TEMPL
  5402. }), exact);
  5403. recv!(s, time 0, Ok(TcpRepr {
  5404. control: TcpControl::Psh,
  5405. seq_number: LOCAL_SEQ + 1 + 6,
  5406. ack_number: Some(REMOTE_SEQ + 1),
  5407. payload: &b"123456"[..],
  5408. ..RECV_TEMPL
  5409. }), exact);
  5410. }
  5411. #[test]
  5412. fn test_psh_receive() {
  5413. let mut s = socket_established();
  5414. send!(
  5415. s,
  5416. TcpRepr {
  5417. control: TcpControl::Psh,
  5418. seq_number: REMOTE_SEQ + 1,
  5419. ack_number: Some(LOCAL_SEQ + 1),
  5420. payload: &b"abcdef"[..],
  5421. ..SEND_TEMPL
  5422. }
  5423. );
  5424. recv!(
  5425. s,
  5426. [TcpRepr {
  5427. seq_number: LOCAL_SEQ + 1,
  5428. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5429. window_len: 58,
  5430. ..RECV_TEMPL
  5431. }]
  5432. );
  5433. }
  5434. #[test]
  5435. fn test_zero_window_ack() {
  5436. let mut s = socket_established();
  5437. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  5438. s.assembler = Assembler::new(s.rx_buffer.capacity());
  5439. send!(
  5440. s,
  5441. TcpRepr {
  5442. seq_number: REMOTE_SEQ + 1,
  5443. ack_number: Some(LOCAL_SEQ + 1),
  5444. payload: &b"abcdef"[..],
  5445. ..SEND_TEMPL
  5446. }
  5447. );
  5448. recv!(
  5449. s,
  5450. [TcpRepr {
  5451. seq_number: LOCAL_SEQ + 1,
  5452. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5453. window_len: 0,
  5454. ..RECV_TEMPL
  5455. }]
  5456. );
  5457. send!(
  5458. s,
  5459. TcpRepr {
  5460. seq_number: REMOTE_SEQ + 1 + 6,
  5461. ack_number: Some(LOCAL_SEQ + 1),
  5462. payload: &b"123456"[..],
  5463. ..SEND_TEMPL
  5464. },
  5465. Ok(Some(TcpRepr {
  5466. seq_number: LOCAL_SEQ + 1,
  5467. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5468. window_len: 0,
  5469. ..RECV_TEMPL
  5470. }))
  5471. );
  5472. }
  5473. #[test]
  5474. fn test_zero_window_ack_on_window_growth() {
  5475. let mut s = socket_established();
  5476. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  5477. s.assembler = Assembler::new(s.rx_buffer.capacity());
  5478. send!(
  5479. s,
  5480. TcpRepr {
  5481. seq_number: REMOTE_SEQ + 1,
  5482. ack_number: Some(LOCAL_SEQ + 1),
  5483. payload: &b"abcdef"[..],
  5484. ..SEND_TEMPL
  5485. }
  5486. );
  5487. recv!(
  5488. s,
  5489. [TcpRepr {
  5490. seq_number: LOCAL_SEQ + 1,
  5491. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5492. window_len: 0,
  5493. ..RECV_TEMPL
  5494. }]
  5495. );
  5496. recv!(s, time 0, Err(Error::Exhausted));
  5497. s.recv(|buffer| {
  5498. assert_eq!(&buffer[..3], b"abc");
  5499. (3, ())
  5500. })
  5501. .unwrap();
  5502. recv!(s, time 0, Ok(TcpRepr {
  5503. seq_number: LOCAL_SEQ + 1,
  5504. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5505. window_len: 3,
  5506. ..RECV_TEMPL
  5507. }));
  5508. recv!(s, time 0, Err(Error::Exhausted));
  5509. s.recv(|buffer| {
  5510. assert_eq!(buffer, b"def");
  5511. (buffer.len(), ())
  5512. })
  5513. .unwrap();
  5514. recv!(s, time 0, Ok(TcpRepr {
  5515. seq_number: LOCAL_SEQ + 1,
  5516. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5517. window_len: 6,
  5518. ..RECV_TEMPL
  5519. }));
  5520. }
  5521. #[test]
  5522. fn test_fill_peer_window() {
  5523. let mut s = socket_established();
  5524. s.remote_mss = 6;
  5525. s.send_slice(b"abcdef123456!@#$%^").unwrap();
  5526. recv!(
  5527. s,
  5528. [
  5529. TcpRepr {
  5530. seq_number: LOCAL_SEQ + 1,
  5531. ack_number: Some(REMOTE_SEQ + 1),
  5532. payload: &b"abcdef"[..],
  5533. ..RECV_TEMPL
  5534. },
  5535. TcpRepr {
  5536. seq_number: LOCAL_SEQ + 1 + 6,
  5537. ack_number: Some(REMOTE_SEQ + 1),
  5538. payload: &b"123456"[..],
  5539. ..RECV_TEMPL
  5540. },
  5541. TcpRepr {
  5542. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  5543. ack_number: Some(REMOTE_SEQ + 1),
  5544. payload: &b"!@#$%^"[..],
  5545. ..RECV_TEMPL
  5546. }
  5547. ]
  5548. );
  5549. }
  5550. #[test]
  5551. fn test_announce_window_after_read() {
  5552. let mut s = socket_established();
  5553. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  5554. s.assembler = Assembler::new(s.rx_buffer.capacity());
  5555. send!(
  5556. s,
  5557. TcpRepr {
  5558. seq_number: REMOTE_SEQ + 1,
  5559. ack_number: Some(LOCAL_SEQ + 1),
  5560. payload: &b"abc"[..],
  5561. ..SEND_TEMPL
  5562. }
  5563. );
  5564. recv!(
  5565. s,
  5566. [TcpRepr {
  5567. seq_number: LOCAL_SEQ + 1,
  5568. ack_number: Some(REMOTE_SEQ + 1 + 3),
  5569. window_len: 3,
  5570. ..RECV_TEMPL
  5571. }]
  5572. );
  5573. // Test that `dispatch` updates `remote_last_win`
  5574. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  5575. s.recv(|buffer| (buffer.len(), ())).unwrap();
  5576. assert!(s.window_to_update());
  5577. recv!(
  5578. s,
  5579. [TcpRepr {
  5580. seq_number: LOCAL_SEQ + 1,
  5581. ack_number: Some(REMOTE_SEQ + 1 + 3),
  5582. window_len: 6,
  5583. ..RECV_TEMPL
  5584. }]
  5585. );
  5586. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  5587. // Provoke immediate ACK to test that `process` updates `remote_last_win`
  5588. send!(
  5589. s,
  5590. TcpRepr {
  5591. seq_number: REMOTE_SEQ + 1 + 6,
  5592. ack_number: Some(LOCAL_SEQ + 1),
  5593. payload: &b"def"[..],
  5594. ..SEND_TEMPL
  5595. },
  5596. Ok(Some(TcpRepr {
  5597. seq_number: LOCAL_SEQ + 1,
  5598. ack_number: Some(REMOTE_SEQ + 1 + 3),
  5599. window_len: 6,
  5600. ..RECV_TEMPL
  5601. }))
  5602. );
  5603. send!(
  5604. s,
  5605. TcpRepr {
  5606. seq_number: REMOTE_SEQ + 1 + 3,
  5607. ack_number: Some(LOCAL_SEQ + 1),
  5608. payload: &b"abc"[..],
  5609. ..SEND_TEMPL
  5610. },
  5611. Ok(Some(TcpRepr {
  5612. seq_number: LOCAL_SEQ + 1,
  5613. ack_number: Some(REMOTE_SEQ + 1 + 9),
  5614. window_len: 0,
  5615. ..RECV_TEMPL
  5616. }))
  5617. );
  5618. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  5619. s.recv(|buffer| (buffer.len(), ())).unwrap();
  5620. assert!(s.window_to_update());
  5621. }
  5622. // =========================================================================================//
  5623. // Tests for timeouts.
  5624. // =========================================================================================//
  5625. #[test]
  5626. fn test_listen_timeout() {
  5627. let mut s = socket_listen();
  5628. s.set_timeout(Some(Duration::from_millis(100)));
  5629. assert_eq!(s.poll_at(&Context::DUMMY), PollAt::Ingress);
  5630. }
  5631. #[test]
  5632. fn test_connect_timeout() {
  5633. let mut s = socket();
  5634. s.local_seq_no = LOCAL_SEQ;
  5635. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  5636. s.set_timeout(Some(Duration::from_millis(100)));
  5637. recv!(s, time 150, Ok(TcpRepr {
  5638. control: TcpControl::Syn,
  5639. seq_number: LOCAL_SEQ,
  5640. ack_number: None,
  5641. max_seg_size: Some(BASE_MSS),
  5642. window_scale: Some(0),
  5643. sack_permitted: true,
  5644. ..RECV_TEMPL
  5645. }));
  5646. assert_eq!(s.state, State::SynSent);
  5647. assert_eq!(
  5648. s.poll_at(&Context::DUMMY),
  5649. PollAt::Time(Instant::from_millis(250))
  5650. );
  5651. recv!(s, time 250, Ok(TcpRepr {
  5652. control: TcpControl::Rst,
  5653. seq_number: LOCAL_SEQ + 1,
  5654. ack_number: Some(TcpSeqNumber(0)),
  5655. window_scale: None,
  5656. ..RECV_TEMPL
  5657. }));
  5658. assert_eq!(s.state, State::Closed);
  5659. }
  5660. #[test]
  5661. fn test_established_timeout() {
  5662. let mut s = socket_established();
  5663. s.set_timeout(Some(Duration::from_millis(1000)));
  5664. recv!(s, time 250, Err(Error::Exhausted));
  5665. assert_eq!(
  5666. s.poll_at(&Context::DUMMY),
  5667. PollAt::Time(Instant::from_millis(1250))
  5668. );
  5669. s.send_slice(b"abcdef").unwrap();
  5670. assert_eq!(s.poll_at(&Context::DUMMY), PollAt::Now);
  5671. recv!(s, time 255, Ok(TcpRepr {
  5672. seq_number: LOCAL_SEQ + 1,
  5673. ack_number: Some(REMOTE_SEQ + 1),
  5674. payload: &b"abcdef"[..],
  5675. ..RECV_TEMPL
  5676. }));
  5677. assert_eq!(
  5678. s.poll_at(&Context::DUMMY),
  5679. PollAt::Time(Instant::from_millis(955))
  5680. );
  5681. recv!(s, time 955, Ok(TcpRepr {
  5682. seq_number: LOCAL_SEQ + 1,
  5683. ack_number: Some(REMOTE_SEQ + 1),
  5684. payload: &b"abcdef"[..],
  5685. ..RECV_TEMPL
  5686. }));
  5687. assert_eq!(
  5688. s.poll_at(&Context::DUMMY),
  5689. PollAt::Time(Instant::from_millis(1255))
  5690. );
  5691. recv!(s, time 1255, Ok(TcpRepr {
  5692. control: TcpControl::Rst,
  5693. seq_number: LOCAL_SEQ + 1 + 6,
  5694. ack_number: Some(REMOTE_SEQ + 1),
  5695. ..RECV_TEMPL
  5696. }));
  5697. assert_eq!(s.state, State::Closed);
  5698. }
  5699. #[test]
  5700. fn test_established_keep_alive_timeout() {
  5701. let mut s = socket_established();
  5702. s.set_keep_alive(Some(Duration::from_millis(50)));
  5703. s.set_timeout(Some(Duration::from_millis(100)));
  5704. recv!(s, time 100, Ok(TcpRepr {
  5705. seq_number: LOCAL_SEQ,
  5706. ack_number: Some(REMOTE_SEQ + 1),
  5707. payload: &[0],
  5708. ..RECV_TEMPL
  5709. }));
  5710. recv!(s, time 100, Err(Error::Exhausted));
  5711. assert_eq!(
  5712. s.poll_at(&Context::DUMMY),
  5713. PollAt::Time(Instant::from_millis(150))
  5714. );
  5715. send!(s, time 105, TcpRepr {
  5716. seq_number: REMOTE_SEQ + 1,
  5717. ack_number: Some(LOCAL_SEQ + 1),
  5718. ..SEND_TEMPL
  5719. });
  5720. assert_eq!(
  5721. s.poll_at(&Context::DUMMY),
  5722. PollAt::Time(Instant::from_millis(155))
  5723. );
  5724. recv!(s, time 155, Ok(TcpRepr {
  5725. seq_number: LOCAL_SEQ,
  5726. ack_number: Some(REMOTE_SEQ + 1),
  5727. payload: &[0],
  5728. ..RECV_TEMPL
  5729. }));
  5730. recv!(s, time 155, Err(Error::Exhausted));
  5731. assert_eq!(
  5732. s.poll_at(&Context::DUMMY),
  5733. PollAt::Time(Instant::from_millis(205))
  5734. );
  5735. recv!(s, time 200, Err(Error::Exhausted));
  5736. recv!(s, time 205, Ok(TcpRepr {
  5737. control: TcpControl::Rst,
  5738. seq_number: LOCAL_SEQ + 1,
  5739. ack_number: Some(REMOTE_SEQ + 1),
  5740. ..RECV_TEMPL
  5741. }));
  5742. recv!(s, time 205, Err(Error::Exhausted));
  5743. assert_eq!(s.state, State::Closed);
  5744. }
  5745. #[test]
  5746. fn test_fin_wait_1_timeout() {
  5747. let mut s = socket_fin_wait_1();
  5748. s.set_timeout(Some(Duration::from_millis(1000)));
  5749. recv!(s, time 100, Ok(TcpRepr {
  5750. control: TcpControl::Fin,
  5751. seq_number: LOCAL_SEQ + 1,
  5752. ack_number: Some(REMOTE_SEQ + 1),
  5753. ..RECV_TEMPL
  5754. }));
  5755. recv!(s, time 1100, Ok(TcpRepr {
  5756. control: TcpControl::Rst,
  5757. seq_number: LOCAL_SEQ + 1 + 1,
  5758. ack_number: Some(REMOTE_SEQ + 1),
  5759. ..RECV_TEMPL
  5760. }));
  5761. assert_eq!(s.state, State::Closed);
  5762. }
  5763. #[test]
  5764. fn test_last_ack_timeout() {
  5765. let mut s = socket_last_ack();
  5766. s.set_timeout(Some(Duration::from_millis(1000)));
  5767. recv!(s, time 100, Ok(TcpRepr {
  5768. control: TcpControl::Fin,
  5769. seq_number: LOCAL_SEQ + 1,
  5770. ack_number: Some(REMOTE_SEQ + 1 + 1),
  5771. ..RECV_TEMPL
  5772. }));
  5773. recv!(s, time 1100, Ok(TcpRepr {
  5774. control: TcpControl::Rst,
  5775. seq_number: LOCAL_SEQ + 1 + 1,
  5776. ack_number: Some(REMOTE_SEQ + 1 + 1),
  5777. ..RECV_TEMPL
  5778. }));
  5779. assert_eq!(s.state, State::Closed);
  5780. }
  5781. #[test]
  5782. fn test_closed_timeout() {
  5783. let mut s = socket_established();
  5784. s.set_timeout(Some(Duration::from_millis(200)));
  5785. s.remote_last_ts = Some(Instant::from_millis(100));
  5786. s.abort();
  5787. assert_eq!(s.poll_at(&Context::DUMMY), PollAt::Now);
  5788. recv!(s, time 100, Ok(TcpRepr {
  5789. control: TcpControl::Rst,
  5790. seq_number: LOCAL_SEQ + 1,
  5791. ack_number: Some(REMOTE_SEQ + 1),
  5792. ..RECV_TEMPL
  5793. }));
  5794. assert_eq!(s.poll_at(&Context::DUMMY), PollAt::Ingress);
  5795. }
  5796. // =========================================================================================//
  5797. // Tests for keep-alive.
  5798. // =========================================================================================//
  5799. #[test]
  5800. fn test_responds_to_keep_alive() {
  5801. let mut s = socket_established();
  5802. send!(
  5803. s,
  5804. TcpRepr {
  5805. seq_number: REMOTE_SEQ,
  5806. ack_number: Some(LOCAL_SEQ + 1),
  5807. ..SEND_TEMPL
  5808. },
  5809. Ok(Some(TcpRepr {
  5810. seq_number: LOCAL_SEQ + 1,
  5811. ack_number: Some(REMOTE_SEQ + 1),
  5812. ..RECV_TEMPL
  5813. }))
  5814. );
  5815. }
  5816. #[test]
  5817. fn test_sends_keep_alive() {
  5818. let mut s = socket_established();
  5819. s.set_keep_alive(Some(Duration::from_millis(100)));
  5820. // drain the forced keep-alive packet
  5821. assert_eq!(s.poll_at(&Context::DUMMY), PollAt::Now);
  5822. recv!(s, time 0, Ok(TcpRepr {
  5823. seq_number: LOCAL_SEQ,
  5824. ack_number: Some(REMOTE_SEQ + 1),
  5825. payload: &[0],
  5826. ..RECV_TEMPL
  5827. }));
  5828. assert_eq!(
  5829. s.poll_at(&Context::DUMMY),
  5830. PollAt::Time(Instant::from_millis(100))
  5831. );
  5832. recv!(s, time 95, Err(Error::Exhausted));
  5833. recv!(s, time 100, Ok(TcpRepr {
  5834. seq_number: LOCAL_SEQ,
  5835. ack_number: Some(REMOTE_SEQ + 1),
  5836. payload: &[0],
  5837. ..RECV_TEMPL
  5838. }));
  5839. assert_eq!(
  5840. s.poll_at(&Context::DUMMY),
  5841. PollAt::Time(Instant::from_millis(200))
  5842. );
  5843. recv!(s, time 195, Err(Error::Exhausted));
  5844. recv!(s, time 200, Ok(TcpRepr {
  5845. seq_number: LOCAL_SEQ,
  5846. ack_number: Some(REMOTE_SEQ + 1),
  5847. payload: &[0],
  5848. ..RECV_TEMPL
  5849. }));
  5850. send!(s, time 250, TcpRepr {
  5851. seq_number: REMOTE_SEQ + 1,
  5852. ack_number: Some(LOCAL_SEQ + 1),
  5853. ..SEND_TEMPL
  5854. });
  5855. assert_eq!(
  5856. s.poll_at(&Context::DUMMY),
  5857. PollAt::Time(Instant::from_millis(350))
  5858. );
  5859. recv!(s, time 345, Err(Error::Exhausted));
  5860. recv!(s, time 350, Ok(TcpRepr {
  5861. seq_number: LOCAL_SEQ,
  5862. ack_number: Some(REMOTE_SEQ + 1),
  5863. payload: &b"\x00"[..],
  5864. ..RECV_TEMPL
  5865. }));
  5866. }
  5867. // =========================================================================================//
  5868. // Tests for time-to-live configuration.
  5869. // =========================================================================================//
  5870. #[test]
  5871. fn test_set_hop_limit() {
  5872. let mut s = socket_syn_received();
  5873. s.set_hop_limit(Some(0x2a));
  5874. assert_eq!(
  5875. s.dispatch(&Context::DUMMY, |(ip_repr, _)| {
  5876. assert_eq!(ip_repr.hop_limit(), 0x2a);
  5877. Ok(())
  5878. }),
  5879. Ok(())
  5880. );
  5881. }
  5882. #[test]
  5883. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  5884. fn test_set_hop_limit_zero() {
  5885. let mut s = socket_syn_received();
  5886. s.set_hop_limit(Some(0));
  5887. }
  5888. // =========================================================================================//
  5889. // Tests for reassembly.
  5890. // =========================================================================================//
  5891. #[test]
  5892. fn test_out_of_order() {
  5893. let mut s = socket_established();
  5894. send!(
  5895. s,
  5896. TcpRepr {
  5897. seq_number: REMOTE_SEQ + 1 + 3,
  5898. ack_number: Some(LOCAL_SEQ + 1),
  5899. payload: &b"def"[..],
  5900. ..SEND_TEMPL
  5901. },
  5902. Ok(Some(TcpRepr {
  5903. seq_number: LOCAL_SEQ + 1,
  5904. ack_number: Some(REMOTE_SEQ + 1),
  5905. ..RECV_TEMPL
  5906. }))
  5907. );
  5908. s.recv(|buffer| {
  5909. assert_eq!(buffer, b"");
  5910. (buffer.len(), ())
  5911. })
  5912. .unwrap();
  5913. send!(
  5914. s,
  5915. TcpRepr {
  5916. seq_number: REMOTE_SEQ + 1,
  5917. ack_number: Some(LOCAL_SEQ + 1),
  5918. payload: &b"abcdef"[..],
  5919. ..SEND_TEMPL
  5920. },
  5921. Ok(Some(TcpRepr {
  5922. seq_number: LOCAL_SEQ + 1,
  5923. ack_number: Some(REMOTE_SEQ + 1 + 6),
  5924. window_len: 58,
  5925. ..RECV_TEMPL
  5926. }))
  5927. );
  5928. s.recv(|buffer| {
  5929. assert_eq!(buffer, b"abcdef");
  5930. (buffer.len(), ())
  5931. })
  5932. .unwrap();
  5933. }
  5934. #[test]
  5935. fn test_buffer_wraparound_rx() {
  5936. let mut s = socket_established();
  5937. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  5938. s.assembler = Assembler::new(s.rx_buffer.capacity());
  5939. send!(
  5940. s,
  5941. TcpRepr {
  5942. seq_number: REMOTE_SEQ + 1,
  5943. ack_number: Some(LOCAL_SEQ + 1),
  5944. payload: &b"abc"[..],
  5945. ..SEND_TEMPL
  5946. }
  5947. );
  5948. s.recv(|buffer| {
  5949. assert_eq!(buffer, b"abc");
  5950. (buffer.len(), ())
  5951. })
  5952. .unwrap();
  5953. send!(
  5954. s,
  5955. TcpRepr {
  5956. seq_number: REMOTE_SEQ + 1 + 3,
  5957. ack_number: Some(LOCAL_SEQ + 1),
  5958. payload: &b"defghi"[..],
  5959. ..SEND_TEMPL
  5960. }
  5961. );
  5962. let mut data = [0; 6];
  5963. assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
  5964. assert_eq!(data, &b"defghi"[..]);
  5965. }
  5966. #[test]
  5967. fn test_buffer_wraparound_tx() {
  5968. let mut s = socket_established();
  5969. s.set_nagle_enabled(false);
  5970. s.tx_buffer = SocketBuffer::new(vec![b'.'; 9]);
  5971. assert_eq!(s.send_slice(b"xxxyyy"), Ok(6));
  5972. assert_eq!(s.tx_buffer.dequeue_many(3), &b"xxx"[..]);
  5973. assert_eq!(s.tx_buffer.len(), 3);
  5974. // "abcdef" not contiguous in tx buffer
  5975. assert_eq!(s.send_slice(b"abcdef"), Ok(6));
  5976. recv!(
  5977. s,
  5978. Ok(TcpRepr {
  5979. seq_number: LOCAL_SEQ + 1,
  5980. ack_number: Some(REMOTE_SEQ + 1),
  5981. payload: &b"yyyabc"[..],
  5982. ..RECV_TEMPL
  5983. })
  5984. );
  5985. recv!(
  5986. s,
  5987. Ok(TcpRepr {
  5988. seq_number: LOCAL_SEQ + 1 + 6,
  5989. ack_number: Some(REMOTE_SEQ + 1),
  5990. payload: &b"def"[..],
  5991. ..RECV_TEMPL
  5992. })
  5993. );
  5994. }
  5995. // =========================================================================================//
  5996. // Tests for graceful vs ungraceful rx close
  5997. // =========================================================================================//
  5998. #[test]
  5999. fn test_rx_close_fin() {
  6000. let mut s = socket_established();
  6001. send!(
  6002. s,
  6003. TcpRepr {
  6004. control: TcpControl::Fin,
  6005. seq_number: REMOTE_SEQ + 1,
  6006. ack_number: Some(LOCAL_SEQ + 1),
  6007. payload: &b"abc"[..],
  6008. ..SEND_TEMPL
  6009. }
  6010. );
  6011. s.recv(|data| {
  6012. assert_eq!(data, b"abc");
  6013. (3, ())
  6014. })
  6015. .unwrap();
  6016. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  6017. }
  6018. #[test]
  6019. fn test_rx_close_fin_in_fin_wait_1() {
  6020. let mut s = socket_fin_wait_1();
  6021. send!(
  6022. s,
  6023. TcpRepr {
  6024. control: TcpControl::Fin,
  6025. seq_number: REMOTE_SEQ + 1,
  6026. ack_number: Some(LOCAL_SEQ + 1),
  6027. payload: &b"abc"[..],
  6028. ..SEND_TEMPL
  6029. }
  6030. );
  6031. assert_eq!(s.state, State::Closing);
  6032. s.recv(|data| {
  6033. assert_eq!(data, b"abc");
  6034. (3, ())
  6035. })
  6036. .unwrap();
  6037. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  6038. }
  6039. #[test]
  6040. fn test_rx_close_fin_in_fin_wait_2() {
  6041. let mut s = socket_fin_wait_2();
  6042. send!(
  6043. s,
  6044. TcpRepr {
  6045. control: TcpControl::Fin,
  6046. seq_number: REMOTE_SEQ + 1,
  6047. ack_number: Some(LOCAL_SEQ + 1 + 1),
  6048. payload: &b"abc"[..],
  6049. ..SEND_TEMPL
  6050. }
  6051. );
  6052. assert_eq!(s.state, State::TimeWait);
  6053. s.recv(|data| {
  6054. assert_eq!(data, b"abc");
  6055. (3, ())
  6056. })
  6057. .unwrap();
  6058. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  6059. }
  6060. #[test]
  6061. fn test_rx_close_fin_with_hole() {
  6062. let mut s = socket_established();
  6063. send!(
  6064. s,
  6065. TcpRepr {
  6066. seq_number: REMOTE_SEQ + 1,
  6067. ack_number: Some(LOCAL_SEQ + 1),
  6068. payload: &b"abc"[..],
  6069. ..SEND_TEMPL
  6070. }
  6071. );
  6072. send!(
  6073. s,
  6074. TcpRepr {
  6075. control: TcpControl::Fin,
  6076. seq_number: REMOTE_SEQ + 1 + 6,
  6077. ack_number: Some(LOCAL_SEQ + 1),
  6078. payload: &b"ghi"[..],
  6079. ..SEND_TEMPL
  6080. },
  6081. Ok(Some(TcpRepr {
  6082. seq_number: LOCAL_SEQ + 1,
  6083. ack_number: Some(REMOTE_SEQ + 1 + 3),
  6084. window_len: 61,
  6085. ..RECV_TEMPL
  6086. }))
  6087. );
  6088. s.recv(|data| {
  6089. assert_eq!(data, b"abc");
  6090. (3, ())
  6091. })
  6092. .unwrap();
  6093. s.recv(|data| {
  6094. assert_eq!(data, b"");
  6095. (0, ())
  6096. })
  6097. .unwrap();
  6098. send!(
  6099. s,
  6100. TcpRepr {
  6101. control: TcpControl::Rst,
  6102. seq_number: REMOTE_SEQ + 1 + 9,
  6103. ack_number: Some(LOCAL_SEQ + 1),
  6104. ..SEND_TEMPL
  6105. }
  6106. );
  6107. // Error must be `Illegal` even if we've received a FIN,
  6108. // because we are missing data.
  6109. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  6110. }
  6111. #[test]
  6112. fn test_rx_close_rst() {
  6113. let mut s = socket_established();
  6114. send!(
  6115. s,
  6116. TcpRepr {
  6117. seq_number: REMOTE_SEQ + 1,
  6118. ack_number: Some(LOCAL_SEQ + 1),
  6119. payload: &b"abc"[..],
  6120. ..SEND_TEMPL
  6121. }
  6122. );
  6123. send!(
  6124. s,
  6125. TcpRepr {
  6126. control: TcpControl::Rst,
  6127. seq_number: REMOTE_SEQ + 1 + 3,
  6128. ack_number: Some(LOCAL_SEQ + 1),
  6129. ..SEND_TEMPL
  6130. }
  6131. );
  6132. s.recv(|data| {
  6133. assert_eq!(data, b"abc");
  6134. (3, ())
  6135. })
  6136. .unwrap();
  6137. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  6138. }
  6139. #[test]
  6140. fn test_rx_close_rst_with_hole() {
  6141. let mut s = socket_established();
  6142. send!(
  6143. s,
  6144. TcpRepr {
  6145. seq_number: REMOTE_SEQ + 1,
  6146. ack_number: Some(LOCAL_SEQ + 1),
  6147. payload: &b"abc"[..],
  6148. ..SEND_TEMPL
  6149. }
  6150. );
  6151. send!(
  6152. s,
  6153. TcpRepr {
  6154. seq_number: REMOTE_SEQ + 1 + 6,
  6155. ack_number: Some(LOCAL_SEQ + 1),
  6156. payload: &b"ghi"[..],
  6157. ..SEND_TEMPL
  6158. },
  6159. Ok(Some(TcpRepr {
  6160. seq_number: LOCAL_SEQ + 1,
  6161. ack_number: Some(REMOTE_SEQ + 1 + 3),
  6162. window_len: 61,
  6163. ..RECV_TEMPL
  6164. }))
  6165. );
  6166. send!(
  6167. s,
  6168. TcpRepr {
  6169. control: TcpControl::Rst,
  6170. seq_number: REMOTE_SEQ + 1 + 9,
  6171. ack_number: Some(LOCAL_SEQ + 1),
  6172. ..SEND_TEMPL
  6173. }
  6174. );
  6175. s.recv(|data| {
  6176. assert_eq!(data, b"abc");
  6177. (3, ())
  6178. })
  6179. .unwrap();
  6180. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  6181. }
  6182. // =========================================================================================//
  6183. // Tests for delayed ACK
  6184. // =========================================================================================//
  6185. #[test]
  6186. fn test_delayed_ack() {
  6187. let mut s = socket_established();
  6188. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  6189. send!(
  6190. s,
  6191. TcpRepr {
  6192. seq_number: REMOTE_SEQ + 1,
  6193. ack_number: Some(LOCAL_SEQ + 1),
  6194. payload: &b"abc"[..],
  6195. ..SEND_TEMPL
  6196. }
  6197. );
  6198. // No ACK is immediately sent.
  6199. recv!(s, Err(Error::Exhausted));
  6200. // After 10ms, it is sent.
  6201. recv!(s, time 11, Ok(TcpRepr {
  6202. seq_number: LOCAL_SEQ + 1,
  6203. ack_number: Some(REMOTE_SEQ + 1 + 3),
  6204. window_len: 61,
  6205. ..RECV_TEMPL
  6206. }));
  6207. }
  6208. #[test]
  6209. fn test_delayed_ack_win() {
  6210. let mut s = socket_established();
  6211. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  6212. send!(
  6213. s,
  6214. TcpRepr {
  6215. seq_number: REMOTE_SEQ + 1,
  6216. ack_number: Some(LOCAL_SEQ + 1),
  6217. payload: &b"abc"[..],
  6218. ..SEND_TEMPL
  6219. }
  6220. );
  6221. // Reading the data off the buffer should cause a window update.
  6222. s.recv(|data| {
  6223. assert_eq!(data, b"abc");
  6224. (3, ())
  6225. })
  6226. .unwrap();
  6227. // However, no ACK or window update is immediately sent.
  6228. recv!(s, Err(Error::Exhausted));
  6229. // After 10ms, it is sent.
  6230. recv!(s, time 11, Ok(TcpRepr {
  6231. seq_number: LOCAL_SEQ + 1,
  6232. ack_number: Some(REMOTE_SEQ + 1 + 3),
  6233. ..RECV_TEMPL
  6234. }));
  6235. }
  6236. #[test]
  6237. fn test_delayed_ack_reply() {
  6238. let mut s = socket_established();
  6239. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  6240. send!(
  6241. s,
  6242. TcpRepr {
  6243. seq_number: REMOTE_SEQ + 1,
  6244. ack_number: Some(LOCAL_SEQ + 1),
  6245. payload: &b"abc"[..],
  6246. ..SEND_TEMPL
  6247. }
  6248. );
  6249. s.recv(|data| {
  6250. assert_eq!(data, b"abc");
  6251. (3, ())
  6252. })
  6253. .unwrap();
  6254. s.send_slice(&b"xyz"[..]).unwrap();
  6255. // Writing data to the socket causes ACK to not be delayed,
  6256. // because it is immediately sent with the data.
  6257. recv!(
  6258. s,
  6259. Ok(TcpRepr {
  6260. seq_number: LOCAL_SEQ + 1,
  6261. ack_number: Some(REMOTE_SEQ + 1 + 3),
  6262. payload: &b"xyz"[..],
  6263. ..RECV_TEMPL
  6264. })
  6265. );
  6266. }
  6267. #[test]
  6268. fn test_delayed_ack_every_second_packet() {
  6269. let mut s = socket_established();
  6270. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  6271. send!(
  6272. s,
  6273. TcpRepr {
  6274. seq_number: REMOTE_SEQ + 1,
  6275. ack_number: Some(LOCAL_SEQ + 1),
  6276. payload: &b"abc"[..],
  6277. ..SEND_TEMPL
  6278. }
  6279. );
  6280. // No ACK is immediately sent.
  6281. recv!(s, Err(Error::Exhausted));
  6282. send!(
  6283. s,
  6284. TcpRepr {
  6285. seq_number: REMOTE_SEQ + 1 + 3,
  6286. ack_number: Some(LOCAL_SEQ + 1),
  6287. payload: &b"def"[..],
  6288. ..SEND_TEMPL
  6289. }
  6290. );
  6291. // Every 2nd packet, ACK is sent without delay.
  6292. recv!(
  6293. s,
  6294. Ok(TcpRepr {
  6295. seq_number: LOCAL_SEQ + 1,
  6296. ack_number: Some(REMOTE_SEQ + 1 + 6),
  6297. window_len: 58,
  6298. ..RECV_TEMPL
  6299. })
  6300. );
  6301. }
  6302. #[test]
  6303. fn test_delayed_ack_three_packets() {
  6304. let mut s = socket_established();
  6305. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  6306. send!(
  6307. s,
  6308. TcpRepr {
  6309. seq_number: REMOTE_SEQ + 1,
  6310. ack_number: Some(LOCAL_SEQ + 1),
  6311. payload: &b"abc"[..],
  6312. ..SEND_TEMPL
  6313. }
  6314. );
  6315. // No ACK is immediately sent.
  6316. recv!(s, Err(Error::Exhausted));
  6317. send!(
  6318. s,
  6319. TcpRepr {
  6320. seq_number: REMOTE_SEQ + 1 + 3,
  6321. ack_number: Some(LOCAL_SEQ + 1),
  6322. payload: &b"def"[..],
  6323. ..SEND_TEMPL
  6324. }
  6325. );
  6326. send!(
  6327. s,
  6328. TcpRepr {
  6329. seq_number: REMOTE_SEQ + 1 + 6,
  6330. ack_number: Some(LOCAL_SEQ + 1),
  6331. payload: &b"ghi"[..],
  6332. ..SEND_TEMPL
  6333. }
  6334. );
  6335. // Every 2nd (or more) packet, ACK is sent without delay.
  6336. recv!(
  6337. s,
  6338. Ok(TcpRepr {
  6339. seq_number: LOCAL_SEQ + 1,
  6340. ack_number: Some(REMOTE_SEQ + 1 + 9),
  6341. window_len: 55,
  6342. ..RECV_TEMPL
  6343. })
  6344. );
  6345. }
  6346. // =========================================================================================//
  6347. // Tests for Nagle's Algorithm
  6348. // =========================================================================================//
  6349. #[test]
  6350. fn test_nagle() {
  6351. let mut s = socket_established();
  6352. s.remote_mss = 6;
  6353. s.send_slice(b"abcdef").unwrap();
  6354. recv!(
  6355. s,
  6356. [TcpRepr {
  6357. seq_number: LOCAL_SEQ + 1,
  6358. ack_number: Some(REMOTE_SEQ + 1),
  6359. payload: &b"abcdef"[..],
  6360. ..RECV_TEMPL
  6361. }]
  6362. );
  6363. // If there's data in flight, full segments get sent.
  6364. s.send_slice(b"foobar").unwrap();
  6365. recv!(
  6366. s,
  6367. [TcpRepr {
  6368. seq_number: LOCAL_SEQ + 1 + 6,
  6369. ack_number: Some(REMOTE_SEQ + 1),
  6370. payload: &b"foobar"[..],
  6371. ..RECV_TEMPL
  6372. }]
  6373. );
  6374. s.send_slice(b"aaabbbccc").unwrap();
  6375. // If there's data in flight, not-full segments don't get sent.
  6376. recv!(
  6377. s,
  6378. [TcpRepr {
  6379. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  6380. ack_number: Some(REMOTE_SEQ + 1),
  6381. payload: &b"aaabbb"[..],
  6382. ..RECV_TEMPL
  6383. }]
  6384. );
  6385. // Data gets ACKd, so there's no longer data in flight
  6386. send!(
  6387. s,
  6388. TcpRepr {
  6389. seq_number: REMOTE_SEQ + 1,
  6390. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6 + 6),
  6391. ..SEND_TEMPL
  6392. }
  6393. );
  6394. // Now non-full segment gets sent.
  6395. recv!(
  6396. s,
  6397. [TcpRepr {
  6398. seq_number: LOCAL_SEQ + 1 + 6 + 6 + 6,
  6399. ack_number: Some(REMOTE_SEQ + 1),
  6400. payload: &b"ccc"[..],
  6401. ..RECV_TEMPL
  6402. }]
  6403. );
  6404. }
  6405. // =========================================================================================//
  6406. // Tests for packet filtering.
  6407. // =========================================================================================//
  6408. #[test]
  6409. fn test_doesnt_accept_wrong_port() {
  6410. let mut s = socket_established();
  6411. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  6412. s.assembler = Assembler::new(s.rx_buffer.capacity());
  6413. let tcp_repr = TcpRepr {
  6414. seq_number: REMOTE_SEQ + 1,
  6415. ack_number: Some(LOCAL_SEQ + 1),
  6416. dst_port: LOCAL_PORT + 1,
  6417. ..SEND_TEMPL
  6418. };
  6419. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  6420. let tcp_repr = TcpRepr {
  6421. seq_number: REMOTE_SEQ + 1,
  6422. ack_number: Some(LOCAL_SEQ + 1),
  6423. src_port: REMOTE_PORT + 1,
  6424. ..SEND_TEMPL
  6425. };
  6426. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  6427. }
  6428. #[test]
  6429. fn test_doesnt_accept_wrong_ip() {
  6430. let s = socket_established();
  6431. let tcp_repr = TcpRepr {
  6432. seq_number: REMOTE_SEQ + 1,
  6433. ack_number: Some(LOCAL_SEQ + 1),
  6434. payload: &b"abcdef"[..],
  6435. ..SEND_TEMPL
  6436. };
  6437. let ip_repr = IpRepr::Unspecified {
  6438. src_addr: MOCK_IP_ADDR_2,
  6439. dst_addr: MOCK_IP_ADDR_1,
  6440. protocol: IpProtocol::Tcp,
  6441. payload_len: tcp_repr.buffer_len(),
  6442. hop_limit: 64,
  6443. };
  6444. assert!(s.accepts(&ip_repr, &tcp_repr));
  6445. let ip_repr_wrong_src = IpRepr::Unspecified {
  6446. src_addr: MOCK_IP_ADDR_3,
  6447. dst_addr: MOCK_IP_ADDR_1,
  6448. protocol: IpProtocol::Tcp,
  6449. payload_len: tcp_repr.buffer_len(),
  6450. hop_limit: 64,
  6451. };
  6452. assert!(!s.accepts(&ip_repr_wrong_src, &tcp_repr));
  6453. let ip_repr_wrong_dst = IpRepr::Unspecified {
  6454. src_addr: MOCK_IP_ADDR_2,
  6455. dst_addr: MOCK_IP_ADDR_3,
  6456. protocol: IpProtocol::Tcp,
  6457. payload_len: tcp_repr.buffer_len(),
  6458. hop_limit: 64,
  6459. };
  6460. assert!(!s.accepts(&ip_repr_wrong_dst, &tcp_repr));
  6461. }
  6462. // =========================================================================================//
  6463. // Timer tests
  6464. // =========================================================================================//
  6465. #[test]
  6466. fn test_timer_retransmit() {
  6467. const RTO: Duration = Duration::from_millis(100);
  6468. let mut r = Timer::new();
  6469. assert_eq!(r.should_retransmit(Instant::from_secs(1)), None);
  6470. r.set_for_retransmit(Instant::from_millis(1000), RTO);
  6471. assert_eq!(r.should_retransmit(Instant::from_millis(1000)), None);
  6472. assert_eq!(r.should_retransmit(Instant::from_millis(1050)), None);
  6473. assert_eq!(
  6474. r.should_retransmit(Instant::from_millis(1101)),
  6475. Some(Duration::from_millis(101))
  6476. );
  6477. r.set_for_retransmit(Instant::from_millis(1101), RTO);
  6478. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), None);
  6479. assert_eq!(r.should_retransmit(Instant::from_millis(1150)), None);
  6480. assert_eq!(r.should_retransmit(Instant::from_millis(1200)), None);
  6481. assert_eq!(
  6482. r.should_retransmit(Instant::from_millis(1301)),
  6483. Some(Duration::from_millis(300))
  6484. );
  6485. r.set_for_idle(Instant::from_millis(1301), None);
  6486. assert_eq!(r.should_retransmit(Instant::from_millis(1350)), None);
  6487. }
  6488. #[test]
  6489. fn test_rtt_estimator() {
  6490. let mut r = RttEstimator::default();
  6491. let rtos = &[
  6492. 751, 766, 755, 731, 697, 656, 613, 567, 523, 484, 445, 411, 378, 350, 322, 299, 280,
  6493. 261, 243, 229, 215, 206, 197, 188,
  6494. ];
  6495. for &rto in rtos {
  6496. r.sample(100);
  6497. assert_eq!(r.retransmission_timeout(), Duration::from_millis(rto));
  6498. }
  6499. }
  6500. }