tcp.rs 127 KB

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