tcp.rs 135 KB

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