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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  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 <timer.h>
  8. #include <gpxe/iobuf.h>
  9. #include <gpxe/malloc.h>
  10. #include <gpxe/retry.h>
  11. #include <gpxe/refcnt.h>
  12. #include <gpxe/xfer.h>
  13. #include <gpxe/open.h>
  14. #include <gpxe/uri.h>
  15. #include <gpxe/tcpip.h>
  16. #include <gpxe/tcp.h>
  17. /** @file
  18. *
  19. * TCP protocol
  20. *
  21. */
  22. /** A TCP connection */
  23. struct tcp_connection {
  24. /** Reference counter */
  25. struct refcnt refcnt;
  26. /** List of TCP connections */
  27. struct list_head list;
  28. /** Data transfer interface */
  29. struct xfer_interface xfer;
  30. /** Data transfer interface closed flag */
  31. int xfer_closed;
  32. /** Remote socket address */
  33. struct sockaddr_tcpip peer;
  34. /** Local port, in network byte order */
  35. unsigned int local_port;
  36. /** Current TCP state */
  37. unsigned int tcp_state;
  38. /** Previous TCP state
  39. *
  40. * Maintained only for debug messages
  41. */
  42. unsigned int prev_tcp_state;
  43. /** Current sequence number
  44. *
  45. * Equivalent to SND.UNA in RFC 793 terminology.
  46. */
  47. uint32_t snd_seq;
  48. /** Unacknowledged sequence count
  49. *
  50. * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
  51. */
  52. uint32_t snd_sent;
  53. /** Send window
  54. *
  55. * Equivalent to SND.WND in RFC 793 terminology
  56. */
  57. uint32_t snd_win;
  58. /** Current acknowledgement number
  59. *
  60. * Equivalent to RCV.NXT in RFC 793 terminology.
  61. */
  62. uint32_t rcv_ack;
  63. /** Most recent received timestamp
  64. *
  65. * Equivalent to TS.Recent in RFC 1323 terminology.
  66. */
  67. uint32_t ts_recent;
  68. /** Timestamps enabled */
  69. int timestamps;
  70. /** Transmit queue */
  71. struct list_head queue;
  72. /** Retransmission timer */
  73. struct retry_timer timer;
  74. };
  75. /**
  76. * List of registered TCP connections
  77. */
  78. static LIST_HEAD ( tcp_conns );
  79. /* Forward declarations */
  80. static struct xfer_interface_operations tcp_xfer_operations;
  81. static void tcp_expired ( struct retry_timer *timer, int over );
  82. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  83. uint32_t win );
  84. /**
  85. * Name TCP state
  86. *
  87. * @v state TCP state
  88. * @ret name Name of TCP state
  89. */
  90. static inline __attribute__ (( always_inline )) const char *
  91. tcp_state ( int state ) {
  92. switch ( state ) {
  93. case TCP_CLOSED: return "CLOSED";
  94. case TCP_LISTEN: return "LISTEN";
  95. case TCP_SYN_SENT: return "SYN_SENT";
  96. case TCP_SYN_RCVD: return "SYN_RCVD";
  97. case TCP_ESTABLISHED: return "ESTABLISHED";
  98. case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
  99. case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
  100. case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
  101. case TCP_TIME_WAIT: return "TIME_WAIT";
  102. case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
  103. default: return "INVALID";
  104. }
  105. }
  106. /**
  107. * Dump TCP state transition
  108. *
  109. * @v tcp TCP connection
  110. */
  111. static inline __attribute__ (( always_inline )) void
  112. tcp_dump_state ( struct tcp_connection *tcp ) {
  113. if ( tcp->tcp_state != tcp->prev_tcp_state ) {
  114. DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
  115. tcp_state ( tcp->prev_tcp_state ),
  116. tcp_state ( tcp->tcp_state ) );
  117. }
  118. tcp->prev_tcp_state = tcp->tcp_state;
  119. }
  120. /**
  121. * Dump TCP flags
  122. *
  123. * @v flags TCP flags
  124. */
  125. static inline __attribute__ (( always_inline )) void
  126. tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
  127. if ( flags & TCP_RST )
  128. DBGC ( tcp, " RST" );
  129. if ( flags & TCP_SYN )
  130. DBGC ( tcp, " SYN" );
  131. if ( flags & TCP_PSH )
  132. DBGC ( tcp, " PSH" );
  133. if ( flags & TCP_FIN )
  134. DBGC ( tcp, " FIN" );
  135. if ( flags & TCP_ACK )
  136. DBGC ( tcp, " ACK" );
  137. }
  138. /***************************************************************************
  139. *
  140. * Open and close
  141. *
  142. ***************************************************************************
  143. */
  144. /**
  145. * Bind TCP connection to local port
  146. *
  147. * @v tcp TCP connection
  148. * @v port Local port number, in network-endian order
  149. * @ret rc Return status code
  150. *
  151. * If the port is 0, the connection is assigned an available port
  152. * between 1024 and 65535.
  153. */
  154. static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
  155. struct tcp_connection *existing;
  156. static uint16_t try_port = 1023;
  157. /* If no port specified, find the first available port */
  158. if ( ! port ) {
  159. while ( try_port ) {
  160. try_port++;
  161. if ( try_port < 1024 )
  162. continue;
  163. if ( tcp_bind ( tcp, htons ( try_port ) ) == 0 )
  164. return 0;
  165. }
  166. DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
  167. return -EADDRINUSE;
  168. }
  169. /* Attempt bind to local port */
  170. list_for_each_entry ( existing, &tcp_conns, list ) {
  171. if ( existing->local_port == port ) {
  172. DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
  173. tcp, ntohs ( port ) );
  174. return -EADDRINUSE;
  175. }
  176. }
  177. tcp->local_port = port;
  178. DBGC ( tcp, "TCP %p bound to port %d\n", tcp, ntohs ( port ) );
  179. return 0;
  180. }
  181. /**
  182. * Open a TCP connection
  183. *
  184. * @v xfer Data transfer interface
  185. * @v peer Peer socket address
  186. * @v local Local socket address, or NULL
  187. * @ret rc Return status code
  188. */
  189. static int tcp_open ( struct xfer_interface *xfer, struct sockaddr *peer,
  190. struct sockaddr *local ) {
  191. struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
  192. struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
  193. struct tcp_connection *tcp;
  194. unsigned int bind_port;
  195. int rc;
  196. /* Allocate and initialise structure */
  197. tcp = zalloc ( sizeof ( *tcp ) );
  198. if ( ! tcp )
  199. return -ENOMEM;
  200. DBGC ( tcp, "TCP %p allocated\n", tcp );
  201. xfer_init ( &tcp->xfer, &tcp_xfer_operations, &tcp->refcnt );
  202. tcp->prev_tcp_state = TCP_CLOSED;
  203. tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
  204. tcp_dump_state ( tcp );
  205. tcp->snd_seq = random();
  206. INIT_LIST_HEAD ( &tcp->queue );
  207. tcp->timer.expired = tcp_expired;
  208. memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
  209. /* Bind to local port */
  210. bind_port = ( st_local ? st_local->st_port : 0 );
  211. if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
  212. goto err;
  213. /* Start timer to initiate SYN */
  214. start_timer ( &tcp->timer );
  215. /* Attach parent interface, transfer reference to connection
  216. * list and return
  217. */
  218. xfer_plug_plug ( &tcp->xfer, xfer );
  219. list_add ( &tcp->list, &tcp_conns );
  220. return 0;
  221. err:
  222. ref_put ( &tcp->refcnt );
  223. return rc;
  224. }
  225. /**
  226. * Close TCP connection
  227. *
  228. * @v tcp TCP connection
  229. * @v rc Reason for close
  230. *
  231. * Closes the data transfer interface. If the TCP state machine is in
  232. * a suitable state, the connection will be deleted.
  233. */
  234. static void tcp_close ( struct tcp_connection *tcp, int rc ) {
  235. struct io_buffer *iobuf;
  236. struct io_buffer *tmp;
  237. /* Close data transfer interface */
  238. xfer_nullify ( &tcp->xfer );
  239. xfer_close ( &tcp->xfer, rc );
  240. tcp->xfer_closed = 1;
  241. /* If we are in CLOSED, or have otherwise not yet received a
  242. * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
  243. * connection.
  244. */
  245. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  246. /* Transition to CLOSED for the sake of debugging messages */
  247. tcp->tcp_state = TCP_CLOSED;
  248. tcp_dump_state ( tcp );
  249. /* Free any unsent I/O buffers */
  250. list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
  251. list_del ( &iobuf->list );
  252. free_iob ( iobuf );
  253. }
  254. /* Remove from list and drop reference */
  255. stop_timer ( &tcp->timer );
  256. list_del ( &tcp->list );
  257. ref_put ( &tcp->refcnt );
  258. DBGC ( tcp, "TCP %p connection deleted\n", tcp );
  259. return;
  260. }
  261. /* If we have not had our SYN acknowledged (i.e. we are in
  262. * SYN_RCVD), pretend that it has been acknowledged so that we
  263. * can send a FIN without breaking things.
  264. */
  265. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  266. tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
  267. /* If we have no data remaining to send, start sending FIN */
  268. if ( list_empty ( &tcp->queue ) ) {
  269. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  270. tcp_dump_state ( tcp );
  271. }
  272. }
  273. /***************************************************************************
  274. *
  275. * Transmit data path
  276. *
  277. ***************************************************************************
  278. */
  279. /**
  280. * Calculate transmission window
  281. *
  282. * @v tcp TCP connection
  283. * @ret len Maximum length that can be sent in a single packet
  284. */
  285. static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
  286. size_t len;
  287. /* Not ready if we're not in a suitable connection state */
  288. if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
  289. return 0;
  290. /* Length is the minimum of the receiver's window and the path MTU */
  291. len = tcp->snd_win;
  292. if ( len > TCP_PATH_MTU )
  293. len = TCP_PATH_MTU;
  294. return len;
  295. }
  296. /**
  297. * Process TCP transmit queue
  298. *
  299. * @v tcp TCP connection
  300. * @v max_len Maximum length to process
  301. * @v dest I/O buffer to fill with data, or NULL
  302. * @v remove Remove data from queue
  303. * @ret len Length of data processed
  304. *
  305. * This processes at most @c max_len bytes from the TCP connection's
  306. * transmit queue. Data will be copied into the @c dest I/O buffer
  307. * (if provided) and, if @c remove is true, removed from the transmit
  308. * queue.
  309. */
  310. static size_t tcp_process_queue ( struct tcp_connection *tcp, size_t max_len,
  311. struct io_buffer *dest, int remove ) {
  312. struct io_buffer *iobuf;
  313. struct io_buffer *tmp;
  314. size_t frag_len;
  315. size_t len = 0;
  316. list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
  317. frag_len = iob_len ( iobuf );
  318. if ( frag_len > max_len )
  319. frag_len = max_len;
  320. if ( dest ) {
  321. memcpy ( iob_put ( dest, frag_len ), iobuf->data,
  322. frag_len );
  323. }
  324. if ( remove ) {
  325. iob_pull ( iobuf, frag_len );
  326. if ( ! iob_len ( iobuf ) ) {
  327. list_del ( &iobuf->list );
  328. free_iob ( iobuf );
  329. }
  330. }
  331. len += frag_len;
  332. max_len -= frag_len;
  333. }
  334. return len;
  335. }
  336. /**
  337. * Transmit any outstanding data
  338. *
  339. * @v tcp TCP connection
  340. * @v force_send Force sending of packet
  341. *
  342. * Transmits any outstanding data on the connection.
  343. *
  344. * Note that even if an error is returned, the retransmission timer
  345. * will have been started if necessary, and so the stack will
  346. * eventually attempt to retransmit the failed packet.
  347. */
  348. static int tcp_xmit ( struct tcp_connection *tcp, int force_send ) {
  349. struct io_buffer *iobuf;
  350. struct tcp_header *tcphdr;
  351. struct tcp_mss_option *mssopt;
  352. struct tcp_timestamp_padded_option *tsopt;
  353. void *payload;
  354. unsigned int flags;
  355. size_t len = 0;
  356. size_t seq_len;
  357. size_t app_win;
  358. size_t rcv_win;
  359. int rc;
  360. /* If retransmission timer is already running, do nothing */
  361. if ( timer_running ( &tcp->timer ) )
  362. return 0;
  363. /* Calculate both the actual (payload) and sequence space
  364. * lengths that we wish to transmit.
  365. */
  366. if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
  367. len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
  368. NULL, 0 );
  369. }
  370. seq_len = len;
  371. flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
  372. if ( flags & ( TCP_SYN | TCP_FIN ) ) {
  373. /* SYN or FIN consume one byte, and we can never send both */
  374. assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
  375. seq_len++;
  376. }
  377. tcp->snd_sent = seq_len;
  378. /* If we have nothing to transmit, stop now */
  379. if ( ( seq_len == 0 ) && ! force_send )
  380. return 0;
  381. /* If we are transmitting anything that requires
  382. * acknowledgement (i.e. consumes sequence space), start the
  383. * retransmission timer. Do this before attempting to
  384. * allocate the I/O buffer, in case allocation itself fails.
  385. */
  386. if ( seq_len )
  387. start_timer ( &tcp->timer );
  388. /* Allocate I/O buffer */
  389. iobuf = alloc_iob ( len + MAX_HDR_LEN );
  390. if ( ! iobuf ) {
  391. DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
  392. return -ENOMEM;
  393. }
  394. iob_reserve ( iobuf, MAX_HDR_LEN );
  395. /* Fill data payload from transmit queue */
  396. tcp_process_queue ( tcp, len, iobuf, 0 );
  397. /* Estimate window size */
  398. rcv_win = ( ( freemem * 3 ) / 4 );
  399. if ( rcv_win > TCP_MAX_WINDOW_SIZE )
  400. rcv_win = TCP_MAX_WINDOW_SIZE;
  401. app_win = xfer_window ( &tcp->xfer );
  402. if ( rcv_win > app_win )
  403. rcv_win = app_win;
  404. rcv_win &= ~0x03; /* Keep everything dword-aligned */
  405. /* Fill up the TCP header */
  406. payload = iobuf->data;
  407. if ( flags & TCP_SYN ) {
  408. mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
  409. mssopt->kind = TCP_OPTION_MSS;
  410. mssopt->length = sizeof ( *mssopt );
  411. mssopt->mss = htons ( TCP_MSS );
  412. }
  413. if ( ( flags & TCP_SYN ) || tcp->timestamps ) {
  414. tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
  415. memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
  416. tsopt->tsopt.kind = TCP_OPTION_TS;
  417. tsopt->tsopt.length = sizeof ( tsopt->tsopt );
  418. tsopt->tsopt.tsval = ntohl ( currticks() );
  419. tsopt->tsopt.tsecr = ntohl ( tcp->ts_recent );
  420. }
  421. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  422. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  423. tcphdr->src = tcp->local_port;
  424. tcphdr->dest = tcp->peer.st_port;
  425. tcphdr->seq = htonl ( tcp->snd_seq );
  426. tcphdr->ack = htonl ( tcp->rcv_ack );
  427. tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
  428. tcphdr->flags = flags;
  429. tcphdr->win = htons ( rcv_win );
  430. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  431. /* Dump header */
  432. DBGC ( tcp, "TCP %p TX %d->%d %08lx..%08lx %08lx %4zd",
  433. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  434. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
  435. ntohl ( tcphdr->ack ), len );
  436. tcp_dump_flags ( tcp, tcphdr->flags );
  437. DBGC ( tcp, "\n" );
  438. /* Transmit packet */
  439. rc = tcpip_tx ( iobuf, &tcp_protocol, &tcp->peer, NULL, &tcphdr->csum );
  440. /* If we got -ENETUNREACH, kill the connection immediately
  441. * because there is no point retrying. This isn't strictly
  442. * necessary (since we will eventually time out anyway), but
  443. * it avoids irritating needless delays. Don't do this for
  444. * RST packets transmitted on connection abort, to avoid a
  445. * potential infinite loop.
  446. */
  447. if ( ( ! ( tcp->tcp_state & TCP_STATE_SENT ( TCP_RST ) ) ) &&
  448. ( rc == -ENETUNREACH ) ) {
  449. DBGC ( tcp, "TCP %p aborting after TX failed: %s\n",
  450. tcp, strerror ( rc ) );
  451. tcp->tcp_state = TCP_CLOSED;
  452. tcp_dump_state ( tcp );
  453. tcp_close ( tcp, rc );
  454. }
  455. return rc;
  456. }
  457. /**
  458. * Retransmission timer expired
  459. *
  460. * @v timer Retry timer
  461. * @v over Failure indicator
  462. */
  463. static void tcp_expired ( struct retry_timer *timer, int over ) {
  464. struct tcp_connection *tcp =
  465. container_of ( timer, struct tcp_connection, timer );
  466. int graceful_close = TCP_CLOSED_GRACEFULLY ( tcp->tcp_state );
  467. DBGC ( tcp, "TCP %p timer %s in %s\n", tcp,
  468. ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ) );
  469. assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
  470. ( tcp->tcp_state == TCP_SYN_RCVD ) ||
  471. ( tcp->tcp_state == TCP_ESTABLISHED ) ||
  472. ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
  473. ( tcp->tcp_state == TCP_TIME_WAIT ) ||
  474. ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
  475. ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
  476. if ( over || graceful_close ) {
  477. /* If we have finally timed out and given up, or if
  478. * this is the result of a graceful close, terminate
  479. * the connection
  480. */
  481. tcp->tcp_state = TCP_CLOSED;
  482. tcp_dump_state ( tcp );
  483. tcp_close ( tcp, -ETIMEDOUT );
  484. } else {
  485. /* Otherwise, retransmit the packet */
  486. tcp_xmit ( tcp, 0 );
  487. }
  488. }
  489. /**
  490. * Send RST response to incoming packet
  491. *
  492. * @v in_tcphdr TCP header of incoming packet
  493. * @ret rc Return status code
  494. */
  495. static int tcp_xmit_reset ( struct tcp_connection *tcp,
  496. struct sockaddr_tcpip *st_dest,
  497. struct tcp_header *in_tcphdr ) {
  498. struct io_buffer *iobuf;
  499. struct tcp_header *tcphdr;
  500. /* Allocate space for dataless TX buffer */
  501. iobuf = alloc_iob ( MAX_HDR_LEN );
  502. if ( ! iobuf ) {
  503. DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
  504. return -ENOMEM;
  505. }
  506. iob_reserve ( iobuf, MAX_HDR_LEN );
  507. /* Construct RST response */
  508. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  509. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  510. tcphdr->src = in_tcphdr->dest;
  511. tcphdr->dest = in_tcphdr->src;
  512. tcphdr->seq = in_tcphdr->ack;
  513. tcphdr->ack = in_tcphdr->seq;
  514. tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  515. tcphdr->flags = ( TCP_RST | TCP_ACK );
  516. tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
  517. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  518. /* Dump header */
  519. DBGC ( tcp, "TCP %p TX %d->%d %08lx..%08lx %08lx %4zd",
  520. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  521. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
  522. ntohl ( tcphdr->ack ), 0 );
  523. tcp_dump_flags ( tcp, tcphdr->flags );
  524. DBGC ( tcp, "\n" );
  525. /* Transmit packet */
  526. return tcpip_tx ( iobuf, &tcp_protocol, st_dest,
  527. NULL, &tcphdr->csum );
  528. }
  529. /***************************************************************************
  530. *
  531. * Receive data path
  532. *
  533. ***************************************************************************
  534. */
  535. /**
  536. * Identify TCP connection by local port number
  537. *
  538. * @v local_port Local port (in network-endian order)
  539. * @ret tcp TCP connection, or NULL
  540. */
  541. static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
  542. struct tcp_connection *tcp;
  543. list_for_each_entry ( tcp, &tcp_conns, list ) {
  544. if ( tcp->local_port == local_port )
  545. return tcp;
  546. }
  547. return NULL;
  548. }
  549. /**
  550. * Parse TCP received options
  551. *
  552. * @v tcp TCP connection
  553. * @v data Raw options data
  554. * @v len Raw options length
  555. * @v options Options structure to fill in
  556. */
  557. static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
  558. size_t len, struct tcp_options *options ) {
  559. const void *end = ( data + len );
  560. const struct tcp_option *option;
  561. unsigned int kind;
  562. memset ( options, 0, sizeof ( *options ) );
  563. while ( data < end ) {
  564. option = data;
  565. kind = option->kind;
  566. if ( kind == TCP_OPTION_END )
  567. return;
  568. if ( kind == TCP_OPTION_NOP ) {
  569. data++;
  570. continue;
  571. }
  572. switch ( kind ) {
  573. case TCP_OPTION_MSS:
  574. options->mssopt = data;
  575. break;
  576. case TCP_OPTION_TS:
  577. options->tsopt = data;
  578. break;
  579. default:
  580. DBGC ( tcp, "TCP %p received unknown option %d\n",
  581. tcp, kind );
  582. break;
  583. }
  584. data += option->length;
  585. }
  586. }
  587. /**
  588. * Handle TCP received SYN
  589. *
  590. * @v tcp TCP connection
  591. * @v seq SEQ value (in host-endian order)
  592. * @v options TCP options
  593. * @ret rc Return status code
  594. */
  595. static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
  596. struct tcp_options *options ) {
  597. /* Synchronise sequence numbers on first SYN */
  598. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  599. tcp->rcv_ack = seq;
  600. if ( options->tsopt )
  601. tcp->timestamps = 1;
  602. }
  603. /* Ignore duplicate SYN */
  604. if ( ( tcp->rcv_ack - seq ) > 0 )
  605. return 0;
  606. /* Mark SYN as received and start sending ACKs with each packet */
  607. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  608. TCP_STATE_RCVD ( TCP_SYN ) );
  609. /* Acknowledge SYN */
  610. tcp->rcv_ack++;
  611. return 0;
  612. }
  613. /**
  614. * Handle TCP received ACK
  615. *
  616. * @v tcp TCP connection
  617. * @v ack ACK value (in host-endian order)
  618. * @v win WIN value (in host-endian order)
  619. * @ret rc Return status code
  620. */
  621. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  622. uint32_t win ) {
  623. size_t ack_len = ( ack - tcp->snd_seq );
  624. size_t len;
  625. unsigned int acked_flags;
  626. /* Ignore duplicate or out-of-range ACK */
  627. if ( ack_len > tcp->snd_sent ) {
  628. DBGC ( tcp, "TCP %p received ACK for [%08lx,%08lx), "
  629. "sent only [%08lx,%08lx)\n", tcp, tcp->snd_seq,
  630. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  631. ( tcp->snd_seq + tcp->snd_sent ) );
  632. return -EINVAL;
  633. }
  634. /* Acknowledge any flags being sent */
  635. len = ack_len;
  636. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  637. ( TCP_SYN | TCP_FIN ) );
  638. if ( acked_flags )
  639. len--;
  640. /* Update SEQ and sent counters, and window size */
  641. tcp->snd_seq = ack;
  642. tcp->snd_sent = 0;
  643. tcp->snd_win = win;
  644. /* Stop the retransmission timer */
  645. stop_timer ( &tcp->timer );
  646. /* Remove any acknowledged data from transmit queue */
  647. tcp_process_queue ( tcp, len, NULL, 1 );
  648. /* Mark SYN/FIN as acknowledged if applicable. */
  649. if ( acked_flags )
  650. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  651. /* Start sending FIN if we've had all possible data ACKed */
  652. if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
  653. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  654. return 0;
  655. }
  656. /**
  657. * Handle TCP received data
  658. *
  659. * @v tcp TCP connection
  660. * @v seq SEQ value (in host-endian order)
  661. * @v iobuf I/O buffer
  662. * @ret rc Return status code
  663. *
  664. * This function takes ownership of the I/O buffer.
  665. */
  666. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  667. struct io_buffer *iobuf ) {
  668. size_t already_rcvd;
  669. size_t len;
  670. int rc;
  671. /* Ignore duplicate or out-of-order data */
  672. already_rcvd = ( tcp->rcv_ack - seq );
  673. len = iob_len ( iobuf );
  674. if ( already_rcvd >= len ) {
  675. free_iob ( iobuf );
  676. return 0;
  677. }
  678. iob_pull ( iobuf, already_rcvd );
  679. len -= already_rcvd;
  680. /* Deliver data to application */
  681. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 )
  682. return rc;
  683. /* Acknowledge new data */
  684. tcp->rcv_ack += len;
  685. return 0;
  686. }
  687. /**
  688. * Handle TCP received FIN
  689. *
  690. * @v tcp TCP connection
  691. * @v seq SEQ value (in host-endian order)
  692. * @ret rc Return status code
  693. */
  694. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  695. /* Ignore duplicate or out-of-order FIN */
  696. if ( ( tcp->rcv_ack - seq ) > 0 )
  697. return 0;
  698. /* Mark FIN as received and acknowledge it */
  699. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  700. tcp->rcv_ack++;
  701. /* Close connection */
  702. tcp_close ( tcp, 0 );
  703. return 0;
  704. }
  705. /**
  706. * Handle TCP received RST
  707. *
  708. * @v tcp TCP connection
  709. * @v seq SEQ value (in host-endian order)
  710. * @ret rc Return status code
  711. */
  712. static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  713. /* Accept RST only if it falls within the window. If we have
  714. * not yet received a SYN, then we have no window to test
  715. * against, so fall back to checking that our SYN has been
  716. * ACKed.
  717. */
  718. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  719. if ( ( tcp->rcv_ack - seq ) > 0 )
  720. return 0;
  721. } else {
  722. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  723. return 0;
  724. }
  725. /* Abort connection */
  726. tcp->tcp_state = TCP_CLOSED;
  727. tcp_dump_state ( tcp );
  728. tcp_close ( tcp, -ECONNRESET );
  729. return -ECONNRESET;
  730. }
  731. /**
  732. * Process received packet
  733. *
  734. * @v iobuf I/O buffer
  735. * @v st_src Partially-filled source address
  736. * @v st_dest Partially-filled destination address
  737. * @v pshdr_csum Pseudo-header checksum
  738. * @ret rc Return status code
  739. */
  740. static int tcp_rx ( struct io_buffer *iobuf,
  741. struct sockaddr_tcpip *st_src,
  742. struct sockaddr_tcpip *st_dest __unused,
  743. uint16_t pshdr_csum ) {
  744. struct tcp_header *tcphdr = iobuf->data;
  745. struct tcp_connection *tcp;
  746. struct tcp_options options;
  747. unsigned int hlen;
  748. uint16_t csum;
  749. uint32_t start_seq;
  750. uint32_t seq;
  751. uint32_t ack;
  752. uint32_t win;
  753. unsigned int flags;
  754. size_t len;
  755. int rc;
  756. /* Sanity check packet */
  757. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  758. DBG ( "TCP packet too short at %d bytes (min %d bytes)\n",
  759. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  760. rc = -EINVAL;
  761. goto discard;
  762. }
  763. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  764. if ( hlen < sizeof ( *tcphdr ) ) {
  765. DBG ( "TCP header too short at %d bytes (min %d bytes)\n",
  766. hlen, sizeof ( *tcphdr ) );
  767. rc = -EINVAL;
  768. goto discard;
  769. }
  770. if ( hlen > iob_len ( iobuf ) ) {
  771. DBG ( "TCP header too long at %d bytes (max %d bytes)\n",
  772. hlen, iob_len ( iobuf ) );
  773. rc = -EINVAL;
  774. goto discard;
  775. }
  776. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data, iob_len ( iobuf ));
  777. if ( csum != 0 ) {
  778. DBG ( "TCP checksum incorrect (is %04x including checksum "
  779. "field, should be 0000)\n", csum );
  780. rc = -EINVAL;
  781. goto discard;
  782. }
  783. /* Parse parameters from header and strip header */
  784. tcp = tcp_demux ( tcphdr->dest );
  785. start_seq = seq = ntohl ( tcphdr->seq );
  786. ack = ntohl ( tcphdr->ack );
  787. win = ntohs ( tcphdr->win );
  788. flags = tcphdr->flags;
  789. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  790. ( hlen - sizeof ( *tcphdr ) ), &options );
  791. iob_pull ( iobuf, hlen );
  792. len = iob_len ( iobuf );
  793. /* Dump header */
  794. DBGC ( tcp, "TCP %p RX %d<-%d %08lx %08lx..%08lx %4zd",
  795. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  796. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  797. ( ntohl ( tcphdr->seq ) + len +
  798. ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 ) ), len);
  799. tcp_dump_flags ( tcp, tcphdr->flags );
  800. DBGC ( tcp, "\n" );
  801. /* If no connection was found, send RST */
  802. if ( ! tcp ) {
  803. tcp_xmit_reset ( tcp, st_src, tcphdr );
  804. rc = -ENOTCONN;
  805. goto discard;
  806. }
  807. /* Handle ACK, if present */
  808. if ( flags & TCP_ACK ) {
  809. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  810. tcp_xmit_reset ( tcp, st_src, tcphdr );
  811. goto discard;
  812. }
  813. }
  814. /* Handle SYN, if present */
  815. if ( flags & TCP_SYN ) {
  816. tcp_rx_syn ( tcp, seq, &options );
  817. seq++;
  818. }
  819. /* Handle RST, if present */
  820. if ( flags & TCP_RST ) {
  821. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  822. goto discard;
  823. }
  824. /* Handle new data, if any */
  825. tcp_rx_data ( tcp, seq, iobuf );
  826. seq += len;
  827. /* Handle FIN, if present */
  828. if ( flags & TCP_FIN ) {
  829. tcp_rx_fin ( tcp, seq );
  830. seq++;
  831. }
  832. /* Update timestamp, if present and applicable */
  833. if ( ( seq == tcp->rcv_ack ) && options.tsopt )
  834. tcp->ts_recent = ntohl ( options.tsopt->tsval );
  835. /* Dump out any state change as a result of the received packet */
  836. tcp_dump_state ( tcp );
  837. /* Send out any pending data. If peer is expecting an ACK for
  838. * this packet then force sending a reply.
  839. */
  840. tcp_xmit ( tcp, ( start_seq != seq ) );
  841. /* If this packet was the last we expect to receive, set up
  842. * timer to expire and cause the connection to be freed.
  843. */
  844. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  845. tcp->timer.timeout = ( 2 * TCP_MSL );
  846. start_timer ( &tcp->timer );
  847. }
  848. return 0;
  849. discard:
  850. /* Free received packet */
  851. free_iob ( iobuf );
  852. return rc;
  853. }
  854. /** TCP protocol */
  855. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  856. .name = "TCP",
  857. .rx = tcp_rx,
  858. .tcpip_proto = IP_TCP,
  859. };
  860. /***************************************************************************
  861. *
  862. * Data transfer interface
  863. *
  864. ***************************************************************************
  865. */
  866. /**
  867. * Close interface
  868. *
  869. * @v xfer Data transfer interface
  870. * @v rc Reason for close
  871. */
  872. static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
  873. struct tcp_connection *tcp =
  874. container_of ( xfer, struct tcp_connection, xfer );
  875. /* Close data transfer interface */
  876. tcp_close ( tcp, rc );
  877. /* Transmit FIN, if possible */
  878. tcp_xmit ( tcp, 0 );
  879. }
  880. /**
  881. * Check flow control window
  882. *
  883. * @v xfer Data transfer interface
  884. * @ret len Length of window
  885. */
  886. static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
  887. struct tcp_connection *tcp =
  888. container_of ( xfer, struct tcp_connection, xfer );
  889. /* Not ready if data queue is non-empty. This imposes a limit
  890. * of only one unACKed packet in the TX queue at any time; we
  891. * do this to conserve memory usage.
  892. */
  893. if ( ! list_empty ( &tcp->queue ) )
  894. return 0;
  895. /* Return TCP window length */
  896. return tcp_xmit_win ( tcp );
  897. }
  898. /**
  899. * Deliver datagram as I/O buffer
  900. *
  901. * @v xfer Data transfer interface
  902. * @v iobuf Datagram I/O buffer
  903. * @v meta Data transfer metadata, or NULL
  904. * @ret rc Return status code
  905. */
  906. static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
  907. struct io_buffer *iobuf,
  908. struct xfer_metadata *meta __unused ) {
  909. struct tcp_connection *tcp =
  910. container_of ( xfer, struct tcp_connection, xfer );
  911. /* Enqueue packet */
  912. list_add_tail ( &iobuf->list, &tcp->queue );
  913. /* Transmit data, if possible */
  914. tcp_xmit ( tcp, 0 );
  915. return 0;
  916. }
  917. /** TCP data transfer interface operations */
  918. static struct xfer_interface_operations tcp_xfer_operations = {
  919. .close = tcp_xfer_close,
  920. .vredirect = ignore_xfer_vredirect,
  921. .seek = ignore_xfer_seek,
  922. .window = tcp_xfer_window,
  923. .alloc_iob = default_xfer_alloc_iob,
  924. .deliver_iob = tcp_xfer_deliver_iob,
  925. .deliver_raw = xfer_deliver_as_iob,
  926. };
  927. /***************************************************************************
  928. *
  929. * Openers
  930. *
  931. ***************************************************************************
  932. */
  933. /** TCP socket opener */
  934. struct socket_opener tcp_socket_opener __socket_opener = {
  935. .semantics = SOCK_STREAM,
  936. .family = AF_INET,
  937. .open = tcp_open,
  938. };
  939. char TCP_SOCK_STREAM[1];
  940. /**
  941. * Open TCP URI
  942. *
  943. * @v xfer Data transfer interface
  944. * @v uri URI
  945. * @ret rc Return status code
  946. */
  947. static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
  948. struct sockaddr_tcpip peer;
  949. /* Sanity check */
  950. if ( ! uri->host )
  951. return -EINVAL;
  952. memset ( &peer, 0, sizeof ( peer ) );
  953. peer.st_port = htons ( uri_port ( uri, 0 ) );
  954. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  955. ( struct sockaddr * ) &peer,
  956. uri->host, NULL );
  957. }
  958. /** TCP URI opener */
  959. struct uri_opener tcp_uri_opener __uri_opener = {
  960. .scheme = "tcp",
  961. .open = tcp_open_uri,
  962. };