tcp.rs 122 KB

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