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.

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