tcp.rs 228 KB

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