You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tcp.c 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <assert.h>
  5. #include <errno.h>
  6. #include <byteswap.h>
  7. #include <ipxe/timer.h>
  8. #include <ipxe/iobuf.h>
  9. #include <ipxe/malloc.h>
  10. #include <ipxe/init.h>
  11. #include <ipxe/retry.h>
  12. #include <ipxe/refcnt.h>
  13. #include <ipxe/pending.h>
  14. #include <ipxe/xfer.h>
  15. #include <ipxe/open.h>
  16. #include <ipxe/uri.h>
  17. #include <ipxe/netdevice.h>
  18. #include <ipxe/tcpip.h>
  19. #include <ipxe/tcp.h>
  20. /** @file
  21. *
  22. * TCP protocol
  23. *
  24. */
  25. FILE_LICENCE ( GPL2_OR_LATER );
  26. /** A TCP connection */
  27. struct tcp_connection {
  28. /** Reference counter */
  29. struct refcnt refcnt;
  30. /** List of TCP connections */
  31. struct list_head list;
  32. /** Flags */
  33. unsigned int flags;
  34. /** Data transfer interface */
  35. struct interface xfer;
  36. /** Remote socket address */
  37. struct sockaddr_tcpip peer;
  38. /** Local port */
  39. unsigned int local_port;
  40. /** Current TCP state */
  41. unsigned int tcp_state;
  42. /** Previous TCP state
  43. *
  44. * Maintained only for debug messages
  45. */
  46. unsigned int prev_tcp_state;
  47. /** Current sequence number
  48. *
  49. * Equivalent to SND.UNA in RFC 793 terminology.
  50. */
  51. uint32_t snd_seq;
  52. /** Unacknowledged sequence count
  53. *
  54. * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
  55. */
  56. uint32_t snd_sent;
  57. /** Send window
  58. *
  59. * Equivalent to SND.WND in RFC 793 terminology
  60. */
  61. uint32_t snd_win;
  62. /** Current acknowledgement number
  63. *
  64. * Equivalent to RCV.NXT in RFC 793 terminology.
  65. */
  66. uint32_t rcv_ack;
  67. /** Receive window
  68. *
  69. * Equivalent to RCV.WND in RFC 793 terminology.
  70. */
  71. uint32_t rcv_win;
  72. /** Received timestamp value
  73. *
  74. * Updated when a packet is received; copied to ts_recent when
  75. * the window is advanced.
  76. */
  77. uint32_t ts_val;
  78. /** Most recent received timestamp that advanced the window
  79. *
  80. * Equivalent to TS.Recent in RFC 1323 terminology.
  81. */
  82. uint32_t ts_recent;
  83. /** Transmit queue */
  84. struct list_head tx_queue;
  85. /** Receive queue */
  86. struct list_head rx_queue;
  87. /** Retransmission timer */
  88. struct retry_timer timer;
  89. /** Shutdown (TIME_WAIT) timer */
  90. struct retry_timer wait;
  91. /** Pending operations for SYN and FIN */
  92. struct pending_operation pending_flags;
  93. /** Pending operations for transmit queue */
  94. struct pending_operation pending_data;
  95. };
  96. /** TCP flags */
  97. enum tcp_flags {
  98. /** TCP data transfer interface has been closed */
  99. TCP_XFER_CLOSED = 0x0001,
  100. /** TCP timestamps are enabled */
  101. TCP_TS_ENABLED = 0x0002,
  102. /** TCP acknowledgement is pending */
  103. TCP_ACK_PENDING = 0x0004,
  104. };
  105. /** TCP internal header
  106. *
  107. * This is the header that replaces the TCP header for packets
  108. * enqueued on the receive queue.
  109. */
  110. struct tcp_rx_queued_header {
  111. /** SEQ value, in host-endian order
  112. *
  113. * This represents the SEQ value at the time the packet is
  114. * enqueued, and so excludes the SYN, if present.
  115. */
  116. uint32_t seq;
  117. /** Flags
  118. *
  119. * Only FIN is valid within this flags byte; all other flags
  120. * have already been processed by the time the packet is
  121. * enqueued.
  122. */
  123. uint8_t flags;
  124. /** Reserved */
  125. uint8_t reserved[3];
  126. };
  127. /**
  128. * List of registered TCP connections
  129. */
  130. static LIST_HEAD ( tcp_conns );
  131. /* Forward declarations */
  132. static struct interface_descriptor tcp_xfer_desc;
  133. static void tcp_expired ( struct retry_timer *timer, int over );
  134. static void tcp_wait_expired ( struct retry_timer *timer, int over );
  135. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  136. uint32_t win );
  137. /**
  138. * Name TCP state
  139. *
  140. * @v state TCP state
  141. * @ret name Name of TCP state
  142. */
  143. static inline __attribute__ (( always_inline )) const char *
  144. tcp_state ( int state ) {
  145. switch ( state ) {
  146. case TCP_CLOSED: return "CLOSED";
  147. case TCP_LISTEN: return "LISTEN";
  148. case TCP_SYN_SENT: return "SYN_SENT";
  149. case TCP_SYN_RCVD: return "SYN_RCVD";
  150. case TCP_ESTABLISHED: return "ESTABLISHED";
  151. case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
  152. case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
  153. case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
  154. case TCP_TIME_WAIT: return "TIME_WAIT";
  155. case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
  156. default: return "INVALID";
  157. }
  158. }
  159. /**
  160. * Dump TCP state transition
  161. *
  162. * @v tcp TCP connection
  163. */
  164. static inline __attribute__ (( always_inline )) void
  165. tcp_dump_state ( struct tcp_connection *tcp ) {
  166. if ( tcp->tcp_state != tcp->prev_tcp_state ) {
  167. DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
  168. tcp_state ( tcp->prev_tcp_state ),
  169. tcp_state ( tcp->tcp_state ) );
  170. }
  171. tcp->prev_tcp_state = tcp->tcp_state;
  172. }
  173. /**
  174. * Dump TCP flags
  175. *
  176. * @v flags TCP flags
  177. */
  178. static inline __attribute__ (( always_inline )) void
  179. tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
  180. if ( flags & TCP_RST )
  181. DBGC2 ( tcp, " RST" );
  182. if ( flags & TCP_SYN )
  183. DBGC2 ( tcp, " SYN" );
  184. if ( flags & TCP_PSH )
  185. DBGC2 ( tcp, " PSH" );
  186. if ( flags & TCP_FIN )
  187. DBGC2 ( tcp, " FIN" );
  188. if ( flags & TCP_ACK )
  189. DBGC2 ( tcp, " ACK" );
  190. }
  191. /***************************************************************************
  192. *
  193. * Open and close
  194. *
  195. ***************************************************************************
  196. */
  197. /**
  198. * Bind TCP connection to local port
  199. *
  200. * @v tcp TCP connection
  201. * @v port Local port number
  202. * @ret rc Return status code
  203. *
  204. * If the port is 0, the connection is assigned an available port
  205. * between 1024 and 65535.
  206. */
  207. static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
  208. struct tcp_connection *existing;
  209. uint16_t try_port;
  210. unsigned int i;
  211. /* If no port is specified, find an available port */
  212. if ( ! port ) {
  213. try_port = random();
  214. for ( i = 0 ; i < 65536 ; i++ ) {
  215. try_port++;
  216. if ( try_port < 1024 )
  217. continue;
  218. if ( tcp_bind ( tcp, try_port ) == 0 )
  219. return 0;
  220. }
  221. DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
  222. return -EADDRINUSE;
  223. }
  224. /* Attempt bind to local port */
  225. list_for_each_entry ( existing, &tcp_conns, list ) {
  226. if ( existing->local_port == port ) {
  227. DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
  228. tcp, port );
  229. return -EADDRINUSE;
  230. }
  231. }
  232. tcp->local_port = port;
  233. DBGC ( tcp, "TCP %p bound to port %d\n", tcp, port );
  234. return 0;
  235. }
  236. /**
  237. * Open a TCP connection
  238. *
  239. * @v xfer Data transfer interface
  240. * @v peer Peer socket address
  241. * @v local Local socket address, or NULL
  242. * @ret rc Return status code
  243. */
  244. static int tcp_open ( struct interface *xfer, struct sockaddr *peer,
  245. struct sockaddr *local ) {
  246. struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
  247. struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
  248. struct tcp_connection *tcp;
  249. unsigned int bind_port;
  250. int rc;
  251. /* Allocate and initialise structure */
  252. tcp = zalloc ( sizeof ( *tcp ) );
  253. if ( ! tcp )
  254. return -ENOMEM;
  255. DBGC ( tcp, "TCP %p allocated\n", tcp );
  256. ref_init ( &tcp->refcnt, NULL );
  257. intf_init ( &tcp->xfer, &tcp_xfer_desc, &tcp->refcnt );
  258. timer_init ( &tcp->timer, tcp_expired, &tcp->refcnt );
  259. timer_init ( &tcp->wait, tcp_wait_expired, &tcp->refcnt );
  260. tcp->prev_tcp_state = TCP_CLOSED;
  261. tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
  262. tcp_dump_state ( tcp );
  263. tcp->snd_seq = random();
  264. INIT_LIST_HEAD ( &tcp->tx_queue );
  265. INIT_LIST_HEAD ( &tcp->rx_queue );
  266. memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
  267. /* Bind to local port */
  268. bind_port = ( st_local ? ntohs ( st_local->st_port ) : 0 );
  269. if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
  270. goto err;
  271. /* Start timer to initiate SYN */
  272. start_timer_nodelay ( &tcp->timer );
  273. /* Add a pending operation for the SYN */
  274. pending_get ( &tcp->pending_flags );
  275. /* Attach parent interface, transfer reference to connection
  276. * list and return
  277. */
  278. intf_plug_plug ( &tcp->xfer, xfer );
  279. list_add ( &tcp->list, &tcp_conns );
  280. return 0;
  281. err:
  282. ref_put ( &tcp->refcnt );
  283. return rc;
  284. }
  285. /**
  286. * Close TCP connection
  287. *
  288. * @v tcp TCP connection
  289. * @v rc Reason for close
  290. *
  291. * Closes the data transfer interface. If the TCP state machine is in
  292. * a suitable state, the connection will be deleted.
  293. */
  294. static void tcp_close ( struct tcp_connection *tcp, int rc ) {
  295. struct io_buffer *iobuf;
  296. struct io_buffer *tmp;
  297. /* Close data transfer interface */
  298. intf_shutdown ( &tcp->xfer, rc );
  299. tcp->flags |= TCP_XFER_CLOSED;
  300. /* If we are in CLOSED, or have otherwise not yet received a
  301. * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
  302. * connection.
  303. */
  304. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  305. /* Transition to CLOSED for the sake of debugging messages */
  306. tcp->tcp_state = TCP_CLOSED;
  307. tcp_dump_state ( tcp );
  308. /* Free any unprocessed I/O buffers */
  309. list_for_each_entry_safe ( iobuf, tmp, &tcp->rx_queue, list ) {
  310. list_del ( &iobuf->list );
  311. free_iob ( iobuf );
  312. }
  313. /* Free any unsent I/O buffers */
  314. list_for_each_entry_safe ( iobuf, tmp, &tcp->tx_queue, list ) {
  315. list_del ( &iobuf->list );
  316. free_iob ( iobuf );
  317. pending_put ( &tcp->pending_data );
  318. }
  319. assert ( ! is_pending ( &tcp->pending_data ) );
  320. /* Remove pending operations for SYN and FIN, if applicable */
  321. pending_put ( &tcp->pending_flags );
  322. pending_put ( &tcp->pending_flags );
  323. /* Remove from list and drop reference */
  324. stop_timer ( &tcp->timer );
  325. stop_timer ( &tcp->wait );
  326. list_del ( &tcp->list );
  327. ref_put ( &tcp->refcnt );
  328. DBGC ( tcp, "TCP %p connection deleted\n", tcp );
  329. return;
  330. }
  331. /* If we have not had our SYN acknowledged (i.e. we are in
  332. * SYN_RCVD), pretend that it has been acknowledged so that we
  333. * can send a FIN without breaking things.
  334. */
  335. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  336. tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
  337. /* If we have no data remaining to send, start sending FIN */
  338. if ( list_empty ( &tcp->tx_queue ) &&
  339. ! ( tcp->tcp_state & TCP_STATE_SENT ( TCP_FIN ) ) ) {
  340. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  341. tcp_dump_state ( tcp );
  342. /* Add a pending operation for the FIN */
  343. pending_get ( &tcp->pending_flags );
  344. }
  345. }
  346. /***************************************************************************
  347. *
  348. * Transmit data path
  349. *
  350. ***************************************************************************
  351. */
  352. /**
  353. * Calculate transmission window
  354. *
  355. * @v tcp TCP connection
  356. * @ret len Maximum length that can be sent in a single packet
  357. */
  358. static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
  359. size_t len;
  360. /* Not ready if we're not in a suitable connection state */
  361. if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
  362. return 0;
  363. /* Length is the minimum of the receiver's window and the path MTU */
  364. len = tcp->snd_win;
  365. if ( len > TCP_PATH_MTU )
  366. len = TCP_PATH_MTU;
  367. return len;
  368. }
  369. /**
  370. * Check data-transfer flow control window
  371. *
  372. * @v tcp TCP connection
  373. * @ret len Length of window
  374. */
  375. static size_t tcp_xfer_window ( struct tcp_connection *tcp ) {
  376. /* Not ready if data queue is non-empty. This imposes a limit
  377. * of only one unACKed packet in the TX queue at any time; we
  378. * do this to conserve memory usage.
  379. */
  380. if ( ! list_empty ( &tcp->tx_queue ) )
  381. return 0;
  382. /* Return TCP window length */
  383. return tcp_xmit_win ( tcp );
  384. }
  385. /**
  386. * Process TCP transmit queue
  387. *
  388. * @v tcp TCP connection
  389. * @v max_len Maximum length to process
  390. * @v dest I/O buffer to fill with data, or NULL
  391. * @v remove Remove data from queue
  392. * @ret len Length of data processed
  393. *
  394. * This processes at most @c max_len bytes from the TCP connection's
  395. * transmit queue. Data will be copied into the @c dest I/O buffer
  396. * (if provided) and, if @c remove is true, removed from the transmit
  397. * queue.
  398. */
  399. static size_t tcp_process_tx_queue ( struct tcp_connection *tcp, size_t max_len,
  400. struct io_buffer *dest, int remove ) {
  401. struct io_buffer *iobuf;
  402. struct io_buffer *tmp;
  403. size_t frag_len;
  404. size_t len = 0;
  405. list_for_each_entry_safe ( iobuf, tmp, &tcp->tx_queue, list ) {
  406. frag_len = iob_len ( iobuf );
  407. if ( frag_len > max_len )
  408. frag_len = max_len;
  409. if ( dest ) {
  410. memcpy ( iob_put ( dest, frag_len ), iobuf->data,
  411. frag_len );
  412. }
  413. if ( remove ) {
  414. iob_pull ( iobuf, frag_len );
  415. if ( ! iob_len ( iobuf ) ) {
  416. list_del ( &iobuf->list );
  417. free_iob ( iobuf );
  418. pending_put ( &tcp->pending_data );
  419. }
  420. }
  421. len += frag_len;
  422. max_len -= frag_len;
  423. }
  424. return len;
  425. }
  426. /**
  427. * Transmit any outstanding data
  428. *
  429. * @v tcp TCP connection
  430. *
  431. * Transmits any outstanding data on the connection.
  432. *
  433. * Note that even if an error is returned, the retransmission timer
  434. * will have been started if necessary, and so the stack will
  435. * eventually attempt to retransmit the failed packet.
  436. */
  437. static int tcp_xmit ( struct tcp_connection *tcp ) {
  438. struct io_buffer *iobuf;
  439. struct tcp_header *tcphdr;
  440. struct tcp_mss_option *mssopt;
  441. struct tcp_timestamp_padded_option *tsopt;
  442. void *payload;
  443. unsigned int flags;
  444. size_t len = 0;
  445. uint32_t seq_len;
  446. uint32_t app_win;
  447. uint32_t max_rcv_win;
  448. int rc;
  449. /* If retransmission timer is already running, do nothing */
  450. if ( timer_running ( &tcp->timer ) )
  451. return 0;
  452. /* Calculate both the actual (payload) and sequence space
  453. * lengths that we wish to transmit.
  454. */
  455. if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
  456. len = tcp_process_tx_queue ( tcp, tcp_xmit_win ( tcp ),
  457. NULL, 0 );
  458. }
  459. seq_len = len;
  460. flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
  461. if ( flags & ( TCP_SYN | TCP_FIN ) ) {
  462. /* SYN or FIN consume one byte, and we can never send both */
  463. assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
  464. seq_len++;
  465. }
  466. tcp->snd_sent = seq_len;
  467. /* If we have nothing to transmit, stop now */
  468. if ( ( seq_len == 0 ) && ! ( tcp->flags & TCP_ACK_PENDING ) )
  469. return 0;
  470. /* If we are transmitting anything that requires
  471. * acknowledgement (i.e. consumes sequence space), start the
  472. * retransmission timer. Do this before attempting to
  473. * allocate the I/O buffer, in case allocation itself fails.
  474. */
  475. if ( seq_len )
  476. start_timer ( &tcp->timer );
  477. /* Allocate I/O buffer */
  478. iobuf = alloc_iob ( len + TCP_MAX_HEADER_LEN );
  479. if ( ! iobuf ) {
  480. DBGC ( tcp, "TCP %p could not allocate iobuf for %08x..%08x "
  481. "%08x\n", tcp, tcp->snd_seq, ( tcp->snd_seq + seq_len ),
  482. tcp->rcv_ack );
  483. return -ENOMEM;
  484. }
  485. iob_reserve ( iobuf, TCP_MAX_HEADER_LEN );
  486. /* Fill data payload from transmit queue */
  487. tcp_process_tx_queue ( tcp, len, iobuf, 0 );
  488. /* Expand receive window if possible */
  489. max_rcv_win = ( ( freemem * 3 ) / 4 );
  490. if ( max_rcv_win > TCP_MAX_WINDOW_SIZE )
  491. max_rcv_win = TCP_MAX_WINDOW_SIZE;
  492. app_win = xfer_window ( &tcp->xfer );
  493. if ( max_rcv_win > app_win )
  494. max_rcv_win = app_win;
  495. max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
  496. if ( tcp->rcv_win < max_rcv_win )
  497. tcp->rcv_win = max_rcv_win;
  498. /* Fill up the TCP header */
  499. payload = iobuf->data;
  500. if ( flags & TCP_SYN ) {
  501. mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
  502. mssopt->kind = TCP_OPTION_MSS;
  503. mssopt->length = sizeof ( *mssopt );
  504. mssopt->mss = htons ( TCP_MSS );
  505. }
  506. if ( ( flags & TCP_SYN ) || ( tcp->flags & TCP_TS_ENABLED ) ) {
  507. tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
  508. memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
  509. tsopt->tsopt.kind = TCP_OPTION_TS;
  510. tsopt->tsopt.length = sizeof ( tsopt->tsopt );
  511. tsopt->tsopt.tsval = htonl ( currticks() );
  512. tsopt->tsopt.tsecr = htonl ( tcp->ts_recent );
  513. }
  514. if ( len != 0 )
  515. flags |= TCP_PSH;
  516. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  517. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  518. tcphdr->src = htons ( tcp->local_port );
  519. tcphdr->dest = tcp->peer.st_port;
  520. tcphdr->seq = htonl ( tcp->snd_seq );
  521. tcphdr->ack = htonl ( tcp->rcv_ack );
  522. tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
  523. tcphdr->flags = flags;
  524. tcphdr->win = htons ( tcp->rcv_win );
  525. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  526. /* Dump header */
  527. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4zd",
  528. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  529. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
  530. ntohl ( tcphdr->ack ), len );
  531. tcp_dump_flags ( tcp, tcphdr->flags );
  532. DBGC2 ( tcp, "\n" );
  533. /* Transmit packet */
  534. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
  535. &tcphdr->csum ) ) != 0 ) {
  536. DBGC ( tcp, "TCP %p could not transmit %08x..%08x %08x: %s\n",
  537. tcp, tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ),
  538. tcp->rcv_ack, strerror ( rc ) );
  539. return rc;
  540. }
  541. /* Clear ACK-pending flag */
  542. tcp->flags &= ~TCP_ACK_PENDING;
  543. return 0;
  544. }
  545. /**
  546. * Retransmission timer expired
  547. *
  548. * @v timer Retransmission timer
  549. * @v over Failure indicator
  550. */
  551. static void tcp_expired ( struct retry_timer *timer, int over ) {
  552. struct tcp_connection *tcp =
  553. container_of ( timer, struct tcp_connection, timer );
  554. DBGC ( tcp, "TCP %p timer %s in %s for %08x..%08x %08x\n", tcp,
  555. ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ),
  556. tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  557. assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
  558. ( tcp->tcp_state == TCP_SYN_RCVD ) ||
  559. ( tcp->tcp_state == TCP_ESTABLISHED ) ||
  560. ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
  561. ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
  562. ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
  563. if ( over ) {
  564. /* If we have finally timed out and given up,
  565. * terminate the connection
  566. */
  567. tcp->tcp_state = TCP_CLOSED;
  568. tcp_dump_state ( tcp );
  569. tcp_close ( tcp, -ETIMEDOUT );
  570. } else {
  571. /* Otherwise, retransmit the packet */
  572. tcp_xmit ( tcp );
  573. }
  574. }
  575. /**
  576. * Shutdown timer expired
  577. *
  578. * @v timer Shutdown timer
  579. * @v over Failure indicator
  580. */
  581. static void tcp_wait_expired ( struct retry_timer *timer, int over __unused ) {
  582. struct tcp_connection *tcp =
  583. container_of ( timer, struct tcp_connection, wait );
  584. assert ( tcp->tcp_state == TCP_TIME_WAIT );
  585. DBGC ( tcp, "TCP %p wait complete in %s for %08x..%08x %08x\n", tcp,
  586. tcp_state ( tcp->tcp_state ), tcp->snd_seq,
  587. ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
  588. tcp->tcp_state = TCP_CLOSED;
  589. tcp_dump_state ( tcp );
  590. tcp_close ( tcp, 0 );
  591. }
  592. /**
  593. * Send RST response to incoming packet
  594. *
  595. * @v in_tcphdr TCP header of incoming packet
  596. * @ret rc Return status code
  597. */
  598. static int tcp_xmit_reset ( struct tcp_connection *tcp,
  599. struct sockaddr_tcpip *st_dest,
  600. struct tcp_header *in_tcphdr ) {
  601. struct io_buffer *iobuf;
  602. struct tcp_header *tcphdr;
  603. int rc;
  604. /* Allocate space for dataless TX buffer */
  605. iobuf = alloc_iob ( TCP_MAX_HEADER_LEN );
  606. if ( ! iobuf ) {
  607. DBGC ( tcp, "TCP %p could not allocate iobuf for RST "
  608. "%08x..%08x %08x\n", tcp, ntohl ( in_tcphdr->ack ),
  609. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ) );
  610. return -ENOMEM;
  611. }
  612. iob_reserve ( iobuf, TCP_MAX_HEADER_LEN );
  613. /* Construct RST response */
  614. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  615. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  616. tcphdr->src = in_tcphdr->dest;
  617. tcphdr->dest = in_tcphdr->src;
  618. tcphdr->seq = in_tcphdr->ack;
  619. tcphdr->ack = in_tcphdr->seq;
  620. tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  621. tcphdr->flags = ( TCP_RST | TCP_ACK );
  622. tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
  623. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  624. /* Dump header */
  625. DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
  626. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  627. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
  628. ntohl ( tcphdr->ack ), 0 );
  629. tcp_dump_flags ( tcp, tcphdr->flags );
  630. DBGC2 ( tcp, "\n" );
  631. /* Transmit packet */
  632. if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
  633. NULL, &tcphdr->csum ) ) != 0 ) {
  634. DBGC ( tcp, "TCP %p could not transmit RST %08x..%08x %08x: "
  635. "%s\n", tcp, ntohl ( in_tcphdr->ack ),
  636. ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ),
  637. strerror ( rc ) );
  638. return rc;
  639. }
  640. return 0;
  641. }
  642. /***************************************************************************
  643. *
  644. * Receive data path
  645. *
  646. ***************************************************************************
  647. */
  648. /**
  649. * Identify TCP connection by local port number
  650. *
  651. * @v local_port Local port
  652. * @ret tcp TCP connection, or NULL
  653. */
  654. static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
  655. struct tcp_connection *tcp;
  656. list_for_each_entry ( tcp, &tcp_conns, list ) {
  657. if ( tcp->local_port == local_port )
  658. return tcp;
  659. }
  660. return NULL;
  661. }
  662. /**
  663. * Parse TCP received options
  664. *
  665. * @v tcp TCP connection
  666. * @v data Raw options data
  667. * @v len Raw options length
  668. * @v options Options structure to fill in
  669. */
  670. static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
  671. size_t len, struct tcp_options *options ) {
  672. const void *end = ( data + len );
  673. const struct tcp_option *option;
  674. unsigned int kind;
  675. memset ( options, 0, sizeof ( *options ) );
  676. while ( data < end ) {
  677. option = data;
  678. kind = option->kind;
  679. if ( kind == TCP_OPTION_END )
  680. return;
  681. if ( kind == TCP_OPTION_NOP ) {
  682. data++;
  683. continue;
  684. }
  685. switch ( kind ) {
  686. case TCP_OPTION_MSS:
  687. options->mssopt = data;
  688. break;
  689. case TCP_OPTION_TS:
  690. options->tsopt = data;
  691. break;
  692. default:
  693. DBGC ( tcp, "TCP %p received unknown option %d\n",
  694. tcp, kind );
  695. break;
  696. }
  697. data += option->length;
  698. }
  699. }
  700. /**
  701. * Consume received sequence space
  702. *
  703. * @v tcp TCP connection
  704. * @v seq_len Sequence space length to consume
  705. */
  706. static void tcp_rx_seq ( struct tcp_connection *tcp, uint32_t seq_len ) {
  707. /* Sanity check */
  708. assert ( seq_len > 0 );
  709. /* Update acknowledgement number */
  710. tcp->rcv_ack += seq_len;
  711. /* Update window */
  712. if ( tcp->rcv_win > seq_len ) {
  713. tcp->rcv_win -= seq_len;
  714. } else {
  715. tcp->rcv_win = 0;
  716. }
  717. /* Update timestamp */
  718. tcp->ts_recent = tcp->ts_val;
  719. /* Mark ACK as pending */
  720. tcp->flags |= TCP_ACK_PENDING;
  721. }
  722. /**
  723. * Handle TCP received SYN
  724. *
  725. * @v tcp TCP connection
  726. * @v seq SEQ value (in host-endian order)
  727. * @v options TCP options
  728. * @ret rc Return status code
  729. */
  730. static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
  731. struct tcp_options *options ) {
  732. /* Synchronise sequence numbers on first SYN */
  733. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  734. tcp->rcv_ack = seq;
  735. if ( options->tsopt )
  736. tcp->flags |= TCP_TS_ENABLED;
  737. }
  738. /* Ignore duplicate SYN */
  739. if ( seq != tcp->rcv_ack )
  740. return 0;
  741. /* Acknowledge SYN */
  742. tcp_rx_seq ( tcp, 1 );
  743. /* Mark SYN as received and start sending ACKs with each packet */
  744. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  745. TCP_STATE_RCVD ( TCP_SYN ) );
  746. return 0;
  747. }
  748. /**
  749. * Handle TCP received ACK
  750. *
  751. * @v tcp TCP connection
  752. * @v ack ACK value (in host-endian order)
  753. * @v win WIN value (in host-endian order)
  754. * @ret rc Return status code
  755. */
  756. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  757. uint32_t win ) {
  758. uint32_t ack_len = ( ack - tcp->snd_seq );
  759. size_t len;
  760. unsigned int acked_flags;
  761. /* Check for out-of-range or old duplicate ACKs */
  762. if ( ack_len > tcp->snd_sent ) {
  763. DBGC ( tcp, "TCP %p received ACK for %08x..%08x, "
  764. "sent only %08x..%08x\n", tcp, tcp->snd_seq,
  765. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  766. ( tcp->snd_seq + tcp->snd_sent ) );
  767. if ( TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) ) {
  768. /* Just ignore what might be old duplicate ACKs */
  769. return 0;
  770. } else {
  771. /* Send RST if an out-of-range ACK is received
  772. * on a not-yet-established connection, as per
  773. * RFC 793.
  774. */
  775. return -EINVAL;
  776. }
  777. }
  778. /* Ignore ACKs that don't actually acknowledge any new data.
  779. * (In particular, do not stop the retransmission timer; this
  780. * avoids creating a sorceror's apprentice syndrome when a
  781. * duplicate ACK is received and we still have data in our
  782. * transmit queue.)
  783. */
  784. if ( ack_len == 0 )
  785. return 0;
  786. /* Stop the retransmission timer */
  787. stop_timer ( &tcp->timer );
  788. /* Determine acknowledged flags and data length */
  789. len = ack_len;
  790. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  791. ( TCP_SYN | TCP_FIN ) );
  792. if ( acked_flags ) {
  793. len--;
  794. pending_put ( &tcp->pending_flags );
  795. }
  796. /* Update SEQ and sent counters, and window size */
  797. tcp->snd_seq = ack;
  798. tcp->snd_sent = 0;
  799. tcp->snd_win = win;
  800. /* Remove any acknowledged data from transmit queue */
  801. tcp_process_tx_queue ( tcp, len, NULL, 1 );
  802. /* Mark SYN/FIN as acknowledged if applicable. */
  803. if ( acked_flags )
  804. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  805. /* Start sending FIN if we've had all possible data ACKed */
  806. if ( list_empty ( &tcp->tx_queue ) &&
  807. ( tcp->flags & TCP_XFER_CLOSED ) &&
  808. ! ( tcp->tcp_state & TCP_STATE_SENT ( TCP_FIN ) ) ) {
  809. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  810. pending_get ( &tcp->pending_flags );
  811. }
  812. return 0;
  813. }
  814. /**
  815. * Handle TCP received data
  816. *
  817. * @v tcp TCP connection
  818. * @v seq SEQ value (in host-endian order)
  819. * @v iobuf I/O buffer
  820. * @ret rc Return status code
  821. *
  822. * This function takes ownership of the I/O buffer.
  823. */
  824. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  825. struct io_buffer *iobuf ) {
  826. uint32_t already_rcvd;
  827. uint32_t len;
  828. int rc;
  829. /* Ignore duplicate or out-of-order data */
  830. already_rcvd = ( tcp->rcv_ack - seq );
  831. len = iob_len ( iobuf );
  832. if ( already_rcvd >= len ) {
  833. free_iob ( iobuf );
  834. return 0;
  835. }
  836. iob_pull ( iobuf, already_rcvd );
  837. len -= already_rcvd;
  838. /* Acknowledge new data */
  839. tcp_rx_seq ( tcp, len );
  840. /* Deliver data to application */
  841. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
  842. DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
  843. tcp, seq, ( seq + len ), strerror ( rc ) );
  844. return rc;
  845. }
  846. return 0;
  847. }
  848. /**
  849. * Handle TCP received FIN
  850. *
  851. * @v tcp TCP connection
  852. * @v seq SEQ value (in host-endian order)
  853. * @ret rc Return status code
  854. */
  855. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  856. /* Ignore duplicate or out-of-order FIN */
  857. if ( seq != tcp->rcv_ack )
  858. return 0;
  859. /* Acknowledge FIN */
  860. tcp_rx_seq ( tcp, 1 );
  861. /* Mark FIN as received */
  862. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  863. /* Close connection */
  864. tcp_close ( tcp, 0 );
  865. return 0;
  866. }
  867. /**
  868. * Handle TCP received RST
  869. *
  870. * @v tcp TCP connection
  871. * @v seq SEQ value (in host-endian order)
  872. * @ret rc Return status code
  873. */
  874. static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  875. /* Accept RST only if it falls within the window. If we have
  876. * not yet received a SYN, then we have no window to test
  877. * against, so fall back to checking that our SYN has been
  878. * ACKed.
  879. */
  880. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  881. if ( ! tcp_in_window ( seq, tcp->rcv_ack, tcp->rcv_win ) )
  882. return 0;
  883. } else {
  884. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  885. return 0;
  886. }
  887. /* Abort connection */
  888. tcp->tcp_state = TCP_CLOSED;
  889. tcp_dump_state ( tcp );
  890. tcp_close ( tcp, -ECONNRESET );
  891. DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
  892. return -ECONNRESET;
  893. }
  894. /**
  895. * Enqueue received TCP packet
  896. *
  897. * @v tcp TCP connection
  898. * @v seq SEQ value (in host-endian order)
  899. * @v flags TCP flags
  900. * @v iobuf I/O buffer
  901. */
  902. static void tcp_rx_enqueue ( struct tcp_connection *tcp, uint32_t seq,
  903. uint8_t flags, struct io_buffer *iobuf ) {
  904. struct tcp_rx_queued_header *tcpqhdr;
  905. struct io_buffer *queued;
  906. size_t len;
  907. uint32_t seq_len;
  908. /* Calculate remaining flags and sequence length. Note that
  909. * SYN, if present, has already been processed by this point.
  910. */
  911. flags &= TCP_FIN;
  912. len = iob_len ( iobuf );
  913. seq_len = ( len + ( flags ? 1 : 0 ) );
  914. /* Discard immediately (to save memory) if:
  915. *
  916. * a) we have not yet received a SYN (and so have no defined
  917. * receive window), or
  918. * b) the packet lies entirely outside the receive window, or
  919. * c) there is no further content to process.
  920. */
  921. if ( ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) ||
  922. ( tcp_cmp ( seq, tcp->rcv_ack + tcp->rcv_win ) >= 0 ) ||
  923. ( tcp_cmp ( seq + seq_len, tcp->rcv_ack ) < 0 ) ||
  924. ( seq_len == 0 ) ) {
  925. free_iob ( iobuf );
  926. return;
  927. }
  928. /* Add internal header */
  929. tcpqhdr = iob_push ( iobuf, sizeof ( *tcpqhdr ) );
  930. tcpqhdr->seq = seq;
  931. tcpqhdr->flags = flags;
  932. /* Add to RX queue */
  933. list_for_each_entry ( queued, &tcp->rx_queue, list ) {
  934. tcpqhdr = queued->data;
  935. if ( tcp_cmp ( seq, tcpqhdr->seq ) < 0 )
  936. break;
  937. }
  938. list_add_tail ( &iobuf->list, &queued->list );
  939. }
  940. /**
  941. * Process receive queue
  942. *
  943. * @v tcp TCP connection
  944. */
  945. static void tcp_process_rx_queue ( struct tcp_connection *tcp ) {
  946. struct io_buffer *iobuf;
  947. struct tcp_rx_queued_header *tcpqhdr;
  948. uint32_t seq;
  949. unsigned int flags;
  950. size_t len;
  951. /* Process all applicable received buffers. Note that we
  952. * cannot use list_for_each_entry() to iterate over the RX
  953. * queue, since tcp_discard() may remove packets from the RX
  954. * queue while we are processing.
  955. */
  956. while ( ( iobuf = list_first_entry ( &tcp->rx_queue, struct io_buffer,
  957. list ) ) ) {
  958. /* Stop processing when we hit the first gap */
  959. tcpqhdr = iobuf->data;
  960. if ( tcp_cmp ( tcpqhdr->seq, tcp->rcv_ack ) > 0 )
  961. break;
  962. /* Strip internal header and remove from RX queue */
  963. list_del ( &iobuf->list );
  964. seq = tcpqhdr->seq;
  965. flags = tcpqhdr->flags;
  966. iob_pull ( iobuf, sizeof ( *tcpqhdr ) );
  967. len = iob_len ( iobuf );
  968. /* Handle new data, if any */
  969. tcp_rx_data ( tcp, seq, iob_disown ( iobuf ) );
  970. seq += len;
  971. /* Handle FIN, if present */
  972. if ( flags & TCP_FIN ) {
  973. tcp_rx_fin ( tcp, seq );
  974. seq++;
  975. }
  976. }
  977. }
  978. /**
  979. * Process received packet
  980. *
  981. * @v iobuf I/O buffer
  982. * @v st_src Partially-filled source address
  983. * @v st_dest Partially-filled destination address
  984. * @v pshdr_csum Pseudo-header checksum
  985. * @ret rc Return status code
  986. */
  987. static int tcp_rx ( struct io_buffer *iobuf,
  988. struct sockaddr_tcpip *st_src,
  989. struct sockaddr_tcpip *st_dest __unused,
  990. uint16_t pshdr_csum ) {
  991. struct tcp_header *tcphdr = iobuf->data;
  992. struct tcp_connection *tcp;
  993. struct tcp_options options;
  994. size_t hlen;
  995. uint16_t csum;
  996. uint32_t seq;
  997. uint32_t ack;
  998. uint32_t win;
  999. unsigned int flags;
  1000. size_t len;
  1001. uint32_t seq_len;
  1002. size_t old_xfer_window;
  1003. int rc;
  1004. /* Sanity check packet */
  1005. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  1006. DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
  1007. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  1008. rc = -EINVAL;
  1009. goto discard;
  1010. }
  1011. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  1012. if ( hlen < sizeof ( *tcphdr ) ) {
  1013. DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
  1014. hlen, sizeof ( *tcphdr ) );
  1015. rc = -EINVAL;
  1016. goto discard;
  1017. }
  1018. if ( hlen > iob_len ( iobuf ) ) {
  1019. DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
  1020. hlen, iob_len ( iobuf ) );
  1021. rc = -EINVAL;
  1022. goto discard;
  1023. }
  1024. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
  1025. iob_len ( iobuf ) );
  1026. if ( csum != 0 ) {
  1027. DBG ( "TCP checksum incorrect (is %04x including checksum "
  1028. "field, should be 0000)\n", csum );
  1029. rc = -EINVAL;
  1030. goto discard;
  1031. }
  1032. /* Parse parameters from header and strip header */
  1033. tcp = tcp_demux ( ntohs ( tcphdr->dest ) );
  1034. seq = ntohl ( tcphdr->seq );
  1035. ack = ntohl ( tcphdr->ack );
  1036. win = ntohs ( tcphdr->win );
  1037. flags = tcphdr->flags;
  1038. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  1039. ( hlen - sizeof ( *tcphdr ) ), &options );
  1040. if ( tcp && options.tsopt )
  1041. tcp->ts_val = ntohl ( options.tsopt->tsval );
  1042. iob_pull ( iobuf, hlen );
  1043. len = iob_len ( iobuf );
  1044. seq_len = ( len + ( ( flags & TCP_SYN ) ? 1 : 0 ) +
  1045. ( ( flags & TCP_FIN ) ? 1 : 0 ) );
  1046. /* Dump header */
  1047. DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08x %4zd",
  1048. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  1049. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  1050. ( ntohl ( tcphdr->seq ) + seq_len ), len );
  1051. tcp_dump_flags ( tcp, tcphdr->flags );
  1052. DBGC2 ( tcp, "\n" );
  1053. /* If no connection was found, send RST */
  1054. if ( ! tcp ) {
  1055. tcp_xmit_reset ( tcp, st_src, tcphdr );
  1056. rc = -ENOTCONN;
  1057. goto discard;
  1058. }
  1059. /* Record old data-transfer window */
  1060. old_xfer_window = tcp_xfer_window ( tcp );
  1061. /* Handle ACK, if present */
  1062. if ( flags & TCP_ACK ) {
  1063. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  1064. tcp_xmit_reset ( tcp, st_src, tcphdr );
  1065. goto discard;
  1066. }
  1067. }
  1068. /* Force an ACK if this packet is out of order */
  1069. if ( ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) &&
  1070. ( seq != tcp->rcv_ack ) ) {
  1071. tcp->flags |= TCP_ACK_PENDING;
  1072. }
  1073. /* Handle SYN, if present */
  1074. if ( flags & TCP_SYN ) {
  1075. tcp_rx_syn ( tcp, seq, &options );
  1076. seq++;
  1077. }
  1078. /* Handle RST, if present */
  1079. if ( flags & TCP_RST ) {
  1080. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  1081. goto discard;
  1082. }
  1083. /* Enqueue received data */
  1084. tcp_rx_enqueue ( tcp, seq, flags, iob_disown ( iobuf ) );
  1085. /* Process receive queue */
  1086. tcp_process_rx_queue ( tcp );
  1087. /* Dump out any state change as a result of the received packet */
  1088. tcp_dump_state ( tcp );
  1089. /* Send out any pending data */
  1090. tcp_xmit ( tcp );
  1091. /* If this packet was the last we expect to receive, set up
  1092. * timer to expire and cause the connection to be freed.
  1093. */
  1094. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  1095. stop_timer ( &tcp->wait );
  1096. start_timer_fixed ( &tcp->wait, ( 2 * TCP_MSL ) );
  1097. }
  1098. /* Notify application if window has changed */
  1099. if ( tcp_xfer_window ( tcp ) != old_xfer_window )
  1100. xfer_window_changed ( &tcp->xfer );
  1101. return 0;
  1102. discard:
  1103. /* Free received packet */
  1104. free_iob ( iobuf );
  1105. return rc;
  1106. }
  1107. /** TCP protocol */
  1108. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  1109. .name = "TCP",
  1110. .rx = tcp_rx,
  1111. .tcpip_proto = IP_TCP,
  1112. };
  1113. /**
  1114. * Discard some cached TCP data
  1115. *
  1116. * @ret discarded Number of cached items discarded
  1117. */
  1118. static unsigned int tcp_discard ( void ) {
  1119. struct tcp_connection *tcp;
  1120. struct io_buffer *iobuf;
  1121. unsigned int discarded = 0;
  1122. /* Try to drop one queued RX packet from each connection */
  1123. list_for_each_entry ( tcp, &tcp_conns, list ) {
  1124. list_for_each_entry_reverse ( iobuf, &tcp->rx_queue, list ) {
  1125. list_del ( &iobuf->list );
  1126. free_iob ( iobuf );
  1127. discarded++;
  1128. break;
  1129. }
  1130. }
  1131. return discarded;
  1132. }
  1133. /** TCP cache discarder */
  1134. struct cache_discarder tcp_cache_discarder __cache_discarder = {
  1135. .discard = tcp_discard,
  1136. };
  1137. /**
  1138. * Shut down all TCP connections
  1139. *
  1140. */
  1141. static void tcp_shutdown ( int booting __unused ) {
  1142. struct tcp_connection *tcp;
  1143. while ( ( tcp = list_first_entry ( &tcp_conns, struct tcp_connection,
  1144. list ) ) != NULL ) {
  1145. tcp->tcp_state = TCP_CLOSED;
  1146. tcp_dump_state ( tcp );
  1147. tcp_close ( tcp, -ECANCELED );
  1148. }
  1149. }
  1150. /** TCP shutdown function */
  1151. struct startup_fn tcp_startup_fn __startup_fn ( STARTUP_EARLY ) = {
  1152. .shutdown = tcp_shutdown,
  1153. };
  1154. /***************************************************************************
  1155. *
  1156. * Data transfer interface
  1157. *
  1158. ***************************************************************************
  1159. */
  1160. /**
  1161. * Close interface
  1162. *
  1163. * @v tcp TCP connection
  1164. * @v rc Reason for close
  1165. */
  1166. static void tcp_xfer_close ( struct tcp_connection *tcp, int rc ) {
  1167. /* Close data transfer interface */
  1168. tcp_close ( tcp, rc );
  1169. /* Transmit FIN, if possible */
  1170. tcp_xmit ( tcp );
  1171. }
  1172. /**
  1173. * Deliver datagram as I/O buffer
  1174. *
  1175. * @v tcp TCP connection
  1176. * @v iobuf Datagram I/O buffer
  1177. * @v meta Data transfer metadata
  1178. * @ret rc Return status code
  1179. */
  1180. static int tcp_xfer_deliver ( struct tcp_connection *tcp,
  1181. struct io_buffer *iobuf,
  1182. struct xfer_metadata *meta __unused ) {
  1183. /* Enqueue packet */
  1184. list_add_tail ( &iobuf->list, &tcp->tx_queue );
  1185. /* Each enqueued packet is a pending operation */
  1186. pending_get ( &tcp->pending_data );
  1187. /* Transmit data, if possible */
  1188. tcp_xmit ( tcp );
  1189. return 0;
  1190. }
  1191. /** TCP data transfer interface operations */
  1192. static struct interface_operation tcp_xfer_operations[] = {
  1193. INTF_OP ( xfer_deliver, struct tcp_connection *, tcp_xfer_deliver ),
  1194. INTF_OP ( xfer_window, struct tcp_connection *, tcp_xfer_window ),
  1195. INTF_OP ( intf_close, struct tcp_connection *, tcp_xfer_close ),
  1196. };
  1197. /** TCP data transfer interface descriptor */
  1198. static struct interface_descriptor tcp_xfer_desc =
  1199. INTF_DESC ( struct tcp_connection, xfer, tcp_xfer_operations );
  1200. /***************************************************************************
  1201. *
  1202. * Openers
  1203. *
  1204. ***************************************************************************
  1205. */
  1206. /** TCP socket opener */
  1207. struct socket_opener tcp_socket_opener __socket_opener = {
  1208. .semantics = TCP_SOCK_STREAM,
  1209. .family = AF_INET,
  1210. .open = tcp_open,
  1211. };
  1212. /** Linkage hack */
  1213. int tcp_sock_stream = TCP_SOCK_STREAM;
  1214. /**
  1215. * Open TCP URI
  1216. *
  1217. * @v xfer Data transfer interface
  1218. * @v uri URI
  1219. * @ret rc Return status code
  1220. */
  1221. static int tcp_open_uri ( struct interface *xfer, struct uri *uri ) {
  1222. struct sockaddr_tcpip peer;
  1223. /* Sanity check */
  1224. if ( ! uri->host )
  1225. return -EINVAL;
  1226. memset ( &peer, 0, sizeof ( peer ) );
  1227. peer.st_port = htons ( uri_port ( uri, 0 ) );
  1228. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  1229. ( struct sockaddr * ) &peer,
  1230. uri->host, NULL );
  1231. }
  1232. /** TCP URI opener */
  1233. struct uri_opener tcp_uri_opener __uri_opener = {
  1234. .scheme = "tcp",
  1235. .open = tcp_open_uri,
  1236. };