Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

tcp.c 37KB

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