Adding debian version 3.70~pre8+dfsg-1.
[syslinux-debian/hramrach.git] / gpxe / src / net / tcp.c
blobda8e87b4b4360b0fe90d3d6a7c4268ee3541f233
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>
18 /** @file
20 * TCP protocol
24 /** A TCP connection */
25 struct tcp_connection {
26 /** Reference counter */
27 struct refcnt refcnt;
28 /** List of TCP connections */
29 struct list_head list;
31 /** Data transfer interface */
32 struct xfer_interface xfer;
33 /** Data transfer interface closed flag */
34 int xfer_closed;
36 /** Remote socket address */
37 struct sockaddr_tcpip peer;
38 /** Local port, in network byte order */
39 unsigned int local_port;
41 /** Current TCP state */
42 unsigned int tcp_state;
43 /** Previous TCP state
45 * Maintained only for debug messages
47 unsigned int prev_tcp_state;
48 /** Current sequence number
50 * Equivalent to SND.UNA in RFC 793 terminology.
52 uint32_t snd_seq;
53 /** Unacknowledged sequence count
55 * Equivalent to (SND.NXT-SND.UNA) in RFC 793 terminology.
57 uint32_t snd_sent;
58 /** Send window
60 * Equivalent to SND.WND in RFC 793 terminology
62 uint32_t snd_win;
63 /** Current acknowledgement number
65 * Equivalent to RCV.NXT in RFC 793 terminology.
67 uint32_t rcv_ack;
68 /** Most recent received timestamp
70 * Equivalent to TS.Recent in RFC 1323 terminology.
72 uint32_t ts_recent;
73 /** Timestamps enabled */
74 int timestamps;
76 /** Transmit queue */
77 struct list_head queue;
78 /** Retransmission timer */
79 struct retry_timer timer;
82 /**
83 * List of registered TCP connections
85 static LIST_HEAD ( tcp_conns );
87 /* Forward declarations */
88 static struct xfer_interface_operations tcp_xfer_operations;
89 static void tcp_expired ( struct retry_timer *timer, int over );
90 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
91 uint32_t win );
93 /**
94 * Name TCP state
96 * @v state TCP state
97 * @ret name Name of TCP state
99 static inline __attribute__ (( always_inline )) const char *
100 tcp_state ( int state ) {
101 switch ( state ) {
102 case TCP_CLOSED: return "CLOSED";
103 case TCP_LISTEN: return "LISTEN";
104 case TCP_SYN_SENT: return "SYN_SENT";
105 case TCP_SYN_RCVD: return "SYN_RCVD";
106 case TCP_ESTABLISHED: return "ESTABLISHED";
107 case TCP_FIN_WAIT_1: return "FIN_WAIT_1";
108 case TCP_FIN_WAIT_2: return "FIN_WAIT_2";
109 case TCP_CLOSING_OR_LAST_ACK: return "CLOSING/LAST_ACK";
110 case TCP_TIME_WAIT: return "TIME_WAIT";
111 case TCP_CLOSE_WAIT: return "CLOSE_WAIT";
112 default: return "INVALID";
117 * Dump TCP state transition
119 * @v tcp TCP connection
121 static inline __attribute__ (( always_inline )) void
122 tcp_dump_state ( struct tcp_connection *tcp ) {
124 if ( tcp->tcp_state != tcp->prev_tcp_state ) {
125 DBGC ( tcp, "TCP %p transitioned from %s to %s\n", tcp,
126 tcp_state ( tcp->prev_tcp_state ),
127 tcp_state ( tcp->tcp_state ) );
129 tcp->prev_tcp_state = tcp->tcp_state;
133 * Dump TCP flags
135 * @v flags TCP flags
137 static inline __attribute__ (( always_inline )) void
138 tcp_dump_flags ( struct tcp_connection *tcp, unsigned int flags ) {
139 if ( flags & TCP_RST )
140 DBGC ( tcp, " RST" );
141 if ( flags & TCP_SYN )
142 DBGC ( tcp, " SYN" );
143 if ( flags & TCP_PSH )
144 DBGC ( tcp, " PSH" );
145 if ( flags & TCP_FIN )
146 DBGC ( tcp, " FIN" );
147 if ( flags & TCP_ACK )
148 DBGC ( tcp, " ACK" );
151 /***************************************************************************
153 * Open and close
155 ***************************************************************************
159 * Bind TCP connection to local port
161 * @v tcp TCP connection
162 * @v port Local port number, in network-endian order
163 * @ret rc Return status code
165 * If the port is 0, the connection is assigned an available port
166 * between 1024 and 65535.
168 static int tcp_bind ( struct tcp_connection *tcp, unsigned int port ) {
169 struct tcp_connection *existing;
170 static uint16_t try_port = 1023;
172 /* If no port specified, find the first available port */
173 if ( ! port ) {
174 while ( try_port ) {
175 try_port++;
176 if ( try_port < 1024 )
177 continue;
178 if ( tcp_bind ( tcp, htons ( try_port ) ) == 0 )
179 return 0;
181 DBGC ( tcp, "TCP %p could not bind: no free ports\n", tcp );
182 return -EADDRINUSE;
185 /* Attempt bind to local port */
186 list_for_each_entry ( existing, &tcp_conns, list ) {
187 if ( existing->local_port == port ) {
188 DBGC ( tcp, "TCP %p could not bind: port %d in use\n",
189 tcp, ntohs ( port ) );
190 return -EADDRINUSE;
193 tcp->local_port = port;
195 DBGC ( tcp, "TCP %p bound to port %d\n", tcp, ntohs ( port ) );
196 return 0;
200 * Open a TCP connection
202 * @v xfer Data transfer interface
203 * @v peer Peer socket address
204 * @v local Local socket address, or NULL
205 * @ret rc Return status code
207 static int tcp_open ( struct xfer_interface *xfer, struct sockaddr *peer,
208 struct sockaddr *local ) {
209 struct sockaddr_tcpip *st_peer = ( struct sockaddr_tcpip * ) peer;
210 struct sockaddr_tcpip *st_local = ( struct sockaddr_tcpip * ) local;
211 struct tcp_connection *tcp;
212 unsigned int bind_port;
213 int rc;
215 /* Allocate and initialise structure */
216 tcp = zalloc ( sizeof ( *tcp ) );
217 if ( ! tcp )
218 return -ENOMEM;
219 DBGC ( tcp, "TCP %p allocated\n", tcp );
220 xfer_init ( &tcp->xfer, &tcp_xfer_operations, &tcp->refcnt );
221 tcp->prev_tcp_state = TCP_CLOSED;
222 tcp->tcp_state = TCP_STATE_SENT ( TCP_SYN );
223 tcp_dump_state ( tcp );
224 tcp->snd_seq = random();
225 INIT_LIST_HEAD ( &tcp->queue );
226 tcp->timer.expired = tcp_expired;
227 memcpy ( &tcp->peer, st_peer, sizeof ( tcp->peer ) );
229 /* Bind to local port */
230 bind_port = ( st_local ? st_local->st_port : 0 );
231 if ( ( rc = tcp_bind ( tcp, bind_port ) ) != 0 )
232 goto err;
234 /* Start timer to initiate SYN */
235 start_timer_nodelay ( &tcp->timer );
237 /* Attach parent interface, transfer reference to connection
238 * list and return
240 xfer_plug_plug ( &tcp->xfer, xfer );
241 list_add ( &tcp->list, &tcp_conns );
242 return 0;
244 err:
245 ref_put ( &tcp->refcnt );
246 return rc;
250 * Close TCP connection
252 * @v tcp TCP connection
253 * @v rc Reason for close
255 * Closes the data transfer interface. If the TCP state machine is in
256 * a suitable state, the connection will be deleted.
258 static void tcp_close ( struct tcp_connection *tcp, int rc ) {
259 struct io_buffer *iobuf;
260 struct io_buffer *tmp;
262 /* Close data transfer interface */
263 xfer_nullify ( &tcp->xfer );
264 xfer_close ( &tcp->xfer, rc );
265 tcp->xfer_closed = 1;
267 /* If we are in CLOSED, or have otherwise not yet received a
268 * SYN (i.e. we are in LISTEN or SYN_SENT), just delete the
269 * connection.
271 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
273 /* Transition to CLOSED for the sake of debugging messages */
274 tcp->tcp_state = TCP_CLOSED;
275 tcp_dump_state ( tcp );
277 /* Free any unsent I/O buffers */
278 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
279 list_del ( &iobuf->list );
280 free_iob ( iobuf );
283 /* Remove from list and drop reference */
284 stop_timer ( &tcp->timer );
285 list_del ( &tcp->list );
286 ref_put ( &tcp->refcnt );
287 DBGC ( tcp, "TCP %p connection deleted\n", tcp );
288 return;
291 /* If we have not had our SYN acknowledged (i.e. we are in
292 * SYN_RCVD), pretend that it has been acknowledged so that we
293 * can send a FIN without breaking things.
295 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
296 tcp_rx_ack ( tcp, ( tcp->snd_seq + 1 ), 0 );
298 /* If we have no data remaining to send, start sending FIN */
299 if ( list_empty ( &tcp->queue ) ) {
300 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
301 tcp_dump_state ( tcp );
305 /***************************************************************************
307 * Transmit data path
309 ***************************************************************************
313 * Calculate transmission window
315 * @v tcp TCP connection
316 * @ret len Maximum length that can be sent in a single packet
318 static size_t tcp_xmit_win ( struct tcp_connection *tcp ) {
319 size_t len;
321 /* Not ready if we're not in a suitable connection state */
322 if ( ! TCP_CAN_SEND_DATA ( tcp->tcp_state ) )
323 return 0;
325 /* Length is the minimum of the receiver's window and the path MTU */
326 len = tcp->snd_win;
327 if ( len > TCP_PATH_MTU )
328 len = TCP_PATH_MTU;
330 return len;
334 * Process TCP transmit queue
336 * @v tcp TCP connection
337 * @v max_len Maximum length to process
338 * @v dest I/O buffer to fill with data, or NULL
339 * @v remove Remove data from queue
340 * @ret len Length of data processed
342 * This processes at most @c max_len bytes from the TCP connection's
343 * transmit queue. Data will be copied into the @c dest I/O buffer
344 * (if provided) and, if @c remove is true, removed from the transmit
345 * queue.
347 static size_t tcp_process_queue ( struct tcp_connection *tcp, size_t max_len,
348 struct io_buffer *dest, int remove ) {
349 struct io_buffer *iobuf;
350 struct io_buffer *tmp;
351 size_t frag_len;
352 size_t len = 0;
354 list_for_each_entry_safe ( iobuf, tmp, &tcp->queue, list ) {
355 frag_len = iob_len ( iobuf );
356 if ( frag_len > max_len )
357 frag_len = max_len;
358 if ( dest ) {
359 memcpy ( iob_put ( dest, frag_len ), iobuf->data,
360 frag_len );
362 if ( remove ) {
363 iob_pull ( iobuf, frag_len );
364 if ( ! iob_len ( iobuf ) ) {
365 list_del ( &iobuf->list );
366 free_iob ( iobuf );
369 len += frag_len;
370 max_len -= frag_len;
372 return len;
376 * Transmit any outstanding data
378 * @v tcp TCP connection
379 * @v force_send Force sending of packet
381 * Transmits any outstanding data on the connection.
383 * Note that even if an error is returned, the retransmission timer
384 * will have been started if necessary, and so the stack will
385 * eventually attempt to retransmit the failed packet.
387 static int tcp_xmit ( struct tcp_connection *tcp, int force_send ) {
388 struct io_buffer *iobuf;
389 struct tcp_header *tcphdr;
390 struct tcp_mss_option *mssopt;
391 struct tcp_timestamp_padded_option *tsopt;
392 void *payload;
393 unsigned int flags;
394 size_t len = 0;
395 size_t seq_len;
396 size_t app_win;
397 size_t rcv_win;
399 /* If retransmission timer is already running, do nothing */
400 if ( timer_running ( &tcp->timer ) )
401 return 0;
403 /* Calculate both the actual (payload) and sequence space
404 * lengths that we wish to transmit.
406 if ( TCP_CAN_SEND_DATA ( tcp->tcp_state ) ) {
407 len = tcp_process_queue ( tcp, tcp_xmit_win ( tcp ),
408 NULL, 0 );
410 seq_len = len;
411 flags = TCP_FLAGS_SENDING ( tcp->tcp_state );
412 if ( flags & ( TCP_SYN | TCP_FIN ) ) {
413 /* SYN or FIN consume one byte, and we can never send both */
414 assert ( ! ( ( flags & TCP_SYN ) && ( flags & TCP_FIN ) ) );
415 seq_len++;
417 tcp->snd_sent = seq_len;
419 /* If we have nothing to transmit, stop now */
420 if ( ( seq_len == 0 ) && ! force_send )
421 return 0;
423 /* If we are transmitting anything that requires
424 * acknowledgement (i.e. consumes sequence space), start the
425 * retransmission timer. Do this before attempting to
426 * allocate the I/O buffer, in case allocation itself fails.
428 if ( seq_len )
429 start_timer ( &tcp->timer );
431 /* Allocate I/O buffer */
432 iobuf = alloc_iob ( len + MAX_HDR_LEN );
433 if ( ! iobuf ) {
434 DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
435 return -ENOMEM;
437 iob_reserve ( iobuf, MAX_HDR_LEN );
439 /* Fill data payload from transmit queue */
440 tcp_process_queue ( tcp, len, iobuf, 0 );
442 /* Estimate window size */
443 rcv_win = ( ( freemem * 3 ) / 4 );
444 if ( rcv_win > TCP_MAX_WINDOW_SIZE )
445 rcv_win = TCP_MAX_WINDOW_SIZE;
446 app_win = xfer_window ( &tcp->xfer );
447 if ( rcv_win > app_win )
448 rcv_win = app_win;
449 rcv_win &= ~0x03; /* Keep everything dword-aligned */
451 /* Fill up the TCP header */
452 payload = iobuf->data;
453 if ( flags & TCP_SYN ) {
454 mssopt = iob_push ( iobuf, sizeof ( *mssopt ) );
455 mssopt->kind = TCP_OPTION_MSS;
456 mssopt->length = sizeof ( *mssopt );
457 mssopt->mss = htons ( TCP_MSS );
459 if ( ( flags & TCP_SYN ) || tcp->timestamps ) {
460 tsopt = iob_push ( iobuf, sizeof ( *tsopt ) );
461 memset ( tsopt->nop, TCP_OPTION_NOP, sizeof ( tsopt->nop ) );
462 tsopt->tsopt.kind = TCP_OPTION_TS;
463 tsopt->tsopt.length = sizeof ( tsopt->tsopt );
464 tsopt->tsopt.tsval = ntohl ( currticks() );
465 tsopt->tsopt.tsecr = ntohl ( tcp->ts_recent );
467 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
468 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
469 tcphdr->src = tcp->local_port;
470 tcphdr->dest = tcp->peer.st_port;
471 tcphdr->seq = htonl ( tcp->snd_seq );
472 tcphdr->ack = htonl ( tcp->rcv_ack );
473 tcphdr->hlen = ( ( payload - iobuf->data ) << 2 );
474 tcphdr->flags = flags;
475 tcphdr->win = htons ( rcv_win );
476 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
478 /* Dump header */
479 DBGC ( tcp, "TCP %p TX %d->%d %08lx..%08lx %08lx %4zd",
480 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
481 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) + seq_len ),
482 ntohl ( tcphdr->ack ), len );
483 tcp_dump_flags ( tcp, tcphdr->flags );
484 DBGC ( tcp, "\n" );
486 /* Transmit packet */
487 return tcpip_tx ( iobuf, &tcp_protocol, &tcp->peer, NULL,
488 &tcphdr->csum );
492 * Retransmission timer expired
494 * @v timer Retry timer
495 * @v over Failure indicator
497 static void tcp_expired ( struct retry_timer *timer, int over ) {
498 struct tcp_connection *tcp =
499 container_of ( timer, struct tcp_connection, timer );
500 int graceful_close = TCP_CLOSED_GRACEFULLY ( tcp->tcp_state );
502 DBGC ( tcp, "TCP %p timer %s in %s\n", tcp,
503 ( over ? "expired" : "fired" ), tcp_state ( tcp->tcp_state ) );
505 assert ( ( tcp->tcp_state == TCP_SYN_SENT ) ||
506 ( tcp->tcp_state == TCP_SYN_RCVD ) ||
507 ( tcp->tcp_state == TCP_ESTABLISHED ) ||
508 ( tcp->tcp_state == TCP_FIN_WAIT_1 ) ||
509 ( tcp->tcp_state == TCP_TIME_WAIT ) ||
510 ( tcp->tcp_state == TCP_CLOSE_WAIT ) ||
511 ( tcp->tcp_state == TCP_CLOSING_OR_LAST_ACK ) );
513 if ( over || graceful_close ) {
514 /* If we have finally timed out and given up, or if
515 * this is the result of a graceful close, terminate
516 * the connection
518 tcp->tcp_state = TCP_CLOSED;
519 tcp_dump_state ( tcp );
520 tcp_close ( tcp, -ETIMEDOUT );
521 } else {
522 /* Otherwise, retransmit the packet */
523 tcp_xmit ( tcp, 0 );
528 * Send RST response to incoming packet
530 * @v in_tcphdr TCP header of incoming packet
531 * @ret rc Return status code
533 static int tcp_xmit_reset ( struct tcp_connection *tcp,
534 struct sockaddr_tcpip *st_dest,
535 struct tcp_header *in_tcphdr ) {
536 struct io_buffer *iobuf;
537 struct tcp_header *tcphdr;
539 /* Allocate space for dataless TX buffer */
540 iobuf = alloc_iob ( MAX_HDR_LEN );
541 if ( ! iobuf ) {
542 DBGC ( tcp, "TCP %p could not allocate data buffer\n", tcp );
543 return -ENOMEM;
545 iob_reserve ( iobuf, MAX_HDR_LEN );
547 /* Construct RST response */
548 tcphdr = iob_push ( iobuf, sizeof ( *tcphdr ) );
549 memset ( tcphdr, 0, sizeof ( *tcphdr ) );
550 tcphdr->src = in_tcphdr->dest;
551 tcphdr->dest = in_tcphdr->src;
552 tcphdr->seq = in_tcphdr->ack;
553 tcphdr->ack = in_tcphdr->seq;
554 tcphdr->hlen = ( ( sizeof ( *tcphdr ) / 4 ) << 4 );
555 tcphdr->flags = ( TCP_RST | TCP_ACK );
556 tcphdr->win = htons ( TCP_MAX_WINDOW_SIZE );
557 tcphdr->csum = tcpip_chksum ( iobuf->data, iob_len ( iobuf ) );
559 /* Dump header */
560 DBGC ( tcp, "TCP %p TX %d->%d %08lx..%08lx %08lx %4d",
561 tcp, ntohs ( tcphdr->src ), ntohs ( tcphdr->dest ),
562 ntohl ( tcphdr->seq ), ( ntohl ( tcphdr->seq ) ),
563 ntohl ( tcphdr->ack ), 0 );
564 tcp_dump_flags ( tcp, tcphdr->flags );
565 DBGC ( tcp, "\n" );
567 /* Transmit packet */
568 return tcpip_tx ( iobuf, &tcp_protocol, st_dest,
569 NULL, &tcphdr->csum );
572 /***************************************************************************
574 * Receive data path
576 ***************************************************************************
580 * Identify TCP connection by local port number
582 * @v local_port Local port (in network-endian order)
583 * @ret tcp TCP connection, or NULL
585 static struct tcp_connection * tcp_demux ( unsigned int local_port ) {
586 struct tcp_connection *tcp;
588 list_for_each_entry ( tcp, &tcp_conns, list ) {
589 if ( tcp->local_port == local_port )
590 return tcp;
592 return NULL;
596 * Parse TCP received options
598 * @v tcp TCP connection
599 * @v data Raw options data
600 * @v len Raw options length
601 * @v options Options structure to fill in
603 static void tcp_rx_opts ( struct tcp_connection *tcp, const void *data,
604 size_t len, struct tcp_options *options ) {
605 const void *end = ( data + len );
606 const struct tcp_option *option;
607 unsigned int kind;
609 memset ( options, 0, sizeof ( *options ) );
610 while ( data < end ) {
611 option = data;
612 kind = option->kind;
613 if ( kind == TCP_OPTION_END )
614 return;
615 if ( kind == TCP_OPTION_NOP ) {
616 data++;
617 continue;
619 switch ( kind ) {
620 case TCP_OPTION_MSS:
621 options->mssopt = data;
622 break;
623 case TCP_OPTION_TS:
624 options->tsopt = data;
625 break;
626 default:
627 DBGC ( tcp, "TCP %p received unknown option %d\n",
628 tcp, kind );
629 break;
631 data += option->length;
636 * Handle TCP received SYN
638 * @v tcp TCP connection
639 * @v seq SEQ value (in host-endian order)
640 * @v options TCP options
641 * @ret rc Return status code
643 static int tcp_rx_syn ( struct tcp_connection *tcp, uint32_t seq,
644 struct tcp_options *options ) {
646 /* Synchronise sequence numbers on first SYN */
647 if ( ! ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) ) {
648 tcp->rcv_ack = seq;
649 if ( options->tsopt )
650 tcp->timestamps = 1;
653 /* Ignore duplicate SYN */
654 if ( ( tcp->rcv_ack - seq ) > 0 )
655 return 0;
657 /* Mark SYN as received and start sending ACKs with each packet */
658 tcp->tcp_state |= ( TCP_STATE_SENT ( TCP_ACK ) |
659 TCP_STATE_RCVD ( TCP_SYN ) );
661 /* Acknowledge SYN */
662 tcp->rcv_ack++;
664 return 0;
668 * Handle TCP received ACK
670 * @v tcp TCP connection
671 * @v ack ACK value (in host-endian order)
672 * @v win WIN value (in host-endian order)
673 * @ret rc Return status code
675 static int tcp_rx_ack ( struct tcp_connection *tcp, uint32_t ack,
676 uint32_t win ) {
677 size_t ack_len = ( ack - tcp->snd_seq );
678 size_t len;
679 unsigned int acked_flags;
681 /* Ignore duplicate or out-of-range ACK */
682 if ( ack_len > tcp->snd_sent ) {
683 DBGC ( tcp, "TCP %p received ACK for [%08lx,%08lx), "
684 "sent only [%08lx,%08lx)\n", tcp, tcp->snd_seq,
685 ( tcp->snd_seq + ack_len ), tcp->snd_seq,
686 ( tcp->snd_seq + tcp->snd_sent ) );
687 return -EINVAL;
690 /* Acknowledge any flags being sent */
691 len = ack_len;
692 acked_flags = ( TCP_FLAGS_SENDING ( tcp->tcp_state ) &
693 ( TCP_SYN | TCP_FIN ) );
694 if ( acked_flags )
695 len--;
697 /* Update SEQ and sent counters, and window size */
698 tcp->snd_seq = ack;
699 tcp->snd_sent = 0;
700 tcp->snd_win = win;
702 /* Stop the retransmission timer */
703 stop_timer ( &tcp->timer );
705 /* Remove any acknowledged data from transmit queue */
706 tcp_process_queue ( tcp, len, NULL, 1 );
708 /* Mark SYN/FIN as acknowledged if applicable. */
709 if ( acked_flags )
710 tcp->tcp_state |= TCP_STATE_ACKED ( acked_flags );
712 /* Start sending FIN if we've had all possible data ACKed */
713 if ( list_empty ( &tcp->queue ) && tcp->xfer_closed )
714 tcp->tcp_state |= TCP_STATE_SENT ( TCP_FIN );
716 return 0;
720 * Handle TCP received data
722 * @v tcp TCP connection
723 * @v seq SEQ value (in host-endian order)
724 * @v iobuf I/O buffer
725 * @ret rc Return status code
727 * This function takes ownership of the I/O buffer.
729 static int tcp_rx_data ( struct tcp_connection *tcp, uint32_t seq,
730 struct io_buffer *iobuf ) {
731 size_t already_rcvd;
732 size_t len;
733 int rc;
735 /* Ignore duplicate or out-of-order data */
736 already_rcvd = ( tcp->rcv_ack - seq );
737 len = iob_len ( iobuf );
738 if ( already_rcvd >= len ) {
739 free_iob ( iobuf );
740 return 0;
742 iob_pull ( iobuf, already_rcvd );
743 len -= already_rcvd;
745 /* Deliver data to application */
746 if ( ( rc = xfer_deliver_iob ( &tcp->xfer, iobuf ) ) != 0 )
747 return rc;
749 /* Acknowledge new data */
750 tcp->rcv_ack += len;
751 return 0;
755 * Handle TCP received FIN
757 * @v tcp TCP connection
758 * @v seq SEQ value (in host-endian order)
759 * @ret rc Return status code
761 static int tcp_rx_fin ( struct tcp_connection *tcp, uint32_t seq ) {
763 /* Ignore duplicate or out-of-order FIN */
764 if ( ( tcp->rcv_ack - seq ) > 0 )
765 return 0;
767 /* Mark FIN as received and acknowledge it */
768 tcp->tcp_state |= TCP_STATE_RCVD ( TCP_FIN );
769 tcp->rcv_ack++;
771 /* Close connection */
772 tcp_close ( tcp, 0 );
774 return 0;
778 * Handle TCP received RST
780 * @v tcp TCP connection
781 * @v seq SEQ value (in host-endian order)
782 * @ret rc Return status code
784 static int tcp_rx_rst ( struct tcp_connection *tcp, uint32_t seq ) {
786 /* Accept RST only if it falls within the window. If we have
787 * not yet received a SYN, then we have no window to test
788 * against, so fall back to checking that our SYN has been
789 * ACKed.
791 if ( tcp->tcp_state & TCP_STATE_RCVD ( TCP_SYN ) ) {
792 if ( ( tcp->rcv_ack - seq ) > 0 )
793 return 0;
794 } else {
795 if ( ! ( tcp->tcp_state & TCP_STATE_ACKED ( TCP_SYN ) ) )
796 return 0;
799 /* Abort connection */
800 tcp->tcp_state = TCP_CLOSED;
801 tcp_dump_state ( tcp );
802 tcp_close ( tcp, -ECONNRESET );
804 return -ECONNRESET;
808 * Process received packet
810 * @v iobuf I/O buffer
811 * @v st_src Partially-filled source address
812 * @v st_dest Partially-filled destination address
813 * @v pshdr_csum Pseudo-header checksum
814 * @ret rc Return status code
816 static int tcp_rx ( struct io_buffer *iobuf,
817 struct sockaddr_tcpip *st_src,
818 struct sockaddr_tcpip *st_dest __unused,
819 uint16_t pshdr_csum ) {
820 struct tcp_header *tcphdr = iobuf->data;
821 struct tcp_connection *tcp;
822 struct tcp_options options;
823 size_t hlen;
824 uint16_t csum;
825 uint32_t start_seq;
826 uint32_t seq;
827 uint32_t ack;
828 uint32_t win;
829 unsigned int flags;
830 size_t len;
831 int rc;
833 /* Sanity check packet */
834 if ( iob_len ( iobuf ) < sizeof ( *tcphdr ) ) {
835 DBG ( "TCP packet too short at %zd bytes (min %zd bytes)\n",
836 iob_len ( iobuf ), sizeof ( *tcphdr ) );
837 rc = -EINVAL;
838 goto discard;
840 hlen = ( ( tcphdr->hlen & TCP_MASK_HLEN ) / 16 ) * 4;
841 if ( hlen < sizeof ( *tcphdr ) ) {
842 DBG ( "TCP header too short at %zd bytes (min %zd bytes)\n",
843 hlen, sizeof ( *tcphdr ) );
844 rc = -EINVAL;
845 goto discard;
847 if ( hlen > iob_len ( iobuf ) ) {
848 DBG ( "TCP header too long at %zd bytes (max %zd bytes)\n",
849 hlen, iob_len ( iobuf ) );
850 rc = -EINVAL;
851 goto discard;
853 csum = tcpip_continue_chksum ( pshdr_csum, iobuf->data, iob_len ( iobuf ));
854 if ( csum != 0 ) {
855 DBG ( "TCP checksum incorrect (is %04x including checksum "
856 "field, should be 0000)\n", csum );
857 rc = -EINVAL;
858 goto discard;
861 /* Parse parameters from header and strip header */
862 tcp = tcp_demux ( tcphdr->dest );
863 start_seq = seq = ntohl ( tcphdr->seq );
864 ack = ntohl ( tcphdr->ack );
865 win = ntohs ( tcphdr->win );
866 flags = tcphdr->flags;
867 tcp_rx_opts ( tcp, ( ( ( void * ) tcphdr ) + sizeof ( *tcphdr ) ),
868 ( hlen - sizeof ( *tcphdr ) ), &options );
869 iob_pull ( iobuf, hlen );
870 len = iob_len ( iobuf );
872 /* Dump header */
873 DBGC ( tcp, "TCP %p RX %d<-%d %08lx %08lx..%08lx %4zd",
874 tcp, ntohs ( tcphdr->dest ), ntohs ( tcphdr->src ),
875 ntohl ( tcphdr->ack ), ntohl ( tcphdr->seq ),
876 ( ntohl ( tcphdr->seq ) + len +
877 ( ( tcphdr->flags & ( TCP_SYN | TCP_FIN ) ) ? 1 : 0 ) ), len);
878 tcp_dump_flags ( tcp, tcphdr->flags );
879 DBGC ( tcp, "\n" );
881 /* If no connection was found, send RST */
882 if ( ! tcp ) {
883 tcp_xmit_reset ( tcp, st_src, tcphdr );
884 rc = -ENOTCONN;
885 goto discard;
888 /* Handle ACK, if present */
889 if ( flags & TCP_ACK ) {
890 if ( ( rc = tcp_rx_ack ( tcp, ack, win ) ) != 0 ) {
891 tcp_xmit_reset ( tcp, st_src, tcphdr );
892 goto discard;
896 /* Handle SYN, if present */
897 if ( flags & TCP_SYN ) {
898 tcp_rx_syn ( tcp, seq, &options );
899 seq++;
902 /* Handle RST, if present */
903 if ( flags & TCP_RST ) {
904 if ( ( rc = tcp_rx_rst ( tcp, seq ) ) != 0 )
905 goto discard;
908 /* Handle new data, if any */
909 tcp_rx_data ( tcp, seq, iobuf );
910 seq += len;
912 /* Handle FIN, if present */
913 if ( flags & TCP_FIN ) {
914 tcp_rx_fin ( tcp, seq );
915 seq++;
918 /* Update timestamp, if present and applicable */
919 if ( ( seq == tcp->rcv_ack ) && options.tsopt )
920 tcp->ts_recent = ntohl ( options.tsopt->tsval );
922 /* Dump out any state change as a result of the received packet */
923 tcp_dump_state ( tcp );
925 /* Send out any pending data. If peer is expecting an ACK for
926 * this packet then force sending a reply.
928 tcp_xmit ( tcp, ( start_seq != seq ) );
930 /* If this packet was the last we expect to receive, set up
931 * timer to expire and cause the connection to be freed.
933 if ( TCP_CLOSED_GRACEFULLY ( tcp->tcp_state ) ) {
934 tcp->timer.timeout = ( 2 * TCP_MSL );
935 start_timer ( &tcp->timer );
938 return 0;
940 discard:
941 /* Free received packet */
942 free_iob ( iobuf );
943 return rc;
946 /** TCP protocol */
947 struct tcpip_protocol tcp_protocol __tcpip_protocol = {
948 .name = "TCP",
949 .rx = tcp_rx,
950 .tcpip_proto = IP_TCP,
953 /***************************************************************************
955 * Data transfer interface
957 ***************************************************************************
961 * Close interface
963 * @v xfer Data transfer interface
964 * @v rc Reason for close
966 static void tcp_xfer_close ( struct xfer_interface *xfer, int rc ) {
967 struct tcp_connection *tcp =
968 container_of ( xfer, struct tcp_connection, xfer );
970 /* Close data transfer interface */
971 tcp_close ( tcp, rc );
973 /* Transmit FIN, if possible */
974 tcp_xmit ( tcp, 0 );
978 * Check flow control window
980 * @v xfer Data transfer interface
981 * @ret len Length of window
983 static size_t tcp_xfer_window ( struct xfer_interface *xfer ) {
984 struct tcp_connection *tcp =
985 container_of ( xfer, struct tcp_connection, xfer );
987 /* Not ready if data queue is non-empty. This imposes a limit
988 * of only one unACKed packet in the TX queue at any time; we
989 * do this to conserve memory usage.
991 if ( ! list_empty ( &tcp->queue ) )
992 return 0;
994 /* Return TCP window length */
995 return tcp_xmit_win ( tcp );
999 * Deliver datagram as I/O buffer
1001 * @v xfer Data transfer interface
1002 * @v iobuf Datagram I/O buffer
1003 * @v meta Data transfer metadata, or NULL
1004 * @ret rc Return status code
1006 static int tcp_xfer_deliver_iob ( struct xfer_interface *xfer,
1007 struct io_buffer *iobuf,
1008 struct xfer_metadata *meta __unused ) {
1009 struct tcp_connection *tcp =
1010 container_of ( xfer, struct tcp_connection, xfer );
1012 /* Enqueue packet */
1013 list_add_tail ( &iobuf->list, &tcp->queue );
1015 /* Transmit data, if possible */
1016 tcp_xmit ( tcp, 0 );
1018 return 0;
1021 /** TCP data transfer interface operations */
1022 static struct xfer_interface_operations tcp_xfer_operations = {
1023 .close = tcp_xfer_close,
1024 .vredirect = ignore_xfer_vredirect,
1025 .window = tcp_xfer_window,
1026 .alloc_iob = default_xfer_alloc_iob,
1027 .deliver_iob = tcp_xfer_deliver_iob,
1028 .deliver_raw = xfer_deliver_as_iob,
1031 /***************************************************************************
1033 * Openers
1035 ***************************************************************************
1038 /** TCP socket opener */
1039 struct socket_opener tcp_socket_opener __socket_opener = {
1040 .semantics = SOCK_STREAM,
1041 .family = AF_INET,
1042 .open = tcp_open,
1045 char TCP_SOCK_STREAM[1];
1048 * Open TCP URI
1050 * @v xfer Data transfer interface
1051 * @v uri URI
1052 * @ret rc Return status code
1054 static int tcp_open_uri ( struct xfer_interface *xfer, struct uri *uri ) {
1055 struct sockaddr_tcpip peer;
1057 /* Sanity check */
1058 if ( ! uri->host )
1059 return -EINVAL;
1061 memset ( &peer, 0, sizeof ( peer ) );
1062 peer.st_port = htons ( uri_port ( uri, 0 ) );
1063 return xfer_open_named_socket ( xfer, SOCK_STREAM,
1064 ( struct sockaddr * ) &peer,
1065 uri->host, NULL );
1068 /** TCP URI opener */
1069 struct uri_opener tcp_uri_opener __uri_opener = {
1070 .scheme = "tcp",
1071 .open = tcp_open_uri,