tcp.rs 229 KB

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