Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

tcp.c 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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/retry.h>
  11. #include <ipxe/refcnt.h>
  12. #include <ipxe/xfer.h>
  13. #include <ipxe/open.h>
  14. #include <ipxe/uri.h>
  15. #include <ipxe/tcpip.h>
  16. #include <ipxe/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. uint32_t seq_len;
  363. uint32_t app_win;
  364. uint32_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..%08x %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, uint32_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. /* Acknowledge SYN */
  635. tcp_rx_seq ( tcp, 1 );
  636. /* Mark SYN as received and start sending ACKs with each packet */
  637. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  638. TCP_STATE_RCVD ( TCP_SYN ) );
  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. uint32_t ack_len = ( ack - tcp->snd_seq );
  652. size_t len;
  653. unsigned int acked_flags;
  654. /* Check for out-of-range or old duplicate ACKs */
  655. if ( ack_len > tcp->snd_sent ) {
  656. DBGC ( tcp, "TCP %p received ACK for %08x..%08x, "
  657. "sent only %08x..%08x\n", tcp, tcp->snd_seq,
  658. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  659. ( tcp->snd_seq + tcp->snd_sent ) );
  660. if ( TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) ) {
  661. /* Just ignore what might be old duplicate ACKs */
  662. return 0;
  663. } else {
  664. /* Send RST if an out-of-range ACK is received
  665. * on a not-yet-established connection, as per
  666. * RFC 793.
  667. */
  668. return -EINVAL;
  669. }
  670. }
  671. /* Ignore ACKs that don't actually acknowledge any new data.
  672. * (In particular, do not stop the retransmission timer; this
  673. * avoids creating a sorceror's apprentice syndrome when a
  674. * duplicate ACK is received and we still have data in our
  675. * transmit queue.)
  676. */
  677. if ( ack_len == 0 )
  678. return 0;
  679. /* Stop the retransmission timer */
  680. stop_timer ( &tcp->timer );
  681. /* Determine acknowledged flags and data length */
  682. len = ack_len;
  683. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  684. ( TCP_SYN | TCP_FIN ) );
  685. if ( acked_flags )
  686. len--;
  687. /* Update SEQ and sent counters, and window size */
  688. tcp->snd_seq = ack;
  689. tcp->snd_sent = 0;
  690. tcp->snd_win = win;
  691. /* Remove any acknowledged data from transmit queue */
  692. tcp_process_queue ( tcp, len, NULL, 1 );
  693. /* Mark SYN/FIN as acknowledged if applicable. */
  694. if ( acked_flags )
  695. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  696. /* Start sending FIN if we've had all possible data ACKed */
  697. if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
  698. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  699. return 0;
  700. }
  701. /**
  702. * Handle TCP received data
  703. *
  704. * @v tcp TCP connection
  705. * @v seq SEQ value (in host-endian order)
  706. * @v iobuf I/O buffer
  707. * @ret rc Return status code
  708. *
  709. * This function takes ownership of the I/O buffer.
  710. */
  711. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  712. struct io_buffer *iobuf ) {
  713. uint32_t already_rcvd;
  714. uint32_t len;
  715. int rc;
  716. /* Ignore duplicate or out-of-order data */
  717. already_rcvd = ( tcp->rcv_ack - seq );
  718. len = iob_len ( iobuf );
  719. if ( already_rcvd >= len ) {
  720. free_iob ( iobuf );
  721. return 0;
  722. }
  723. iob_pull ( iobuf, already_rcvd );
  724. len -= already_rcvd;
  725. /* Acknowledge new data */
  726. tcp_rx_seq ( tcp, len );
  727. /* Deliver data to application */
  728. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
  729. DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
  730. tcp, seq, ( seq + len ), strerror ( rc ) );
  731. return rc;
  732. }
  733. return 0;
  734. }
  735. /**
  736. * Handle TCP received FIN
  737. *
  738. * @v tcp TCP connection
  739. * @v seq SEQ value (in host-endian order)
  740. * @ret rc Return status code
  741. */
  742. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  743. /* Ignore duplicate or out-of-order FIN */
  744. if ( ( tcp->rcv_ack - seq ) > 0 )
  745. return 0;
  746. /* Acknowledge FIN */
  747. tcp_rx_seq ( tcp, 1 );
  748. /* Mark FIN as received */
  749. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  750. /* Close connection */
  751. tcp_close ( tcp, 0 );
  752. return 0;
  753. }
  754. /**
  755. * Handle TCP received RST
  756. *
  757. * @v tcp TCP connection
  758. * @v seq SEQ value (in host-endian order)
  759. * @ret rc Return status code
  760. */
  761. static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  762. /* Accept RST only if it falls within the window. If we have
  763. * not yet received a SYN, then we have no window to test
  764. * against, so fall back to checking that our SYN has been
  765. * ACKed.
  766. */
  767. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  768. if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
  769. return 0;
  770. } else {
  771. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  772. return 0;
  773. }
  774. /* Abort connection */
  775. tcp->tcp_state = TCP_CLOSED;
  776. tcp_dump_state ( tcp );
  777. tcp_close ( tcp, -ECONNRESET );
  778. DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
  779. return -ECONNRESET;
  780. }
  781. /**
  782. * Process received packet
  783. *
  784. * @v iobuf I/O buffer
  785. * @v st_src Partially-filled source address
  786. * @v st_dest Partially-filled destination address
  787. * @v pshdr_csum Pseudo-header checksum
  788. * @ret rc Return status code
  789. */
  790. static int tcp_rx ( struct io_buffer *iobuf,
  791. struct sockaddr_tcpip *st_src,
  792. struct sockaddr_tcpip *st_dest __unused,
  793. uint16_t pshdr_csum ) {
  794. struct tcp_header *tcphdr = iobuf->data;
  795. struct tcp_connection *tcp;
  796. struct tcp_options options;
  797. size_t hlen;
  798. uint16_t csum;
  799. uint32_t start_seq;
  800. uint32_t seq;
  801. uint32_t ack;
  802. uint32_t win;
  803. unsigned int flags;
  804. size_t len;
  805. int rc;
  806. /* Sanity check packet */
  807. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  808. DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
  809. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  810. rc = -EINVAL;
  811. goto discard;
  812. }
  813. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  814. if ( hlen < sizeof ( *tcphdr ) ) {
  815. DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
  816. hlen, sizeof ( *tcphdr ) );
  817. rc = -EINVAL;
  818. goto discard;
  819. }
  820. if ( hlen > iob_len ( iobuf ) ) {
  821. DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
  822. hlen, iob_len ( iobuf ) );
  823. rc = -EINVAL;
  824. goto discard;
  825. }
  826. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
  827. iob_len ( iobuf ) );
  828. if ( csum != 0 ) {
  829. DBG ( "TCP checksum incorrect (is %04x including checksum "
  830. "field, should be 0000)\n", csum );
  831. rc = -EINVAL;
  832. goto discard;
  833. }
  834. /* Parse parameters from header and strip header */
  835. tcp = tcp_demux ( tcphdr->dest );
  836. start_seq = seq = ntohl ( tcphdr->seq );
  837. ack = ntohl ( tcphdr->ack );
  838. win = ntohs ( tcphdr->win );
  839. flags = tcphdr->flags;
  840. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  841. ( hlen - sizeof ( *tcphdr ) ), &options );
  842. iob_pull ( iobuf, hlen );
  843. len = iob_len ( iobuf );
  844. /* Dump header */
  845. DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
  846. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  847. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  848. ( ntohl ( tcphdr->seq ) + len +
  849. ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 )), len);
  850. tcp_dump_flags ( tcp, tcphdr->flags );
  851. DBGC2 ( tcp, "\n" );
  852. /* If no connection was found, send RST */
  853. if ( ! tcp ) {
  854. tcp_xmit_reset ( tcp, st_src, tcphdr );
  855. rc = -ENOTCONN;
  856. goto discard;
  857. }
  858. /* Handle ACK, if present */
  859. if ( flags & TCP_ACK ) {
  860. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  861. tcp_xmit_reset ( tcp, st_src, tcphdr );
  862. goto discard;
  863. }
  864. }
  865. /* Handle SYN, if present */
  866. if ( flags & TCP_SYN ) {
  867. tcp_rx_syn ( tcp, seq, &options );
  868. seq++;
  869. }
  870. /* Handle RST, if present */
  871. if ( flags & TCP_RST ) {
  872. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  873. goto discard;
  874. }
  875. /* Handle new data, if any */
  876. tcp_rx_data ( tcp, seq, iobuf );
  877. seq += len;
  878. /* Handle FIN, if present */
  879. if ( flags & TCP_FIN ) {
  880. tcp_rx_fin ( tcp, seq );
  881. seq++;
  882. }
  883. /* Update timestamp, if present and applicable */
  884. if ( ( seq == tcp->rcv_ack ) && options.tsopt )
  885. tcp->ts_recent = ntohl ( options.tsopt->tsval );
  886. /* Dump out any state change as a result of the received packet */
  887. tcp_dump_state ( tcp );
  888. /* Send out any pending data. We force sending a reply if either
  889. *
  890. * a) the peer is expecting an ACK (i.e. consumed sequence space), or
  891. * b) either end of the packet was outside the receive window
  892. *
  893. * Case (b) enables us to support TCP keepalives using
  894. * zero-length packets, which we would otherwise ignore. Note
  895. * that for case (b), we need *only* consider zero-length
  896. * packets, since non-zero-length packets will already be
  897. * caught by case (a).
  898. */
  899. tcp_xmit ( tcp, ( ( start_seq != seq ) ||
  900. ( ( seq - tcp->rcv_ack ) > tcp->rcv_win ) ) );
  901. /* If this packet was the last we expect to receive, set up
  902. * timer to expire and cause the connection to be freed.
  903. */
  904. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  905. tcp->timer.timeout = ( 2 * TCP_MSL );
  906. start_timer ( &tcp->timer );
  907. }
  908. return 0;
  909. discard:
  910. /* Free received packet */
  911. free_iob ( iobuf );
  912. return rc;
  913. }
  914. /** TCP protocol */
  915. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  916. .name = "TCP",
  917. .rx = tcp_rx,
  918. .tcpip_proto = IP_TCP,
  919. };
  920. /***************************************************************************
  921. *
  922. * Data transfer interface
  923. *
  924. ***************************************************************************
  925. */
  926. /**
  927. * Close interface
  928. *
  929. * @v xfer Data transfer interface
  930. * @v rc Reason for close
  931. */
  932. static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
  933. struct tcp_connection *tcp =
  934. container_of ( xfer, struct tcp_connection, xfer );
  935. /* Close data transfer interface */
  936. tcp_close ( tcp, rc );
  937. /* Transmit FIN, if possible */
  938. tcp_xmit ( tcp, 0 );
  939. }
  940. /**
  941. * Check flow control window
  942. *
  943. * @v xfer Data transfer interface
  944. * @ret len Length of window
  945. */
  946. static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
  947. struct tcp_connection *tcp =
  948. container_of ( xfer, struct tcp_connection, xfer );
  949. /* Not ready if data queue is non-empty. This imposes a limit
  950. * of only one unACKed packet in the TX queue at any time; we
  951. * do this to conserve memory usage.
  952. */
  953. if ( ! list_empty ( &tcp->queue ) )
  954. return 0;
  955. /* Return TCP window length */
  956. return tcp_xmit_win ( tcp );
  957. }
  958. /**
  959. * Deliver datagram as I/O buffer
  960. *
  961. * @v xfer Data transfer interface
  962. * @v iobuf Datagram I/O buffer
  963. * @v meta Data transfer metadata
  964. * @ret rc Return status code
  965. */
  966. static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
  967. struct io_buffer *iobuf,
  968. struct xfer_metadata *meta __unused ) {
  969. struct tcp_connection *tcp =
  970. container_of ( xfer, struct tcp_connection, xfer );
  971. /* Enqueue packet */
  972. list_add_tail ( &iobuf->list, &tcp->queue );
  973. /* Transmit data, if possible */
  974. tcp_xmit ( tcp, 0 );
  975. return 0;
  976. }
  977. /** TCP data transfer interface operations */
  978. static struct xfer_interface_operations tcp_xfer_operations = {
  979. .close = tcp_xfer_close,
  980. .vredirect = ignore_xfer_vredirect,
  981. .window = tcp_xfer_window,
  982. .alloc_iob = default_xfer_alloc_iob,
  983. .deliver_iob = tcp_xfer_deliver_iob,
  984. .deliver_raw = xfer_deliver_as_iob,
  985. };
  986. /***************************************************************************
  987. *
  988. * Openers
  989. *
  990. ***************************************************************************
  991. */
  992. /** TCP socket opener */
  993. struct socket_opener tcp_socket_opener __socket_opener = {
  994. .semantics = TCP_SOCK_STREAM,
  995. .family = AF_INET,
  996. .open = tcp_open,
  997. };
  998. /** Linkage hack */
  999. int tcp_sock_stream = TCP_SOCK_STREAM;
  1000. /**
  1001. * Open TCP URI
  1002. *
  1003. * @v xfer Data transfer interface
  1004. * @v uri URI
  1005. * @ret rc Return status code
  1006. */
  1007. static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
  1008. struct sockaddr_tcpip peer;
  1009. /* Sanity check */
  1010. if ( ! uri->host )
  1011. return -EINVAL;
  1012. memset ( &peer, 0, sizeof ( peer ) );
  1013. peer.st_port = htons ( uri_port ( uri, 0 ) );
  1014. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  1015. ( struct sockaddr * ) &peer,
  1016. uri->host, NULL );
  1017. }
  1018. /** TCP URI opener */
  1019. struct uri_opener tcp_uri_opener __uri_opener = {
  1020. .scheme = "tcp",
  1021. .open = tcp_open_uri,
  1022. };