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.

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