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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  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. if ( ! ( flags & TCP_SYN ) )
  428. flags |= TCP_PSH;
  429. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  430. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  431. tcphdr->src = tcp->local_port;
  432. tcphdr->dest = tcp->peer.st_port;
  433. tcphdr->seq = htonl ( tcp->snd_seq );
  434. tcphdr->ack = htonl ( tcp->rcv_ack );
  435. tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
  436. tcphdr->flags = flags;
  437. tcphdr->win = htons ( tcp->rcv_win );
  438. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  439. /* Dump header */
  440. DBGC ( tcp, "TCP %p TX %d->%d %08x..%08zx %08x %4zd",
  441. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  442. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
  443. ntohl ( tcphdr->ack ), len );
  444. tcp_dump_flags ( tcp, tcphdr->flags );
  445. DBGC ( tcp, "\n" );
  446. /* Transmit packet */
  447. return tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
  448. &tcphdr->csum );
  449. }
  450. /**
  451. * Retransmission timer expired
  452. *
  453. * @v timer Retry timer
  454. * @v over Failure indicator
  455. */
  456. static void tcp_expired ( struct retry_timer *timer, int over ) {
  457. struct tcp_connection *tcp =
  458. container_of ( timer, struct tcp_connection, timer );
  459. int graceful_close = TCP_CLOSED_GRACEFULLY ( tcp->tcp_state );
  460. DBGC ( tcp, "TCP %p timer %s in %s\n", tcp,
  461. ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ) );
  462. assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
  463. ( tcp->tcp_state == TCP_SYN_RCVD ) ||
  464. ( tcp->tcp_state == TCP_ESTABLISHED ) ||
  465. ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
  466. ( tcp->tcp_state == TCP_TIME_WAIT ) ||
  467. ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
  468. ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
  469. if ( over || graceful_close ) {
  470. /* If we have finally timed out and given up, or if
  471. * this is the result of a graceful close, terminate
  472. * the connection
  473. */
  474. tcp->tcp_state = TCP_CLOSED;
  475. tcp_dump_state ( tcp );
  476. tcp_close ( tcp, -ETIMEDOUT );
  477. } else {
  478. /* Otherwise, retransmit the packet */
  479. tcp_xmit ( tcp, 0 );
  480. }
  481. }
  482. /**
  483. * Send RST response to incoming packet
  484. *
  485. * @v in_tcphdr TCP header of incoming packet
  486. * @ret rc Return status code
  487. */
  488. static int tcp_xmit_reset ( struct tcp_connection *tcp,
  489. struct sockaddr_tcpip *st_dest,
  490. struct tcp_header *in_tcphdr ) {
  491. struct io_buffer *iobuf;
  492. struct tcp_header *tcphdr;
  493. /* Allocate space for dataless TX buffer */
  494. iobuf = alloc_iob ( MAX_HDR_LEN );
  495. if ( ! iobuf ) {
  496. DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
  497. return -ENOMEM;
  498. }
  499. iob_reserve ( iobuf, MAX_HDR_LEN );
  500. /* Construct RST response */
  501. tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
  502. memset ( tcphdr, 0, sizeof ( *tcphdr ) );
  503. tcphdr->src = in_tcphdr->dest;
  504. tcphdr->dest = in_tcphdr->src;
  505. tcphdr->seq = in_tcphdr->ack;
  506. tcphdr->ack = in_tcphdr->seq;
  507. tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
  508. tcphdr->flags = ( TCP_RST | TCP_ACK );
  509. tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
  510. tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
  511. /* Dump header */
  512. DBGC ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
  513. tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
  514. ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
  515. ntohl ( tcphdr->ack ), 0 );
  516. tcp_dump_flags ( tcp, tcphdr->flags );
  517. DBGC ( tcp, "\n" );
  518. /* Transmit packet */
  519. return tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
  520. NULL, &tcphdr->csum );
  521. }
  522. /***************************************************************************
  523. *
  524. * Receive data path
  525. *
  526. ***************************************************************************
  527. */
  528. /**
  529. * Identify TCP connection by local port number
  530. *
  531. * @v local_port Local port (in network-endian order)
  532. * @ret tcp TCP connection, or NULL
  533. */
  534. static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
  535. struct tcp_connection *tcp;
  536. list_for_each_entry ( tcp, &tcp_conns, list ) {
  537. if ( tcp->local_port == local_port )
  538. return tcp;
  539. }
  540. return NULL;
  541. }
  542. /**
  543. * Parse TCP received options
  544. *
  545. * @v tcp TCP connection
  546. * @v data Raw options data
  547. * @v len Raw options length
  548. * @v options Options structure to fill in
  549. */
  550. static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
  551. size_t len, struct tcp_options *options ) {
  552. const void *end = ( data + len );
  553. const struct tcp_option *option;
  554. unsigned int kind;
  555. memset ( options, 0, sizeof ( *options ) );
  556. while ( data < end ) {
  557. option = data;
  558. kind = option->kind;
  559. if ( kind == TCP_OPTION_END )
  560. return;
  561. if ( kind == TCP_OPTION_NOP ) {
  562. data++;
  563. continue;
  564. }
  565. switch ( kind ) {
  566. case TCP_OPTION_MSS:
  567. options->mssopt = data;
  568. break;
  569. case TCP_OPTION_TS:
  570. options->tsopt = data;
  571. break;
  572. default:
  573. DBGC ( tcp, "TCP %p received unknown option %d\n",
  574. tcp, kind );
  575. break;
  576. }
  577. data += option->length;
  578. }
  579. }
  580. /**
  581. * Consume received sequence space
  582. *
  583. * @v tcp TCP connection
  584. * @v seq_len Sequence space length to consume
  585. */
  586. static void tcp_rx_seq ( struct tcp_connection *tcp, size_t seq_len ) {
  587. tcp->rcv_ack += seq_len;
  588. if ( tcp->rcv_win > seq_len ) {
  589. tcp->rcv_win -= seq_len;
  590. } else {
  591. tcp->rcv_win = 0;
  592. }
  593. }
  594. /**
  595. * Handle TCP received SYN
  596. *
  597. * @v tcp TCP connection
  598. * @v seq SEQ value (in host-endian order)
  599. * @v options TCP options
  600. * @ret rc Return status code
  601. */
  602. static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
  603. struct tcp_options *options ) {
  604. /* Synchronise sequence numbers on first SYN */
  605. if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
  606. tcp->rcv_ack = seq;
  607. if ( options->tsopt )
  608. tcp->timestamps = 1;
  609. }
  610. /* Ignore duplicate SYN */
  611. if ( ( tcp->rcv_ack - seq ) > 0 )
  612. return 0;
  613. /* Mark SYN as received and start sending ACKs with each packet */
  614. tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
  615. TCP_STATE_RCVD ( TCP_SYN ) );
  616. /* Acknowledge SYN */
  617. tcp_rx_seq ( tcp, 1 );
  618. return 0;
  619. }
  620. /**
  621. * Handle TCP received ACK
  622. *
  623. * @v tcp TCP connection
  624. * @v ack ACK value (in host-endian order)
  625. * @v win WIN value (in host-endian order)
  626. * @ret rc Return status code
  627. */
  628. static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
  629. uint32_t win ) {
  630. size_t ack_len = ( ack - tcp->snd_seq );
  631. size_t len;
  632. unsigned int acked_flags;
  633. /* Ignore duplicate or out-of-range ACK */
  634. if ( ack_len > tcp->snd_sent ) {
  635. DBGC ( tcp, "TCP %p received ACK for [%08x,%08zx), "
  636. "sent only [%08x,%08x)\n", tcp, tcp->snd_seq,
  637. ( tcp->snd_seq + ack_len ), tcp->snd_seq,
  638. ( tcp->snd_seq + tcp->snd_sent ) );
  639. return -EINVAL;
  640. }
  641. /* Acknowledge any flags being sent */
  642. len = ack_len;
  643. acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
  644. ( TCP_SYN | TCP_FIN ) );
  645. if ( acked_flags )
  646. len--;
  647. /* Update SEQ and sent counters, and window size */
  648. tcp->snd_seq = ack;
  649. tcp->snd_sent = 0;
  650. tcp->snd_win = win;
  651. /* Stop the retransmission timer */
  652. stop_timer ( &tcp->timer );
  653. /* Remove any acknowledged data from transmit queue */
  654. tcp_process_queue ( tcp, len, NULL, 1 );
  655. /* Mark SYN/FIN as acknowledged if applicable. */
  656. if ( acked_flags )
  657. tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
  658. /* Start sending FIN if we've had all possible data ACKed */
  659. if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
  660. tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
  661. return 0;
  662. }
  663. /**
  664. * Handle TCP received data
  665. *
  666. * @v tcp TCP connection
  667. * @v seq SEQ value (in host-endian order)
  668. * @v iobuf I/O buffer
  669. * @ret rc Return status code
  670. *
  671. * This function takes ownership of the I/O buffer.
  672. */
  673. static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
  674. struct io_buffer *iobuf ) {
  675. size_t already_rcvd;
  676. size_t len;
  677. int rc;
  678. /* Ignore duplicate or out-of-order data */
  679. already_rcvd = ( tcp->rcv_ack - seq );
  680. len = iob_len ( iobuf );
  681. if ( already_rcvd >= len ) {
  682. free_iob ( iobuf );
  683. return 0;
  684. }
  685. iob_pull ( iobuf, already_rcvd );
  686. len -= already_rcvd;
  687. /* Deliver data to application */
  688. if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 )
  689. return rc;
  690. /* Acknowledge new data */
  691. tcp_rx_seq ( tcp, len );
  692. return 0;
  693. }
  694. /**
  695. * Handle TCP received FIN
  696. *
  697. * @v tcp TCP connection
  698. * @v seq SEQ value (in host-endian order)
  699. * @ret rc Return status code
  700. */
  701. static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
  702. /* Ignore duplicate or out-of-order FIN */
  703. if ( ( tcp->rcv_ack - seq ) > 0 )
  704. return 0;
  705. /* Mark FIN as received and acknowledge it */
  706. tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
  707. tcp_rx_seq ( tcp, 1 );
  708. /* Close connection */
  709. tcp_close ( tcp, 0 );
  710. return 0;
  711. }
  712. /**
  713. * Handle TCP received RST
  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_rst ( struct tcp_connection *tcp, uint32_t seq ) {
  720. /* Accept RST only if it falls within the window. If we have
  721. * not yet received a SYN, then we have no window to test
  722. * against, so fall back to checking that our SYN has been
  723. * ACKed.
  724. */
  725. if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
  726. if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
  727. return 0;
  728. } else {
  729. if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
  730. return 0;
  731. }
  732. /* Abort connection */
  733. tcp->tcp_state = TCP_CLOSED;
  734. tcp_dump_state ( tcp );
  735. tcp_close ( tcp, -ECONNRESET );
  736. return -ECONNRESET;
  737. }
  738. /**
  739. * Process received packet
  740. *
  741. * @v iobuf I/O buffer
  742. * @v st_src Partially-filled source address
  743. * @v st_dest Partially-filled destination address
  744. * @v pshdr_csum Pseudo-header checksum
  745. * @ret rc Return status code
  746. */
  747. static int tcp_rx ( struct io_buffer *iobuf,
  748. struct sockaddr_tcpip *st_src,
  749. struct sockaddr_tcpip *st_dest __unused,
  750. uint16_t pshdr_csum ) {
  751. struct tcp_header *tcphdr = iobuf->data;
  752. struct tcp_connection *tcp;
  753. struct tcp_options options;
  754. size_t hlen;
  755. uint16_t csum;
  756. uint32_t start_seq;
  757. uint32_t seq;
  758. uint32_t ack;
  759. uint32_t win;
  760. unsigned int flags;
  761. size_t len;
  762. int rc;
  763. /* Sanity check packet */
  764. if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
  765. DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
  766. iob_len ( iobuf ), sizeof ( *tcphdr ) );
  767. rc = -EINVAL;
  768. goto discard;
  769. }
  770. hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
  771. if ( hlen < sizeof ( *tcphdr ) ) {
  772. DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
  773. hlen, sizeof ( *tcphdr ) );
  774. rc = -EINVAL;
  775. goto discard;
  776. }
  777. if ( hlen > iob_len ( iobuf ) ) {
  778. DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
  779. hlen, iob_len ( iobuf ) );
  780. rc = -EINVAL;
  781. goto discard;
  782. }
  783. csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
  784. iob_len ( iobuf ) );
  785. if ( csum != 0 ) {
  786. DBG ( "TCP checksum incorrect (is %04x including checksum "
  787. "field, should be 0000)\n", csum );
  788. rc = -EINVAL;
  789. goto discard;
  790. }
  791. /* Parse parameters from header and strip header */
  792. tcp = tcp_demux ( tcphdr->dest );
  793. start_seq = seq = ntohl ( tcphdr->seq );
  794. ack = ntohl ( tcphdr->ack );
  795. win = ntohs ( tcphdr->win );
  796. flags = tcphdr->flags;
  797. tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
  798. ( hlen - sizeof ( *tcphdr ) ), &options );
  799. iob_pull ( iobuf, hlen );
  800. len = iob_len ( iobuf );
  801. /* Dump header */
  802. DBGC ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
  803. tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
  804. ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
  805. ( ntohl ( tcphdr->seq ) + len +
  806. ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 ) ), len);
  807. tcp_dump_flags ( tcp, tcphdr->flags );
  808. DBGC ( tcp, "\n" );
  809. /* If no connection was found, send RST */
  810. if ( ! tcp ) {
  811. tcp_xmit_reset ( tcp, st_src, tcphdr );
  812. rc = -ENOTCONN;
  813. goto discard;
  814. }
  815. /* Handle ACK, if present */
  816. if ( flags & TCP_ACK ) {
  817. if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
  818. tcp_xmit_reset ( tcp, st_src, tcphdr );
  819. goto discard;
  820. }
  821. }
  822. /* Handle SYN, if present */
  823. if ( flags & TCP_SYN ) {
  824. tcp_rx_syn ( tcp, seq, &options );
  825. seq++;
  826. }
  827. /* Handle RST, if present */
  828. if ( flags & TCP_RST ) {
  829. if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
  830. goto discard;
  831. }
  832. /* Handle new data, if any */
  833. tcp_rx_data ( tcp, seq, iobuf );
  834. seq += len;
  835. /* Handle FIN, if present */
  836. if ( flags & TCP_FIN ) {
  837. tcp_rx_fin ( tcp, seq );
  838. seq++;
  839. }
  840. /* Update timestamp, if present and applicable */
  841. if ( ( seq == tcp->rcv_ack ) && options.tsopt )
  842. tcp->ts_recent = ntohl ( options.tsopt->tsval );
  843. /* Dump out any state change as a result of the received packet */
  844. tcp_dump_state ( tcp );
  845. /* Send out any pending data. We force sending a reply if either
  846. *
  847. * a) the peer is expecting an ACK (i.e. consumed sequence space), or
  848. * b) either end of the packet was outside the receive window
  849. *
  850. * Case (b) enables us to support TCP keepalives using
  851. * zero-length packets, which we would otherwise ignore. Note
  852. * that for case (b), we need *only* consider zero-length
  853. * packets, since non-zero-length packets will already be
  854. * caught by case (a).
  855. */
  856. tcp_xmit ( tcp, ( ( start_seq != seq ) ||
  857. ( ( seq - tcp->rcv_ack ) > tcp->rcv_win ) ) );
  858. /* If this packet was the last we expect to receive, set up
  859. * timer to expire and cause the connection to be freed.
  860. */
  861. if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
  862. tcp->timer.timeout = ( 2 * TCP_MSL );
  863. start_timer ( &tcp->timer );
  864. }
  865. return 0;
  866. discard:
  867. /* Free received packet */
  868. free_iob ( iobuf );
  869. return rc;
  870. }
  871. /** TCP protocol */
  872. struct tcpip_protocol tcp_protocol __tcpip_protocol = {
  873. .name = "TCP",
  874. .rx = tcp_rx,
  875. .tcpip_proto = IP_TCP,
  876. };
  877. /***************************************************************************
  878. *
  879. * Data transfer interface
  880. *
  881. ***************************************************************************
  882. */
  883. /**
  884. * Close interface
  885. *
  886. * @v xfer Data transfer interface
  887. * @v rc Reason for close
  888. */
  889. static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
  890. struct tcp_connection *tcp =
  891. container_of ( xfer, struct tcp_connection, xfer );
  892. /* Close data transfer interface */
  893. tcp_close ( tcp, rc );
  894. /* Transmit FIN, if possible */
  895. tcp_xmit ( tcp, 0 );
  896. }
  897. /**
  898. * Check flow control window
  899. *
  900. * @v xfer Data transfer interface
  901. * @ret len Length of window
  902. */
  903. static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
  904. struct tcp_connection *tcp =
  905. container_of ( xfer, struct tcp_connection, xfer );
  906. /* Not ready if data queue is non-empty. This imposes a limit
  907. * of only one unACKed packet in the TX queue at any time; we
  908. * do this to conserve memory usage.
  909. */
  910. if ( ! list_empty ( &tcp->queue ) )
  911. return 0;
  912. /* Return TCP window length */
  913. return tcp_xmit_win ( tcp );
  914. }
  915. /**
  916. * Deliver datagram as I/O buffer
  917. *
  918. * @v xfer Data transfer interface
  919. * @v iobuf Datagram I/O buffer
  920. * @v meta Data transfer metadata
  921. * @ret rc Return status code
  922. */
  923. static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
  924. struct io_buffer *iobuf,
  925. struct xfer_metadata *meta __unused ) {
  926. struct tcp_connection *tcp =
  927. container_of ( xfer, struct tcp_connection, xfer );
  928. /* Enqueue packet */
  929. list_add_tail ( &iobuf->list, &tcp->queue );
  930. /* Transmit data, if possible */
  931. tcp_xmit ( tcp, 0 );
  932. return 0;
  933. }
  934. /** TCP data transfer interface operations */
  935. static struct xfer_interface_operations tcp_xfer_operations = {
  936. .close = tcp_xfer_close,
  937. .vredirect = ignore_xfer_vredirect,
  938. .window = tcp_xfer_window,
  939. .alloc_iob = default_xfer_alloc_iob,
  940. .deliver_iob = tcp_xfer_deliver_iob,
  941. .deliver_raw = xfer_deliver_as_iob,
  942. };
  943. /***************************************************************************
  944. *
  945. * Openers
  946. *
  947. ***************************************************************************
  948. */
  949. /** TCP socket opener */
  950. struct socket_opener tcp_socket_opener __socket_opener = {
  951. .semantics = TCP_SOCK_STREAM,
  952. .family = AF_INET,
  953. .open = tcp_open,
  954. };
  955. /** Linkage hack */
  956. int tcp_sock_stream = TCP_SOCK_STREAM;
  957. /**
  958. * Open TCP URI
  959. *
  960. * @v xfer Data transfer interface
  961. * @v uri URI
  962. * @ret rc Return status code
  963. */
  964. static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
  965. struct sockaddr_tcpip peer;
  966. /* Sanity check */
  967. if ( ! uri->host )
  968. return -EINVAL;
  969. memset ( &peer, 0, sizeof ( peer ) );
  970. peer.st_port = htons ( uri_port ( uri, 0 ) );
  971. return xfer_open_named_socket ( xfer, SOCK_STREAM,
  972. ( struct sockaddr * ) &peer,
  973. uri->host, NULL );
  974. }
  975. /** TCP URI opener */
  976. struct uri_opener tcp_uri_opener __uri_opener = {
  977. .scheme = "tcp",
  978. .open = tcp_open_uri,
  979. };