2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
34 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
35 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.2 2003/06/17 04:28:51 dillon Exp $
38 #include "opt_ipfw.h" /* for ipfw_fwd */
39 #include "opt_inet6.h"
40 #include "opt_ipsec.h"
41 #include "opt_tcpdebug.h"
42 #include "opt_tcp_input.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/sysctl.h>
48 #include <sys/malloc.h>
50 #include <sys/proc.h> /* for proc0 declaration */
51 #include <sys/protosw.h>
52 #include <sys/socket.h>
53 #include <sys/socketvar.h>
54 #include <sys/syslog.h>
56 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
59 #include <net/route.h>
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
65 #include <netinet/in_var.h>
66 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
67 #include <netinet/in_pcb.h>
68 #include <netinet/ip_var.h>
69 #include <netinet/ip6.h>
70 #include <netinet/icmp6.h>
71 #include <netinet6/nd6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/in6_pcb.h>
74 #include <netinet/tcp.h>
75 #include <netinet/tcp_fsm.h>
76 #include <netinet/tcp_seq.h>
77 #include <netinet/tcp_timer.h>
78 #include <netinet/tcp_var.h>
79 #include <netinet6/tcp6_var.h>
80 #include <netinet/tcpip.h>
82 #include <netinet/tcp_debug.h>
84 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
85 struct tcphdr tcp_savetcp;
89 #include <netipsec/ipsec.h>
90 #include <netipsec/ipsec6.h>
94 #include <netinet6/ipsec.h>
95 #include <netinet6/ipsec6.h>
96 #include <netkey/key.h>
99 #include <machine/in_cksum.h>
101 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
103 static const int tcprexmtthresh = 3;
106 struct tcpstat tcpstat;
107 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
108 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
110 static int log_in_vain = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
112 &log_in_vain, 0, "Log all incoming TCP connections");
114 static int blackhole = 0;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
116 &blackhole, 0, "Do not send RST when dropping refused connections");
118 int tcp_delack_enabled = 1;
119 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
120 &tcp_delack_enabled, 0,
121 "Delay ACK to try and piggyback it onto a data packet");
123 #ifdef TCP_DROP_SYNFIN
124 static int drop_synfin = 0;
125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
126 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
129 struct inpcbhead tcb;
130 #define tcb6 tcb /* for KAME src sync over BSD*'s */
131 struct inpcbinfo tcbinfo;
133 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
134 static void tcp_pulloutofband(struct socket *,
135 struct tcphdr *, struct mbuf *, int);
136 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
138 static void tcp_xmit_timer(struct tcpcb *, int);
139 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
141 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
143 #define ND6_HINT(tp) \
145 if ((tp) && (tp)->t_inpcb && \
146 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
147 (tp)->t_inpcb->in6p_route.ro_rt) \
148 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
155 * Indicate whether this ack should be delayed. We can delay the ack if
156 * - delayed acks are enabled and
157 * - there is no delayed ack timer in progress and
158 * - our last ack wasn't a 0-sized window. We never want to delay
159 * the ack that opens up a 0-sized window.
161 #define DELAY_ACK(tp) \
162 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
163 (tp->t_flags & TF_RXWIN0SENT) == 0)
166 tcp_reass(tp, th, tlenp, m)
167 register struct tcpcb *tp;
168 register struct tcphdr *th;
173 struct tseg_qent *p = NULL;
174 struct tseg_qent *nq;
175 struct tseg_qent *te;
176 struct socket *so = tp->t_inpcb->inp_socket;
180 * Call with th==0 after become established to
181 * force pre-ESTABLISHED data up to user socket.
186 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
187 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
190 tcpstat.tcps_rcvmemdrop++;
196 * Find a segment which begins after this one does.
198 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
199 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
205 * If there is a preceding segment, it may provide some of
206 * our data already. If so, drop the data from the incoming
207 * segment. If it provides all of our data, drop us.
211 /* conversion to int (in i) handles seq wraparound */
212 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
215 tcpstat.tcps_rcvduppack++;
216 tcpstat.tcps_rcvdupbyte += *tlenp;
220 * Try to present any queued data
221 * at the left window edge to the user.
222 * This is needed after the 3-WHS
225 goto present; /* ??? */
232 tcpstat.tcps_rcvoopack++;
233 tcpstat.tcps_rcvoobyte += *tlenp;
236 * While we overlap succeeding segments trim them or,
237 * if they are completely covered, dequeue them.
240 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
243 if (i < q->tqe_len) {
244 q->tqe_th->th_seq += i;
250 nq = LIST_NEXT(q, tqe_q);
251 LIST_REMOVE(q, tqe_q);
257 /* Insert the new segment queue entry into place. */
260 te->tqe_len = *tlenp;
263 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
265 LIST_INSERT_AFTER(p, te, tqe_q);
270 * Present data to user, advancing rcv_nxt through
271 * completed sequence space.
273 if (!TCPS_HAVEESTABLISHED(tp->t_state))
275 q = LIST_FIRST(&tp->t_segq);
276 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
279 tp->rcv_nxt += q->tqe_len;
280 flags = q->tqe_th->th_flags & TH_FIN;
281 nq = LIST_NEXT(q, tqe_q);
282 LIST_REMOVE(q, tqe_q);
283 if (so->so_state & SS_CANTRCVMORE)
286 sbappend(&so->so_rcv, q->tqe_m);
289 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
296 * TCP input routine, follows pages 65-76 of the
297 * protocol specification dated September, 1981 very closely.
301 tcp6_input(mp, offp, proto)
305 register struct mbuf *m = *mp;
306 struct in6_ifaddr *ia6;
308 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
311 * draft-itojun-ipv6-tcp-to-anycast
312 * better place to put this in?
314 ia6 = ip6_getdstifaddr(m);
315 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
318 ip6 = mtod(m, struct ip6_hdr *);
319 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
320 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
324 tcp_input(m, *offp, proto);
330 tcp_input(m, off0, proto)
331 register struct mbuf *m;
334 register struct tcphdr *th;
335 register struct ip *ip = NULL;
336 register struct ipovly *ipov;
337 register struct inpcb *inp = NULL;
342 register struct tcpcb *tp = NULL;
343 register int thflags;
344 struct socket *so = 0;
345 int todrop, acked, ourfinisacked, needoutput = 0;
347 struct tcpopt to; /* options in this segment */
348 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
349 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
350 struct sockaddr_in *next_hop = NULL;
351 int rstreason; /* For badport_bandlim accounting purposes */
352 struct ip6_hdr *ip6 = NULL;
356 const int isipv6 = 0;
362 /* Grab info from MT_TAG mbufs prepended to the chain. */
363 for (;m && m->m_type == MT_TAG; m = m->m_next) {
364 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
365 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
368 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
370 bzero((char *)&to, sizeof(to));
372 tcpstat.tcps_rcvtotal++;
375 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
376 ip6 = mtod(m, struct ip6_hdr *);
377 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
378 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
379 tcpstat.tcps_rcvbadsum++;
382 th = (struct tcphdr *)((caddr_t)ip6 + off0);
385 * Be proactive about unspecified IPv6 address in source.
386 * As we use all-zero to indicate unbounded/unconnected pcb,
387 * unspecified IPv6 address can be used to confuse us.
389 * Note that packets with unspecified IPv6 destination is
390 * already dropped in ip6_input.
392 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
398 * Get IP and TCP header together in first mbuf.
399 * Note: IP leaves IP header in first mbuf.
401 if (off0 > sizeof(struct ip)) {
402 ip_stripoptions(m, (struct mbuf *)0);
403 off0 = sizeof(struct ip);
405 if (m->m_len < sizeof(struct tcpiphdr)) {
406 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
407 tcpstat.tcps_rcvshort++;
411 ip = mtod(m, struct ip *);
412 ipov = (struct ipovly *)ip;
413 th = (struct tcphdr *)((caddr_t)ip + off0);
416 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
417 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
418 th->th_sum = m->m_pkthdr.csum_data;
420 th->th_sum = in_pseudo(ip->ip_src.s_addr,
422 htonl(m->m_pkthdr.csum_data +
425 th->th_sum ^= 0xffff;
428 * Checksum extended TCP header and data.
430 len = sizeof(struct ip) + tlen;
431 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
432 ipov->ih_len = (u_short)tlen;
433 ipov->ih_len = htons(ipov->ih_len);
434 th->th_sum = in_cksum(m, len);
437 tcpstat.tcps_rcvbadsum++;
441 /* Re-initialization for later version check */
442 ip->ip_v = IPVERSION;
447 * Check that TCP offset makes sense,
448 * pull out TCP options and adjust length. XXX
450 off = th->th_off << 2;
451 if (off < sizeof(struct tcphdr) || off > tlen) {
452 tcpstat.tcps_rcvbadoff++;
455 tlen -= off; /* tlen is used instead of ti->ti_len */
456 if (off > sizeof(struct tcphdr)) {
458 IP6_EXTHDR_CHECK(m, off0, off, );
459 ip6 = mtod(m, struct ip6_hdr *);
460 th = (struct tcphdr *)((caddr_t)ip6 + off0);
462 if (m->m_len < sizeof(struct ip) + off) {
463 if ((m = m_pullup(m, sizeof(struct ip) + off))
465 tcpstat.tcps_rcvshort++;
468 ip = mtod(m, struct ip *);
469 ipov = (struct ipovly *)ip;
470 th = (struct tcphdr *)((caddr_t)ip + off0);
473 optlen = off - sizeof(struct tcphdr);
474 optp = (u_char *)(th + 1);
476 thflags = th->th_flags;
478 #ifdef TCP_DROP_SYNFIN
480 * If the drop_synfin option is enabled, drop all packets with
481 * both the SYN and FIN bits set. This prevents e.g. nmap from
482 * identifying the TCP/IP stack.
484 * This is a violation of the TCP specification.
486 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
491 * Convert TCP protocol specific fields to host format.
493 th->th_seq = ntohl(th->th_seq);
494 th->th_ack = ntohl(th->th_ack);
495 th->th_win = ntohs(th->th_win);
496 th->th_urp = ntohs(th->th_urp);
499 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
500 * until after ip6_savecontrol() is called and before other functions
501 * which don't want those proto headers.
502 * Because ip6_savecontrol() is going to parse the mbuf to
503 * search for data to be passed up to user-land, it wants mbuf
504 * parameters to be unchanged.
505 * XXX: the call of ip6_savecontrol() has been obsoleted based on
506 * latest version of the advanced API (20020110).
508 drop_hdrlen = off0 + off;
511 * Locate pcb for segment.
514 /* IPFIREWALL_FORWARD section */
515 if (next_hop != NULL && isipv6 == 0) { /* IPv6 support is not yet */
517 * Transparently forwarded. Pretend to be the destination.
518 * already got one like this?
520 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
521 ip->ip_dst, th->th_dport,
522 0, m->m_pkthdr.rcvif);
524 /* It's new. Try find the ambushing socket. */
525 inp = in_pcblookup_hash(&tcbinfo,
526 ip->ip_src, th->th_sport,
529 ntohs(next_hop->sin_port) :
531 1, m->m_pkthdr.rcvif);
535 inp = in6_pcblookup_hash(&tcbinfo,
536 &ip6->ip6_src, th->th_sport,
537 &ip6->ip6_dst, th->th_dport,
538 1, m->m_pkthdr.rcvif);
540 inp = in_pcblookup_hash(&tcbinfo,
541 ip->ip_src, th->th_sport,
542 ip->ip_dst, th->th_dport,
543 1, m->m_pkthdr.rcvif);
548 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
549 ipsec6stat.in_polvio++;
553 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
554 ipsecstat.in_polvio++;
561 if (inp != NULL && ipsec6_in_reject(m, inp)) {
565 if (inp != NULL && ipsec4_in_reject(m, inp)) {
572 * If the state is CLOSED (i.e., TCB does not exist) then
573 * all data in the incoming segment is discarded.
574 * If the TCB exists but is in CLOSED state, it is embryonic,
575 * but should either do a listen or a connect soon.
580 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
582 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
587 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
588 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
592 strcpy(dbuf, inet_ntoa(ip->ip_dst));
593 strcpy(sbuf, inet_ntoa(ip->ip_src));
595 switch (log_in_vain) {
597 if ((thflags & TH_SYN) == 0)
601 "Connection attempt to TCP %s:%d "
602 "from %s:%d flags:0x%02x\n",
603 dbuf, ntohs(th->th_dport), sbuf,
604 ntohs(th->th_sport), thflags);
613 if (thflags & TH_SYN)
622 rstreason = BANDLIM_RST_CLOSEDPORT;
627 rstreason = BANDLIM_RST_CLOSEDPORT;
630 if (tp->t_state == TCPS_CLOSED)
633 /* Unscale the window into a 32-bit value. */
634 if ((thflags & TH_SYN) == 0)
635 tiwin = th->th_win << tp->snd_scale;
639 so = inp->inp_socket;
640 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
641 struct in_conninfo inc;
643 if (so->so_options & SO_DEBUG) {
644 ostate = tp->t_state;
646 bcopy((char *)ip6, (char *)tcp_saveipgen,
649 bcopy((char *)ip, (char *)tcp_saveipgen,
654 /* skip if this isn't a listen socket */
655 if ((so->so_options & SO_ACCEPTCONN) == 0)
658 inc.inc_isipv6 = isipv6;
661 inc.inc6_faddr = ip6->ip6_src;
662 inc.inc6_laddr = ip6->ip6_dst;
663 inc.inc6_route.ro_rt = NULL; /* XXX */
665 inc.inc_faddr = ip->ip_src;
666 inc.inc_laddr = ip->ip_dst;
667 inc.inc_route.ro_rt = NULL; /* XXX */
669 inc.inc_fport = th->th_sport;
670 inc.inc_lport = th->th_dport;
673 * If the state is LISTEN then ignore segment if it contains
674 * a RST. If the segment contains an ACK then it is bad and
675 * send a RST. If it does not contain a SYN then it is not
676 * interesting; drop it.
678 * If the state is SYN_RECEIVED (syncache) and seg contains
679 * an ACK, but not for our SYN/ACK, send a RST. If the seg
680 * contains a RST, check the sequence number to see if it
681 * is a valid reset segment.
683 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
684 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
685 if (!syncache_expand(&inc, th, &so, m)) {
687 * No syncache entry, or ACK was not
688 * for our SYN/ACK. Send a RST.
690 tcpstat.tcps_badsyn++;
691 rstreason = BANDLIM_RST_OPENPORT;
696 * Could not complete 3-way handshake,
697 * connection is being closed down, and
698 * syncache will free mbuf.
702 * Socket is created in state SYN_RECEIVED.
703 * Continue processing segment.
708 * This is what would have happened in
709 * tcp_output() when the SYN,ACK was sent.
711 tp->snd_up = tp->snd_una;
712 tp->snd_max = tp->snd_nxt = tp->iss + 1;
713 tp->last_ack_sent = tp->rcv_nxt;
715 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
716 * until the _second_ ACK is received:
717 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
718 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
719 * move to ESTAB, set snd_wnd to tiwin.
721 tp->snd_wnd = tiwin; /* unscaled */
724 if (thflags & TH_RST) {
725 syncache_chkrst(&inc, th);
728 if (thflags & TH_ACK) {
729 syncache_badack(&inc);
730 tcpstat.tcps_badsyn++;
731 rstreason = BANDLIM_RST_OPENPORT;
738 * Segment's flags are (SYN) or (SYN|FIN).
742 * If deprecated address is forbidden,
743 * we do not accept SYN to deprecated interface
744 * address to prevent any new inbound connection from
745 * getting established.
746 * When we do not accept SYN, we send a TCP RST,
747 * with deprecated source address (instead of dropping
748 * it). We compromise it as it is much better for peer
749 * to send a RST, and RST will be the final packet
752 * If we do not forbid deprecated addresses, we accept
753 * the SYN packet. RFC2462 does not suggest dropping
755 * If we decipher RFC2462 5.5.4, it says like this:
756 * 1. use of deprecated addr with existing
757 * communication is okay - "SHOULD continue to be
759 * 2. use of it with new communication:
760 * (2a) "SHOULD NOT be used if alternate address
761 * with sufficient scope is available"
762 * (2b) nothing mentioned otherwise.
763 * Here we fall into (2b) case as we have no choice in
764 * our source address selection - we must obey the peer.
766 * The wording in RFC2462 is confusing, and there are
767 * multiple description text for deprecated address
768 * handling - worse, they are not exactly the same.
769 * I believe 5.5.4 is the best one, so we follow 5.5.4.
771 if (isipv6 && !ip6_use_deprecated) {
772 struct in6_ifaddr *ia6;
774 if ((ia6 = ip6_getdstifaddr(m)) &&
775 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
777 rstreason = BANDLIM_RST_OPENPORT;
783 * If it is from this socket, drop it, it must be forged.
784 * Don't bother responding if the destination was a broadcast.
786 if (th->th_dport == th->th_sport) {
788 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
792 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
797 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
799 * Note that it is quite possible to receive unicast
800 * link-layer packets with a broadcast IP address. Use
801 * in_broadcast() to find them.
803 if (m->m_flags & (M_BCAST|M_MCAST))
806 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
807 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
810 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
811 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
812 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
813 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
817 * SYN appears to be valid; create compressed TCP state
818 * for syncache, or perform t/tcp connection.
820 if (so->so_qlen <= so->so_qlimit) {
821 tcp_dooptions(&to, optp, optlen, 1);
822 if (!syncache_add(&inc, &to, th, &so, m))
826 * Entry added to syncache, mbuf used to
827 * send SYN,ACK packet.
831 * Segment passed TAO tests.
836 tp->t_starttime = ticks;
837 tp->t_state = TCPS_ESTABLISHED;
840 * If there is a FIN, or if there is data and the
841 * connection is local, then delay SYN,ACK(SYN) in
842 * the hope of piggy-backing it on a response
843 * segment. Otherwise must send ACK now in case
844 * the other side is slow starting.
847 ((thflags & TH_FIN) ||
849 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
850 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
851 callout_reset(tp->tt_delack, tcp_delacktime,
852 tcp_timer_delack, tp);
853 tp->t_flags |= TF_NEEDSYN;
855 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
857 tcpstat.tcps_connects++;
865 /* XXX temp debugging */
866 /* should not happen - syncache should pick up these connections */
867 if (tp->t_state == TCPS_LISTEN)
868 panic("tcp_input: TCPS_LISTEN");
871 * Segment received on connection.
872 * Reset idle time and keep-alive timer.
874 tp->t_rcvtime = ticks;
875 if (TCPS_HAVEESTABLISHED(tp->t_state))
876 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
880 * XXX this is tradtitional behavior, may need to be cleaned up.
882 tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
883 if (thflags & TH_SYN) {
884 if (to.to_flags & TOF_SCALE) {
885 tp->t_flags |= TF_RCVD_SCALE;
886 tp->requested_s_scale = to.to_requested_s_scale;
888 if (to.to_flags & TOF_TS) {
889 tp->t_flags |= TF_RCVD_TSTMP;
890 tp->ts_recent = to.to_tsval;
891 tp->ts_recent_age = ticks;
893 if (to.to_flags & (TOF_CC|TOF_CCNEW))
894 tp->t_flags |= TF_RCVD_CC;
895 if (to.to_flags & TOF_MSS)
896 tcp_mss(tp, to.to_mss);
900 * Header prediction: check for the two common cases
901 * of a uni-directional data xfer. If the packet has
902 * no control flags, is in-sequence, the window didn't
903 * change and we're not retransmitting, it's a
904 * candidate. If the length is zero and the ack moved
905 * forward, we're the sender side of the xfer. Just
906 * free the data acked & wake any higher level process
907 * that was blocked waiting for space. If the length
908 * is non-zero and the ack didn't move, we're the
909 * receiver side. If we're getting packets in-order
910 * (the reassembly queue is empty), add the data to
911 * the socket buffer and note that we need a delayed ack.
912 * Make sure that the hidden state-flags are also off.
913 * Since we check for TCPS_ESTABLISHED above, it can only
916 if (tp->t_state == TCPS_ESTABLISHED &&
917 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
918 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
919 ((to.to_flags & TOF_TS) == 0 ||
920 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
922 * Using the CC option is compulsory if once started:
923 * the segment is OK if no T/TCP was negotiated or
924 * if the segment has a CC option equal to CCrecv
926 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
927 ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
928 th->th_seq == tp->rcv_nxt &&
929 tiwin && tiwin == tp->snd_wnd &&
930 tp->snd_nxt == tp->snd_max) {
933 * If last ACK falls within this segment's sequence numbers,
934 * record the timestamp.
935 * NOTE that the test is modified according to the latest
936 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
938 if ((to.to_flags & TOF_TS) != 0 &&
939 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
940 tp->ts_recent_age = ticks;
941 tp->ts_recent = to.to_tsval;
945 if (SEQ_GT(th->th_ack, tp->snd_una) &&
946 SEQ_LEQ(th->th_ack, tp->snd_max) &&
947 tp->snd_cwnd >= tp->snd_wnd &&
949 tp->t_dupacks < tcprexmtthresh) ||
951 !SEQ_LT(tp->snd_una, tp->snd_recover)))) {
953 * this is a pure ack for outstanding data.
955 ++tcpstat.tcps_predack;
957 * "bad retransmit" recovery
959 if (tp->t_rxtshift == 1 &&
960 ticks < tp->t_badrxtwin) {
961 tp->snd_cwnd = tp->snd_cwnd_prev;
963 tp->snd_ssthresh_prev;
964 tp->snd_high = tp->snd_high_prev;
965 tp->snd_nxt = tp->snd_max;
969 * Recalculate the retransmit timer / rtt.
971 * Some machines (certain windows boxes)
972 * send broken timestamp replies during the
973 * SYN+ACK phase, ignore timestamps of 0.
975 if ((to.to_flags & TOF_TS) != 0 &&
978 ticks - to.to_tsecr + 1);
979 } else if (tp->t_rtttime &&
980 SEQ_GT(th->th_ack, tp->t_rtseq)) {
982 ticks - tp->t_rtttime);
984 tcp_xmit_bandwidth_limit(tp, th->th_ack);
985 acked = th->th_ack - tp->snd_una;
986 tcpstat.tcps_rcvackpack++;
987 tcpstat.tcps_rcvackbyte += acked;
988 sbdrop(&so->so_snd, acked);
989 if (SEQ_GT(tp->snd_una, tp->snd_high) &&
990 SEQ_LEQ(th->th_ack, tp->snd_high))
991 tp->snd_high = th->th_ack - 1;
992 tp->snd_una = tp->snd_recover = th->th_ack;
995 ND6_HINT(tp); /* some progress has been done */
998 * If all outstanding data are acked, stop
999 * retransmit timer, otherwise restart timer
1000 * using current (possibly backed-off) value.
1001 * If process is waiting for space,
1002 * wakeup/selwakeup/signal. If data
1003 * are ready to send, let tcp_output
1004 * decide between more output or persist.
1006 if (tp->snd_una == tp->snd_max)
1007 callout_stop(tp->tt_rexmt);
1008 else if (!callout_active(tp->tt_persist))
1009 callout_reset(tp->tt_rexmt,
1011 tcp_timer_rexmt, tp);
1014 if (so->so_snd.sb_cc)
1015 (void) tcp_output(tp);
1018 } else if (th->th_ack == tp->snd_una &&
1019 LIST_EMPTY(&tp->t_segq) &&
1020 tlen <= sbspace(&so->so_rcv)) {
1022 * this is a pure, in-sequence data packet
1023 * with nothing on the reassembly queue and
1024 * we have enough buffer space to take it.
1026 ++tcpstat.tcps_preddat;
1027 tp->rcv_nxt += tlen;
1028 tcpstat.tcps_rcvpack++;
1029 tcpstat.tcps_rcvbyte += tlen;
1030 ND6_HINT(tp); /* some progress has been done */
1032 * Add data to socket buffer.
1034 if (so->so_state & SS_CANTRCVMORE) {
1037 m_adj(m, drop_hdrlen); /* delayed header drop */
1038 sbappend(&so->so_rcv, m);
1041 if (DELAY_ACK(tp)) {
1042 callout_reset(tp->tt_delack, tcp_delacktime,
1043 tcp_timer_delack, tp);
1045 tp->t_flags |= TF_ACKNOW;
1053 * Calculate amount of space in receive window,
1054 * and then do TCP input processing.
1055 * Receive window is amount of space in rcv queue,
1056 * but not less than advertised window.
1060 win = sbspace(&so->so_rcv);
1063 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1066 switch (tp->t_state) {
1069 * If the state is SYN_RECEIVED:
1070 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1072 case TCPS_SYN_RECEIVED:
1073 if ((thflags & TH_ACK) &&
1074 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1075 SEQ_GT(th->th_ack, tp->snd_max))) {
1076 rstreason = BANDLIM_RST_OPENPORT;
1082 * If the state is SYN_SENT:
1083 * if seg contains an ACK, but not for our SYN, drop the input.
1084 * if seg contains a RST, then drop the connection.
1085 * if seg does not contain SYN, then drop it.
1086 * Otherwise this is an acceptable SYN segment
1087 * initialize tp->rcv_nxt and tp->irs
1088 * if seg contains ack then advance tp->snd_una
1089 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1090 * arrange for segment to be acked (eventually)
1091 * continue processing rest of data/controls, beginning with URG
1094 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1095 taop = &tao_noncached;
1096 bzero(taop, sizeof(*taop));
1099 if ((thflags & TH_ACK) &&
1100 (SEQ_LEQ(th->th_ack, tp->iss) ||
1101 SEQ_GT(th->th_ack, tp->snd_max))) {
1103 * If we have a cached CCsent for the remote host,
1104 * hence we haven't just crashed and restarted,
1105 * do not send a RST. This may be a retransmission
1106 * from the other side after our earlier ACK was lost.
1107 * Our new SYN, when it arrives, will serve as the
1110 if (taop->tao_ccsent != 0)
1113 rstreason = BANDLIM_UNLIMITED;
1117 if (thflags & TH_RST) {
1118 if (thflags & TH_ACK)
1119 tp = tcp_drop(tp, ECONNREFUSED);
1122 if ((thflags & TH_SYN) == 0)
1124 tp->snd_wnd = th->th_win; /* initial send window */
1125 tp->cc_recv = to.to_cc; /* foreign CC */
1127 tp->irs = th->th_seq;
1129 if (thflags & TH_ACK) {
1131 * Our SYN was acked. If segment contains CC.ECHO
1132 * option, check it to make sure this segment really
1133 * matches our SYN. If not, just drop it as old
1134 * duplicate, but send an RST if we're still playing
1135 * by the old rules. If no CC.ECHO option, make sure
1136 * we don't get fooled into using T/TCP.
1138 if (to.to_flags & TOF_CCECHO) {
1139 if (tp->cc_send != to.to_ccecho) {
1140 if (taop->tao_ccsent != 0)
1143 rstreason = BANDLIM_UNLIMITED;
1148 tp->t_flags &= ~TF_RCVD_CC;
1149 tcpstat.tcps_connects++;
1151 /* Do window scaling on this connection? */
1152 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1153 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1154 tp->snd_scale = tp->requested_s_scale;
1155 tp->rcv_scale = tp->request_r_scale;
1157 /* Segment is acceptable, update cache if undefined. */
1158 if (taop->tao_ccsent == 0)
1159 taop->tao_ccsent = to.to_ccecho;
1161 tp->rcv_adv += tp->rcv_wnd;
1162 tp->snd_una++; /* SYN is acked */
1164 * If there's data, delay ACK; if there's also a FIN
1165 * ACKNOW will be turned on later.
1167 if (DELAY_ACK(tp) && tlen != 0)
1168 callout_reset(tp->tt_delack, tcp_delacktime,
1169 tcp_timer_delack, tp);
1171 tp->t_flags |= TF_ACKNOW;
1173 * Received <SYN,ACK> in SYN_SENT[*] state.
1175 * SYN_SENT --> ESTABLISHED
1176 * SYN_SENT* --> FIN_WAIT_1
1178 tp->t_starttime = ticks;
1179 if (tp->t_flags & TF_NEEDFIN) {
1180 tp->t_state = TCPS_FIN_WAIT_1;
1181 tp->t_flags &= ~TF_NEEDFIN;
1184 tp->t_state = TCPS_ESTABLISHED;
1185 callout_reset(tp->tt_keep, tcp_keepidle,
1186 tcp_timer_keep, tp);
1190 * Received initial SYN in SYN-SENT[*] state =>
1191 * simultaneous open. If segment contains CC option
1192 * and there is a cached CC, apply TAO test.
1193 * If it succeeds, connection is * half-synchronized.
1194 * Otherwise, do 3-way handshake:
1195 * SYN-SENT -> SYN-RECEIVED
1196 * SYN-SENT* -> SYN-RECEIVED*
1197 * If there was no CC option, clear cached CC value.
1199 tp->t_flags |= TF_ACKNOW;
1200 callout_stop(tp->tt_rexmt);
1201 if (to.to_flags & TOF_CC) {
1202 if (taop->tao_cc != 0 &&
1203 CC_GT(to.to_cc, taop->tao_cc)) {
1205 * update cache and make transition:
1206 * SYN-SENT -> ESTABLISHED*
1207 * SYN-SENT* -> FIN-WAIT-1*
1209 taop->tao_cc = to.to_cc;
1210 tp->t_starttime = ticks;
1211 if (tp->t_flags & TF_NEEDFIN) {
1212 tp->t_state = TCPS_FIN_WAIT_1;
1213 tp->t_flags &= ~TF_NEEDFIN;
1215 tp->t_state = TCPS_ESTABLISHED;
1216 callout_reset(tp->tt_keep,
1221 tp->t_flags |= TF_NEEDSYN;
1223 tp->t_state = TCPS_SYN_RECEIVED;
1225 /* CC.NEW or no option => invalidate cache */
1227 tp->t_state = TCPS_SYN_RECEIVED;
1233 * Advance th->th_seq to correspond to first data byte.
1234 * If data, trim to stay within window,
1235 * dropping FIN if necessary.
1238 if (tlen > tp->rcv_wnd) {
1239 todrop = tlen - tp->rcv_wnd;
1243 tcpstat.tcps_rcvpackafterwin++;
1244 tcpstat.tcps_rcvbyteafterwin += todrop;
1246 tp->snd_wl1 = th->th_seq - 1;
1247 tp->rcv_up = th->th_seq;
1249 * Client side of transaction: already sent SYN and data.
1250 * If the remote host used T/TCP to validate the SYN,
1251 * our data will be ACK'd; if so, enter normal data segment
1252 * processing in the middle of step 5, ack processing.
1253 * Otherwise, goto step 6.
1255 if (thflags & TH_ACK)
1261 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1262 * if segment contains a SYN and CC [not CC.NEW] option:
1263 * if state == TIME_WAIT and connection duration > MSL,
1264 * drop packet and send RST;
1266 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1267 * ack the FIN (and data) in retransmission queue.
1268 * Complete close and delete TCPCB. Then reprocess
1269 * segment, hoping to find new TCPCB in LISTEN state;
1271 * else must be old SYN; drop it.
1272 * else do normal processing.
1276 case TCPS_TIME_WAIT:
1277 if ((thflags & TH_SYN) &&
1278 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1279 if (tp->t_state == TCPS_TIME_WAIT &&
1280 (ticks - tp->t_starttime) > tcp_msl) {
1281 rstreason = BANDLIM_UNLIMITED;
1284 if (CC_GT(to.to_cc, tp->cc_recv)) {
1291 break; /* continue normal processing */
1295 * States other than LISTEN or SYN_SENT.
1296 * First check the RST flag and sequence number since reset segments
1297 * are exempt from the timestamp and connection count tests. This
1298 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1299 * below which allowed reset segments in half the sequence space
1300 * to fall though and be processed (which gives forged reset
1301 * segments with a random sequence number a 50 percent chance of
1302 * killing a connection).
1303 * Then check timestamp, if present.
1304 * Then check the connection count, if present.
1305 * Then check that at least some bytes of segment are within
1306 * receive window. If segment begins before rcv_nxt,
1307 * drop leading data (and SYN); if nothing left, just ack.
1310 * If the RST bit is set, check the sequence number to see
1311 * if this is a valid reset segment.
1313 * In all states except SYN-SENT, all reset (RST) segments
1314 * are validated by checking their SEQ-fields. A reset is
1315 * valid if its sequence number is in the window.
1316 * Note: this does not take into account delayed ACKs, so
1317 * we should test against last_ack_sent instead of rcv_nxt.
1318 * The sequence number in the reset segment is normally an
1319 * echo of our outgoing acknowlegement numbers, but some hosts
1320 * send a reset with the sequence number at the rightmost edge
1321 * of our receive window, and we have to handle this case.
1322 * If we have multiple segments in flight, the intial reset
1323 * segment sequence numbers will be to the left of last_ack_sent,
1324 * but they will eventually catch up.
1325 * In any case, it never made sense to trim reset segments to
1326 * fit the receive window since RFC 1122 says:
1327 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1329 * A TCP SHOULD allow a received RST segment to include data.
1332 * It has been suggested that a RST segment could contain
1333 * ASCII text that encoded and explained the cause of the
1334 * RST. No standard has yet been established for such
1337 * If the reset segment passes the sequence number test examine
1339 * SYN_RECEIVED STATE:
1340 * If passive open, return to LISTEN state.
1341 * If active open, inform user that connection was refused.
1342 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1343 * Inform user that connection was reset, and close tcb.
1344 * CLOSING, LAST_ACK STATES:
1347 * Drop the segment - see Stevens, vol. 2, p. 964 and
1350 if (thflags & TH_RST) {
1351 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1352 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1353 switch (tp->t_state) {
1355 case TCPS_SYN_RECEIVED:
1356 so->so_error = ECONNREFUSED;
1359 case TCPS_ESTABLISHED:
1360 case TCPS_FIN_WAIT_1:
1361 case TCPS_FIN_WAIT_2:
1362 case TCPS_CLOSE_WAIT:
1363 so->so_error = ECONNRESET;
1365 tp->t_state = TCPS_CLOSED;
1366 tcpstat.tcps_drops++;
1375 case TCPS_TIME_WAIT:
1383 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1384 * and it's less than ts_recent, drop it.
1386 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1387 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1389 /* Check to see if ts_recent is over 24 days old. */
1390 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1392 * Invalidate ts_recent. If this segment updates
1393 * ts_recent, the age will be reset later and ts_recent
1394 * will get a valid value. If it does not, setting
1395 * ts_recent to zero will at least satisfy the
1396 * requirement that zero be placed in the timestamp
1397 * echo reply when ts_recent isn't valid. The
1398 * age isn't reset until we get a valid ts_recent
1399 * because we don't want out-of-order segments to be
1400 * dropped when ts_recent is old.
1404 tcpstat.tcps_rcvduppack++;
1405 tcpstat.tcps_rcvdupbyte += tlen;
1406 tcpstat.tcps_pawsdrop++;
1415 * If T/TCP was negotiated and the segment doesn't have CC,
1416 * or if its CC is wrong then drop the segment.
1417 * RST segments do not have to comply with this.
1419 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1420 ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1424 * In the SYN-RECEIVED state, validate that the packet belongs to
1425 * this connection before trimming the data to fit the receive
1426 * window. Check the sequence number versus IRS since we know
1427 * the sequence numbers haven't wrapped. This is a partial fix
1428 * for the "LAND" DoS attack.
1430 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1431 rstreason = BANDLIM_RST_OPENPORT;
1435 todrop = tp->rcv_nxt - th->th_seq;
1437 if (thflags & TH_SYN) {
1447 * Following if statement from Stevens, vol. 2, p. 960.
1450 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1452 * Any valid FIN must be to the left of the window.
1453 * At this point the FIN must be a duplicate or out
1454 * of sequence; drop it.
1459 * Send an ACK to resynchronize and drop any data.
1460 * But keep on processing for RST or ACK.
1462 tp->t_flags |= TF_ACKNOW;
1464 tcpstat.tcps_rcvduppack++;
1465 tcpstat.tcps_rcvdupbyte += todrop;
1467 tcpstat.tcps_rcvpartduppack++;
1468 tcpstat.tcps_rcvpartdupbyte += todrop;
1470 drop_hdrlen += todrop; /* drop from the top afterwards */
1471 th->th_seq += todrop;
1473 if (th->th_urp > todrop)
1474 th->th_urp -= todrop;
1482 * If new data are received on a connection after the
1483 * user processes are gone, then RST the other end.
1485 if ((so->so_state & SS_NOFDREF) &&
1486 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1488 tcpstat.tcps_rcvafterclose++;
1489 rstreason = BANDLIM_UNLIMITED;
1494 * If segment ends after window, drop trailing data
1495 * (and PUSH and FIN); if nothing left, just ACK.
1497 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1499 tcpstat.tcps_rcvpackafterwin++;
1500 if (todrop >= tlen) {
1501 tcpstat.tcps_rcvbyteafterwin += tlen;
1503 * If a new connection request is received
1504 * while in TIME_WAIT, drop the old connection
1505 * and start over if the sequence numbers
1506 * are above the previous ones.
1508 if (thflags & TH_SYN &&
1509 tp->t_state == TCPS_TIME_WAIT &&
1510 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1515 * If window is closed can only take segments at
1516 * window edge, and have to drop data and PUSH from
1517 * incoming segments. Continue processing, but
1518 * remember to ack. Otherwise, drop segment
1521 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1522 tp->t_flags |= TF_ACKNOW;
1523 tcpstat.tcps_rcvwinprobe++;
1527 tcpstat.tcps_rcvbyteafterwin += todrop;
1530 thflags &= ~(TH_PUSH|TH_FIN);
1534 * If last ACK falls within this segment's sequence numbers,
1535 * record its timestamp.
1536 * NOTE that the test is modified according to the latest
1537 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1539 if ((to.to_flags & TOF_TS) != 0 &&
1540 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1541 tp->ts_recent_age = ticks;
1542 tp->ts_recent = to.to_tsval;
1546 * If a SYN is in the window, then this is an
1547 * error and we send an RST and drop the connection.
1549 if (thflags & TH_SYN) {
1550 tp = tcp_drop(tp, ECONNRESET);
1551 rstreason = BANDLIM_UNLIMITED;
1556 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1557 * flag is on (half-synchronized state), then queue data for
1558 * later processing; else drop segment and return.
1560 if ((thflags & TH_ACK) == 0) {
1561 if (tp->t_state == TCPS_SYN_RECEIVED ||
1562 (tp->t_flags & TF_NEEDSYN))
1571 switch (tp->t_state) {
1574 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1575 * ESTABLISHED state and continue processing.
1576 * The ACK was checked above.
1578 case TCPS_SYN_RECEIVED:
1580 tcpstat.tcps_connects++;
1582 /* Do window scaling? */
1583 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1584 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1585 tp->snd_scale = tp->requested_s_scale;
1586 tp->rcv_scale = tp->request_r_scale;
1589 * Upon successful completion of 3-way handshake,
1590 * update cache.CC if it was undefined, pass any queued
1591 * data to the user, and advance state appropriately.
1593 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1595 taop->tao_cc = tp->cc_recv;
1599 * SYN-RECEIVED -> ESTABLISHED
1600 * SYN-RECEIVED* -> FIN-WAIT-1
1602 tp->t_starttime = ticks;
1603 if (tp->t_flags & TF_NEEDFIN) {
1604 tp->t_state = TCPS_FIN_WAIT_1;
1605 tp->t_flags &= ~TF_NEEDFIN;
1607 tp->t_state = TCPS_ESTABLISHED;
1608 callout_reset(tp->tt_keep, tcp_keepidle,
1609 tcp_timer_keep, tp);
1612 * If segment contains data or ACK, will call tcp_reass()
1613 * later; if not, do so now to pass queued data to user.
1615 if (tlen == 0 && (thflags & TH_FIN) == 0)
1616 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1618 tp->snd_wl1 = th->th_seq - 1;
1622 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1623 * ACKs. If the ack is in the range
1624 * tp->snd_una < th->th_ack <= tp->snd_max
1625 * then advance tp->snd_una to th->th_ack and drop
1626 * data from the retransmission queue. If this ACK reflects
1627 * more up to date window information we update our window information.
1629 case TCPS_ESTABLISHED:
1630 case TCPS_FIN_WAIT_1:
1631 case TCPS_FIN_WAIT_2:
1632 case TCPS_CLOSE_WAIT:
1635 case TCPS_TIME_WAIT:
1637 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1638 if (tlen == 0 && tiwin == tp->snd_wnd) {
1639 tcpstat.tcps_rcvdupack++;
1641 * If we have outstanding data (other than
1642 * a window probe), this is a completely
1643 * duplicate ack (ie, window info didn't
1644 * change), the ack is the biggest we've
1645 * seen and we've seen exactly our rexmt
1646 * threshhold of them, assume a packet
1647 * has been dropped and retransmit it.
1648 * Kludge snd_nxt & the congestion
1649 * window so we send only this one
1652 * We know we're losing at the current
1653 * window size so do congestion avoidance
1654 * (set ssthresh to half the current window
1655 * and pull our congestion window back to
1656 * the new ssthresh).
1658 * Dup acks mean that packets have left the
1659 * network (they're now cached at the receiver)
1660 * so bump cwnd by the amount in the receiver
1661 * to keep a constant cwnd packets in the
1664 if (!callout_active(tp->tt_rexmt) ||
1665 th->th_ack != tp->snd_una)
1667 else if (++tp->t_dupacks > tcprexmtthresh ||
1670 tp->snd_recover))) {
1671 tp->snd_cwnd += tp->t_maxseg;
1672 (void) tcp_output(tp);
1674 } else if (tp->t_dupacks == tcprexmtthresh) {
1675 tcp_seq onxt = tp->snd_nxt;
1677 if (tcp_do_newreno &&
1678 SEQ_LEQ(th->th_ack, tp->snd_high)) {
1682 win = min(tp->snd_wnd, tp->snd_cwnd) /
1686 tp->snd_ssthresh = win * tp->t_maxseg;
1687 tp->snd_recover = tp->snd_max;
1688 callout_stop(tp->tt_rexmt);
1690 tp->snd_nxt = th->th_ack;
1691 tp->snd_cwnd = tp->t_maxseg;
1692 (void) tcp_output(tp);
1693 tp->snd_cwnd = tp->snd_ssthresh +
1694 tp->t_maxseg * tp->t_dupacks;
1695 if (SEQ_GT(onxt, tp->snd_nxt))
1704 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1707 * If the congestion window was inflated to account
1708 * for the other side's cached packets, retract it.
1710 if (tcp_do_newreno) {
1711 if (SEQ_LT(tp->snd_una, tp->snd_recover)) {
1712 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1713 tcp_newreno_partial_ack(tp, th);
1716 * Window inflation should have left us
1717 * with approximately snd_ssthresh
1719 * But in case we would be inclined to
1720 * send a burst, better to do it via
1721 * the slow start mechanism.
1723 if (SEQ_GT(th->th_ack +
1726 tp->snd_cwnd = tp->snd_max -
1730 tp->snd_cwnd = tp->snd_ssthresh;
1734 if (tp->t_dupacks >= tcprexmtthresh &&
1735 tp->snd_cwnd > tp->snd_ssthresh)
1736 tp->snd_cwnd = tp->snd_ssthresh;
1739 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1740 tcpstat.tcps_rcvacktoomuch++;
1744 * If we reach this point, ACK is not a duplicate,
1745 * i.e., it ACKs something we sent.
1747 if (tp->t_flags & TF_NEEDSYN) {
1749 * T/TCP: Connection was half-synchronized, and our
1750 * SYN has been ACK'd (so connection is now fully
1751 * synchronized). Go to non-starred state,
1752 * increment snd_una for ACK of SYN, and check if
1753 * we can do window scaling.
1755 tp->t_flags &= ~TF_NEEDSYN;
1757 /* Do window scaling? */
1758 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1759 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1760 tp->snd_scale = tp->requested_s_scale;
1761 tp->rcv_scale = tp->request_r_scale;
1766 acked = th->th_ack - tp->snd_una;
1767 tcpstat.tcps_rcvackpack++;
1768 tcpstat.tcps_rcvackbyte += acked;
1771 * If we just performed our first retransmit, and the ACK
1772 * arrives within our recovery window, then it was a mistake
1773 * to do the retransmit in the first place. Recover our
1774 * original cwnd and ssthresh, and proceed to transmit where
1777 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1778 tp->snd_cwnd = tp->snd_cwnd_prev;
1779 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1780 tp->snd_high = tp->snd_high_prev;
1781 tp->snd_nxt = tp->snd_max;
1782 tp->t_badrxtwin = 0; /* XXX probably not required */
1786 * If we have a timestamp reply, update smoothed
1787 * round trip time. If no timestamp is present but
1788 * transmit timer is running and timed sequence
1789 * number was acked, update smoothed round trip time.
1790 * Since we now have an rtt measurement, cancel the
1791 * timer backoff (cf., Phil Karn's retransmit alg.).
1792 * Recompute the initial retransmit timer.
1794 * Some machines (certain windows boxes) send broken
1795 * timestamp replies during the SYN+ACK phase, ignore
1798 if ((to.to_flags & TOF_TS) != 0 &&
1800 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1801 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1802 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1804 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1807 * If all outstanding data is acked, stop retransmit
1808 * timer and remember to restart (more output or persist).
1809 * If there is more data to be acked, restart retransmit
1810 * timer, using current (possibly backed-off) value.
1812 if (th->th_ack == tp->snd_max) {
1813 callout_stop(tp->tt_rexmt);
1815 } else if (!callout_active(tp->tt_persist))
1816 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1817 tcp_timer_rexmt, tp);
1820 * If no data (only SYN) was ACK'd,
1821 * skip rest of ACK processing.
1827 * When new data is acked, open the congestion window.
1828 * If the window gives us less than ssthresh packets
1829 * in flight, open exponentially (maxseg per packet).
1830 * Otherwise open linearly: maxseg per window
1831 * (maxseg^2 / cwnd per packet).
1833 if (!tcp_do_newreno || SEQ_GEQ(tp->snd_una, tp->snd_recover)) {
1834 register u_int cw = tp->snd_cwnd;
1835 register u_int incr = tp->t_maxseg;
1836 if (cw > tp->snd_ssthresh)
1837 incr = incr * incr / cw;
1838 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1840 if (acked > so->so_snd.sb_cc) {
1841 tp->snd_wnd -= so->so_snd.sb_cc;
1842 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1845 sbdrop(&so->so_snd, acked);
1846 tp->snd_wnd -= acked;
1850 /* detect una wraparound */
1851 if (SEQ_GEQ(tp->snd_una, tp->snd_recover) &&
1852 SEQ_LT(th->th_ack, tp->snd_recover))
1853 tp->snd_recover = th->th_ack;
1854 if (SEQ_GT(tp->snd_una, tp->snd_high) &&
1855 SEQ_LEQ(th->th_ack, tp->snd_high))
1856 tp->snd_high = th->th_ack - 1;
1857 tp->snd_una = th->th_ack;
1858 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1859 tp->snd_nxt = tp->snd_una;
1861 switch (tp->t_state) {
1864 * In FIN_WAIT_1 STATE in addition to the processing
1865 * for the ESTABLISHED state if our FIN is now acknowledged
1866 * then enter FIN_WAIT_2.
1868 case TCPS_FIN_WAIT_1:
1869 if (ourfinisacked) {
1871 * If we can't receive any more
1872 * data, then closing user can proceed.
1873 * Starting the timer is contrary to the
1874 * specification, but if we don't get a FIN
1875 * we'll hang forever.
1877 if (so->so_state & SS_CANTRCVMORE) {
1878 soisdisconnected(so);
1879 callout_reset(tp->tt_2msl, tcp_maxidle,
1880 tcp_timer_2msl, tp);
1882 tp->t_state = TCPS_FIN_WAIT_2;
1887 * In CLOSING STATE in addition to the processing for
1888 * the ESTABLISHED state if the ACK acknowledges our FIN
1889 * then enter the TIME-WAIT state, otherwise ignore
1893 if (ourfinisacked) {
1894 tp->t_state = TCPS_TIME_WAIT;
1895 tcp_canceltimers(tp);
1896 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1897 if (tp->cc_recv != 0 &&
1898 (ticks - tp->t_starttime) < tcp_msl)
1899 callout_reset(tp->tt_2msl,
1902 tcp_timer_2msl, tp);
1904 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1905 tcp_timer_2msl, tp);
1906 soisdisconnected(so);
1911 * In LAST_ACK, we may still be waiting for data to drain
1912 * and/or to be acked, as well as for the ack of our FIN.
1913 * If our FIN is now acknowledged, delete the TCB,
1914 * enter the closed state and return.
1917 if (ourfinisacked) {
1924 * In TIME_WAIT state the only thing that should arrive
1925 * is a retransmission of the remote FIN. Acknowledge
1926 * it and restart the finack timer.
1928 case TCPS_TIME_WAIT:
1929 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1930 tcp_timer_2msl, tp);
1937 * Update window information.
1938 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1940 if ((thflags & TH_ACK) &&
1941 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1942 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1943 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1944 /* keep track of pure window updates */
1946 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1947 tcpstat.tcps_rcvwinupd++;
1948 tp->snd_wnd = tiwin;
1949 tp->snd_wl1 = th->th_seq;
1950 tp->snd_wl2 = th->th_ack;
1951 if (tp->snd_wnd > tp->max_sndwnd)
1952 tp->max_sndwnd = tp->snd_wnd;
1957 * Process segments with URG.
1959 if ((thflags & TH_URG) && th->th_urp &&
1960 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1962 * This is a kludge, but if we receive and accept
1963 * random urgent pointers, we'll crash in
1964 * soreceive. It's hard to imagine someone
1965 * actually wanting to send this much urgent data.
1967 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1968 th->th_urp = 0; /* XXX */
1969 thflags &= ~TH_URG; /* XXX */
1970 goto dodata; /* XXX */
1973 * If this segment advances the known urgent pointer,
1974 * then mark the data stream. This should not happen
1975 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1976 * a FIN has been received from the remote side.
1977 * In these states we ignore the URG.
1979 * According to RFC961 (Assigned Protocols),
1980 * the urgent pointer points to the last octet
1981 * of urgent data. We continue, however,
1982 * to consider it to indicate the first octet
1983 * of data past the urgent section as the original
1984 * spec states (in one of two places).
1986 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1987 tp->rcv_up = th->th_seq + th->th_urp;
1988 so->so_oobmark = so->so_rcv.sb_cc +
1989 (tp->rcv_up - tp->rcv_nxt) - 1;
1990 if (so->so_oobmark == 0)
1991 so->so_state |= SS_RCVATMARK;
1993 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1996 * Remove out of band data so doesn't get presented to user.
1997 * This can happen independent of advancing the URG pointer,
1998 * but if two URG's are pending at once, some out-of-band
1999 * data may creep in... ick.
2001 if (th->th_urp <= (u_long)tlen
2003 && (so->so_options & SO_OOBINLINE) == 0
2006 tcp_pulloutofband(so, th, m,
2007 drop_hdrlen); /* hdr drop is delayed */
2010 * If no out of band data is expected,
2011 * pull receive urgent pointer along
2012 * with the receive window.
2014 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2015 tp->rcv_up = tp->rcv_nxt;
2020 * Process the segment text, merging it into the TCP sequencing queue,
2021 * and arranging for acknowledgment of receipt if necessary.
2022 * This process logically involves adjusting tp->rcv_wnd as data
2023 * is presented to the user (this happens in tcp_usrreq.c,
2024 * case PRU_RCVD). If a FIN has already been received on this
2025 * connection then we just ignore the text.
2027 if ((tlen || (thflags & TH_FIN)) &&
2028 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2029 m_adj(m, drop_hdrlen); /* delayed header drop */
2031 * Insert segment which includes th into TCP reassembly queue
2032 * with control block tp. Set thflags to whether reassembly now
2033 * includes a segment with FIN. This handles the common case
2034 * inline (segment is the next to be received on an established
2035 * connection, and the queue is empty), avoiding linkage into
2036 * and removal from the queue and repetition of various
2038 * Set DELACK for segments received in order, but ack
2039 * immediately when segments are out of order (so
2040 * fast retransmit can work).
2042 if (th->th_seq == tp->rcv_nxt &&
2043 LIST_EMPTY(&tp->t_segq) &&
2044 TCPS_HAVEESTABLISHED(tp->t_state)) {
2046 callout_reset(tp->tt_delack, tcp_delacktime,
2047 tcp_timer_delack, tp);
2049 tp->t_flags |= TF_ACKNOW;
2050 tp->rcv_nxt += tlen;
2051 thflags = th->th_flags & TH_FIN;
2052 tcpstat.tcps_rcvpack++;
2053 tcpstat.tcps_rcvbyte += tlen;
2055 if (so->so_state & SS_CANTRCVMORE)
2058 sbappend(&so->so_rcv, m);
2061 thflags = tcp_reass(tp, th, &tlen, m);
2062 tp->t_flags |= TF_ACKNOW;
2066 * Note the amount of data that peer has sent into
2067 * our window, in order to estimate the sender's
2070 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2077 * If FIN is received ACK the FIN and let the user know
2078 * that the connection is closing.
2080 if (thflags & TH_FIN) {
2081 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2084 * If connection is half-synchronized
2085 * (ie NEEDSYN flag on) then delay ACK,
2086 * so it may be piggybacked when SYN is sent.
2087 * Otherwise, since we received a FIN then no
2088 * more input can be expected, send ACK now.
2090 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2091 callout_reset(tp->tt_delack, tcp_delacktime,
2092 tcp_timer_delack, tp);
2094 tp->t_flags |= TF_ACKNOW;
2097 switch (tp->t_state) {
2100 * In SYN_RECEIVED and ESTABLISHED STATES
2101 * enter the CLOSE_WAIT state.
2103 case TCPS_SYN_RECEIVED:
2104 tp->t_starttime = ticks;
2106 case TCPS_ESTABLISHED:
2107 tp->t_state = TCPS_CLOSE_WAIT;
2111 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2112 * enter the CLOSING state.
2114 case TCPS_FIN_WAIT_1:
2115 tp->t_state = TCPS_CLOSING;
2119 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2120 * starting the time-wait timer, turning off the other
2123 case TCPS_FIN_WAIT_2:
2124 tp->t_state = TCPS_TIME_WAIT;
2125 tcp_canceltimers(tp);
2126 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2127 if (tp->cc_recv != 0 &&
2128 (ticks - tp->t_starttime) < tcp_msl) {
2129 callout_reset(tp->tt_2msl,
2130 tp->t_rxtcur * TCPTV_TWTRUNC,
2131 tcp_timer_2msl, tp);
2132 /* For transaction client, force ACK now. */
2133 tp->t_flags |= TF_ACKNOW;
2136 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2137 tcp_timer_2msl, tp);
2138 soisdisconnected(so);
2142 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2144 case TCPS_TIME_WAIT:
2145 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2146 tcp_timer_2msl, tp);
2151 if (so->so_options & SO_DEBUG)
2152 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2157 * Return any desired output.
2159 if (needoutput || (tp->t_flags & TF_ACKNOW))
2160 (void) tcp_output(tp);
2165 * Generate an ACK dropping incoming segment if it occupies
2166 * sequence space, where the ACK reflects our state.
2168 * We can now skip the test for the RST flag since all
2169 * paths to this code happen after packets containing
2170 * RST have been dropped.
2172 * In the SYN-RECEIVED state, don't send an ACK unless the
2173 * segment we received passes the SYN-RECEIVED ACK test.
2174 * If it fails send a RST. This breaks the loop in the
2175 * "LAND" DoS attack, and also prevents an ACK storm
2176 * between two listening ports that have been sent forged
2177 * SYN segments, each with the source address of the other.
2179 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2180 (SEQ_GT(tp->snd_una, th->th_ack) ||
2181 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2182 rstreason = BANDLIM_RST_OPENPORT;
2186 if (so->so_options & SO_DEBUG)
2187 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2191 tp->t_flags |= TF_ACKNOW;
2192 (void) tcp_output(tp);
2197 * Generate a RST, dropping incoming segment.
2198 * Make ACK acceptable to originator of segment.
2199 * Don't bother to respond if destination was broadcast/multicast.
2201 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2204 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2205 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2208 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2209 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2210 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2211 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2214 /* IPv6 anycast check is done at tcp6_input() */
2217 * Perform bandwidth limiting.
2220 if (badport_bandlim(rstreason) < 0)
2225 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2226 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2229 if (thflags & TH_ACK)
2230 /* mtod() below is safe as long as hdr dropping is delayed */
2231 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2234 if (thflags & TH_SYN)
2236 /* mtod() below is safe as long as hdr dropping is delayed */
2237 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2238 (tcp_seq)0, TH_RST|TH_ACK);
2244 * Drop space held by incoming segment and return.
2247 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2248 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2256 * Parse TCP options and place in tcpopt.
2259 tcp_dooptions(to, cp, cnt, is_syn)
2267 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2269 if (opt == TCPOPT_EOL)
2271 if (opt == TCPOPT_NOP)
2277 if (optlen < 2 || optlen > cnt)
2282 if (optlen != TCPOLEN_MAXSEG)
2286 to->to_flags |= TOF_MSS;
2287 bcopy((char *)cp + 2,
2288 (char *)&to->to_mss, sizeof(to->to_mss));
2289 to->to_mss = ntohs(to->to_mss);
2292 if (optlen != TCPOLEN_WINDOW)
2296 to->to_flags |= TOF_SCALE;
2297 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2299 case TCPOPT_TIMESTAMP:
2300 if (optlen != TCPOLEN_TIMESTAMP)
2302 to->to_flags |= TOF_TS;
2303 bcopy((char *)cp + 2,
2304 (char *)&to->to_tsval, sizeof(to->to_tsval));
2305 to->to_tsval = ntohl(to->to_tsval);
2306 bcopy((char *)cp + 6,
2307 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2308 to->to_tsecr = ntohl(to->to_tsecr);
2311 if (optlen != TCPOLEN_CC)
2313 to->to_flags |= TOF_CC;
2314 bcopy((char *)cp + 2,
2315 (char *)&to->to_cc, sizeof(to->to_cc));
2316 to->to_cc = ntohl(to->to_cc);
2319 if (optlen != TCPOLEN_CC)
2323 to->to_flags |= TOF_CCNEW;
2324 bcopy((char *)cp + 2,
2325 (char *)&to->to_cc, sizeof(to->to_cc));
2326 to->to_cc = ntohl(to->to_cc);
2329 if (optlen != TCPOLEN_CC)
2333 to->to_flags |= TOF_CCECHO;
2334 bcopy((char *)cp + 2,
2335 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2336 to->to_ccecho = ntohl(to->to_ccecho);
2345 * Pull out of band byte out of a segment so
2346 * it doesn't appear in the user's data queue.
2347 * It is still reflected in the segment length for
2348 * sequencing purposes.
2351 tcp_pulloutofband(so, th, m, off)
2354 register struct mbuf *m;
2355 int off; /* delayed to be droped hdrlen */
2357 int cnt = off + th->th_urp - 1;
2360 if (m->m_len > cnt) {
2361 char *cp = mtod(m, caddr_t) + cnt;
2362 struct tcpcb *tp = sototcpcb(so);
2365 tp->t_oobflags |= TCPOOB_HAVEDATA;
2366 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2368 if (m->m_flags & M_PKTHDR)
2377 panic("tcp_pulloutofband");
2381 * Collect new round-trip time estimate
2382 * and update averages and current timeout.
2385 tcp_xmit_timer(tp, rtt)
2386 register struct tcpcb *tp;
2391 tcpstat.tcps_rttupdated++;
2393 if (tp->t_srtt != 0) {
2395 * srtt is stored as fixed point with 5 bits after the
2396 * binary point (i.e., scaled by 8). The following magic
2397 * is equivalent to the smoothing algorithm in rfc793 with
2398 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2399 * point). Adjust rtt to origin 0.
2401 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2402 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2404 if ((tp->t_srtt += delta) <= 0)
2408 * We accumulate a smoothed rtt variance (actually, a
2409 * smoothed mean difference), then set the retransmit
2410 * timer to smoothed rtt + 4 times the smoothed variance.
2411 * rttvar is stored as fixed point with 4 bits after the
2412 * binary point (scaled by 16). The following is
2413 * equivalent to rfc793 smoothing with an alpha of .75
2414 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2415 * rfc793's wired-in beta.
2419 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2420 if ((tp->t_rttvar += delta) <= 0)
2422 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2423 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2426 * No rtt measurement yet - use the unsmoothed rtt.
2427 * Set the variance to half the rtt (so our first
2428 * retransmit happens at 3*rtt).
2430 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2431 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2432 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2438 * the retransmit should happen at rtt + 4 * rttvar.
2439 * Because of the way we do the smoothing, srtt and rttvar
2440 * will each average +1/2 tick of bias. When we compute
2441 * the retransmit timer, we want 1/2 tick of rounding and
2442 * 1 extra tick because of +-1/2 tick uncertainty in the
2443 * firing of the timer. The bias will give us exactly the
2444 * 1.5 tick we need. But, because the bias is
2445 * statistical, we have to test that we don't drop below
2446 * the minimum feasible timer (which is 2 ticks).
2448 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2449 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2452 * We received an ack for a packet that wasn't retransmitted;
2453 * it is probably safe to discard any error indications we've
2454 * received recently. This isn't quite right, but close enough
2455 * for now (a route might have failed after we sent a segment,
2456 * and the return path might not be symmetrical).
2458 tp->t_softerror = 0;
2462 * Determine a reasonable value for maxseg size.
2463 * If the route is known, check route for mtu.
2464 * If none, use an mss that can be handled on the outgoing
2465 * interface without forcing IP to fragment; if bigger than
2466 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2467 * to utilize large mbufs. If no route is found, route has no mtu,
2468 * or the destination isn't local, use a default, hopefully conservative
2469 * size (usually 512 or the default IP max size, but no more than the mtu
2470 * of the interface), as we can't discover anything about intervening
2471 * gateways or networks. We also initialize the congestion/slow start
2472 * window to be a single segment if the destination isn't local.
2473 * While looking at the routing entry, we also initialize other path-dependent
2474 * parameters from pre-set or cached values in the routing entry.
2476 * Also take into account the space needed for options that we
2477 * send regularly. Make maxseg shorter by that amount to assure
2478 * that we can send maxseg amount of data even when the options
2479 * are present. Store the upper limit of the length of options plus
2482 * NOTE that this routine is only called when we process an incoming
2483 * segment, for outgoing segments only tcp_mssopt is called.
2485 * In case of T/TCP, we call this routine during implicit connection
2486 * setup as well (offer = -1), to initialize maxseg from the cached
2494 register struct rtentry *rt;
2496 register int rtt, mss;
2498 struct inpcb *inp = tp->t_inpcb;
2500 struct rmxp_tao *taop;
2501 int origoffer = offer;
2503 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2504 size_t min_protoh = isipv6 ?
2505 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2506 sizeof(struct tcpiphdr);
2508 const int isipv6 = 0;
2509 const size_t min_protoh = sizeof(struct tcpiphdr);
2513 rt = tcp_rtlookup6(&inp->inp_inc);
2515 rt = tcp_rtlookup(&inp->inp_inc);
2517 tp->t_maxopd = tp->t_maxseg =
2518 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2522 so = inp->inp_socket;
2524 taop = rmx_taop(rt->rt_rmx);
2526 * Offer == -1 means that we didn't receive SYN yet,
2527 * use cached value in that case;
2530 offer = taop->tao_mssopt;
2532 * Offer == 0 means that there was no MSS on the SYN segment,
2533 * in this case we use tcp_mssdflt.
2536 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2539 * Sanity check: make sure that maxopd will be large
2540 * enough to allow some data on segments even is the
2541 * all the option space is used (40bytes). Otherwise
2542 * funny things may happen in tcp_output.
2544 offer = max(offer, 64);
2545 taop->tao_mssopt = offer;
2548 * While we're here, check if there's an initial rtt
2549 * or rttvar. Convert from the route-table units
2550 * to scaled multiples of the slow timeout timer.
2552 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2554 * XXX the lock bit for RTT indicates that the value
2555 * is also a minimum value; this is subject to time.
2557 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2558 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2559 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2560 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2561 tcpstat.tcps_usedrtt++;
2562 if (rt->rt_rmx.rmx_rttvar) {
2563 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2564 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2565 tcpstat.tcps_usedrttvar++;
2567 /* default variation is +- 1 rtt */
2569 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2571 TCPT_RANGESET(tp->t_rxtcur,
2572 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2573 tp->t_rttmin, TCPTV_REXMTMAX);
2576 * if there's an mtu associated with the route, use it
2577 * else, use the link mtu.
2579 if (rt->rt_rmx.rmx_mtu)
2580 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2583 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2585 if (!in6_localaddr(&inp->in6p_faddr))
2586 mss = min(mss, tcp_v6mssdflt);
2588 mss = ifp->if_mtu - min_protoh;
2589 if (!in_localaddr(inp->inp_faddr))
2590 mss = min(mss, tcp_mssdflt);
2593 mss = min(mss, offer);
2595 * maxopd stores the maximum length of data AND options
2596 * in a segment; maxseg is the amount of data in a normal
2597 * segment. We need to store this value (maxopd) apart
2598 * from maxseg, because now every segment carries options
2599 * and thus we normally have somewhat less data in segments.
2604 * In case of T/TCP, origoffer==-1 indicates, that no segments
2605 * were received yet. In this case we just guess, otherwise
2606 * we do the same as before T/TCP.
2608 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2610 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2611 mss -= TCPOLEN_TSTAMP_APPA;
2612 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2614 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2615 mss -= TCPOLEN_CC_APPA;
2617 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2619 mss &= ~(MCLBYTES-1);
2622 mss = mss / MCLBYTES * MCLBYTES;
2625 * If there's a pipesize, change the socket buffer
2626 * to that size. Make the socket buffers an integral
2627 * number of mss units; if the mss is larger than
2628 * the socket buffer, decrease the mss.
2631 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2633 bufsize = so->so_snd.sb_hiwat;
2637 bufsize = roundup(bufsize, mss);
2638 if (bufsize > sb_max)
2640 if (bufsize > so->so_snd.sb_hiwat)
2641 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2646 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2648 bufsize = so->so_rcv.sb_hiwat;
2649 if (bufsize > mss) {
2650 bufsize = roundup(bufsize, mss);
2651 if (bufsize > sb_max)
2653 if (bufsize > so->so_rcv.sb_hiwat)
2654 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2658 * Set the slow-start flight size depending on whether this
2659 * is a local network or not.
2661 if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2662 (!isipv6 && in_localaddr(inp->inp_faddr)))
2663 tp->snd_cwnd = mss * ss_fltsz_local;
2665 tp->snd_cwnd = mss * ss_fltsz;
2667 if (rt->rt_rmx.rmx_ssthresh) {
2669 * There's some sort of gateway or interface
2670 * buffer limit on the path. Use this to set
2671 * the slow start threshhold, but set the
2672 * threshold to no less than 2*mss.
2674 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2675 tcpstat.tcps_usedssthresh++;
2680 * Determine the MSS option to send on an outgoing SYN.
2688 int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2689 int min_protoh = isipv6 ?
2690 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2691 sizeof(struct tcpiphdr);
2693 const int isipv6 = 0;
2694 const size_t min_protoh = sizeof(struct tcpiphdr);
2698 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2700 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2702 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2704 return (rt->rt_ifp->if_mtu - min_protoh);
2709 * When a partial ack arrives, force the retransmission of the
2710 * next unacknowledged segment. Do not clear tp->t_dupacks.
2711 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2715 tcp_newreno_partial_ack(tp, th)
2719 tcp_seq onxt = tp->snd_nxt;
2720 u_long ocwnd = tp->snd_cwnd;
2722 callout_stop(tp->tt_rexmt);
2724 tp->snd_nxt = th->th_ack;
2726 * Set snd_cwnd to one segment beyond acknowledged offset
2727 * (tp->snd_una has not yet been updated when this function is called.)
2729 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2730 tp->t_flags |= TF_ACKNOW;
2731 (void) tcp_output(tp);
2732 tp->snd_cwnd = ocwnd;
2733 if (SEQ_GT(onxt, tp->snd_nxt))
2736 * Partial window deflation. Relies on fact that tp->snd_una
2739 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);