tcpsm.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. /*
  2. * Copyright (C) 2001-2007 by egnite Software GmbH
  3. * Copyright (C) 2009 by egnite GmbH
  4. * Copyright (c) 1993 by Digital Equipment Corporation
  5. * Copyright (c) 1983, 1993 by The Regents of the University of California
  6. *
  7. * All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in the
  17. * documentation and/or other materials provided with the distribution.
  18. * 3. Neither the name of the copyright holders nor the names of
  19. * contributors may be used to endorse or promote products derived
  20. * from this software without specific prior written permission.
  21. *
  22. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  29. * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
  30. * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  31. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  32. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  33. * SUCH DAMAGE.
  34. *
  35. * For additional information see http://www.ethernut.de/
  36. */
  37. /*!
  38. * \file net/tcpsm.c
  39. * \brief TCP state machine.
  40. *
  41. * \verbatim
  42. * $Id: tcpsm.c 5691 2014-05-02 15:23:32Z haraldkipp $
  43. * \endverbatim
  44. */
  45. #include <cfg/os.h>
  46. #include <cfg/tcp.h>
  47. #include <sys/thread.h>
  48. #include <sys/heap.h>
  49. #include <sys/event.h>
  50. #include <sys/timer.h>
  51. #include <errno.h>
  52. #include <netinet/in.h>
  53. #include <netinet/ip.h>
  54. #include <net/route.h>
  55. #include <sys/socket.h>
  56. #include <netinet/tcputil.h>
  57. #include <netinet/tcp.h>
  58. #ifdef NUTDEBUG
  59. #include <net/netdebug.h>
  60. #endif
  61. #ifndef NUT_THREAD_TCPSMSTACK
  62. #if defined(__AVR__)
  63. #if defined(__GNUC__)
  64. /* avr-gcc size optimized code used 148 bytes. */
  65. #define NUT_THREAD_TCPSMSTACK 256
  66. #else
  67. /* icc-avr v7.19 used 312 bytes. */
  68. #define NUT_THREAD_TCPSMSTACK 512
  69. #endif
  70. #elif defined(__AVR32__)
  71. #define NUT_THREAD_TCPSMSTACK 1024
  72. #else
  73. /* arm-elf-gcc used 260 bytes with size optimized, 644 bytes with debug code. */
  74. #define NUT_THREAD_TCPSMSTACK 384
  75. #endif
  76. #endif
  77. #ifndef TCP_RETRIES_MAX
  78. #define TCP_RETRIES_MAX 7
  79. #endif
  80. extern TCPSOCKET *tcpSocketList;
  81. /*!
  82. * \addtogroup xgTCP
  83. */
  84. /*@{*/
  85. HANDLE tcp_in_rdy;
  86. NETBUF *volatile tcp_in_nbq;
  87. static uint16_t tcp_in_cnt;
  88. static HANDLE tcpThread = 0;
  89. #ifndef TCP_COLLECT_INADV
  90. #define TCP_COLLECT_INADV 8
  91. #endif
  92. #ifndef TCP_COLLECT_SLIMIT
  93. #define TCP_COLLECT_SLIMIT 256
  94. #endif
  95. #ifndef TCP_BACKLOG_MAX
  96. #define TCP_BACKLOG_MAX 8
  97. #endif
  98. #if TCP_BACKLOG_MAX
  99. #ifndef TCP_BACKLOG_TIME
  100. #define TCP_BACKLOG_TIME 5
  101. #endif
  102. static NETBUF *tcp_backlog[TCP_BACKLOG_MAX];
  103. static uint_fast8_t tcp_backlog_time[TCP_BACKLOG_MAX];
  104. #endif
  105. static size_t tcp_adv_cnt;
  106. static size_t tcp_adv_max = TCP_WINSIZE;
  107. static int tcp_run_gc = 0;
  108. static void NutTcpStateProcess(TCPSOCKET * sock, NETBUF * nb);
  109. /* ================================================================
  110. * Helper functions
  111. * ================================================================
  112. */
  113. #if TCP_BACKLOG_MAX
  114. static int NutTcpBacklogAdd(NETBUF *nb)
  115. {
  116. uint_fast8_t i;
  117. uint_fast8_t n = TCP_BACKLOG_MAX;
  118. IPHDR *ih = (IPHDR *) nb->nb_nw.vp;
  119. TCPHDR *th = (TCPHDR *) nb->nb_tp.vp;
  120. /* Process SYN segments only. */
  121. if ((th->th_flags & (TH_SYN | TH_ACK | TH_RST)) == TH_SYN) {
  122. for (i = 0; i < TCP_BACKLOG_MAX; i++) {
  123. if (tcp_backlog[i] == NULL) {
  124. /* Remember the first free entry. */
  125. if (n == TCP_BACKLOG_MAX) {
  126. n = i;
  127. }
  128. }
  129. else if (((IPHDR *) tcp_backlog[i]->nb_nw.vp)->ip_src == ih->ip_src &&
  130. ((TCPHDR *) tcp_backlog[i]->nb_tp.vp)->th_sport == th->th_sport) {
  131. /* Already received a SYN. Either the remote is too impatient
  132. or we are too busy. Kill this entry and reject the SYN. */
  133. NutNetBufFree(tcp_backlog[i]);
  134. tcp_backlog[i] = NULL;
  135. return -1;
  136. }
  137. }
  138. /* First SYN from the remote for this port.
  139. If there is a free entry left, then use it. */
  140. if (n != TCP_BACKLOG_MAX) {
  141. tcp_backlog[n] = nb;
  142. tcp_backlog_time[n] = 0;
  143. return 0;
  144. }
  145. }
  146. return -1;
  147. }
  148. static NETBUF *NutTcpBacklogCheck(uint16_t port)
  149. {
  150. NETBUF *nb;
  151. uint_fast8_t i;
  152. uint_fast8_t n = TCP_BACKLOG_MAX;
  153. for (i = 0; i < TCP_BACKLOG_MAX; i++) {
  154. if (tcp_backlog[i]) {
  155. if (((TCPHDR *) tcp_backlog[i]->nb_tp.vp)->th_dport == port) {
  156. if (n == TCP_BACKLOG_MAX || tcp_backlog_time[i] > tcp_backlog_time[n]) {
  157. n = i;
  158. }
  159. }
  160. }
  161. }
  162. if (n == TCP_BACKLOG_MAX) {
  163. nb = NULL;
  164. } else {
  165. nb = tcp_backlog[n];
  166. tcp_backlog[n] = NULL;
  167. }
  168. return nb;
  169. }
  170. static NETBUF *NutTcpBacklogTimer(void)
  171. {
  172. NETBUF *nb;
  173. uint_fast8_t i;
  174. uint_fast8_t n = TCP_BACKLOG_MAX;
  175. for (i = 0; i < TCP_BACKLOG_MAX; i++) {
  176. if (tcp_backlog[i]) {
  177. if (tcp_backlog_time[i] < TCP_BACKLOG_TIME) {
  178. tcp_backlog_time[i]++;
  179. } else {
  180. n = i;
  181. }
  182. }
  183. }
  184. if (n == TCP_BACKLOG_MAX) {
  185. nb = NULL;
  186. } else {
  187. nb = tcp_backlog[n];
  188. tcp_backlog[n] = NULL;
  189. }
  190. return nb;
  191. }
  192. #endif /* TCP_BACKLOG_MAX */
  193. /*!
  194. * \brief Reads TCP option fields if any, and writes the data to
  195. * the socket descriptor if important for us.
  196. *
  197. * \param sock Socket descriptor. This pointer must have been
  198. * retrieved by calling NutTcpCreateSocket().
  199. * \param nb Network buffer structure containing a TCP segment.
  200. */
  201. static void NutTcpInputOptions(TCPSOCKET * sock, NETBUF * nb)
  202. {
  203. uint8_t *cp;
  204. uint16_t s;
  205. /* any options there? */
  206. if (nb->nb_tp.sz <= sizeof(TCPHDR)) {
  207. return;
  208. }
  209. /* loop through available options */
  210. for (cp = ((uint8_t *) nb->nb_tp.vp) + sizeof(TCPHDR); (*cp != TCPOPT_EOL)
  211. && (cp - (uint8_t *) nb->nb_tp.vp < (int) nb->nb_tp.sz);) {
  212. switch (*cp) {
  213. /* On NOP just proceed to next option */
  214. case TCPOPT_NOP:
  215. cp++;
  216. continue;
  217. /* Read MAXSEG option */
  218. case TCPOPT_MAXSEG:
  219. /* Network uses big endian. */
  220. s = cp[2];
  221. s <<= 8;
  222. s |= cp[3];
  223. if (s < sock->so_mss) {
  224. sock->so_mss = s;
  225. }
  226. cp += TCPOLEN_MAXSEG;
  227. break;
  228. /* Ignore any other options */
  229. default:
  230. cp += *(uint8_t *) (cp + 1);
  231. break;
  232. }
  233. }
  234. }
  235. /*!
  236. * \brief Move application data in sync from the network buffer
  237. * structure to the socket's receive buffer.
  238. *
  239. * \param sock Socket descriptor. This pointer must have been
  240. * retrieved by calling NutTcpCreateSocket().
  241. * \param nb Network buffer structure containing a TCP segment.
  242. */
  243. static void NutTcpProcessAppData(TCPSOCKET * sock, NETBUF * nb)
  244. {
  245. /*
  246. * Add the NETBUF to the socket's input buffer.
  247. */
  248. if (sock->so_rx_buf) {
  249. NETBUF *nbp = sock->so_rx_buf;
  250. while (nbp->nb_next) {
  251. nbp = nbp->nb_next;
  252. }
  253. nbp->nb_next = nb;
  254. } else {
  255. sock->so_rx_buf = nb;
  256. }
  257. /*
  258. * Update the number of bytes available in the socket's input buffer
  259. * and the sequence number we expect next.
  260. */
  261. sock->so_rx_cnt += nb->nb_ap.sz;
  262. sock->so_rx_nxt += nb->nb_ap.sz;
  263. /*
  264. * Reduce our TCP window size.
  265. */
  266. if (nb->nb_ap.sz >= sock->so_rx_win) {
  267. sock->so_rx_win = 0;
  268. } else {
  269. sock->so_rx_win -= nb->nb_ap.sz;
  270. }
  271. /*
  272. * Set the socket's ACK flag. This will enable ACK transmission in
  273. * the next outgoing segment. If no more NETBUFs are queued, we
  274. * force immediate transmission of the ACK.
  275. */
  276. sock->so_tx_flags |= SO_ACK;
  277. if (nb->nb_next) {
  278. nb->nb_next = NULL;
  279. } else {
  280. sock->so_tx_flags |= SO_FORCE;
  281. }
  282. if (++sock->so_rx_apc > TCP_COLLECT_INADV) {
  283. NETBUF *nbq;
  284. int_fast8_t apc = sock->so_rx_apc;
  285. int cnt = sock->so_rx_cnt;
  286. for (nbq = sock->so_rx_buf; nbq; nbq = nbq->nb_next) {
  287. if (nbq->nb_ap.sz < TCP_COLLECT_SLIMIT) {
  288. sock->so_rx_apc -= NutNetBufCollect(nbq, cnt);
  289. break;
  290. }
  291. if (--apc < 8) {
  292. break;
  293. }
  294. cnt -= nbq->nb_ap.sz;
  295. }
  296. }
  297. NutTcpOutput(sock, NULL, 0);
  298. }
  299. /*
  300. * \param sock Socket descriptor.
  301. */
  302. static void NutTcpProcessSyn(TCPSOCKET * sock, IPHDR * ih, TCPHDR * th)
  303. {
  304. uint16_t mss;
  305. NUTDEVICE *dev;
  306. IFNET *nif;
  307. sock->so_local_addr = ih->ip_dst;
  308. sock->so_remote_port = th->th_sport;
  309. sock->so_remote_addr = ih->ip_src;
  310. sock->so_rx_nxt = sock->so_tx_wl1 = sock->so_rx_isn = ntohl(th->th_seq);
  311. sock->so_rx_nxt++;
  312. sock->so_tx_win = ntohs(th->th_win);
  313. /*
  314. * To avoid unnecessary fragmentation, limit the
  315. * maximum segment size to the maximum transfer
  316. * unit of our interface.
  317. */
  318. dev = NutIpRouteQuery(ih->ip_src, NULL);
  319. if (dev) {
  320. nif = dev->dev_icb;
  321. mss = nif->if_mtu - sizeof(IPHDR) - sizeof(TCPHDR);
  322. if (sock->so_mss == 0 || sock->so_mss > mss) {
  323. sock->so_mss = mss;
  324. }
  325. /* Limit output buffer size to mms */
  326. if (sock->so_devobsz > sock->so_mss) {
  327. sock->so_devobsz = sock->so_mss;
  328. }
  329. }
  330. }
  331. /*!
  332. * \brief ACK processing.
  333. *
  334. * \param sock Socket descriptor. This pointer must have been
  335. * retrieved by calling NutTcpCreateSocket().
  336. *
  337. */
  338. static int NutTcpProcessAck(TCPSOCKET * sock, TCPHDR * th, uint16_t length)
  339. {
  340. NETBUF *nb;
  341. uint32_t h_seq;
  342. uint32_t h_ack;
  343. /*
  344. * If remote acked something not yet send, reply immediately.
  345. */
  346. h_ack = ntohl(th->th_ack);
  347. if (SeqIsAfter(h_ack, sock->so_tx_nxt)) {
  348. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  349. return 0;
  350. }
  351. /*
  352. * If the new sequence number or acknowledged sequence number
  353. * is above our last update, we adjust our transmit window.
  354. * Avoid dupe ACK processing on window updates.
  355. */
  356. if (h_ack == sock->so_tx_una) {
  357. h_seq = ntohl(th->th_seq);
  358. if (SeqIsAfter(h_seq, sock->so_tx_wl1) || (h_seq == sock->so_tx_wl1 && !SeqIsAfter(sock->so_tx_wl2, h_ack))) {
  359. sock->so_tx_win = ntohs(th->th_win);
  360. sock->so_tx_wl1 = h_seq;
  361. sock->so_tx_wl2 = h_ack;
  362. }
  363. }
  364. /*
  365. * Ignore old ACKs but wake up sleeping transmitter threads, because
  366. * the window size may have changed.
  367. */
  368. if (SeqIsAfter(sock->so_tx_una, h_ack)) {
  369. return 0;
  370. }
  371. /*
  372. * Process duplicate ACKs.
  373. */
  374. if (h_ack == sock->so_tx_una) {
  375. /*
  376. * Don't count, if nothing is waiting for ACK,
  377. * segment contains data or on SYN/FIN segments.
  378. */
  379. if (sock->so_tx_nbq && length == 0 && (th->th_flags & (TH_SYN | TH_FIN)) == 0) {
  380. /*
  381. * If dupe counter reaches it's limit, resend
  382. * the oldest unacknowledged netbuf.
  383. */
  384. if (++sock->so_tx_dup >= 3) {
  385. sock->so_tx_dup = 0;
  386. #ifdef NUTDEBUG
  387. if (__tcp_trf & NET_DBG_SOCKSTATE) {
  388. NutDumpTcpHeader(__tcp_trs, "RET", sock, sock->so_tx_nbq);
  389. }
  390. #endif
  391. /*
  392. * Retransmit first unacked packet from queue.
  393. * Actually we got much more trouble if this fails.
  394. */
  395. if (NutTcpStateRetranTimeout(sock)) {
  396. return -1;
  397. }
  398. }
  399. }
  400. return 0;
  401. }
  402. /*
  403. * We're here, so the ACK must have actually acked something
  404. */
  405. sock->so_tx_dup = 0;
  406. sock->so_tx_una = h_ack;
  407. /*
  408. * Bugfix contributed by Liu Limin: If the remote is slow and this
  409. * line is missing, then Ethernut will send a full data packet even
  410. * if the remote closed the window.
  411. */
  412. sock->so_tx_win = ntohs(th->th_win);
  413. /*
  414. * Do round trip time calculation.
  415. */
  416. if (sock->so_rtt_seq && SeqIsAfter(h_ack, sock->so_rtt_seq)) {
  417. NutTcpCalcRtt(sock);
  418. }
  419. sock->so_rtt_seq = 0;
  420. /*
  421. * Remove all acknowledged netbufs.
  422. */
  423. while ((nb = sock->so_tx_nbq) != NULL) {
  424. /* Calculate the sequence beyond this netbuf. */
  425. h_seq = ntohl(((TCPHDR *) (nb->nb_tp.vp))->th_seq) + nb->nb_ap.sz;
  426. if (((TCPHDR *) (nb->nb_tp.vp))->th_flags & (TH_SYN | TH_FIN)) {
  427. h_seq++;
  428. }
  429. if (SeqIsAfter(h_seq, h_ack)) {
  430. break;
  431. }
  432. sock->so_tx_nbq = nb->nb_next;
  433. NutNetBufFree(nb);
  434. }
  435. /*
  436. * Reset retransmit timer and wake up waiting transmissions.
  437. */
  438. if (sock->so_tx_nbq) {
  439. sock->so_retran_time = (uint16_t) NutGetMillis() | 1;
  440. } else {
  441. sock->so_retran_time = 0;
  442. }
  443. sock->so_retransmits = 0;
  444. return 0;
  445. }
  446. /* ================================================================
  447. * State changes.
  448. * ================================================================
  449. */
  450. /*!
  451. * State change, possibly inform application.
  452. *
  453. * \param sock Socket descriptor.
  454. * \param state New state to switch to.
  455. *
  456. * \return 0 on success, -1 on illegal state change attempt.
  457. */
  458. static int NutTcpStateChange(TCPSOCKET * sock, uint8_t state)
  459. {
  460. int rc = 0;
  461. ureg_t txf = 0;
  462. switch (sock->so_state) {
  463. /* Handle the most common case first. */
  464. case TCPS_ESTABLISHED:
  465. switch (state) {
  466. case TCPS_FIN_WAIT_1:
  467. /*
  468. * Closed by application.
  469. */
  470. sock->so_tx_flags |= SO_FIN | SO_ACK;
  471. txf = 1;
  472. #ifdef RTLCONNECTHACK
  473. /*
  474. * Hack alert!
  475. * On the RTL8019AS we got a problem. Because of not handling
  476. * the CHRDY line, the controller drops outgoing packets when
  477. * a browser opens multiple connections concurrently, producing
  478. * several short incoming packets. Empirical test showed, that
  479. * a slight delay during connects and disconnects helped to
  480. * remarkably reduce this problem.
  481. */
  482. NutDelay(5);
  483. #endif
  484. break;
  485. case TCPS_CLOSE_WAIT:
  486. /*
  487. * FIN received.
  488. */
  489. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  490. txf = 1;
  491. break;
  492. default:
  493. rc = -1;
  494. break;
  495. }
  496. break;
  497. case TCPS_LISTEN:
  498. /*
  499. * SYN received.
  500. */
  501. if (state == TCPS_SYN_RECEIVED) {
  502. sock->so_tx_flags |= SO_SYN | SO_ACK;
  503. txf = 1;
  504. #ifdef RTLCONNECTHACK
  505. /*
  506. * Hack alert!
  507. * On the RTL8019AS we got a problem. Because of not handling
  508. * the CHRDY line, the controller drops outgoing packets when
  509. * a browser opens multiple connections concurrently, producing
  510. * several short incoming packets. Empirical test showed, that
  511. * a slight delay during connects and disconnects helped to
  512. * remarkably reduce this problem.
  513. */
  514. NutDelay(5);
  515. #endif
  516. } else
  517. if (state == TCPS_DESTROY) {
  518. /* Change to DESTROY. Socket will be destroyed ASAP */
  519. break;
  520. } else
  521. rc = -1;
  522. break;
  523. case TCPS_SYN_SENT:
  524. switch (state) {
  525. case TCPS_LISTEN:
  526. /*
  527. * RST received on passive socket.
  528. */
  529. break;
  530. case TCPS_SYN_RECEIVED:
  531. /*
  532. * SYN received.
  533. */
  534. sock->so_tx_flags |= SO_SYN | SO_ACK;
  535. txf = 1;
  536. break;
  537. case TCPS_ESTABLISHED:
  538. /*
  539. * SYNACK received.
  540. */
  541. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  542. txf = 1;
  543. break;
  544. case TCPS_DESTROY:
  545. /* Change to DESTROY. Socket will be destroyed ASAP */
  546. break;
  547. default:
  548. rc = -1;
  549. break;
  550. }
  551. break;
  552. case TCPS_SYN_RECEIVED:
  553. switch (state) {
  554. case TCPS_LISTEN:
  555. /*
  556. * RST received on passive socket.
  557. */
  558. break;
  559. case TCPS_ESTABLISHED:
  560. /*
  561. * ACK of SYN received.
  562. */
  563. break;
  564. case TCPS_FIN_WAIT_1:
  565. /*
  566. * Closed by application.
  567. */
  568. sock->so_tx_flags |= SO_FIN;
  569. txf = 1;
  570. break;
  571. case TCPS_CLOSE_WAIT:
  572. /*
  573. * FIN received.
  574. */
  575. sock->so_tx_flags |= SO_FIN | SO_ACK;
  576. txf = 1;
  577. break;
  578. default:
  579. rc = -1;
  580. break;
  581. }
  582. break;
  583. case TCPS_FIN_WAIT_1:
  584. switch (state) {
  585. case TCPS_FIN_WAIT_1:
  586. case TCPS_FIN_WAIT_2:
  587. /*
  588. * ACK of FIN received.
  589. */
  590. break;
  591. case TCPS_CLOSING:
  592. /*
  593. * FIN received.
  594. */
  595. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  596. txf = 1;
  597. break;
  598. case TCPS_TIME_WAIT:
  599. /*
  600. * FIN and ACK of FIN received.
  601. */
  602. break;
  603. case TCPS_DESTROY:
  604. /* Change to DESTROY. Socket will be destroyed ASAP */
  605. break;
  606. default:
  607. rc = -1;
  608. break;
  609. }
  610. break;
  611. case TCPS_FIN_WAIT_2:
  612. if (state == TCPS_DESTROY) {
  613. /* Change to DESTROY. Socket will be destroyed ASAP */
  614. break;
  615. } else
  616. /*
  617. * FIN received.
  618. */
  619. if (state != TCPS_TIME_WAIT) {
  620. rc = -1;
  621. }
  622. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  623. txf = 1;
  624. break;
  625. case TCPS_CLOSE_WAIT:
  626. /*
  627. * Closed by application.
  628. */
  629. if (state == TCPS_LAST_ACK) {
  630. sock->so_tx_flags |= SO_FIN | SO_ACK;
  631. txf = 1;
  632. } else {
  633. rc = -1;
  634. }
  635. break;
  636. case TCPS_CLOSING:
  637. if (state == TCPS_DESTROY) {
  638. /* Change to DESTROY. Socket will be destroyed ASAP */
  639. break;
  640. } else
  641. /*
  642. * ACK of FIN received.
  643. */
  644. if (state != TCPS_TIME_WAIT) {
  645. rc = -1;
  646. }
  647. break;
  648. case TCPS_LAST_ACK:
  649. if (state == TCPS_DESTROY) {
  650. /* Change to DESTROY. Socket will be destroyed ASAP */
  651. break;
  652. } else
  653. rc = -1;
  654. break;
  655. case TCPS_TIME_WAIT:
  656. if (state == TCPS_DESTROY) {
  657. /* Change to DESTROY. Socket will be destroyed ASAP */
  658. break;
  659. } else
  660. rc = -1;
  661. break;
  662. case TCPS_CLOSED:
  663. switch (state) {
  664. case TCPS_LISTEN:
  665. /*
  666. * Passive open by application.
  667. */
  668. break;
  669. case TCPS_SYN_SENT:
  670. /*
  671. * Active open by application.
  672. */
  673. sock->so_tx_flags |= SO_SYN;
  674. txf = 1;
  675. break;
  676. case TCPS_DESTROY:
  677. /* Change to DESTROY. Socket will be destroyed ASAP */
  678. break;
  679. default:
  680. rc = -1;
  681. break;
  682. }
  683. break;
  684. case TCPS_DESTROY:
  685. /* Do nothing, ignore the state change. Socket will be destroyed ASAP */
  686. break;
  687. }
  688. #ifdef NUTDEBUG
  689. if (__tcp_trf & NET_DBG_SOCKSTATE) {
  690. fprintf(__tcp_trs, " %04x-", (unsigned int) sock);
  691. if (rc) {
  692. NutDumpSockState(__tcp_trs, sock->so_state, "**ERR ", "**>");
  693. }
  694. NutDumpSockState(__tcp_trs, state, "[>", "]");
  695. }
  696. #endif
  697. if (rc == 0) {
  698. if (state == TCPS_DESTROY) {
  699. tcp_run_gc = 1;
  700. }
  701. sock->so_state = state;
  702. if (txf && NutTcpOutput(sock, NULL, 0)) {
  703. if (state == TCPS_SYN_SENT) {
  704. rc = -1;
  705. sock->so_last_error = EHOSTDOWN;
  706. NutEventPostAsync(&sock->so_ac_tq);
  707. }
  708. }
  709. if (state == TCPS_CLOSE_WAIT) {
  710. /*
  711. * Inform application.
  712. */
  713. NutEventBroadcast(&sock->so_rx_tq);
  714. NutEventBroadcast(&sock->so_pc_tq);
  715. NutEventBroadcast(&sock->so_ac_tq);
  716. /* Wake up all running selects (read and write queue) on this socket */
  717. NutSelectWakeup(sock->so_rx_wq_list, WQ_FLAG_READ);
  718. NutSelectWakeup(sock->so_tx_wq_list, WQ_FLAG_WRITE);
  719. }
  720. }
  721. return rc;
  722. }
  723. /* ================================================================
  724. * Application events.
  725. * ================================================================
  726. */
  727. /*!
  728. * \brief Initiated by the application.
  729. *
  730. * \param sock Socket descriptor. This pointer must have been
  731. * retrieved by calling NutTcpCreateSocket().
  732. *
  733. * \return 0 if granted, -1 otherwise. The specific error code
  734. * can be retrieved by calling NutTcpError().
  735. */
  736. int NutTcpStatePassiveOpenEvent(TCPSOCKET * sock)
  737. {
  738. if (sock->so_state != TCPS_CLOSED) {
  739. sock->so_last_error = EISCONN;
  740. return -1;
  741. }
  742. NutTcpStateChange(sock, TCPS_LISTEN);
  743. #if TCP_BACKLOG_MAX
  744. {
  745. /* If a SYN segment is already waiting in the backlog,
  746. then process it and return to the caller. */
  747. NETBUF *nb = NutTcpBacklogCheck(sock->so_local_port);
  748. if (nb) {
  749. NutTcpInputOptions(sock, nb);
  750. NutTcpStateProcess(sock, nb);
  751. return 0;
  752. }
  753. }
  754. if (NutEventWait(&sock->so_pc_tq, sock->so_read_to)) {
  755. sock->so_state = TCPS_CLOSED;
  756. sock->so_last_error = ETIMEDOUT;
  757. return -1;
  758. }
  759. #else
  760. /* For backward compatibility we simply block the application.
  761. If we do not have a backlog, then timing out would not make
  762. much sense anyway, because incoming connection attempts will
  763. be immediately rejected. */
  764. NutEventWait(&sock->so_pc_tq, 0);
  765. #endif /* TCP_BACKLOG_MAX */
  766. return 0;
  767. }
  768. /*!
  769. * \brief Initiated by the application.
  770. *
  771. * The caller must make sure, that the socket is in closed state.
  772. *
  773. * \param sock Socket descriptor. This pointer must have been
  774. * retrieved by calling NutTcpCreateSocket().
  775. *
  776. * \return 0 if granted, -1 otherwise.
  777. */
  778. int NutTcpStateActiveOpenEvent(TCPSOCKET * sock)
  779. {
  780. /*
  781. * Switch state to SYN_SENT. This will
  782. * transmit a SYN packet.
  783. */
  784. NutTcpStateChange(sock, TCPS_SYN_SENT);
  785. /*
  786. * Block application.
  787. */
  788. if (sock->so_state == TCPS_SYN_SENT) {
  789. if (NutEventWait(&sock->so_ac_tq, sock->so_write_to)) {
  790. NutTcpAbortSocket(sock, ETIMEDOUT);
  791. return -1;
  792. }
  793. }
  794. if (sock->so_state != TCPS_ESTABLISHED && sock->so_state != TCPS_CLOSE_WAIT) {
  795. return -1;
  796. }
  797. return 0;
  798. }
  799. /*!
  800. * \brief Socket close by application.
  801. *
  802. * If socket is in state SYN_RECEIVED or ESTABLISHED,
  803. * it is changed to FINWAIT1.
  804. *
  805. * No further data sending is accepted.
  806. * Receiving is still allowed.
  807. *
  808. * \param sock Socket descriptor. This pointer must have been
  809. * retrieved by calling NutTcpCreateSocket().
  810. */
  811. int NutTcpStateCloseEvent(TCPSOCKET * sock)
  812. {
  813. if (sock == NULL) {
  814. return -1;
  815. }
  816. NutThreadYield();
  817. switch (sock->so_state) {
  818. case TCPS_LISTEN:
  819. case TCPS_SYN_SENT:
  820. case TCPS_CLOSED:
  821. /*
  822. * No connection yet, immediately destroy the socket.
  823. */
  824. NutTcpStateChange(sock, TCPS_DESTROY);
  825. break;
  826. case TCPS_SYN_RECEIVED:
  827. case TCPS_ESTABLISHED:
  828. /*
  829. * Send a FIN and wait for ACK or FIN.
  830. */
  831. NutTcpStateChange(sock, TCPS_FIN_WAIT_1);
  832. break;
  833. case TCPS_CLOSE_WAIT:
  834. /*
  835. * RFC 793 is wrong.
  836. */
  837. NutTcpStateChange(sock, TCPS_LAST_ACK);
  838. break;
  839. case TCPS_FIN_WAIT_1:
  840. case TCPS_FIN_WAIT_2:
  841. case TCPS_CLOSING:
  842. case TCPS_LAST_ACK:
  843. case TCPS_TIME_WAIT:
  844. sock->so_last_error = EALREADY;
  845. return -1;
  846. case TCPS_DESTROY:
  847. default:
  848. sock->so_last_error = ENOTCONN;
  849. return -1;
  850. }
  851. return 0;
  852. }
  853. /*!
  854. * \brief Initiated by the application.
  855. *
  856. * \param sock Socket descriptor. This pointer must have been
  857. * retrieved by calling NutTcpCreateSocket().
  858. */
  859. int NutTcpStateWindowEvent(TCPSOCKET * sock)
  860. {
  861. if (sock == NULL) {
  862. return -1;
  863. }
  864. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  865. NutTcpOutput(sock, NULL, 0);
  866. return 0;
  867. }
  868. /* ================================================================
  869. * Timeout events.
  870. * ================================================================
  871. */
  872. /*!
  873. * \brief Retransmit a segment after ACK timeout.
  874. *
  875. * This function is called by the TCP timer.
  876. *
  877. * \param sock Socket descriptor. This pointer must have been
  878. * retrieved by calling NutTcpCreateSocket().
  879. * \returns Nonzero if socket was aborted due to reach of retransmit
  880. * limit or network error.
  881. *
  882. */
  883. int NutTcpStateRetranTimeout(TCPSOCKET * sock)
  884. {
  885. NETBUF *so_tx_next;
  886. if (sock->so_retransmits++ > TCP_RETRIES_MAX) {
  887. /* Abort the socket */
  888. NutTcpAbortSocket(sock, ETIMEDOUT);
  889. return -1;
  890. } else {
  891. #ifdef NUTDEBUG
  892. if (__tcp_trf & NET_DBG_SOCKSTATE) {
  893. NutDumpTcpHeader(__tcp_trs, "RET", sock, sock->so_tx_nbq);
  894. }
  895. #endif
  896. /* We must save sock->so_tx_nbq->nb_next before calling NutIpOutput,
  897. * because in case of error the NETBUF is release by NutIpOutput and
  898. * not longer available.
  899. */
  900. so_tx_next = sock->so_tx_nbq->nb_next;
  901. if (NutIpOutput(IPPROTO_TCP, sock->so_remote_addr, sock->so_tx_nbq)) {
  902. /* Adjust packet queue */
  903. sock->so_tx_nbq = so_tx_next;
  904. /* Abort the socket */
  905. NutTcpAbortSocket(sock, ENETDOWN);
  906. return -1;
  907. } else {
  908. /* Restart the retransmission timer. */
  909. sock->so_retran_time = (uint16_t) NutGetMillis() | 1;
  910. /* Double retransmission timeout up to maximum. */
  911. if (sock->so_rtto < TCP_RTTO_MAX / 2) {
  912. sock->so_rtto <<= 1;
  913. } else {
  914. sock->so_rtto = TCP_RTTO_MAX;
  915. }
  916. return 0;
  917. }
  918. }
  919. }
  920. /* ================================================================
  921. * Segment arrival events.
  922. * ================================================================
  923. */
  924. /*!
  925. * \brief
  926. * Process incoming segments in listening state.
  927. *
  928. * Wait for a connection request from a remote socket.
  929. *
  930. * \param sock Socket descriptor.
  931. * \param nb Network buffer structure containing a TCP segment.
  932. */
  933. static void NutTcpStateListen(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  934. {
  935. /*
  936. * Got a SYN segment. Store relevant data in our socket
  937. * structure and switch to TCPS_SYN_RECEIVED.
  938. */
  939. if ((flags & (TH_SYN | TH_ACK | TH_RST)) == TH_SYN) {
  940. NutTcpProcessSyn(sock, nb->nb_nw.vp, th);
  941. NutTcpStateChange(sock, TCPS_SYN_RECEIVED);
  942. NutNetBufFree(nb);
  943. } else
  944. NutTcpReject(nb);
  945. }
  946. /*!
  947. * \brief Process incoming segments in SYN-SENT state.
  948. *
  949. * Wait for a matching connection request after having sent ours.
  950. *
  951. * \param sock Socket descriptor.
  952. * \param nb Network buffer structure containing a TCP segment.
  953. */
  954. static void NutTcpStateSynSent(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  955. {
  956. /*
  957. * Validate ACK, if set.
  958. */
  959. if (flags & TH_ACK) {
  960. if (!SeqIsBetween(ntohl(th->th_ack), sock->so_tx_isn + 1, sock->so_tx_nxt)) {
  961. NutTcpReject(nb);
  962. return;
  963. }
  964. }
  965. /*
  966. * Handle RST flag. If we were in the LISTEN state,
  967. * then we return to the LISTEN state, otherwise we
  968. * abort the connection and go to the CLOSED state.
  969. */
  970. if (flags & TH_RST) {
  971. if (flags & TH_ACK) {
  972. NutTcpAbortSocket(sock, ECONNREFUSED);
  973. }
  974. NutNetBufFree(nb);
  975. return;
  976. }
  977. /*
  978. * Handle SYN flag. If we got a valid ACK too, then
  979. * our connection is established. Otherwise enter
  980. * SYNRCVD state.
  981. */
  982. if (flags & TH_SYN) {
  983. NutTcpProcessSyn(sock, nb->nb_nw.vp, th);
  984. if (flags & TH_ACK) {
  985. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  986. NutTcpStateChange(sock, TCPS_ESTABLISHED);
  987. /* Wake up the actively connecting thread. */
  988. NutEventPost(&sock->so_ac_tq);
  989. } else {
  990. NutTcpStateChange(sock, TCPS_SYN_RECEIVED);
  991. }
  992. }
  993. NutNetBufFree(nb);
  994. }
  995. /*
  996. * \brief
  997. * Process incoming segments in SYN-RECEIVED state.
  998. *
  999. * Waiting for a confirming connection request
  1000. * acknowledgment after having both received
  1001. * and sent a connection request.
  1002. *
  1003. * \param sock Socket descriptor.
  1004. * \param nb Network buffer structure containing a TCP segment.
  1005. */
  1006. static void NutTcpStateSynReceived(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1007. {
  1008. /*
  1009. * If our previous ack receives a reset response,
  1010. * then we fall back to the listening state.
  1011. */
  1012. if (flags & TH_RST) {
  1013. if (sock->so_pc_tq) {
  1014. NutTcpStateChange(sock, TCPS_LISTEN);
  1015. } else {
  1016. NutTcpAbortSocket(sock, ECONNREFUSED);
  1017. }
  1018. NutNetBufFree(nb);
  1019. sock->so_retran_time = 0;
  1020. NutTcpDiscardBuffers(sock);
  1021. return;
  1022. }
  1023. /*
  1024. * Silently discard duplicate SYN.
  1025. */
  1026. if (flags & TH_SYN) {
  1027. NutNetBufFree(nb);
  1028. return;
  1029. }
  1030. /*
  1031. * Silently discard segments without ACK.
  1032. */
  1033. if ((flags & TH_ACK) == 0) {
  1034. NutNetBufFree(nb);
  1035. return;
  1036. }
  1037. /*
  1038. * Reject out of window sequence.
  1039. */
  1040. if (!SeqIsBetween(ntohl(th->th_ack), sock->so_tx_una + 1, sock->so_tx_nxt)) {
  1041. NutTcpReject(nb);
  1042. return;
  1043. }
  1044. /* Acknowledge processing. */
  1045. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1046. /*
  1047. * Even SYN segments may contain application data, which will be stored
  1048. * in the socket's input buffer. However, there is no need to post an
  1049. * event to any thread waiting for data, because our connection is not
  1050. * yet established.
  1051. */
  1052. if (nb->nb_ap.sz) {
  1053. NutTcpProcessAppData(sock, nb);
  1054. } else {
  1055. NutNetBufFree(nb);
  1056. }
  1057. /*
  1058. * Process state change.
  1059. */
  1060. if (flags & TH_FIN) {
  1061. sock->so_rx_nxt++;
  1062. NutTcpStateChange(sock, TCPS_CLOSE_WAIT);
  1063. } else {
  1064. NutTcpStateChange(sock, TCPS_ESTABLISHED);
  1065. NutEventPost(&sock->so_pc_tq);
  1066. NutEventPost(&sock->so_ac_tq);
  1067. }
  1068. }
  1069. /*
  1070. * \brief Process incoming segments from established connections.
  1071. *
  1072. * Received application data will be delivered to the application
  1073. * until we receive a FIN segment.
  1074. *
  1075. * \param sock Socket descriptor.
  1076. * \param flags TCP flags.
  1077. * \param th Pointer to the TCP header within the NETBUF.
  1078. * \param nb Network buffer structure containing a TCP segment.
  1079. *
  1080. * \todo We may remove the unused counter of dropped segments, which
  1081. * were out of sequence.
  1082. */
  1083. static void NutTcpStateEstablished(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1084. {
  1085. if (flags & TH_RST) {
  1086. NutNetBufFree(nb);
  1087. NutTcpAbortSocket(sock, ECONNRESET);
  1088. return;
  1089. }
  1090. /*
  1091. * Reject SYNs. Silently discard late SYNs
  1092. * (Thanks to Mike Cornelius).
  1093. */
  1094. if (flags & TH_SYN) {
  1095. if (ntohl(th->th_seq) != sock->so_rx_isn) {
  1096. NutTcpReject(nb);
  1097. } else {
  1098. NutNetBufFree(nb);
  1099. }
  1100. return;
  1101. }
  1102. /*
  1103. * Silently discard segments without ACK.
  1104. */
  1105. if ((flags & TH_ACK) == 0) {
  1106. NutNetBufFree(nb);
  1107. return;
  1108. }
  1109. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1110. /*
  1111. * If the sequence number of the incoming segment is larger than
  1112. * expected, we probably missed one or more previous segments. Let's
  1113. * add this one to a linked list of segments received in advance and
  1114. * hope that the missing data will arrive later.
  1115. */
  1116. if (SeqIsAfter(ntohl(th->th_seq), sock->so_rx_nxt)) {
  1117. NETBUF *nbq;
  1118. NETBUF **nbqp;
  1119. TCPHDR *thq;
  1120. uint32_t th_seq;
  1121. uint32_t thq_seq;
  1122. if (nb->nb_ap.sz) {
  1123. /* Keep track of the number of bytes used by packets
  1124. received in advance. Honor a global limit. */
  1125. tcp_adv_cnt += nb->nb_dl.sz + sizeof(IPHDR) + sizeof(TCPHDR) + nb->nb_ap.sz;
  1126. if (tcp_adv_cnt > tcp_adv_max) {
  1127. /* Limit reached, discard the packet. */
  1128. NutNetBufFree(nb);
  1129. tcp_adv_cnt -= nb->nb_dl.sz + sizeof(IPHDR) + sizeof(TCPHDR) + nb->nb_ap.sz;
  1130. } else {
  1131. nbq = sock->so_rx_nbq;
  1132. nbqp = &sock->so_rx_nbq;
  1133. while (nbq) {
  1134. thq = (TCPHDR *) (nbq->nb_tp.vp);
  1135. th_seq = ntohl(th->th_seq);
  1136. thq_seq = ntohl(thq->th_seq);
  1137. if (SeqIsAfter(thq_seq, th_seq)) {
  1138. *nbqp = nb;
  1139. nb->nb_next = nbq;
  1140. break;
  1141. }
  1142. if (th_seq == thq_seq) {
  1143. NutNetBufFree(nb);
  1144. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  1145. NutTcpOutput(sock, NULL, 0);
  1146. return;
  1147. }
  1148. nbqp = &nbq->nb_next;
  1149. nbq = nbq->nb_next;
  1150. }
  1151. if (nbq == NULL) {
  1152. *nbqp = nb;
  1153. nb->nb_next = NULL;
  1154. }
  1155. }
  1156. } else
  1157. NutNetBufFree(nb);
  1158. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  1159. NutTcpOutput(sock, NULL, 0);
  1160. return;
  1161. }
  1162. /*
  1163. * Acknowledge any sequence numbers not expected,
  1164. * even if they do not contain any data. Keep alive
  1165. * packets contain a sequence number one less
  1166. * than the next data expected and they do not
  1167. * contain any data.
  1168. */
  1169. if (ntohl(th->th_seq) != sock->so_rx_nxt) {
  1170. sock->so_tx_flags |= SO_ACK | SO_FORCE;
  1171. /* This seems to be unused. */
  1172. sock->so_oos_drop++;
  1173. NutNetBufFree(nb);
  1174. NutTcpOutput(sock, NULL, 0);
  1175. }
  1176. /*
  1177. * The sequence number is exactly what we expected.
  1178. */
  1179. else if (nb->nb_ap.sz) {
  1180. NutTcpProcessAppData(sock, nb);
  1181. /*
  1182. * Process segments we may have received in advance.
  1183. */
  1184. while ((nb = sock->so_rx_nbq) != NULL) {
  1185. th = (TCPHDR *) (nb->nb_tp.vp);
  1186. if (SeqIsAfter(ntohl(th->th_seq), sock->so_rx_nxt)) {
  1187. break;
  1188. }
  1189. sock->so_rx_nbq = nb->nb_next;
  1190. /* Update the heap space used by packets
  1191. received in advance. */
  1192. tcp_adv_cnt -= nb->nb_dl.sz + sizeof(IPHDR) + sizeof(TCPHDR) + nb->nb_ap.sz;
  1193. if (ntohl(th->th_seq) == sock->so_rx_nxt) {
  1194. NutTcpProcessAppData(sock, nb);
  1195. flags |= th->th_flags;
  1196. } else
  1197. NutNetBufFree(nb);
  1198. }
  1199. /* Wake up a thread waiting for data. */
  1200. NutEventPost(&sock->so_rx_tq);
  1201. /* Wake up all running selects (read queue) on this socket */
  1202. NutSelectWakeup(sock->so_rx_wq_list, WQ_FLAG_READ);
  1203. } else {
  1204. NutNetBufFree(nb);
  1205. }
  1206. if (flags & TH_FIN) {
  1207. sock->so_rx_nxt++;
  1208. NutTcpStateChange(sock, TCPS_CLOSE_WAIT);
  1209. }
  1210. }
  1211. /*
  1212. * \brief Process incoming segments in FIN-WAIT1 state.
  1213. *
  1214. * Waiting for a connection termination request
  1215. * from the remote, or an acknowledgment of the
  1216. * connection termination request previously sent.
  1217. *
  1218. * The application already closed the socket.
  1219. *
  1220. * \param sock Socket descriptor.
  1221. * \param nb Network buffer structure containing a TCP segment.
  1222. *
  1223. * \todo The out of sync case seems to be ignored. Anyway, do we
  1224. * really need to process application data in this state?
  1225. */
  1226. static void NutTcpStateFinWait1(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1227. {
  1228. if (flags & TH_RST) {
  1229. NutNetBufFree(nb);
  1230. NutTcpStateChange(sock, TCPS_DESTROY);
  1231. return;
  1232. }
  1233. /*
  1234. * Reject SYNs.
  1235. */
  1236. if (flags & TH_SYN) {
  1237. NutTcpReject(nb);
  1238. return;
  1239. }
  1240. /*
  1241. * Silently discard segments without ACK.
  1242. */
  1243. if ((flags & TH_ACK) == 0) {
  1244. NutNetBufFree(nb);
  1245. return;
  1246. }
  1247. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1248. /*
  1249. * All segments had been acknowledged, including our FIN.
  1250. */
  1251. if (sock->so_tx_nxt == sock->so_tx_una) {
  1252. NutTcpStateChange(sock, TCPS_FIN_WAIT_2);
  1253. }
  1254. /*
  1255. * Process application data and release the network buffer.
  1256. * Is this really required?
  1257. */
  1258. if (nb->nb_ap.sz) {
  1259. NutTcpProcessAppData(sock, nb);
  1260. /* Wake up a thread waiting for data. */
  1261. NutEventPost(&sock->so_rx_tq);
  1262. /* Wake up all running selects (read queue) on this socket */
  1263. NutSelectWakeup(sock->so_rx_wq_list, WQ_FLAG_READ);
  1264. } else {
  1265. NutNetBufFree(nb);
  1266. }
  1267. if (flags & TH_FIN) {
  1268. sock->so_rx_nxt++;
  1269. /*
  1270. * Our FIN has been acked.
  1271. */
  1272. sock->so_time_wait = 0;
  1273. if (sock->so_state == TCPS_FIN_WAIT_2) {
  1274. NutTcpStateChange(sock, TCPS_TIME_WAIT);
  1275. } else {
  1276. NutTcpStateChange(sock, TCPS_CLOSING);
  1277. }
  1278. }
  1279. }
  1280. /*
  1281. * \brief Process incoming segments in FIN-WAIT2 state.
  1282. *
  1283. * Waiting for a connection termination request
  1284. * from the remote.
  1285. *
  1286. * The application already closed the socket.
  1287. *
  1288. * \param sock Socket descriptor.
  1289. * \param nb Network buffer structure containing a TCP segment.
  1290. *
  1291. * \todo There's probably no need to process application data.
  1292. */
  1293. static void NutTcpStateFinWait2(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1294. {
  1295. if (flags & TH_RST) {
  1296. NutNetBufFree(nb);
  1297. NutTcpStateChange(sock, TCPS_DESTROY);
  1298. return;
  1299. }
  1300. /*
  1301. * Reject SYNs.
  1302. */
  1303. if (flags & TH_SYN) {
  1304. NutTcpReject(nb);
  1305. return;
  1306. }
  1307. /*
  1308. * Silently discard segments without ACK.
  1309. */
  1310. if ((flags & TH_ACK) == 0) {
  1311. NutNetBufFree(nb);
  1312. return;
  1313. }
  1314. /*
  1315. * Process acknowledge and application data and release the
  1316. * network buffer.
  1317. */
  1318. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1319. /* Do we really need this? */
  1320. if (nb->nb_ap.sz) {
  1321. NutTcpProcessAppData(sock, nb);
  1322. /* Wake up a thread waiting for data. */
  1323. NutEventPost(&sock->so_rx_tq);
  1324. /* Wake up all running selects (read queue) on this socket */
  1325. NutSelectWakeup(sock->so_rx_wq_list, WQ_FLAG_READ);
  1326. } else
  1327. NutNetBufFree(nb);
  1328. if (flags & TH_FIN) {
  1329. sock->so_rx_nxt++;
  1330. sock->so_time_wait = 0;
  1331. NutTcpStateChange(sock, TCPS_TIME_WAIT);
  1332. }
  1333. }
  1334. /*
  1335. * \brief
  1336. * Process incoming segments in CLOSE-WAIT state.
  1337. *
  1338. * Waiting for a connection termination request
  1339. * from the local application.
  1340. *
  1341. * \param sock Socket descriptor.
  1342. * \param nb Network buffer structure containing a TCP segment.
  1343. */
  1344. static void NutTcpStateCloseWait(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1345. {
  1346. if (flags & TH_RST) {
  1347. NutNetBufFree(nb);
  1348. NutTcpAbortSocket(sock, ECONNRESET);
  1349. return;
  1350. }
  1351. /*
  1352. * Reject SYNs.
  1353. */
  1354. if (flags & TH_SYN) {
  1355. NutTcpReject(nb);
  1356. return;
  1357. }
  1358. /*
  1359. * Silently discard segments without ACK.
  1360. */
  1361. if (flags & TH_ACK) {
  1362. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1363. }
  1364. NutNetBufFree(nb);
  1365. }
  1366. /*
  1367. * \brief
  1368. * Process incoming segments in CLOSING state.
  1369. *
  1370. * Waiting for a connection termination request
  1371. * acknowledgment from the remote.
  1372. *
  1373. * The application already closed the socket.
  1374. *
  1375. * \param sock Socket descriptor.
  1376. * \param nb Network buffer structure containing a TCP segment.
  1377. */
  1378. static void NutTcpStateClosing(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1379. {
  1380. if (flags & TH_RST) {
  1381. NutNetBufFree(nb);
  1382. NutTcpStateChange(sock, TCPS_DESTROY);
  1383. return;
  1384. }
  1385. /*
  1386. * Reject SYNs.
  1387. */
  1388. if (flags & TH_SYN) {
  1389. NutTcpReject(nb);
  1390. return;
  1391. }
  1392. /*
  1393. * Silently discard segments without ACK.
  1394. */
  1395. if ((flags & TH_ACK) == 0) {
  1396. NutNetBufFree(nb);
  1397. return;
  1398. }
  1399. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1400. /*
  1401. * All segments had been acknowledged, including our FIN.
  1402. */
  1403. if (sock->so_tx_nxt == sock->so_tx_una) {
  1404. sock->so_time_wait = 0;
  1405. NutTcpStateChange(sock, TCPS_TIME_WAIT);
  1406. }
  1407. NutNetBufFree(nb);
  1408. }
  1409. /*!
  1410. * \brief
  1411. * Process incoming segment in LAST_ACK state.
  1412. *
  1413. * Waiting for an acknowledgment of the connection termination
  1414. * request previously sent.
  1415. *
  1416. * The application already closed the socket.
  1417. *
  1418. * \param sock Socket descriptor.
  1419. * \param flags TCP flags of incoming segment.
  1420. * \param th TCP header of incoming segment.
  1421. * \param nb Network buffer structure containing a TCP segment.
  1422. */
  1423. static void NutTcpStateLastAck(TCPSOCKET * sock, uint8_t flags, TCPHDR * th, NETBUF * nb)
  1424. {
  1425. if (flags & TH_RST) {
  1426. NutNetBufFree(nb);
  1427. NutTcpStateChange(sock, TCPS_DESTROY);
  1428. return;
  1429. }
  1430. /*
  1431. * Reject SYNs.
  1432. */
  1433. if (flags & TH_SYN) {
  1434. NutTcpReject(nb);
  1435. return;
  1436. }
  1437. /*
  1438. * Silently discard segments without ACK.
  1439. */
  1440. if ((flags & TH_ACK) == 0) {
  1441. NutNetBufFree(nb);
  1442. return;
  1443. }
  1444. NutTcpProcessAck(sock, th, nb->nb_ap.sz);
  1445. NutNetBufFree(nb);
  1446. if (sock->so_tx_nxt == sock->so_tx_una) {
  1447. NutTcpStateChange(sock, TCPS_DESTROY);
  1448. }
  1449. }
  1450. /*!
  1451. * \brief Process incoming TCP segments.
  1452. *
  1453. * Processing is based on the current state of the socket connection.
  1454. *
  1455. * \param sock Socket descriptor. This pointer must have been
  1456. * retrieved by calling NutTcpCreateSocket().
  1457. * \param nb Network buffer structure containing a TCP segment.
  1458. * Will be released within this routine.
  1459. */
  1460. static void NutTcpStateProcess(TCPSOCKET * sock, NETBUF * nb)
  1461. {
  1462. uint32_t tx_win;
  1463. uint32_t tx_una;
  1464. TCPHDR *th = (TCPHDR *) nb->nb_tp.vp;
  1465. uint8_t flags = th->th_flags;
  1466. #ifdef NUTDEBUG
  1467. if (__tcp_trf & NET_DBG_SOCKSTATE) {
  1468. fprintf(__tcp_trs, " %04x-", (unsigned int) sock);
  1469. NutDumpSockState(__tcp_trs, sock->so_state, "[", ">]");
  1470. }
  1471. #endif
  1472. switch (sock->so_state) {
  1473. /* Handle the most common case first. */
  1474. case TCPS_ESTABLISHED:
  1475. tx_win = sock->so_tx_win;
  1476. tx_una = sock->so_tx_una;
  1477. NutTcpStateEstablished(sock, flags, th, nb);
  1478. /* Wake up all threads waiting for transmit, if something interesting happened. */
  1479. if (sock->so_state != TCPS_ESTABLISHED || /* Status changed. */
  1480. sock->so_tx_win > tx_win || /* Windows changed. */
  1481. sock->so_tx_una != tx_una) { /* Unacknowledged data changed. */
  1482. NutEventBroadcast(&sock->so_tx_tq);
  1483. /* Wake up all running selects (write queue) on this socket */
  1484. NutSelectWakeup(sock->so_tx_wq_list, WQ_FLAG_WRITE);
  1485. }
  1486. break;
  1487. case TCPS_LISTEN:
  1488. NutTcpStateListen(sock, flags, th, nb);
  1489. break;
  1490. case TCPS_SYN_SENT:
  1491. NutTcpStateSynSent(sock, flags, th, nb);
  1492. break;
  1493. case TCPS_SYN_RECEIVED:
  1494. NutTcpStateSynReceived(sock, flags, th, nb);
  1495. break;
  1496. case TCPS_FIN_WAIT_1:
  1497. NutTcpStateFinWait1(sock, flags, th, nb);
  1498. break;
  1499. case TCPS_FIN_WAIT_2:
  1500. NutTcpStateFinWait2(sock, flags, th, nb);
  1501. break;
  1502. case TCPS_CLOSE_WAIT:
  1503. NutTcpStateCloseWait(sock, flags, th, nb);
  1504. break;
  1505. case TCPS_CLOSING:
  1506. NutTcpStateClosing(sock, flags, th, nb);
  1507. break;
  1508. case TCPS_LAST_ACK:
  1509. NutTcpStateLastAck(sock, flags, th, nb);
  1510. break;
  1511. case TCPS_TIME_WAIT:
  1512. /*
  1513. * Ignore everything while in TIME_WAIT state.
  1514. */
  1515. NutNetBufFree(nb);
  1516. break;
  1517. case TCPS_CLOSED:
  1518. case TCPS_DESTROY:
  1519. /*
  1520. * Reject everything while in CLOSED or DESTROY state.
  1521. */
  1522. NutTcpReject(nb);
  1523. break;
  1524. default:
  1525. NutNetBufFree(nb);
  1526. break;
  1527. }
  1528. }
  1529. /*!
  1530. * \brief Destroy previously allocated socket marked for destroy.
  1531. *
  1532. * Remove socket from the socket list and release occupied memory.
  1533. *
  1534. * This function is called, if the TCP statemachine is idle
  1535. */
  1536. void NutTcpGarbadgeCollect(void)
  1537. {
  1538. TCPSOCKET *sp;
  1539. TCPSOCKET *volatile *spp;
  1540. TCPSOCKET *sock;
  1541. /*
  1542. * Remove socket from the list and free its allocated memory
  1543. */
  1544. sp = tcpSocketList;
  1545. spp = &tcpSocketList;
  1546. while (sp) {
  1547. if (sp->so_state == TCPS_DESTROY) {
  1548. sock = sp;
  1549. *spp = sp->so_next;
  1550. sp = sp->so_next;
  1551. NutTcpDestroySocket(sock);
  1552. continue;
  1553. }
  1554. spp = &sp->so_next;
  1555. sp = sp->so_next;
  1556. }
  1557. }
  1558. /*! \fn NutTcpSm(void *arg)
  1559. * \brief TCP state machine thread.
  1560. *
  1561. * The TCP state machine serves two purposes: It processes incoming TCP
  1562. * segments and handles TCP timers.
  1563. */
  1564. THREAD(NutTcpSm, arg)
  1565. {
  1566. NETBUF *nb;
  1567. NETBUF *nbx;
  1568. TCPHDR *th;
  1569. IPHDR *ih;
  1570. TCPSOCKET *sock;
  1571. uint8_t tac = 0;
  1572. (void)arg;
  1573. /*
  1574. * It won't help giving us a higher priority than the application
  1575. * code. We depend on the speed of the reading application.
  1576. */
  1577. NutThreadSetPriority(32);
  1578. for (;;) {
  1579. if (tcp_run_gc) {
  1580. tcp_run_gc = 0;
  1581. NutTcpGarbadgeCollect();
  1582. }
  1583. if (++tac > 3 || NutEventWait(&tcp_in_rdy, 200)) {
  1584. tac = 0;
  1585. #if TCP_BACKLOG_MAX
  1586. /* Process backlog timer.
  1587. *
  1588. * Note, that the tac counter will spoil any exact timing.
  1589. * On the other hand, if we are very busy, it may not be that
  1590. * bad to kill early SYN segments soon.
  1591. */
  1592. nb = NutTcpBacklogTimer();
  1593. if (nb) {
  1594. NutTcpReject(nb);
  1595. }
  1596. #endif /* TCP_BACKLOG_MAX */
  1597. for (sock = tcpSocketList; sock; sock = sock->so_next) {
  1598. /*
  1599. * Send late acks.
  1600. */
  1601. if (sock->so_tx_flags & SO_ACK) {
  1602. sock->so_tx_flags |= SO_FORCE;
  1603. NutTcpOutput(sock, NULL, 0);
  1604. }
  1605. /*
  1606. * Process retransmit timer.
  1607. */
  1608. if (sock->so_tx_nbq && sock->so_retran_time) {
  1609. if ((uint16_t) ((uint16_t) NutGetMillis() - (sock->so_retran_time & ~1)) >= sock->so_rtto) {
  1610. NutTcpStateRetranTimeout(sock);
  1611. }
  1612. }
  1613. /*
  1614. * Destroy sockets after timeout in TIMEWAIT state.
  1615. */
  1616. if (sock->so_state == TCPS_TIME_WAIT || sock->so_state == TCPS_FIN_WAIT_2) {
  1617. if (sock->so_time_wait++ >= 9) {
  1618. NutTcpStateChange(sock, TCPS_DESTROY);
  1619. break;
  1620. }
  1621. }
  1622. /*
  1623. * Recover from SYN flood attacks.
  1624. */
  1625. else if (sock->so_state == TCPS_SYN_RECEIVED) {
  1626. if (sock->so_time_wait++ >= 45) {
  1627. sock->so_state = TCPS_LISTEN;
  1628. sock->so_time_wait = 0;
  1629. }
  1630. }
  1631. }
  1632. } else {
  1633. nb = tcp_in_nbq;
  1634. tcp_in_nbq = NULL;
  1635. tcp_in_cnt = 0;
  1636. while (nb) {
  1637. ih = (IPHDR *) nb->nb_nw.vp;
  1638. th = (TCPHDR *) nb->nb_tp.vp;
  1639. sock = NutTcpFindSocket(th->th_dport, th->th_sport, ih->ip_src);
  1640. #ifdef NUTDEBUG
  1641. if (__tcp_trf & NET_DBG_SOCKSTATE) {
  1642. NutDumpTcpHeader(__tcp_trs, " IN", sock, nb);
  1643. }
  1644. #endif
  1645. nbx = nb->nb_next;
  1646. /* If a matching socket exists, process the NETBUF. */
  1647. if (sock) {
  1648. NutTcpInputOptions(sock, nb);
  1649. NutTcpStateProcess(sock, nb);
  1650. }
  1651. #if TCP_BACKLOG_MAX
  1652. /* No matching socket, try to add it to the backlog. */
  1653. else if (NutTcpBacklogAdd(nb) == 0) {
  1654. }
  1655. #endif
  1656. /* No matching socket and no backlog. Reject it. */
  1657. else {
  1658. NutTcpReject(nb);
  1659. }
  1660. nb = nbx;
  1661. }
  1662. }
  1663. }
  1664. }
  1665. /*!
  1666. * \brief Process incoming TCP segments.
  1667. *
  1668. * All incoming TCP packets are passed to this routine. They will
  1669. * be added to a global queue and processed by the TCP state
  1670. * machine, which is running on a separate thread.
  1671. *
  1672. * \note This routine is called by the IP layer on incoming
  1673. * TCP segments. Applications typically do not call
  1674. * this function.
  1675. */
  1676. void NutTcpStateMachine(NETBUF * nb)
  1677. {
  1678. NETBUF *nbp;
  1679. uint16_t size;
  1680. nb->nb_next = NULL;
  1681. /*
  1682. * Incoming TCP segments are rejected and released if no TCP
  1683. * sockets have been opened. Not doing so would add them
  1684. * to the queue and never release the NETBUF. Thanks to
  1685. * Ralph Mason for this fix.
  1686. */
  1687. if (tcpThread == NULL) {
  1688. NutTcpReject(nb);
  1689. return;
  1690. }
  1691. nbp = tcp_in_nbq;
  1692. if (nbp == NULL) {
  1693. tcp_in_nbq = nb;
  1694. NutEventPost(&tcp_in_rdy);
  1695. } else {
  1696. size = nb->nb_nw.sz + nb->nb_tp.sz + nb->nb_ap.sz;
  1697. if (tcp_in_cnt + size + 2048 < NutHeapAvailable()) {
  1698. tcp_in_cnt += size;
  1699. while (nbp->nb_next)
  1700. nbp = nbp->nb_next;
  1701. nbp->nb_next = nb;
  1702. NutEventPost(&tcp_in_rdy);
  1703. } else
  1704. NutNetBufFree(nb);
  1705. }
  1706. }
  1707. /*!
  1708. * \brief Start TCP state machine.
  1709. *
  1710. * The socket interface will automatically call this routine as
  1711. * soon as the first socket is created.
  1712. *
  1713. * \return 0 on success, -1 otherwise.
  1714. */
  1715. int NutTcpInitStateMachine(void)
  1716. {
  1717. if (tcpThread == NULL) {
  1718. tcpThread = NutThreadCreate("tcpsm", NutTcpSm, NULL, NUT_THREAD_TCPSMSTACK * NUT_THREAD_STACK_MULT + NUT_THREAD_STACK_ADD);
  1719. if (tcpThread == NULL) {
  1720. return -1;
  1721. }
  1722. }
  1723. return 0;
  1724. }
  1725. /*!
  1726. * \brief Closes socket with error.
  1727. *
  1728. * Aborts any socket activity and sets last error.
  1729. *
  1730. * \param sock Socket descriptor.
  1731. * \param last_error Error number to report
  1732. *
  1733. * \note This routine is called internally by Nut/Net.
  1734. * Applications typically do not call this function.
  1735. *
  1736. * \return 0 on success, -1 otherwise.
  1737. */
  1738. int NutTcpAbortSocket(TCPSOCKET * sock, uint16_t last_error)
  1739. {
  1740. uint8_t current_state = sock->so_state;
  1741. sock->so_last_error = last_error;
  1742. sock->so_retran_time = 0;
  1743. sock->so_time_wait = 0;
  1744. /*
  1745. * If NutTcpCloseSocket was already called, we have to change
  1746. * to TCPS_TIME_WAIT state, otherwise the socket will not be destroyed.
  1747. * For the other cases just go to TCPS_CLOSED.
  1748. */
  1749. if (sock->so_state >= TCPS_FIN_WAIT_1) {
  1750. sock->so_state = TCPS_TIME_WAIT;
  1751. } else {
  1752. sock->so_state = TCPS_CLOSED;
  1753. }
  1754. NutTcpDiscardBuffers(sock);
  1755. NutEventBroadcast(&sock->so_rx_tq);
  1756. NutEventBroadcast(&sock->so_tx_tq);
  1757. NutEventBroadcast(&sock->so_pc_tq);
  1758. NutEventBroadcast(&sock->so_ac_tq);
  1759. /* Check if we had a timeout on NutTcpConnect(). In this case there is no
  1760. need for a notification of the select wait queues.
  1761. */
  1762. if (!((current_state == TCPS_SYN_SENT) && (last_error == ETIMEDOUT))) {
  1763. /* Wake up all running selects on this socket */
  1764. NutSelectWakeup(sock->so_rx_wq_list, WQ_FLAG_READ);
  1765. NutSelectWakeup(sock->so_tx_wq_list, WQ_FLAG_WRITE);
  1766. }
  1767. return 0;
  1768. }
  1769. /*@}*/