tcp.rs 192 KB

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