tcp.rs 234 KB

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