Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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, send RST */
  1083. if ( ! tcp ) {
  1084. tcp_xmit_reset ( tcp, st_src, tcphdr );
  1085. rc = -ENOTCONN;
  1086. goto discard;
  1087. }
  1088. /* Record old data-transfer window */
  1089. old_xfer_window = tcp_xfer_window ( tcp );
  1090. /* Handle ACK, if present */
  1091. if ( flags & TCP_ACK ) {
  1092. win = ( raw_win << tcp->snd_win_scale );
  1093. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  1094. tcp_xmit_reset ( tcp, st_src, tcphdr );
  1095. goto discard;
  1096. }
  1097. }
  1098. /* Force an ACK if this packet is out of order */
  1099. if ( ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) &&
  1100. ( seq != tcp->rcv_ack ) ) {
  1101. tcp->flags |= TCP_ACK_PENDING;
  1102. }
  1103. /* Handle SYN, if present */
  1104. if ( flags & TCP_SYN ) {
  1105. tcp_rx_syn ( tcp, seq, &options );
  1106. seq++;
  1107. }
  1108. /* Handle RST, if present */
  1109. if ( flags & TCP_RST ) {
  1110. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  1111. goto discard;
  1112. }
  1113. /* Enqueue received data */
  1114. tcp_rx_enqueue ( tcp, seq, flags, iob_disown ( iobuf ) );
  1115. /* Process receive queue */
  1116. tcp_process_rx_queue ( tcp );
  1117. /* Dump out any state change as a result of the received packet */
  1118. tcp_dump_state ( tcp );
  1119. /* Send out any pending data */
  1120. tcp_xmit ( tcp );
  1121. /* If this packet was the last we expect to receive, set up
  1122. * timer to expire and cause the connection to be freed.
  1123. */
  1124. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  1125. stop_timer ( &tcp->wait );
  1126. start_timer_fixed ( &tcp->wait, ( 2 * TCP_MSL ) );
  1127. }
  1128. /* Notify application if window has changed */
  1129. if ( tcp_xfer_window ( tcp ) != old_xfer_window )
  1130. xfer_window_changed ( &tcp->xfer );
  1131. return 0;
  1132. discard:
  1133. /* Free received packet */
  1134. free_iob ( iobuf );
  1135. return rc;
  1136. }
  1137. /** TCP protocol */
  1138. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  1139. .name = "TCP",
  1140. .rx = tcp_rx,
  1141. .tcpip_proto = IP_TCP,
  1142. };
  1143. /**
  1144. * Discard some cached TCP data
  1145. *
  1146. * @ret discarded Number of cached items discarded
  1147. */
  1148. static unsigned int tcp_discard ( void ) {
  1149. struct tcp_connection *tcp;
  1150. struct io_buffer *iobuf;
  1151. struct tcp_rx_queued_header *tcpqhdr;
  1152. uint32_t max_win;
  1153. unsigned int discarded = 0;
  1154. /* Try to drop one queued RX packet from each connection */
  1155. list_for_each_entry ( tcp, &tcp_conns, list ) {
  1156. list_for_each_entry_reverse ( iobuf, &tcp->rx_queue, list ) {
  1157. /* Limit window to prevent future discards */
  1158. tcpqhdr = iobuf->data;
  1159. max_win = ( tcpqhdr->seq - tcp->rcv_ack );
  1160. if ( max_win < tcp->max_rcv_win ) {
  1161. DBGC ( tcp, "TCP %p reducing maximum window "
  1162. "from %d to %d\n",
  1163. tcp, tcp->max_rcv_win, max_win );
  1164. tcp->max_rcv_win = max_win;
  1165. }
  1166. /* Remove packet from queue */
  1167. list_del ( &iobuf->list );
  1168. free_iob ( iobuf );
  1169. /* Report discard */
  1170. discarded++;
  1171. break;
  1172. }
  1173. }
  1174. return discarded;
  1175. }
  1176. /** TCP cache discarder */
  1177. struct cache_discarder tcp_discarder __cache_discarder ( CACHE_NORMAL ) = {
  1178. .discard = tcp_discard,
  1179. };
  1180. /**
  1181. * Shut down all TCP connections
  1182. *
  1183. */
  1184. static void tcp_shutdown ( int booting __unused ) {
  1185. struct tcp_connection *tcp;
  1186. while ( ( tcp = list_first_entry ( &tcp_conns, struct tcp_connection,
  1187. list ) ) != NULL ) {
  1188. tcp->tcp_state = TCP_CLOSED;
  1189. tcp_dump_state ( tcp );
  1190. tcp_close ( tcp, -ECANCELED );
  1191. }
  1192. }
  1193. /** TCP shutdown function */
  1194. struct startup_fn tcp_startup_fn __startup_fn ( STARTUP_EARLY ) = {
  1195. .shutdown = tcp_shutdown,
  1196. };
  1197. /***************************************************************************
  1198. *
  1199. * Data transfer interface
  1200. *
  1201. ***************************************************************************
  1202. */
  1203. /**
  1204. * Close interface
  1205. *
  1206. * @v tcp TCP connection
  1207. * @v rc Reason for close
  1208. */
  1209. static void tcp_xfer_close ( struct tcp_connection *tcp, int rc ) {
  1210. /* Close data transfer interface */
  1211. tcp_close ( tcp, rc );
  1212. /* Transmit FIN, if possible */
  1213. tcp_xmit ( tcp );
  1214. }
  1215. /**
  1216. * Deliver datagram as I/O buffer
  1217. *
  1218. * @v tcp TCP connection
  1219. * @v iobuf Datagram I/O buffer
  1220. * @v meta Data transfer metadata
  1221. * @ret rc Return status code
  1222. */
  1223. static int tcp_xfer_deliver ( struct tcp_connection *tcp,
  1224. struct io_buffer *iobuf,
  1225. struct xfer_metadata *meta __unused ) {
  1226. /* Enqueue packet */
  1227. list_add_tail ( &iobuf->list, &tcp->tx_queue );
  1228. /* Each enqueued packet is a pending operation */
  1229. pending_get ( &tcp->pending_data );
  1230. /* Transmit data, if possible */
  1231. tcp_xmit ( tcp );
  1232. return 0;
  1233. }
  1234. /** TCP data transfer interface operations */
  1235. static struct interface_operation tcp_xfer_operations[] = {
  1236. INTF_OP ( xfer_deliver, struct tcp_connection *, tcp_xfer_deliver ),
  1237. INTF_OP ( xfer_window, struct tcp_connection *, tcp_xfer_window ),
  1238. INTF_OP ( intf_close, struct tcp_connection *, tcp_xfer_close ),
  1239. };
  1240. /** TCP data transfer interface descriptor */
  1241. static struct interface_descriptor tcp_xfer_desc =
  1242. INTF_DESC ( struct tcp_connection, xfer, tcp_xfer_operations );
  1243. /***************************************************************************
  1244. *
  1245. * Openers
  1246. *
  1247. ***************************************************************************
  1248. */
  1249. /** TCP socket opener */
  1250. struct socket_opener tcp_socket_opener __socket_opener = {
  1251. .semantics = TCP_SOCK_STREAM,
  1252. .family = AF_INET,
  1253. .open = tcp_open,
  1254. };
  1255. /** Linkage hack */
  1256. int tcp_sock_stream = TCP_SOCK_STREAM;
  1257. /**
  1258. * Open TCP URI
  1259. *
  1260. * @v xfer Data transfer interface
  1261. * @v uri URI
  1262. * @ret rc Return status code
  1263. */
  1264. static int tcp_open_uri ( struct interface *xfer, struct uri *uri ) {
  1265. struct sockaddr_tcpip peer;
  1266. /* Sanity check */
  1267. if ( ! uri->host )
  1268. return -EINVAL;
  1269. memset ( &peer, 0, sizeof ( peer ) );
  1270. peer.st_port = htons ( uri_port ( uri, 0 ) );
  1271. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  1272. ( struct sockaddr * ) &peer,
  1273. uri->host, NULL );
  1274. }
  1275. /** TCP URI opener */
  1276. struct uri_opener tcp_uri_opener __uri_opener = {
  1277. .scheme = "tcp",
  1278. .open = tcp_open_uri,
  1279. };