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;
407 /* If retransmission timer is already running, do nothing */
408 if ( timer_running ( &tcp->timer ) )
411 /* Calculate both the actual (payload) and sequence space
412 * lengths that we wish to transmit.
414 if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
415 len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
419 flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
420 if ( flags & ( TCP_SYN | TCP_FIN ) ) {
421 /* SYN or FIN consume one byte, and we can never send both */
422 assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
425 tcp->snd_sent = seq_len;
427 /* If we have nothing to transmit, stop now */
428 if ( ( seq_len == 0 ) && ! force_send )
431 /* If we are transmitting anything that requires
432 * acknowledgement (i.e. consumes sequence space), start the
433 * retransmission timer. Do this before attempting to
434 * allocate the I/O buffer, in case allocation itself fails.
437 start_timer ( &tcp->timer );
439 /* Allocate I/O buffer */
440 iobuf = alloc_iob ( len + MAX_HDR_LEN );
442 DBGC ( tcp, "TCP %p could not allocate iobuf for %08x..%08x "
443 "%08x\n", tcp, tcp->snd_seq, ( tcp->snd_seq + seq_len ),
447 iob_reserve ( iobuf, MAX_HDR_LEN );
449 /* Fill data payload from transmit queue */
450 tcp_process_queue ( tcp, len, iobuf, 0 );
452 /* Expand receive window if possible */
453 max_rcv_win = ( ( freemem * 3 ) / 4 );
454 if ( max_rcv_win > TCP_MAX_WINDOW_SIZE )
455 max_rcv_win = TCP_MAX_WINDOW_SIZE;
456 app_win = xfer_window ( &tcp->xfer );
457 if ( max_rcv_win > app_win )
458 max_rcv_win = app_win;
459 max_rcv_win &= ~0x03; /* Keep everything dword-aligned */
460 if ( tcp->rcv_win < max_rcv_win )
461 tcp->rcv_win = max_rcv_win;
463 /* Fill up the TCP header */
464 payload = iobuf->data;
465 if ( flags & TCP_SYN ) {
466 mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
467 mssopt->kind = TCP_OPTION_MSS;
468 mssopt->length = sizeof ( *mssopt );
469 mssopt->mss = htons ( TCP_MSS );
471 if ( ( flags & TCP_SYN ) || tcp->timestamps ) {
472 tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
473 memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
474 tsopt->tsopt.kind = TCP_OPTION_TS;
475 tsopt->tsopt.length = sizeof ( tsopt->tsopt );
476 tsopt->tsopt.tsval = ntohl ( currticks() );
477 tsopt->tsopt.tsecr = ntohl ( tcp->ts_recent );
479 if ( ! ( flags & TCP_SYN ) )
481 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
482 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
483 tcphdr->src = tcp->local_port;
484 tcphdr->dest = tcp->peer.st_port;
485 tcphdr->seq = htonl ( tcp->snd_seq );
486 tcphdr->ack = htonl ( tcp->rcv_ack );
487 tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
488 tcphdr->flags = flags;
489 tcphdr->win = htons ( tcp->rcv_win );
490 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
493 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08zx %08x %4zd",
494 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
495 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
496 ntohl ( tcphdr->ack ), len );
497 tcp_dump_flags ( tcp, tcphdr->flags );
500 /* Transmit packet */
501 if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, &tcp->peer, NULL,
502 &tcphdr->csum ) ) != 0 ) {
503 DBGC ( tcp, "TCP %p could not transmit %08x..%08x %08x: %s\n",
504 tcp, tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ),
505 tcp->rcv_ack, strerror ( rc ) );
513 * Retransmission timer expired
515 * @v timer Retry timer
516 * @v over Failure indicator
518 static void tcp_expired ( struct retry_timer *timer, int over ) {
519 struct tcp_connection *tcp =
520 container_of ( timer, struct tcp_connection, timer );
521 int graceful_close = TCP_CLOSED_GRACEFULLY ( tcp->tcp_state );
523 DBGC ( tcp, "TCP %p timer %s in %s for %08x..%08x %08x\n", tcp,
524 ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ),
525 tcp->snd_seq, ( tcp->snd_seq + tcp->snd_sent ), tcp->rcv_ack );
527 assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
528 ( tcp->tcp_state == TCP_SYN_RCVD ) ||
529 ( tcp->tcp_state == TCP_ESTABLISHED ) ||
530 ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
531 ( tcp->tcp_state == TCP_TIME_WAIT ) ||
532 ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
533 ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
535 if ( over || graceful_close ) {
536 /* If we have finally timed out and given up, or if
537 * this is the result of a graceful close, terminate
540 tcp->tcp_state = TCP_CLOSED;
541 tcp_dump_state ( tcp );
542 tcp_close ( tcp, -ETIMEDOUT );
544 /* Otherwise, retransmit the packet */
550 * Send RST response to incoming packet
552 * @v in_tcphdr TCP header of incoming packet
553 * @ret rc Return status code
555 static int tcp_xmit_reset ( struct tcp_connection *tcp,
556 struct sockaddr_tcpip *st_dest,
557 struct tcp_header *in_tcphdr ) {
558 struct io_buffer *iobuf;
559 struct tcp_header *tcphdr;
562 /* Allocate space for dataless TX buffer */
563 iobuf = alloc_iob ( MAX_HDR_LEN );
565 DBGC ( tcp, "TCP %p could not allocate iobuf for RST "
566 "%08x..%08x %08x\n", tcp, ntohl ( in_tcphdr->ack ),
567 ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ) );
570 iob_reserve ( iobuf, MAX_HDR_LEN );
572 /* Construct RST response */
573 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
574 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
575 tcphdr->src = in_tcphdr->dest;
576 tcphdr->dest = in_tcphdr->src;
577 tcphdr->seq = in_tcphdr->ack;
578 tcphdr->ack = in_tcphdr->seq;
579 tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
580 tcphdr->flags = ( TCP_RST | TCP_ACK );
581 tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
582 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
585 DBGC2 ( tcp, "TCP %p TX %d->%d %08x..%08x %08x %4d",
586 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
587 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
588 ntohl ( tcphdr->ack ), 0 );
589 tcp_dump_flags ( tcp, tcphdr->flags );
592 /* Transmit packet */
593 if ( ( rc = tcpip_tx ( iobuf, &tcp_protocol, NULL, st_dest,
594 NULL, &tcphdr->csum ) ) != 0 ) {
595 DBGC ( tcp, "TCP %p could not transmit RST %08x..%08x %08x: "
596 "%s\n", tcp, ntohl ( in_tcphdr->ack ),
597 ntohl ( in_tcphdr->ack ), ntohl ( in_tcphdr->seq ),
605 /***************************************************************************
609 ***************************************************************************
613 * Identify TCP connection by local port number
615 * @v local_port Local port (in network-endian order)
616 * @ret tcp TCP connection, or NULL
618 static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
619 struct tcp_connection *tcp;
621 list_for_each_entry ( tcp, &tcp_conns, list ) {
622 if ( tcp->local_port == local_port )
629 * Parse TCP received options
631 * @v tcp TCP connection
632 * @v data Raw options data
633 * @v len Raw options length
634 * @v options Options structure to fill in
636 static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
637 size_t len, struct tcp_options *options ) {
638 const void *end = ( data + len );
639 const struct tcp_option *option;
642 memset ( options, 0, sizeof ( *options ) );
643 while ( data < end ) {
646 if ( kind == TCP_OPTION_END )
648 if ( kind == TCP_OPTION_NOP ) {
654 options->mssopt = data;
657 options->tsopt = data;
660 DBGC ( tcp, "TCP %p received unknown option %d\n",
664 data += option->length;
669 * Consume received sequence space
671 * @v tcp TCP connection
672 * @v seq_len Sequence space length to consume
674 static void tcp_rx_seq ( struct tcp_connection *tcp, size_t seq_len ) {
675 tcp->rcv_ack += seq_len;
676 if ( tcp->rcv_win > seq_len ) {
677 tcp->rcv_win -= seq_len;
684 * Handle TCP received SYN
686 * @v tcp TCP connection
687 * @v seq SEQ value (in host-endian order)
688 * @v options TCP options
689 * @ret rc Return status code
691 static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
692 struct tcp_options *options ) {
694 /* Synchronise sequence numbers on first SYN */
695 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
697 if ( options->tsopt )
701 /* Ignore duplicate SYN */
702 if ( ( tcp->rcv_ack - seq ) > 0 )
705 /* Mark SYN as received and start sending ACKs with each packet */
706 tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
707 TCP_STATE_RCVD ( TCP_SYN ) );
709 /* Acknowledge SYN */
710 tcp_rx_seq ( tcp, 1 );
716 * Handle TCP received ACK
718 * @v tcp TCP connection
719 * @v ack ACK value (in host-endian order)
720 * @v win WIN value (in host-endian order)
721 * @ret rc Return status code
723 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
725 size_t ack_len = ( ack - tcp->snd_seq );
727 unsigned int acked_flags;
729 /* Determine acknowledged flags and data length */
731 acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
732 ( TCP_SYN | TCP_FIN ) );
736 /* Stop retransmission timer if necessary */
737 if ( ack_len == 0 ) {
738 /* Duplicate ACK (or just a packet that isn't
739 * intending to ACK any new data). If the
740 * retransmission timer is running, leave it running
741 * so that we don't immediately retransmit and cause a
742 * sorceror's apprentice syndrome.
744 } else if ( ack_len <= tcp->snd_sent ) {
745 /* ACK of new data. Stop the retransmission timer. */
746 stop_timer ( &tcp->timer );
748 /* Out-of-range (or old duplicate) ACK. Leave the
749 * timer running, as for the ack_len==0 case, to
750 * handle old duplicate ACKs.
752 DBGC ( tcp, "TCP %p received ACK for %08x..%08zx, "
753 "sent only %08x..%08x\n", tcp, tcp->snd_seq,
754 ( tcp->snd_seq + ack_len ), tcp->snd_seq,
755 ( tcp->snd_seq + tcp->snd_sent ) );
756 /* Send RST if an out-of-range ACK is received on a
757 * not-yet-established connection.
759 if ( ! TCP_HAS_BEEN_ESTABLISHED ( tcp->tcp_state ) )
763 /* Update SEQ and sent counters, and window size */
768 /* Remove any acknowledged data from transmit queue */
769 tcp_process_queue ( tcp, len, NULL, 1 );
771 /* Mark SYN/FIN as acknowledged if applicable. */
773 tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
775 /* Start sending FIN if we've had all possible data ACKed */
776 if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
777 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
783 * Handle TCP received data
785 * @v tcp TCP connection
786 * @v seq SEQ value (in host-endian order)
787 * @v iobuf I/O buffer
788 * @ret rc Return status code
790 * This function takes ownership of the I/O buffer.
792 static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
793 struct io_buffer *iobuf ) {
798 /* Ignore duplicate or out-of-order data */
799 already_rcvd = ( tcp->rcv_ack - seq );
800 len = iob_len ( iobuf );
801 if ( already_rcvd >= len ) {
805 iob_pull ( iobuf, already_rcvd );
808 /* Deliver data to application */
809 if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 ) {
810 DBGC ( tcp, "TCP %p could not deliver %08x..%08x: %s\n",
811 tcp, seq, ( seq + len ), strerror ( rc ) );
815 /* Acknowledge new data */
816 tcp_rx_seq ( tcp, len );
822 * Handle TCP received FIN
824 * @v tcp TCP connection
825 * @v seq SEQ value (in host-endian order)
826 * @ret rc Return status code
828 static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
830 /* Ignore duplicate or out-of-order FIN */
831 if ( ( tcp->rcv_ack - seq ) > 0 )
834 /* Mark FIN as received and acknowledge it */
835 tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
836 tcp_rx_seq ( tcp, 1 );
838 /* Close connection */
839 tcp_close ( tcp, 0 );
845 * Handle TCP received RST
847 * @v tcp TCP connection
848 * @v seq SEQ value (in host-endian order)
849 * @ret rc Return status code
851 static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
853 /* Accept RST only if it falls within the window. If we have
854 * not yet received a SYN, then we have no window to test
855 * against, so fall back to checking that our SYN has been
858 if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
859 if ( ( seq - tcp->rcv_ack ) >= tcp->rcv_win )
862 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
866 /* Abort connection */
867 tcp->tcp_state = TCP_CLOSED;
868 tcp_dump_state ( tcp );
869 tcp_close ( tcp, -ECONNRESET );
871 DBGC ( tcp, "TCP %p connection reset by peer\n", tcp );
876 * Process received packet
878 * @v iobuf I/O buffer
879 * @v st_src Partially-filled source address
880 * @v st_dest Partially-filled destination address
881 * @v pshdr_csum Pseudo-header checksum
882 * @ret rc Return status code
884 static int tcp_rx ( struct io_buffer *iobuf,
885 struct sockaddr_tcpip *st_src,
886 struct sockaddr_tcpip *st_dest __unused,
887 uint16_t pshdr_csum ) {
888 struct tcp_header *tcphdr = iobuf->data;
889 struct tcp_connection *tcp;
890 struct tcp_options options;
901 /* Sanity check packet */
902 if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
903 DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
904 iob_len ( iobuf ), sizeof ( *tcphdr ) );
908 hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
909 if ( hlen < sizeof ( *tcphdr ) ) {
910 DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
911 hlen, sizeof ( *tcphdr ) );
915 if ( hlen > iob_len ( iobuf ) ) {
916 DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
917 hlen, iob_len ( iobuf ) );
921 csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data,
924 DBG ( "TCP checksum incorrect (is %04x including checksum "
925 "field, should be 0000)\n", csum );
930 /* Parse parameters from header and strip header */
931 tcp = tcp_demux ( tcphdr->dest );
932 start_seq = seq = ntohl ( tcphdr->seq );
933 ack = ntohl ( tcphdr->ack );
934 win = ntohs ( tcphdr->win );
935 flags = tcphdr->flags;
936 tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
937 ( hlen - sizeof ( *tcphdr ) ), &options );
938 iob_pull ( iobuf, hlen );
939 len = iob_len ( iobuf );
942 DBGC2 ( tcp, "TCP %p RX %d<-%d %08x %08x..%08zx %4zd",
943 tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
944 ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
945 ( ntohl ( tcphdr->seq ) + len +
946 ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 )), len);
947 tcp_dump_flags ( tcp, tcphdr->flags );
950 /* If no connection was found, send RST */
952 tcp_xmit_reset ( tcp, st_src, tcphdr );
957 /* Handle ACK, if present */
958 if ( flags & TCP_ACK ) {
959 if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
960 tcp_xmit_reset ( tcp, st_src, tcphdr );
965 /* Handle SYN, if present */
966 if ( flags & TCP_SYN ) {
967 tcp_rx_syn ( tcp, seq, &options );
971 /* Handle RST, if present */
972 if ( flags & TCP_RST ) {
973 if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
977 /* Handle new data, if any */
978 tcp_rx_data ( tcp, seq, iobuf );
981 /* Handle FIN, if present */
982 if ( flags & TCP_FIN ) {
983 tcp_rx_fin ( tcp, seq );
987 /* Update timestamp, if present and applicable */
988 if ( ( seq == tcp->rcv_ack ) && options.tsopt )
989 tcp->ts_recent = ntohl ( options.tsopt->tsval );
991 /* Dump out any state change as a result of the received packet */
992 tcp_dump_state ( tcp );
994 /* Send out any pending data. We force sending a reply if either
996 * a) the peer is expecting an ACK (i.e. consumed sequence space), or
997 * b) either end of the packet was outside the receive window
999 * Case (b) enables us to support TCP keepalives using
1000 * zero-length packets, which we would otherwise ignore. Note
1001 * that for case (b), we need *only* consider zero-length
1002 * packets, since non-zero-length packets will already be
1003 * caught by case (a).
1005 tcp_xmit ( tcp, ( ( start_seq != seq ) ||
1006 ( ( seq - tcp->rcv_ack ) > tcp->rcv_win ) ) );
1008 /* If this packet was the last we expect to receive, set up
1009 * timer to expire and cause the connection to be freed.
1011 if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
1012 tcp->timer.timeout = ( 2 * TCP_MSL );
1013 start_timer ( &tcp->timer );
1019 /* Free received packet */
1025 struct tcpip_protocol tcp_protocol __tcpip_protocol = {
1028 .tcpip_proto = IP_TCP,
1031 /***************************************************************************
1033 * Data transfer interface
1035 ***************************************************************************
1041 * @v xfer Data transfer interface
1042 * @v rc Reason for close
1044 static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
1045 struct tcp_connection *tcp =
1046 container_of ( xfer, struct tcp_connection, xfer );
1048 /* Close data transfer interface */
1049 tcp_close ( tcp, rc );
1051 /* Transmit FIN, if possible */
1052 tcp_xmit ( tcp, 0 );
1056 * Check flow control window
1058 * @v xfer Data transfer interface
1059 * @ret len Length of window
1061 static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
1062 struct tcp_connection *tcp =
1063 container_of ( xfer, struct tcp_connection, xfer );
1065 /* Not ready if data queue is non-empty. This imposes a limit
1066 * of only one unACKed packet in the TX queue at any time; we
1067 * do this to conserve memory usage.
1069 if ( ! list_empty ( &tcp->queue ) )
1072 /* Return TCP window length */
1073 return tcp_xmit_win ( tcp );
1077 * Deliver datagram as I/O buffer
1079 * @v xfer Data transfer interface
1080 * @v iobuf Datagram I/O buffer
1081 * @v meta Data transfer metadata
1082 * @ret rc Return status code
1084 static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
1085 struct io_buffer *iobuf,
1086 struct xfer_metadata *meta __unused ) {
1087 struct tcp_connection *tcp =
1088 container_of ( xfer, struct tcp_connection, xfer );
1090 /* Enqueue packet */
1091 list_add_tail ( &iobuf->list, &tcp->queue );
1093 /* Transmit data, if possible */
1094 tcp_xmit ( tcp, 0 );
1099 /** TCP data transfer interface operations */
1100 static struct xfer_interface_operations tcp_xfer_operations = {
1101 .close = tcp_xfer_close,
1102 .vredirect = ignore_xfer_vredirect,
1103 .window = tcp_xfer_window,
1104 .alloc_iob = default_xfer_alloc_iob,
1105 .deliver_iob = tcp_xfer_deliver_iob,
1106 .deliver_raw = xfer_deliver_as_iob,
1109 /***************************************************************************
1113 ***************************************************************************
1116 /** TCP socket opener */
1117 struct socket_opener tcp_socket_opener __socket_opener = {
1118 .semantics = TCP_SOCK_STREAM,
1124 int tcp_sock_stream = TCP_SOCK_STREAM;
1129 * @v xfer Data transfer interface
1131 * @ret rc Return status code
1133 static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
1134 struct sockaddr_tcpip peer;
1140 memset ( &peer, 0, sizeof ( peer ) );
1141 peer.st_port = htons ( uri_port ( uri, 0 ) );
1142 return xfer_open_named_socket ( xfer, SOCK_STREAM,
1143 ( struct sockaddr * ) &peer,
1147 /** TCP URI opener */
1148 struct uri_opener tcp_uri_opener __uri_opener = {
1150 .open = tcp_open_uri,