tcp.c 29KB

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