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.

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