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>
15 #include <gpxe/tcpip.h>
24 FILE_LICENCE ( GPL2_OR_LATER );
26 /** A TCP connection */
27 struct tcp_connection {
28 /** Reference counter */
30 /** List of TCP connections */
31 struct list_head list;
33 /** Data transfer interface */
34 struct xfer_interface xfer;
35 /** Data transfer interface closed flag */
38 /** Remote socket address */
39 struct sockaddr_tcpip peer;
40 /** Local port, in network byte order */
41 unsigned int local_port;
43 /** Current TCP state */
44 unsigned int tcp_state;
45 /** Previous TCP state
47 * Maintained only for debug messages
49 unsigned int prev_tcp_state;
50 /** Current sequence number
52 * Equivalent to SND.UNA in RFC 793 terminology.
55 /** Unacknowledged sequence count
57 * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
62 * Equivalent to SND.WND in RFC 793 terminology
65 /** Current acknowledgement number
67 * Equivalent to RCV.NXT in RFC 793 terminology.
72 * Equivalent to RCV.WND in RFC 793 terminology.
75 /** Most recent received timestamp
77 * Equivalent to TS.Recent in RFC 1323 terminology.
80 /** Timestamps enabled */
84 struct list_head queue;
85 /** Retransmission timer */
86 struct retry_timer timer;
90 * List of registered TCP connections
92 static LIST_HEAD ( tcp_conns );
94 /* Forward declarations */
95 static struct xfer_interface_operations tcp_xfer_operations;
96 static void tcp_expired ( struct retry_timer *timer, int over );
97 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
104 * @ret name Name of TCP state
106 static inline __attribute__ (( always_inline )) const char *
107 tcp_state ( int state ) {
109 case TCP_CLOSED: return "CLOSED";
110 case TCP_LISTEN: return "LISTEN";
111 case TCP_SYN_SENT: return "SYN_SENT";
112 case TCP_SYN_RCVD: return "SYN_RCVD";
113 case TCP_ESTABLISHED: return "ESTABLISHED";
114 case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
115 case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
116 case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
117 case TCP_TIME_WAIT: return "TIME_WAIT";
118 case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
119 default: return "INVALID";
124 * Dump TCP state transition
126 * @v tcp TCP connection
128 static inline __attribute__ (( always_inline )) void
129 tcp_dump_state ( struct tcp_connection *tcp ) {
131 if ( tcp->tcp_state != tcp->prev_tcp_state ) {
132 DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
133 tcp_state ( tcp->prev_tcp_state ),
134 tcp_state ( tcp->tcp_state ) );
136 tcp->prev_tcp_state = tcp->tcp_state;
144 static inline __attribute__ (( always_inline )) void
145 tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
146 if ( flags & TCP_RST )
147 DBGC2 ( tcp, " RST" );
148 if ( flags & TCP_SYN )
149 DBGC2 ( tcp, " SYN" );
150 if ( flags & TCP_PSH )
151 DBGC2 ( tcp, " PSH" );
152 if ( flags & TCP_FIN )
153 DBGC2 ( tcp, " FIN" );
154 if ( flags & TCP_ACK )
155 DBGC2 ( tcp, " ACK" );
158 /***************************************************************************
162 ***************************************************************************
166 * Bind TCP connection to local port
168 * @v tcp TCP connection
169 * @v port Local port number, in network-endian order
170 * @ret rc Return status code
172 * If the port is 0, the connection is assigned an available port
173 * between 1024 and 65535.
175 static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
176 struct tcp_connection *existing;
177 static uint16_t try_port = 1023;
179 /* If no port specified, find the first available port */
183 if ( try_port < 1024 )
185 if ( tcp_bind ( tcp, htons ( try_port ) ) == 0 )
188 DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
192 /* Attempt bind to local port */
193 list_for_each_entry ( existing, &tcp_conns, list ) {
194 if ( existing->local_port == port ) {
195 DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
196 tcp, ntohs ( port ) );
200 tcp->local_port = port;
202 DBGC ( tcp, "TCP %p bound to port %d\n", tcp, ntohs ( port ) );
207 * Open a TCP connection
209 * @v xfer Data transfer interface
210 * @v peer Peer socket address
211 * @v local Local socket address, or NULL
212 * @ret rc Return status code
214 static int tcp_open ( struct xfer_interface *xfer, struct sockaddr *peer,
215 struct sockaddr *local ) {
216 struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
217 struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
218 struct tcp_connection *tcp;
219 unsigned int bind_port;
222 /* Allocate and initialise structure */
223 tcp = zalloc ( sizeof ( *tcp ) );
226 DBGC ( tcp, "TCP %p allocated\n", tcp );
227 xfer_init ( &tcp->xfer, &tcp_xfer_operations, &tcp->refcnt );
228 tcp->prev_tcp_state = TCP_CLOSED;
229 tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
230 tcp_dump_state ( tcp );
231 tcp->snd_seq = random();
232 INIT_LIST_HEAD ( &tcp->queue );
233 tcp->timer.expired = tcp_expired;
234 memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
236 /* Bind to local port */
237 bind_port = ( st_local ? st_local->st_port : 0 );
238 if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
241 /* Start timer to initiate SYN */
242 start_timer_nodelay ( &tcp->timer );
244 /* Attach parent interface, transfer reference to connection
247 xfer_plug_plug ( &tcp->xfer, xfer );
248 list_add ( &tcp->list, &tcp_conns );
252 ref_put ( &tcp->refcnt );
257 * Close TCP connection
259 * @v tcp TCP connection
260 * @v rc Reason for close
262 * Closes the data transfer interface. If the TCP state machine is in
263 * a suitable state, the connection will be deleted.
265 static void tcp_close ( struct tcp_connection *tcp, int rc ) {
266 struct io_buffer *iobuf;
267 struct io_buffer *tmp;
269 /* Close data transfer interface */
270 xfer_nullify ( &tcp->xfer );
271 xfer_close ( &tcp->xfer, rc );
272 tcp->xfer_closed = 1;
274 /* If we are in CLOSED, or have otherwise not yet received a
275 * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
278 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
280 /* Transition to CLOSED for the sake of debugging messages */
281 tcp->tcp_state = TCP_CLOSED;
282 tcp_dump_state ( tcp );
284 /* Free any unsent I/O buffers */
285 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
286 list_del ( &iobuf->list );
290 /* Remove from list and drop reference */
291 stop_timer ( &tcp->timer );
292 list_del ( &tcp->list );
293 ref_put ( &tcp->refcnt );
294 DBGC ( tcp, "TCP %p connection deleted\n", tcp );
298 /* If we have not had our SYN acknowledged (i.e. we are in
299 * SYN_RCVD), pretend that it has been acknowledged so that we
300 * can send a FIN without breaking things.
302 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
303 tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
305 /* If we have no data remaining to send, start sending FIN */
306 if ( list_empty ( &tcp->queue ) ) {
307 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
308 tcp_dump_state ( tcp );
312 /***************************************************************************
316 ***************************************************************************
320 * Calculate transmission window
322 * @v tcp TCP connection
323 * @ret len Maximum length that can be sent in a single packet
325 static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
328 /* Not ready if we're not in a suitable connection state */
329 if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
332 /* Length is the minimum of the receiver's window and the path MTU */
334 if ( len > TCP_PATH_MTU )
341 * Process TCP transmit queue
343 * @v tcp TCP connection
344 * @v max_len Maximum length to process
345 * @v dest I/O buffer to fill with data, or NULL
346 * @v remove Remove data from queue
347 * @ret len Length of data processed
349 * This processes at most @c max_len bytes from the TCP connection's
350 * transmit queue. Data will be copied into the @c dest I/O buffer
351 * (if provided) and, if @c remove is true, removed from the transmit
354 static size_t tcp_process_queue ( struct tcp_connection *tcp, size_t max_len,
355 struct io_buffer *dest, int remove ) {
356 struct io_buffer *iobuf;
357 struct io_buffer *tmp;
361 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
362 frag_len = iob_len ( iobuf );
363 if ( frag_len > max_len )
366 memcpy ( iob_put ( dest, frag_len ), iobuf->data,
370 iob_pull ( iobuf, frag_len );
371 if ( ! iob_len ( iobuf ) ) {
372 list_del ( &iobuf->list );
383 * Transmit any outstanding data
385 * @v tcp TCP connection
386 * @v force_send Force sending of packet
388 * Transmits any outstanding data on the connection.
390 * Note that even if an error is returned, the retransmission timer
391 * will have been started if necessary, and so the stack will
392 * eventually attempt to retransmit the failed packet.
394 static int tcp_xmit ( struct tcp_connection *tcp, int force_send ) {
395 struct io_buffer *iobuf;
396 struct tcp_header *tcphdr;
397 struct tcp_mss_option *mssopt;
398 struct tcp_timestamp_padded_option *tsopt;
406 /* If retransmission timer is already running, do nothing */
407 if ( timer_running ( &tcp->timer ) )
410 /* Calculate both the actual (payload) and sequence space
411 * lengths that we wish to transmit.
413 if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
414 len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
418 flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
419 if ( flags & ( TCP_SYN | TCP_FIN ) ) {
420 /* SYN or FIN consume one byte, and we can never send both */
421 assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
424 tcp->snd_sent = seq_len;
426 /* If we have nothing to transmit, stop now */
427 if ( ( seq_len == 0 ) && ! force_send )
430 /* If we are transmitting anything that requires
431 * acknowledgement (i.e. consumes sequence space), start the
432 * retransmission timer. Do this before attempting to
433 * allocate the I/O buffer, in case allocation itself fails.
436 start_timer ( &tcp->timer );
438 /* Allocate I/O buffer */
439 iobuf = alloc_iob ( len + MAX_HDR_LEN );
441 DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
444 iob_reserve ( iobuf, MAX_HDR_LEN );
446 /* Fill data payload from transmit queue */
447 tcp_process_queue ( tcp, len, iobuf, 0 );
449 /* Expand receive window if possible */
450 max_rcv_win = ( ( freemem * 3 ) / 4 );
451 if ( max_rcv_win > TCP_MAX_WINDOW_SIZE )
452 max_rcv_win = TCP_MAX_WINDOW_SIZE;
453 app_win = xfer_window ( &tcp->xfer );
454 if ( max_rcv_win > app_win )
455 max_rcv_win = app_win;
456 max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
457 if ( tcp->rcv_win < max_rcv_win )
458 tcp->rcv_win = max_rcv_win;
460 /* Fill up the TCP header */
461 payload = iobuf->data;
462 if ( flags & TCP_SYN ) {
463 mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
464 mssopt->kind = TCP_OPTION_MSS;
465 mssopt->length = sizeof ( *mssopt );
466 mssopt->mss = htons ( TCP_MSS );
468 if ( ( flags & TCP_SYN ) || tcp->timestamps ) {
469 tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
470 memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
471 tsopt->tsopt.kind = TCP_OPTION_TS;
472 tsopt->tsopt.length = sizeof ( tsopt->tsopt );
473 tsopt->tsopt.tsval = ntohl ( currticks() );
474 tsopt->tsopt.tsecr = ntohl ( tcp->ts_recent );
476 if ( ! ( flags & TCP_SYN ) )
478 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
479 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
480 tcphdr->src = tcp->local_port;
481 tcphdr->dest = tcp->peer.st_port;
482 tcphdr->seq = htonl ( tcp->snd_seq );
483 tcphdr->ack = htonl ( tcp->rcv_ack );
484 tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
485 tcphdr->flags = flags;
486 tcphdr->win = htons ( tcp->rcv_win );
487 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
490 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08zx %08x %4zd",
491 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
492 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
493 ntohl ( tcphdr->ack ), len );
494 tcp_dump_flags ( tcp, tcphdr->flags );
497 /* Transmit packet */
498 return tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
503 * Retransmission timer expired
505 * @v timer Retry timer
506 * @v over Failure indicator
508 static void tcp_expired ( struct retry_timer *timer, int over ) {
509 struct tcp_connection *tcp =
510 container_of ( timer, struct tcp_connection, timer );
511 int graceful_close = TCP_CLOSED_GRACEFULLY ( tcp->tcp_state );
513 DBGC ( tcp, "TCP %p timer %s in %s\n", tcp,
514 ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ) );
516 assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
517 ( tcp->tcp_state == TCP_SYN_RCVD ) ||
518 ( tcp->tcp_state == TCP_ESTABLISHED ) ||
519 ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
520 ( tcp->tcp_state == TCP_TIME_WAIT ) ||
521 ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
522 ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
524 if ( over || graceful_close ) {
525 /* If we have finally timed out and given up, or if
526 * this is the result of a graceful close, terminate
529 tcp->tcp_state = TCP_CLOSED;
530 tcp_dump_state ( tcp );
531 tcp_close ( tcp, -ETIMEDOUT );
533 /* Otherwise, retransmit the packet */
539 * Send RST response to incoming packet
541 * @v in_tcphdr TCP header of incoming packet
542 * @ret rc Return status code
544 static int tcp_xmit_reset ( struct tcp_connection *tcp,
545 struct sockaddr_tcpip *st_dest,
546 struct tcp_header *in_tcphdr ) {
547 struct io_buffer *iobuf;
548 struct tcp_header *tcphdr;
550 /* Allocate space for dataless TX buffer */
551 iobuf = alloc_iob ( MAX_HDR_LEN );
553 DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
556 iob_reserve ( iobuf, MAX_HDR_LEN );
558 /* Construct RST response */
559 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
560 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
561 tcphdr->src = in_tcphdr->dest;
562 tcphdr->dest = in_tcphdr->src;
563 tcphdr->seq = in_tcphdr->ack;
564 tcphdr->ack = in_tcphdr->seq;
565 tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
566 tcphdr->flags = ( TCP_RST | TCP_ACK );
567 tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
568 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
571 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
572 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
573 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
574 ntohl ( tcphdr->ack ), 0 );
575 tcp_dump_flags ( tcp, tcphdr->flags );
578 /* Transmit packet */
579 return tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
580 NULL, &tcphdr->csum );
583 /***************************************************************************
587 ***************************************************************************
591 * Identify TCP connection by local port number
593 * @v local_port Local port (in network-endian order)
594 * @ret tcp TCP connection, or NULL
596 static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
597 struct tcp_connection *tcp;
599 list_for_each_entry ( tcp, &tcp_conns, list ) {
600 if ( tcp->local_port == local_port )
607 * Parse TCP received options
609 * @v tcp TCP connection
610 * @v data Raw options data
611 * @v len Raw options length
612 * @v options Options structure to fill in
614 static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
615 size_t len, struct tcp_options *options ) {
616 const void *end = ( data + len );
617 const struct tcp_option *option;
620 memset ( options, 0, sizeof ( *options ) );
621 while ( data < end ) {
624 if ( kind == TCP_OPTION_END )
626 if ( kind == TCP_OPTION_NOP ) {
632 options->mssopt = data;
635 options->tsopt = data;
638 DBGC ( tcp, "TCP %p received unknown option %d\n",
642 data += option->length;
647 * Consume received sequence space
649 * @v tcp TCP connection
650 * @v seq_len Sequence space length to consume
652 static void tcp_rx_seq ( struct tcp_connection *tcp, size_t seq_len ) {
653 tcp->rcv_ack += seq_len;
654 if ( tcp->rcv_win > seq_len ) {
655 tcp->rcv_win -= seq_len;
662 * Handle TCP received SYN
664 * @v tcp TCP connection
665 * @v seq SEQ value (in host-endian order)
666 * @v options TCP options
667 * @ret rc Return status code
669 static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
670 struct tcp_options *options ) {
672 /* Synchronise sequence numbers on first SYN */
673 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
675 if ( options->tsopt )
679 /* Ignore duplicate SYN */
680 if ( ( tcp->rcv_ack - seq ) > 0 )
683 /* Mark SYN as received and start sending ACKs with each packet */
684 tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
685 TCP_STATE_RCVD ( TCP_SYN ) );
687 /* Acknowledge SYN */
688 tcp_rx_seq ( tcp, 1 );
694 * Handle TCP received ACK
696 * @v tcp TCP connection
697 * @v ack ACK value (in host-endian order)
698 * @v win WIN value (in host-endian order)
699 * @ret rc Return status code
701 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
703 size_t ack_len = ( ack - tcp->snd_seq );
705 unsigned int acked_flags;
707 /* Determine acknowledged flags and data length */
709 acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
710 ( TCP_SYN | TCP_FIN ) );
714 /* Stop retransmission timer if necessary */
715 if ( ack_len == 0 ) {
716 /* Duplicate ACK (or just a packet that isn't
717 * intending to ACK any new data). If the
718 * retransmission timer is running, leave it running
719 * so that we don't immediately retransmit and cause a
720 * sorceror's apprentice syndrome.
722 } else if ( ack_len <= tcp->snd_sent ) {
723 /* ACK of new data. Stop the retransmission timer. */
724 stop_timer ( &tcp->timer );
726 /* Out-of-range (or old duplicate) ACK. Leave the
727 * timer running, as for the ack_len==0 case, to
728 * handle old duplicate ACKs.
730 DBGC ( tcp, "TCP %p received ACK for [%08x,%08zx), "
731 "sent only [%08x,%08x)\n", tcp, tcp->snd_seq,
732 ( tcp->snd_seq + ack_len ), tcp->snd_seq,
733 ( tcp->snd_seq + tcp->snd_sent ) );
734 /* Send RST if an out-of-range ACK is received on a
735 * not-yet-established connection.
737 if ( ! TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) )
741 /* Update SEQ and sent counters, and window size */
746 /* Remove any acknowledged data from transmit queue */
747 tcp_process_queue ( tcp, len, NULL, 1 );
749 /* Mark SYN/FIN as acknowledged if applicable. */
751 tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
753 /* Start sending FIN if we've had all possible data ACKed */
754 if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
755 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
761 * Handle TCP received data
763 * @v tcp TCP connection
764 * @v seq SEQ value (in host-endian order)
765 * @v iobuf I/O buffer
766 * @ret rc Return status code
768 * This function takes ownership of the I/O buffer.
770 static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
771 struct io_buffer *iobuf ) {
776 /* Ignore duplicate or out-of-order data */
777 already_rcvd = ( tcp->rcv_ack - seq );
778 len = iob_len ( iobuf );
779 if ( already_rcvd >= len ) {
783 iob_pull ( iobuf, already_rcvd );
786 /* Deliver data to application */
787 if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 )
790 /* Acknowledge new data */
791 tcp_rx_seq ( tcp, len );
797 * Handle TCP received FIN
799 * @v tcp TCP connection
800 * @v seq SEQ value (in host-endian order)
801 * @ret rc Return status code
803 static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
805 /* Ignore duplicate or out-of-order FIN */
806 if ( ( tcp->rcv_ack - seq ) > 0 )
809 /* Mark FIN as received and acknowledge it */
810 tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
811 tcp_rx_seq ( tcp, 1 );
813 /* Close connection */
814 tcp_close ( tcp, 0 );
820 * Handle TCP received RST
822 * @v tcp TCP connection
823 * @v seq SEQ value (in host-endian order)
824 * @ret rc Return status code
826 static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
828 /* Accept RST only if it falls within the window. If we have
829 * not yet received a SYN, then we have no window to test
830 * against, so fall back to checking that our SYN has been
833 if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
834 if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
837 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
841 /* Abort connection */
842 tcp->tcp_state = TCP_CLOSED;
843 tcp_dump_state ( tcp );
844 tcp_close ( tcp, -ECONNRESET );
850 * Process received packet
852 * @v iobuf I/O buffer
853 * @v st_src Partially-filled source address
854 * @v st_dest Partially-filled destination address
855 * @v pshdr_csum Pseudo-header checksum
856 * @ret rc Return status code
858 static int tcp_rx ( struct io_buffer *iobuf,
859 struct sockaddr_tcpip *st_src,
860 struct sockaddr_tcpip *st_dest __unused,
861 uint16_t pshdr_csum ) {
862 struct tcp_header *tcphdr = iobuf->data;
863 struct tcp_connection *tcp;
864 struct tcp_options options;
875 /* Sanity check packet */
876 if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
877 DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
878 iob_len ( iobuf ), sizeof ( *tcphdr ) );
882 hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
883 if ( hlen < sizeof ( *tcphdr ) ) {
884 DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
885 hlen, sizeof ( *tcphdr ) );
889 if ( hlen > iob_len ( iobuf ) ) {
890 DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
891 hlen, iob_len ( iobuf ) );
895 csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
898 DBG ( "TCP checksum incorrect (is %04x including checksum "
899 "field, should be 0000)\n", csum );
904 /* Parse parameters from header and strip header */
905 tcp = tcp_demux ( tcphdr->dest );
906 start_seq = seq = ntohl ( tcphdr->seq );
907 ack = ntohl ( tcphdr->ack );
908 win = ntohs ( tcphdr->win );
909 flags = tcphdr->flags;
910 tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
911 ( hlen - sizeof ( *tcphdr ) ), &options );
912 iob_pull ( iobuf, hlen );
913 len = iob_len ( iobuf );
916 DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
917 tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
918 ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
919 ( ntohl ( tcphdr->seq ) + len +
920 ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 )), len);
921 tcp_dump_flags ( tcp, tcphdr->flags );
924 /* If no connection was found, send RST */
926 tcp_xmit_reset ( tcp, st_src, tcphdr );
931 /* Handle ACK, if present */
932 if ( flags & TCP_ACK ) {
933 if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
934 tcp_xmit_reset ( tcp, st_src, tcphdr );
939 /* Handle SYN, if present */
940 if ( flags & TCP_SYN ) {
941 tcp_rx_syn ( tcp, seq, &options );
945 /* Handle RST, if present */
946 if ( flags & TCP_RST ) {
947 if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
951 /* Handle new data, if any */
952 tcp_rx_data ( tcp, seq, iobuf );
955 /* Handle FIN, if present */
956 if ( flags & TCP_FIN ) {
957 tcp_rx_fin ( tcp, seq );
961 /* Update timestamp, if present and applicable */
962 if ( ( seq == tcp->rcv_ack ) && options.tsopt )
963 tcp->ts_recent = ntohl ( options.tsopt->tsval );
965 /* Dump out any state change as a result of the received packet */
966 tcp_dump_state ( tcp );
968 /* Send out any pending data. We force sending a reply if either
970 * a) the peer is expecting an ACK (i.e. consumed sequence space), or
971 * b) either end of the packet was outside the receive window
973 * Case (b) enables us to support TCP keepalives using
974 * zero-length packets, which we would otherwise ignore. Note
975 * that for case (b), we need *only* consider zero-length
976 * packets, since non-zero-length packets will already be
977 * caught by case (a).
979 tcp_xmit ( tcp, ( ( start_seq != seq ) ||
980 ( ( seq - tcp->rcv_ack ) > tcp->rcv_win ) ) );
982 /* If this packet was the last we expect to receive, set up
983 * timer to expire and cause the connection to be freed.
985 if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
986 tcp->timer.timeout = ( 2 * TCP_MSL );
987 start_timer ( &tcp->timer );
993 /* Free received packet */
999 struct tcpip_protocol tcp_protocol __tcpip_protocol = {
1002 .tcpip_proto = IP_TCP,
1005 /***************************************************************************
1007 * Data transfer interface
1009 ***************************************************************************
1015 * @v xfer Data transfer interface
1016 * @v rc Reason for close
1018 static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
1019 struct tcp_connection *tcp =
1020 container_of ( xfer, struct tcp_connection, xfer );
1022 /* Close data transfer interface */
1023 tcp_close ( tcp, rc );
1025 /* Transmit FIN, if possible */
1026 tcp_xmit ( tcp, 0 );
1030 * Check flow control window
1032 * @v xfer Data transfer interface
1033 * @ret len Length of window
1035 static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
1036 struct tcp_connection *tcp =
1037 container_of ( xfer, struct tcp_connection, xfer );
1039 /* Not ready if data queue is non-empty. This imposes a limit
1040 * of only one unACKed packet in the TX queue at any time; we
1041 * do this to conserve memory usage.
1043 if ( ! list_empty ( &tcp->queue ) )
1046 /* Return TCP window length */
1047 return tcp_xmit_win ( tcp );
1051 * Deliver datagram as I/O buffer
1053 * @v xfer Data transfer interface
1054 * @v iobuf Datagram I/O buffer
1055 * @v meta Data transfer metadata
1056 * @ret rc Return status code
1058 static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
1059 struct io_buffer *iobuf,
1060 struct xfer_metadata *meta __unused ) {
1061 struct tcp_connection *tcp =
1062 container_of ( xfer, struct tcp_connection, xfer );
1064 /* Enqueue packet */
1065 list_add_tail ( &iobuf->list, &tcp->queue );
1067 /* Transmit data, if possible */
1068 tcp_xmit ( tcp, 0 );
1073 /** TCP data transfer interface operations */
1074 static struct xfer_interface_operations tcp_xfer_operations = {
1075 .close = tcp_xfer_close,
1076 .vredirect = ignore_xfer_vredirect,
1077 .window = tcp_xfer_window,
1078 .alloc_iob = default_xfer_alloc_iob,
1079 .deliver_iob = tcp_xfer_deliver_iob,
1080 .deliver_raw = xfer_deliver_as_iob,
1083 /***************************************************************************
1087 ***************************************************************************
1090 /** TCP socket opener */
1091 struct socket_opener tcp_socket_opener __socket_opener = {
1092 .semantics = TCP_SOCK_STREAM,
1098 int tcp_sock_stream = TCP_SOCK_STREAM;
1103 * @v xfer Data transfer interface
1105 * @ret rc Return status code
1107 static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
1108 struct sockaddr_tcpip peer;
1114 memset ( &peer, 0, sizeof ( peer ) );
1115 peer.st_port = htons ( uri_port ( uri, 0 ) );
1116 return xfer_open_named_socket ( xfer, SOCK_STREAM,
1117 ( struct sockaddr * ) &peer,
1121 /** TCP URI opener */
1122 struct uri_opener tcp_uri_opener __uri_opener = {
1124 .open = tcp_open_uri,