tcp.rs 197 KB

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