Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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