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.

tcp.c 28KB

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