tcp.rs 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380
  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. pub(crate) fn poll_at(&self) -> PollAt {
  1711. // The logic here mirrors the beginning of dispatch() closely.
  1712. if !self.remote_endpoint.is_specified() {
  1713. // No one to talk to, nothing to transmit.
  1714. PollAt::Ingress
  1715. } else if self.remote_last_ts.is_none() {
  1716. // Socket stopped being quiet recently, we need to acquire a timestamp.
  1717. PollAt::Now
  1718. } else if self.state == State::Closed {
  1719. // Socket was aborted, we have an RST packet to transmit.
  1720. PollAt::Now
  1721. } else if self.seq_to_transmit() {
  1722. // We have a data or flag packet to transmit.
  1723. PollAt::Now
  1724. } else {
  1725. let want_ack = self.ack_to_transmit() || self.window_to_update();
  1726. let delayed_ack_poll_at = match (want_ack, self.ack_delay_until) {
  1727. (false, _) => PollAt::Ingress,
  1728. (true, None) => PollAt::Now,
  1729. (true, Some(t)) => PollAt::Time(t),
  1730. };
  1731. let timeout_poll_at = match (self.remote_last_ts, self.timeout) {
  1732. // If we're transmitting or retransmitting data, we need to poll at the moment
  1733. // when the timeout would expire.
  1734. (Some(remote_last_ts), Some(timeout)) => PollAt::Time(remote_last_ts + timeout),
  1735. // Otherwise we have no timeout.
  1736. (_, _) => PollAt::Ingress,
  1737. };
  1738. // We wait for the earliest of our timers to fire.
  1739. *[self.timer.poll_at(), timeout_poll_at, delayed_ack_poll_at]
  1740. .iter()
  1741. .min().unwrap_or(&PollAt::Ingress)
  1742. }
  1743. }
  1744. }
  1745. impl<'a, 'b> Into<Socket<'a, 'b>> for TcpSocket<'a> {
  1746. fn into(self) -> Socket<'a, 'b> {
  1747. Socket::Tcp(self)
  1748. }
  1749. }
  1750. impl<'a> fmt::Write for TcpSocket<'a> {
  1751. fn write_str(&mut self, slice: &str) -> fmt::Result {
  1752. let slice = slice.as_bytes();
  1753. if self.send_slice(slice) == Ok(slice.len()) {
  1754. Ok(())
  1755. } else {
  1756. Err(fmt::Error)
  1757. }
  1758. }
  1759. }
  1760. #[cfg(test)]
  1761. mod test {
  1762. use core::i32;
  1763. use std::vec::Vec;
  1764. use crate::wire::{IpAddress, IpRepr, IpCidr};
  1765. use crate::wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3, MOCK_UNSPECIFIED};
  1766. use super::*;
  1767. // =========================================================================================//
  1768. // Constants
  1769. // =========================================================================================//
  1770. const LOCAL_PORT: u16 = 80;
  1771. const REMOTE_PORT: u16 = 49500;
  1772. const LOCAL_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_1, port: LOCAL_PORT };
  1773. const REMOTE_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_2, port: REMOTE_PORT };
  1774. const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
  1775. const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10000);
  1776. const SEND_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1777. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1778. protocol: IpProtocol::Tcp, payload_len: 20,
  1779. hop_limit: 64
  1780. };
  1781. const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
  1782. src_port: REMOTE_PORT, dst_port: LOCAL_PORT,
  1783. control: TcpControl::None,
  1784. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1785. window_len: 256, window_scale: None,
  1786. max_seg_size: None,
  1787. sack_permitted: false,
  1788. sack_ranges: [None, None, None],
  1789. payload: &[]
  1790. };
  1791. const _RECV_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1792. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1793. protocol: IpProtocol::Tcp, payload_len: 20,
  1794. hop_limit: 64
  1795. };
  1796. const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
  1797. src_port: LOCAL_PORT, dst_port: REMOTE_PORT,
  1798. control: TcpControl::None,
  1799. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1800. window_len: 64, window_scale: None,
  1801. max_seg_size: None,
  1802. sack_permitted: false,
  1803. sack_ranges: [None, None, None],
  1804. payload: &[]
  1805. };
  1806. #[cfg(feature = "proto-ipv6")]
  1807. const BASE_MSS: u16 = 1460;
  1808. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1809. const BASE_MSS: u16 = 1480;
  1810. // =========================================================================================//
  1811. // Helper functions
  1812. // =========================================================================================//
  1813. fn send(socket: &mut TcpSocket, timestamp: Instant, repr: &TcpRepr) ->
  1814. Result<Option<TcpRepr<'static>>> {
  1815. let ip_repr = IpRepr::Unspecified {
  1816. src_addr: MOCK_IP_ADDR_2,
  1817. dst_addr: MOCK_IP_ADDR_1,
  1818. protocol: IpProtocol::Tcp,
  1819. payload_len: repr.buffer_len(),
  1820. hop_limit: 64
  1821. };
  1822. net_trace!("send: {}", repr);
  1823. assert!(socket.accepts(&ip_repr, repr));
  1824. match socket.process(timestamp, &ip_repr, repr) {
  1825. Ok(Some((_ip_repr, repr))) => {
  1826. net_trace!("recv: {}", repr);
  1827. Ok(Some(repr))
  1828. }
  1829. Ok(None) => Ok(None),
  1830. Err(err) => Err(err)
  1831. }
  1832. }
  1833. fn recv<F>(socket: &mut TcpSocket, timestamp: Instant, mut f: F)
  1834. where F: FnMut(Result<TcpRepr>) {
  1835. let caps = DeviceCapabilities {
  1836. max_transmission_unit: 1520,
  1837. ..Default::default()
  1838. };
  1839. let result = socket.dispatch(timestamp, &caps, |(ip_repr, tcp_repr)| {
  1840. let ip_repr = ip_repr.lower(&[IpCidr::new(LOCAL_END.addr, 24)]).unwrap();
  1841. assert_eq!(ip_repr.protocol(), IpProtocol::Tcp);
  1842. assert_eq!(ip_repr.src_addr(), MOCK_IP_ADDR_1);
  1843. assert_eq!(ip_repr.dst_addr(), MOCK_IP_ADDR_2);
  1844. assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
  1845. net_trace!("recv: {}", tcp_repr);
  1846. Ok(f(Ok(tcp_repr)))
  1847. });
  1848. match result {
  1849. Ok(()) => (),
  1850. Err(e) => f(Err(e))
  1851. }
  1852. }
  1853. macro_rules! send {
  1854. ($socket:ident, $repr:expr) =>
  1855. (send!($socket, time 0, $repr));
  1856. ($socket:ident, $repr:expr, $result:expr) =>
  1857. (send!($socket, time 0, $repr, $result));
  1858. ($socket:ident, time $time:expr, $repr:expr) =>
  1859. (send!($socket, time $time, $repr, Ok(None)));
  1860. ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
  1861. (assert_eq!(send(&mut $socket, Instant::from_millis($time), &$repr), $result));
  1862. }
  1863. macro_rules! recv {
  1864. ($socket:ident, [$( $repr:expr ),*]) => ({
  1865. $( recv!($socket, Ok($repr)); )*
  1866. recv!($socket, Err(Error::Exhausted))
  1867. });
  1868. ($socket:ident, $result:expr) =>
  1869. (recv!($socket, time 0, $result));
  1870. ($socket:ident, time $time:expr, $result:expr) =>
  1871. (recv(&mut $socket, Instant::from_millis($time), |result| {
  1872. // Most of the time we don't care about the PSH flag.
  1873. let result = result.map(|mut repr| {
  1874. repr.control = repr.control.quash_psh();
  1875. repr
  1876. });
  1877. assert_eq!(result, $result)
  1878. }));
  1879. ($socket:ident, time $time:expr, $result:expr, exact) =>
  1880. (recv(&mut $socket, Instant::from_millis($time), |repr| assert_eq!(repr, $result)));
  1881. }
  1882. macro_rules! sanity {
  1883. ($socket1:expr, $socket2:expr) => ({
  1884. let (s1, s2) = ($socket1, $socket2);
  1885. assert_eq!(s1.state, s2.state, "state");
  1886. assert_eq!(s1.listen_address, s2.listen_address, "listen_address");
  1887. assert_eq!(s1.local_endpoint, s2.local_endpoint, "local_endpoint");
  1888. assert_eq!(s1.remote_endpoint, s2.remote_endpoint, "remote_endpoint");
  1889. assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
  1890. assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
  1891. assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
  1892. assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
  1893. assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
  1894. assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
  1895. assert_eq!(s1.timer, s2.timer, "timer");
  1896. })
  1897. }
  1898. #[cfg(feature = "log")]
  1899. fn init_logger() {
  1900. struct Logger;
  1901. static LOGGER: Logger = Logger;
  1902. impl log::Log for Logger {
  1903. fn enabled(&self, _metadata: &log::Metadata) -> bool {
  1904. true
  1905. }
  1906. fn log(&self, record: &log::Record) {
  1907. println!("{}", record.args());
  1908. }
  1909. fn flush(&self) {
  1910. }
  1911. }
  1912. // If it fails, that just means we've already set it to the same value.
  1913. let _ = log::set_logger(&LOGGER);
  1914. log::set_max_level(log::LevelFilter::Trace);
  1915. println!();
  1916. }
  1917. fn socket() -> TcpSocket<'static> {
  1918. socket_with_buffer_sizes(64, 64)
  1919. }
  1920. fn socket_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  1921. #[cfg(feature = "log")]
  1922. init_logger();
  1923. let rx_buffer = SocketBuffer::new(vec![0; rx_len]);
  1924. let tx_buffer = SocketBuffer::new(vec![0; tx_len]);
  1925. let mut socket = TcpSocket::new(rx_buffer, tx_buffer);
  1926. socket.set_ack_delay(None);
  1927. socket
  1928. }
  1929. fn socket_syn_received_with_buffer_sizes(
  1930. tx_len: usize,
  1931. rx_len: usize
  1932. ) -> TcpSocket<'static> {
  1933. let mut s = socket_with_buffer_sizes(tx_len, rx_len);
  1934. s.state = State::SynReceived;
  1935. s.local_endpoint = LOCAL_END;
  1936. s.remote_endpoint = REMOTE_END;
  1937. s.local_seq_no = LOCAL_SEQ;
  1938. s.remote_seq_no = REMOTE_SEQ + 1;
  1939. s.remote_last_seq = LOCAL_SEQ;
  1940. s.remote_win_len = 256;
  1941. s
  1942. }
  1943. fn socket_syn_received() -> TcpSocket<'static> {
  1944. socket_syn_received_with_buffer_sizes(64, 64)
  1945. }
  1946. fn socket_syn_sent() -> TcpSocket<'static> {
  1947. let mut s = socket();
  1948. s.state = State::SynSent;
  1949. s.local_endpoint = IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_PORT);
  1950. s.remote_endpoint = REMOTE_END;
  1951. s.local_seq_no = LOCAL_SEQ;
  1952. s.remote_last_seq = LOCAL_SEQ;
  1953. s
  1954. }
  1955. fn socket_syn_sent_with_local_ipendpoint(local: IpEndpoint) -> TcpSocket<'static> {
  1956. let mut s = socket();
  1957. s.state = State::SynSent;
  1958. s.local_endpoint = local;
  1959. s.remote_endpoint = REMOTE_END;
  1960. s.local_seq_no = LOCAL_SEQ;
  1961. s.remote_last_seq = LOCAL_SEQ;
  1962. s
  1963. }
  1964. fn socket_established_with_buffer_sizes(tx_len: usize, rx_len: usize) -> TcpSocket<'static> {
  1965. let mut s = socket_syn_received_with_buffer_sizes(tx_len, rx_len);
  1966. s.state = State::Established;
  1967. s.local_seq_no = LOCAL_SEQ + 1;
  1968. s.remote_last_seq = LOCAL_SEQ + 1;
  1969. s.remote_last_ack = Some(REMOTE_SEQ + 1);
  1970. s.remote_last_win = 64;
  1971. s
  1972. }
  1973. fn socket_established() -> TcpSocket<'static> {
  1974. socket_established_with_buffer_sizes(64, 64)
  1975. }
  1976. fn socket_fin_wait_1() -> TcpSocket<'static> {
  1977. let mut s = socket_established();
  1978. s.state = State::FinWait1;
  1979. s
  1980. }
  1981. fn socket_fin_wait_2() -> TcpSocket<'static> {
  1982. let mut s = socket_fin_wait_1();
  1983. s.state = State::FinWait2;
  1984. s.local_seq_no = LOCAL_SEQ + 1 + 1;
  1985. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1986. s
  1987. }
  1988. fn socket_closing() -> TcpSocket<'static> {
  1989. let mut s = socket_fin_wait_1();
  1990. s.state = State::Closing;
  1991. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1992. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1993. s
  1994. }
  1995. fn socket_time_wait(from_closing: bool) -> TcpSocket<'static> {
  1996. let mut s = socket_fin_wait_2();
  1997. s.state = State::TimeWait;
  1998. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1999. if from_closing {
  2000. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2001. }
  2002. s.timer = Timer::Close { expires_at: Instant::from_secs(1) + CLOSE_DELAY };
  2003. s
  2004. }
  2005. fn socket_close_wait() -> TcpSocket<'static> {
  2006. let mut s = socket_established();
  2007. s.state = State::CloseWait;
  2008. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  2009. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  2010. s
  2011. }
  2012. fn socket_last_ack() -> TcpSocket<'static> {
  2013. let mut s = socket_close_wait();
  2014. s.state = State::LastAck;
  2015. s
  2016. }
  2017. fn socket_recved() -> TcpSocket<'static> {
  2018. let mut s = socket_established();
  2019. send!(s, TcpRepr {
  2020. seq_number: REMOTE_SEQ + 1,
  2021. ack_number: Some(LOCAL_SEQ + 1),
  2022. payload: &b"abcdef"[..],
  2023. ..SEND_TEMPL
  2024. });
  2025. recv!(s, [TcpRepr {
  2026. seq_number: LOCAL_SEQ + 1,
  2027. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2028. window_len: 58,
  2029. ..RECV_TEMPL
  2030. }]);
  2031. s
  2032. }
  2033. // =========================================================================================//
  2034. // Tests for the CLOSED state.
  2035. // =========================================================================================//
  2036. #[test]
  2037. fn test_closed_reject() {
  2038. let s = socket();
  2039. assert_eq!(s.state, State::Closed);
  2040. let tcp_repr = TcpRepr {
  2041. control: TcpControl::Syn,
  2042. ..SEND_TEMPL
  2043. };
  2044. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2045. }
  2046. #[test]
  2047. fn test_closed_reject_after_listen() {
  2048. let mut s = socket();
  2049. s.listen(LOCAL_END).unwrap();
  2050. s.close();
  2051. let tcp_repr = TcpRepr {
  2052. control: TcpControl::Syn,
  2053. ..SEND_TEMPL
  2054. };
  2055. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2056. }
  2057. #[test]
  2058. fn test_closed_close() {
  2059. let mut s = socket();
  2060. s.close();
  2061. assert_eq!(s.state, State::Closed);
  2062. }
  2063. // =========================================================================================//
  2064. // Tests for the LISTEN state.
  2065. // =========================================================================================//
  2066. fn socket_listen() -> TcpSocket<'static> {
  2067. let mut s = socket();
  2068. s.state = State::Listen;
  2069. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  2070. s
  2071. }
  2072. #[test]
  2073. fn test_listen_sack_option() {
  2074. let mut s = socket_listen();
  2075. send!(s, TcpRepr {
  2076. control: TcpControl::Syn,
  2077. seq_number: REMOTE_SEQ,
  2078. ack_number: None,
  2079. sack_permitted: false,
  2080. ..SEND_TEMPL
  2081. });
  2082. assert!(!s.remote_has_sack);
  2083. recv!(s, [TcpRepr {
  2084. control: TcpControl::Syn,
  2085. seq_number: LOCAL_SEQ,
  2086. ack_number: Some(REMOTE_SEQ + 1),
  2087. max_seg_size: Some(BASE_MSS),
  2088. ..RECV_TEMPL
  2089. }]);
  2090. let mut s = socket_listen();
  2091. send!(s, TcpRepr {
  2092. control: TcpControl::Syn,
  2093. seq_number: REMOTE_SEQ,
  2094. ack_number: None,
  2095. sack_permitted: true,
  2096. ..SEND_TEMPL
  2097. });
  2098. assert!(s.remote_has_sack);
  2099. recv!(s, [TcpRepr {
  2100. control: TcpControl::Syn,
  2101. seq_number: LOCAL_SEQ,
  2102. ack_number: Some(REMOTE_SEQ + 1),
  2103. max_seg_size: Some(BASE_MSS),
  2104. sack_permitted: true,
  2105. ..RECV_TEMPL
  2106. }]);
  2107. }
  2108. #[test]
  2109. fn test_listen_syn_win_scale_buffers() {
  2110. for (buffer_size, shift_amt) in &[
  2111. (64, 0),
  2112. (128, 0),
  2113. (1024, 0),
  2114. (65535, 0),
  2115. (65536, 1),
  2116. (65537, 1),
  2117. (131071, 1),
  2118. (131072, 2),
  2119. (524287, 3),
  2120. (524288, 4),
  2121. (655350, 4),
  2122. (1048576, 5),
  2123. ] {
  2124. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  2125. s.state = State::Listen;
  2126. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  2127. assert_eq!(s.remote_win_shift, *shift_amt);
  2128. send!(s, TcpRepr {
  2129. control: TcpControl::Syn,
  2130. seq_number: REMOTE_SEQ,
  2131. ack_number: None,
  2132. window_scale: Some(0),
  2133. ..SEND_TEMPL
  2134. });
  2135. assert_eq!(s.remote_win_shift, *shift_amt);
  2136. recv!(s, [TcpRepr {
  2137. control: TcpControl::Syn,
  2138. seq_number: LOCAL_SEQ,
  2139. ack_number: Some(REMOTE_SEQ + 1),
  2140. max_seg_size: Some(BASE_MSS),
  2141. window_scale: Some(*shift_amt),
  2142. window_len: cmp::min(*buffer_size >> *shift_amt, 65535) as u16,
  2143. ..RECV_TEMPL
  2144. }]);
  2145. }
  2146. }
  2147. #[test]
  2148. fn test_listen_sanity() {
  2149. let mut s = socket();
  2150. s.listen(LOCAL_PORT).unwrap();
  2151. sanity!(s, socket_listen());
  2152. }
  2153. #[test]
  2154. fn test_listen_validation() {
  2155. let mut s = socket();
  2156. assert_eq!(s.listen(0), Err(Error::Unaddressable));
  2157. }
  2158. #[test]
  2159. fn test_listen_twice() {
  2160. let mut s = socket();
  2161. assert_eq!(s.listen(80), Ok(()));
  2162. assert_eq!(s.listen(80), Err(Error::Illegal));
  2163. }
  2164. #[test]
  2165. fn test_listen_syn() {
  2166. let mut s = socket_listen();
  2167. send!(s, TcpRepr {
  2168. control: TcpControl::Syn,
  2169. seq_number: REMOTE_SEQ,
  2170. ack_number: None,
  2171. ..SEND_TEMPL
  2172. });
  2173. sanity!(s, socket_syn_received());
  2174. }
  2175. #[test]
  2176. fn test_listen_syn_reject_ack() {
  2177. let s = socket_listen();
  2178. let tcp_repr = TcpRepr {
  2179. control: TcpControl::Syn,
  2180. seq_number: REMOTE_SEQ,
  2181. ack_number: Some(LOCAL_SEQ),
  2182. ..SEND_TEMPL
  2183. };
  2184. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  2185. assert_eq!(s.state, State::Listen);
  2186. }
  2187. #[test]
  2188. fn test_listen_rst() {
  2189. let mut s = socket_listen();
  2190. send!(s, TcpRepr {
  2191. control: TcpControl::Rst,
  2192. seq_number: REMOTE_SEQ,
  2193. ack_number: None,
  2194. ..SEND_TEMPL
  2195. }, Err(Error::Dropped));
  2196. }
  2197. #[test]
  2198. fn test_listen_close() {
  2199. let mut s = socket_listen();
  2200. s.close();
  2201. assert_eq!(s.state, State::Closed);
  2202. }
  2203. // =========================================================================================//
  2204. // Tests for the SYN-RECEIVED state.
  2205. // =========================================================================================//
  2206. #[test]
  2207. fn test_syn_received_ack() {
  2208. let mut s = socket_syn_received();
  2209. recv!(s, [TcpRepr {
  2210. control: TcpControl::Syn,
  2211. seq_number: LOCAL_SEQ,
  2212. ack_number: Some(REMOTE_SEQ + 1),
  2213. max_seg_size: Some(BASE_MSS),
  2214. ..RECV_TEMPL
  2215. }]);
  2216. send!(s, TcpRepr {
  2217. seq_number: REMOTE_SEQ + 1,
  2218. ack_number: Some(LOCAL_SEQ + 1),
  2219. ..SEND_TEMPL
  2220. });
  2221. assert_eq!(s.state, State::Established);
  2222. sanity!(s, socket_established());
  2223. }
  2224. #[test]
  2225. fn test_syn_received_fin() {
  2226. let mut s = socket_syn_received();
  2227. recv!(s, [TcpRepr {
  2228. control: TcpControl::Syn,
  2229. seq_number: LOCAL_SEQ,
  2230. ack_number: Some(REMOTE_SEQ + 1),
  2231. max_seg_size: Some(BASE_MSS),
  2232. ..RECV_TEMPL
  2233. }]);
  2234. send!(s, TcpRepr {
  2235. control: TcpControl::Fin,
  2236. seq_number: REMOTE_SEQ + 1,
  2237. ack_number: Some(LOCAL_SEQ + 1),
  2238. payload: &b"abcdef"[..],
  2239. ..SEND_TEMPL
  2240. });
  2241. recv!(s, [TcpRepr {
  2242. seq_number: LOCAL_SEQ + 1,
  2243. ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
  2244. window_len: 58,
  2245. ..RECV_TEMPL
  2246. }]);
  2247. assert_eq!(s.state, State::CloseWait);
  2248. sanity!(s, TcpSocket {
  2249. remote_last_ack: Some(REMOTE_SEQ + 1 + 6 + 1),
  2250. remote_last_win: 58,
  2251. ..socket_close_wait()
  2252. });
  2253. }
  2254. #[test]
  2255. fn test_syn_received_rst() {
  2256. let mut s = socket_syn_received();
  2257. recv!(s, [TcpRepr {
  2258. control: TcpControl::Syn,
  2259. seq_number: LOCAL_SEQ,
  2260. ack_number: Some(REMOTE_SEQ + 1),
  2261. max_seg_size: Some(BASE_MSS),
  2262. ..RECV_TEMPL
  2263. }]);
  2264. send!(s, TcpRepr {
  2265. control: TcpControl::Rst,
  2266. seq_number: REMOTE_SEQ + 1,
  2267. ack_number: Some(LOCAL_SEQ),
  2268. ..SEND_TEMPL
  2269. });
  2270. assert_eq!(s.state, State::Listen);
  2271. assert_eq!(s.local_endpoint, IpEndpoint::new(IpAddress::Unspecified, LOCAL_END.port));
  2272. assert_eq!(s.remote_endpoint, IpEndpoint::default());
  2273. }
  2274. #[test]
  2275. fn test_syn_received_no_window_scaling() {
  2276. let mut s = socket_listen();
  2277. send!(s, TcpRepr {
  2278. control: TcpControl::Syn,
  2279. seq_number: REMOTE_SEQ,
  2280. ack_number: None,
  2281. ..SEND_TEMPL
  2282. });
  2283. assert_eq!(s.state(), State::SynReceived);
  2284. assert_eq!(s.local_endpoint(), LOCAL_END);
  2285. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2286. recv!(s, [TcpRepr {
  2287. control: TcpControl::Syn,
  2288. seq_number: LOCAL_SEQ,
  2289. ack_number: Some(REMOTE_SEQ + 1),
  2290. max_seg_size: Some(BASE_MSS),
  2291. window_scale: None,
  2292. ..RECV_TEMPL
  2293. }]);
  2294. send!(s, TcpRepr {
  2295. seq_number: REMOTE_SEQ + 1,
  2296. ack_number: Some(LOCAL_SEQ + 1),
  2297. window_scale: None,
  2298. ..SEND_TEMPL
  2299. });
  2300. assert_eq!(s.remote_win_scale, None);
  2301. }
  2302. #[test]
  2303. fn test_syn_received_window_scaling() {
  2304. for scale in 0..14 {
  2305. let mut s = socket_listen();
  2306. send!(s, TcpRepr {
  2307. control: TcpControl::Syn,
  2308. seq_number: REMOTE_SEQ,
  2309. ack_number: None,
  2310. window_scale: Some(scale),
  2311. ..SEND_TEMPL
  2312. });
  2313. assert_eq!(s.state(), State::SynReceived);
  2314. assert_eq!(s.local_endpoint(), LOCAL_END);
  2315. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2316. recv!(s, [TcpRepr {
  2317. control: TcpControl::Syn,
  2318. seq_number: LOCAL_SEQ,
  2319. ack_number: Some(REMOTE_SEQ + 1),
  2320. max_seg_size: Some(BASE_MSS),
  2321. window_scale: Some(0),
  2322. ..RECV_TEMPL
  2323. }]);
  2324. send!(s, TcpRepr {
  2325. seq_number: REMOTE_SEQ + 1,
  2326. ack_number: Some(LOCAL_SEQ + 1),
  2327. window_scale: None,
  2328. ..SEND_TEMPL
  2329. });
  2330. assert_eq!(s.remote_win_scale, Some(scale));
  2331. }
  2332. }
  2333. #[test]
  2334. fn test_syn_received_close() {
  2335. let mut s = socket_syn_received();
  2336. s.close();
  2337. assert_eq!(s.state, State::FinWait1);
  2338. }
  2339. // =========================================================================================//
  2340. // Tests for the SYN-SENT state.
  2341. // =========================================================================================//
  2342. #[test]
  2343. fn test_connect_validation() {
  2344. let mut s = socket();
  2345. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2346. Err(Error::Unaddressable));
  2347. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 0)),
  2348. Err(Error::Unaddressable));
  2349. assert_eq!(s.connect((MOCK_UNSPECIFIED, 0), LOCAL_END),
  2350. Err(Error::Unaddressable));
  2351. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  2352. Err(Error::Unaddressable));
  2353. s.connect(REMOTE_END, LOCAL_END).expect("Connect failed with valid parameters");
  2354. assert_eq!(s.local_endpoint(), LOCAL_END);
  2355. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2356. }
  2357. #[test]
  2358. fn test_connect() {
  2359. let mut s = socket();
  2360. s.local_seq_no = LOCAL_SEQ;
  2361. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  2362. assert_eq!(s.local_endpoint, IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_END.port));
  2363. recv!(s, [TcpRepr {
  2364. control: TcpControl::Syn,
  2365. seq_number: LOCAL_SEQ,
  2366. ack_number: None,
  2367. max_seg_size: Some(BASE_MSS),
  2368. window_scale: Some(0),
  2369. sack_permitted: true,
  2370. ..RECV_TEMPL
  2371. }]);
  2372. send!(s, TcpRepr {
  2373. control: TcpControl::Syn,
  2374. seq_number: REMOTE_SEQ,
  2375. ack_number: Some(LOCAL_SEQ + 1),
  2376. max_seg_size: Some(BASE_MSS - 80),
  2377. window_scale: Some(0),
  2378. ..SEND_TEMPL
  2379. });
  2380. assert_eq!(s.local_endpoint, LOCAL_END);
  2381. }
  2382. #[test]
  2383. fn test_connect_unspecified_local() {
  2384. let mut s = socket();
  2385. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 80)),
  2386. Ok(()));
  2387. s.abort();
  2388. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2389. Ok(()));
  2390. s.abort();
  2391. }
  2392. #[test]
  2393. fn test_connect_specified_local() {
  2394. let mut s = socket();
  2395. assert_eq!(s.connect(REMOTE_END, (MOCK_IP_ADDR_2, 80)),
  2396. Ok(()));
  2397. }
  2398. #[test]
  2399. fn test_connect_twice() {
  2400. let mut s = socket();
  2401. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2402. Ok(()));
  2403. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  2404. Err(Error::Illegal));
  2405. }
  2406. #[test]
  2407. fn test_syn_sent_sanity() {
  2408. let mut s = socket();
  2409. s.local_seq_no = LOCAL_SEQ;
  2410. s.connect(REMOTE_END, LOCAL_END).unwrap();
  2411. sanity!(s, socket_syn_sent_with_local_ipendpoint(LOCAL_END));
  2412. }
  2413. #[test]
  2414. fn test_syn_sent_syn_ack() {
  2415. let mut s = socket_syn_sent();
  2416. recv!(s, [TcpRepr {
  2417. control: TcpControl::Syn,
  2418. seq_number: LOCAL_SEQ,
  2419. ack_number: None,
  2420. max_seg_size: Some(BASE_MSS),
  2421. window_scale: Some(0),
  2422. sack_permitted: true,
  2423. ..RECV_TEMPL
  2424. }]);
  2425. send!(s, TcpRepr {
  2426. control: TcpControl::Syn,
  2427. seq_number: REMOTE_SEQ,
  2428. ack_number: Some(LOCAL_SEQ + 1),
  2429. max_seg_size: Some(BASE_MSS - 80),
  2430. window_scale: Some(0),
  2431. ..SEND_TEMPL
  2432. });
  2433. recv!(s, [TcpRepr {
  2434. seq_number: LOCAL_SEQ + 1,
  2435. ack_number: Some(REMOTE_SEQ + 1),
  2436. ..RECV_TEMPL
  2437. }]);
  2438. recv!(s, time 1000, Err(Error::Exhausted));
  2439. assert_eq!(s.state, State::Established);
  2440. sanity!(s, socket_established());
  2441. }
  2442. #[test]
  2443. fn test_syn_sent_rst() {
  2444. let mut s = socket_syn_sent();
  2445. send!(s, TcpRepr {
  2446. control: TcpControl::Rst,
  2447. seq_number: REMOTE_SEQ,
  2448. ack_number: Some(LOCAL_SEQ + 1),
  2449. ..SEND_TEMPL
  2450. });
  2451. assert_eq!(s.state, State::Closed);
  2452. }
  2453. #[test]
  2454. fn test_syn_sent_rst_no_ack() {
  2455. let mut s = socket_syn_sent();
  2456. send!(s, TcpRepr {
  2457. control: TcpControl::Rst,
  2458. seq_number: REMOTE_SEQ,
  2459. ack_number: None,
  2460. ..SEND_TEMPL
  2461. }, Err(Error::Dropped));
  2462. assert_eq!(s.state, State::SynSent);
  2463. }
  2464. #[test]
  2465. fn test_syn_sent_rst_bad_ack() {
  2466. let mut s = socket_syn_sent();
  2467. send!(s, TcpRepr {
  2468. control: TcpControl::Rst,
  2469. seq_number: REMOTE_SEQ,
  2470. ack_number: Some(TcpSeqNumber(1234)),
  2471. ..SEND_TEMPL
  2472. }, Err(Error::Dropped));
  2473. assert_eq!(s.state, State::SynSent);
  2474. }
  2475. #[test]
  2476. fn test_syn_sent_bad_ack() {
  2477. let mut s = socket_syn_sent();
  2478. send!(s, TcpRepr {
  2479. control: TcpControl::None,
  2480. ack_number: Some(TcpSeqNumber(1)),
  2481. ..SEND_TEMPL
  2482. }, Err(Error::Dropped));
  2483. assert_eq!(s.state, State::Closed);
  2484. }
  2485. #[test]
  2486. fn test_syn_sent_close() {
  2487. let mut s = socket();
  2488. s.close();
  2489. assert_eq!(s.state, State::Closed);
  2490. }
  2491. #[test]
  2492. fn test_syn_sent_win_scale_buffers() {
  2493. for (buffer_size, shift_amt) in &[
  2494. (64, 0),
  2495. (128, 0),
  2496. (1024, 0),
  2497. (65535, 0),
  2498. (65536, 1),
  2499. (65537, 1),
  2500. (131071, 1),
  2501. (131072, 2),
  2502. (524287, 3),
  2503. (524288, 4),
  2504. (655350, 4),
  2505. (1048576, 5),
  2506. ] {
  2507. let mut s = socket_with_buffer_sizes(64, *buffer_size);
  2508. assert_eq!(s.remote_win_shift, *shift_amt);
  2509. s.connect(REMOTE_END, LOCAL_END).unwrap();
  2510. recv!(s, [TcpRepr {
  2511. control: TcpControl::Syn,
  2512. ack_number: None,
  2513. max_seg_size: Some(BASE_MSS),
  2514. window_scale: Some(*shift_amt),
  2515. window_len: cmp::min(*buffer_size >> *shift_amt, 65535) as u16,
  2516. sack_permitted: true,
  2517. ..RECV_TEMPL
  2518. }]);
  2519. }
  2520. }
  2521. // =========================================================================================//
  2522. // Tests for the ESTABLISHED state.
  2523. // =========================================================================================//
  2524. #[test]
  2525. fn test_established_recv() {
  2526. let mut s = socket_established();
  2527. send!(s, TcpRepr {
  2528. seq_number: REMOTE_SEQ + 1,
  2529. ack_number: Some(LOCAL_SEQ + 1),
  2530. payload: &b"abcdef"[..],
  2531. ..SEND_TEMPL
  2532. });
  2533. recv!(s, [TcpRepr {
  2534. seq_number: LOCAL_SEQ + 1,
  2535. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2536. window_len: 58,
  2537. ..RECV_TEMPL
  2538. }]);
  2539. assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
  2540. }
  2541. fn setup_rfc2018_cases() -> (TcpSocket<'static>, Vec<u8>) {
  2542. // This is a utility function used by the tests for RFC 2018 cases. It configures a socket
  2543. // in a particular way suitable for those cases.
  2544. //
  2545. // RFC 2018: Assume the left window edge is 5000 and that the data transmitter sends [...]
  2546. // segments, each containing 500 data bytes.
  2547. let mut s = socket_established_with_buffer_sizes(4000, 4000);
  2548. s.remote_has_sack = true;
  2549. // create a segment that is 500 bytes long
  2550. let mut segment: Vec<u8> = Vec::with_capacity(500);
  2551. // move the last ack to 5000 by sending ten of them
  2552. for _ in 0..50 { segment.extend_from_slice(b"abcdefghij") }
  2553. for offset in (0..5000).step_by(500) {
  2554. send!(s, TcpRepr {
  2555. seq_number: REMOTE_SEQ + 1 + offset,
  2556. ack_number: Some(LOCAL_SEQ + 1),
  2557. payload: &segment,
  2558. ..SEND_TEMPL
  2559. });
  2560. recv!(s, [TcpRepr {
  2561. seq_number: LOCAL_SEQ + 1,
  2562. ack_number: Some(REMOTE_SEQ + 1 + offset + 500),
  2563. window_len: 3500,
  2564. ..RECV_TEMPL
  2565. }]);
  2566. s.recv(|data| {
  2567. assert_eq!(data.len(), 500);
  2568. assert_eq!(data, segment.as_slice());
  2569. (500, ())
  2570. }).unwrap();
  2571. }
  2572. assert_eq!(s.remote_last_win, 3500);
  2573. (s, segment)
  2574. }
  2575. #[test]
  2576. fn test_established_rfc2018_cases() {
  2577. // This test case verifies the exact scenarios described on pages 8-9 of RFC 2018. Please
  2578. // ensure its behavior does not deviate from those scenarios.
  2579. let (mut s, segment) = setup_rfc2018_cases();
  2580. // RFC 2018:
  2581. //
  2582. // Case 2: The first segment is dropped but the remaining 7 are received.
  2583. //
  2584. // Upon receiving each of the last seven packets, the data receiver will return a TCP ACK
  2585. // segment that acknowledges sequence number 5000 and contains a SACK option specifying one
  2586. // block of queued data:
  2587. //
  2588. // Triggering ACK Left Edge Right Edge
  2589. // Segment
  2590. //
  2591. // 5000 (lost)
  2592. // 5500 5000 5500 6000
  2593. // 6000 5000 5500 6500
  2594. // 6500 5000 5500 7000
  2595. // 7000 5000 5500 7500
  2596. // 7500 5000 5500 8000
  2597. // 8000 5000 5500 8500
  2598. // 8500 5000 5500 9000
  2599. //
  2600. for offset in (500..3500).step_by(500) {
  2601. send!(s, TcpRepr {
  2602. seq_number: REMOTE_SEQ + 1 + offset + 5000,
  2603. ack_number: Some(LOCAL_SEQ + 1),
  2604. payload: &segment,
  2605. ..SEND_TEMPL
  2606. }, Ok(Some(TcpRepr {
  2607. seq_number: LOCAL_SEQ + 1,
  2608. ack_number: Some(REMOTE_SEQ + 1 + 5000),
  2609. window_len: 4000,
  2610. sack_ranges: [
  2611. Some((REMOTE_SEQ.0 as u32 + 1 + 5500,
  2612. REMOTE_SEQ.0 as u32 + 1 + 5500 + offset as u32)),
  2613. None, None],
  2614. ..RECV_TEMPL
  2615. })));
  2616. }
  2617. }
  2618. #[test]
  2619. fn test_established_sliding_window_recv() {
  2620. let mut s = socket_established();
  2621. // Update our scaling parameters for a TCP with a scaled buffer.
  2622. assert_eq!(s.rx_buffer.len(), 0);
  2623. s.rx_buffer = SocketBuffer::new(vec![0; 262143]);
  2624. s.assembler = Assembler::new(s.rx_buffer.capacity());
  2625. s.remote_win_scale = Some(0);
  2626. s.remote_last_win = 65535;
  2627. s.remote_win_shift = 2;
  2628. // Create a TCP segment that will mostly fill an IP frame.
  2629. let mut segment: Vec<u8> = Vec::with_capacity(1400);
  2630. for _ in 0..100 { segment.extend_from_slice(b"abcdefghijklmn") }
  2631. assert_eq!(segment.len(), 1400);
  2632. // Send the frame
  2633. send!(s, TcpRepr {
  2634. seq_number: REMOTE_SEQ + 1,
  2635. ack_number: Some(LOCAL_SEQ + 1),
  2636. payload: &segment,
  2637. ..SEND_TEMPL
  2638. });
  2639. // Ensure that the received window size is shifted right by 2.
  2640. recv!(s, [TcpRepr {
  2641. seq_number: LOCAL_SEQ + 1,
  2642. ack_number: Some(REMOTE_SEQ + 1 + 1400),
  2643. window_len: 65185,
  2644. ..RECV_TEMPL
  2645. }]);
  2646. }
  2647. #[test]
  2648. fn test_established_send() {
  2649. let mut s = socket_established();
  2650. // First roundtrip after establishing.
  2651. s.send_slice(b"abcdef").unwrap();
  2652. recv!(s, [TcpRepr {
  2653. seq_number: LOCAL_SEQ + 1,
  2654. ack_number: Some(REMOTE_SEQ + 1),
  2655. payload: &b"abcdef"[..],
  2656. ..RECV_TEMPL
  2657. }]);
  2658. assert_eq!(s.tx_buffer.len(), 6);
  2659. send!(s, TcpRepr {
  2660. seq_number: REMOTE_SEQ + 1,
  2661. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2662. ..SEND_TEMPL
  2663. });
  2664. assert_eq!(s.tx_buffer.len(), 0);
  2665. // Second roundtrip.
  2666. s.send_slice(b"foobar").unwrap();
  2667. recv!(s, [TcpRepr {
  2668. seq_number: LOCAL_SEQ + 1 + 6,
  2669. ack_number: Some(REMOTE_SEQ + 1),
  2670. payload: &b"foobar"[..],
  2671. ..RECV_TEMPL
  2672. }]);
  2673. send!(s, TcpRepr {
  2674. seq_number: REMOTE_SEQ + 1,
  2675. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2676. ..SEND_TEMPL
  2677. });
  2678. assert_eq!(s.tx_buffer.len(), 0);
  2679. }
  2680. #[test]
  2681. fn test_established_send_no_ack_send() {
  2682. let mut s = socket_established();
  2683. s.send_slice(b"abcdef").unwrap();
  2684. recv!(s, [TcpRepr {
  2685. seq_number: LOCAL_SEQ + 1,
  2686. ack_number: Some(REMOTE_SEQ + 1),
  2687. payload: &b"abcdef"[..],
  2688. ..RECV_TEMPL
  2689. }]);
  2690. s.send_slice(b"foobar").unwrap();
  2691. recv!(s, [TcpRepr {
  2692. seq_number: LOCAL_SEQ + 1 + 6,
  2693. ack_number: Some(REMOTE_SEQ + 1),
  2694. payload: &b"foobar"[..],
  2695. ..RECV_TEMPL
  2696. }]);
  2697. }
  2698. #[test]
  2699. fn test_established_send_buf_gt_win() {
  2700. let mut data = [0; 32];
  2701. for (i, elem) in data.iter_mut().enumerate() {
  2702. *elem = i as u8
  2703. }
  2704. let mut s = socket_established();
  2705. s.remote_win_len = 16;
  2706. s.send_slice(&data[..]).unwrap();
  2707. recv!(s, [TcpRepr {
  2708. seq_number: LOCAL_SEQ + 1,
  2709. ack_number: Some(REMOTE_SEQ + 1),
  2710. payload: &data[0..16],
  2711. ..RECV_TEMPL
  2712. }]);
  2713. }
  2714. #[test]
  2715. fn test_established_send_wrap() {
  2716. let mut s = socket_established();
  2717. let local_seq_start = TcpSeqNumber(i32::MAX - 1);
  2718. s.local_seq_no = local_seq_start + 1;
  2719. s.remote_last_seq = local_seq_start + 1;
  2720. s.send_slice(b"abc").unwrap();
  2721. recv!(s, time 1000, Ok(TcpRepr {
  2722. seq_number: local_seq_start + 1,
  2723. ack_number: Some(REMOTE_SEQ + 1),
  2724. payload: &b"abc"[..],
  2725. ..RECV_TEMPL
  2726. }));
  2727. }
  2728. #[test]
  2729. fn test_established_no_ack() {
  2730. let mut s = socket_established();
  2731. send!(s, TcpRepr {
  2732. seq_number: REMOTE_SEQ + 1,
  2733. ack_number: None,
  2734. ..SEND_TEMPL
  2735. }, Err(Error::Dropped));
  2736. }
  2737. #[test]
  2738. fn test_established_bad_ack() {
  2739. let mut s = socket_established();
  2740. // Already acknowledged data.
  2741. send!(s, TcpRepr {
  2742. seq_number: REMOTE_SEQ + 1,
  2743. ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
  2744. ..SEND_TEMPL
  2745. }, Err(Error::Dropped));
  2746. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2747. // Data not yet transmitted.
  2748. send!(s, TcpRepr {
  2749. seq_number: REMOTE_SEQ + 1,
  2750. ack_number: Some(LOCAL_SEQ + 10),
  2751. ..SEND_TEMPL
  2752. }, Ok(Some(TcpRepr {
  2753. seq_number: LOCAL_SEQ + 1,
  2754. ack_number: Some(REMOTE_SEQ + 1),
  2755. ..RECV_TEMPL
  2756. })));
  2757. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2758. }
  2759. #[test]
  2760. fn test_established_bad_seq() {
  2761. let mut s = socket_established();
  2762. // Data outside of receive window.
  2763. send!(s, TcpRepr {
  2764. seq_number: REMOTE_SEQ + 1 + 256,
  2765. ack_number: Some(LOCAL_SEQ + 1),
  2766. ..SEND_TEMPL
  2767. }, Ok(Some(TcpRepr {
  2768. seq_number: LOCAL_SEQ + 1,
  2769. ack_number: Some(REMOTE_SEQ + 1),
  2770. ..RECV_TEMPL
  2771. })));
  2772. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  2773. }
  2774. #[test]
  2775. fn test_established_fin() {
  2776. let mut s = socket_established();
  2777. send!(s, TcpRepr {
  2778. control: TcpControl::Fin,
  2779. seq_number: REMOTE_SEQ + 1,
  2780. ack_number: Some(LOCAL_SEQ + 1),
  2781. ..SEND_TEMPL
  2782. });
  2783. recv!(s, [TcpRepr {
  2784. seq_number: LOCAL_SEQ + 1,
  2785. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2786. ..RECV_TEMPL
  2787. }]);
  2788. assert_eq!(s.state, State::CloseWait);
  2789. sanity!(s, socket_close_wait());
  2790. }
  2791. #[test]
  2792. fn test_established_fin_after_missing() {
  2793. let mut s = socket_established();
  2794. send!(s, TcpRepr {
  2795. control: TcpControl::Fin,
  2796. seq_number: REMOTE_SEQ + 1 + 6,
  2797. ack_number: Some(LOCAL_SEQ + 1),
  2798. payload: &b"123456"[..],
  2799. ..SEND_TEMPL
  2800. }, Ok(Some(TcpRepr {
  2801. seq_number: LOCAL_SEQ + 1,
  2802. ack_number: Some(REMOTE_SEQ + 1),
  2803. ..RECV_TEMPL
  2804. })));
  2805. assert_eq!(s.state, State::Established);
  2806. send!(s, TcpRepr {
  2807. seq_number: REMOTE_SEQ + 1,
  2808. ack_number: Some(LOCAL_SEQ + 1),
  2809. payload: &b"abcdef"[..],
  2810. ..SEND_TEMPL
  2811. }, Ok(Some(TcpRepr {
  2812. seq_number: LOCAL_SEQ + 1,
  2813. ack_number: Some(REMOTE_SEQ + 1 + 6 + 6),
  2814. window_len: 52,
  2815. ..RECV_TEMPL
  2816. })));
  2817. assert_eq!(s.state, State::Established);
  2818. }
  2819. #[test]
  2820. fn test_established_send_fin() {
  2821. let mut s = socket_established();
  2822. s.send_slice(b"abcdef").unwrap();
  2823. send!(s, TcpRepr {
  2824. control: TcpControl::Fin,
  2825. seq_number: REMOTE_SEQ + 1,
  2826. ack_number: Some(LOCAL_SEQ + 1),
  2827. ..SEND_TEMPL
  2828. });
  2829. assert_eq!(s.state, State::CloseWait);
  2830. recv!(s, [TcpRepr {
  2831. seq_number: LOCAL_SEQ + 1,
  2832. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2833. payload: &b"abcdef"[..],
  2834. ..RECV_TEMPL
  2835. }]);
  2836. }
  2837. #[test]
  2838. fn test_established_rst() {
  2839. let mut s = socket_established();
  2840. send!(s, TcpRepr {
  2841. control: TcpControl::Rst,
  2842. seq_number: REMOTE_SEQ + 1,
  2843. ack_number: Some(LOCAL_SEQ + 1),
  2844. ..SEND_TEMPL
  2845. });
  2846. assert_eq!(s.state, State::Closed);
  2847. }
  2848. #[test]
  2849. fn test_established_rst_no_ack() {
  2850. let mut s = socket_established();
  2851. send!(s, TcpRepr {
  2852. control: TcpControl::Rst,
  2853. seq_number: REMOTE_SEQ + 1,
  2854. ack_number: None,
  2855. ..SEND_TEMPL
  2856. });
  2857. assert_eq!(s.state, State::Closed);
  2858. }
  2859. #[test]
  2860. fn test_established_close() {
  2861. let mut s = socket_established();
  2862. s.close();
  2863. assert_eq!(s.state, State::FinWait1);
  2864. sanity!(s, socket_fin_wait_1());
  2865. }
  2866. #[test]
  2867. fn test_established_abort() {
  2868. let mut s = socket_established();
  2869. s.abort();
  2870. assert_eq!(s.state, State::Closed);
  2871. recv!(s, [TcpRepr {
  2872. control: TcpControl::Rst,
  2873. seq_number: LOCAL_SEQ + 1,
  2874. ack_number: Some(REMOTE_SEQ + 1),
  2875. ..RECV_TEMPL
  2876. }]);
  2877. }
  2878. #[test]
  2879. fn test_established_rst_bad_seq() {
  2880. let mut s = socket_established();
  2881. send!(s, TcpRepr {
  2882. control: TcpControl::Rst,
  2883. seq_number: REMOTE_SEQ, // Wrong seq
  2884. ack_number: None,
  2885. ..SEND_TEMPL
  2886. }, Ok(Some(TcpRepr {
  2887. seq_number: LOCAL_SEQ + 1,
  2888. ack_number: Some(REMOTE_SEQ + 1),
  2889. ..RECV_TEMPL
  2890. })));
  2891. assert_eq!(s.state, State::Established);
  2892. // Send something to advance seq by 1
  2893. send!(s, TcpRepr {
  2894. seq_number: REMOTE_SEQ + 1, // correct seq
  2895. ack_number: Some(LOCAL_SEQ + 1),
  2896. payload: &b"a"[..],
  2897. ..SEND_TEMPL
  2898. });
  2899. // Send wrong rst again, check that the challenge ack is correctly updated
  2900. // The ack number must be updated even if we don't call dispatch on the socket
  2901. // See https://github.com/smoltcp-rs/smoltcp/issues/338
  2902. send!(s, TcpRepr {
  2903. control: TcpControl::Rst,
  2904. seq_number: REMOTE_SEQ, // Wrong seq
  2905. ack_number: None,
  2906. ..SEND_TEMPL
  2907. }, Ok(Some(TcpRepr {
  2908. seq_number: LOCAL_SEQ + 1,
  2909. ack_number: Some(REMOTE_SEQ + 2), // this has changed
  2910. window_len: 63,
  2911. ..RECV_TEMPL
  2912. })));
  2913. }
  2914. // =========================================================================================//
  2915. // Tests for the FIN-WAIT-1 state.
  2916. // =========================================================================================//
  2917. #[test]
  2918. fn test_fin_wait_1_fin_ack() {
  2919. let mut s = socket_fin_wait_1();
  2920. recv!(s, [TcpRepr {
  2921. control: TcpControl::Fin,
  2922. seq_number: LOCAL_SEQ + 1,
  2923. ack_number: Some(REMOTE_SEQ + 1),
  2924. ..RECV_TEMPL
  2925. }]);
  2926. send!(s, TcpRepr {
  2927. seq_number: REMOTE_SEQ + 1,
  2928. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2929. ..SEND_TEMPL
  2930. });
  2931. assert_eq!(s.state, State::FinWait2);
  2932. sanity!(s, socket_fin_wait_2());
  2933. }
  2934. #[test]
  2935. fn test_fin_wait_1_fin_fin() {
  2936. let mut s = socket_fin_wait_1();
  2937. recv!(s, [TcpRepr {
  2938. control: TcpControl::Fin,
  2939. seq_number: LOCAL_SEQ + 1,
  2940. ack_number: Some(REMOTE_SEQ + 1),
  2941. ..RECV_TEMPL
  2942. }]);
  2943. send!(s, TcpRepr {
  2944. control: TcpControl::Fin,
  2945. seq_number: REMOTE_SEQ + 1,
  2946. ack_number: Some(LOCAL_SEQ + 1),
  2947. ..SEND_TEMPL
  2948. });
  2949. assert_eq!(s.state, State::Closing);
  2950. sanity!(s, socket_closing());
  2951. }
  2952. #[test]
  2953. fn test_fin_wait_1_fin_with_data_queued() {
  2954. let mut s = socket_established();
  2955. s.remote_win_len = 6;
  2956. s.send_slice(b"abcdef123456").unwrap();
  2957. s.close();
  2958. recv!(s, Ok(TcpRepr {
  2959. seq_number: LOCAL_SEQ + 1,
  2960. ack_number: Some(REMOTE_SEQ + 1),
  2961. payload: &b"abcdef"[..],
  2962. ..RECV_TEMPL
  2963. }));
  2964. send!(s, TcpRepr {
  2965. seq_number: REMOTE_SEQ + 1,
  2966. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2967. ..SEND_TEMPL
  2968. });
  2969. assert_eq!(s.state, State::FinWait1);
  2970. }
  2971. #[test]
  2972. fn test_fin_wait_1_recv() {
  2973. let mut s = socket_fin_wait_1();
  2974. send!(s, TcpRepr {
  2975. seq_number: REMOTE_SEQ + 1,
  2976. ack_number: Some(LOCAL_SEQ + 1),
  2977. payload: &b"abc"[..],
  2978. ..SEND_TEMPL
  2979. });
  2980. assert_eq!(s.state, State::FinWait1);
  2981. s.recv(|data| {
  2982. assert_eq!(data, b"abc");
  2983. (3, ())
  2984. }).unwrap();
  2985. }
  2986. #[test]
  2987. fn test_fin_wait_1_close() {
  2988. let mut s = socket_fin_wait_1();
  2989. s.close();
  2990. assert_eq!(s.state, State::FinWait1);
  2991. }
  2992. // =========================================================================================//
  2993. // Tests for the FIN-WAIT-2 state.
  2994. // =========================================================================================//
  2995. #[test]
  2996. fn test_fin_wait_2_fin() {
  2997. let mut s = socket_fin_wait_2();
  2998. send!(s, time 1_000, TcpRepr {
  2999. control: TcpControl::Fin,
  3000. seq_number: REMOTE_SEQ + 1,
  3001. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3002. ..SEND_TEMPL
  3003. });
  3004. assert_eq!(s.state, State::TimeWait);
  3005. sanity!(s, socket_time_wait(false));
  3006. }
  3007. #[test]
  3008. fn test_fin_wait_2_recv() {
  3009. let mut s = socket_fin_wait_2();
  3010. send!(s, TcpRepr {
  3011. seq_number: REMOTE_SEQ + 1,
  3012. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3013. payload: &b"abc"[..],
  3014. ..SEND_TEMPL
  3015. });
  3016. assert_eq!(s.state, State::FinWait2);
  3017. s.recv(|data| {
  3018. assert_eq!(data, b"abc");
  3019. (3, ())
  3020. }).unwrap();
  3021. recv!(s, [TcpRepr {
  3022. seq_number: LOCAL_SEQ + 1 + 1,
  3023. ack_number: Some(REMOTE_SEQ + 1 + 3),
  3024. ..RECV_TEMPL
  3025. }]);
  3026. }
  3027. #[test]
  3028. fn test_fin_wait_2_close() {
  3029. let mut s = socket_fin_wait_2();
  3030. s.close();
  3031. assert_eq!(s.state, State::FinWait2);
  3032. }
  3033. // =========================================================================================//
  3034. // Tests for the CLOSING state.
  3035. // =========================================================================================//
  3036. #[test]
  3037. fn test_closing_ack_fin() {
  3038. let mut s = socket_closing();
  3039. recv!(s, [TcpRepr {
  3040. seq_number: LOCAL_SEQ + 1 + 1,
  3041. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3042. ..RECV_TEMPL
  3043. }]);
  3044. send!(s, time 1_000, TcpRepr {
  3045. seq_number: REMOTE_SEQ + 1 + 1,
  3046. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3047. ..SEND_TEMPL
  3048. });
  3049. assert_eq!(s.state, State::TimeWait);
  3050. sanity!(s, socket_time_wait(true));
  3051. }
  3052. #[test]
  3053. fn test_closing_close() {
  3054. let mut s = socket_closing();
  3055. s.close();
  3056. assert_eq!(s.state, State::Closing);
  3057. }
  3058. // =========================================================================================//
  3059. // Tests for the TIME-WAIT state.
  3060. // =========================================================================================//
  3061. #[test]
  3062. fn test_time_wait_from_fin_wait_2_ack() {
  3063. let mut s = socket_time_wait(false);
  3064. recv!(s, [TcpRepr {
  3065. seq_number: LOCAL_SEQ + 1 + 1,
  3066. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3067. ..RECV_TEMPL
  3068. }]);
  3069. }
  3070. #[test]
  3071. fn test_time_wait_from_closing_no_ack() {
  3072. let mut s = socket_time_wait(true);
  3073. recv!(s, []);
  3074. }
  3075. #[test]
  3076. fn test_time_wait_close() {
  3077. let mut s = socket_time_wait(false);
  3078. s.close();
  3079. assert_eq!(s.state, State::TimeWait);
  3080. }
  3081. #[test]
  3082. fn test_time_wait_retransmit() {
  3083. let mut s = socket_time_wait(false);
  3084. recv!(s, [TcpRepr {
  3085. seq_number: LOCAL_SEQ + 1 + 1,
  3086. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3087. ..RECV_TEMPL
  3088. }]);
  3089. send!(s, time 5_000, TcpRepr {
  3090. control: TcpControl::Fin,
  3091. seq_number: REMOTE_SEQ + 1,
  3092. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3093. ..SEND_TEMPL
  3094. }, Ok(Some(TcpRepr {
  3095. seq_number: LOCAL_SEQ + 1 + 1,
  3096. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3097. ..RECV_TEMPL
  3098. })));
  3099. assert_eq!(s.timer, Timer::Close { expires_at: Instant::from_secs(5) + CLOSE_DELAY });
  3100. }
  3101. #[test]
  3102. fn test_time_wait_timeout() {
  3103. let mut s = socket_time_wait(false);
  3104. recv!(s, [TcpRepr {
  3105. seq_number: LOCAL_SEQ + 1 + 1,
  3106. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3107. ..RECV_TEMPL
  3108. }]);
  3109. assert_eq!(s.state, State::TimeWait);
  3110. recv!(s, time 60_000, Err(Error::Exhausted));
  3111. assert_eq!(s.state, State::Closed);
  3112. }
  3113. // =========================================================================================//
  3114. // Tests for the CLOSE-WAIT state.
  3115. // =========================================================================================//
  3116. #[test]
  3117. fn test_close_wait_ack() {
  3118. let mut s = socket_close_wait();
  3119. s.send_slice(b"abcdef").unwrap();
  3120. recv!(s, [TcpRepr {
  3121. seq_number: LOCAL_SEQ + 1,
  3122. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3123. payload: &b"abcdef"[..],
  3124. ..RECV_TEMPL
  3125. }]);
  3126. send!(s, TcpRepr {
  3127. seq_number: REMOTE_SEQ + 1 + 1,
  3128. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3129. ..SEND_TEMPL
  3130. });
  3131. }
  3132. #[test]
  3133. fn test_close_wait_close() {
  3134. let mut s = socket_close_wait();
  3135. s.close();
  3136. assert_eq!(s.state, State::LastAck);
  3137. sanity!(s, socket_last_ack());
  3138. }
  3139. // =========================================================================================//
  3140. // Tests for the LAST-ACK state.
  3141. // =========================================================================================//
  3142. #[test]
  3143. fn test_last_ack_fin_ack() {
  3144. let mut s = socket_last_ack();
  3145. recv!(s, [TcpRepr {
  3146. control: TcpControl::Fin,
  3147. seq_number: LOCAL_SEQ + 1,
  3148. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3149. ..RECV_TEMPL
  3150. }]);
  3151. assert_eq!(s.state, State::LastAck);
  3152. send!(s, TcpRepr {
  3153. seq_number: REMOTE_SEQ + 1 + 1,
  3154. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3155. ..SEND_TEMPL
  3156. });
  3157. assert_eq!(s.state, State::Closed);
  3158. }
  3159. #[test]
  3160. fn test_last_ack_close() {
  3161. let mut s = socket_last_ack();
  3162. s.close();
  3163. assert_eq!(s.state, State::LastAck);
  3164. }
  3165. // =========================================================================================//
  3166. // Tests for transitioning through multiple states.
  3167. // =========================================================================================//
  3168. #[test]
  3169. fn test_listen() {
  3170. let mut s = socket();
  3171. s.listen(IpEndpoint::new(IpAddress::default(), LOCAL_PORT)).unwrap();
  3172. assert_eq!(s.state, State::Listen);
  3173. }
  3174. #[test]
  3175. fn test_three_way_handshake() {
  3176. let mut s = socket_listen();
  3177. send!(s, TcpRepr {
  3178. control: TcpControl::Syn,
  3179. seq_number: REMOTE_SEQ,
  3180. ack_number: None,
  3181. ..SEND_TEMPL
  3182. });
  3183. assert_eq!(s.state(), State::SynReceived);
  3184. assert_eq!(s.local_endpoint(), LOCAL_END);
  3185. assert_eq!(s.remote_endpoint(), REMOTE_END);
  3186. recv!(s, [TcpRepr {
  3187. control: TcpControl::Syn,
  3188. seq_number: LOCAL_SEQ,
  3189. ack_number: Some(REMOTE_SEQ + 1),
  3190. max_seg_size: Some(BASE_MSS),
  3191. ..RECV_TEMPL
  3192. }]);
  3193. send!(s, TcpRepr {
  3194. seq_number: REMOTE_SEQ + 1,
  3195. ack_number: Some(LOCAL_SEQ + 1),
  3196. ..SEND_TEMPL
  3197. });
  3198. assert_eq!(s.state(), State::Established);
  3199. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  3200. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  3201. }
  3202. #[test]
  3203. fn test_remote_close() {
  3204. let mut s = socket_established();
  3205. send!(s, TcpRepr {
  3206. control: TcpControl::Fin,
  3207. seq_number: REMOTE_SEQ + 1,
  3208. ack_number: Some(LOCAL_SEQ + 1),
  3209. ..SEND_TEMPL
  3210. });
  3211. assert_eq!(s.state, State::CloseWait);
  3212. recv!(s, [TcpRepr {
  3213. seq_number: LOCAL_SEQ + 1,
  3214. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3215. ..RECV_TEMPL
  3216. }]);
  3217. s.close();
  3218. assert_eq!(s.state, State::LastAck);
  3219. recv!(s, [TcpRepr {
  3220. control: TcpControl::Fin,
  3221. seq_number: LOCAL_SEQ + 1,
  3222. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3223. ..RECV_TEMPL
  3224. }]);
  3225. send!(s, TcpRepr {
  3226. seq_number: REMOTE_SEQ + 1 + 1,
  3227. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3228. ..SEND_TEMPL
  3229. });
  3230. assert_eq!(s.state, State::Closed);
  3231. }
  3232. #[test]
  3233. fn test_local_close() {
  3234. let mut s = socket_established();
  3235. s.close();
  3236. assert_eq!(s.state, State::FinWait1);
  3237. recv!(s, [TcpRepr {
  3238. control: TcpControl::Fin,
  3239. seq_number: LOCAL_SEQ + 1,
  3240. ack_number: Some(REMOTE_SEQ + 1),
  3241. ..RECV_TEMPL
  3242. }]);
  3243. send!(s, TcpRepr {
  3244. seq_number: REMOTE_SEQ + 1,
  3245. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3246. ..SEND_TEMPL
  3247. });
  3248. assert_eq!(s.state, State::FinWait2);
  3249. send!(s, TcpRepr {
  3250. control: TcpControl::Fin,
  3251. seq_number: REMOTE_SEQ + 1,
  3252. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3253. ..SEND_TEMPL
  3254. });
  3255. assert_eq!(s.state, State::TimeWait);
  3256. recv!(s, [TcpRepr {
  3257. seq_number: LOCAL_SEQ + 1 + 1,
  3258. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3259. ..RECV_TEMPL
  3260. }]);
  3261. }
  3262. #[test]
  3263. fn test_simultaneous_close() {
  3264. let mut s = socket_established();
  3265. s.close();
  3266. assert_eq!(s.state, State::FinWait1);
  3267. recv!(s, [TcpRepr { // due to reordering, this is logically located...
  3268. control: TcpControl::Fin,
  3269. seq_number: LOCAL_SEQ + 1,
  3270. ack_number: Some(REMOTE_SEQ + 1),
  3271. ..RECV_TEMPL
  3272. }]);
  3273. send!(s, TcpRepr {
  3274. control: TcpControl::Fin,
  3275. seq_number: REMOTE_SEQ + 1,
  3276. ack_number: Some(LOCAL_SEQ + 1),
  3277. ..SEND_TEMPL
  3278. });
  3279. assert_eq!(s.state, State::Closing);
  3280. recv!(s, [TcpRepr {
  3281. seq_number: LOCAL_SEQ + 1 + 1,
  3282. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3283. ..RECV_TEMPL
  3284. }]);
  3285. // ... at this point
  3286. send!(s, TcpRepr {
  3287. seq_number: REMOTE_SEQ + 1 + 1,
  3288. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3289. ..SEND_TEMPL
  3290. });
  3291. assert_eq!(s.state, State::TimeWait);
  3292. recv!(s, []);
  3293. }
  3294. #[test]
  3295. fn test_simultaneous_close_combined_fin_ack() {
  3296. let mut s = socket_established();
  3297. s.close();
  3298. assert_eq!(s.state, State::FinWait1);
  3299. recv!(s, [TcpRepr {
  3300. control: TcpControl::Fin,
  3301. seq_number: LOCAL_SEQ + 1,
  3302. ack_number: Some(REMOTE_SEQ + 1),
  3303. ..RECV_TEMPL
  3304. }]);
  3305. send!(s, TcpRepr {
  3306. control: TcpControl::Fin,
  3307. seq_number: REMOTE_SEQ + 1,
  3308. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3309. ..SEND_TEMPL
  3310. });
  3311. assert_eq!(s.state, State::TimeWait);
  3312. recv!(s, [TcpRepr {
  3313. seq_number: LOCAL_SEQ + 1 + 1,
  3314. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3315. ..RECV_TEMPL
  3316. }]);
  3317. }
  3318. #[test]
  3319. fn test_simultaneous_close_raced() {
  3320. let mut s = socket_established();
  3321. s.close();
  3322. assert_eq!(s.state, State::FinWait1);
  3323. // Socket receives FIN before it has a chance to send its own FIN
  3324. send!(s, TcpRepr {
  3325. control: TcpControl::Fin,
  3326. seq_number: REMOTE_SEQ + 1,
  3327. ack_number: Some(LOCAL_SEQ + 1),
  3328. ..SEND_TEMPL
  3329. });
  3330. assert_eq!(s.state, State::Closing);
  3331. // FIN + ack-of-FIN
  3332. recv!(s, [TcpRepr {
  3333. control: TcpControl::Fin,
  3334. seq_number: LOCAL_SEQ + 1,
  3335. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3336. ..RECV_TEMPL
  3337. }]);
  3338. assert_eq!(s.state, State::Closing);
  3339. send!(s, TcpRepr {
  3340. seq_number: REMOTE_SEQ + 1 + 1,
  3341. ack_number: Some(LOCAL_SEQ + 1 + 1),
  3342. ..SEND_TEMPL
  3343. });
  3344. assert_eq!(s.state, State::TimeWait);
  3345. recv!(s, []);
  3346. }
  3347. #[test]
  3348. fn test_simultaneous_close_raced_with_data() {
  3349. let mut s = socket_established();
  3350. s.send_slice(b"abcdef").unwrap();
  3351. s.close();
  3352. assert_eq!(s.state, State::FinWait1);
  3353. // Socket receives FIN before it has a chance to send its own data+FIN
  3354. send!(s, TcpRepr {
  3355. control: TcpControl::Fin,
  3356. seq_number: REMOTE_SEQ + 1,
  3357. ack_number: Some(LOCAL_SEQ + 1),
  3358. ..SEND_TEMPL
  3359. });
  3360. assert_eq!(s.state, State::Closing);
  3361. // data + FIN + ack-of-FIN
  3362. recv!(s, [TcpRepr {
  3363. control: TcpControl::Fin,
  3364. seq_number: LOCAL_SEQ + 1,
  3365. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3366. payload: &b"abcdef"[..],
  3367. ..RECV_TEMPL
  3368. }]);
  3369. assert_eq!(s.state, State::Closing);
  3370. send!(s, TcpRepr {
  3371. seq_number: REMOTE_SEQ + 1 + 1,
  3372. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3373. ..SEND_TEMPL
  3374. });
  3375. assert_eq!(s.state, State::TimeWait);
  3376. recv!(s, []);
  3377. }
  3378. #[test]
  3379. fn test_fin_with_data() {
  3380. let mut s = socket_established();
  3381. s.send_slice(b"abcdef").unwrap();
  3382. s.close();
  3383. recv!(s, [TcpRepr {
  3384. control: TcpControl::Fin,
  3385. seq_number: LOCAL_SEQ + 1,
  3386. ack_number: Some(REMOTE_SEQ + 1),
  3387. payload: &b"abcdef"[..],
  3388. ..RECV_TEMPL
  3389. }])
  3390. }
  3391. #[test]
  3392. fn test_mutual_close_with_data_1() {
  3393. let mut s = socket_established();
  3394. s.send_slice(b"abcdef").unwrap();
  3395. s.close();
  3396. assert_eq!(s.state, State::FinWait1);
  3397. recv!(s, [TcpRepr {
  3398. control: TcpControl::Fin,
  3399. seq_number: LOCAL_SEQ + 1,
  3400. ack_number: Some(REMOTE_SEQ + 1),
  3401. payload: &b"abcdef"[..],
  3402. ..RECV_TEMPL
  3403. }]);
  3404. send!(s, TcpRepr {
  3405. control: TcpControl::Fin,
  3406. seq_number: REMOTE_SEQ + 1,
  3407. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3408. ..SEND_TEMPL
  3409. });
  3410. }
  3411. #[test]
  3412. fn test_mutual_close_with_data_2() {
  3413. let mut s = socket_established();
  3414. s.send_slice(b"abcdef").unwrap();
  3415. s.close();
  3416. assert_eq!(s.state, State::FinWait1);
  3417. recv!(s, [TcpRepr {
  3418. control: TcpControl::Fin,
  3419. seq_number: LOCAL_SEQ + 1,
  3420. ack_number: Some(REMOTE_SEQ + 1),
  3421. payload: &b"abcdef"[..],
  3422. ..RECV_TEMPL
  3423. }]);
  3424. send!(s, TcpRepr {
  3425. seq_number: REMOTE_SEQ + 1,
  3426. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3427. ..SEND_TEMPL
  3428. });
  3429. assert_eq!(s.state, State::FinWait2);
  3430. send!(s, TcpRepr {
  3431. control: TcpControl::Fin,
  3432. seq_number: REMOTE_SEQ + 1,
  3433. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  3434. ..SEND_TEMPL
  3435. });
  3436. recv!(s, [TcpRepr {
  3437. seq_number: LOCAL_SEQ + 1 + 6 + 1,
  3438. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3439. ..RECV_TEMPL
  3440. }]);
  3441. assert_eq!(s.state, State::TimeWait);
  3442. }
  3443. // =========================================================================================//
  3444. // Tests for retransmission on packet loss.
  3445. // =========================================================================================//
  3446. #[test]
  3447. fn test_duplicate_seq_ack() {
  3448. let mut s = socket_recved();
  3449. // remote retransmission
  3450. send!(s, TcpRepr {
  3451. seq_number: REMOTE_SEQ + 1,
  3452. ack_number: Some(LOCAL_SEQ + 1),
  3453. payload: &b"abcdef"[..],
  3454. ..SEND_TEMPL
  3455. }, Ok(Some(TcpRepr {
  3456. seq_number: LOCAL_SEQ + 1,
  3457. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3458. window_len: 58,
  3459. ..RECV_TEMPL
  3460. })));
  3461. }
  3462. #[test]
  3463. fn test_data_retransmit() {
  3464. let mut s = socket_established();
  3465. s.send_slice(b"abcdef").unwrap();
  3466. recv!(s, time 1000, Ok(TcpRepr {
  3467. seq_number: LOCAL_SEQ + 1,
  3468. ack_number: Some(REMOTE_SEQ + 1),
  3469. payload: &b"abcdef"[..],
  3470. ..RECV_TEMPL
  3471. }));
  3472. recv!(s, time 1050, Err(Error::Exhausted));
  3473. recv!(s, time 2000, Ok(TcpRepr {
  3474. seq_number: LOCAL_SEQ + 1,
  3475. ack_number: Some(REMOTE_SEQ + 1),
  3476. payload: &b"abcdef"[..],
  3477. ..RECV_TEMPL
  3478. }));
  3479. }
  3480. #[test]
  3481. fn test_data_retransmit_bursts() {
  3482. let mut s = socket_established();
  3483. s.remote_mss = 6;
  3484. s.send_slice(b"abcdef012345").unwrap();
  3485. recv!(s, time 0, Ok(TcpRepr {
  3486. control: TcpControl::None,
  3487. seq_number: LOCAL_SEQ + 1,
  3488. ack_number: Some(REMOTE_SEQ + 1),
  3489. payload: &b"abcdef"[..],
  3490. ..RECV_TEMPL
  3491. }), exact);
  3492. recv!(s, time 0, Ok(TcpRepr {
  3493. control: TcpControl::Psh,
  3494. seq_number: LOCAL_SEQ + 1 + 6,
  3495. ack_number: Some(REMOTE_SEQ + 1),
  3496. payload: &b"012345"[..],
  3497. ..RECV_TEMPL
  3498. }), exact);
  3499. recv!(s, time 0, Err(Error::Exhausted));
  3500. recv!(s, time 50, Err(Error::Exhausted));
  3501. recv!(s, time 1000, Ok(TcpRepr {
  3502. control: TcpControl::None,
  3503. seq_number: LOCAL_SEQ + 1,
  3504. ack_number: Some(REMOTE_SEQ + 1),
  3505. payload: &b"abcdef"[..],
  3506. ..RECV_TEMPL
  3507. }), exact);
  3508. recv!(s, time 1500, Ok(TcpRepr {
  3509. control: TcpControl::Psh,
  3510. seq_number: LOCAL_SEQ + 1 + 6,
  3511. ack_number: Some(REMOTE_SEQ + 1),
  3512. payload: &b"012345"[..],
  3513. ..RECV_TEMPL
  3514. }), exact);
  3515. recv!(s, time 1550, Err(Error::Exhausted));
  3516. }
  3517. #[test]
  3518. fn test_send_data_after_syn_ack_retransmit() {
  3519. let mut s = socket_syn_received();
  3520. recv!(s, time 50, Ok(TcpRepr {
  3521. control: TcpControl::Syn,
  3522. seq_number: LOCAL_SEQ,
  3523. ack_number: Some(REMOTE_SEQ + 1),
  3524. max_seg_size: Some(BASE_MSS),
  3525. ..RECV_TEMPL
  3526. }));
  3527. recv!(s, time 750, Ok(TcpRepr { // retransmit
  3528. control: TcpControl::Syn,
  3529. seq_number: LOCAL_SEQ,
  3530. ack_number: Some(REMOTE_SEQ + 1),
  3531. max_seg_size: Some(BASE_MSS),
  3532. ..RECV_TEMPL
  3533. }));
  3534. send!(s, TcpRepr {
  3535. seq_number: REMOTE_SEQ + 1,
  3536. ack_number: Some(LOCAL_SEQ + 1),
  3537. ..SEND_TEMPL
  3538. });
  3539. assert_eq!(s.state(), State::Established);
  3540. s.send_slice(b"abcdef").unwrap();
  3541. recv!(s, [TcpRepr {
  3542. seq_number: LOCAL_SEQ + 1,
  3543. ack_number: Some(REMOTE_SEQ + 1),
  3544. payload: &b"abcdef"[..],
  3545. ..RECV_TEMPL
  3546. }])
  3547. }
  3548. #[test]
  3549. fn test_established_retransmit_for_dup_ack() {
  3550. let mut s = socket_established();
  3551. // Duplicate ACKs do not replace the retransmission timer
  3552. s.send_slice(b"abc").unwrap();
  3553. recv!(s, time 1000, Ok(TcpRepr {
  3554. seq_number: LOCAL_SEQ + 1,
  3555. ack_number: Some(REMOTE_SEQ + 1),
  3556. payload: &b"abc"[..],
  3557. ..RECV_TEMPL
  3558. }));
  3559. // Retransmit timer is on because all data was sent
  3560. assert_eq!(s.tx_buffer.len(), 3);
  3561. // ACK nothing new
  3562. send!(s, TcpRepr {
  3563. seq_number: REMOTE_SEQ + 1,
  3564. ack_number: Some(LOCAL_SEQ + 1),
  3565. ..SEND_TEMPL
  3566. });
  3567. // Retransmit
  3568. recv!(s, time 4000, Ok(TcpRepr {
  3569. seq_number: LOCAL_SEQ + 1,
  3570. ack_number: Some(REMOTE_SEQ + 1),
  3571. payload: &b"abc"[..],
  3572. ..RECV_TEMPL
  3573. }));
  3574. }
  3575. #[test]
  3576. fn test_established_retransmit_reset_after_ack() {
  3577. let mut s = socket_established();
  3578. s.remote_win_len = 6;
  3579. s.send_slice(b"abcdef").unwrap();
  3580. s.send_slice(b"123456").unwrap();
  3581. s.send_slice(b"ABCDEF").unwrap();
  3582. recv!(s, time 1000, Ok(TcpRepr {
  3583. seq_number: LOCAL_SEQ + 1,
  3584. ack_number: Some(REMOTE_SEQ + 1),
  3585. payload: &b"abcdef"[..],
  3586. ..RECV_TEMPL
  3587. }));
  3588. send!(s, time 1005, TcpRepr {
  3589. seq_number: REMOTE_SEQ + 1,
  3590. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3591. window_len: 6,
  3592. ..SEND_TEMPL
  3593. });
  3594. recv!(s, time 1010, Ok(TcpRepr {
  3595. seq_number: LOCAL_SEQ + 1 + 6,
  3596. ack_number: Some(REMOTE_SEQ + 1),
  3597. payload: &b"123456"[..],
  3598. ..RECV_TEMPL
  3599. }));
  3600. send!(s, time 1015, TcpRepr {
  3601. seq_number: REMOTE_SEQ + 1,
  3602. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3603. window_len: 6,
  3604. ..SEND_TEMPL
  3605. });
  3606. recv!(s, time 1020, Ok(TcpRepr {
  3607. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3608. ack_number: Some(REMOTE_SEQ + 1),
  3609. payload: &b"ABCDEF"[..],
  3610. ..RECV_TEMPL
  3611. }));
  3612. }
  3613. #[test]
  3614. fn test_established_queue_during_retransmission() {
  3615. let mut s = socket_established();
  3616. s.remote_mss = 6;
  3617. s.send_slice(b"abcdef123456ABCDEF").unwrap();
  3618. recv!(s, time 1000, Ok(TcpRepr {
  3619. seq_number: LOCAL_SEQ + 1,
  3620. ack_number: Some(REMOTE_SEQ + 1),
  3621. payload: &b"abcdef"[..],
  3622. ..RECV_TEMPL
  3623. })); // this one is dropped
  3624. recv!(s, time 1005, Ok(TcpRepr {
  3625. seq_number: LOCAL_SEQ + 1 + 6,
  3626. ack_number: Some(REMOTE_SEQ + 1),
  3627. payload: &b"123456"[..],
  3628. ..RECV_TEMPL
  3629. })); // this one is received
  3630. recv!(s, time 1010, Ok(TcpRepr {
  3631. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3632. ack_number: Some(REMOTE_SEQ + 1),
  3633. payload: &b"ABCDEF"[..],
  3634. ..RECV_TEMPL
  3635. })); // also dropped
  3636. recv!(s, time 2000, Ok(TcpRepr {
  3637. seq_number: LOCAL_SEQ + 1,
  3638. ack_number: Some(REMOTE_SEQ + 1),
  3639. payload: &b"abcdef"[..],
  3640. ..RECV_TEMPL
  3641. })); // retransmission
  3642. send!(s, time 2005, TcpRepr {
  3643. seq_number: REMOTE_SEQ + 1,
  3644. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3645. ..SEND_TEMPL
  3646. }); // acknowledgement of both segments
  3647. recv!(s, time 2010, Ok(TcpRepr {
  3648. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3649. ack_number: Some(REMOTE_SEQ + 1),
  3650. payload: &b"ABCDEF"[..],
  3651. ..RECV_TEMPL
  3652. })); // retransmission of only unacknowledged data
  3653. }
  3654. #[test]
  3655. fn test_close_wait_retransmit_reset_after_ack() {
  3656. let mut s = socket_close_wait();
  3657. s.remote_win_len = 6;
  3658. s.send_slice(b"abcdef").unwrap();
  3659. s.send_slice(b"123456").unwrap();
  3660. s.send_slice(b"ABCDEF").unwrap();
  3661. recv!(s, time 1000, Ok(TcpRepr {
  3662. seq_number: LOCAL_SEQ + 1,
  3663. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3664. payload: &b"abcdef"[..],
  3665. ..RECV_TEMPL
  3666. }));
  3667. send!(s, time 1005, TcpRepr {
  3668. seq_number: REMOTE_SEQ + 1 + 1,
  3669. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3670. window_len: 6,
  3671. ..SEND_TEMPL
  3672. });
  3673. recv!(s, time 1010, Ok(TcpRepr {
  3674. seq_number: LOCAL_SEQ + 1 + 6,
  3675. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3676. payload: &b"123456"[..],
  3677. ..RECV_TEMPL
  3678. }));
  3679. send!(s, time 1015, TcpRepr {
  3680. seq_number: REMOTE_SEQ + 1 + 1,
  3681. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3682. window_len: 6,
  3683. ..SEND_TEMPL
  3684. });
  3685. recv!(s, time 1020, Ok(TcpRepr {
  3686. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3687. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3688. payload: &b"ABCDEF"[..],
  3689. ..RECV_TEMPL
  3690. }));
  3691. }
  3692. #[test]
  3693. fn test_fin_wait_1_retransmit_reset_after_ack() {
  3694. let mut s = socket_established();
  3695. s.remote_win_len = 6;
  3696. s.send_slice(b"abcdef").unwrap();
  3697. s.send_slice(b"123456").unwrap();
  3698. s.send_slice(b"ABCDEF").unwrap();
  3699. s.close();
  3700. recv!(s, time 1000, Ok(TcpRepr {
  3701. seq_number: LOCAL_SEQ + 1,
  3702. ack_number: Some(REMOTE_SEQ + 1),
  3703. payload: &b"abcdef"[..],
  3704. ..RECV_TEMPL
  3705. }));
  3706. send!(s, time 1005, TcpRepr {
  3707. seq_number: REMOTE_SEQ + 1,
  3708. ack_number: Some(LOCAL_SEQ + 1 + 6),
  3709. window_len: 6,
  3710. ..SEND_TEMPL
  3711. });
  3712. recv!(s, time 1010, Ok(TcpRepr {
  3713. seq_number: LOCAL_SEQ + 1 + 6,
  3714. ack_number: Some(REMOTE_SEQ + 1),
  3715. payload: &b"123456"[..],
  3716. ..RECV_TEMPL
  3717. }));
  3718. send!(s, time 1015, TcpRepr {
  3719. seq_number: REMOTE_SEQ + 1,
  3720. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  3721. window_len: 6,
  3722. ..SEND_TEMPL
  3723. });
  3724. recv!(s, time 1020, Ok(TcpRepr {
  3725. control: TcpControl::Fin,
  3726. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3727. ack_number: Some(REMOTE_SEQ + 1),
  3728. payload: &b"ABCDEF"[..],
  3729. ..RECV_TEMPL
  3730. }));
  3731. }
  3732. #[test]
  3733. fn test_fast_retransmit_after_triple_duplicate_ack() {
  3734. let mut s = socket_established();
  3735. s.remote_mss = 6;
  3736. // Normal ACK of previously recived segment
  3737. send!(s, time 0, TcpRepr {
  3738. seq_number: REMOTE_SEQ + 1,
  3739. ack_number: Some(LOCAL_SEQ + 1),
  3740. ..SEND_TEMPL
  3741. });
  3742. // Send a long string of text divided into several packets
  3743. // because of previously recieved "window_len"
  3744. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  3745. // This packet is lost
  3746. recv!(s, time 1000, Ok(TcpRepr {
  3747. seq_number: LOCAL_SEQ + 1,
  3748. ack_number: Some(REMOTE_SEQ + 1),
  3749. payload: &b"xxxxxx"[..],
  3750. ..RECV_TEMPL
  3751. }));
  3752. recv!(s, time 1005, Ok(TcpRepr {
  3753. seq_number: LOCAL_SEQ + 1 + 6,
  3754. ack_number: Some(REMOTE_SEQ + 1),
  3755. payload: &b"yyyyyy"[..],
  3756. ..RECV_TEMPL
  3757. }));
  3758. recv!(s, time 1010, Ok(TcpRepr {
  3759. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3760. ack_number: Some(REMOTE_SEQ + 1),
  3761. payload: &b"wwwwww"[..],
  3762. ..RECV_TEMPL
  3763. }));
  3764. recv!(s, time 1015, Ok(TcpRepr {
  3765. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3766. ack_number: Some(REMOTE_SEQ + 1),
  3767. payload: &b"zzzzzz"[..],
  3768. ..RECV_TEMPL
  3769. }));
  3770. // First duplicate ACK
  3771. send!(s, time 1050, TcpRepr {
  3772. seq_number: REMOTE_SEQ + 1,
  3773. ack_number: Some(LOCAL_SEQ + 1),
  3774. ..SEND_TEMPL
  3775. });
  3776. // Second duplicate ACK
  3777. send!(s, time 1055, TcpRepr {
  3778. seq_number: REMOTE_SEQ + 1,
  3779. ack_number: Some(LOCAL_SEQ + 1),
  3780. ..SEND_TEMPL
  3781. });
  3782. // Third duplicate ACK
  3783. // Should trigger a fast retransmit of dropped packet
  3784. send!(s, time 1060, TcpRepr {
  3785. seq_number: REMOTE_SEQ + 1,
  3786. ack_number: Some(LOCAL_SEQ + 1),
  3787. ..SEND_TEMPL
  3788. });
  3789. // Fast retransmit packet
  3790. recv!(s, time 1100, Ok(TcpRepr {
  3791. seq_number: LOCAL_SEQ + 1,
  3792. ack_number: Some(REMOTE_SEQ + 1),
  3793. payload: &b"xxxxxx"[..],
  3794. ..RECV_TEMPL
  3795. }));
  3796. recv!(s, time 1105, Ok(TcpRepr {
  3797. seq_number: LOCAL_SEQ + 1 + 6,
  3798. ack_number: Some(REMOTE_SEQ + 1),
  3799. payload: &b"yyyyyy"[..],
  3800. ..RECV_TEMPL
  3801. }));
  3802. recv!(s, time 1110, Ok(TcpRepr {
  3803. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3804. ack_number: Some(REMOTE_SEQ + 1),
  3805. payload: &b"wwwwww"[..],
  3806. ..RECV_TEMPL
  3807. }));
  3808. recv!(s, time 1115, Ok(TcpRepr {
  3809. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3810. ack_number: Some(REMOTE_SEQ + 1),
  3811. payload: &b"zzzzzz"[..],
  3812. ..RECV_TEMPL
  3813. }));
  3814. // After all was send out, enter *normal* retransmission,
  3815. // don't stay in fast retransmission.
  3816. assert!(match s.timer {
  3817. Timer::Retransmit { expires_at, .. } => expires_at > Instant::from_millis(1115),
  3818. _ => false,
  3819. });
  3820. // ACK all recived segments
  3821. send!(s, time 1120, TcpRepr {
  3822. seq_number: REMOTE_SEQ + 1,
  3823. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  3824. ..SEND_TEMPL
  3825. });
  3826. }
  3827. #[test]
  3828. fn test_fast_retransmit_duplicate_detection_with_data() {
  3829. let mut s = socket_established();
  3830. s.send_slice(b"abc").unwrap(); // This is lost
  3831. recv!(s, time 1000, Ok(TcpRepr {
  3832. seq_number: LOCAL_SEQ + 1,
  3833. ack_number: Some(REMOTE_SEQ + 1),
  3834. payload: &b"abc"[..],
  3835. ..RECV_TEMPL
  3836. }));
  3837. // Normal ACK of previously recieved segment
  3838. send!(s, TcpRepr {
  3839. seq_number: REMOTE_SEQ + 1,
  3840. ack_number: Some(LOCAL_SEQ + 1),
  3841. ..SEND_TEMPL
  3842. });
  3843. // First duplicate
  3844. send!(s, TcpRepr {
  3845. seq_number: REMOTE_SEQ + 1,
  3846. ack_number: Some(LOCAL_SEQ + 1),
  3847. ..SEND_TEMPL
  3848. });
  3849. // Second duplicate
  3850. send!(s, TcpRepr {
  3851. seq_number: REMOTE_SEQ + 1,
  3852. ack_number: Some(LOCAL_SEQ + 1),
  3853. ..SEND_TEMPL
  3854. });
  3855. assert_eq!(s.local_rx_dup_acks, 2,
  3856. "duplicate ACK counter is not set");
  3857. // This packet has content, hence should not be detected
  3858. // as a duplicate ACK and should reset the duplicate ACK count
  3859. send!(s, TcpRepr {
  3860. seq_number: REMOTE_SEQ + 1,
  3861. ack_number: Some(LOCAL_SEQ + 1),
  3862. payload: &b"xxxxxx"[..],
  3863. ..SEND_TEMPL
  3864. });
  3865. recv!(s, [TcpRepr {
  3866. seq_number: LOCAL_SEQ + 1 + 3,
  3867. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3868. window_len: 58,
  3869. ..RECV_TEMPL
  3870. }]);
  3871. assert_eq!(s.local_rx_dup_acks, 0,
  3872. "duplicate ACK counter is not reset when reciving data");
  3873. }
  3874. #[test]
  3875. fn test_fast_retransmit_duplicate_detection() {
  3876. let mut s = socket_established();
  3877. s.remote_mss = 6;
  3878. // Normal ACK of previously recived segment
  3879. send!(s, time 0, TcpRepr {
  3880. seq_number: REMOTE_SEQ + 1,
  3881. ack_number: Some(LOCAL_SEQ + 1),
  3882. ..SEND_TEMPL
  3883. });
  3884. // First duplicate, should not be counted as there is nothing to resend
  3885. send!(s, time 0, TcpRepr {
  3886. seq_number: REMOTE_SEQ + 1,
  3887. ack_number: Some(LOCAL_SEQ + 1),
  3888. ..SEND_TEMPL
  3889. });
  3890. assert_eq!(s.local_rx_dup_acks, 0,
  3891. "duplicate ACK counter is set but wound not transmit data");
  3892. // Send a long string of text divided into several packets
  3893. // because of small remote_mss
  3894. s.send_slice(b"xxxxxxyyyyyywwwwwwzzzzzz").unwrap();
  3895. // This packet is reordered in network
  3896. recv!(s, time 1000, Ok(TcpRepr {
  3897. seq_number: LOCAL_SEQ + 1,
  3898. ack_number: Some(REMOTE_SEQ + 1),
  3899. payload: &b"xxxxxx"[..],
  3900. ..RECV_TEMPL
  3901. }));
  3902. recv!(s, time 1005, Ok(TcpRepr {
  3903. seq_number: LOCAL_SEQ + 1 + 6,
  3904. ack_number: Some(REMOTE_SEQ + 1),
  3905. payload: &b"yyyyyy"[..],
  3906. ..RECV_TEMPL
  3907. }));
  3908. recv!(s, time 1010, Ok(TcpRepr {
  3909. seq_number: LOCAL_SEQ + 1 + (6 * 2),
  3910. ack_number: Some(REMOTE_SEQ + 1),
  3911. payload: &b"wwwwww"[..],
  3912. ..RECV_TEMPL
  3913. }));
  3914. recv!(s, time 1015, Ok(TcpRepr {
  3915. seq_number: LOCAL_SEQ + 1 + (6 * 3),
  3916. ack_number: Some(REMOTE_SEQ + 1),
  3917. payload: &b"zzzzzz"[..],
  3918. ..RECV_TEMPL
  3919. }));
  3920. // First duplicate ACK
  3921. send!(s, time 1050, TcpRepr {
  3922. seq_number: REMOTE_SEQ + 1,
  3923. ack_number: Some(LOCAL_SEQ + 1),
  3924. ..SEND_TEMPL
  3925. });
  3926. // Second duplicate ACK
  3927. send!(s, time 1055, TcpRepr {
  3928. seq_number: REMOTE_SEQ + 1,
  3929. ack_number: Some(LOCAL_SEQ + 1),
  3930. ..SEND_TEMPL
  3931. });
  3932. // Reordered packet arrives which should reset duplicate ACK count
  3933. send!(s, time 1060, TcpRepr {
  3934. seq_number: REMOTE_SEQ + 1,
  3935. ack_number: Some(LOCAL_SEQ + 1 + (6 * 3)),
  3936. ..SEND_TEMPL
  3937. });
  3938. assert_eq!(s.local_rx_dup_acks, 0,
  3939. "duplicate ACK counter is not reset when reciving ACK which updates send window");
  3940. // ACK all recived segments
  3941. send!(s, time 1120, TcpRepr {
  3942. seq_number: REMOTE_SEQ + 1,
  3943. ack_number: Some(LOCAL_SEQ + 1 + (6 * 4)),
  3944. ..SEND_TEMPL
  3945. });
  3946. }
  3947. #[test]
  3948. fn test_fast_retransmit_dup_acks_counter() {
  3949. let mut s = socket_established();
  3950. s.send_slice(b"abc").unwrap(); // This is lost
  3951. recv!(s, time 0, Ok(TcpRepr {
  3952. seq_number: LOCAL_SEQ + 1,
  3953. ack_number: Some(REMOTE_SEQ + 1),
  3954. payload: &b"abc"[..],
  3955. ..RECV_TEMPL
  3956. }));
  3957. send!(s, time 0, TcpRepr {
  3958. seq_number: REMOTE_SEQ + 1,
  3959. ack_number: Some(LOCAL_SEQ + 1),
  3960. ..SEND_TEMPL
  3961. });
  3962. // A lot of retransmits happen here
  3963. s.local_rx_dup_acks = u8::max_value() - 1;
  3964. // Send 3 more ACKs, which could overflow local_rx_dup_acks,
  3965. // but intended behaviour is that we saturate the bounds
  3966. // of local_rx_dup_acks
  3967. send!(s, time 0, TcpRepr {
  3968. seq_number: REMOTE_SEQ + 1,
  3969. ack_number: Some(LOCAL_SEQ + 1),
  3970. ..SEND_TEMPL
  3971. });
  3972. send!(s, time 0, TcpRepr {
  3973. seq_number: REMOTE_SEQ + 1,
  3974. ack_number: Some(LOCAL_SEQ + 1),
  3975. ..SEND_TEMPL
  3976. });
  3977. send!(s, time 0, TcpRepr {
  3978. seq_number: REMOTE_SEQ + 1,
  3979. ack_number: Some(LOCAL_SEQ + 1),
  3980. ..SEND_TEMPL
  3981. });
  3982. assert_eq!(s.local_rx_dup_acks, u8::max_value(), "duplicate ACK count should not overflow but saturate");
  3983. }
  3984. // =========================================================================================//
  3985. // Tests for window management.
  3986. // =========================================================================================//
  3987. #[test]
  3988. fn test_maximum_segment_size() {
  3989. let mut s = socket_listen();
  3990. s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
  3991. send!(s, TcpRepr {
  3992. control: TcpControl::Syn,
  3993. seq_number: REMOTE_SEQ,
  3994. ack_number: None,
  3995. max_seg_size: Some(1000),
  3996. ..SEND_TEMPL
  3997. });
  3998. recv!(s, [TcpRepr {
  3999. control: TcpControl::Syn,
  4000. seq_number: LOCAL_SEQ,
  4001. ack_number: Some(REMOTE_SEQ + 1),
  4002. max_seg_size: Some(BASE_MSS),
  4003. ..RECV_TEMPL
  4004. }]);
  4005. send!(s, TcpRepr {
  4006. seq_number: REMOTE_SEQ + 1,
  4007. ack_number: Some(LOCAL_SEQ + 1),
  4008. window_len: 32767,
  4009. ..SEND_TEMPL
  4010. });
  4011. s.send_slice(&[0; 1200][..]).unwrap();
  4012. recv!(s, Ok(TcpRepr {
  4013. seq_number: LOCAL_SEQ + 1,
  4014. ack_number: Some(REMOTE_SEQ + 1),
  4015. payload: &[0; 1000][..],
  4016. ..RECV_TEMPL
  4017. }));
  4018. }
  4019. #[test]
  4020. fn test_close_wait_no_window_update() {
  4021. let mut s = socket_established();
  4022. send!(s, TcpRepr {
  4023. control: TcpControl::Fin,
  4024. seq_number: REMOTE_SEQ + 1,
  4025. ack_number: Some(LOCAL_SEQ + 1),
  4026. payload: &[1,2,3,4],
  4027. ..SEND_TEMPL
  4028. });
  4029. assert_eq!(s.state, State::CloseWait);
  4030. // we ack the FIN, with the reduced window size.
  4031. recv!(s, Ok(TcpRepr {
  4032. seq_number: LOCAL_SEQ + 1,
  4033. ack_number: Some(REMOTE_SEQ + 6),
  4034. window_len: 60,
  4035. ..RECV_TEMPL
  4036. }));
  4037. let rx_buf = &mut [0; 32];
  4038. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  4039. // check that we do NOT send a window update even if it has changed.
  4040. recv!(s, Err(Error::Exhausted));
  4041. }
  4042. #[test]
  4043. fn test_time_wait_no_window_update() {
  4044. let mut s = socket_fin_wait_2();
  4045. send!(s, TcpRepr {
  4046. control: TcpControl::Fin,
  4047. seq_number: REMOTE_SEQ + 1,
  4048. ack_number: Some(LOCAL_SEQ + 2),
  4049. payload: &[1,2,3,4],
  4050. ..SEND_TEMPL
  4051. });
  4052. assert_eq!(s.state, State::TimeWait);
  4053. // we ack the FIN, with the reduced window size.
  4054. recv!(s, Ok(TcpRepr {
  4055. seq_number: LOCAL_SEQ + 2,
  4056. ack_number: Some(REMOTE_SEQ + 6),
  4057. window_len: 60,
  4058. ..RECV_TEMPL
  4059. }));
  4060. let rx_buf = &mut [0; 32];
  4061. assert_eq!(s.recv_slice(rx_buf), Ok(4));
  4062. // check that we do NOT send a window update even if it has changed.
  4063. recv!(s, Err(Error::Exhausted));
  4064. }
  4065. // =========================================================================================//
  4066. // Tests for flow control.
  4067. // =========================================================================================//
  4068. #[test]
  4069. fn test_psh_transmit() {
  4070. let mut s = socket_established();
  4071. s.remote_mss = 6;
  4072. s.send_slice(b"abcdef").unwrap();
  4073. s.send_slice(b"123456").unwrap();
  4074. recv!(s, time 0, Ok(TcpRepr {
  4075. control: TcpControl::None,
  4076. seq_number: LOCAL_SEQ + 1,
  4077. ack_number: Some(REMOTE_SEQ + 1),
  4078. payload: &b"abcdef"[..],
  4079. ..RECV_TEMPL
  4080. }), exact);
  4081. recv!(s, time 0, Ok(TcpRepr {
  4082. control: TcpControl::Psh,
  4083. seq_number: LOCAL_SEQ + 1 + 6,
  4084. ack_number: Some(REMOTE_SEQ + 1),
  4085. payload: &b"123456"[..],
  4086. ..RECV_TEMPL
  4087. }), exact);
  4088. }
  4089. #[test]
  4090. fn test_psh_receive() {
  4091. let mut s = socket_established();
  4092. send!(s, TcpRepr {
  4093. control: TcpControl::Psh,
  4094. seq_number: REMOTE_SEQ + 1,
  4095. ack_number: Some(LOCAL_SEQ + 1),
  4096. payload: &b"abcdef"[..],
  4097. ..SEND_TEMPL
  4098. });
  4099. recv!(s, [TcpRepr {
  4100. seq_number: LOCAL_SEQ + 1,
  4101. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4102. window_len: 58,
  4103. ..RECV_TEMPL
  4104. }]);
  4105. }
  4106. #[test]
  4107. fn test_zero_window_ack() {
  4108. let mut s = socket_established();
  4109. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4110. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4111. send!(s, TcpRepr {
  4112. seq_number: REMOTE_SEQ + 1,
  4113. ack_number: Some(LOCAL_SEQ + 1),
  4114. payload: &b"abcdef"[..],
  4115. ..SEND_TEMPL
  4116. });
  4117. recv!(s, [TcpRepr {
  4118. seq_number: LOCAL_SEQ + 1,
  4119. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4120. window_len: 0,
  4121. ..RECV_TEMPL
  4122. }]);
  4123. send!(s, TcpRepr {
  4124. seq_number: REMOTE_SEQ + 1 + 6,
  4125. ack_number: Some(LOCAL_SEQ + 1),
  4126. payload: &b"123456"[..],
  4127. ..SEND_TEMPL
  4128. }, Ok(Some(TcpRepr {
  4129. seq_number: LOCAL_SEQ + 1,
  4130. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4131. window_len: 0,
  4132. ..RECV_TEMPL
  4133. })));
  4134. }
  4135. #[test]
  4136. fn test_zero_window_ack_on_window_growth() {
  4137. let mut s = socket_established();
  4138. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4139. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4140. send!(s, TcpRepr {
  4141. seq_number: REMOTE_SEQ + 1,
  4142. ack_number: Some(LOCAL_SEQ + 1),
  4143. payload: &b"abcdef"[..],
  4144. ..SEND_TEMPL
  4145. });
  4146. recv!(s, [TcpRepr {
  4147. seq_number: LOCAL_SEQ + 1,
  4148. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4149. window_len: 0,
  4150. ..RECV_TEMPL
  4151. }]);
  4152. recv!(s, time 0, Err(Error::Exhausted));
  4153. s.recv(|buffer| {
  4154. assert_eq!(&buffer[..3], b"abc");
  4155. (3, ())
  4156. }).unwrap();
  4157. recv!(s, time 0, Ok(TcpRepr {
  4158. seq_number: LOCAL_SEQ + 1,
  4159. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4160. window_len: 3,
  4161. ..RECV_TEMPL
  4162. }));
  4163. recv!(s, time 0, Err(Error::Exhausted));
  4164. s.recv(|buffer| {
  4165. assert_eq!(buffer, b"def");
  4166. (buffer.len(), ())
  4167. }).unwrap();
  4168. recv!(s, time 0, Ok(TcpRepr {
  4169. seq_number: LOCAL_SEQ + 1,
  4170. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4171. window_len: 6,
  4172. ..RECV_TEMPL
  4173. }));
  4174. }
  4175. #[test]
  4176. fn test_fill_peer_window() {
  4177. let mut s = socket_established();
  4178. s.remote_mss = 6;
  4179. s.send_slice(b"abcdef123456!@#$%^").unwrap();
  4180. recv!(s, [TcpRepr {
  4181. seq_number: LOCAL_SEQ + 1,
  4182. ack_number: Some(REMOTE_SEQ + 1),
  4183. payload: &b"abcdef"[..],
  4184. ..RECV_TEMPL
  4185. }, TcpRepr {
  4186. seq_number: LOCAL_SEQ + 1 + 6,
  4187. ack_number: Some(REMOTE_SEQ + 1),
  4188. payload: &b"123456"[..],
  4189. ..RECV_TEMPL
  4190. }, TcpRepr {
  4191. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  4192. ack_number: Some(REMOTE_SEQ + 1),
  4193. payload: &b"!@#$%^"[..],
  4194. ..RECV_TEMPL
  4195. }]);
  4196. }
  4197. #[test]
  4198. fn test_announce_window_after_read() {
  4199. let mut s = socket_established();
  4200. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4201. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4202. send!(s, TcpRepr {
  4203. seq_number: REMOTE_SEQ + 1,
  4204. ack_number: Some(LOCAL_SEQ + 1),
  4205. payload: &b"abc"[..],
  4206. ..SEND_TEMPL
  4207. });
  4208. recv!(s, [TcpRepr {
  4209. seq_number: LOCAL_SEQ + 1,
  4210. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4211. window_len: 3,
  4212. ..RECV_TEMPL
  4213. }]);
  4214. // Test that `dispatch` updates `remote_last_win`
  4215. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4216. s.recv(|buffer| {
  4217. (buffer.len(), ())
  4218. }).unwrap();
  4219. assert!(s.window_to_update());
  4220. recv!(s, [TcpRepr {
  4221. seq_number: LOCAL_SEQ + 1,
  4222. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4223. window_len: 6,
  4224. ..RECV_TEMPL
  4225. }]);
  4226. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4227. // Provoke immediate ACK to test that `process` updates `remote_last_win`
  4228. send!(s, TcpRepr {
  4229. seq_number: REMOTE_SEQ + 1 + 6,
  4230. ack_number: Some(LOCAL_SEQ + 1),
  4231. payload: &b"def"[..],
  4232. ..SEND_TEMPL
  4233. }, Ok(Some(TcpRepr {
  4234. seq_number: LOCAL_SEQ + 1,
  4235. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4236. window_len: 6,
  4237. ..RECV_TEMPL
  4238. })));
  4239. send!(s, TcpRepr {
  4240. seq_number: REMOTE_SEQ + 1 + 3,
  4241. ack_number: Some(LOCAL_SEQ + 1),
  4242. payload: &b"abc"[..],
  4243. ..SEND_TEMPL
  4244. }, Ok(Some(TcpRepr {
  4245. seq_number: LOCAL_SEQ + 1,
  4246. ack_number: Some(REMOTE_SEQ + 1 + 9),
  4247. window_len: 0,
  4248. ..RECV_TEMPL
  4249. })));
  4250. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  4251. s.recv(|buffer| {
  4252. (buffer.len(), ())
  4253. }).unwrap();
  4254. assert!(s.window_to_update());
  4255. }
  4256. // =========================================================================================//
  4257. // Tests for timeouts.
  4258. // =========================================================================================//
  4259. #[test]
  4260. fn test_listen_timeout() {
  4261. let mut s = socket_listen();
  4262. s.set_timeout(Some(Duration::from_millis(100)));
  4263. assert_eq!(s.poll_at(), PollAt::Ingress);
  4264. }
  4265. #[test]
  4266. fn test_connect_timeout() {
  4267. let mut s = socket();
  4268. s.local_seq_no = LOCAL_SEQ;
  4269. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  4270. s.set_timeout(Some(Duration::from_millis(100)));
  4271. recv!(s, time 150, Ok(TcpRepr {
  4272. control: TcpControl::Syn,
  4273. seq_number: LOCAL_SEQ,
  4274. ack_number: None,
  4275. max_seg_size: Some(BASE_MSS),
  4276. window_scale: Some(0),
  4277. sack_permitted: true,
  4278. ..RECV_TEMPL
  4279. }));
  4280. assert_eq!(s.state, State::SynSent);
  4281. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(250)));
  4282. recv!(s, time 250, Ok(TcpRepr {
  4283. control: TcpControl::Rst,
  4284. seq_number: LOCAL_SEQ + 1,
  4285. ack_number: Some(TcpSeqNumber(0)),
  4286. window_scale: None,
  4287. ..RECV_TEMPL
  4288. }));
  4289. assert_eq!(s.state, State::Closed);
  4290. }
  4291. #[test]
  4292. fn test_established_timeout() {
  4293. let mut s = socket_established();
  4294. s.set_timeout(Some(Duration::from_millis(1000)));
  4295. recv!(s, time 250, Err(Error::Exhausted));
  4296. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(1250)));
  4297. s.send_slice(b"abcdef").unwrap();
  4298. assert_eq!(s.poll_at(), PollAt::Now);
  4299. recv!(s, time 255, Ok(TcpRepr {
  4300. seq_number: LOCAL_SEQ + 1,
  4301. ack_number: Some(REMOTE_SEQ + 1),
  4302. payload: &b"abcdef"[..],
  4303. ..RECV_TEMPL
  4304. }));
  4305. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(955)));
  4306. recv!(s, time 955, Ok(TcpRepr {
  4307. seq_number: LOCAL_SEQ + 1,
  4308. ack_number: Some(REMOTE_SEQ + 1),
  4309. payload: &b"abcdef"[..],
  4310. ..RECV_TEMPL
  4311. }));
  4312. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(1255)));
  4313. recv!(s, time 1255, Ok(TcpRepr {
  4314. control: TcpControl::Rst,
  4315. seq_number: LOCAL_SEQ + 1 + 6,
  4316. ack_number: Some(REMOTE_SEQ + 1),
  4317. ..RECV_TEMPL
  4318. }));
  4319. assert_eq!(s.state, State::Closed);
  4320. }
  4321. #[test]
  4322. fn test_established_keep_alive_timeout() {
  4323. let mut s = socket_established();
  4324. s.set_keep_alive(Some(Duration::from_millis(50)));
  4325. s.set_timeout(Some(Duration::from_millis(100)));
  4326. recv!(s, time 100, Ok(TcpRepr {
  4327. seq_number: LOCAL_SEQ,
  4328. ack_number: Some(REMOTE_SEQ + 1),
  4329. payload: &[0],
  4330. ..RECV_TEMPL
  4331. }));
  4332. recv!(s, time 100, Err(Error::Exhausted));
  4333. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(150)));
  4334. send!(s, time 105, TcpRepr {
  4335. seq_number: REMOTE_SEQ + 1,
  4336. ack_number: Some(LOCAL_SEQ + 1),
  4337. ..SEND_TEMPL
  4338. });
  4339. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(155)));
  4340. recv!(s, time 155, Ok(TcpRepr {
  4341. seq_number: LOCAL_SEQ,
  4342. ack_number: Some(REMOTE_SEQ + 1),
  4343. payload: &[0],
  4344. ..RECV_TEMPL
  4345. }));
  4346. recv!(s, time 155, Err(Error::Exhausted));
  4347. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(205)));
  4348. recv!(s, time 200, Err(Error::Exhausted));
  4349. recv!(s, time 205, Ok(TcpRepr {
  4350. control: TcpControl::Rst,
  4351. seq_number: LOCAL_SEQ + 1,
  4352. ack_number: Some(REMOTE_SEQ + 1),
  4353. ..RECV_TEMPL
  4354. }));
  4355. recv!(s, time 205, Err(Error::Exhausted));
  4356. assert_eq!(s.state, State::Closed);
  4357. }
  4358. #[test]
  4359. fn test_fin_wait_1_timeout() {
  4360. let mut s = socket_fin_wait_1();
  4361. s.set_timeout(Some(Duration::from_millis(1000)));
  4362. recv!(s, time 100, Ok(TcpRepr {
  4363. control: TcpControl::Fin,
  4364. seq_number: LOCAL_SEQ + 1,
  4365. ack_number: Some(REMOTE_SEQ + 1),
  4366. ..RECV_TEMPL
  4367. }));
  4368. recv!(s, time 1100, Ok(TcpRepr {
  4369. control: TcpControl::Rst,
  4370. seq_number: LOCAL_SEQ + 1 + 1,
  4371. ack_number: Some(REMOTE_SEQ + 1),
  4372. ..RECV_TEMPL
  4373. }));
  4374. assert_eq!(s.state, State::Closed);
  4375. }
  4376. #[test]
  4377. fn test_last_ack_timeout() {
  4378. let mut s = socket_last_ack();
  4379. s.set_timeout(Some(Duration::from_millis(1000)));
  4380. recv!(s, time 100, Ok(TcpRepr {
  4381. control: TcpControl::Fin,
  4382. seq_number: LOCAL_SEQ + 1,
  4383. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4384. ..RECV_TEMPL
  4385. }));
  4386. recv!(s, time 1100, Ok(TcpRepr {
  4387. control: TcpControl::Rst,
  4388. seq_number: LOCAL_SEQ + 1 + 1,
  4389. ack_number: Some(REMOTE_SEQ + 1 + 1),
  4390. ..RECV_TEMPL
  4391. }));
  4392. assert_eq!(s.state, State::Closed);
  4393. }
  4394. #[test]
  4395. fn test_closed_timeout() {
  4396. let mut s = socket_established();
  4397. s.set_timeout(Some(Duration::from_millis(200)));
  4398. s.remote_last_ts = Some(Instant::from_millis(100));
  4399. s.abort();
  4400. assert_eq!(s.poll_at(), PollAt::Now);
  4401. recv!(s, time 100, Ok(TcpRepr {
  4402. control: TcpControl::Rst,
  4403. seq_number: LOCAL_SEQ + 1,
  4404. ack_number: Some(REMOTE_SEQ + 1),
  4405. ..RECV_TEMPL
  4406. }));
  4407. assert_eq!(s.poll_at(), PollAt::Ingress);
  4408. }
  4409. // =========================================================================================//
  4410. // Tests for keep-alive.
  4411. // =========================================================================================//
  4412. #[test]
  4413. fn test_responds_to_keep_alive() {
  4414. let mut s = socket_established();
  4415. send!(s, TcpRepr {
  4416. seq_number: REMOTE_SEQ,
  4417. ack_number: Some(LOCAL_SEQ + 1),
  4418. ..SEND_TEMPL
  4419. }, Ok(Some(TcpRepr {
  4420. seq_number: LOCAL_SEQ + 1,
  4421. ack_number: Some(REMOTE_SEQ + 1),
  4422. ..RECV_TEMPL
  4423. })));
  4424. }
  4425. #[test]
  4426. fn test_sends_keep_alive() {
  4427. let mut s = socket_established();
  4428. s.set_keep_alive(Some(Duration::from_millis(100)));
  4429. // drain the forced keep-alive packet
  4430. assert_eq!(s.poll_at(), PollAt::Now);
  4431. recv!(s, time 0, Ok(TcpRepr {
  4432. seq_number: LOCAL_SEQ,
  4433. ack_number: Some(REMOTE_SEQ + 1),
  4434. payload: &[0],
  4435. ..RECV_TEMPL
  4436. }));
  4437. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(100)));
  4438. recv!(s, time 95, Err(Error::Exhausted));
  4439. recv!(s, time 100, Ok(TcpRepr {
  4440. seq_number: LOCAL_SEQ,
  4441. ack_number: Some(REMOTE_SEQ + 1),
  4442. payload: &[0],
  4443. ..RECV_TEMPL
  4444. }));
  4445. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  4446. recv!(s, time 195, Err(Error::Exhausted));
  4447. recv!(s, time 200, Ok(TcpRepr {
  4448. seq_number: LOCAL_SEQ,
  4449. ack_number: Some(REMOTE_SEQ + 1),
  4450. payload: &[0],
  4451. ..RECV_TEMPL
  4452. }));
  4453. send!(s, time 250, TcpRepr {
  4454. seq_number: REMOTE_SEQ + 1,
  4455. ack_number: Some(LOCAL_SEQ + 1),
  4456. ..SEND_TEMPL
  4457. });
  4458. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(350)));
  4459. recv!(s, time 345, Err(Error::Exhausted));
  4460. recv!(s, time 350, Ok(TcpRepr {
  4461. seq_number: LOCAL_SEQ,
  4462. ack_number: Some(REMOTE_SEQ + 1),
  4463. payload: &b"\x00"[..],
  4464. ..RECV_TEMPL
  4465. }));
  4466. }
  4467. // =========================================================================================//
  4468. // Tests for time-to-live configuration.
  4469. // =========================================================================================//
  4470. #[test]
  4471. fn test_set_hop_limit() {
  4472. let mut s = socket_syn_received();
  4473. let caps = DeviceCapabilities {
  4474. max_transmission_unit: 1520,
  4475. ..Default::default()
  4476. };
  4477. s.set_hop_limit(Some(0x2a));
  4478. assert_eq!(s.dispatch(Instant::from_millis(0), &caps, |(ip_repr, _)| {
  4479. assert_eq!(ip_repr.hop_limit(), 0x2a);
  4480. Ok(())
  4481. }), Ok(()));
  4482. }
  4483. #[test]
  4484. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  4485. fn test_set_hop_limit_zero() {
  4486. let mut s = socket_syn_received();
  4487. s.set_hop_limit(Some(0));
  4488. }
  4489. // =========================================================================================//
  4490. // Tests for reassembly.
  4491. // =========================================================================================//
  4492. #[test]
  4493. fn test_out_of_order() {
  4494. let mut s = socket_established();
  4495. send!(s, TcpRepr {
  4496. seq_number: REMOTE_SEQ + 1 + 3,
  4497. ack_number: Some(LOCAL_SEQ + 1),
  4498. payload: &b"def"[..],
  4499. ..SEND_TEMPL
  4500. }, Ok(Some(TcpRepr {
  4501. seq_number: LOCAL_SEQ + 1,
  4502. ack_number: Some(REMOTE_SEQ + 1),
  4503. ..RECV_TEMPL
  4504. })));
  4505. s.recv(|buffer| {
  4506. assert_eq!(buffer, b"");
  4507. (buffer.len(), ())
  4508. }).unwrap();
  4509. send!(s, TcpRepr {
  4510. seq_number: REMOTE_SEQ + 1,
  4511. ack_number: Some(LOCAL_SEQ + 1),
  4512. payload: &b"abcdef"[..],
  4513. ..SEND_TEMPL
  4514. }, Ok(Some(TcpRepr {
  4515. seq_number: LOCAL_SEQ + 1,
  4516. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4517. window_len: 58,
  4518. ..RECV_TEMPL
  4519. })));
  4520. s.recv(|buffer| {
  4521. assert_eq!(buffer, b"abcdef");
  4522. (buffer.len(), ())
  4523. }).unwrap();
  4524. }
  4525. #[test]
  4526. fn test_buffer_wraparound_rx() {
  4527. let mut s = socket_established();
  4528. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4529. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4530. send!(s, TcpRepr {
  4531. seq_number: REMOTE_SEQ + 1,
  4532. ack_number: Some(LOCAL_SEQ + 1),
  4533. payload: &b"abc"[..],
  4534. ..SEND_TEMPL
  4535. });
  4536. s.recv(|buffer| {
  4537. assert_eq!(buffer, b"abc");
  4538. (buffer.len(), ())
  4539. }).unwrap();
  4540. send!(s, TcpRepr {
  4541. seq_number: REMOTE_SEQ + 1 + 3,
  4542. ack_number: Some(LOCAL_SEQ + 1),
  4543. payload: &b"defghi"[..],
  4544. ..SEND_TEMPL
  4545. });
  4546. let mut data = [0; 6];
  4547. assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
  4548. assert_eq!(data, &b"defghi"[..]);
  4549. }
  4550. #[test]
  4551. fn test_buffer_wraparound_tx() {
  4552. let mut s = socket_established();
  4553. s.tx_buffer = SocketBuffer::new(vec![b'.'; 9]);
  4554. assert_eq!(s.send_slice(b"xxxyyy"), Ok(6));
  4555. assert_eq!(s.tx_buffer.dequeue_many(3), &b"xxx"[..]);
  4556. assert_eq!(s.tx_buffer.len(), 3);
  4557. // "abcdef" not contiguous in tx buffer
  4558. assert_eq!(s.send_slice(b"abcdef"), Ok(6));
  4559. recv!(s, Ok(TcpRepr {
  4560. seq_number: LOCAL_SEQ + 1,
  4561. ack_number: Some(REMOTE_SEQ + 1),
  4562. payload: &b"yyyabc"[..],
  4563. ..RECV_TEMPL
  4564. }));
  4565. recv!(s, Ok(TcpRepr {
  4566. seq_number: LOCAL_SEQ + 1 + 6,
  4567. ack_number: Some(REMOTE_SEQ + 1),
  4568. payload: &b"def"[..],
  4569. ..RECV_TEMPL
  4570. }));
  4571. }
  4572. // =========================================================================================//
  4573. // Tests for graceful vs ungraceful rx close
  4574. // =========================================================================================//
  4575. #[test]
  4576. fn test_rx_close_fin() {
  4577. let mut s = socket_established();
  4578. send!(s, TcpRepr {
  4579. control: TcpControl::Fin,
  4580. seq_number: REMOTE_SEQ + 1,
  4581. ack_number: Some(LOCAL_SEQ + 1),
  4582. payload: &b"abc"[..],
  4583. ..SEND_TEMPL
  4584. });
  4585. s.recv(|data| {
  4586. assert_eq!(data, b"abc");
  4587. (3, ())
  4588. }).unwrap();
  4589. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4590. }
  4591. #[test]
  4592. fn test_rx_close_fin_in_fin_wait_1() {
  4593. let mut s = socket_fin_wait_1();
  4594. send!(s, TcpRepr {
  4595. control: TcpControl::Fin,
  4596. seq_number: REMOTE_SEQ + 1,
  4597. ack_number: Some(LOCAL_SEQ + 1),
  4598. payload: &b"abc"[..],
  4599. ..SEND_TEMPL
  4600. });
  4601. assert_eq!(s.state, State::Closing);
  4602. s.recv(|data| {
  4603. assert_eq!(data, b"abc");
  4604. (3, ())
  4605. }).unwrap();
  4606. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4607. }
  4608. #[test]
  4609. fn test_rx_close_fin_in_fin_wait_2() {
  4610. let mut s = socket_fin_wait_2();
  4611. send!(s, TcpRepr {
  4612. control: TcpControl::Fin,
  4613. seq_number: REMOTE_SEQ + 1,
  4614. ack_number: Some(LOCAL_SEQ + 1 + 1),
  4615. payload: &b"abc"[..],
  4616. ..SEND_TEMPL
  4617. });
  4618. assert_eq!(s.state, State::TimeWait);
  4619. s.recv(|data| {
  4620. assert_eq!(data, b"abc");
  4621. (3, ())
  4622. }).unwrap();
  4623. assert_eq!(s.recv(|_| (0, ())), Err(Error::Finished));
  4624. }
  4625. #[test]
  4626. fn test_rx_close_fin_with_hole() {
  4627. let mut s = socket_established();
  4628. send!(s, TcpRepr {
  4629. seq_number: REMOTE_SEQ + 1,
  4630. ack_number: Some(LOCAL_SEQ + 1),
  4631. payload: &b"abc"[..],
  4632. ..SEND_TEMPL
  4633. });
  4634. send!(s, TcpRepr {
  4635. control: TcpControl::Fin,
  4636. seq_number: REMOTE_SEQ + 1 + 6,
  4637. ack_number: Some(LOCAL_SEQ + 1),
  4638. payload: &b"ghi"[..],
  4639. ..SEND_TEMPL
  4640. }, Ok(Some(TcpRepr {
  4641. seq_number: LOCAL_SEQ + 1,
  4642. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4643. window_len: 61,
  4644. ..RECV_TEMPL
  4645. })));
  4646. s.recv(|data| {
  4647. assert_eq!(data, b"abc");
  4648. (3, ())
  4649. }).unwrap();
  4650. s.recv(|data| {
  4651. assert_eq!(data, b"");
  4652. (0, ())
  4653. }).unwrap();
  4654. send!(s, TcpRepr {
  4655. control: TcpControl::Rst,
  4656. seq_number: REMOTE_SEQ + 1 + 9,
  4657. ack_number: Some(LOCAL_SEQ + 1),
  4658. ..SEND_TEMPL
  4659. });
  4660. // Error must be `Illegal` even if we've received a FIN,
  4661. // because we are missing data.
  4662. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4663. }
  4664. #[test]
  4665. fn test_rx_close_rst() {
  4666. let mut s = socket_established();
  4667. send!(s, TcpRepr {
  4668. seq_number: REMOTE_SEQ + 1,
  4669. ack_number: Some(LOCAL_SEQ + 1),
  4670. payload: &b"abc"[..],
  4671. ..SEND_TEMPL
  4672. });
  4673. send!(s, TcpRepr {
  4674. control: TcpControl::Rst,
  4675. seq_number: REMOTE_SEQ + 1 + 3,
  4676. ack_number: Some(LOCAL_SEQ + 1),
  4677. ..SEND_TEMPL
  4678. });
  4679. s.recv(|data| {
  4680. assert_eq!(data, b"abc");
  4681. (3, ())
  4682. }).unwrap();
  4683. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4684. }
  4685. #[test]
  4686. fn test_rx_close_rst_with_hole() {
  4687. let mut s = socket_established();
  4688. send!(s, TcpRepr {
  4689. seq_number: REMOTE_SEQ + 1,
  4690. ack_number: Some(LOCAL_SEQ + 1),
  4691. payload: &b"abc"[..],
  4692. ..SEND_TEMPL
  4693. });
  4694. send!(s, TcpRepr {
  4695. seq_number: REMOTE_SEQ + 1 + 6,
  4696. ack_number: Some(LOCAL_SEQ + 1),
  4697. payload: &b"ghi"[..],
  4698. ..SEND_TEMPL
  4699. }, Ok(Some(TcpRepr {
  4700. seq_number: LOCAL_SEQ + 1,
  4701. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4702. window_len: 61,
  4703. ..RECV_TEMPL
  4704. })));
  4705. send!(s, TcpRepr {
  4706. control: TcpControl::Rst,
  4707. seq_number: REMOTE_SEQ + 1 + 9,
  4708. ack_number: Some(LOCAL_SEQ + 1),
  4709. ..SEND_TEMPL
  4710. });
  4711. s.recv(|data| {
  4712. assert_eq!(data, b"abc");
  4713. (3, ())
  4714. }).unwrap();
  4715. assert_eq!(s.recv(|_| (0, ())), Err(Error::Illegal));
  4716. }
  4717. // =========================================================================================//
  4718. // Tests for delayed ACK
  4719. // =========================================================================================//
  4720. #[test]
  4721. fn test_delayed_ack() {
  4722. let mut s = socket_established();
  4723. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  4724. send!(s, TcpRepr {
  4725. seq_number: REMOTE_SEQ + 1,
  4726. ack_number: Some(LOCAL_SEQ + 1),
  4727. payload: &b"abc"[..],
  4728. ..SEND_TEMPL
  4729. });
  4730. // No ACK is immediately sent.
  4731. recv!(s, Err(Error::Exhausted));
  4732. // After 10ms, it is sent.
  4733. recv!(s, time 11, Ok(TcpRepr {
  4734. seq_number: LOCAL_SEQ + 1,
  4735. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4736. window_len: 61,
  4737. ..RECV_TEMPL
  4738. }));
  4739. }
  4740. #[test]
  4741. fn test_delayed_ack_win() {
  4742. let mut s = socket_established();
  4743. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  4744. send!(s, TcpRepr {
  4745. seq_number: REMOTE_SEQ + 1,
  4746. ack_number: Some(LOCAL_SEQ + 1),
  4747. payload: &b"abc"[..],
  4748. ..SEND_TEMPL
  4749. });
  4750. // Reading the data off the buffer should cause a window update.
  4751. s.recv(|data| {
  4752. assert_eq!(data, b"abc");
  4753. (3, ())
  4754. }).unwrap();
  4755. // However, no ACK or window update is immediately sent.
  4756. recv!(s, Err(Error::Exhausted));
  4757. // After 10ms, it is sent.
  4758. recv!(s, time 11, Ok(TcpRepr {
  4759. seq_number: LOCAL_SEQ + 1,
  4760. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4761. ..RECV_TEMPL
  4762. }));
  4763. }
  4764. #[test]
  4765. fn test_delayed_ack_reply() {
  4766. let mut s = socket_established();
  4767. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  4768. send!(s, TcpRepr {
  4769. seq_number: REMOTE_SEQ + 1,
  4770. ack_number: Some(LOCAL_SEQ + 1),
  4771. payload: &b"abc"[..],
  4772. ..SEND_TEMPL
  4773. });
  4774. s.recv(|data| {
  4775. assert_eq!(data, b"abc");
  4776. (3, ())
  4777. }).unwrap();
  4778. s.send_slice(&b"xyz"[..]).unwrap();
  4779. // Writing data to the socket causes ACK to not be delayed,
  4780. // because it is immediately sent with the data.
  4781. recv!(s, Ok(TcpRepr {
  4782. seq_number: LOCAL_SEQ + 1,
  4783. ack_number: Some(REMOTE_SEQ + 1 + 3),
  4784. payload: &b"xyz"[..],
  4785. ..RECV_TEMPL
  4786. }));
  4787. }
  4788. #[test]
  4789. fn test_delayed_ack_every_second_packet() {
  4790. let mut s = socket_established();
  4791. s.set_ack_delay(Some(ACK_DELAY_DEFAULT));
  4792. send!(s, TcpRepr {
  4793. seq_number: REMOTE_SEQ + 1,
  4794. ack_number: Some(LOCAL_SEQ + 1),
  4795. payload: &b"abc"[..],
  4796. ..SEND_TEMPL
  4797. });
  4798. // No ACK is immediately sent.
  4799. recv!(s, Err(Error::Exhausted));
  4800. send!(s, TcpRepr {
  4801. seq_number: REMOTE_SEQ + 1 + 3,
  4802. ack_number: Some(LOCAL_SEQ + 1),
  4803. payload: &b"def"[..],
  4804. ..SEND_TEMPL
  4805. });
  4806. // Every 2nd packet, ACK is sent without delay.
  4807. recv!(s, Ok(TcpRepr {
  4808. seq_number: LOCAL_SEQ + 1,
  4809. ack_number: Some(REMOTE_SEQ + 1 + 6),
  4810. window_len: 58,
  4811. ..RECV_TEMPL
  4812. }));
  4813. }
  4814. // =========================================================================================//
  4815. // Tests for packet filtering.
  4816. // =========================================================================================//
  4817. #[test]
  4818. fn test_doesnt_accept_wrong_port() {
  4819. let mut s = socket_established();
  4820. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  4821. s.assembler = Assembler::new(s.rx_buffer.capacity());
  4822. let tcp_repr = TcpRepr {
  4823. seq_number: REMOTE_SEQ + 1,
  4824. ack_number: Some(LOCAL_SEQ + 1),
  4825. dst_port: LOCAL_PORT + 1,
  4826. ..SEND_TEMPL
  4827. };
  4828. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  4829. let tcp_repr = TcpRepr {
  4830. seq_number: REMOTE_SEQ + 1,
  4831. ack_number: Some(LOCAL_SEQ + 1),
  4832. src_port: REMOTE_PORT + 1,
  4833. ..SEND_TEMPL
  4834. };
  4835. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  4836. }
  4837. #[test]
  4838. fn test_doesnt_accept_wrong_ip() {
  4839. let s = socket_established();
  4840. let tcp_repr = TcpRepr {
  4841. seq_number: REMOTE_SEQ + 1,
  4842. ack_number: Some(LOCAL_SEQ + 1),
  4843. payload: &b"abcdef"[..],
  4844. ..SEND_TEMPL
  4845. };
  4846. let ip_repr = IpRepr::Unspecified {
  4847. src_addr: MOCK_IP_ADDR_2,
  4848. dst_addr: MOCK_IP_ADDR_1,
  4849. protocol: IpProtocol::Tcp,
  4850. payload_len: tcp_repr.buffer_len(),
  4851. hop_limit: 64
  4852. };
  4853. assert!(s.accepts(&ip_repr, &tcp_repr));
  4854. let ip_repr_wrong_src = IpRepr::Unspecified {
  4855. src_addr: MOCK_IP_ADDR_3,
  4856. dst_addr: MOCK_IP_ADDR_1,
  4857. protocol: IpProtocol::Tcp,
  4858. payload_len: tcp_repr.buffer_len(),
  4859. hop_limit: 64
  4860. };
  4861. assert!(!s.accepts(&ip_repr_wrong_src, &tcp_repr));
  4862. let ip_repr_wrong_dst = IpRepr::Unspecified {
  4863. src_addr: MOCK_IP_ADDR_2,
  4864. dst_addr: MOCK_IP_ADDR_3,
  4865. protocol: IpProtocol::Tcp,
  4866. payload_len: tcp_repr.buffer_len(),
  4867. hop_limit: 64
  4868. };
  4869. assert!(!s.accepts(&ip_repr_wrong_dst, &tcp_repr));
  4870. }
  4871. // =========================================================================================//
  4872. // Timer tests
  4873. // =========================================================================================//
  4874. #[test]
  4875. fn test_timer_retransmit() {
  4876. const RTO: Duration = Duration::from_millis(100);
  4877. let mut r = Timer::default();
  4878. assert_eq!(r.should_retransmit(Instant::from_secs(1)), None);
  4879. r.set_for_retransmit(Instant::from_millis(1000), RTO);
  4880. assert_eq!(r.should_retransmit(Instant::from_millis(1000)), None);
  4881. assert_eq!(r.should_retransmit(Instant::from_millis(1050)), None);
  4882. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), Some(Duration::from_millis(101)));
  4883. r.set_for_retransmit(Instant::from_millis(1101), RTO);
  4884. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), None);
  4885. assert_eq!(r.should_retransmit(Instant::from_millis(1150)), None);
  4886. assert_eq!(r.should_retransmit(Instant::from_millis(1200)), None);
  4887. assert_eq!(r.should_retransmit(Instant::from_millis(1301)), Some(Duration::from_millis(300)));
  4888. r.set_for_idle(Instant::from_millis(1301), None);
  4889. assert_eq!(r.should_retransmit(Instant::from_millis(1350)), None);
  4890. }
  4891. #[test]
  4892. fn test_rtt_estimator() {
  4893. #[cfg(feature = "log")]
  4894. init_logger();
  4895. let mut r = RttEstimator::default();
  4896. let rtos = &[
  4897. 751, 766, 755, 731, 697, 656, 613, 567,
  4898. 523, 484, 445, 411, 378, 350, 322, 299,
  4899. 280, 261, 243, 229, 215, 206, 197, 188
  4900. ];
  4901. for &rto in rtos {
  4902. r.sample(100);
  4903. assert_eq!(r.retransmission_timeout(), Duration::from_millis(rto));
  4904. }
  4905. }
  4906. }