tcp.rs 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837
  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};
  5. use {Error, Result};
  6. use phy::DeviceCapabilities;
  7. use time::{Duration, Instant};
  8. use socket::{Socket, SocketMeta, SocketHandle, PollAt};
  9. use storage::{Assembler, RingBuffer};
  10. use wire::{IpProtocol, IpRepr, IpAddress, IpEndpoint, TcpSeqNumber, TcpRepr, TcpControl};
  11. /// A TCP socket ring buffer.
  12. pub type SocketBuffer<'a> = RingBuffer<'a, u8>;
  13. /// The state of a TCP socket, according to [RFC 793].
  14. ///
  15. /// [RFC 793]: https://tools.ietf.org/html/rfc793
  16. #[derive(Debug, PartialEq, Eq, Clone, Copy)]
  17. pub enum State {
  18. Closed,
  19. Listen,
  20. SynSent,
  21. SynReceived,
  22. Established,
  23. FinWait1,
  24. FinWait2,
  25. CloseWait,
  26. Closing,
  27. LastAck,
  28. TimeWait
  29. }
  30. impl fmt::Display for State {
  31. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  32. match self {
  33. &State::Closed => write!(f, "CLOSED"),
  34. &State::Listen => write!(f, "LISTEN"),
  35. &State::SynSent => write!(f, "SYN-SENT"),
  36. &State::SynReceived => write!(f, "SYN-RECEIVED"),
  37. &State::Established => write!(f, "ESTABLISHED"),
  38. &State::FinWait1 => write!(f, "FIN-WAIT-1"),
  39. &State::FinWait2 => write!(f, "FIN-WAIT-2"),
  40. &State::CloseWait => write!(f, "CLOSE-WAIT"),
  41. &State::Closing => write!(f, "CLOSING"),
  42. &State::LastAck => write!(f, "LAST-ACK"),
  43. &State::TimeWait => write!(f, "TIME-WAIT")
  44. }
  45. }
  46. }
  47. #[derive(Debug, Clone, Copy, PartialEq)]
  48. enum Timer {
  49. Idle {
  50. keep_alive_at: Option<Instant>,
  51. },
  52. Retransmit {
  53. expires_at: Instant,
  54. delay: Duration
  55. },
  56. Close {
  57. expires_at: Instant
  58. }
  59. }
  60. const RETRANSMIT_DELAY: Duration = Duration { millis: 100 };
  61. const CLOSE_DELAY: Duration = Duration { millis: 10_000 };
  62. impl Default for Timer {
  63. fn default() -> Timer {
  64. Timer::Idle { keep_alive_at: None }
  65. }
  66. }
  67. impl Timer {
  68. fn should_keep_alive(&self, timestamp: Instant) -> bool {
  69. match *self {
  70. Timer::Idle { keep_alive_at: Some(keep_alive_at) }
  71. if timestamp >= keep_alive_at => {
  72. true
  73. }
  74. _ => false
  75. }
  76. }
  77. fn should_retransmit(&self, timestamp: Instant) -> Option<Duration> {
  78. match *self {
  79. Timer::Retransmit { expires_at, delay }
  80. if timestamp >= expires_at => {
  81. Some(timestamp - expires_at + delay)
  82. }
  83. _ => None
  84. }
  85. }
  86. fn should_close(&self, timestamp: Instant) -> bool {
  87. match *self {
  88. Timer::Close { expires_at }
  89. if timestamp >= expires_at => {
  90. true
  91. }
  92. _ => false
  93. }
  94. }
  95. fn poll_at(&self) -> PollAt {
  96. match *self {
  97. Timer::Idle { keep_alive_at: Some(keep_alive_at) } => PollAt::Time(keep_alive_at),
  98. Timer::Idle { keep_alive_at: None } => PollAt::Ingress,
  99. Timer::Retransmit { expires_at, .. } => PollAt::Time(expires_at),
  100. Timer::Close { expires_at } => PollAt::Time(expires_at),
  101. }
  102. }
  103. fn set_for_idle(&mut self, timestamp: Instant, interval: Option<Duration>) {
  104. *self = Timer::Idle {
  105. keep_alive_at: interval.map(|interval| timestamp + interval)
  106. }
  107. }
  108. fn set_keep_alive(&mut self) {
  109. match *self {
  110. Timer::Idle { ref mut keep_alive_at }
  111. if keep_alive_at.is_none() => {
  112. *keep_alive_at = Some(Instant::from_millis(0))
  113. }
  114. _ => ()
  115. }
  116. }
  117. fn rewind_keep_alive(&mut self, timestamp: Instant, interval: Option<Duration>) {
  118. match self {
  119. &mut Timer::Idle { ref mut keep_alive_at } => {
  120. *keep_alive_at = interval.map(|interval| timestamp + interval)
  121. }
  122. _ => ()
  123. }
  124. }
  125. fn set_for_retransmit(&mut self, timestamp: Instant) {
  126. match *self {
  127. Timer::Idle { .. } => {
  128. *self = Timer::Retransmit {
  129. expires_at: timestamp + RETRANSMIT_DELAY,
  130. delay: RETRANSMIT_DELAY,
  131. }
  132. }
  133. Timer::Retransmit { expires_at, delay }
  134. if timestamp >= expires_at => {
  135. *self = Timer::Retransmit {
  136. expires_at: timestamp + delay,
  137. delay: delay * 2
  138. }
  139. }
  140. Timer::Retransmit { .. } => (),
  141. Timer::Close { .. } => ()
  142. }
  143. }
  144. fn set_for_close(&mut self, timestamp: Instant) {
  145. *self = Timer::Close {
  146. expires_at: timestamp + CLOSE_DELAY
  147. }
  148. }
  149. fn is_retransmit(&self) -> bool {
  150. match *self {
  151. Timer::Retransmit {..} => true,
  152. _ => false,
  153. }
  154. }
  155. }
  156. /// A Transmission Control Protocol socket.
  157. ///
  158. /// A TCP socket may passively listen for connections or actively connect to another endpoint.
  159. /// Note that, for listening sockets, there is no "backlog"; to be able to simultaneously
  160. /// accept several connections, as many sockets must be allocated, or any new connection
  161. /// attempts will be reset.
  162. #[derive(Debug)]
  163. pub struct TcpSocket<'a> {
  164. pub(crate) meta: SocketMeta,
  165. state: State,
  166. timer: Timer,
  167. assembler: Assembler,
  168. rx_buffer: SocketBuffer<'a>,
  169. tx_buffer: SocketBuffer<'a>,
  170. /// Interval after which, if no inbound packets are received, the connection is aborted.
  171. timeout: Option<Duration>,
  172. /// Interval at which keep-alive packets will be sent.
  173. keep_alive: Option<Duration>,
  174. /// The time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  175. hop_limit: Option<u8>,
  176. /// Address passed to listen(). Listen address is set when listen() is called and
  177. /// used every time the socket is reset back to the LISTEN state.
  178. listen_address: IpAddress,
  179. /// Current local endpoint. This is used for both filtering the incoming packets and
  180. /// setting the source address. When listening or initiating connection on/from
  181. /// an unspecified address, this field is updated with the chosen source address before
  182. /// any packets are sent.
  183. local_endpoint: IpEndpoint,
  184. /// Current remote endpoint. This is used for both filtering the incoming packets and
  185. /// setting the destination address. If the remote endpoint is unspecified, it means that
  186. /// aborting the connection will not send an RST, and, in TIME-WAIT state, will not
  187. /// send an ACK.
  188. remote_endpoint: IpEndpoint,
  189. /// The sequence number corresponding to the beginning of the transmit buffer.
  190. /// I.e. an ACK(local_seq_no+n) packet removes n bytes from the transmit buffer.
  191. local_seq_no: TcpSeqNumber,
  192. /// The sequence number corresponding to the beginning of the receive buffer.
  193. /// I.e. userspace reading n bytes adds n to remote_seq_no.
  194. remote_seq_no: TcpSeqNumber,
  195. /// The last sequence number sent.
  196. /// I.e. in an idle socket, local_seq_no+tx_buffer.len().
  197. remote_last_seq: TcpSeqNumber,
  198. /// The last acknowledgement number sent.
  199. /// I.e. in an idle socket, remote_seq_no+rx_buffer.len().
  200. remote_last_ack: Option<TcpSeqNumber>,
  201. /// The last window length sent.
  202. remote_last_win: u16,
  203. /// The speculative remote window size.
  204. /// I.e. the actual remote window size minus the count of in-flight octets.
  205. remote_win_len: usize,
  206. /// The maximum number of data octets that the remote side may receive.
  207. remote_mss: usize,
  208. /// The timestamp of the last packet received.
  209. remote_last_ts: Option<Instant>,
  210. }
  211. const DEFAULT_MSS: usize = 536;
  212. impl<'a> TcpSocket<'a> {
  213. /// Create a socket using the given buffers.
  214. pub fn new<T>(rx_buffer: T, tx_buffer: T) -> TcpSocket<'a>
  215. where T: Into<SocketBuffer<'a>> {
  216. let (rx_buffer, tx_buffer) = (rx_buffer.into(), tx_buffer.into());
  217. if rx_buffer.capacity() > <u16>::max_value() as usize {
  218. panic!("buffers larger than {} require window scaling, which is not implemented",
  219. <u16>::max_value())
  220. }
  221. TcpSocket {
  222. meta: SocketMeta::default(),
  223. state: State::Closed,
  224. timer: Timer::default(),
  225. assembler: Assembler::new(rx_buffer.capacity()),
  226. tx_buffer: tx_buffer,
  227. rx_buffer: rx_buffer,
  228. timeout: None,
  229. keep_alive: None,
  230. hop_limit: None,
  231. listen_address: IpAddress::default(),
  232. local_endpoint: IpEndpoint::default(),
  233. remote_endpoint: IpEndpoint::default(),
  234. local_seq_no: TcpSeqNumber::default(),
  235. remote_seq_no: TcpSeqNumber::default(),
  236. remote_last_seq: TcpSeqNumber::default(),
  237. remote_last_ack: None,
  238. remote_last_win: 0,
  239. remote_win_len: 0,
  240. remote_mss: DEFAULT_MSS,
  241. remote_last_ts: None,
  242. }
  243. }
  244. /// Return the socket handle.
  245. #[inline]
  246. pub fn handle(&self) -> SocketHandle {
  247. self.meta.handle
  248. }
  249. /// Return the timeout duration.
  250. ///
  251. /// See also the [set_timeout](#method.set_timeout) method.
  252. pub fn timeout(&self) -> Option<Duration> {
  253. self.timeout
  254. }
  255. /// Set the timeout duration.
  256. ///
  257. /// A socket with a timeout duration set will abort the connection if either of the following
  258. /// occurs:
  259. ///
  260. /// * After a [connect](#method.connect) call, the remote endpoint does not respond within
  261. /// the specified duration;
  262. /// * After establishing a connection, there is data in the transmit buffer and the remote
  263. /// endpoint exceeds the specified duration between any two packets it sends;
  264. /// * After enabling [keep-alive](#method.set_keep_alive), the remote endpoint exceeds
  265. /// the specified duration between any two packets it sends.
  266. pub fn set_timeout(&mut self, duration: Option<Duration>) {
  267. self.timeout = duration
  268. }
  269. /// Return the keep-alive interval.
  270. ///
  271. /// See also the [set_keep_alive](#method.set_keep_alive) method.
  272. pub fn keep_alive(&self) -> Option<Duration> {
  273. self.keep_alive
  274. }
  275. /// Set the keep-alive interval.
  276. ///
  277. /// An idle socket with a keep-alive interval set will transmit a "challenge ACK" packet
  278. /// every time it receives no communication during that interval. As a result, three things
  279. /// may happen:
  280. ///
  281. /// * The remote endpoint is fine and answers with an ACK packet.
  282. /// * The remote endpoint has rebooted and answers with an RST packet.
  283. /// * The remote endpoint has crashed and does not answer.
  284. ///
  285. /// The keep-alive functionality together with the timeout functionality allows to react
  286. /// to these error conditions.
  287. pub fn set_keep_alive(&mut self, interval: Option<Duration>) {
  288. self.keep_alive = interval;
  289. if self.keep_alive.is_some() {
  290. // If the connection is idle and we've just set the option, it would not take effect
  291. // until the next packet, unless we wind up the timer explicitly.
  292. self.timer.set_keep_alive();
  293. }
  294. }
  295. /// Return the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  296. ///
  297. /// See also the [set_hop_limit](#method.set_hop_limit) method
  298. pub fn hop_limit(&self) -> Option<u8> {
  299. self.hop_limit
  300. }
  301. /// Set the time-to-live (IPv4) or hop limit (IPv6) value used in outgoing packets.
  302. ///
  303. /// A socket without an explicitly set hop limit value uses the default [IANA recommended]
  304. /// value (64).
  305. ///
  306. /// # Panics
  307. ///
  308. /// This function panics if a hop limit value of 0 is given. See [RFC 1122 § 3.2.1.7].
  309. ///
  310. /// [IANA recommended]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml
  311. /// [RFC 1122 § 3.2.1.7]: https://tools.ietf.org/html/rfc1122#section-3.2.1.7
  312. pub fn set_hop_limit(&mut self, hop_limit: Option<u8>) {
  313. // A host MUST NOT send a datagram with a hop limit value of 0
  314. if let Some(0) = hop_limit {
  315. panic!("the time-to-live value of a packet must not be zero")
  316. }
  317. self.hop_limit = hop_limit
  318. }
  319. /// Return the local endpoint.
  320. #[inline]
  321. pub fn local_endpoint(&self) -> IpEndpoint {
  322. self.local_endpoint
  323. }
  324. /// Return the remote endpoint.
  325. #[inline]
  326. pub fn remote_endpoint(&self) -> IpEndpoint {
  327. self.remote_endpoint
  328. }
  329. /// Return the connection state, in terms of the TCP state machine.
  330. #[inline]
  331. pub fn state(&self) -> State {
  332. self.state
  333. }
  334. fn reset(&mut self) {
  335. self.state = State::Closed;
  336. self.timer = Timer::default();
  337. self.assembler = Assembler::new(self.rx_buffer.capacity());
  338. self.tx_buffer.clear();
  339. self.rx_buffer.clear();
  340. self.keep_alive = None;
  341. self.timeout = None;
  342. self.hop_limit = None;
  343. self.listen_address = IpAddress::default();
  344. self.local_endpoint = IpEndpoint::default();
  345. self.remote_endpoint = IpEndpoint::default();
  346. self.local_seq_no = TcpSeqNumber::default();
  347. self.remote_seq_no = TcpSeqNumber::default();
  348. self.remote_last_seq = TcpSeqNumber::default();
  349. self.remote_last_ack = None;
  350. self.remote_last_win = 0;
  351. self.remote_win_len = 0;
  352. self.remote_mss = DEFAULT_MSS;
  353. self.remote_last_ts = None;
  354. }
  355. /// Start listening on the given endpoint.
  356. ///
  357. /// This function returns `Err(Error::Illegal)` if the socket was already open
  358. /// (see [is_open](#method.is_open)), and `Err(Error::Unaddressable)`
  359. /// if the port in the given endpoint is zero.
  360. pub fn listen<T>(&mut self, local_endpoint: T) -> Result<()>
  361. where T: Into<IpEndpoint> {
  362. let local_endpoint = local_endpoint.into();
  363. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  364. if self.is_open() { return Err(Error::Illegal) }
  365. self.reset();
  366. self.listen_address = local_endpoint.addr;
  367. self.local_endpoint = local_endpoint;
  368. self.remote_endpoint = IpEndpoint::default();
  369. self.set_state(State::Listen);
  370. Ok(())
  371. }
  372. /// Connect to a given endpoint.
  373. ///
  374. /// The local port must be provided explicitly. Assuming `fn get_ephemeral_port() -> u16`
  375. /// allocates a port between 49152 and 65535, a connection may be established as follows:
  376. ///
  377. /// ```rust,ignore
  378. /// socket.connect((IpAddress::v4(10, 0, 0, 1), 80), get_ephemeral_port())
  379. /// ```
  380. ///
  381. /// The local address may optionally be provided.
  382. ///
  383. /// This function returns an error if the socket was open; see [is_open](#method.is_open).
  384. /// It also returns an error if the local or remote port is zero, or if the remote address
  385. /// is unspecified.
  386. pub fn connect<T, U>(&mut self, remote_endpoint: T, local_endpoint: U) -> Result<()>
  387. where T: Into<IpEndpoint>, U: Into<IpEndpoint> {
  388. let remote_endpoint = remote_endpoint.into();
  389. let local_endpoint = local_endpoint.into();
  390. if self.is_open() { return Err(Error::Illegal) }
  391. if !remote_endpoint.is_specified() { return Err(Error::Unaddressable) }
  392. if local_endpoint.port == 0 { return Err(Error::Unaddressable) }
  393. // If local address is not provided, use an unspecified address but a specified protocol.
  394. // This lets us lower IpRepr later to determine IP header size and calculate MSS,
  395. // but without committing to a specific address right away.
  396. let local_addr = match remote_endpoint.addr {
  397. IpAddress::Unspecified => return Err(Error::Unaddressable),
  398. _ => remote_endpoint.addr.to_unspecified(),
  399. };
  400. let local_endpoint = IpEndpoint { addr: local_addr, ..local_endpoint };
  401. // Carry over the local sequence number.
  402. let local_seq_no = self.local_seq_no;
  403. self.reset();
  404. self.local_endpoint = local_endpoint;
  405. self.remote_endpoint = remote_endpoint;
  406. self.local_seq_no = local_seq_no;
  407. self.remote_last_seq = local_seq_no;
  408. self.set_state(State::SynSent);
  409. Ok(())
  410. }
  411. /// Close the transmit half of the full-duplex connection.
  412. ///
  413. /// Note that there is no corresponding function for the receive half of the full-duplex
  414. /// connection; only the remote end can close it. If you no longer wish to receive any
  415. /// data and would like to reuse the socket right away, use [abort](#method.abort).
  416. pub fn close(&mut self) {
  417. match self.state {
  418. // In the LISTEN state there is no established connection.
  419. State::Listen =>
  420. self.set_state(State::Closed),
  421. // In the SYN-SENT state the remote endpoint is not yet synchronized and, upon
  422. // receiving an RST, will abort the connection.
  423. State::SynSent =>
  424. self.set_state(State::Closed),
  425. // In the SYN-RECEIVED, ESTABLISHED and CLOSE-WAIT states the transmit half
  426. // of the connection is open, and needs to be explicitly closed with a FIN.
  427. State::SynReceived | State::Established =>
  428. self.set_state(State::FinWait1),
  429. State::CloseWait =>
  430. self.set_state(State::LastAck),
  431. // In the FIN-WAIT-1, FIN-WAIT-2, CLOSING, LAST-ACK, TIME-WAIT and CLOSED states,
  432. // the transmit half of the connection is already closed, and no further
  433. // action is needed.
  434. State::FinWait1 | State::FinWait2 | State::Closing |
  435. State::TimeWait | State::LastAck | State::Closed => ()
  436. }
  437. }
  438. /// Aborts the connection, if any.
  439. ///
  440. /// This function instantly closes the socket. One reset packet will be sent to the remote
  441. /// endpoint.
  442. ///
  443. /// In terms of the TCP state machine, the socket may be in any state and is moved to
  444. /// the `CLOSED` state.
  445. pub fn abort(&mut self) {
  446. self.set_state(State::Closed);
  447. }
  448. /// Return whether the socket is passively listening for incoming connections.
  449. ///
  450. /// In terms of the TCP state machine, the socket must be in the `LISTEN` state.
  451. #[inline]
  452. pub fn is_listening(&self) -> bool {
  453. match self.state {
  454. State::Listen => true,
  455. _ => false
  456. }
  457. }
  458. /// Return whether the socket is open.
  459. ///
  460. /// This function returns true if the socket will process incoming or dispatch outgoing
  461. /// packets. Note that this does not mean that it is possible to send or receive data through
  462. /// the socket; for that, use [can_send](#method.can_send) or [can_recv](#method.can_recv).
  463. ///
  464. /// In terms of the TCP state machine, the socket must not be in the `CLOSED`
  465. /// or `TIME-WAIT` states.
  466. #[inline]
  467. pub fn is_open(&self) -> bool {
  468. match self.state {
  469. State::Closed => false,
  470. State::TimeWait => false,
  471. _ => true
  472. }
  473. }
  474. /// Return whether a connection is active.
  475. ///
  476. /// This function returns true if the socket is actively exchanging packets with
  477. /// a remote endpoint. Note that this does not mean that it is possible to send or receive
  478. /// data through the socket; for that, use [can_send](#method.can_send) or
  479. /// [can_recv](#method.can_recv).
  480. ///
  481. /// If a connection is established, [abort](#method.close) will send a reset to
  482. /// the remote endpoint.
  483. ///
  484. /// In terms of the TCP state machine, the socket must be in the `CLOSED`, `TIME-WAIT`,
  485. /// or `LISTEN` state.
  486. #[inline]
  487. pub fn is_active(&self) -> bool {
  488. match self.state {
  489. State::Closed => false,
  490. State::TimeWait => false,
  491. State::Listen => false,
  492. _ => true
  493. }
  494. }
  495. /// Return whether the transmit half of the full-duplex connection is open.
  496. ///
  497. /// This function returns true if it's possible to send data and have it arrive
  498. /// to the remote endpoint. However, it does not make any guarantees about the state
  499. /// of the transmit buffer, and even if it returns true, [send](#method.send) may
  500. /// not be able to enqueue any octets.
  501. ///
  502. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED` or
  503. /// `CLOSE-WAIT` state.
  504. #[inline]
  505. pub fn may_send(&self) -> bool {
  506. match self.state {
  507. State::Established => true,
  508. // In CLOSE-WAIT, the remote endpoint has closed our receive half of the connection
  509. // but we still can transmit indefinitely.
  510. State::CloseWait => true,
  511. _ => false
  512. }
  513. }
  514. /// Return whether the receive half of the full-duplex connection is open.
  515. ///
  516. /// This function returns true if it's possible to receive data from the remote endpoint.
  517. /// It will return true while there is data in the receive buffer, and if there isn't,
  518. /// as long as the remote endpoint has not closed the connection.
  519. ///
  520. /// In terms of the TCP state machine, the socket must be in the `ESTABLISHED`,
  521. /// `FIN-WAIT-1`, or `FIN-WAIT-2` state, or have data in the receive buffer instead.
  522. #[inline]
  523. pub fn may_recv(&self) -> bool {
  524. match self.state {
  525. State::Established => true,
  526. // In FIN-WAIT-1/2, we have closed our transmit half of the connection but
  527. // we still can receive indefinitely.
  528. State::FinWait1 | State::FinWait2 => true,
  529. // If we have something in the receive buffer, we can receive that.
  530. _ if self.rx_buffer.len() > 0 => true,
  531. _ => false
  532. }
  533. }
  534. /// Check whether the transmit half of the full-duplex connection is open
  535. /// (see [may_send](#method.may_send), and the transmit buffer is not full.
  536. #[inline]
  537. pub fn can_send(&self) -> bool {
  538. if !self.may_send() { return false }
  539. !self.tx_buffer.is_full()
  540. }
  541. /// Check whether the receive half of the full-duplex connection buffer is open
  542. /// (see [may_recv](#method.may_recv), and the receive buffer is not empty.
  543. #[inline]
  544. pub fn can_recv(&self) -> bool {
  545. if !self.may_recv() { return false }
  546. !self.rx_buffer.is_empty()
  547. }
  548. fn send_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  549. where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
  550. if !self.may_send() { return Err(Error::Illegal) }
  551. // The connection might have been idle for a long time, and so remote_last_ts
  552. // would be far in the past. Unless we clear it here, we'll abort the connection
  553. // down over in dispatch() by erroneously detecting it as timed out.
  554. if self.tx_buffer.is_empty() { self.remote_last_ts = None }
  555. let _old_length = self.tx_buffer.len();
  556. let (size, result) = f(&mut self.tx_buffer);
  557. if size > 0 {
  558. #[cfg(any(test, feature = "verbose"))]
  559. net_trace!("{}:{}:{}: tx buffer: enqueueing {} octets (now {})",
  560. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  561. size, _old_length + size);
  562. }
  563. Ok(result)
  564. }
  565. /// Call `f` with the largest contiguous slice of octets in the transmit buffer,
  566. /// and enqueue the amount of elements returned by `f`.
  567. ///
  568. /// This function returns `Err(Error::Illegal) if the transmit half of
  569. /// the connection is not open; see [may_send](#method.may_send).
  570. pub fn send<'b, F, R>(&'b mut self, f: F) -> Result<R>
  571. where F: FnOnce(&'b mut [u8]) -> (usize, R) {
  572. self.send_impl(|tx_buffer| {
  573. tx_buffer.enqueue_many_with(f)
  574. })
  575. }
  576. /// Enqueue a sequence of octets to be sent, and fill it from a slice.
  577. ///
  578. /// This function returns the amount of bytes actually enqueued, which is limited
  579. /// by the amount of free space in the transmit buffer; down to zero.
  580. ///
  581. /// See also [send](#method.send).
  582. pub fn send_slice(&mut self, data: &[u8]) -> Result<usize> {
  583. self.send_impl(|tx_buffer| {
  584. let size = tx_buffer.enqueue_slice(data);
  585. (size, size)
  586. })
  587. }
  588. fn recv_impl<'b, F, R>(&'b mut self, f: F) -> Result<R>
  589. where F: FnOnce(&'b mut SocketBuffer<'a>) -> (usize, R) {
  590. // We may have received some data inside the initial SYN, but until the connection
  591. // is fully open we must not dequeue any data, as it may be overwritten by e.g.
  592. // another (stale) SYN. (We do not support TCP Fast Open.)
  593. if !self.may_recv() { return Err(Error::Illegal) }
  594. let _old_length = self.rx_buffer.len();
  595. let (size, result) = f(&mut self.rx_buffer);
  596. self.remote_seq_no += size;
  597. if size > 0 {
  598. #[cfg(any(test, feature = "verbose"))]
  599. net_trace!("{}:{}:{}: rx buffer: dequeueing {} octets (now {})",
  600. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  601. size, _old_length - size);
  602. }
  603. Ok(result)
  604. }
  605. /// Call `f` with the largest contiguous slice of octets in the receive buffer,
  606. /// and dequeue the amount of elements returned by `f`.
  607. ///
  608. /// This function returns `Err(Error::Illegal) if the receive half of
  609. /// the connection is not open; see [may_recv](#method.may_recv).
  610. pub fn recv<'b, F, R>(&'b mut self, f: F) -> Result<R>
  611. where F: FnOnce(&'b mut [u8]) -> (usize, R) {
  612. self.recv_impl(|rx_buffer| {
  613. rx_buffer.dequeue_many_with(f)
  614. })
  615. }
  616. /// Dequeue a sequence of received octets, and fill a slice from it.
  617. ///
  618. /// This function returns the amount of bytes actually dequeued, which is limited
  619. /// by the amount of free space in the transmit buffer; down to zero.
  620. ///
  621. /// See also [recv](#method.recv).
  622. pub fn recv_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  623. self.recv_impl(|rx_buffer| {
  624. let size = rx_buffer.dequeue_slice(data);
  625. (size, size)
  626. })
  627. }
  628. /// Peek at a sequence of received octets without removing them from
  629. /// the receive buffer, and return a pointer to it.
  630. ///
  631. /// This function otherwise behaves identically to [recv](#method.recv).
  632. pub fn peek(&mut self, size: usize) -> Result<&[u8]> {
  633. // See recv() above.
  634. if !self.may_recv() { return Err(Error::Illegal) }
  635. let buffer = self.rx_buffer.get_allocated(0, size);
  636. if buffer.len() > 0 {
  637. #[cfg(any(test, feature = "verbose"))]
  638. net_trace!("{}:{}:{}: rx buffer: peeking at {} octets",
  639. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  640. buffer.len());
  641. }
  642. Ok(buffer)
  643. }
  644. /// Peek at a sequence of received octets without removing them from
  645. /// the receive buffer, and fill a slice from it.
  646. ///
  647. /// This function otherwise behaves identically to [recv_slice](#method.recv_slice).
  648. pub fn peek_slice(&mut self, data: &mut [u8]) -> Result<usize> {
  649. let buffer = self.peek(data.len())?;
  650. let data = &mut data[..buffer.len()];
  651. data.copy_from_slice(buffer);
  652. Ok(buffer.len())
  653. }
  654. /// Return the amount of octets queued in the transmit buffer.
  655. ///
  656. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  657. pub fn send_queue(&self) -> usize {
  658. self.tx_buffer.len()
  659. }
  660. /// Return the amount of octets queued in the receive buffer.
  661. ///
  662. /// Note that the Berkeley sockets interface does not have an equivalent of this API.
  663. pub fn recv_queue(&self) -> usize {
  664. self.rx_buffer.len()
  665. }
  666. fn set_state(&mut self, state: State) {
  667. if self.state != state {
  668. if self.remote_endpoint.addr.is_unspecified() {
  669. net_trace!("{}:{}: state={}=>{}",
  670. self.meta.handle, self.local_endpoint,
  671. self.state, state);
  672. } else {
  673. net_trace!("{}:{}:{}: state={}=>{}",
  674. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  675. self.state, state);
  676. }
  677. }
  678. self.state = state
  679. }
  680. pub(crate) fn reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  681. let reply_repr = TcpRepr {
  682. src_port: repr.dst_port,
  683. dst_port: repr.src_port,
  684. control: TcpControl::None,
  685. seq_number: TcpSeqNumber(0),
  686. ack_number: None,
  687. window_len: 0,
  688. max_seg_size: None,
  689. payload: &[]
  690. };
  691. let ip_reply_repr = IpRepr::Unspecified {
  692. src_addr: ip_repr.dst_addr(),
  693. dst_addr: ip_repr.src_addr(),
  694. protocol: IpProtocol::Tcp,
  695. payload_len: reply_repr.buffer_len(),
  696. hop_limit: 64
  697. };
  698. (ip_reply_repr, reply_repr)
  699. }
  700. pub(crate) fn rst_reply(ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  701. debug_assert!(repr.control != TcpControl::Rst);
  702. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  703. // See https://www.snellman.net/blog/archive/2016-02-01-tcp-rst/ for explanation
  704. // of why we sometimes send an RST and sometimes an RST|ACK
  705. reply_repr.control = TcpControl::Rst;
  706. reply_repr.seq_number = repr.ack_number.unwrap_or_default();
  707. if repr.control == TcpControl::Syn {
  708. reply_repr.ack_number = Some(repr.seq_number + repr.segment_len());
  709. }
  710. (ip_reply_repr, reply_repr)
  711. }
  712. fn ack_reply(&mut self, ip_repr: &IpRepr, repr: &TcpRepr) -> (IpRepr, TcpRepr<'static>) {
  713. let (ip_reply_repr, mut reply_repr) = Self::reply(ip_repr, repr);
  714. // From RFC 793:
  715. // [...] an empty acknowledgment segment containing the current send-sequence number
  716. // and an acknowledgment indicating the next sequence number expected
  717. // to be received.
  718. reply_repr.seq_number = self.remote_last_seq;
  719. reply_repr.ack_number = self.remote_last_ack;
  720. reply_repr.window_len = self.rx_buffer.window() as u16;
  721. self.remote_last_win = reply_repr.window_len;
  722. (ip_reply_repr, reply_repr)
  723. }
  724. pub(crate) fn accepts(&self, ip_repr: &IpRepr, repr: &TcpRepr) -> bool {
  725. if self.state == State::Closed { return false }
  726. // If we're still listening for SYNs and the packet has an ACK, it cannot
  727. // be destined to this socket, but another one may well listen on the same
  728. // local endpoint.
  729. if self.state == State::Listen && repr.ack_number.is_some() { return false }
  730. // Reject packets with a wrong destination.
  731. if self.local_endpoint.port != repr.dst_port { return false }
  732. if !self.local_endpoint.addr.is_unspecified() &&
  733. self.local_endpoint.addr != ip_repr.dst_addr() { return false }
  734. // Reject packets from a source to which we aren't connected.
  735. if self.remote_endpoint.port != 0 &&
  736. self.remote_endpoint.port != repr.src_port { return false }
  737. if !self.remote_endpoint.addr.is_unspecified() &&
  738. self.remote_endpoint.addr != ip_repr.src_addr() { return false }
  739. true
  740. }
  741. pub(crate) fn process(&mut self, timestamp: Instant, ip_repr: &IpRepr, repr: &TcpRepr) ->
  742. Result<Option<(IpRepr, TcpRepr<'static>)>> {
  743. debug_assert!(self.accepts(ip_repr, repr));
  744. // Consider how much the sequence number space differs from the transmit buffer space.
  745. let (sent_syn, sent_fin) = match self.state {
  746. // In SYN-SENT or SYN-RECEIVED, we've just sent a SYN.
  747. State::SynSent | State::SynReceived => (true, false),
  748. // In FIN-WAIT-1, LAST-ACK, or CLOSING, we've just sent a FIN.
  749. State::FinWait1 | State::LastAck | State::Closing => (false, true),
  750. // In all other states we've already got acknowledgemetns for
  751. // all of the control flags we sent.
  752. _ => (false, false)
  753. };
  754. let control_len = (sent_syn as usize) + (sent_fin as usize);
  755. // Reject unacceptable acknowledgements.
  756. match (self.state, repr) {
  757. // An RST received in response to initial SYN is acceptable if it acknowledges
  758. // the initial SYN.
  759. (State::SynSent, &TcpRepr {
  760. control: TcpControl::Rst, ack_number: None, ..
  761. }) => {
  762. net_debug!("{}:{}:{}: unacceptable RST (expecting RST|ACK) \
  763. in response to initial SYN",
  764. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  765. return Err(Error::Dropped)
  766. }
  767. (State::SynSent, &TcpRepr {
  768. control: TcpControl::Rst, ack_number: Some(ack_number), ..
  769. }) => {
  770. if ack_number != self.local_seq_no + 1 {
  771. net_debug!("{}:{}:{}: unacceptable RST|ACK in response to initial SYN",
  772. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  773. return Err(Error::Dropped)
  774. }
  775. }
  776. // Any other RST need only have a valid sequence number.
  777. (_, &TcpRepr { control: TcpControl::Rst, .. }) => (),
  778. // The initial SYN cannot contain an acknowledgement.
  779. (State::Listen, &TcpRepr { ack_number: None, .. }) => (),
  780. // This case is handled above.
  781. (State::Listen, &TcpRepr { ack_number: Some(_), .. }) => unreachable!(),
  782. // Every packet after the initial SYN must be an acknowledgement.
  783. (_, &TcpRepr { ack_number: None, .. }) => {
  784. net_debug!("{}:{}:{}: expecting an ACK",
  785. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  786. return Err(Error::Dropped)
  787. }
  788. // Every acknowledgement must be for transmitted but unacknowledged data.
  789. (_, &TcpRepr { ack_number: Some(ack_number), .. }) => {
  790. let unacknowledged = self.tx_buffer.len() + control_len;
  791. if ack_number < self.local_seq_no {
  792. net_debug!("{}:{}:{}: duplicate ACK ({} not in {}...{})",
  793. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  794. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  795. // FIXME: implement fast retransmit
  796. return Err(Error::Dropped)
  797. }
  798. if ack_number > self.local_seq_no + unacknowledged {
  799. net_debug!("{}:{}:{}: unacceptable ACK ({} not in {}...{})",
  800. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  801. ack_number, self.local_seq_no, self.local_seq_no + unacknowledged);
  802. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  803. }
  804. }
  805. }
  806. let window_start = self.remote_seq_no + self.rx_buffer.len();
  807. let window_end = self.remote_seq_no + self.rx_buffer.capacity();
  808. let segment_start = repr.seq_number;
  809. let segment_end = repr.seq_number + repr.segment_len();
  810. let payload_offset;
  811. match self.state {
  812. // In LISTEN and SYN-SENT states, we have not yet synchronized with the remote end.
  813. State::Listen | State::SynSent =>
  814. payload_offset = 0,
  815. // In all other states, segments must occupy a valid portion of the receive window.
  816. _ => {
  817. let mut segment_in_window = true;
  818. if window_start == window_end && segment_start != segment_end {
  819. net_debug!("{}:{}:{}: non-zero-length segment with zero receive window, \
  820. will only send an ACK",
  821. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  822. segment_in_window = false;
  823. }
  824. if segment_start == segment_end && segment_end == window_start - 1 {
  825. net_debug!("{}:{}:{}: received a keep-alive or window probe packet, \
  826. will send an ACK",
  827. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  828. segment_in_window = false;
  829. } else if !((window_start <= segment_start && segment_start <= window_end) &&
  830. (window_start <= segment_end && segment_end <= window_end)) {
  831. net_debug!("{}:{}:{}: segment not in receive window \
  832. ({}..{} not intersecting {}..{}), will send challenge ACK",
  833. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  834. segment_start, segment_end, window_start, window_end);
  835. segment_in_window = false;
  836. }
  837. if segment_in_window {
  838. // We've checked that segment_start >= window_start above.
  839. payload_offset = (segment_start - window_start) as usize;
  840. } else {
  841. // If we're in the TIME-WAIT state, restart the TIME-WAIT timeout, since
  842. // the remote end may not have realized we've closed the connection.
  843. if self.state == State::TimeWait {
  844. self.timer.set_for_close(timestamp);
  845. }
  846. return Ok(Some(self.ack_reply(ip_repr, &repr)))
  847. }
  848. }
  849. }
  850. // Compute the amount of acknowledged octets, removing the SYN and FIN bits
  851. // from the sequence space.
  852. let mut ack_len = 0;
  853. let mut ack_of_fin = false;
  854. if repr.control != TcpControl::Rst {
  855. if let Some(ack_number) = repr.ack_number {
  856. ack_len = ack_number - self.local_seq_no;
  857. // There could have been no data sent before the SYN, so we always remove it
  858. // from the sequence space.
  859. if sent_syn {
  860. ack_len -= 1
  861. }
  862. // We could've sent data before the FIN, so only remove FIN from the sequence
  863. // space if all of that data is acknowledged.
  864. if sent_fin && self.tx_buffer.len() + 1 == ack_len {
  865. ack_len -= 1;
  866. net_trace!("{}:{}:{}: received ACK of FIN",
  867. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  868. ack_of_fin = true;
  869. }
  870. }
  871. }
  872. // Disregard control flags we don't care about or shouldn't act on yet.
  873. let mut control = repr.control;
  874. control = control.quash_psh();
  875. // If a FIN is received at the end of the current segment but the start of the segment
  876. // is not at the start of the receive window, disregard this FIN.
  877. if control == TcpControl::Fin && window_start != segment_start {
  878. control = TcpControl::None;
  879. }
  880. // Validate and update the state.
  881. match (self.state, control) {
  882. // RSTs are not accepted in the LISTEN state.
  883. (State::Listen, TcpControl::Rst) =>
  884. return Err(Error::Dropped),
  885. // RSTs in SYN-RECEIVED flip the socket back to the LISTEN state.
  886. (State::SynReceived, TcpControl::Rst) => {
  887. net_trace!("{}:{}:{}: received RST",
  888. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  889. self.local_endpoint.addr = self.listen_address;
  890. self.remote_endpoint = IpEndpoint::default();
  891. self.set_state(State::Listen);
  892. return Ok(None)
  893. }
  894. // RSTs in any other state close the socket.
  895. (_, TcpControl::Rst) => {
  896. net_trace!("{}:{}:{}: received RST",
  897. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  898. self.set_state(State::Closed);
  899. self.local_endpoint = IpEndpoint::default();
  900. self.remote_endpoint = IpEndpoint::default();
  901. return Ok(None)
  902. }
  903. // SYN packets in the LISTEN state change it to SYN-RECEIVED.
  904. (State::Listen, TcpControl::Syn) => {
  905. net_trace!("{}:{}: received SYN",
  906. self.meta.handle, self.local_endpoint);
  907. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  908. self.remote_endpoint = IpEndpoint::new(ip_repr.src_addr(), repr.src_port);
  909. // FIXME: use something more secure here
  910. self.local_seq_no = TcpSeqNumber(-repr.seq_number.0);
  911. self.remote_seq_no = repr.seq_number + 1;
  912. self.remote_last_seq = self.local_seq_no;
  913. if let Some(max_seg_size) = repr.max_seg_size {
  914. self.remote_mss = max_seg_size as usize
  915. }
  916. self.set_state(State::SynReceived);
  917. self.timer.set_for_idle(timestamp, self.keep_alive);
  918. }
  919. // ACK packets in the SYN-RECEIVED state change it to ESTABLISHED.
  920. (State::SynReceived, TcpControl::None) => {
  921. self.set_state(State::Established);
  922. self.timer.set_for_idle(timestamp, self.keep_alive);
  923. }
  924. // FIN packets in the SYN-RECEIVED state change it to CLOSE-WAIT.
  925. // It's not obvious from RFC 793 that this is permitted, but
  926. // 7th and 8th steps in the "SEGMENT ARRIVES" event describe this behavior.
  927. (State::SynReceived, TcpControl::Fin) => {
  928. self.remote_seq_no += 1;
  929. self.set_state(State::CloseWait);
  930. self.timer.set_for_idle(timestamp, self.keep_alive);
  931. }
  932. // SYN|ACK packets in the SYN-SENT state change it to ESTABLISHED.
  933. (State::SynSent, TcpControl::Syn) => {
  934. net_trace!("{}:{}:{}: received SYN|ACK",
  935. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  936. self.local_endpoint = IpEndpoint::new(ip_repr.dst_addr(), repr.dst_port);
  937. self.remote_seq_no = repr.seq_number + 1;
  938. self.remote_last_seq = self.local_seq_no + 1;
  939. self.remote_last_ack = Some(repr.seq_number);
  940. if let Some(max_seg_size) = repr.max_seg_size {
  941. self.remote_mss = max_seg_size as usize;
  942. }
  943. self.set_state(State::Established);
  944. self.timer.set_for_idle(timestamp, self.keep_alive);
  945. }
  946. // ACK packets in ESTABLISHED state reset the retransmit timer,
  947. // except for duplicate ACK packets which preserve it.
  948. (State::Established, TcpControl::None) => {
  949. if !self.timer.is_retransmit() || ack_len != 0 {
  950. self.timer.set_for_idle(timestamp, self.keep_alive);
  951. }
  952. },
  953. // FIN packets in ESTABLISHED state indicate the remote side has closed.
  954. (State::Established, TcpControl::Fin) => {
  955. self.remote_seq_no += 1;
  956. self.set_state(State::CloseWait);
  957. self.timer.set_for_idle(timestamp, self.keep_alive);
  958. }
  959. // ACK packets in FIN-WAIT-1 state change it to FIN-WAIT-2, if we've already
  960. // sent everything in the transmit buffer. If not, they reset the retransmit timer.
  961. (State::FinWait1, TcpControl::None) => {
  962. if ack_of_fin {
  963. self.set_state(State::FinWait2);
  964. }
  965. self.timer.set_for_idle(timestamp, self.keep_alive);
  966. }
  967. // FIN packets in FIN-WAIT-1 state change it to CLOSING, or to TIME-WAIT
  968. // if they also acknowledge our FIN.
  969. (State::FinWait1, TcpControl::Fin) => {
  970. self.remote_seq_no += 1;
  971. if ack_of_fin {
  972. self.set_state(State::TimeWait);
  973. self.timer.set_for_close(timestamp);
  974. } else {
  975. self.set_state(State::Closing);
  976. self.timer.set_for_idle(timestamp, self.keep_alive);
  977. }
  978. }
  979. // FIN packets in FIN-WAIT-2 state change it to TIME-WAIT.
  980. (State::FinWait2, TcpControl::Fin) => {
  981. self.remote_seq_no += 1;
  982. self.set_state(State::TimeWait);
  983. self.timer.set_for_close(timestamp);
  984. }
  985. // ACK packets in CLOSING state change it to TIME-WAIT.
  986. (State::Closing, TcpControl::None) => {
  987. if ack_of_fin {
  988. self.set_state(State::TimeWait);
  989. self.timer.set_for_close(timestamp);
  990. } else {
  991. self.timer.set_for_idle(timestamp, self.keep_alive);
  992. }
  993. }
  994. // ACK packets in CLOSE-WAIT state reset the retransmit timer.
  995. (State::CloseWait, TcpControl::None) => {
  996. self.timer.set_for_idle(timestamp, self.keep_alive);
  997. }
  998. // ACK packets in LAST-ACK state change it to CLOSED.
  999. (State::LastAck, TcpControl::None) => {
  1000. // Clear the remote endpoint, or we'll send an RST there.
  1001. self.set_state(State::Closed);
  1002. self.local_endpoint = IpEndpoint::default();
  1003. self.remote_endpoint = IpEndpoint::default();
  1004. }
  1005. _ => {
  1006. net_debug!("{}:{}:{}: unexpected packet {}",
  1007. self.meta.handle, self.local_endpoint, self.remote_endpoint, repr);
  1008. return Err(Error::Dropped)
  1009. }
  1010. }
  1011. // Update remote state.
  1012. self.remote_last_ts = Some(timestamp);
  1013. self.remote_win_len = repr.window_len as usize;
  1014. if ack_len > 0 {
  1015. // Dequeue acknowledged octets.
  1016. debug_assert!(self.tx_buffer.len() >= ack_len);
  1017. net_trace!("{}:{}:{}: tx buffer: dequeueing {} octets (now {})",
  1018. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1019. ack_len, self.tx_buffer.len() - ack_len);
  1020. self.tx_buffer.dequeue_allocated(ack_len);
  1021. }
  1022. if let Some(ack_number) = repr.ack_number {
  1023. // We've processed everything in the incoming segment, so advance the local
  1024. // sequence number past it.
  1025. self.local_seq_no = ack_number;
  1026. // During retransmission, if an earlier segment got lost but later was
  1027. // successfully received, self.local_seq_no can move past self.remote_last_seq.
  1028. // Do not attempt to retransmit the latter segments; not only this is pointless
  1029. // in theory but also impossible in practice, since they have been already
  1030. // deallocated from the buffer.
  1031. if self.remote_last_seq < self.local_seq_no {
  1032. self.remote_last_seq = self.local_seq_no
  1033. }
  1034. }
  1035. let payload_len = repr.payload.len();
  1036. if payload_len == 0 { return Ok(None) }
  1037. let assembler_was_empty = self.assembler.is_empty();
  1038. // Try adding payload octets to the assembler.
  1039. match self.assembler.add(payload_offset, payload_len) {
  1040. Ok(()) => {
  1041. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1042. // Place payload octets into the buffer.
  1043. net_trace!("{}:{}:{}: rx buffer: receiving {} octets at offset {}",
  1044. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1045. payload_len, payload_offset);
  1046. self.rx_buffer.write_unallocated(payload_offset, repr.payload);
  1047. }
  1048. Err(()) => {
  1049. net_debug!("{}:{}:{}: assembler: too many holes to add {} octets at offset {}",
  1050. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1051. payload_len, payload_offset);
  1052. return Err(Error::Dropped)
  1053. }
  1054. }
  1055. if let Some(contig_len) = self.assembler.remove_front() {
  1056. debug_assert!(self.assembler.total_size() == self.rx_buffer.capacity());
  1057. // Enqueue the contiguous data octets in front of the buffer.
  1058. net_trace!("{}:{}:{}: rx buffer: enqueueing {} octets (now {})",
  1059. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1060. contig_len, self.rx_buffer.len() + contig_len);
  1061. self.rx_buffer.enqueue_unallocated(contig_len);
  1062. }
  1063. if !self.assembler.is_empty() {
  1064. // Print the ranges recorded in the assembler.
  1065. net_trace!("{}:{}:{}: assembler: {}",
  1066. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1067. self.assembler);
  1068. }
  1069. // Per RFC 5681, we should send an immediate ACK when either:
  1070. // 1) an out-of-order segment is received, or
  1071. // 2) a segment arrives that fills in all or part of a gap in sequence space.
  1072. if !self.assembler.is_empty() || !assembler_was_empty {
  1073. // Note that we change the transmitter state here.
  1074. // This is fine because smoltcp assumes that it can always transmit zero or one
  1075. // packets for every packet it receives.
  1076. net_trace!("{}:{}:{}: ACKing incoming segment",
  1077. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1078. self.remote_last_ack = Some(self.remote_seq_no + self.rx_buffer.len());
  1079. Ok(Some(self.ack_reply(ip_repr, &repr)))
  1080. } else {
  1081. Ok(None)
  1082. }
  1083. }
  1084. fn timed_out(&self, timestamp: Instant) -> bool {
  1085. match (self.remote_last_ts, self.timeout) {
  1086. (Some(remote_last_ts), Some(timeout)) =>
  1087. timestamp >= remote_last_ts + timeout,
  1088. (_, _) =>
  1089. false
  1090. }
  1091. }
  1092. fn seq_to_transmit(&self) -> bool {
  1093. let control;
  1094. match self.state {
  1095. State::SynSent | State::SynReceived =>
  1096. control = TcpControl::Syn,
  1097. State::FinWait1 | State::LastAck =>
  1098. control = TcpControl::Fin,
  1099. _ => control = TcpControl::None
  1100. }
  1101. if self.remote_win_len > 0 {
  1102. self.remote_last_seq < self.local_seq_no + self.tx_buffer.len() + control.len()
  1103. } else {
  1104. false
  1105. }
  1106. }
  1107. fn ack_to_transmit(&self) -> bool {
  1108. if let Some(remote_last_ack) = self.remote_last_ack {
  1109. remote_last_ack < self.remote_seq_no + self.rx_buffer.len()
  1110. } else {
  1111. false
  1112. }
  1113. }
  1114. fn window_to_update(&self) -> bool {
  1115. self.rx_buffer.window() as u16 > self.remote_last_win
  1116. }
  1117. pub(crate) fn dispatch<F>(&mut self, timestamp: Instant, caps: &DeviceCapabilities,
  1118. emit: F) -> Result<()>
  1119. where F: FnOnce((IpRepr, TcpRepr)) -> Result<()> {
  1120. if !self.remote_endpoint.is_specified() { return Err(Error::Exhausted) }
  1121. if self.remote_last_ts.is_none() {
  1122. // We get here in exactly two cases:
  1123. // 1) This socket just transitioned into SYN-SENT.
  1124. // 2) This socket had an empty transmit buffer and some data was added there.
  1125. // Both are similar in that the socket has been quiet for an indefinite
  1126. // period of time, it isn't anymore, and the local endpoint is talking.
  1127. // So, we start counting the timeout not from the last received packet
  1128. // but from the first transmitted one.
  1129. self.remote_last_ts = Some(timestamp);
  1130. }
  1131. // Check if any state needs to be changed because of a timer.
  1132. if self.timed_out(timestamp) {
  1133. // If a timeout expires, we should abort the connection.
  1134. net_debug!("{}:{}:{}: timeout exceeded",
  1135. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1136. self.set_state(State::Closed);
  1137. } else if !self.seq_to_transmit() {
  1138. if let Some(retransmit_delta) = self.timer.should_retransmit(timestamp) {
  1139. // If a retransmit timer expired, we should resend data starting at the last ACK.
  1140. net_debug!("{}:{}:{}: retransmitting at t+{}",
  1141. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1142. retransmit_delta);
  1143. self.remote_last_seq = self.local_seq_no;
  1144. }
  1145. }
  1146. // Decide whether we're sending a packet.
  1147. if self.seq_to_transmit() {
  1148. // If we have data to transmit and it fits into partner's window, do it.
  1149. net_trace!("{}:{}:{}: outgoing segment will send data or flags",
  1150. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1151. } else if self.ack_to_transmit() {
  1152. // If we have data to acknowledge, do it.
  1153. net_trace!("{}:{}:{}: outgoing segment will acknowledge",
  1154. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1155. } else if self.window_to_update() {
  1156. // If we have window length increase to advertise, do it.
  1157. net_trace!("{}:{}:{}: outgoing segment will update window",
  1158. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1159. } else if self.state == State::Closed {
  1160. // If we need to abort the connection, do it.
  1161. net_trace!("{}:{}:{}: outgoing segment will abort connection",
  1162. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1163. } else if self.timer.should_retransmit(timestamp).is_some() {
  1164. // If we have packets to retransmit, do it.
  1165. net_trace!("{}:{}:{}: retransmit timer expired",
  1166. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1167. } else if self.timer.should_keep_alive(timestamp) {
  1168. // If we need to transmit a keep-alive packet, do it.
  1169. net_trace!("{}:{}:{}: keep-alive timer expired",
  1170. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1171. } else if self.timer.should_close(timestamp) {
  1172. // If we have spent enough time in the TIME-WAIT state, close the socket.
  1173. net_trace!("{}:{}:{}: TIME-WAIT timer expired",
  1174. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1175. self.reset();
  1176. return Err(Error::Exhausted)
  1177. } else {
  1178. return Err(Error::Exhausted)
  1179. }
  1180. // Construct the lowered IP representation.
  1181. // We might need this to calculate the MSS, so do it early.
  1182. let mut ip_repr = IpRepr::Unspecified {
  1183. src_addr: self.local_endpoint.addr,
  1184. dst_addr: self.remote_endpoint.addr,
  1185. protocol: IpProtocol::Tcp,
  1186. hop_limit: self.hop_limit.unwrap_or(64),
  1187. payload_len: 0
  1188. }.lower(&[])?;
  1189. // Construct the basic TCP representation, an empty ACK packet.
  1190. // We'll adjust this to be more specific as needed.
  1191. let mut repr = TcpRepr {
  1192. src_port: self.local_endpoint.port,
  1193. dst_port: self.remote_endpoint.port,
  1194. control: TcpControl::None,
  1195. seq_number: self.remote_last_seq,
  1196. ack_number: Some(self.remote_seq_no + self.rx_buffer.len()),
  1197. window_len: self.rx_buffer.window() as u16,
  1198. max_seg_size: None,
  1199. payload: &[]
  1200. };
  1201. match self.state {
  1202. // We transmit an RST in the CLOSED state. If we ended up in the CLOSED state
  1203. // with a specified endpoint, it means that the socket was aborted.
  1204. State::Closed => {
  1205. repr.control = TcpControl::Rst;
  1206. }
  1207. // We never transmit anything in the LISTEN state.
  1208. State::Listen => return Err(Error::Exhausted),
  1209. // We transmit a SYN in the SYN-SENT state.
  1210. // We transmit a SYN|ACK in the SYN-RECEIVED state.
  1211. State::SynSent | State::SynReceived => {
  1212. repr.control = TcpControl::Syn;
  1213. if self.state == State::SynSent {
  1214. repr.ack_number = None;
  1215. }
  1216. }
  1217. // We transmit data in all states where we may have data in the buffer,
  1218. // or the transmit half of the connection is still open:
  1219. // the ESTABLISHED, FIN-WAIT-1, CLOSE-WAIT and LAST-ACK states.
  1220. State::Established | State::FinWait1 | State::CloseWait | State::LastAck => {
  1221. // Extract as much data as the remote side can receive in this packet
  1222. // from the transmit buffer.
  1223. let offset = self.remote_last_seq - self.local_seq_no;
  1224. let size = cmp::min(self.remote_win_len, self.remote_mss);
  1225. repr.payload = self.tx_buffer.get_allocated(offset, size);
  1226. // If we've sent everything we had in the buffer, follow it with the PSH or FIN
  1227. // flags, depending on whether the transmit half of the connection is open.
  1228. if offset + repr.payload.len() == self.tx_buffer.len() {
  1229. match self.state {
  1230. State::FinWait1 | State::LastAck =>
  1231. repr.control = TcpControl::Fin,
  1232. State::Established | State::CloseWait if repr.payload.len() > 0 =>
  1233. repr.control = TcpControl::Psh,
  1234. _ => ()
  1235. }
  1236. }
  1237. }
  1238. // We do not transmit anything in the FIN-WAIT-2 state.
  1239. State::FinWait2 => return Err(Error::Exhausted),
  1240. // We do not transmit data or control flags in the CLOSING or TIME-WAIT states,
  1241. // but we may retransmit an ACK.
  1242. State::Closing | State::TimeWait => ()
  1243. }
  1244. // There might be more than one reason to send a packet. E.g. the keep-alive timer
  1245. // has expired, and we also have data in transmit buffer. Since any packet that occupies
  1246. // sequence space will elicit an ACK, we only need to send an explicit packet if we
  1247. // couldn't fill the sequence space with anything.
  1248. let is_keep_alive;
  1249. if self.timer.should_keep_alive(timestamp) && repr.is_empty() {
  1250. repr.seq_number = repr.seq_number - 1;
  1251. repr.payload = b"\x00"; // RFC 1122 says we should do this
  1252. is_keep_alive = true;
  1253. } else {
  1254. is_keep_alive = false;
  1255. }
  1256. // Trace a summary of what will be sent.
  1257. if is_keep_alive {
  1258. net_trace!("{}:{}:{}: sending a keep-alive",
  1259. self.meta.handle, self.local_endpoint, self.remote_endpoint);
  1260. } else if repr.payload.len() > 0 {
  1261. net_trace!("{}:{}:{}: tx buffer: sending {} octets at offset {}",
  1262. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1263. repr.payload.len(), self.remote_last_seq - self.local_seq_no);
  1264. }
  1265. if repr.control != TcpControl::None || repr.payload.len() == 0 {
  1266. let flags =
  1267. match (repr.control, repr.ack_number) {
  1268. (TcpControl::Syn, None) => "SYN",
  1269. (TcpControl::Syn, Some(_)) => "SYN|ACK",
  1270. (TcpControl::Fin, Some(_)) => "FIN|ACK",
  1271. (TcpControl::Rst, Some(_)) => "RST|ACK",
  1272. (TcpControl::Psh, Some(_)) => "PSH|ACK",
  1273. (TcpControl::None, Some(_)) => "ACK",
  1274. _ => "<unreachable>"
  1275. };
  1276. net_trace!("{}:{}:{}: sending {}",
  1277. self.meta.handle, self.local_endpoint, self.remote_endpoint,
  1278. flags);
  1279. }
  1280. if repr.control == TcpControl::Syn {
  1281. // Fill the MSS option. See RFC 6691 for an explanation of this calculation.
  1282. let mut max_segment_size = caps.max_transmission_unit;
  1283. max_segment_size -= ip_repr.buffer_len();
  1284. max_segment_size -= repr.header_len();
  1285. repr.max_seg_size = Some(max_segment_size as u16);
  1286. }
  1287. // Actually send the packet. If this succeeds, it means the packet is in
  1288. // the device buffer, and its transmission is imminent. If not, we might have
  1289. // a number of problems, e.g. we need neighbor discovery.
  1290. //
  1291. // Bailing out if the packet isn't placed in the device buffer allows us
  1292. // to not waste time waiting for the retransmit timer on packets that we know
  1293. // for sure will not be successfully transmitted.
  1294. ip_repr.set_payload_len(repr.buffer_len());
  1295. emit((ip_repr, repr))?;
  1296. // We've sent something, whether useful data or a keep-alive packet, so rewind
  1297. // the keep-alive timer.
  1298. self.timer.rewind_keep_alive(timestamp, self.keep_alive);
  1299. // Leave the rest of the state intact if sending a keep-alive packet, since those
  1300. // carry a fake segment.
  1301. if is_keep_alive { return Ok(()) }
  1302. // We've sent a packet successfully, so we can update the internal state now.
  1303. self.remote_last_seq = repr.seq_number + repr.segment_len();
  1304. self.remote_last_ack = repr.ack_number;
  1305. self.remote_last_win = repr.window_len;
  1306. if !self.seq_to_transmit() && repr.segment_len() > 0 {
  1307. // If we've transmitted all data we could (and there was something at all,
  1308. // data or flag, to transmit, not just an ACK), wind up the retransmit timer.
  1309. self.timer.set_for_retransmit(timestamp);
  1310. }
  1311. if self.state == State::Closed {
  1312. // When aborting a connection, forget about it after sending a single RST packet.
  1313. self.local_endpoint = IpEndpoint::default();
  1314. self.remote_endpoint = IpEndpoint::default();
  1315. }
  1316. Ok(())
  1317. }
  1318. pub(crate) fn poll_at(&self) -> PollAt {
  1319. // The logic here mirrors the beginning of dispatch() closely.
  1320. if !self.remote_endpoint.is_specified() {
  1321. // No one to talk to, nothing to transmit.
  1322. PollAt::Ingress
  1323. } else if self.remote_last_ts.is_none() {
  1324. // Socket stopped being quiet recently, we need to acquire a timestamp.
  1325. PollAt::Now
  1326. } else if self.state == State::Closed {
  1327. // Socket was aborted, we have an RST packet to transmit.
  1328. PollAt::Now
  1329. } else if self.seq_to_transmit() || self.ack_to_transmit() || self.window_to_update() {
  1330. // We have a data or flag packet to transmit.
  1331. PollAt::Now
  1332. } else {
  1333. let timeout_poll_at = match (self.remote_last_ts, self.timeout) {
  1334. // If we're transmitting or retransmitting data, we need to poll at the moment
  1335. // when the timeout would expire.
  1336. (Some(remote_last_ts), Some(timeout)) => PollAt::Time(remote_last_ts + timeout),
  1337. // Otherwise we have no timeout.
  1338. (_, _) => PollAt::Ingress,
  1339. };
  1340. // We wait for the earliest of our timers to fire.
  1341. *[self.timer.poll_at(), timeout_poll_at]
  1342. .iter()
  1343. .filter(|x| !x.is_ingress())
  1344. .min().unwrap_or(&PollAt::Ingress)
  1345. }
  1346. }
  1347. }
  1348. impl<'a> Into<Socket<'a, 'static>> for TcpSocket<'a> {
  1349. fn into(self) -> Socket<'a, 'static> {
  1350. Socket::Tcp(self)
  1351. }
  1352. }
  1353. impl<'a> fmt::Write for TcpSocket<'a> {
  1354. fn write_str(&mut self, slice: &str) -> fmt::Result {
  1355. let slice = slice.as_bytes();
  1356. if self.send_slice(slice) == Ok(slice.len()) {
  1357. Ok(())
  1358. } else {
  1359. Err(fmt::Error)
  1360. }
  1361. }
  1362. }
  1363. #[cfg(test)]
  1364. mod test {
  1365. use core::i32;
  1366. use wire::{IpAddress, IpRepr, IpCidr};
  1367. use wire::ip::test::{MOCK_IP_ADDR_1, MOCK_IP_ADDR_2, MOCK_IP_ADDR_3, MOCK_UNSPECIFIED};
  1368. use super::*;
  1369. // =========================================================================================//
  1370. // Constants
  1371. // =========================================================================================//
  1372. const LOCAL_PORT: u16 = 80;
  1373. const REMOTE_PORT: u16 = 49500;
  1374. const LOCAL_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_1, port: LOCAL_PORT };
  1375. const REMOTE_END: IpEndpoint = IpEndpoint { addr: MOCK_IP_ADDR_2, port: REMOTE_PORT };
  1376. const LOCAL_SEQ: TcpSeqNumber = TcpSeqNumber(10000);
  1377. const REMOTE_SEQ: TcpSeqNumber = TcpSeqNumber(-10000);
  1378. const SEND_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1379. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1380. protocol: IpProtocol::Tcp, payload_len: 20,
  1381. hop_limit: 64
  1382. };
  1383. const SEND_TEMPL: TcpRepr<'static> = TcpRepr {
  1384. src_port: REMOTE_PORT, dst_port: LOCAL_PORT,
  1385. control: TcpControl::None,
  1386. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1387. window_len: 256, max_seg_size: None,
  1388. payload: &[]
  1389. };
  1390. const _RECV_IP_TEMPL: IpRepr = IpRepr::Unspecified {
  1391. src_addr: MOCK_IP_ADDR_1, dst_addr: MOCK_IP_ADDR_2,
  1392. protocol: IpProtocol::Tcp, payload_len: 20,
  1393. hop_limit: 64
  1394. };
  1395. const RECV_TEMPL: TcpRepr<'static> = TcpRepr {
  1396. src_port: LOCAL_PORT, dst_port: REMOTE_PORT,
  1397. control: TcpControl::None,
  1398. seq_number: TcpSeqNumber(0), ack_number: Some(TcpSeqNumber(0)),
  1399. window_len: 64, max_seg_size: None,
  1400. payload: &[]
  1401. };
  1402. #[cfg(feature = "proto-ipv6")]
  1403. const BASE_MSS: u16 = 1460;
  1404. #[cfg(all(feature = "proto-ipv4", not(feature = "proto-ipv6")))]
  1405. const BASE_MSS: u16 = 1480;
  1406. // =========================================================================================//
  1407. // Helper functions
  1408. // =========================================================================================//
  1409. fn send(socket: &mut TcpSocket, timestamp: Instant, repr: &TcpRepr) ->
  1410. Result<Option<TcpRepr<'static>>> {
  1411. let ip_repr = IpRepr::Unspecified {
  1412. src_addr: MOCK_IP_ADDR_2,
  1413. dst_addr: MOCK_IP_ADDR_1,
  1414. protocol: IpProtocol::Tcp,
  1415. payload_len: repr.buffer_len(),
  1416. hop_limit: 64
  1417. };
  1418. net_trace!("send: {}", repr);
  1419. assert!(socket.accepts(&ip_repr, repr));
  1420. match socket.process(timestamp, &ip_repr, repr) {
  1421. Ok(Some((_ip_repr, repr))) => {
  1422. net_trace!("recv: {}", repr);
  1423. Ok(Some(repr))
  1424. }
  1425. Ok(None) => Ok(None),
  1426. Err(err) => Err(err)
  1427. }
  1428. }
  1429. fn recv<F>(socket: &mut TcpSocket, timestamp: Instant, mut f: F)
  1430. where F: FnMut(Result<TcpRepr>) {
  1431. let mut caps = DeviceCapabilities::default();
  1432. caps.max_transmission_unit = 1520;
  1433. let result = socket.dispatch(timestamp, &caps, |(ip_repr, tcp_repr)| {
  1434. let ip_repr = ip_repr.lower(&[IpCidr::new(LOCAL_END.addr, 24)]).unwrap();
  1435. assert_eq!(ip_repr.protocol(), IpProtocol::Tcp);
  1436. assert_eq!(ip_repr.src_addr(), MOCK_IP_ADDR_1);
  1437. assert_eq!(ip_repr.dst_addr(), MOCK_IP_ADDR_2);
  1438. assert_eq!(ip_repr.payload_len(), tcp_repr.buffer_len());
  1439. net_trace!("recv: {}", tcp_repr);
  1440. Ok(f(Ok(tcp_repr)))
  1441. });
  1442. match result {
  1443. Ok(()) => (),
  1444. Err(e) => f(Err(e))
  1445. }
  1446. }
  1447. macro_rules! send {
  1448. ($socket:ident, $repr:expr) =>
  1449. (send!($socket, time 0, $repr));
  1450. ($socket:ident, $repr:expr, $result:expr) =>
  1451. (send!($socket, time 0, $repr, $result));
  1452. ($socket:ident, time $time:expr, $repr:expr) =>
  1453. (send!($socket, time $time, $repr, Ok(None)));
  1454. ($socket:ident, time $time:expr, $repr:expr, $result:expr) =>
  1455. (assert_eq!(send(&mut $socket, Instant::from_millis($time), &$repr), $result));
  1456. }
  1457. macro_rules! recv {
  1458. ($socket:ident, [$( $repr:expr ),*]) => ({
  1459. $( recv!($socket, Ok($repr)); )*
  1460. recv!($socket, Err(Error::Exhausted))
  1461. });
  1462. ($socket:ident, $result:expr) =>
  1463. (recv!($socket, time 0, $result));
  1464. ($socket:ident, time $time:expr, $result:expr) =>
  1465. (recv(&mut $socket, Instant::from_millis($time), |result| {
  1466. // Most of the time we don't care about the PSH flag.
  1467. let result = result.map(|mut repr| {
  1468. repr.control = repr.control.quash_psh();
  1469. repr
  1470. });
  1471. assert_eq!(result, $result)
  1472. }));
  1473. ($socket:ident, time $time:expr, $result:expr, exact) =>
  1474. (recv(&mut $socket, Instant::from_millis($time), |repr| assert_eq!(repr, $result)));
  1475. }
  1476. macro_rules! sanity {
  1477. ($socket1:expr, $socket2:expr) => ({
  1478. let (s1, s2) = ($socket1, $socket2);
  1479. assert_eq!(s1.state, s2.state, "state");
  1480. assert_eq!(s1.listen_address, s2.listen_address, "listen_address");
  1481. assert_eq!(s1.local_endpoint, s2.local_endpoint, "local_endpoint");
  1482. assert_eq!(s1.remote_endpoint, s2.remote_endpoint, "remote_endpoint");
  1483. assert_eq!(s1.local_seq_no, s2.local_seq_no, "local_seq_no");
  1484. assert_eq!(s1.remote_seq_no, s2.remote_seq_no, "remote_seq_no");
  1485. assert_eq!(s1.remote_last_seq, s2.remote_last_seq, "remote_last_seq");
  1486. assert_eq!(s1.remote_last_ack, s2.remote_last_ack, "remote_last_ack");
  1487. assert_eq!(s1.remote_last_win, s2.remote_last_win, "remote_last_win");
  1488. assert_eq!(s1.remote_win_len, s2.remote_win_len, "remote_win_len");
  1489. assert_eq!(s1.timer, s2.timer, "timer");
  1490. })
  1491. }
  1492. #[cfg(feature = "log")]
  1493. fn init_logger() {
  1494. extern crate log;
  1495. use std::boxed::Box;
  1496. struct Logger(());
  1497. impl log::Log for Logger {
  1498. fn enabled(&self, _metadata: &log::LogMetadata) -> bool {
  1499. true
  1500. }
  1501. fn log(&self, record: &log::LogRecord) {
  1502. println!("{}", record.args());
  1503. }
  1504. }
  1505. let _ = log::set_logger(|max_level| {
  1506. max_level.set(log::LogLevelFilter::Trace);
  1507. Box::new(Logger(()))
  1508. });
  1509. println!("");
  1510. }
  1511. fn socket() -> TcpSocket<'static> {
  1512. #[cfg(feature = "log")]
  1513. init_logger();
  1514. let rx_buffer = SocketBuffer::new(vec![0; 64]);
  1515. let tx_buffer = SocketBuffer::new(vec![0; 64]);
  1516. TcpSocket::new(rx_buffer, tx_buffer)
  1517. }
  1518. fn socket_syn_received() -> TcpSocket<'static> {
  1519. let mut s = socket();
  1520. s.state = State::SynReceived;
  1521. s.local_endpoint = LOCAL_END;
  1522. s.remote_endpoint = REMOTE_END;
  1523. s.local_seq_no = LOCAL_SEQ;
  1524. s.remote_seq_no = REMOTE_SEQ + 1;
  1525. s.remote_last_seq = LOCAL_SEQ;
  1526. s.remote_win_len = 256;
  1527. s
  1528. }
  1529. fn socket_syn_sent() -> TcpSocket<'static> {
  1530. let mut s = socket();
  1531. s.state = State::SynSent;
  1532. s.local_endpoint = IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_PORT);
  1533. s.remote_endpoint = REMOTE_END;
  1534. s.local_seq_no = LOCAL_SEQ;
  1535. s.remote_last_seq = LOCAL_SEQ;
  1536. s
  1537. }
  1538. fn socket_established() -> TcpSocket<'static> {
  1539. let mut s = socket_syn_received();
  1540. s.state = State::Established;
  1541. s.local_seq_no = LOCAL_SEQ + 1;
  1542. s.remote_last_seq = LOCAL_SEQ + 1;
  1543. s.remote_last_ack = Some(REMOTE_SEQ + 1);
  1544. s.remote_last_win = 64;
  1545. s
  1546. }
  1547. fn socket_fin_wait_1() -> TcpSocket<'static> {
  1548. let mut s = socket_established();
  1549. s.state = State::FinWait1;
  1550. s
  1551. }
  1552. fn socket_fin_wait_2() -> TcpSocket<'static> {
  1553. let mut s = socket_fin_wait_1();
  1554. s.state = State::FinWait2;
  1555. s.local_seq_no = LOCAL_SEQ + 1 + 1;
  1556. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1557. s
  1558. }
  1559. fn socket_closing() -> TcpSocket<'static> {
  1560. let mut s = socket_fin_wait_1();
  1561. s.state = State::Closing;
  1562. s.remote_last_seq = LOCAL_SEQ + 1 + 1;
  1563. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1564. s
  1565. }
  1566. fn socket_time_wait(from_closing: bool) -> TcpSocket<'static> {
  1567. let mut s = socket_fin_wait_2();
  1568. s.state = State::TimeWait;
  1569. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1570. if from_closing {
  1571. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  1572. }
  1573. s.timer = Timer::Close { expires_at: Instant::from_secs(1) + CLOSE_DELAY };
  1574. s
  1575. }
  1576. fn socket_close_wait() -> TcpSocket<'static> {
  1577. let mut s = socket_established();
  1578. s.state = State::CloseWait;
  1579. s.remote_seq_no = REMOTE_SEQ + 1 + 1;
  1580. s.remote_last_ack = Some(REMOTE_SEQ + 1 + 1);
  1581. s
  1582. }
  1583. fn socket_last_ack() -> TcpSocket<'static> {
  1584. let mut s = socket_close_wait();
  1585. s.state = State::LastAck;
  1586. s
  1587. }
  1588. fn socket_recved() -> TcpSocket<'static> {
  1589. let mut s = socket_established();
  1590. send!(s, TcpRepr {
  1591. seq_number: REMOTE_SEQ + 1,
  1592. ack_number: Some(LOCAL_SEQ + 1),
  1593. payload: &b"abcdef"[..],
  1594. ..SEND_TEMPL
  1595. });
  1596. recv!(s, [TcpRepr {
  1597. seq_number: LOCAL_SEQ + 1,
  1598. ack_number: Some(REMOTE_SEQ + 1 + 6),
  1599. window_len: 58,
  1600. ..RECV_TEMPL
  1601. }]);
  1602. s
  1603. }
  1604. // =========================================================================================//
  1605. // Tests for the CLOSED state.
  1606. // =========================================================================================//
  1607. #[test]
  1608. fn test_closed_reject() {
  1609. let s = socket();
  1610. assert_eq!(s.state, State::Closed);
  1611. let tcp_repr = TcpRepr {
  1612. control: TcpControl::Syn,
  1613. ..SEND_TEMPL
  1614. };
  1615. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1616. }
  1617. #[test]
  1618. fn test_closed_reject_after_listen() {
  1619. let mut s = socket();
  1620. s.listen(LOCAL_END).unwrap();
  1621. s.close();
  1622. let tcp_repr = TcpRepr {
  1623. control: TcpControl::Syn,
  1624. ..SEND_TEMPL
  1625. };
  1626. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1627. }
  1628. #[test]
  1629. fn test_closed_close() {
  1630. let mut s = socket();
  1631. s.close();
  1632. assert_eq!(s.state, State::Closed);
  1633. }
  1634. // =========================================================================================//
  1635. // Tests for the LISTEN state.
  1636. // =========================================================================================//
  1637. fn socket_listen() -> TcpSocket<'static> {
  1638. let mut s = socket();
  1639. s.state = State::Listen;
  1640. s.local_endpoint = IpEndpoint::new(IpAddress::default(), LOCAL_PORT);
  1641. s
  1642. }
  1643. #[test]
  1644. fn test_listen_sanity() {
  1645. let mut s = socket();
  1646. s.listen(LOCAL_PORT).unwrap();
  1647. sanity!(s, socket_listen());
  1648. }
  1649. #[test]
  1650. fn test_listen_validation() {
  1651. let mut s = socket();
  1652. assert_eq!(s.listen(0), Err(Error::Unaddressable));
  1653. }
  1654. #[test]
  1655. fn test_listen_twice() {
  1656. let mut s = socket();
  1657. assert_eq!(s.listen(80), Ok(()));
  1658. assert_eq!(s.listen(80), Err(Error::Illegal));
  1659. }
  1660. #[test]
  1661. fn test_listen_syn() {
  1662. let mut s = socket_listen();
  1663. send!(s, TcpRepr {
  1664. control: TcpControl::Syn,
  1665. seq_number: REMOTE_SEQ,
  1666. ack_number: None,
  1667. ..SEND_TEMPL
  1668. });
  1669. sanity!(s, socket_syn_received());
  1670. }
  1671. #[test]
  1672. fn test_listen_syn_reject_ack() {
  1673. let s = socket_listen();
  1674. let tcp_repr = TcpRepr {
  1675. control: TcpControl::Syn,
  1676. seq_number: REMOTE_SEQ,
  1677. ack_number: Some(LOCAL_SEQ),
  1678. ..SEND_TEMPL
  1679. };
  1680. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  1681. assert_eq!(s.state, State::Listen);
  1682. }
  1683. #[test]
  1684. fn test_listen_rst() {
  1685. let mut s = socket_listen();
  1686. send!(s, TcpRepr {
  1687. control: TcpControl::Rst,
  1688. seq_number: REMOTE_SEQ,
  1689. ack_number: None,
  1690. ..SEND_TEMPL
  1691. }, Err(Error::Dropped));
  1692. }
  1693. #[test]
  1694. fn test_listen_close() {
  1695. let mut s = socket_listen();
  1696. s.close();
  1697. assert_eq!(s.state, State::Closed);
  1698. }
  1699. // =========================================================================================//
  1700. // Tests for the SYN-RECEIVED state.
  1701. // =========================================================================================//
  1702. #[test]
  1703. fn test_syn_received_ack() {
  1704. let mut s = socket_syn_received();
  1705. recv!(s, [TcpRepr {
  1706. control: TcpControl::Syn,
  1707. seq_number: LOCAL_SEQ,
  1708. ack_number: Some(REMOTE_SEQ + 1),
  1709. max_seg_size: Some(BASE_MSS),
  1710. ..RECV_TEMPL
  1711. }]);
  1712. send!(s, TcpRepr {
  1713. seq_number: REMOTE_SEQ + 1,
  1714. ack_number: Some(LOCAL_SEQ + 1),
  1715. ..SEND_TEMPL
  1716. });
  1717. assert_eq!(s.state, State::Established);
  1718. sanity!(s, socket_established());
  1719. }
  1720. #[test]
  1721. fn test_syn_received_fin() {
  1722. let mut s = socket_syn_received();
  1723. recv!(s, [TcpRepr {
  1724. control: TcpControl::Syn,
  1725. seq_number: LOCAL_SEQ,
  1726. ack_number: Some(REMOTE_SEQ + 1),
  1727. max_seg_size: Some(BASE_MSS),
  1728. ..RECV_TEMPL
  1729. }]);
  1730. send!(s, TcpRepr {
  1731. control: TcpControl::Fin,
  1732. seq_number: REMOTE_SEQ + 1,
  1733. ack_number: Some(LOCAL_SEQ + 1),
  1734. payload: &b"abcdef"[..],
  1735. ..SEND_TEMPL
  1736. });
  1737. recv!(s, [TcpRepr {
  1738. seq_number: LOCAL_SEQ + 1,
  1739. ack_number: Some(REMOTE_SEQ + 1 + 6 + 1),
  1740. window_len: 58,
  1741. ..RECV_TEMPL
  1742. }]);
  1743. assert_eq!(s.state, State::CloseWait);
  1744. sanity!(s, TcpSocket {
  1745. remote_last_ack: Some(REMOTE_SEQ + 1 + 6 + 1),
  1746. remote_last_win: 58,
  1747. ..socket_close_wait()
  1748. });
  1749. }
  1750. #[test]
  1751. fn test_syn_received_rst() {
  1752. let mut s = socket_syn_received();
  1753. recv!(s, [TcpRepr {
  1754. control: TcpControl::Syn,
  1755. seq_number: LOCAL_SEQ,
  1756. ack_number: Some(REMOTE_SEQ + 1),
  1757. max_seg_size: Some(BASE_MSS),
  1758. ..RECV_TEMPL
  1759. }]);
  1760. send!(s, TcpRepr {
  1761. control: TcpControl::Rst,
  1762. seq_number: REMOTE_SEQ + 1,
  1763. ack_number: Some(LOCAL_SEQ),
  1764. ..SEND_TEMPL
  1765. });
  1766. assert_eq!(s.state, State::Listen);
  1767. assert_eq!(s.local_endpoint, IpEndpoint::new(IpAddress::Unspecified, LOCAL_END.port));
  1768. assert_eq!(s.remote_endpoint, IpEndpoint::default());
  1769. }
  1770. #[test]
  1771. fn test_syn_received_close() {
  1772. let mut s = socket_syn_received();
  1773. s.close();
  1774. assert_eq!(s.state, State::FinWait1);
  1775. }
  1776. // =========================================================================================//
  1777. // Tests for the SYN-SENT state.
  1778. // =========================================================================================//
  1779. #[test]
  1780. fn test_connect_validation() {
  1781. let mut s = socket();
  1782. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  1783. Err(Error::Unaddressable));
  1784. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 0)),
  1785. Err(Error::Unaddressable));
  1786. assert_eq!(s.connect((MOCK_UNSPECIFIED, 0), LOCAL_END),
  1787. Err(Error::Unaddressable));
  1788. assert_eq!(s.connect((IpAddress::Unspecified, 80), LOCAL_END),
  1789. Err(Error::Unaddressable));
  1790. }
  1791. #[test]
  1792. fn test_connect() {
  1793. let mut s = socket();
  1794. s.local_seq_no = LOCAL_SEQ;
  1795. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  1796. assert_eq!(s.local_endpoint, IpEndpoint::new(MOCK_UNSPECIFIED, LOCAL_END.port));
  1797. recv!(s, [TcpRepr {
  1798. control: TcpControl::Syn,
  1799. seq_number: LOCAL_SEQ,
  1800. ack_number: None,
  1801. max_seg_size: Some(BASE_MSS),
  1802. ..RECV_TEMPL
  1803. }]);
  1804. send!(s, TcpRepr {
  1805. control: TcpControl::Syn,
  1806. seq_number: REMOTE_SEQ,
  1807. ack_number: Some(LOCAL_SEQ + 1),
  1808. max_seg_size: Some(BASE_MSS - 80),
  1809. ..SEND_TEMPL
  1810. });
  1811. assert_eq!(s.local_endpoint, LOCAL_END);
  1812. }
  1813. #[test]
  1814. fn test_connect_unspecified_local() {
  1815. let mut s = socket();
  1816. assert_eq!(s.connect(REMOTE_END, (MOCK_UNSPECIFIED, 80)),
  1817. Ok(()));
  1818. s.abort();
  1819. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1820. Ok(()));
  1821. s.abort();
  1822. }
  1823. #[test]
  1824. fn test_connect_specified_local() {
  1825. let mut s = socket();
  1826. assert_eq!(s.connect(REMOTE_END, (MOCK_IP_ADDR_2, 80)),
  1827. Ok(()));
  1828. }
  1829. #[test]
  1830. fn test_connect_twice() {
  1831. let mut s = socket();
  1832. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1833. Ok(()));
  1834. assert_eq!(s.connect(REMOTE_END, (IpAddress::Unspecified, 80)),
  1835. Err(Error::Illegal));
  1836. }
  1837. #[test]
  1838. fn test_syn_sent_sanity() {
  1839. let mut s = socket();
  1840. s.local_seq_no = LOCAL_SEQ;
  1841. s.connect(REMOTE_END, LOCAL_END).unwrap();
  1842. sanity!(s, socket_syn_sent());
  1843. }
  1844. #[test]
  1845. fn test_syn_sent_syn_ack() {
  1846. let mut s = socket_syn_sent();
  1847. recv!(s, [TcpRepr {
  1848. control: TcpControl::Syn,
  1849. seq_number: LOCAL_SEQ,
  1850. ack_number: None,
  1851. max_seg_size: Some(BASE_MSS),
  1852. ..RECV_TEMPL
  1853. }]);
  1854. send!(s, TcpRepr {
  1855. control: TcpControl::Syn,
  1856. seq_number: REMOTE_SEQ,
  1857. ack_number: Some(LOCAL_SEQ + 1),
  1858. max_seg_size: Some(BASE_MSS - 80),
  1859. ..SEND_TEMPL
  1860. });
  1861. recv!(s, [TcpRepr {
  1862. seq_number: LOCAL_SEQ + 1,
  1863. ack_number: Some(REMOTE_SEQ + 1),
  1864. ..RECV_TEMPL
  1865. }]);
  1866. recv!(s, time 1000, Err(Error::Exhausted));
  1867. assert_eq!(s.state, State::Established);
  1868. sanity!(s, socket_established());
  1869. }
  1870. #[test]
  1871. fn test_syn_sent_rst() {
  1872. let mut s = socket_syn_sent();
  1873. send!(s, TcpRepr {
  1874. control: TcpControl::Rst,
  1875. seq_number: REMOTE_SEQ,
  1876. ack_number: Some(LOCAL_SEQ + 1),
  1877. ..SEND_TEMPL
  1878. });
  1879. assert_eq!(s.state, State::Closed);
  1880. }
  1881. #[test]
  1882. fn test_syn_sent_rst_no_ack() {
  1883. let mut s = socket_syn_sent();
  1884. send!(s, TcpRepr {
  1885. control: TcpControl::Rst,
  1886. seq_number: REMOTE_SEQ,
  1887. ack_number: None,
  1888. ..SEND_TEMPL
  1889. }, Err(Error::Dropped));
  1890. assert_eq!(s.state, State::SynSent);
  1891. }
  1892. #[test]
  1893. fn test_syn_sent_rst_bad_ack() {
  1894. let mut s = socket_syn_sent();
  1895. send!(s, TcpRepr {
  1896. control: TcpControl::Rst,
  1897. seq_number: REMOTE_SEQ,
  1898. ack_number: Some(TcpSeqNumber(1234)),
  1899. ..SEND_TEMPL
  1900. }, Err(Error::Dropped));
  1901. assert_eq!(s.state, State::SynSent);
  1902. }
  1903. #[test]
  1904. fn test_syn_sent_close() {
  1905. let mut s = socket();
  1906. s.close();
  1907. assert_eq!(s.state, State::Closed);
  1908. }
  1909. // =========================================================================================//
  1910. // Tests for the ESTABLISHED state.
  1911. // =========================================================================================//
  1912. #[test]
  1913. fn test_established_recv() {
  1914. let mut s = socket_established();
  1915. send!(s, TcpRepr {
  1916. seq_number: REMOTE_SEQ + 1,
  1917. ack_number: Some(LOCAL_SEQ + 1),
  1918. payload: &b"abcdef"[..],
  1919. ..SEND_TEMPL
  1920. });
  1921. recv!(s, [TcpRepr {
  1922. seq_number: LOCAL_SEQ + 1,
  1923. ack_number: Some(REMOTE_SEQ + 1 + 6),
  1924. window_len: 58,
  1925. ..RECV_TEMPL
  1926. }]);
  1927. assert_eq!(s.rx_buffer.dequeue_many(6), &b"abcdef"[..]);
  1928. }
  1929. #[test]
  1930. fn test_established_send() {
  1931. let mut s = socket_established();
  1932. // First roundtrip after establishing.
  1933. s.send_slice(b"abcdef").unwrap();
  1934. recv!(s, [TcpRepr {
  1935. seq_number: LOCAL_SEQ + 1,
  1936. ack_number: Some(REMOTE_SEQ + 1),
  1937. payload: &b"abcdef"[..],
  1938. ..RECV_TEMPL
  1939. }]);
  1940. assert_eq!(s.tx_buffer.len(), 6);
  1941. send!(s, TcpRepr {
  1942. seq_number: REMOTE_SEQ + 1,
  1943. ack_number: Some(LOCAL_SEQ + 1 + 6),
  1944. ..SEND_TEMPL
  1945. });
  1946. assert_eq!(s.tx_buffer.len(), 0);
  1947. // Second roundtrip.
  1948. s.send_slice(b"foobar").unwrap();
  1949. recv!(s, [TcpRepr {
  1950. seq_number: LOCAL_SEQ + 1 + 6,
  1951. ack_number: Some(REMOTE_SEQ + 1),
  1952. payload: &b"foobar"[..],
  1953. ..RECV_TEMPL
  1954. }]);
  1955. send!(s, TcpRepr {
  1956. seq_number: REMOTE_SEQ + 1,
  1957. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  1958. ..SEND_TEMPL
  1959. });
  1960. assert_eq!(s.tx_buffer.len(), 0);
  1961. }
  1962. #[test]
  1963. fn test_established_send_no_ack_send() {
  1964. let mut s = socket_established();
  1965. s.send_slice(b"abcdef").unwrap();
  1966. recv!(s, [TcpRepr {
  1967. seq_number: LOCAL_SEQ + 1,
  1968. ack_number: Some(REMOTE_SEQ + 1),
  1969. payload: &b"abcdef"[..],
  1970. ..RECV_TEMPL
  1971. }]);
  1972. s.send_slice(b"foobar").unwrap();
  1973. recv!(s, [TcpRepr {
  1974. seq_number: LOCAL_SEQ + 1 + 6,
  1975. ack_number: Some(REMOTE_SEQ + 1),
  1976. payload: &b"foobar"[..],
  1977. ..RECV_TEMPL
  1978. }]);
  1979. }
  1980. #[test]
  1981. fn test_established_send_buf_gt_win() {
  1982. let mut data = [0; 32];
  1983. for (i, elem) in data.iter_mut().enumerate() {
  1984. *elem = i as u8
  1985. }
  1986. let mut s = socket_established();
  1987. s.remote_win_len = 16;
  1988. s.send_slice(&data[..]).unwrap();
  1989. recv!(s, [TcpRepr {
  1990. seq_number: LOCAL_SEQ + 1,
  1991. ack_number: Some(REMOTE_SEQ + 1),
  1992. payload: &data[0..16],
  1993. ..RECV_TEMPL
  1994. }, TcpRepr {
  1995. seq_number: LOCAL_SEQ + 1 + 16,
  1996. ack_number: Some(REMOTE_SEQ + 1),
  1997. payload: &data[16..32],
  1998. ..RECV_TEMPL
  1999. }]);
  2000. }
  2001. #[test]
  2002. fn test_established_send_wrap() {
  2003. let mut s = socket_established();
  2004. let local_seq_start = TcpSeqNumber(i32::MAX - 1);
  2005. s.local_seq_no = local_seq_start + 1;
  2006. s.remote_last_seq = local_seq_start + 1;
  2007. s.send_slice(b"abc").unwrap();
  2008. recv!(s, time 1000, Ok(TcpRepr {
  2009. seq_number: local_seq_start + 1,
  2010. ack_number: Some(REMOTE_SEQ + 1),
  2011. payload: &b"abc"[..],
  2012. ..RECV_TEMPL
  2013. }));
  2014. }
  2015. #[test]
  2016. fn test_established_no_ack() {
  2017. let mut s = socket_established();
  2018. send!(s, TcpRepr {
  2019. seq_number: REMOTE_SEQ + 1,
  2020. ack_number: None,
  2021. ..SEND_TEMPL
  2022. }, Err(Error::Dropped));
  2023. }
  2024. #[test]
  2025. fn test_established_bad_ack() {
  2026. let mut s = socket_established();
  2027. // Already acknowledged data.
  2028. send!(s, TcpRepr {
  2029. seq_number: REMOTE_SEQ + 1,
  2030. ack_number: Some(TcpSeqNumber(LOCAL_SEQ.0 - 1)),
  2031. ..SEND_TEMPL
  2032. }, Err(Error::Dropped));
  2033. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2034. // Data not yet transmitted.
  2035. send!(s, TcpRepr {
  2036. seq_number: REMOTE_SEQ + 1,
  2037. ack_number: Some(LOCAL_SEQ + 10),
  2038. ..SEND_TEMPL
  2039. }, Ok(Some(TcpRepr {
  2040. seq_number: LOCAL_SEQ + 1,
  2041. ack_number: Some(REMOTE_SEQ + 1),
  2042. ..RECV_TEMPL
  2043. })));
  2044. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2045. }
  2046. #[test]
  2047. fn test_established_bad_seq() {
  2048. let mut s = socket_established();
  2049. // Data outside of receive window.
  2050. send!(s, TcpRepr {
  2051. seq_number: REMOTE_SEQ + 1 + 256,
  2052. ack_number: Some(LOCAL_SEQ + 1),
  2053. ..SEND_TEMPL
  2054. }, Ok(Some(TcpRepr {
  2055. seq_number: LOCAL_SEQ + 1,
  2056. ack_number: Some(REMOTE_SEQ + 1),
  2057. ..RECV_TEMPL
  2058. })));
  2059. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  2060. }
  2061. #[test]
  2062. fn test_established_fin() {
  2063. let mut s = socket_established();
  2064. send!(s, TcpRepr {
  2065. control: TcpControl::Fin,
  2066. seq_number: REMOTE_SEQ + 1,
  2067. ack_number: Some(LOCAL_SEQ + 1),
  2068. ..SEND_TEMPL
  2069. });
  2070. recv!(s, [TcpRepr {
  2071. seq_number: LOCAL_SEQ + 1,
  2072. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2073. ..RECV_TEMPL
  2074. }]);
  2075. assert_eq!(s.state, State::CloseWait);
  2076. sanity!(s, socket_close_wait());
  2077. }
  2078. #[test]
  2079. fn test_established_fin_after_missing() {
  2080. let mut s = socket_established();
  2081. send!(s, TcpRepr {
  2082. control: TcpControl::Fin,
  2083. seq_number: REMOTE_SEQ + 1 + 6,
  2084. ack_number: Some(LOCAL_SEQ + 1),
  2085. payload: &b"123456"[..],
  2086. ..SEND_TEMPL
  2087. }, Ok(Some(TcpRepr {
  2088. seq_number: LOCAL_SEQ + 1,
  2089. ack_number: Some(REMOTE_SEQ + 1),
  2090. ..RECV_TEMPL
  2091. })));
  2092. assert_eq!(s.state, State::Established);
  2093. send!(s, TcpRepr {
  2094. seq_number: REMOTE_SEQ + 1,
  2095. ack_number: Some(LOCAL_SEQ + 1),
  2096. payload: &b"abcdef"[..],
  2097. ..SEND_TEMPL
  2098. }, Ok(Some(TcpRepr {
  2099. seq_number: LOCAL_SEQ + 1,
  2100. ack_number: Some(REMOTE_SEQ + 1 + 6 + 6),
  2101. window_len: 52,
  2102. ..RECV_TEMPL
  2103. })));
  2104. assert_eq!(s.state, State::Established);
  2105. }
  2106. #[test]
  2107. fn test_established_send_fin() {
  2108. let mut s = socket_established();
  2109. s.send_slice(b"abcdef").unwrap();
  2110. send!(s, TcpRepr {
  2111. control: TcpControl::Fin,
  2112. seq_number: REMOTE_SEQ + 1,
  2113. ack_number: Some(LOCAL_SEQ + 1),
  2114. ..SEND_TEMPL
  2115. });
  2116. assert_eq!(s.state, State::CloseWait);
  2117. recv!(s, [TcpRepr {
  2118. seq_number: LOCAL_SEQ + 1,
  2119. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2120. payload: &b"abcdef"[..],
  2121. ..RECV_TEMPL
  2122. }]);
  2123. }
  2124. #[test]
  2125. fn test_established_rst() {
  2126. let mut s = socket_established();
  2127. send!(s, TcpRepr {
  2128. control: TcpControl::Rst,
  2129. seq_number: REMOTE_SEQ + 1,
  2130. ack_number: Some(LOCAL_SEQ + 1),
  2131. ..SEND_TEMPL
  2132. });
  2133. assert_eq!(s.state, State::Closed);
  2134. }
  2135. #[test]
  2136. fn test_established_rst_no_ack() {
  2137. let mut s = socket_established();
  2138. send!(s, TcpRepr {
  2139. control: TcpControl::Rst,
  2140. seq_number: REMOTE_SEQ + 1,
  2141. ack_number: None,
  2142. ..SEND_TEMPL
  2143. });
  2144. assert_eq!(s.state, State::Closed);
  2145. }
  2146. #[test]
  2147. fn test_established_close() {
  2148. let mut s = socket_established();
  2149. s.close();
  2150. assert_eq!(s.state, State::FinWait1);
  2151. sanity!(s, socket_fin_wait_1());
  2152. }
  2153. #[test]
  2154. fn test_established_abort() {
  2155. let mut s = socket_established();
  2156. s.abort();
  2157. assert_eq!(s.state, State::Closed);
  2158. recv!(s, [TcpRepr {
  2159. control: TcpControl::Rst,
  2160. seq_number: LOCAL_SEQ + 1,
  2161. ack_number: Some(REMOTE_SEQ + 1),
  2162. ..RECV_TEMPL
  2163. }]);
  2164. }
  2165. // =========================================================================================//
  2166. // Tests for the FIN-WAIT-1 state.
  2167. // =========================================================================================//
  2168. #[test]
  2169. fn test_fin_wait_1_fin_ack() {
  2170. let mut s = socket_fin_wait_1();
  2171. recv!(s, [TcpRepr {
  2172. control: TcpControl::Fin,
  2173. seq_number: LOCAL_SEQ + 1,
  2174. ack_number: Some(REMOTE_SEQ + 1),
  2175. ..RECV_TEMPL
  2176. }]);
  2177. send!(s, TcpRepr {
  2178. seq_number: REMOTE_SEQ + 1,
  2179. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2180. ..SEND_TEMPL
  2181. });
  2182. assert_eq!(s.state, State::FinWait2);
  2183. sanity!(s, socket_fin_wait_2());
  2184. }
  2185. #[test]
  2186. fn test_fin_wait_1_fin_fin() {
  2187. let mut s = socket_fin_wait_1();
  2188. recv!(s, [TcpRepr {
  2189. control: TcpControl::Fin,
  2190. seq_number: LOCAL_SEQ + 1,
  2191. ack_number: Some(REMOTE_SEQ + 1),
  2192. ..RECV_TEMPL
  2193. }]);
  2194. send!(s, TcpRepr {
  2195. control: TcpControl::Fin,
  2196. seq_number: REMOTE_SEQ + 1,
  2197. ack_number: Some(LOCAL_SEQ + 1),
  2198. ..SEND_TEMPL
  2199. });
  2200. assert_eq!(s.state, State::Closing);
  2201. sanity!(s, socket_closing());
  2202. }
  2203. #[test]
  2204. fn test_fin_wait_1_fin_with_data_queued() {
  2205. let mut s = socket_established();
  2206. s.remote_win_len = 6;
  2207. s.send_slice(b"abcdef123456").unwrap();
  2208. s.close();
  2209. recv!(s, Ok(TcpRepr {
  2210. seq_number: LOCAL_SEQ + 1,
  2211. ack_number: Some(REMOTE_SEQ + 1),
  2212. payload: &b"abcdef"[..],
  2213. ..RECV_TEMPL
  2214. }));
  2215. send!(s, TcpRepr {
  2216. seq_number: REMOTE_SEQ + 1,
  2217. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2218. ..SEND_TEMPL
  2219. });
  2220. assert_eq!(s.state, State::FinWait1);
  2221. }
  2222. #[test]
  2223. fn test_fin_wait_1_close() {
  2224. let mut s = socket_fin_wait_1();
  2225. s.close();
  2226. assert_eq!(s.state, State::FinWait1);
  2227. }
  2228. // =========================================================================================//
  2229. // Tests for the FIN-WAIT-2 state.
  2230. // =========================================================================================//
  2231. #[test]
  2232. fn test_fin_wait_2_fin() {
  2233. let mut s = socket_fin_wait_2();
  2234. send!(s, time 1_000, TcpRepr {
  2235. control: TcpControl::Fin,
  2236. seq_number: REMOTE_SEQ + 1,
  2237. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2238. ..SEND_TEMPL
  2239. });
  2240. assert_eq!(s.state, State::TimeWait);
  2241. sanity!(s, socket_time_wait(false));
  2242. }
  2243. #[test]
  2244. fn test_fin_wait_2_close() {
  2245. let mut s = socket_fin_wait_2();
  2246. s.close();
  2247. assert_eq!(s.state, State::FinWait2);
  2248. }
  2249. // =========================================================================================//
  2250. // Tests for the CLOSING state.
  2251. // =========================================================================================//
  2252. #[test]
  2253. fn test_closing_ack_fin() {
  2254. let mut s = socket_closing();
  2255. recv!(s, [TcpRepr {
  2256. seq_number: LOCAL_SEQ + 1 + 1,
  2257. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2258. ..RECV_TEMPL
  2259. }]);
  2260. send!(s, time 1_000, TcpRepr {
  2261. seq_number: REMOTE_SEQ + 1 + 1,
  2262. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2263. ..SEND_TEMPL
  2264. });
  2265. assert_eq!(s.state, State::TimeWait);
  2266. sanity!(s, socket_time_wait(true));
  2267. }
  2268. #[test]
  2269. fn test_closing_close() {
  2270. let mut s = socket_closing();
  2271. s.close();
  2272. assert_eq!(s.state, State::Closing);
  2273. }
  2274. // =========================================================================================//
  2275. // Tests for the TIME-WAIT state.
  2276. // =========================================================================================//
  2277. #[test]
  2278. fn test_time_wait_from_fin_wait_2_ack() {
  2279. let mut s = socket_time_wait(false);
  2280. recv!(s, [TcpRepr {
  2281. seq_number: LOCAL_SEQ + 1 + 1,
  2282. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2283. ..RECV_TEMPL
  2284. }]);
  2285. }
  2286. #[test]
  2287. fn test_time_wait_from_closing_no_ack() {
  2288. let mut s = socket_time_wait(true);
  2289. recv!(s, []);
  2290. }
  2291. #[test]
  2292. fn test_time_wait_close() {
  2293. let mut s = socket_time_wait(false);
  2294. s.close();
  2295. assert_eq!(s.state, State::TimeWait);
  2296. }
  2297. #[test]
  2298. fn test_time_wait_retransmit() {
  2299. let mut s = socket_time_wait(false);
  2300. recv!(s, [TcpRepr {
  2301. seq_number: LOCAL_SEQ + 1 + 1,
  2302. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2303. ..RECV_TEMPL
  2304. }]);
  2305. send!(s, time 5_000, TcpRepr {
  2306. control: TcpControl::Fin,
  2307. seq_number: REMOTE_SEQ + 1,
  2308. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2309. ..SEND_TEMPL
  2310. }, Ok(Some(TcpRepr {
  2311. seq_number: LOCAL_SEQ + 1 + 1,
  2312. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2313. ..RECV_TEMPL
  2314. })));
  2315. assert_eq!(s.timer, Timer::Close { expires_at: Instant::from_secs(5) + CLOSE_DELAY });
  2316. }
  2317. #[test]
  2318. fn test_time_wait_timeout() {
  2319. let mut s = socket_time_wait(false);
  2320. recv!(s, [TcpRepr {
  2321. seq_number: LOCAL_SEQ + 1 + 1,
  2322. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2323. ..RECV_TEMPL
  2324. }]);
  2325. assert_eq!(s.state, State::TimeWait);
  2326. recv!(s, time 60_000, Err(Error::Exhausted));
  2327. assert_eq!(s.state, State::Closed);
  2328. }
  2329. // =========================================================================================//
  2330. // Tests for the CLOSE-WAIT state.
  2331. // =========================================================================================//
  2332. #[test]
  2333. fn test_close_wait_ack() {
  2334. let mut s = socket_close_wait();
  2335. s.send_slice(b"abcdef").unwrap();
  2336. recv!(s, [TcpRepr {
  2337. seq_number: LOCAL_SEQ + 1,
  2338. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2339. payload: &b"abcdef"[..],
  2340. ..RECV_TEMPL
  2341. }]);
  2342. send!(s, TcpRepr {
  2343. seq_number: REMOTE_SEQ + 1 + 1,
  2344. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2345. ..SEND_TEMPL
  2346. });
  2347. }
  2348. #[test]
  2349. fn test_close_wait_close() {
  2350. let mut s = socket_close_wait();
  2351. s.close();
  2352. assert_eq!(s.state, State::LastAck);
  2353. sanity!(s, socket_last_ack());
  2354. }
  2355. // =========================================================================================//
  2356. // Tests for the LAST-ACK state.
  2357. // =========================================================================================//
  2358. #[test]
  2359. fn test_last_ack_fin_ack() {
  2360. let mut s = socket_last_ack();
  2361. recv!(s, [TcpRepr {
  2362. control: TcpControl::Fin,
  2363. seq_number: LOCAL_SEQ + 1,
  2364. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2365. ..RECV_TEMPL
  2366. }]);
  2367. assert_eq!(s.state, State::LastAck);
  2368. send!(s, TcpRepr {
  2369. seq_number: REMOTE_SEQ + 1 + 1,
  2370. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2371. ..SEND_TEMPL
  2372. });
  2373. assert_eq!(s.state, State::Closed);
  2374. }
  2375. #[test]
  2376. fn test_last_ack_close() {
  2377. let mut s = socket_last_ack();
  2378. s.close();
  2379. assert_eq!(s.state, State::LastAck);
  2380. }
  2381. // =========================================================================================//
  2382. // Tests for transitioning through multiple states.
  2383. // =========================================================================================//
  2384. #[test]
  2385. fn test_listen() {
  2386. let mut s = socket();
  2387. s.listen(IpEndpoint::new(IpAddress::default(), LOCAL_PORT)).unwrap();
  2388. assert_eq!(s.state, State::Listen);
  2389. }
  2390. #[test]
  2391. fn test_three_way_handshake() {
  2392. let mut s = socket_listen();
  2393. send!(s, TcpRepr {
  2394. control: TcpControl::Syn,
  2395. seq_number: REMOTE_SEQ,
  2396. ack_number: None,
  2397. ..SEND_TEMPL
  2398. });
  2399. assert_eq!(s.state(), State::SynReceived);
  2400. assert_eq!(s.local_endpoint(), LOCAL_END);
  2401. assert_eq!(s.remote_endpoint(), REMOTE_END);
  2402. recv!(s, [TcpRepr {
  2403. control: TcpControl::Syn,
  2404. seq_number: LOCAL_SEQ,
  2405. ack_number: Some(REMOTE_SEQ + 1),
  2406. max_seg_size: Some(BASE_MSS),
  2407. ..RECV_TEMPL
  2408. }]);
  2409. send!(s, TcpRepr {
  2410. seq_number: REMOTE_SEQ + 1,
  2411. ack_number: Some(LOCAL_SEQ + 1),
  2412. ..SEND_TEMPL
  2413. });
  2414. assert_eq!(s.state(), State::Established);
  2415. assert_eq!(s.local_seq_no, LOCAL_SEQ + 1);
  2416. assert_eq!(s.remote_seq_no, REMOTE_SEQ + 1);
  2417. }
  2418. #[test]
  2419. fn test_remote_close() {
  2420. let mut s = socket_established();
  2421. send!(s, TcpRepr {
  2422. control: TcpControl::Fin,
  2423. seq_number: REMOTE_SEQ + 1,
  2424. ack_number: Some(LOCAL_SEQ + 1),
  2425. ..SEND_TEMPL
  2426. });
  2427. assert_eq!(s.state, State::CloseWait);
  2428. recv!(s, [TcpRepr {
  2429. seq_number: LOCAL_SEQ + 1,
  2430. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2431. ..RECV_TEMPL
  2432. }]);
  2433. s.close();
  2434. assert_eq!(s.state, State::LastAck);
  2435. recv!(s, [TcpRepr {
  2436. control: TcpControl::Fin,
  2437. seq_number: LOCAL_SEQ + 1,
  2438. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2439. ..RECV_TEMPL
  2440. }]);
  2441. send!(s, TcpRepr {
  2442. seq_number: REMOTE_SEQ + 1 + 1,
  2443. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2444. ..SEND_TEMPL
  2445. });
  2446. assert_eq!(s.state, State::Closed);
  2447. }
  2448. #[test]
  2449. fn test_local_close() {
  2450. let mut s = socket_established();
  2451. s.close();
  2452. assert_eq!(s.state, State::FinWait1);
  2453. recv!(s, [TcpRepr {
  2454. control: TcpControl::Fin,
  2455. seq_number: LOCAL_SEQ + 1,
  2456. ack_number: Some(REMOTE_SEQ + 1),
  2457. ..RECV_TEMPL
  2458. }]);
  2459. send!(s, TcpRepr {
  2460. seq_number: REMOTE_SEQ + 1,
  2461. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2462. ..SEND_TEMPL
  2463. });
  2464. assert_eq!(s.state, State::FinWait2);
  2465. send!(s, TcpRepr {
  2466. control: TcpControl::Fin,
  2467. seq_number: REMOTE_SEQ + 1,
  2468. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2469. ..SEND_TEMPL
  2470. });
  2471. assert_eq!(s.state, State::TimeWait);
  2472. recv!(s, [TcpRepr {
  2473. seq_number: LOCAL_SEQ + 1 + 1,
  2474. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2475. ..RECV_TEMPL
  2476. }]);
  2477. }
  2478. #[test]
  2479. fn test_simultaneous_close() {
  2480. let mut s = socket_established();
  2481. s.close();
  2482. assert_eq!(s.state, State::FinWait1);
  2483. recv!(s, [TcpRepr { // due to reordering, this is logically located...
  2484. control: TcpControl::Fin,
  2485. seq_number: LOCAL_SEQ + 1,
  2486. ack_number: Some(REMOTE_SEQ + 1),
  2487. ..RECV_TEMPL
  2488. }]);
  2489. send!(s, TcpRepr {
  2490. control: TcpControl::Fin,
  2491. seq_number: REMOTE_SEQ + 1,
  2492. ack_number: Some(LOCAL_SEQ + 1),
  2493. ..SEND_TEMPL
  2494. });
  2495. assert_eq!(s.state, State::Closing);
  2496. recv!(s, [TcpRepr {
  2497. seq_number: LOCAL_SEQ + 1 + 1,
  2498. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2499. ..RECV_TEMPL
  2500. }]);
  2501. // ... at this point
  2502. send!(s, TcpRepr {
  2503. seq_number: REMOTE_SEQ + 1 + 1,
  2504. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2505. ..SEND_TEMPL
  2506. });
  2507. assert_eq!(s.state, State::TimeWait);
  2508. recv!(s, []);
  2509. }
  2510. #[test]
  2511. fn test_simultaneous_close_combined_fin_ack() {
  2512. let mut s = socket_established();
  2513. s.close();
  2514. assert_eq!(s.state, State::FinWait1);
  2515. recv!(s, [TcpRepr {
  2516. control: TcpControl::Fin,
  2517. seq_number: LOCAL_SEQ + 1,
  2518. ack_number: Some(REMOTE_SEQ + 1),
  2519. ..RECV_TEMPL
  2520. }]);
  2521. send!(s, TcpRepr {
  2522. control: TcpControl::Fin,
  2523. seq_number: REMOTE_SEQ + 1,
  2524. ack_number: Some(LOCAL_SEQ + 1 + 1),
  2525. ..SEND_TEMPL
  2526. });
  2527. assert_eq!(s.state, State::TimeWait);
  2528. recv!(s, [TcpRepr {
  2529. seq_number: LOCAL_SEQ + 1 + 1,
  2530. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2531. ..RECV_TEMPL
  2532. }]);
  2533. }
  2534. #[test]
  2535. fn test_fin_with_data() {
  2536. let mut s = socket_established();
  2537. s.send_slice(b"abcdef").unwrap();
  2538. s.close();
  2539. recv!(s, [TcpRepr {
  2540. control: TcpControl::Fin,
  2541. seq_number: LOCAL_SEQ + 1,
  2542. ack_number: Some(REMOTE_SEQ + 1),
  2543. payload: &b"abcdef"[..],
  2544. ..RECV_TEMPL
  2545. }])
  2546. }
  2547. #[test]
  2548. fn test_mutual_close_with_data_1() {
  2549. let mut s = socket_established();
  2550. s.send_slice(b"abcdef").unwrap();
  2551. s.close();
  2552. assert_eq!(s.state, State::FinWait1);
  2553. recv!(s, [TcpRepr {
  2554. control: TcpControl::Fin,
  2555. seq_number: LOCAL_SEQ + 1,
  2556. ack_number: Some(REMOTE_SEQ + 1),
  2557. payload: &b"abcdef"[..],
  2558. ..RECV_TEMPL
  2559. }]);
  2560. send!(s, TcpRepr {
  2561. control: TcpControl::Fin,
  2562. seq_number: REMOTE_SEQ + 1,
  2563. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2564. ..SEND_TEMPL
  2565. });
  2566. }
  2567. #[test]
  2568. fn test_mutual_close_with_data_2() {
  2569. let mut s = socket_established();
  2570. s.send_slice(b"abcdef").unwrap();
  2571. s.close();
  2572. assert_eq!(s.state, State::FinWait1);
  2573. recv!(s, [TcpRepr {
  2574. control: TcpControl::Fin,
  2575. seq_number: LOCAL_SEQ + 1,
  2576. ack_number: Some(REMOTE_SEQ + 1),
  2577. payload: &b"abcdef"[..],
  2578. ..RECV_TEMPL
  2579. }]);
  2580. send!(s, TcpRepr {
  2581. seq_number: REMOTE_SEQ + 1,
  2582. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2583. ..SEND_TEMPL
  2584. });
  2585. assert_eq!(s.state, State::FinWait2);
  2586. send!(s, TcpRepr {
  2587. control: TcpControl::Fin,
  2588. seq_number: REMOTE_SEQ + 1,
  2589. ack_number: Some(LOCAL_SEQ + 1 + 6 + 1),
  2590. ..SEND_TEMPL
  2591. });
  2592. recv!(s, [TcpRepr {
  2593. seq_number: LOCAL_SEQ + 1 + 6 + 1,
  2594. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2595. ..RECV_TEMPL
  2596. }]);
  2597. assert_eq!(s.state, State::TimeWait);
  2598. }
  2599. // =========================================================================================//
  2600. // Tests for retransmission on packet loss.
  2601. // =========================================================================================//
  2602. #[test]
  2603. fn test_duplicate_seq_ack() {
  2604. let mut s = socket_recved();
  2605. // remote retransmission
  2606. send!(s, TcpRepr {
  2607. seq_number: REMOTE_SEQ + 1,
  2608. ack_number: Some(LOCAL_SEQ + 1),
  2609. payload: &b"abcdef"[..],
  2610. ..SEND_TEMPL
  2611. }, Ok(Some(TcpRepr {
  2612. seq_number: LOCAL_SEQ + 1,
  2613. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2614. window_len: 58,
  2615. ..RECV_TEMPL
  2616. })));
  2617. }
  2618. #[test]
  2619. fn test_data_retransmit() {
  2620. let mut s = socket_established();
  2621. s.send_slice(b"abcdef").unwrap();
  2622. recv!(s, time 1000, Ok(TcpRepr {
  2623. seq_number: LOCAL_SEQ + 1,
  2624. ack_number: Some(REMOTE_SEQ + 1),
  2625. payload: &b"abcdef"[..],
  2626. ..RECV_TEMPL
  2627. }));
  2628. recv!(s, time 1050, Err(Error::Exhausted));
  2629. recv!(s, time 1100, Ok(TcpRepr {
  2630. seq_number: LOCAL_SEQ + 1,
  2631. ack_number: Some(REMOTE_SEQ + 1),
  2632. payload: &b"abcdef"[..],
  2633. ..RECV_TEMPL
  2634. }));
  2635. }
  2636. #[test]
  2637. fn test_data_retransmit_bursts() {
  2638. let mut s = socket_established();
  2639. s.remote_win_len = 6;
  2640. s.send_slice(b"abcdef012345").unwrap();
  2641. recv!(s, time 0, Ok(TcpRepr {
  2642. control: TcpControl::None,
  2643. seq_number: LOCAL_SEQ + 1,
  2644. ack_number: Some(REMOTE_SEQ + 1),
  2645. payload: &b"abcdef"[..],
  2646. ..RECV_TEMPL
  2647. }), exact);
  2648. s.remote_win_len = 6;
  2649. recv!(s, time 0, Ok(TcpRepr {
  2650. control: TcpControl::Psh,
  2651. seq_number: LOCAL_SEQ + 1 + 6,
  2652. ack_number: Some(REMOTE_SEQ + 1),
  2653. payload: &b"012345"[..],
  2654. ..RECV_TEMPL
  2655. }), exact);
  2656. s.remote_win_len = 6;
  2657. recv!(s, time 0, Err(Error::Exhausted));
  2658. recv!(s, time 50, Err(Error::Exhausted));
  2659. recv!(s, time 100, Ok(TcpRepr {
  2660. control: TcpControl::None,
  2661. seq_number: LOCAL_SEQ + 1,
  2662. ack_number: Some(REMOTE_SEQ + 1),
  2663. payload: &b"abcdef"[..],
  2664. ..RECV_TEMPL
  2665. }), exact);
  2666. s.remote_win_len = 6;
  2667. recv!(s, time 150, Ok(TcpRepr {
  2668. control: TcpControl::Psh,
  2669. seq_number: LOCAL_SEQ + 1 + 6,
  2670. ack_number: Some(REMOTE_SEQ + 1),
  2671. payload: &b"012345"[..],
  2672. ..RECV_TEMPL
  2673. }), exact);
  2674. s.remote_win_len = 6;
  2675. recv!(s, time 200, Err(Error::Exhausted));
  2676. }
  2677. #[test]
  2678. fn test_send_data_after_syn_ack_retransmit() {
  2679. let mut s = socket_syn_received();
  2680. recv!(s, time 50, Ok(TcpRepr {
  2681. control: TcpControl::Syn,
  2682. seq_number: LOCAL_SEQ,
  2683. ack_number: Some(REMOTE_SEQ + 1),
  2684. max_seg_size: Some(BASE_MSS),
  2685. ..RECV_TEMPL
  2686. }));
  2687. recv!(s, time 150, Ok(TcpRepr { // retransmit
  2688. control: TcpControl::Syn,
  2689. seq_number: LOCAL_SEQ,
  2690. ack_number: Some(REMOTE_SEQ + 1),
  2691. max_seg_size: Some(BASE_MSS),
  2692. ..RECV_TEMPL
  2693. }));
  2694. send!(s, TcpRepr {
  2695. seq_number: REMOTE_SEQ + 1,
  2696. ack_number: Some(LOCAL_SEQ + 1),
  2697. ..SEND_TEMPL
  2698. });
  2699. assert_eq!(s.state(), State::Established);
  2700. s.send_slice(b"abcdef").unwrap();
  2701. recv!(s, [TcpRepr {
  2702. seq_number: LOCAL_SEQ + 1,
  2703. ack_number: Some(REMOTE_SEQ + 1),
  2704. payload: &b"abcdef"[..],
  2705. ..RECV_TEMPL
  2706. }])
  2707. }
  2708. #[test]
  2709. fn test_established_retransmit_for_dup_ack() {
  2710. let mut s = socket_established();
  2711. // Duplicate ACKs do not replace the retransmission timer
  2712. s.send_slice(b"abc").unwrap();
  2713. recv!(s, time 1000, Ok(TcpRepr {
  2714. seq_number: LOCAL_SEQ + 1,
  2715. ack_number: Some(REMOTE_SEQ + 1),
  2716. payload: &b"abc"[..],
  2717. ..RECV_TEMPL
  2718. }));
  2719. // Retransmit timer is on because all data was sent
  2720. assert_eq!(s.tx_buffer.len(), 3);
  2721. // ACK nothing new
  2722. send!(s, TcpRepr {
  2723. seq_number: REMOTE_SEQ + 1,
  2724. ack_number: Some(LOCAL_SEQ + 1),
  2725. ..SEND_TEMPL
  2726. });
  2727. // Retransmit
  2728. recv!(s, time 4000, Ok(TcpRepr {
  2729. seq_number: LOCAL_SEQ + 1,
  2730. ack_number: Some(REMOTE_SEQ + 1),
  2731. payload: &b"abc"[..],
  2732. ..RECV_TEMPL
  2733. }));
  2734. }
  2735. #[test]
  2736. fn test_established_retransmit_reset_after_ack() {
  2737. let mut s = socket_established();
  2738. s.remote_win_len = 6;
  2739. s.send_slice(b"abcdef").unwrap();
  2740. s.send_slice(b"123456").unwrap();
  2741. s.send_slice(b"ABCDEF").unwrap();
  2742. recv!(s, time 1000, Ok(TcpRepr {
  2743. seq_number: LOCAL_SEQ + 1,
  2744. ack_number: Some(REMOTE_SEQ + 1),
  2745. payload: &b"abcdef"[..],
  2746. ..RECV_TEMPL
  2747. }));
  2748. send!(s, time 1005, TcpRepr {
  2749. seq_number: REMOTE_SEQ + 1,
  2750. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2751. window_len: 6,
  2752. ..SEND_TEMPL
  2753. });
  2754. recv!(s, time 1010, Ok(TcpRepr {
  2755. seq_number: LOCAL_SEQ + 1 + 6,
  2756. ack_number: Some(REMOTE_SEQ + 1),
  2757. payload: &b"123456"[..],
  2758. ..RECV_TEMPL
  2759. }));
  2760. send!(s, time 1015, TcpRepr {
  2761. seq_number: REMOTE_SEQ + 1,
  2762. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2763. window_len: 6,
  2764. ..SEND_TEMPL
  2765. });
  2766. recv!(s, time 1020, Ok(TcpRepr {
  2767. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2768. ack_number: Some(REMOTE_SEQ + 1),
  2769. payload: &b"ABCDEF"[..],
  2770. ..RECV_TEMPL
  2771. }));
  2772. }
  2773. #[test]
  2774. fn test_established_queue_during_retransmission() {
  2775. let mut s = socket_established();
  2776. s.remote_mss = 6;
  2777. s.send_slice(b"abcdef123456ABCDEF").unwrap();
  2778. recv!(s, time 1000, Ok(TcpRepr {
  2779. seq_number: LOCAL_SEQ + 1,
  2780. ack_number: Some(REMOTE_SEQ + 1),
  2781. payload: &b"abcdef"[..],
  2782. ..RECV_TEMPL
  2783. })); // this one is dropped
  2784. recv!(s, time 1005, Ok(TcpRepr {
  2785. seq_number: LOCAL_SEQ + 1 + 6,
  2786. ack_number: Some(REMOTE_SEQ + 1),
  2787. payload: &b"123456"[..],
  2788. ..RECV_TEMPL
  2789. })); // this one is received
  2790. recv!(s, time 1010, Ok(TcpRepr {
  2791. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2792. ack_number: Some(REMOTE_SEQ + 1),
  2793. payload: &b"ABCDEF"[..],
  2794. ..RECV_TEMPL
  2795. })); // also dropped
  2796. recv!(s, time 2000, Ok(TcpRepr {
  2797. seq_number: LOCAL_SEQ + 1,
  2798. ack_number: Some(REMOTE_SEQ + 1),
  2799. payload: &b"abcdef"[..],
  2800. ..RECV_TEMPL
  2801. })); // retransmission
  2802. send!(s, time 2005, TcpRepr {
  2803. seq_number: REMOTE_SEQ + 1,
  2804. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2805. ..SEND_TEMPL
  2806. }); // acknowledgement of both segments
  2807. recv!(s, time 2010, Ok(TcpRepr {
  2808. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2809. ack_number: Some(REMOTE_SEQ + 1),
  2810. payload: &b"ABCDEF"[..],
  2811. ..RECV_TEMPL
  2812. })); // retransmission of only unacknowledged data
  2813. }
  2814. #[test]
  2815. fn test_close_wait_retransmit_reset_after_ack() {
  2816. let mut s = socket_close_wait();
  2817. s.remote_win_len = 6;
  2818. s.send_slice(b"abcdef").unwrap();
  2819. s.send_slice(b"123456").unwrap();
  2820. s.send_slice(b"ABCDEF").unwrap();
  2821. recv!(s, time 1000, Ok(TcpRepr {
  2822. seq_number: LOCAL_SEQ + 1,
  2823. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2824. payload: &b"abcdef"[..],
  2825. ..RECV_TEMPL
  2826. }));
  2827. send!(s, time 1005, TcpRepr {
  2828. seq_number: REMOTE_SEQ + 1 + 1,
  2829. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2830. window_len: 6,
  2831. ..SEND_TEMPL
  2832. });
  2833. recv!(s, time 1010, Ok(TcpRepr {
  2834. seq_number: LOCAL_SEQ + 1 + 6,
  2835. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2836. payload: &b"123456"[..],
  2837. ..RECV_TEMPL
  2838. }));
  2839. send!(s, time 1015, TcpRepr {
  2840. seq_number: REMOTE_SEQ + 1 + 1,
  2841. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2842. window_len: 6,
  2843. ..SEND_TEMPL
  2844. });
  2845. recv!(s, time 1020, Ok(TcpRepr {
  2846. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2847. ack_number: Some(REMOTE_SEQ + 1 + 1),
  2848. payload: &b"ABCDEF"[..],
  2849. ..RECV_TEMPL
  2850. }));
  2851. }
  2852. #[test]
  2853. fn test_fin_wait_1_retransmit_reset_after_ack() {
  2854. let mut s = socket_established();
  2855. s.remote_win_len = 6;
  2856. s.send_slice(b"abcdef").unwrap();
  2857. s.send_slice(b"123456").unwrap();
  2858. s.send_slice(b"ABCDEF").unwrap();
  2859. s.close();
  2860. recv!(s, time 1000, Ok(TcpRepr {
  2861. seq_number: LOCAL_SEQ + 1,
  2862. ack_number: Some(REMOTE_SEQ + 1),
  2863. payload: &b"abcdef"[..],
  2864. ..RECV_TEMPL
  2865. }));
  2866. send!(s, time 1005, TcpRepr {
  2867. seq_number: REMOTE_SEQ + 1,
  2868. ack_number: Some(LOCAL_SEQ + 1 + 6),
  2869. window_len: 6,
  2870. ..SEND_TEMPL
  2871. });
  2872. recv!(s, time 1010, Ok(TcpRepr {
  2873. seq_number: LOCAL_SEQ + 1 + 6,
  2874. ack_number: Some(REMOTE_SEQ + 1),
  2875. payload: &b"123456"[..],
  2876. ..RECV_TEMPL
  2877. }));
  2878. send!(s, time 1015, TcpRepr {
  2879. seq_number: REMOTE_SEQ + 1,
  2880. ack_number: Some(LOCAL_SEQ + 1 + 6 + 6),
  2881. window_len: 6,
  2882. ..SEND_TEMPL
  2883. });
  2884. recv!(s, time 1020, Ok(TcpRepr {
  2885. control: TcpControl::Fin,
  2886. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  2887. ack_number: Some(REMOTE_SEQ + 1),
  2888. payload: &b"ABCDEF"[..],
  2889. ..RECV_TEMPL
  2890. }));
  2891. }
  2892. // =========================================================================================//
  2893. // Tests for window management.
  2894. // =========================================================================================//
  2895. #[test]
  2896. fn test_maximum_segment_size() {
  2897. let mut s = socket_listen();
  2898. s.tx_buffer = SocketBuffer::new(vec![0; 32767]);
  2899. send!(s, TcpRepr {
  2900. control: TcpControl::Syn,
  2901. seq_number: REMOTE_SEQ,
  2902. ack_number: None,
  2903. max_seg_size: Some(1000),
  2904. ..SEND_TEMPL
  2905. });
  2906. recv!(s, [TcpRepr {
  2907. control: TcpControl::Syn,
  2908. seq_number: LOCAL_SEQ,
  2909. ack_number: Some(REMOTE_SEQ + 1),
  2910. max_seg_size: Some(BASE_MSS),
  2911. ..RECV_TEMPL
  2912. }]);
  2913. send!(s, TcpRepr {
  2914. seq_number: REMOTE_SEQ + 1,
  2915. ack_number: Some(LOCAL_SEQ + 1),
  2916. window_len: 32767,
  2917. ..SEND_TEMPL
  2918. });
  2919. s.send_slice(&[0; 1200][..]).unwrap();
  2920. recv!(s, Ok(TcpRepr {
  2921. seq_number: LOCAL_SEQ + 1,
  2922. ack_number: Some(REMOTE_SEQ + 1),
  2923. payload: &[0; 1000][..],
  2924. ..RECV_TEMPL
  2925. }));
  2926. }
  2927. // =========================================================================================//
  2928. // Tests for flow control.
  2929. // =========================================================================================//
  2930. #[test]
  2931. fn test_psh_transmit() {
  2932. let mut s = socket_established();
  2933. s.remote_win_len = 6;
  2934. s.send_slice(b"abcdef").unwrap();
  2935. s.send_slice(b"123456").unwrap();
  2936. recv!(s, time 0, Ok(TcpRepr {
  2937. control: TcpControl::None,
  2938. seq_number: LOCAL_SEQ + 1,
  2939. ack_number: Some(REMOTE_SEQ + 1),
  2940. payload: &b"abcdef"[..],
  2941. ..RECV_TEMPL
  2942. }), exact);
  2943. recv!(s, time 0, Ok(TcpRepr {
  2944. control: TcpControl::Psh,
  2945. seq_number: LOCAL_SEQ + 1 + 6,
  2946. ack_number: Some(REMOTE_SEQ + 1),
  2947. payload: &b"123456"[..],
  2948. ..RECV_TEMPL
  2949. }), exact);
  2950. }
  2951. #[test]
  2952. fn test_psh_receive() {
  2953. let mut s = socket_established();
  2954. send!(s, TcpRepr {
  2955. control: TcpControl::Psh,
  2956. seq_number: REMOTE_SEQ + 1,
  2957. ack_number: Some(LOCAL_SEQ + 1),
  2958. payload: &b"abcdef"[..],
  2959. ..SEND_TEMPL
  2960. });
  2961. recv!(s, [TcpRepr {
  2962. seq_number: LOCAL_SEQ + 1,
  2963. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2964. window_len: 58,
  2965. ..RECV_TEMPL
  2966. }]);
  2967. }
  2968. #[test]
  2969. fn test_zero_window_ack() {
  2970. let mut s = socket_established();
  2971. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  2972. s.assembler = Assembler::new(s.rx_buffer.capacity());
  2973. send!(s, TcpRepr {
  2974. seq_number: REMOTE_SEQ + 1,
  2975. ack_number: Some(LOCAL_SEQ + 1),
  2976. payload: &b"abcdef"[..],
  2977. ..SEND_TEMPL
  2978. });
  2979. recv!(s, [TcpRepr {
  2980. seq_number: LOCAL_SEQ + 1,
  2981. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2982. window_len: 0,
  2983. ..RECV_TEMPL
  2984. }]);
  2985. send!(s, TcpRepr {
  2986. seq_number: REMOTE_SEQ + 1 + 6,
  2987. ack_number: Some(LOCAL_SEQ + 1),
  2988. payload: &b"123456"[..],
  2989. ..SEND_TEMPL
  2990. }, Ok(Some(TcpRepr {
  2991. seq_number: LOCAL_SEQ + 1,
  2992. ack_number: Some(REMOTE_SEQ + 1 + 6),
  2993. window_len: 0,
  2994. ..RECV_TEMPL
  2995. })));
  2996. }
  2997. #[test]
  2998. fn test_zero_window_ack_on_window_growth() {
  2999. let mut s = socket_established();
  3000. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3001. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3002. send!(s, TcpRepr {
  3003. seq_number: REMOTE_SEQ + 1,
  3004. ack_number: Some(LOCAL_SEQ + 1),
  3005. payload: &b"abcdef"[..],
  3006. ..SEND_TEMPL
  3007. });
  3008. recv!(s, [TcpRepr {
  3009. seq_number: LOCAL_SEQ + 1,
  3010. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3011. window_len: 0,
  3012. ..RECV_TEMPL
  3013. }]);
  3014. recv!(s, time 0, Err(Error::Exhausted));
  3015. s.recv(|buffer| {
  3016. assert_eq!(&buffer[..3], b"abc");
  3017. (3, ())
  3018. }).unwrap();
  3019. recv!(s, time 0, Ok(TcpRepr {
  3020. seq_number: LOCAL_SEQ + 1,
  3021. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3022. window_len: 3,
  3023. ..RECV_TEMPL
  3024. }));
  3025. recv!(s, time 0, Err(Error::Exhausted));
  3026. s.recv(|buffer| {
  3027. assert_eq!(buffer, b"def");
  3028. (buffer.len(), ())
  3029. }).unwrap();
  3030. recv!(s, time 0, Ok(TcpRepr {
  3031. seq_number: LOCAL_SEQ + 1,
  3032. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3033. window_len: 6,
  3034. ..RECV_TEMPL
  3035. }));
  3036. }
  3037. #[test]
  3038. fn test_fill_peer_window() {
  3039. let mut s = socket_established();
  3040. s.remote_mss = 6;
  3041. s.send_slice(b"abcdef123456!@#$%^").unwrap();
  3042. recv!(s, [TcpRepr {
  3043. seq_number: LOCAL_SEQ + 1,
  3044. ack_number: Some(REMOTE_SEQ + 1),
  3045. payload: &b"abcdef"[..],
  3046. ..RECV_TEMPL
  3047. }, TcpRepr {
  3048. seq_number: LOCAL_SEQ + 1 + 6,
  3049. ack_number: Some(REMOTE_SEQ + 1),
  3050. payload: &b"123456"[..],
  3051. ..RECV_TEMPL
  3052. }, TcpRepr {
  3053. seq_number: LOCAL_SEQ + 1 + 6 + 6,
  3054. ack_number: Some(REMOTE_SEQ + 1),
  3055. payload: &b"!@#$%^"[..],
  3056. ..RECV_TEMPL
  3057. }]);
  3058. }
  3059. #[test]
  3060. fn test_announce_window_after_read() {
  3061. let mut s = socket_established();
  3062. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3063. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3064. send!(s, TcpRepr {
  3065. seq_number: REMOTE_SEQ + 1,
  3066. ack_number: Some(LOCAL_SEQ + 1),
  3067. payload: &b"abc"[..],
  3068. ..SEND_TEMPL
  3069. });
  3070. recv!(s, [TcpRepr {
  3071. seq_number: LOCAL_SEQ + 1,
  3072. ack_number: Some(REMOTE_SEQ + 1 + 3),
  3073. window_len: 3,
  3074. ..RECV_TEMPL
  3075. }]);
  3076. // Test that `dispatch` updates `remote_last_win`
  3077. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  3078. s.recv(|buffer| {
  3079. (buffer.len(), ())
  3080. }).unwrap();
  3081. assert!(s.window_to_update());
  3082. recv!(s, [TcpRepr {
  3083. seq_number: LOCAL_SEQ + 1,
  3084. ack_number: Some(REMOTE_SEQ + 1 + 3),
  3085. window_len: 6,
  3086. ..RECV_TEMPL
  3087. }]);
  3088. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  3089. // Provoke immediate ACK to test that `process` updates `remote_last_win`
  3090. send!(s, TcpRepr {
  3091. seq_number: REMOTE_SEQ + 1 + 6,
  3092. ack_number: Some(LOCAL_SEQ + 1),
  3093. payload: &b"def"[..],
  3094. ..SEND_TEMPL
  3095. }, Ok(Some(TcpRepr {
  3096. seq_number: LOCAL_SEQ + 1,
  3097. ack_number: Some(REMOTE_SEQ + 1 + 3),
  3098. window_len: 6,
  3099. ..RECV_TEMPL
  3100. })));
  3101. send!(s, TcpRepr {
  3102. seq_number: REMOTE_SEQ + 1 + 3,
  3103. ack_number: Some(LOCAL_SEQ + 1),
  3104. payload: &b"abc"[..],
  3105. ..SEND_TEMPL
  3106. }, Ok(Some(TcpRepr {
  3107. seq_number: LOCAL_SEQ + 1,
  3108. ack_number: Some(REMOTE_SEQ + 1 + 9),
  3109. window_len: 0,
  3110. ..RECV_TEMPL
  3111. })));
  3112. assert_eq!(s.remote_last_win, s.rx_buffer.window() as u16);
  3113. s.recv(|buffer| {
  3114. (buffer.len(), ())
  3115. }).unwrap();
  3116. assert!(s.window_to_update());
  3117. }
  3118. // =========================================================================================//
  3119. // Tests for timeouts.
  3120. // =========================================================================================//
  3121. #[test]
  3122. fn test_listen_timeout() {
  3123. let mut s = socket_listen();
  3124. s.set_timeout(Some(Duration::from_millis(100)));
  3125. assert_eq!(s.poll_at(), PollAt::Ingress);
  3126. }
  3127. #[test]
  3128. fn test_connect_timeout() {
  3129. let mut s = socket();
  3130. s.local_seq_no = LOCAL_SEQ;
  3131. s.connect(REMOTE_END, LOCAL_END.port).unwrap();
  3132. s.set_timeout(Some(Duration::from_millis(100)));
  3133. recv!(s, time 150, Ok(TcpRepr {
  3134. control: TcpControl::Syn,
  3135. seq_number: LOCAL_SEQ,
  3136. ack_number: None,
  3137. max_seg_size: Some(BASE_MSS),
  3138. ..RECV_TEMPL
  3139. }));
  3140. assert_eq!(s.state, State::SynSent);
  3141. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(250)));
  3142. recv!(s, time 250, Ok(TcpRepr {
  3143. control: TcpControl::Rst,
  3144. seq_number: LOCAL_SEQ + 1,
  3145. ack_number: Some(TcpSeqNumber(0)),
  3146. ..RECV_TEMPL
  3147. }));
  3148. assert_eq!(s.state, State::Closed);
  3149. }
  3150. #[test]
  3151. fn test_established_timeout() {
  3152. let mut s = socket_established();
  3153. s.set_timeout(Some(Duration::from_millis(200)));
  3154. recv!(s, time 250, Err(Error::Exhausted));
  3155. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(450)));
  3156. s.send_slice(b"abcdef").unwrap();
  3157. assert_eq!(s.poll_at(), PollAt::Now);
  3158. recv!(s, time 255, Ok(TcpRepr {
  3159. seq_number: LOCAL_SEQ + 1,
  3160. ack_number: Some(REMOTE_SEQ + 1),
  3161. payload: &b"abcdef"[..],
  3162. ..RECV_TEMPL
  3163. }));
  3164. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(355)));
  3165. recv!(s, time 355, Ok(TcpRepr {
  3166. seq_number: LOCAL_SEQ + 1,
  3167. ack_number: Some(REMOTE_SEQ + 1),
  3168. payload: &b"abcdef"[..],
  3169. ..RECV_TEMPL
  3170. }));
  3171. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(455)));
  3172. recv!(s, time 500, Ok(TcpRepr {
  3173. control: TcpControl::Rst,
  3174. seq_number: LOCAL_SEQ + 1 + 6,
  3175. ack_number: Some(REMOTE_SEQ + 1),
  3176. ..RECV_TEMPL
  3177. }));
  3178. assert_eq!(s.state, State::Closed);
  3179. }
  3180. #[test]
  3181. fn test_established_keep_alive_timeout() {
  3182. let mut s = socket_established();
  3183. s.set_keep_alive(Some(Duration::from_millis(50)));
  3184. s.set_timeout(Some(Duration::from_millis(100)));
  3185. recv!(s, time 100, Ok(TcpRepr {
  3186. seq_number: LOCAL_SEQ,
  3187. ack_number: Some(REMOTE_SEQ + 1),
  3188. payload: &[0],
  3189. ..RECV_TEMPL
  3190. }));
  3191. recv!(s, time 100, Err(Error::Exhausted));
  3192. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(150)));
  3193. send!(s, time 105, TcpRepr {
  3194. seq_number: REMOTE_SEQ + 1,
  3195. ack_number: Some(LOCAL_SEQ + 1),
  3196. ..SEND_TEMPL
  3197. });
  3198. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(155)));
  3199. recv!(s, time 155, Ok(TcpRepr {
  3200. seq_number: LOCAL_SEQ,
  3201. ack_number: Some(REMOTE_SEQ + 1),
  3202. payload: &[0],
  3203. ..RECV_TEMPL
  3204. }));
  3205. recv!(s, time 155, Err(Error::Exhausted));
  3206. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(205)));
  3207. recv!(s, time 200, Err(Error::Exhausted));
  3208. recv!(s, time 205, Ok(TcpRepr {
  3209. control: TcpControl::Rst,
  3210. seq_number: LOCAL_SEQ + 1,
  3211. ack_number: Some(REMOTE_SEQ + 1),
  3212. ..RECV_TEMPL
  3213. }));
  3214. recv!(s, time 205, Err(Error::Exhausted));
  3215. assert_eq!(s.state, State::Closed);
  3216. }
  3217. #[test]
  3218. fn test_fin_wait_1_timeout() {
  3219. let mut s = socket_fin_wait_1();
  3220. s.set_timeout(Some(Duration::from_millis(200)));
  3221. recv!(s, time 100, Ok(TcpRepr {
  3222. control: TcpControl::Fin,
  3223. seq_number: LOCAL_SEQ + 1,
  3224. ack_number: Some(REMOTE_SEQ + 1),
  3225. ..RECV_TEMPL
  3226. }));
  3227. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  3228. recv!(s, time 400, Ok(TcpRepr {
  3229. control: TcpControl::Rst,
  3230. seq_number: LOCAL_SEQ + 1 + 1,
  3231. ack_number: Some(REMOTE_SEQ + 1),
  3232. ..RECV_TEMPL
  3233. }));
  3234. assert_eq!(s.state, State::Closed);
  3235. }
  3236. #[test]
  3237. fn test_last_ack_timeout() {
  3238. let mut s = socket_last_ack();
  3239. s.set_timeout(Some(Duration::from_millis(200)));
  3240. recv!(s, time 100, Ok(TcpRepr {
  3241. control: TcpControl::Fin,
  3242. seq_number: LOCAL_SEQ + 1,
  3243. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3244. ..RECV_TEMPL
  3245. }));
  3246. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  3247. recv!(s, time 400, Ok(TcpRepr {
  3248. control: TcpControl::Rst,
  3249. seq_number: LOCAL_SEQ + 1 + 1,
  3250. ack_number: Some(REMOTE_SEQ + 1 + 1),
  3251. ..RECV_TEMPL
  3252. }));
  3253. assert_eq!(s.state, State::Closed);
  3254. }
  3255. #[test]
  3256. fn test_closed_timeout() {
  3257. let mut s = socket_established();
  3258. s.set_timeout(Some(Duration::from_millis(200)));
  3259. s.remote_last_ts = Some(Instant::from_millis(100));
  3260. s.abort();
  3261. assert_eq!(s.poll_at(), PollAt::Now);
  3262. recv!(s, time 100, Ok(TcpRepr {
  3263. control: TcpControl::Rst,
  3264. seq_number: LOCAL_SEQ + 1,
  3265. ack_number: Some(REMOTE_SEQ + 1),
  3266. ..RECV_TEMPL
  3267. }));
  3268. assert_eq!(s.poll_at(), PollAt::Ingress);
  3269. }
  3270. // =========================================================================================//
  3271. // Tests for keep-alive.
  3272. // =========================================================================================//
  3273. #[test]
  3274. fn test_responds_to_keep_alive() {
  3275. let mut s = socket_established();
  3276. send!(s, TcpRepr {
  3277. seq_number: REMOTE_SEQ,
  3278. ack_number: Some(LOCAL_SEQ + 1),
  3279. ..SEND_TEMPL
  3280. }, Ok(Some(TcpRepr {
  3281. seq_number: LOCAL_SEQ + 1,
  3282. ack_number: Some(REMOTE_SEQ + 1),
  3283. ..RECV_TEMPL
  3284. })));
  3285. }
  3286. #[test]
  3287. fn test_sends_keep_alive() {
  3288. let mut s = socket_established();
  3289. s.set_keep_alive(Some(Duration::from_millis(100)));
  3290. // drain the forced keep-alive packet
  3291. assert_eq!(s.poll_at(), PollAt::Now);
  3292. recv!(s, time 0, Ok(TcpRepr {
  3293. seq_number: LOCAL_SEQ,
  3294. ack_number: Some(REMOTE_SEQ + 1),
  3295. payload: &[0],
  3296. ..RECV_TEMPL
  3297. }));
  3298. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(100)));
  3299. recv!(s, time 95, Err(Error::Exhausted));
  3300. recv!(s, time 100, Ok(TcpRepr {
  3301. seq_number: LOCAL_SEQ,
  3302. ack_number: Some(REMOTE_SEQ + 1),
  3303. payload: &[0],
  3304. ..RECV_TEMPL
  3305. }));
  3306. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(200)));
  3307. recv!(s, time 195, Err(Error::Exhausted));
  3308. recv!(s, time 200, Ok(TcpRepr {
  3309. seq_number: LOCAL_SEQ,
  3310. ack_number: Some(REMOTE_SEQ + 1),
  3311. payload: &[0],
  3312. ..RECV_TEMPL
  3313. }));
  3314. send!(s, time 250, TcpRepr {
  3315. seq_number: REMOTE_SEQ + 1,
  3316. ack_number: Some(LOCAL_SEQ + 1),
  3317. ..SEND_TEMPL
  3318. });
  3319. assert_eq!(s.poll_at(), PollAt::Time(Instant::from_millis(350)));
  3320. recv!(s, time 345, Err(Error::Exhausted));
  3321. recv!(s, time 350, Ok(TcpRepr {
  3322. seq_number: LOCAL_SEQ,
  3323. ack_number: Some(REMOTE_SEQ + 1),
  3324. payload: &b"\x00"[..],
  3325. ..RECV_TEMPL
  3326. }));
  3327. }
  3328. // =========================================================================================//
  3329. // Tests for time-to-live configuration.
  3330. // =========================================================================================//
  3331. #[test]
  3332. fn test_set_hop_limit() {
  3333. let mut s = socket_syn_received();
  3334. let mut caps = DeviceCapabilities::default();
  3335. caps.max_transmission_unit = 1520;
  3336. s.set_hop_limit(Some(0x2a));
  3337. assert_eq!(s.dispatch(Instant::from_millis(0), &caps, |(ip_repr, _)| {
  3338. assert_eq!(ip_repr.hop_limit(), 0x2a);
  3339. Ok(())
  3340. }), Ok(()));
  3341. }
  3342. #[test]
  3343. #[should_panic(expected = "the time-to-live value of a packet must not be zero")]
  3344. fn test_set_hop_limit_zero() {
  3345. let mut s = socket_syn_received();
  3346. s.set_hop_limit(Some(0));
  3347. }
  3348. // =========================================================================================//
  3349. // Tests for reassembly.
  3350. // =========================================================================================//
  3351. #[test]
  3352. fn test_out_of_order() {
  3353. let mut s = socket_established();
  3354. send!(s, TcpRepr {
  3355. seq_number: REMOTE_SEQ + 1 + 3,
  3356. ack_number: Some(LOCAL_SEQ + 1),
  3357. payload: &b"def"[..],
  3358. ..SEND_TEMPL
  3359. }, Ok(Some(TcpRepr {
  3360. seq_number: LOCAL_SEQ + 1,
  3361. ack_number: Some(REMOTE_SEQ + 1),
  3362. ..RECV_TEMPL
  3363. })));
  3364. s.recv(|buffer| {
  3365. assert_eq!(buffer, b"");
  3366. (buffer.len(), ())
  3367. }).unwrap();
  3368. send!(s, TcpRepr {
  3369. seq_number: REMOTE_SEQ + 1,
  3370. ack_number: Some(LOCAL_SEQ + 1),
  3371. payload: &b"abcdef"[..],
  3372. ..SEND_TEMPL
  3373. }, Ok(Some(TcpRepr {
  3374. seq_number: LOCAL_SEQ + 1,
  3375. ack_number: Some(REMOTE_SEQ + 1 + 6),
  3376. window_len: 58,
  3377. ..RECV_TEMPL
  3378. })));
  3379. s.recv(|buffer| {
  3380. assert_eq!(buffer, b"abcdef");
  3381. (buffer.len(), ())
  3382. }).unwrap();
  3383. }
  3384. #[test]
  3385. fn test_buffer_wraparound_rx() {
  3386. let mut s = socket_established();
  3387. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3388. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3389. send!(s, TcpRepr {
  3390. seq_number: REMOTE_SEQ + 1,
  3391. ack_number: Some(LOCAL_SEQ + 1),
  3392. payload: &b"abc"[..],
  3393. ..SEND_TEMPL
  3394. });
  3395. s.recv(|buffer| {
  3396. assert_eq!(buffer, b"abc");
  3397. (buffer.len(), ())
  3398. }).unwrap();
  3399. send!(s, TcpRepr {
  3400. seq_number: REMOTE_SEQ + 1 + 3,
  3401. ack_number: Some(LOCAL_SEQ + 1),
  3402. payload: &b"defghi"[..],
  3403. ..SEND_TEMPL
  3404. });
  3405. let mut data = [0; 6];
  3406. assert_eq!(s.recv_slice(&mut data[..]), Ok(6));
  3407. assert_eq!(data, &b"defghi"[..]);
  3408. }
  3409. #[test]
  3410. fn test_buffer_wraparound_tx() {
  3411. let mut s = socket_established();
  3412. s.tx_buffer = SocketBuffer::new(vec![0; 6]);
  3413. assert_eq!(s.send_slice(b"abc"), Ok(3));
  3414. recv!(s, Ok(TcpRepr {
  3415. seq_number: LOCAL_SEQ + 1,
  3416. ack_number: Some(REMOTE_SEQ + 1),
  3417. payload: &b"abc"[..],
  3418. ..RECV_TEMPL
  3419. }));
  3420. send!(s, TcpRepr {
  3421. seq_number: REMOTE_SEQ + 1,
  3422. ack_number: Some(LOCAL_SEQ + 1 + 3),
  3423. ..SEND_TEMPL
  3424. });
  3425. assert_eq!(s.send_slice(b"defghi"), Ok(6));
  3426. recv!(s, Ok(TcpRepr {
  3427. seq_number: LOCAL_SEQ + 1 + 3,
  3428. ack_number: Some(REMOTE_SEQ + 1),
  3429. payload: &b"def"[..],
  3430. ..RECV_TEMPL
  3431. }));
  3432. // "defghi" not contiguous in tx buffer
  3433. recv!(s, Ok(TcpRepr {
  3434. seq_number: LOCAL_SEQ + 1 + 3 + 3,
  3435. ack_number: Some(REMOTE_SEQ + 1),
  3436. payload: &b"ghi"[..],
  3437. ..RECV_TEMPL
  3438. }));
  3439. }
  3440. // =========================================================================================//
  3441. // Tests for packet filtering.
  3442. // =========================================================================================//
  3443. #[test]
  3444. fn test_doesnt_accept_wrong_port() {
  3445. let mut s = socket_established();
  3446. s.rx_buffer = SocketBuffer::new(vec![0; 6]);
  3447. s.assembler = Assembler::new(s.rx_buffer.capacity());
  3448. let tcp_repr = TcpRepr {
  3449. seq_number: REMOTE_SEQ + 1,
  3450. ack_number: Some(LOCAL_SEQ + 1),
  3451. dst_port: LOCAL_PORT + 1,
  3452. ..SEND_TEMPL
  3453. };
  3454. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  3455. let tcp_repr = TcpRepr {
  3456. seq_number: REMOTE_SEQ + 1,
  3457. ack_number: Some(LOCAL_SEQ + 1),
  3458. src_port: REMOTE_PORT + 1,
  3459. ..SEND_TEMPL
  3460. };
  3461. assert!(!s.accepts(&SEND_IP_TEMPL, &tcp_repr));
  3462. }
  3463. #[test]
  3464. fn test_doesnt_accept_wrong_ip() {
  3465. let s = socket_established();
  3466. let tcp_repr = TcpRepr {
  3467. seq_number: REMOTE_SEQ + 1,
  3468. ack_number: Some(LOCAL_SEQ + 1),
  3469. payload: &b"abcdef"[..],
  3470. ..SEND_TEMPL
  3471. };
  3472. let ip_repr = IpRepr::Unspecified {
  3473. src_addr: MOCK_IP_ADDR_2,
  3474. dst_addr: MOCK_IP_ADDR_1,
  3475. protocol: IpProtocol::Tcp,
  3476. payload_len: tcp_repr.buffer_len(),
  3477. hop_limit: 64
  3478. };
  3479. assert!(s.accepts(&ip_repr, &tcp_repr));
  3480. let ip_repr_wrong_src = IpRepr::Unspecified {
  3481. src_addr: MOCK_IP_ADDR_3,
  3482. dst_addr: MOCK_IP_ADDR_1,
  3483. protocol: IpProtocol::Tcp,
  3484. payload_len: tcp_repr.buffer_len(),
  3485. hop_limit: 64
  3486. };
  3487. assert!(!s.accepts(&ip_repr_wrong_src, &tcp_repr));
  3488. let ip_repr_wrong_dst = IpRepr::Unspecified {
  3489. src_addr: MOCK_IP_ADDR_2,
  3490. dst_addr: MOCK_IP_ADDR_3,
  3491. protocol: IpProtocol::Tcp,
  3492. payload_len: tcp_repr.buffer_len(),
  3493. hop_limit: 64
  3494. };
  3495. assert!(!s.accepts(&ip_repr_wrong_dst, &tcp_repr));
  3496. }
  3497. // =========================================================================================//
  3498. // Timer tests
  3499. // =========================================================================================//
  3500. #[test]
  3501. fn test_timer_retransmit() {
  3502. let mut r = Timer::default();
  3503. assert_eq!(r.should_retransmit(Instant::from_secs(1)), None);
  3504. r.set_for_retransmit(Instant::from_millis(1000));
  3505. assert_eq!(r.should_retransmit(Instant::from_millis(1000)), None);
  3506. assert_eq!(r.should_retransmit(Instant::from_millis(1050)), None);
  3507. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), Some(Duration::from_millis(101)));
  3508. r.set_for_retransmit(Instant::from_millis(1101));
  3509. assert_eq!(r.should_retransmit(Instant::from_millis(1101)), None);
  3510. assert_eq!(r.should_retransmit(Instant::from_millis(1150)), None);
  3511. assert_eq!(r.should_retransmit(Instant::from_millis(1200)), None);
  3512. assert_eq!(r.should_retransmit(Instant::from_millis(1301)), Some(Duration::from_millis(300)));
  3513. r.set_for_idle(Instant::from_millis(1301), None);
  3514. assert_eq!(r.should_retransmit(Instant::from_millis(1350)), None);
  3515. }
  3516. }