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 37KB

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