tcp.rs 118 KB

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