Patch forr FreeBSD-SA-04:04.tcp
[dragonfly.git] / sys / netinet / tcp_input.c
1 /*
2  * Copyright (c) 2002-2003 Jeffrey Hsu
3  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by the University of
17  *      California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
35  * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
36  * $DragonFly: src/sys/netinet/tcp_input.c,v 1.15 2004/03/02 20:41:13 rob Exp $
37  */
38
39 #include "opt_ipfw.h"           /* for ipfw_fwd         */
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
42 #include "opt_tcpdebug.h"
43 #include "opt_tcp_input.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>           /* for proc0 declaration */
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/syslog.h>
56 #include <sys/in_cksum.h>
57
58 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
59
60 #include <net/if.h>
61 #include <net/route.h>
62
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_icmp.h>    /* for ICMP_BANDLIM             */
67 #include <netinet/in_var.h>
68 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM             */
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/nd6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/in6_pcb.h>
76 #include <netinet/tcp.h>
77 #include <netinet/tcp_fsm.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/tcp_timer.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet6/tcp6_var.h>
82 #include <netinet/tcpip.h>
83 #ifdef TCPDEBUG
84 #include <netinet/tcp_debug.h>
85
86 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
87 struct tcphdr tcp_savetcp;
88 #endif /* TCPDEBUG */
89
90 #ifdef FAST_IPSEC
91 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
93 #endif
94
95 #ifdef IPSEC
96 #include <netinet6/ipsec.h>
97 #include <netinet6/ipsec6.h>
98 #include <netproto/key/key.h>
99 #endif /*IPSEC*/
100
101 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
102
103 static const int tcprexmtthresh = 3;
104 tcp_cc  tcp_ccgen;
105
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)");
109
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");
113
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");
117
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");
122
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");
127 #endif
128
129 static int tcp_do_limitedtransmit = 1;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
131     &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
132
133 static int tcp_do_rfc3390 = 1;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
135     &tcp_do_rfc3390, 0,
136     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
137
138 static int tcp_do_eifel_detect = 1;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
140     &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
141
142 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
143     "TCP Segment Reassembly Queue");
144
145 int tcp_reass_maxseg = 0;
146 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
147     &tcp_reass_maxseg, 0,
148     "Global maximum number of TCP Segments in Reassembly Queue");
149
150 int tcp_reass_qsize = 0;
151 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
152     &tcp_reass_qsize, 0,
153     "Global number of TCP Segments currently in Reassembly Queue");
154
155 static int tcp_reass_overflows = 0;
156 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157     &tcp_reass_overflows, 0,
158     "Global number of TCP Segment Reassembly Queue Overflows");
159
160 struct inpcbhead tcb;
161 #define tcb6    tcb  /* for KAME src sync over BSD*'s */
162 struct inpcbinfo tcbinfo;
163
164 static void      tcp_dooptions(struct tcpopt *, u_char *, int, int);
165 static void      tcp_pulloutofband(struct socket *,
166                      struct tcphdr *, struct mbuf *, int);
167 static int       tcp_reass(struct tcpcb *, struct tcphdr *, int *,
168                      struct mbuf *);
169 static void      tcp_xmit_timer(struct tcpcb *, int);
170 static void      tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
171
172 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
173 #ifdef INET6
174 #define ND6_HINT(tp) \
175 do { \
176         if ((tp) && (tp)->t_inpcb && \
177             ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
178             (tp)->t_inpcb->in6p_route.ro_rt) \
179                 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
180 } while (0)
181 #else
182 #define ND6_HINT(tp)
183 #endif
184
185 /*
186  * Indicate whether this ack should be delayed.  We can delay the ack if
187  *      - delayed acks are enabled and
188  *      - there is no delayed ack timer in progress and
189  *      - our last ack wasn't a 0-sized window.  We never want to delay
190  *        the ack that opens up a 0-sized window.
191  */
192 #define DELAY_ACK(tp) \
193         (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
194         (tp->t_flags & TF_RXWIN0SENT) == 0)
195
196 static int
197 tcp_reass(tp, th, tlenp, m)
198         struct tcpcb *tp;
199         struct tcphdr *th;
200         int *tlenp;
201         struct mbuf *m;
202 {
203         struct tseg_qent *q;
204         struct tseg_qent *p = NULL;
205         struct tseg_qent *nq;
206         struct tseg_qent *te;
207         struct socket *so = tp->t_inpcb->inp_socket;
208         int flags;
209
210         /*
211          * Call with th==0 after become established to
212          * force pre-ESTABLISHED data up to user socket.
213          */
214         if (th == 0)
215                 goto present;
216
217         /*
218          * Limit the number of segments in the reassembly queue to prevent
219          * holding on to too many segments (and thus running out of mbufs).
220          * Make sure to let the missing segment through which caused this
221          * queue.  Always keep one global queue entry spare to be able to
222          * process the missing segment.
223          */
224         if (th->th_seq != tp->rcv_nxt &&
225             tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
226                 tcp_reass_overflows++;
227                 tcpstat.tcps_rcvmemdrop++;
228                 m_freem(m);
229                 return (0);
230         }
231
232         /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
233         MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
234                M_NOWAIT);
235         if (te == NULL) {
236                 tcpstat.tcps_rcvmemdrop++;
237                 m_freem(m);
238                 return (0);
239         }
240         tcp_reass_qsize++;
241
242         /*
243          * Find a segment which begins after this one does.
244          */
245         LIST_FOREACH(q, &tp->t_segq, tqe_q) {
246                 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
247                         break;
248                 p = q;
249         }
250
251         /*
252          * If there is a preceding segment, it may provide some of
253          * our data already.  If so, drop the data from the incoming
254          * segment.  If it provides all of our data, drop us.
255          */
256         if (p != NULL) {
257                 int i;
258                 /* conversion to int (in i) handles seq wraparound */
259                 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
260                 if (i > 0) {
261                         if (i >= *tlenp) {
262                                 tcpstat.tcps_rcvduppack++;
263                                 tcpstat.tcps_rcvdupbyte += *tlenp;
264                                 m_freem(m);
265                                 free(te, M_TSEGQ);
266                                 tcp_reass_qsize--;
267                                 /*
268                                  * Try to present any queued data
269                                  * at the left window edge to the user.
270                                  * This is needed after the 3-WHS
271                                  * completes.
272                                  */
273                                 goto present;   /* ??? */
274                         }
275                         m_adj(m, i);
276                         *tlenp -= i;
277                         th->th_seq += i;
278                 }
279         }
280         tcpstat.tcps_rcvoopack++;
281         tcpstat.tcps_rcvoobyte += *tlenp;
282
283         /*
284          * While we overlap succeeding segments trim them or,
285          * if they are completely covered, dequeue them.
286          */
287         while (q) {
288                 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
289                 if (i <= 0)
290                         break;
291                 if (i < q->tqe_len) {
292                         q->tqe_th->th_seq += i;
293                         q->tqe_len -= i;
294                         m_adj(q->tqe_m, i);
295                         break;
296                 }
297
298                 nq = LIST_NEXT(q, tqe_q);
299                 LIST_REMOVE(q, tqe_q);
300                 m_freem(q->tqe_m);
301                 free(q, M_TSEGQ);
302                 tcp_reass_qsize--;
303                 q = nq;
304         }
305
306         /* Insert the new segment queue entry into place. */
307         te->tqe_m = m;
308         te->tqe_th = th;
309         te->tqe_len = *tlenp;
310
311         if (p == NULL) {
312                 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
313         } else {
314                 LIST_INSERT_AFTER(p, te, tqe_q);
315         }
316
317 present:
318         /*
319          * Present data to user, advancing rcv_nxt through
320          * completed sequence space.
321          */
322         if (!TCPS_HAVEESTABLISHED(tp->t_state))
323                 return (0);
324         q = LIST_FIRST(&tp->t_segq);
325         if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
326                 return (0);
327         do {
328                 tp->rcv_nxt += q->tqe_len;
329                 flags = q->tqe_th->th_flags & TH_FIN;
330                 nq = LIST_NEXT(q, tqe_q);
331                 LIST_REMOVE(q, tqe_q);
332                 if (so->so_state & SS_CANTRCVMORE)
333                         m_freem(q->tqe_m);
334                 else
335                         sbappend(&so->so_rcv, q->tqe_m);
336                 free(q, M_TSEGQ);
337                 tcp_reass_qsize--;
338                 q = nq;
339         } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
340         ND6_HINT(tp);
341         sorwakeup(so);
342         return (flags);
343 }
344
345 /*
346  * TCP input routine, follows pages 65-76 of the
347  * protocol specification dated September, 1981 very closely.
348  */
349 #ifdef INET6
350 int
351 tcp6_input(mp, offp, proto)
352         struct mbuf **mp;
353         int *offp, proto;
354 {
355         struct mbuf *m = *mp;
356         struct in6_ifaddr *ia6;
357
358         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
359
360         /*
361          * draft-itojun-ipv6-tcp-to-anycast
362          * better place to put this in?
363          */
364         ia6 = ip6_getdstifaddr(m);
365         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {                
366                 struct ip6_hdr *ip6;
367
368                 ip6 = mtod(m, struct ip6_hdr *);
369                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
370                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
371                 return IPPROTO_DONE;
372         }
373
374         tcp_input(m, *offp, proto);
375         return IPPROTO_DONE;
376 }
377 #endif
378
379 void
380 tcp_input(m, off0, proto)
381         struct mbuf *m;
382         int off0, proto;
383 {
384         struct tcphdr *th;
385         struct ip *ip = NULL;
386         struct ipovly *ipov;
387         struct inpcb *inp = NULL;
388         u_char *optp = NULL;
389         int optlen = 0;
390         int len, tlen, off;
391         int drop_hdrlen;
392         struct tcpcb *tp = NULL;
393         int thflags;
394         struct socket *so = 0;
395         int todrop, acked, ourfinisacked, needoutput = 0;
396         u_long tiwin;
397         struct tcpopt to;               /* options in this segment */
398         struct rmxp_tao *taop;          /* pointer to our TAO cache entry */
399         struct rmxp_tao tao_noncached;  /* in case there's no cached entry */
400         struct sockaddr_in *next_hop = NULL;
401         int rstreason; /* For badport_bandlim accounting purposes */
402         struct ip6_hdr *ip6 = NULL;
403 #ifdef INET6
404         int isipv6;
405 #else
406         const int isipv6 = 0;
407 #endif
408 #ifdef TCPDEBUG
409         short ostate = 0;
410 #endif
411
412         /* Grab info from MT_TAG mbufs prepended to the chain. */
413         for (;m && m->m_type == MT_TAG; m = m->m_next) {
414                 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
415                         next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
416         }
417 #ifdef INET6
418         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
419 #endif
420         bzero((char *)&to, sizeof(to));
421
422         tcpstat.tcps_rcvtotal++;
423
424         if (isipv6) {
425                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
426                 ip6 = mtod(m, struct ip6_hdr *);
427                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
428                 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
429                         tcpstat.tcps_rcvbadsum++;
430                         goto drop;
431                 }
432                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
433
434                 /*
435                  * Be proactive about unspecified IPv6 address in source.
436                  * As we use all-zero to indicate unbounded/unconnected pcb,
437                  * unspecified IPv6 address can be used to confuse us.
438                  *
439                  * Note that packets with unspecified IPv6 destination is
440                  * already dropped in ip6_input.
441                  */
442                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
443                         /* XXX stat */
444                         goto drop;
445                 }
446         } else {
447                 /*
448                  * Get IP and TCP header together in first mbuf.
449                  * Note: IP leaves IP header in first mbuf.
450                  */
451                 if (off0 > sizeof(struct ip)) {
452                         ip_stripoptions(m, (struct mbuf *)0);
453                         off0 = sizeof(struct ip);
454                 }
455                 if (m->m_len < sizeof(struct tcpiphdr)) {
456                         if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
457                                 tcpstat.tcps_rcvshort++;
458                                 return;
459                         }
460                 }
461                 ip = mtod(m, struct ip *);
462                 ipov = (struct ipovly *)ip;
463                 th = (struct tcphdr *)((caddr_t)ip + off0);
464                 tlen = ip->ip_len;
465
466                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
467                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
468                                 th->th_sum = m->m_pkthdr.csum_data;
469                         else
470                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
471                                                 ip->ip_dst.s_addr,
472                                                 htonl(m->m_pkthdr.csum_data +
473                                                         ip->ip_len +
474                                                         IPPROTO_TCP));
475                         th->th_sum ^= 0xffff;
476                 } else {
477                         /*
478                          * Checksum extended TCP header and data.
479                          */
480                         len = sizeof(struct ip) + tlen;
481                         bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
482                         ipov->ih_len = (u_short)tlen;
483                         ipov->ih_len = htons(ipov->ih_len);
484                         th->th_sum = in_cksum(m, len);
485                 }
486                 if (th->th_sum) {
487                         tcpstat.tcps_rcvbadsum++;
488                         goto drop;
489                 }
490 #ifdef INET6
491                 /* Re-initialization for later version check */
492                 ip->ip_v = IPVERSION;
493 #endif
494         }
495
496         /*
497          * Check that TCP offset makes sense,
498          * pull out TCP options and adjust length.              XXX
499          */
500         off = th->th_off << 2;
501         if (off < sizeof(struct tcphdr) || off > tlen) {
502                 tcpstat.tcps_rcvbadoff++;
503                 goto drop;
504         }
505         tlen -= off;    /* tlen is used instead of ti->ti_len */
506         if (off > sizeof(struct tcphdr)) {
507                 if (isipv6) {
508                         IP6_EXTHDR_CHECK(m, off0, off, );
509                         ip6 = mtod(m, struct ip6_hdr *);
510                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
511                 } else {
512                         if (m->m_len < sizeof(struct ip) + off) {
513                                 if ((m = m_pullup(m, sizeof(struct ip) + off))
514                                                 == 0) {
515                                         tcpstat.tcps_rcvshort++;
516                                         return;
517                                 }
518                                 ip = mtod(m, struct ip *);
519                                 ipov = (struct ipovly *)ip;
520                                 th = (struct tcphdr *)((caddr_t)ip + off0);
521                         }
522                 }
523                 optlen = off - sizeof(struct tcphdr);
524                 optp = (u_char *)(th + 1);
525         }
526         thflags = th->th_flags;
527
528 #ifdef TCP_DROP_SYNFIN
529         /*
530          * If the drop_synfin option is enabled, drop all packets with
531          * both the SYN and FIN bits set. This prevents e.g. nmap from
532          * identifying the TCP/IP stack.
533          *
534          * This is a violation of the TCP specification.
535          */
536         if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
537                 goto drop;
538 #endif
539
540         /*
541          * Convert TCP protocol specific fields to host format.
542          */
543         th->th_seq = ntohl(th->th_seq);
544         th->th_ack = ntohl(th->th_ack);
545         th->th_win = ntohs(th->th_win);
546         th->th_urp = ntohs(th->th_urp);
547
548         /*
549          * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
550          * until after ip6_savecontrol() is called and before other functions
551          * which don't want those proto headers.
552          * Because ip6_savecontrol() is going to parse the mbuf to
553          * search for data to be passed up to user-land, it wants mbuf
554          * parameters to be unchanged.
555          * XXX: the call of ip6_savecontrol() has been obsoleted based on
556          * latest version of the advanced API (20020110).
557          */
558         drop_hdrlen = off0 + off;
559
560         /*
561          * Locate pcb for segment.
562          */
563 findpcb:
564         /* IPFIREWALL_FORWARD section */
565         if (next_hop != NULL && isipv6 == 0) {  /* IPv6 support is not yet */
566                 /*
567                  * Transparently forwarded. Pretend to be the destination.
568                  * already got one like this? 
569                  */
570                 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
571                                         ip->ip_dst, th->th_dport,
572                                         0, m->m_pkthdr.rcvif);
573                 if (!inp) {
574                         /* It's new.  Try find the ambushing socket. */
575                         inp = in_pcblookup_hash(&tcbinfo,
576                                                 ip->ip_src, th->th_sport,
577                                                 next_hop->sin_addr,
578                                                 next_hop->sin_port ?
579                                                     ntohs(next_hop->sin_port) :
580                                                     th->th_dport,
581                                                 1, m->m_pkthdr.rcvif);
582                 }
583         } else {
584                 if (isipv6)
585                         inp = in6_pcblookup_hash(&tcbinfo,
586                                                  &ip6->ip6_src, th->th_sport,
587                                                  &ip6->ip6_dst, th->th_dport,
588                                                  1, m->m_pkthdr.rcvif);
589                 else
590                         inp = in_pcblookup_hash(&tcbinfo,
591                                                 ip->ip_src, th->th_sport,
592                                                 ip->ip_dst, th->th_dport,
593                                                 1, m->m_pkthdr.rcvif);
594       }
595
596 #ifdef IPSEC
597         if (isipv6) {
598                 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
599                         ipsec6stat.in_polvio++;
600                         goto drop;
601                 }
602         } else {
603                 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
604                         ipsecstat.in_polvio++;
605                         goto drop;
606                 }
607         }
608 #endif
609 #ifdef FAST_IPSEC
610         if (isipv6) {
611                 if (inp != NULL && ipsec6_in_reject(m, inp)) {
612                         goto drop;
613                 }
614         } else {
615                 if (inp != NULL && ipsec4_in_reject(m, inp)) {
616                         goto drop;
617                 }
618         }
619 #endif
620
621         /*
622          * If the state is CLOSED (i.e., TCB does not exist) then
623          * all data in the incoming segment is discarded.
624          * If the TCB exists but is in CLOSED state, it is embryonic,
625          * but should either do a listen or a connect soon.
626          */
627         if (inp == NULL) {
628                 if (log_in_vain) {
629 #ifdef INET6
630                         char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
631 #else
632                         char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
633 #endif
634                         if (isipv6) {
635                                 strcpy(dbuf, "[");
636                                 strcpy(sbuf, "[");
637                                 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
638                                 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
639                                 strcat(dbuf, "]");
640                                 strcat(sbuf, "]");
641                         } else {
642                                 strcpy(dbuf, inet_ntoa(ip->ip_dst));
643                                 strcpy(sbuf, inet_ntoa(ip->ip_src));
644                         }
645                         switch (log_in_vain) {
646                         case 1:
647                                 if ((thflags & TH_SYN) == 0)
648                                         break;
649                         case 2:
650                                 log(LOG_INFO,
651                                     "Connection attempt to TCP %s:%d "
652                                     "from %s:%d flags:0x%02x\n",
653                                     dbuf, ntohs(th->th_dport), sbuf,
654                                     ntohs(th->th_sport), thflags);
655                                 break;
656                         default:
657                                 break;
658                         }
659                 }
660                 if (blackhole) { 
661                         switch (blackhole) {
662                         case 1:
663                                 if (thflags & TH_SYN)
664                                         goto drop;
665                                 break;
666                         case 2:
667                                 goto drop;
668                         default:
669                                 goto drop;
670                         }
671                 }
672                 rstreason = BANDLIM_RST_CLOSEDPORT;
673                 goto dropwithreset;
674         }
675         tp = intotcpcb(inp);
676         if (tp == NULL) {
677                 rstreason = BANDLIM_RST_CLOSEDPORT;
678                 goto dropwithreset;
679         }
680         if (tp->t_state == TCPS_CLOSED)
681                 goto drop;
682
683         /* Unscale the window into a 32-bit value. */
684         if ((thflags & TH_SYN) == 0)
685                 tiwin = th->th_win << tp->snd_scale;
686         else
687                 tiwin = th->th_win;
688
689         so = inp->inp_socket;
690
691 #ifdef TCPDEBUG
692         if (so->so_options & SO_DEBUG) {
693                 ostate = tp->t_state;
694                 if (isipv6)
695                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
696                 else
697                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
698                 tcp_savetcp = *th;
699         }
700 #endif
701
702         if (so->so_options & SO_ACCEPTCONN) {
703                 struct in_conninfo inc;
704
705 #ifdef INET6
706                 inc.inc_isipv6 = isipv6;
707 #endif
708                 if (isipv6) {
709                         inc.inc6_faddr = ip6->ip6_src;
710                         inc.inc6_laddr = ip6->ip6_dst;
711                         inc.inc6_route.ro_rt = NULL;            /* XXX */
712                 } else {
713                         inc.inc_faddr = ip->ip_src;
714                         inc.inc_laddr = ip->ip_dst;
715                         inc.inc_route.ro_rt = NULL;             /* XXX */
716                 }
717                 inc.inc_fport = th->th_sport;
718                 inc.inc_lport = th->th_dport;
719
720                 /*
721                  * If the state is LISTEN then ignore segment if it contains
722                  * a RST.  If the segment contains an ACK then it is bad and
723                  * send a RST.  If it does not contain a SYN then it is not
724                  * interesting; drop it.
725                  *
726                  * If the state is SYN_RECEIVED (syncache) and seg contains
727                  * an ACK, but not for our SYN/ACK, send a RST.  If the seg
728                  * contains a RST, check the sequence number to see if it
729                  * is a valid reset segment.
730                  */
731                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
732                         if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
733                                 if (!syncache_expand(&inc, th, &so, m)) {
734                                         /*
735                                          * No syncache entry, or ACK was not
736                                          * for our SYN/ACK.  Send a RST.
737                                          */
738                                         tcpstat.tcps_badsyn++;
739                                         rstreason = BANDLIM_RST_OPENPORT;
740                                         goto dropwithreset;
741                                 }
742                                 if (so == NULL)
743                                         /*
744                                          * Could not complete 3-way handshake,
745                                          * connection is being closed down, and
746                                          * syncache will free mbuf.
747                                          */
748                                         return;
749                                 /*
750                                  * Socket is created in state SYN_RECEIVED.
751                                  * Continue processing segment.
752                                  */
753                                 inp = sotoinpcb(so);
754                                 tp = intotcpcb(inp);
755                                 /*
756                                  * This is what would have happened in
757                                  * tcp_output() when the SYN,ACK was sent.
758                                  */
759                                 tp->snd_up = tp->snd_una;
760                                 tp->snd_max = tp->snd_nxt = tp->iss + 1;
761                                 tp->last_ack_sent = tp->rcv_nxt;
762 /*
763  * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
764  * until the _second_ ACK is received:
765  *    rcv SYN (set wscale opts)  --> send SYN/ACK, set snd_wnd = window.
766  *    rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
767  *        move to ESTAB, set snd_wnd to tiwin.
768  */        
769                                 tp->snd_wnd = tiwin;    /* unscaled */
770                                 goto after_listen;
771                         }
772                         if (thflags & TH_RST) {
773                                 syncache_chkrst(&inc, th);
774                                 goto drop;
775                         }
776                         if (thflags & TH_ACK) {
777                                 syncache_badack(&inc);
778                                 tcpstat.tcps_badsyn++;
779                                 rstreason = BANDLIM_RST_OPENPORT;
780                                 goto dropwithreset;
781                         }
782                         goto drop;
783                 }
784
785                 /*
786                  * Segment's flags are (SYN) or (SYN|FIN).
787                  */
788 #ifdef INET6
789                 /*
790                  * If deprecated address is forbidden,
791                  * we do not accept SYN to deprecated interface
792                  * address to prevent any new inbound connection from
793                  * getting established.
794                  * When we do not accept SYN, we send a TCP RST,
795                  * with deprecated source address (instead of dropping
796                  * it).  We compromise it as it is much better for peer
797                  * to send a RST, and RST will be the final packet
798                  * for the exchange.
799                  *
800                  * If we do not forbid deprecated addresses, we accept
801                  * the SYN packet.  RFC2462 does not suggest dropping
802                  * SYN in this case.
803                  * If we decipher RFC2462 5.5.4, it says like this:
804                  * 1. use of deprecated addr with existing
805                  *    communication is okay - "SHOULD continue to be
806                  *    used"
807                  * 2. use of it with new communication:
808                  *   (2a) "SHOULD NOT be used if alternate address
809                  *        with sufficient scope is available"
810                  *   (2b) nothing mentioned otherwise.
811                  * Here we fall into (2b) case as we have no choice in
812                  * our source address selection - we must obey the peer.
813                  *
814                  * The wording in RFC2462 is confusing, and there are
815                  * multiple description text for deprecated address
816                  * handling - worse, they are not exactly the same.
817                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
818                  */
819                 if (isipv6 && !ip6_use_deprecated) {
820                         struct in6_ifaddr *ia6;
821
822                         if ((ia6 = ip6_getdstifaddr(m)) &&
823                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
824                                 tp = NULL;
825                                 rstreason = BANDLIM_RST_OPENPORT;
826                                 goto dropwithreset;
827                         }
828                 }
829 #endif
830                 /*
831                  * If it is from this socket, drop it, it must be forged.
832                  * Don't bother responding if the destination was a broadcast.
833                  */
834                 if (th->th_dport == th->th_sport) {
835                         if (isipv6) {
836                                 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
837                                                        &ip6->ip6_src))
838                                         goto drop;
839                         } else {
840                                 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
841                                         goto drop;
842                         }
843                 }
844                 /*
845                  * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
846                  *
847                  * Note that it is quite possible to receive unicast
848                  * link-layer packets with a broadcast IP address. Use
849                  * in_broadcast() to find them.
850                  */
851                 if (m->m_flags & (M_BCAST|M_MCAST))
852                         goto drop;
853                 if (isipv6) {
854                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
855                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
856                                 goto drop;
857                 } else {
858                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
859                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
860                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
861                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
862                                 goto drop;
863                 }
864                 /*
865                  * SYN appears to be valid; create compressed TCP state
866                  * for syncache, or perform t/tcp connection.
867                  */
868                 if (so->so_qlen <= so->so_qlimit) {
869                         tcp_dooptions(&to, optp, optlen, 1);
870                         if (!syncache_add(&inc, &to, th, &so, m))
871                                 goto drop;
872                         if (so == NULL)
873                                 /*
874                                  * Entry added to syncache, mbuf used to
875                                  * send SYN,ACK packet.
876                                  */
877                                 return;
878                         /*
879                          * Segment passed TAO tests.
880                          */
881                         inp = sotoinpcb(so);
882                         tp = intotcpcb(inp);
883                         tp->snd_wnd = tiwin;
884                         tp->t_starttime = ticks;
885                         tp->t_state = TCPS_ESTABLISHED;
886
887                         /*
888                          * If there is a FIN, or if there is data and the
889                          * connection is local, then delay SYN,ACK(SYN) in
890                          * the hope of piggy-backing it on a response
891                          * segment.  Otherwise must send ACK now in case
892                          * the other side is slow starting.
893                          */
894                         if (DELAY_ACK(tp) &&
895                             ((thflags & TH_FIN) ||
896                              (tlen != 0 &&
897                               ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
898                                (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
899                                 callout_reset(tp->tt_delack, tcp_delacktime,  
900                                                 tcp_timer_delack, tp);  
901                                 tp->t_flags |= TF_NEEDSYN;
902                         } else 
903                                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
904
905                         tcpstat.tcps_connects++;
906                         soisconnected(so);
907                         goto trimthenstep6;
908                 }
909                 goto drop;
910         }
911 after_listen:
912
913 /* XXX temp debugging */
914         /* should not happen - syncache should pick up these connections */
915         if (tp->t_state == TCPS_LISTEN)
916                 panic("tcp_input: TCPS_LISTEN");
917
918         /*
919          * Segment received on connection.
920          * Reset idle time and keep-alive timer.
921          */
922         tp->t_rcvtime = ticks;
923         if (TCPS_HAVEESTABLISHED(tp->t_state))
924                 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
925
926         /*
927          * Process options.
928          * XXX this is tradtitional behavior, may need to be cleaned up.
929          */
930         tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
931         if (thflags & TH_SYN) {
932                 if (to.to_flags & TOF_SCALE) {
933                         tp->t_flags |= TF_RCVD_SCALE;
934                         tp->requested_s_scale = to.to_requested_s_scale;
935                 }
936                 if (to.to_flags & TOF_TS) {
937                         tp->t_flags |= TF_RCVD_TSTMP;
938                         tp->ts_recent = to.to_tsval;
939                         tp->ts_recent_age = ticks;
940                 }
941                 if (to.to_flags & (TOF_CC|TOF_CCNEW))
942                         tp->t_flags |= TF_RCVD_CC;
943                 if (to.to_flags & TOF_MSS)
944                         tcp_mss(tp, to.to_mss);
945         }
946
947         /*
948          * Header prediction: check for the two common cases
949          * of a uni-directional data xfer.  If the packet has
950          * no control flags, is in-sequence, the window didn't
951          * change and we're not retransmitting, it's a
952          * candidate.  If the length is zero and the ack moved
953          * forward, we're the sender side of the xfer.  Just
954          * free the data acked & wake any higher level process
955          * that was blocked waiting for space.  If the length
956          * is non-zero and the ack didn't move, we're the
957          * receiver side.  If we're getting packets in-order
958          * (the reassembly queue is empty), add the data to
959          * the socket buffer and note that we need a delayed ack.
960          * Make sure that the hidden state-flags are also off.
961          * Since we check for TCPS_ESTABLISHED above, it can only
962          * be TH_NEEDSYN.
963          */
964         if (tp->t_state == TCPS_ESTABLISHED &&
965             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
966             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
967             ((to.to_flags & TOF_TS) == 0 ||
968              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
969             /*
970              * Using the CC option is compulsory if once started:
971              *   the segment is OK if no T/TCP was negotiated or
972              *   if the segment has a CC option equal to CCrecv
973              */
974             ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
975              ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
976             th->th_seq == tp->rcv_nxt &&
977             tiwin && tiwin == tp->snd_wnd &&
978             tp->snd_nxt == tp->snd_max) {
979
980                 /*
981                  * If last ACK falls within this segment's sequence numbers,
982                  * record the timestamp.
983                  * NOTE that the test is modified according to the latest
984                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
985                  */
986                 if ((to.to_flags & TOF_TS) != 0 &&
987                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
988                         tp->ts_recent_age = ticks;
989                         tp->ts_recent = to.to_tsval;
990                 }
991
992                 if (tlen == 0) {
993                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
994                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
995                             tp->snd_cwnd >= tp->snd_wnd &&
996                             ((!tcp_do_newreno &&
997                               tp->t_dupacks < tcprexmtthresh) ||
998                              (tcp_do_newreno && !IN_FASTRECOVERY(tp)))) {
999                                 /*
1000                                  * this is a pure ack for outstanding data.
1001                                  */
1002                                 ++tcpstat.tcps_predack;
1003                                 /*
1004                                  * "bad retransmit" recovery
1005                                  *
1006                                  * If Eifel detection applies, then
1007                                  * it is deterministic, so use it
1008                                  * unconditionally over the old heuristic.
1009                                  * Otherwise, fall back to the old heuristic.
1010                                  */
1011                                 if (tcp_do_eifel_detect &&
1012                                     (to.to_flags & TOF_TS) && to.to_tsecr &&
1013                                     (tp->t_flags & TF_FIRSTACCACK)) {
1014                                         /* Eifel detection applicable. */
1015                                         if (to.to_tsecr < tp->t_rexmtTS) {
1016                                                 tcp_revert_congestion_state(tp);
1017                                                 ++tcpstat.tcps_eifeldetected;
1018                                         }
1019                                 } else if (tp->t_rxtshift == 1 &&
1020                                            ticks < tp->t_badrxtwin) {
1021                                         tcp_revert_congestion_state(tp);
1022                                         ++tcpstat.tcps_rttdetected;
1023                                 }
1024                                 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1025                                 /*
1026                                  * Recalculate the retransmit timer / rtt.
1027                                  *
1028                                  * Some machines (certain windows boxes) 
1029                                  * send broken timestamp replies during the
1030                                  * SYN+ACK phase, ignore timestamps of 0.
1031                                  */
1032                                 if ((to.to_flags & TOF_TS) != 0 &&
1033                                     to.to_tsecr) {
1034                                         tcp_xmit_timer(tp,
1035                                             ticks - to.to_tsecr + 1);
1036                                 } else if (tp->t_rtttime &&
1037                                             SEQ_GT(th->th_ack, tp->t_rtseq)) {
1038                                         tcp_xmit_timer(tp,
1039                                                        ticks - tp->t_rtttime);
1040                                 }
1041                                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1042                                 acked = th->th_ack - tp->snd_una;
1043                                 tcpstat.tcps_rcvackpack++;
1044                                 tcpstat.tcps_rcvackbyte += acked;
1045                                 sbdrop(&so->so_snd, acked);
1046                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1047                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
1048                                         tp->snd_recover = th->th_ack - 1;
1049                                 tp->snd_una = th->th_ack;
1050                                 tp->t_dupacks = 0;
1051                                 m_freem(m);
1052                                 ND6_HINT(tp); /* some progress has been done */
1053
1054                                 /*
1055                                  * If all outstanding data are acked, stop
1056                                  * retransmit timer, otherwise restart timer
1057                                  * using current (possibly backed-off) value.
1058                                  * If process is waiting for space,
1059                                  * wakeup/selwakeup/signal.  If data
1060                                  * are ready to send, let tcp_output
1061                                  * decide between more output or persist.
1062                                  */
1063                                 if (tp->snd_una == tp->snd_max)
1064                                         callout_stop(tp->tt_rexmt);
1065                                 else if (!callout_active(tp->tt_persist))
1066                                         callout_reset(tp->tt_rexmt, 
1067                                                       tp->t_rxtcur,
1068                                                       tcp_timer_rexmt, tp);
1069
1070                                 sowwakeup(so);
1071                                 if (so->so_snd.sb_cc)
1072                                         (void) tcp_output(tp);
1073                                 return;
1074                         }
1075                 } else if (th->th_ack == tp->snd_una &&
1076                     LIST_EMPTY(&tp->t_segq) &&
1077                     tlen <= sbspace(&so->so_rcv)) {
1078                         /*
1079                          * this is a pure, in-sequence data packet
1080                          * with nothing on the reassembly queue and
1081                          * we have enough buffer space to take it.
1082                          */
1083                         ++tcpstat.tcps_preddat;
1084                         tp->rcv_nxt += tlen;
1085                         tcpstat.tcps_rcvpack++;
1086                         tcpstat.tcps_rcvbyte += tlen;
1087                         ND6_HINT(tp);   /* some progress has been done */
1088                         /*
1089                          * Add data to socket buffer.
1090                          */
1091                         if (so->so_state & SS_CANTRCVMORE) {
1092                                 m_freem(m);
1093                         } else {
1094                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
1095                                 sbappend(&so->so_rcv, m);
1096                         }
1097                         sorwakeup(so);
1098                         if (DELAY_ACK(tp)) {
1099                                 callout_reset(tp->tt_delack, tcp_delacktime,
1100                                     tcp_timer_delack, tp);
1101                         } else {
1102                                 tp->t_flags |= TF_ACKNOW;
1103                                 tcp_output(tp);
1104                         }
1105                         return;
1106                 }
1107         }
1108
1109         /*
1110          * Calculate amount of space in receive window,
1111          * and then do TCP input processing.
1112          * Receive window is amount of space in rcv queue,
1113          * but not less than advertised window.
1114          */
1115         { int win;
1116
1117         win = sbspace(&so->so_rcv);
1118         if (win < 0)
1119                 win = 0;
1120         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1121         }
1122
1123         switch (tp->t_state) {
1124
1125         /*
1126          * If the state is SYN_RECEIVED:
1127          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
1128          */
1129         case TCPS_SYN_RECEIVED:
1130                 if ((thflags & TH_ACK) &&
1131                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1132                      SEQ_GT(th->th_ack, tp->snd_max))) {
1133                                 rstreason = BANDLIM_RST_OPENPORT;
1134                                 goto dropwithreset;
1135                 }
1136                 break;
1137
1138         /*
1139          * If the state is SYN_SENT:
1140          *      if seg contains an ACK, but not for our SYN, drop the input.
1141          *      if seg contains a RST, then drop the connection.
1142          *      if seg does not contain SYN, then drop it.
1143          * Otherwise this is an acceptable SYN segment
1144          *      initialize tp->rcv_nxt and tp->irs
1145          *      if seg contains ack then advance tp->snd_una
1146          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1147          *      arrange for segment to be acked (eventually)
1148          *      continue processing rest of data/controls, beginning with URG
1149          */
1150         case TCPS_SYN_SENT:
1151                 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1152                         taop = &tao_noncached;
1153                         bzero(taop, sizeof(*taop));
1154                 }
1155
1156                 if ((thflags & TH_ACK) &&
1157                     (SEQ_LEQ(th->th_ack, tp->iss) ||
1158                      SEQ_GT(th->th_ack, tp->snd_max))) {
1159                         /*
1160                          * If we have a cached CCsent for the remote host,
1161                          * hence we haven't just crashed and restarted,
1162                          * do not send a RST.  This may be a retransmission
1163                          * from the other side after our earlier ACK was lost.
1164                          * Our new SYN, when it arrives, will serve as the
1165                          * needed ACK.
1166                          */
1167                         if (taop->tao_ccsent != 0)
1168                                 goto drop;
1169                         else {
1170                                 rstreason = BANDLIM_UNLIMITED;
1171                                 goto dropwithreset;
1172                         }
1173                 }
1174                 if (thflags & TH_RST) {
1175                         if (thflags & TH_ACK)
1176                                 tp = tcp_drop(tp, ECONNREFUSED);
1177                         goto drop;
1178                 }
1179                 if ((thflags & TH_SYN) == 0)
1180                         goto drop;
1181                 tp->snd_wnd = th->th_win;       /* initial send window */
1182                 tp->cc_recv = to.to_cc;         /* foreign CC */
1183
1184                 tp->irs = th->th_seq;
1185                 tcp_rcvseqinit(tp);
1186                 if (thflags & TH_ACK) {
1187                         /*
1188                          * Our SYN was acked.  If segment contains CC.ECHO
1189                          * option, check it to make sure this segment really
1190                          * matches our SYN.  If not, just drop it as old
1191                          * duplicate, but send an RST if we're still playing
1192                          * by the old rules.  If no CC.ECHO option, make sure
1193                          * we don't get fooled into using T/TCP.
1194                          */
1195                         if (to.to_flags & TOF_CCECHO) {
1196                                 if (tp->cc_send != to.to_ccecho) {
1197                                         if (taop->tao_ccsent != 0)
1198                                                 goto drop;
1199                                         else {
1200                                                 rstreason = BANDLIM_UNLIMITED;
1201                                                 goto dropwithreset;
1202                                         }
1203                                 }
1204                         } else
1205                                 tp->t_flags &= ~TF_RCVD_CC;
1206                         tcpstat.tcps_connects++;
1207                         soisconnected(so);
1208                         /* Do window scaling on this connection? */
1209                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1210                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1211                                 tp->snd_scale = tp->requested_s_scale;
1212                                 tp->rcv_scale = tp->request_r_scale;
1213                         }
1214                         /* Segment is acceptable, update cache if undefined. */
1215                         if (taop->tao_ccsent == 0)
1216                                 taop->tao_ccsent = to.to_ccecho;
1217
1218                         tp->rcv_adv += tp->rcv_wnd;
1219                         tp->snd_una++;          /* SYN is acked */
1220                         /*
1221                          * If there's data, delay ACK; if there's also a FIN
1222                          * ACKNOW will be turned on later.
1223                          */
1224                         if (DELAY_ACK(tp) && tlen != 0)
1225                                 callout_reset(tp->tt_delack, tcp_delacktime,  
1226                                     tcp_timer_delack, tp);  
1227                         else
1228                                 tp->t_flags |= TF_ACKNOW;
1229                         /*
1230                          * Received <SYN,ACK> in SYN_SENT[*] state.
1231                          * Transitions:
1232                          *      SYN_SENT  --> ESTABLISHED
1233                          *      SYN_SENT* --> FIN_WAIT_1
1234                          */
1235                         tp->t_starttime = ticks;
1236                         if (tp->t_flags & TF_NEEDFIN) {
1237                                 tp->t_state = TCPS_FIN_WAIT_1;
1238                                 tp->t_flags &= ~TF_NEEDFIN;
1239                                 thflags &= ~TH_SYN;
1240                         } else {
1241                                 tp->t_state = TCPS_ESTABLISHED;
1242                                 callout_reset(tp->tt_keep, tcp_keepidle,
1243                                               tcp_timer_keep, tp);
1244                         }
1245                 } else {
1246                         /*
1247                          * Received initial SYN in SYN-SENT[*] state =>
1248                          * simultaneous open.  If segment contains CC option
1249                          * and there is a cached CC, apply TAO test.
1250                          * If it succeeds, connection is * half-synchronized.
1251                          * Otherwise, do 3-way handshake:
1252                          *        SYN-SENT -> SYN-RECEIVED
1253                          *        SYN-SENT* -> SYN-RECEIVED*
1254                          * If there was no CC option, clear cached CC value.
1255                          */
1256                         tp->t_flags |= TF_ACKNOW;
1257                         callout_stop(tp->tt_rexmt);
1258                         if (to.to_flags & TOF_CC) {
1259                                 if (taop->tao_cc != 0 &&
1260                                     CC_GT(to.to_cc, taop->tao_cc)) {
1261                                         /*
1262                                          * update cache and make transition:
1263                                          *        SYN-SENT -> ESTABLISHED*
1264                                          *        SYN-SENT* -> FIN-WAIT-1*
1265                                          */
1266                                         taop->tao_cc = to.to_cc;
1267                                         tp->t_starttime = ticks;
1268                                         if (tp->t_flags & TF_NEEDFIN) {
1269                                                 tp->t_state = TCPS_FIN_WAIT_1;
1270                                                 tp->t_flags &= ~TF_NEEDFIN;
1271                                         } else {
1272                                                 tp->t_state = TCPS_ESTABLISHED;
1273                                                 callout_reset(tp->tt_keep,
1274                                                               tcp_keepidle,
1275                                                               tcp_timer_keep,
1276                                                               tp);
1277                                         }
1278                                         tp->t_flags |= TF_NEEDSYN;
1279                                 } else
1280                                         tp->t_state = TCPS_SYN_RECEIVED;
1281                         } else {
1282                                 /* CC.NEW or no option => invalidate cache */
1283                                 taop->tao_cc = 0;
1284                                 tp->t_state = TCPS_SYN_RECEIVED;
1285                         }
1286                 }
1287
1288 trimthenstep6:
1289                 /*
1290                  * Advance th->th_seq to correspond to first data byte.
1291                  * If data, trim to stay within window,
1292                  * dropping FIN if necessary.
1293                  */
1294                 th->th_seq++;
1295                 if (tlen > tp->rcv_wnd) {
1296                         todrop = tlen - tp->rcv_wnd;
1297                         m_adj(m, -todrop);
1298                         tlen = tp->rcv_wnd;
1299                         thflags &= ~TH_FIN;
1300                         tcpstat.tcps_rcvpackafterwin++;
1301                         tcpstat.tcps_rcvbyteafterwin += todrop;
1302                 }
1303                 tp->snd_wl1 = th->th_seq - 1;
1304                 tp->rcv_up = th->th_seq;
1305                 /*
1306                  * Client side of transaction: already sent SYN and data.
1307                  * If the remote host used T/TCP to validate the SYN,
1308                  * our data will be ACK'd; if so, enter normal data segment
1309                  * processing in the middle of step 5, ack processing.
1310                  * Otherwise, goto step 6.
1311                  */
1312                 if (thflags & TH_ACK)
1313                         goto process_ACK;
1314
1315                 goto step6;
1316
1317         /*
1318          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1319          *      if segment contains a SYN and CC [not CC.NEW] option:
1320          *              if state == TIME_WAIT and connection duration > MSL,
1321          *                  drop packet and send RST;
1322          *
1323          *              if SEG.CC > CCrecv then is new SYN, and can implicitly
1324          *                  ack the FIN (and data) in retransmission queue.
1325          *                  Complete close and delete TCPCB.  Then reprocess
1326          *                  segment, hoping to find new TCPCB in LISTEN state;
1327          *
1328          *              else must be old SYN; drop it.
1329          *      else do normal processing.
1330          */
1331         case TCPS_LAST_ACK:
1332         case TCPS_CLOSING:
1333         case TCPS_TIME_WAIT:
1334                 if ((thflags & TH_SYN) &&
1335                     (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1336                         if (tp->t_state == TCPS_TIME_WAIT &&
1337                                         (ticks - tp->t_starttime) > tcp_msl) {
1338                                 rstreason = BANDLIM_UNLIMITED;
1339                                 goto dropwithreset;
1340                         }
1341                         if (CC_GT(to.to_cc, tp->cc_recv)) {
1342                                 tp = tcp_close(tp);
1343                                 goto findpcb;
1344                         }
1345                         else
1346                                 goto drop;
1347                 }
1348                 break;  /* continue normal processing */
1349         }
1350
1351         /*
1352          * States other than LISTEN or SYN_SENT.
1353          * First check the RST flag and sequence number since reset segments
1354          * are exempt from the timestamp and connection count tests.  This
1355          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1356          * below which allowed reset segments in half the sequence space
1357          * to fall though and be processed (which gives forged reset
1358          * segments with a random sequence number a 50 percent chance of
1359          * killing a connection).
1360          * Then check timestamp, if present.
1361          * Then check the connection count, if present.
1362          * Then check that at least some bytes of segment are within
1363          * receive window.  If segment begins before rcv_nxt,
1364          * drop leading data (and SYN); if nothing left, just ack.
1365          *
1366          *
1367          * If the RST bit is set, check the sequence number to see
1368          * if this is a valid reset segment.
1369          * RFC 793 page 37:
1370          *   In all states except SYN-SENT, all reset (RST) segments
1371          *   are validated by checking their SEQ-fields.  A reset is
1372          *   valid if its sequence number is in the window.
1373          * Note: this does not take into account delayed ACKs, so
1374          *   we should test against last_ack_sent instead of rcv_nxt.
1375          *   The sequence number in the reset segment is normally an
1376          *   echo of our outgoing acknowlegement numbers, but some hosts
1377          *   send a reset with the sequence number at the rightmost edge
1378          *   of our receive window, and we have to handle this case.
1379          * If we have multiple segments in flight, the intial reset
1380          * segment sequence numbers will be to the left of last_ack_sent,
1381          * but they will eventually catch up.
1382          * In any case, it never made sense to trim reset segments to
1383          * fit the receive window since RFC 1122 says:
1384          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1385          *
1386          *    A TCP SHOULD allow a received RST segment to include data.
1387          *
1388          *    DISCUSSION
1389          *         It has been suggested that a RST segment could contain
1390          *         ASCII text that encoded and explained the cause of the
1391          *         RST.  No standard has yet been established for such
1392          *         data.
1393          *
1394          * If the reset segment passes the sequence number test examine
1395          * the state:
1396          *    SYN_RECEIVED STATE:
1397          *      If passive open, return to LISTEN state.
1398          *      If active open, inform user that connection was refused.
1399          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1400          *      Inform user that connection was reset, and close tcb.
1401          *    CLOSING, LAST_ACK STATES:
1402          *      Close the tcb.
1403          *    TIME_WAIT STATE:
1404          *      Drop the segment - see Stevens, vol. 2, p. 964 and
1405          *      RFC 1337.
1406          */
1407         if (thflags & TH_RST) {
1408                 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1409                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1410                         switch (tp->t_state) {
1411
1412                         case TCPS_SYN_RECEIVED:
1413                                 so->so_error = ECONNREFUSED;
1414                                 goto close;
1415
1416                         case TCPS_ESTABLISHED:
1417                         case TCPS_FIN_WAIT_1:
1418                         case TCPS_FIN_WAIT_2:
1419                         case TCPS_CLOSE_WAIT:
1420                                 so->so_error = ECONNRESET;
1421                         close:
1422                                 tp->t_state = TCPS_CLOSED;
1423                                 tcpstat.tcps_drops++;
1424                                 tp = tcp_close(tp);
1425                                 break;
1426
1427                         case TCPS_CLOSING:
1428                         case TCPS_LAST_ACK:
1429                                 tp = tcp_close(tp);
1430                                 break;
1431
1432                         case TCPS_TIME_WAIT:
1433                                 break;
1434                         }
1435                 }
1436                 goto drop;
1437         }
1438
1439         /*
1440          * RFC 1323 PAWS: If we have a timestamp reply on this segment
1441          * and it's less than ts_recent, drop it.
1442          */
1443         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1444             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1445
1446                 /* Check to see if ts_recent is over 24 days old.  */
1447                 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1448                         /*
1449                          * Invalidate ts_recent.  If this segment updates
1450                          * ts_recent, the age will be reset later and ts_recent
1451                          * will get a valid value.  If it does not, setting
1452                          * ts_recent to zero will at least satisfy the
1453                          * requirement that zero be placed in the timestamp
1454                          * echo reply when ts_recent isn't valid.  The
1455                          * age isn't reset until we get a valid ts_recent
1456                          * because we don't want out-of-order segments to be
1457                          * dropped when ts_recent is old.
1458                          */
1459                         tp->ts_recent = 0;
1460                 } else {
1461                         tcpstat.tcps_rcvduppack++;
1462                         tcpstat.tcps_rcvdupbyte += tlen;
1463                         tcpstat.tcps_pawsdrop++;
1464                         if (tlen)
1465                                 goto dropafterack;
1466                         goto drop;
1467                 }
1468         }
1469
1470         /*
1471          * T/TCP mechanism
1472          *   If T/TCP was negotiated and the segment doesn't have CC,
1473          *   or if its CC is wrong then drop the segment.
1474          *   RST segments do not have to comply with this.
1475          */
1476         if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1477             ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1478                 goto dropafterack;
1479
1480         /*
1481          * In the SYN-RECEIVED state, validate that the packet belongs to
1482          * this connection before trimming the data to fit the receive
1483          * window.  Check the sequence number versus IRS since we know
1484          * the sequence numbers haven't wrapped.  This is a partial fix
1485          * for the "LAND" DoS attack.
1486          */
1487         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1488                 rstreason = BANDLIM_RST_OPENPORT;
1489                 goto dropwithreset;
1490         }
1491
1492         todrop = tp->rcv_nxt - th->th_seq;
1493         if (todrop > 0) {
1494                 if (thflags & TH_SYN) {
1495                         thflags &= ~TH_SYN;
1496                         th->th_seq++;
1497                         if (th->th_urp > 1)
1498                                 th->th_urp--;
1499                         else
1500                                 thflags &= ~TH_URG;
1501                         todrop--;
1502                 }
1503                 /*
1504                  * Following if statement from Stevens, vol. 2, p. 960.
1505                  */
1506                 if (todrop > tlen
1507                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1508                         /*
1509                          * Any valid FIN must be to the left of the window.
1510                          * At this point the FIN must be a duplicate or out
1511                          * of sequence; drop it.
1512                          */
1513                         thflags &= ~TH_FIN;
1514
1515                         /*
1516                          * Send an ACK to resynchronize and drop any data.
1517                          * But keep on processing for RST or ACK.
1518                          */
1519                         tp->t_flags |= TF_ACKNOW;
1520                         todrop = tlen;
1521                         tcpstat.tcps_rcvduppack++;
1522                         tcpstat.tcps_rcvdupbyte += todrop;
1523                 } else {
1524                         tcpstat.tcps_rcvpartduppack++;
1525                         tcpstat.tcps_rcvpartdupbyte += todrop;
1526                 }
1527                 drop_hdrlen += todrop;  /* drop from the top afterwards */
1528                 th->th_seq += todrop;
1529                 tlen -= todrop;
1530                 if (th->th_urp > todrop)
1531                         th->th_urp -= todrop;
1532                 else {
1533                         thflags &= ~TH_URG;
1534                         th->th_urp = 0;
1535                 }
1536         }
1537
1538         /*
1539          * If new data are received on a connection after the
1540          * user processes are gone, then RST the other end.
1541          */
1542         if ((so->so_state & SS_NOFDREF) &&
1543             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1544                 tp = tcp_close(tp);
1545                 tcpstat.tcps_rcvafterclose++;
1546                 rstreason = BANDLIM_UNLIMITED;
1547                 goto dropwithreset;
1548         }
1549
1550         /*
1551          * If segment ends after window, drop trailing data
1552          * (and PUSH and FIN); if nothing left, just ACK.
1553          */
1554         todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1555         if (todrop > 0) {
1556                 tcpstat.tcps_rcvpackafterwin++;
1557                 if (todrop >= tlen) {
1558                         tcpstat.tcps_rcvbyteafterwin += tlen;
1559                         /*
1560                          * If a new connection request is received
1561                          * while in TIME_WAIT, drop the old connection
1562                          * and start over if the sequence numbers
1563                          * are above the previous ones.
1564                          */
1565                         if (thflags & TH_SYN &&
1566                             tp->t_state == TCPS_TIME_WAIT &&
1567                             SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1568                                 tp = tcp_close(tp);
1569                                 goto findpcb;
1570                         }
1571                         /*
1572                          * If window is closed can only take segments at
1573                          * window edge, and have to drop data and PUSH from
1574                          * incoming segments.  Continue processing, but
1575                          * remember to ack.  Otherwise, drop segment
1576                          * and ack.
1577                          */
1578                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1579                                 tp->t_flags |= TF_ACKNOW;
1580                                 tcpstat.tcps_rcvwinprobe++;
1581                         } else
1582                                 goto dropafterack;
1583                 } else
1584                         tcpstat.tcps_rcvbyteafterwin += todrop;
1585                 m_adj(m, -todrop);
1586                 tlen -= todrop;
1587                 thflags &= ~(TH_PUSH|TH_FIN);
1588         }
1589
1590         /*
1591          * If last ACK falls within this segment's sequence numbers,
1592          * record its timestamp.
1593          * NOTE that the test is modified according to the latest
1594          * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1595          */
1596         if ((to.to_flags & TOF_TS) != 0 &&
1597             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1598                 tp->ts_recent_age = ticks;
1599                 tp->ts_recent = to.to_tsval;
1600         }
1601
1602         /*
1603          * If a SYN is in the window, then this is an
1604          * error and we send an RST and drop the connection.
1605          */
1606         if (thflags & TH_SYN) {
1607                 tp = tcp_drop(tp, ECONNRESET);
1608                 rstreason = BANDLIM_UNLIMITED;
1609                 goto dropwithreset;
1610         }
1611
1612         /*
1613          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1614          * flag is on (half-synchronized state), then queue data for
1615          * later processing; else drop segment and return.
1616          */
1617         if ((thflags & TH_ACK) == 0) {
1618                 if (tp->t_state == TCPS_SYN_RECEIVED ||
1619                     (tp->t_flags & TF_NEEDSYN))
1620                         goto step6;
1621                 else
1622                         goto drop;
1623         }
1624
1625         /*
1626          * Ack processing.
1627          */
1628         switch (tp->t_state) {
1629
1630         /*
1631          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1632          * ESTABLISHED state and continue processing.
1633          * The ACK was checked above.
1634          */
1635         case TCPS_SYN_RECEIVED:
1636
1637                 tcpstat.tcps_connects++;
1638                 soisconnected(so);
1639                 /* Do window scaling? */
1640                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1641                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1642                         tp->snd_scale = tp->requested_s_scale;
1643                         tp->rcv_scale = tp->request_r_scale;
1644                 }
1645                 /*
1646                  * Upon successful completion of 3-way handshake,
1647                  * update cache.CC if it was undefined, pass any queued
1648                  * data to the user, and advance state appropriately.
1649                  */
1650                 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1651                     taop->tao_cc == 0)
1652                         taop->tao_cc = tp->cc_recv;
1653
1654                 /*
1655                  * Make transitions:
1656                  *      SYN-RECEIVED  -> ESTABLISHED
1657                  *      SYN-RECEIVED* -> FIN-WAIT-1
1658                  */
1659                 tp->t_starttime = ticks;
1660                 if (tp->t_flags & TF_NEEDFIN) {
1661                         tp->t_state = TCPS_FIN_WAIT_1;
1662                         tp->t_flags &= ~TF_NEEDFIN;
1663                 } else {
1664                         tp->t_state = TCPS_ESTABLISHED;
1665                         callout_reset(tp->tt_keep, tcp_keepidle, 
1666                                       tcp_timer_keep, tp);
1667                 }
1668                 /*
1669                  * If segment contains data or ACK, will call tcp_reass()
1670                  * later; if not, do so now to pass queued data to user.
1671                  */
1672                 if (tlen == 0 && (thflags & TH_FIN) == 0)
1673                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1674                             (struct mbuf *)0);
1675                 tp->snd_wl1 = th->th_seq - 1;
1676                 /* fall into ... */
1677
1678         /*
1679          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1680          * ACKs.  If the ack is in the range
1681          *      tp->snd_una < th->th_ack <= tp->snd_max
1682          * then advance tp->snd_una to th->th_ack and drop
1683          * data from the retransmission queue.  If this ACK reflects
1684          * more up to date window information we update our window information.
1685          */
1686         case TCPS_ESTABLISHED:
1687         case TCPS_FIN_WAIT_1:
1688         case TCPS_FIN_WAIT_2:
1689         case TCPS_CLOSE_WAIT:
1690         case TCPS_CLOSING:
1691         case TCPS_LAST_ACK:
1692         case TCPS_TIME_WAIT:
1693
1694                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1695                         if (tlen == 0 && tiwin == tp->snd_wnd) {
1696                                 tcpstat.tcps_rcvdupack++;
1697                                 /*
1698                                  * If we have outstanding data (other than
1699                                  * a window probe), this is a completely
1700                                  * duplicate ack (ie, window info didn't
1701                                  * change), the ack is the biggest we've
1702                                  * seen and we've seen exactly our rexmt
1703                                  * threshhold of them, assume a packet
1704                                  * has been dropped and retransmit it.
1705                                  * Kludge snd_nxt & the congestion
1706                                  * window so we send only this one
1707                                  * packet.
1708                                  *
1709                                  * We know we're losing at the current
1710                                  * window size so do congestion avoidance
1711                                  * (set ssthresh to half the current window
1712                                  * and pull our congestion window back to
1713                                  * the new ssthresh).
1714                                  *
1715                                  * Dup acks mean that packets have left the
1716                                  * network (they're now cached at the receiver)
1717                                  * so bump cwnd by the amount in the receiver
1718                                  * to keep a constant cwnd packets in the
1719                                  * network.
1720                                  */
1721                                 if (!callout_active(tp->tt_rexmt) ||
1722                                     th->th_ack != tp->snd_una)
1723                                         tp->t_dupacks = 0;
1724                                 else if (++tp->t_dupacks > tcprexmtthresh ||
1725                                          (tcp_do_newreno &&
1726                                           IN_FASTRECOVERY(tp))) {
1727                                         tp->snd_cwnd += tp->t_maxseg;
1728                                         (void) tcp_output(tp);
1729                                         goto drop;
1730                                 } else if (tp->t_dupacks == tcprexmtthresh) {
1731                                         tcp_seq onxt = tp->snd_nxt;
1732                                         u_int win;
1733                                         if (tcp_do_newreno &&
1734                                             SEQ_LEQ(th->th_ack,
1735                                                     tp->snd_recover)) {
1736                                                 tp->t_dupacks = 0;
1737                                                 break;
1738                                         }
1739                                         if (tcp_do_eifel_detect &&
1740                                             (tp->t_flags & TF_RCVD_TSTMP)) {
1741                                                 tcp_save_congestion_state(tp);
1742                                                 tp->t_flags |= TF_FASTREXMT;
1743                                         }
1744                                         win = min(tp->snd_wnd, tp->snd_cwnd) /
1745                                             2 / tp->t_maxseg;
1746                                         if (win < 2)
1747                                                 win = 2;
1748                                         tp->snd_ssthresh = win * tp->t_maxseg;
1749                                         ENTER_FASTRECOVERY(tp);
1750                                         tp->snd_recover = tp->snd_max;
1751                                         callout_stop(tp->tt_rexmt);
1752                                         tp->t_rtttime = 0;
1753                                         tp->snd_nxt = th->th_ack;
1754                                         tp->snd_cwnd = tp->t_maxseg;
1755                                         (void) tcp_output(tp);
1756                                         KASSERT(tp->snd_limited <= 2,
1757                                             ("tp->snd_limited too big"));
1758                                         tp->snd_cwnd = tp->snd_ssthresh +
1759                                             (tp->t_maxseg *
1760                                              (tp->t_dupacks - tp->snd_limited));
1761                                         if (SEQ_GT(onxt, tp->snd_nxt))
1762                                                 tp->snd_nxt = onxt;
1763                                         goto drop;
1764                                 } else if (tcp_do_limitedtransmit) {
1765                                         u_long oldcwnd = tp->snd_cwnd;
1766                                         tcp_seq oldsndmax = tp->snd_max;
1767                                         u_int sent;
1768
1769                                         KASSERT(tp->t_dupacks == 1 ||
1770                                             tp->t_dupacks == 2,
1771                                             ("dupacks not 1 or 2"));
1772                                         if (tp->t_dupacks == 1)
1773                                                 tp->snd_limited = 0;
1774                                         tp->snd_cwnd =
1775                                             (tp->snd_nxt - tp->snd_una) +
1776                                             (tp->t_dupacks - tp->snd_limited) *
1777                                             tp->t_maxseg;
1778                                         (void) tcp_output(tp);
1779                                         sent = tp->snd_max - oldsndmax;
1780                                         if (sent > tp->t_maxseg) {
1781                                                 KASSERT((tp->t_dupacks == 2 &&
1782                                                     tp->snd_limited == 0) ||
1783                                                    (sent == tp->t_maxseg + 1 &&
1784                                                     tp->t_flags & TF_SENTFIN),
1785                                                     ("sent too much"));
1786                                                 tp->snd_limited = 2;
1787                                         } else if (sent > 0)
1788                                                 ++tp->snd_limited;
1789                                         tp->snd_cwnd = oldcwnd;
1790                                         goto drop;
1791                                 }
1792                         } else
1793                                 tp->t_dupacks = 0;
1794                         break;
1795                 }
1796
1797                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1798
1799                 /*
1800                  * If the congestion window was inflated to account
1801                  * for the other side's cached packets, retract it.
1802                  */
1803                 if (tcp_do_newreno) {
1804                         if (IN_FASTRECOVERY(tp)) {
1805                                 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1806                                         tcp_newreno_partial_ack(tp, th);
1807                                 } else {
1808                                         /*
1809                                          * Window inflation should have left us
1810                                          * with approximately snd_ssthresh
1811                                          * outstanding data.
1812                                          * But in case we would be inclined to
1813                                          * send a burst, better to do it via
1814                                          * the slow start mechanism.
1815                                          */
1816                                         if (SEQ_GT(th->th_ack +
1817                                                         tp->snd_ssthresh,
1818                                                    tp->snd_max))
1819                                                 tp->snd_cwnd = tp->snd_max -
1820                                                                 th->th_ack +
1821                                                                 tp->t_maxseg;
1822                                         else
1823                                                 tp->snd_cwnd = tp->snd_ssthresh;
1824                                 }
1825                         }
1826                 } else {
1827                         if (tp->t_dupacks >= tcprexmtthresh &&
1828                             tp->snd_cwnd > tp->snd_ssthresh)
1829                                 tp->snd_cwnd = tp->snd_ssthresh;
1830                 }
1831                 tp->t_dupacks = 0;
1832                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1833                         tcpstat.tcps_rcvacktoomuch++;
1834                         goto dropafterack;
1835                 }
1836                 /*
1837                  * If we reach this point, ACK is not a duplicate,
1838                  *     i.e., it ACKs something we sent.
1839                  */
1840                 if (tp->t_flags & TF_NEEDSYN) {
1841                         /*
1842                          * T/TCP: Connection was half-synchronized, and our
1843                          * SYN has been ACK'd (so connection is now fully
1844                          * synchronized).  Go to non-starred state,
1845                          * increment snd_una for ACK of SYN, and check if
1846                          * we can do window scaling.
1847                          */
1848                         tp->t_flags &= ~TF_NEEDSYN;
1849                         tp->snd_una++;
1850                         /* Do window scaling? */
1851                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1852                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1853                                 tp->snd_scale = tp->requested_s_scale;
1854                                 tp->rcv_scale = tp->request_r_scale;
1855                         }
1856                 }
1857
1858 process_ACK:
1859                 acked = th->th_ack - tp->snd_una;
1860                 tcpstat.tcps_rcvackpack++;
1861                 tcpstat.tcps_rcvackbyte += acked;
1862
1863                 /*
1864                  * If we just performed our first retransmit, and the ACK
1865                  * arrives within our recovery window, then it was a mistake
1866                  * to do the retransmit in the first place.  Recover our
1867                  * original cwnd and ssthresh, and proceed to transmit where
1868                  * we left off.
1869                  */
1870                 if (tcp_do_eifel_detect && acked &&
1871                     (to.to_flags & TOF_TS) && to.to_tsecr &&
1872                     (tp->t_flags & TF_FIRSTACCACK)) {
1873                         /* Eifel detection applicable. */
1874                         if (to.to_tsecr < tp->t_rexmtTS) {
1875                                 tcp_revert_congestion_state(tp);
1876                                 ++tcpstat.tcps_eifeldetected;
1877                         }
1878                 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1879                         tcp_revert_congestion_state(tp);
1880                         ++tcpstat.tcps_rttdetected;
1881                 }
1882
1883                 /*
1884                  * If we have a timestamp reply, update smoothed
1885                  * round trip time.  If no timestamp is present but
1886                  * transmit timer is running and timed sequence
1887                  * number was acked, update smoothed round trip time.
1888                  * Since we now have an rtt measurement, cancel the
1889                  * timer backoff (cf., Phil Karn's retransmit alg.).
1890                  * Recompute the initial retransmit timer.
1891                  *
1892                  * Some machines (certain windows boxes) send broken
1893                  * timestamp replies during the SYN+ACK phase, ignore 
1894                  * timestamps of 0.
1895                  */
1896                 if ((to.to_flags & TOF_TS) != 0 &&
1897                     to.to_tsecr) {
1898                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1899                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1900                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1901                 }
1902                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1903
1904                 /*
1905                  * If all outstanding data is acked, stop retransmit
1906                  * timer and remember to restart (more output or persist).
1907                  * If there is more data to be acked, restart retransmit
1908                  * timer, using current (possibly backed-off) value.
1909                  */
1910                 if (th->th_ack == tp->snd_max) {
1911                         callout_stop(tp->tt_rexmt);
1912                         needoutput = 1;
1913                 } else if (!callout_active(tp->tt_persist))
1914                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1915                                       tcp_timer_rexmt, tp);
1916
1917                 /*
1918                  * If no data (only SYN) was ACK'd,
1919                  *    skip rest of ACK processing.
1920                  */
1921                 if (acked == 0)
1922                         goto step6;
1923
1924                 /* Stop looking for an acceptable ACK since one was received. */
1925                 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1926
1927                 /*
1928                  * When new data is acked, open the congestion window.
1929                  * If the window gives us less than ssthresh packets
1930                  * in flight, open exponentially (maxseg per packet).
1931                  * Otherwise open linearly: maxseg per window
1932                  * (maxseg^2 / cwnd per packet).
1933                  */
1934                 if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
1935                         u_int cw = tp->snd_cwnd;
1936                         u_int incr = tp->t_maxseg;
1937                         if (cw > tp->snd_ssthresh)
1938                                 incr = incr * incr / cw;
1939                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1940                 }
1941                 if (acked > so->so_snd.sb_cc) {
1942                         tp->snd_wnd -= so->so_snd.sb_cc;
1943                         sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1944                         ourfinisacked = 1;
1945                 } else {
1946                         sbdrop(&so->so_snd, acked);
1947                         tp->snd_wnd -= acked;
1948                         ourfinisacked = 0;
1949                 }
1950                 sowwakeup(so);
1951                 /* detect una wraparound */
1952                 if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
1953                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
1954                     SEQ_LEQ(th->th_ack, tp->snd_recover))
1955                         tp->snd_recover = th->th_ack - 1;
1956                 if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
1957                     SEQ_GEQ(th->th_ack, tp->snd_recover))
1958                         EXIT_FASTRECOVERY(tp);
1959                 tp->snd_una = th->th_ack;
1960                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1961                         tp->snd_nxt = tp->snd_una;
1962
1963                 switch (tp->t_state) {
1964
1965                 /*
1966                  * In FIN_WAIT_1 STATE in addition to the processing
1967                  * for the ESTABLISHED state if our FIN is now acknowledged
1968                  * then enter FIN_WAIT_2.
1969                  */
1970                 case TCPS_FIN_WAIT_1:
1971                         if (ourfinisacked) {
1972                                 /*
1973                                  * If we can't receive any more
1974                                  * data, then closing user can proceed.
1975                                  * Starting the timer is contrary to the
1976                                  * specification, but if we don't get a FIN
1977                                  * we'll hang forever.
1978                                  */
1979                                 if (so->so_state & SS_CANTRCVMORE) {
1980                                         soisdisconnected(so);
1981                                         callout_reset(tp->tt_2msl, tcp_maxidle,
1982                                                       tcp_timer_2msl, tp);
1983                                 }
1984                                 tp->t_state = TCPS_FIN_WAIT_2;
1985                         }
1986                         break;
1987
1988                 /*
1989                  * In CLOSING STATE in addition to the processing for
1990                  * the ESTABLISHED state if the ACK acknowledges our FIN
1991                  * then enter the TIME-WAIT state, otherwise ignore
1992                  * the segment.
1993                  */
1994                 case TCPS_CLOSING:
1995                         if (ourfinisacked) {
1996                                 tp->t_state = TCPS_TIME_WAIT;
1997                                 tcp_canceltimers(tp);
1998                                 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1999                                 if (tp->cc_recv != 0 &&
2000                                     (ticks - tp->t_starttime) < tcp_msl)
2001                                         callout_reset(tp->tt_2msl,
2002                                                       tp->t_rxtcur *
2003                                                       TCPTV_TWTRUNC,
2004                                                       tcp_timer_2msl, tp);
2005                                 else
2006                                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2007                                                       tcp_timer_2msl, tp);
2008                                 soisdisconnected(so);
2009                         }
2010                         break;
2011
2012                 /*
2013                  * In LAST_ACK, we may still be waiting for data to drain
2014                  * and/or to be acked, as well as for the ack of our FIN.
2015                  * If our FIN is now acknowledged, delete the TCB,
2016                  * enter the closed state and return.
2017                  */
2018                 case TCPS_LAST_ACK:
2019                         if (ourfinisacked) {
2020                                 tp = tcp_close(tp);
2021                                 goto drop;
2022                         }
2023                         break;
2024
2025                 /*
2026                  * In TIME_WAIT state the only thing that should arrive
2027                  * is a retransmission of the remote FIN.  Acknowledge
2028                  * it and restart the finack timer.
2029                  */
2030                 case TCPS_TIME_WAIT:
2031                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2032                                       tcp_timer_2msl, tp);
2033                         goto dropafterack;
2034                 }
2035         }
2036
2037 step6:
2038         /*
2039          * Update window information.
2040          * Don't look at window if no ACK: TAC's send garbage on first SYN.
2041          */
2042         if ((thflags & TH_ACK) &&
2043             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2044             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2045              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2046                 /* keep track of pure window updates */
2047                 if (tlen == 0 &&
2048                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2049                         tcpstat.tcps_rcvwinupd++;
2050                 tp->snd_wnd = tiwin;
2051                 tp->snd_wl1 = th->th_seq;
2052                 tp->snd_wl2 = th->th_ack;
2053                 if (tp->snd_wnd > tp->max_sndwnd)
2054                         tp->max_sndwnd = tp->snd_wnd;
2055                 needoutput = 1;
2056         }
2057
2058         /*
2059          * Process segments with URG.
2060          */
2061         if ((thflags & TH_URG) && th->th_urp &&
2062             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2063                 /*
2064                  * This is a kludge, but if we receive and accept
2065                  * random urgent pointers, we'll crash in
2066                  * soreceive.  It's hard to imagine someone
2067                  * actually wanting to send this much urgent data.
2068                  */
2069                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2070                         th->th_urp = 0;                 /* XXX */
2071                         thflags &= ~TH_URG;             /* XXX */
2072                         goto dodata;                    /* XXX */
2073                 }
2074                 /*
2075                  * If this segment advances the known urgent pointer,
2076                  * then mark the data stream.  This should not happen
2077                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2078                  * a FIN has been received from the remote side.
2079                  * In these states we ignore the URG.
2080                  *
2081                  * According to RFC961 (Assigned Protocols),
2082                  * the urgent pointer points to the last octet
2083                  * of urgent data.  We continue, however,
2084                  * to consider it to indicate the first octet
2085                  * of data past the urgent section as the original
2086                  * spec states (in one of two places).
2087                  */
2088                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2089                         tp->rcv_up = th->th_seq + th->th_urp;
2090                         so->so_oobmark = so->so_rcv.sb_cc +
2091                             (tp->rcv_up - tp->rcv_nxt) - 1;
2092                         if (so->so_oobmark == 0)
2093                                 so->so_state |= SS_RCVATMARK;
2094                         sohasoutofband(so);
2095                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2096                 }
2097                 /*
2098                  * Remove out of band data so doesn't get presented to user.
2099                  * This can happen independent of advancing the URG pointer,
2100                  * but if two URG's are pending at once, some out-of-band
2101                  * data may creep in... ick.
2102                  */
2103                 if (th->th_urp <= (u_long)tlen
2104 #ifdef SO_OOBINLINE
2105                      && (so->so_options & SO_OOBINLINE) == 0
2106 #endif
2107                      )
2108                         tcp_pulloutofband(so, th, m,
2109                                 drop_hdrlen);   /* hdr drop is delayed */
2110         } else {
2111                 /*
2112                  * If no out of band data is expected,
2113                  * pull receive urgent pointer along
2114                  * with the receive window.
2115                  */
2116                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2117                         tp->rcv_up = tp->rcv_nxt;
2118         }
2119 dodata:                                                 /* XXX */
2120
2121         /*
2122          * Process the segment text, merging it into the TCP sequencing queue,
2123          * and arranging for acknowledgment of receipt if necessary.
2124          * This process logically involves adjusting tp->rcv_wnd as data
2125          * is presented to the user (this happens in tcp_usrreq.c,
2126          * case PRU_RCVD).  If a FIN has already been received on this
2127          * connection then we just ignore the text.
2128          */
2129         if ((tlen || (thflags & TH_FIN)) &&
2130             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2131                 m_adj(m, drop_hdrlen);  /* delayed header drop */
2132                 /*
2133                  * Insert segment which includes th into TCP reassembly queue
2134                  * with control block tp.  Set thflags to whether reassembly now
2135                  * includes a segment with FIN.  This handles the common case
2136                  * inline (segment is the next to be received on an established
2137                  * connection, and the queue is empty), avoiding linkage into
2138                  * and removal from the queue and repetition of various
2139                  * conversions.
2140                  * Set DELACK for segments received in order, but ack
2141                  * immediately when segments are out of order (so
2142                  * fast retransmit can work).
2143                  */
2144                 if (th->th_seq == tp->rcv_nxt &&
2145                     LIST_EMPTY(&tp->t_segq) &&
2146                     TCPS_HAVEESTABLISHED(tp->t_state)) {
2147                         if (DELAY_ACK(tp))
2148                                 callout_reset(tp->tt_delack, tcp_delacktime,
2149                                               tcp_timer_delack, tp);
2150                         else
2151                                 tp->t_flags |= TF_ACKNOW;
2152                         tp->rcv_nxt += tlen;
2153                         thflags = th->th_flags & TH_FIN;
2154                         tcpstat.tcps_rcvpack++;
2155                         tcpstat.tcps_rcvbyte += tlen;
2156                         ND6_HINT(tp);
2157                         if (so->so_state & SS_CANTRCVMORE)
2158                                 m_freem(m);
2159                         else
2160                                 sbappend(&so->so_rcv, m);
2161                         sorwakeup(so);
2162                 } else {
2163                         thflags = tcp_reass(tp, th, &tlen, m);
2164                         tp->t_flags |= TF_ACKNOW;
2165                 }
2166
2167                 /*
2168                  * Note the amount of data that peer has sent into
2169                  * our window, in order to estimate the sender's
2170                  * buffer size.
2171                  */
2172                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2173         } else {
2174                 m_freem(m);
2175                 thflags &= ~TH_FIN;
2176         }
2177
2178         /*
2179          * If FIN is received ACK the FIN and let the user know
2180          * that the connection is closing.
2181          */
2182         if (thflags & TH_FIN) {
2183                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2184                         socantrcvmore(so);
2185                         /*
2186                          * If connection is half-synchronized
2187                          * (ie NEEDSYN flag on) then delay ACK,
2188                          * so it may be piggybacked when SYN is sent.
2189                          * Otherwise, since we received a FIN then no
2190                          * more input can be expected, send ACK now.
2191                          */
2192                         if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2193                                 callout_reset(tp->tt_delack, tcp_delacktime,  
2194                                     tcp_timer_delack, tp);  
2195                         else
2196                                 tp->t_flags |= TF_ACKNOW;
2197                         tp->rcv_nxt++;
2198                 }
2199                 switch (tp->t_state) {
2200
2201                 /*
2202                  * In SYN_RECEIVED and ESTABLISHED STATES
2203                  * enter the CLOSE_WAIT state.
2204                  */
2205                 case TCPS_SYN_RECEIVED:
2206                         tp->t_starttime = ticks;
2207                         /*FALLTHROUGH*/
2208                 case TCPS_ESTABLISHED:
2209                         tp->t_state = TCPS_CLOSE_WAIT;
2210                         break;
2211
2212                 /*
2213                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
2214                  * enter the CLOSING state.
2215                  */
2216                 case TCPS_FIN_WAIT_1:
2217                         tp->t_state = TCPS_CLOSING;
2218                         break;
2219
2220                 /*
2221                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
2222                  * starting the time-wait timer, turning off the other
2223                  * standard timers.
2224                  */
2225                 case TCPS_FIN_WAIT_2:
2226                         tp->t_state = TCPS_TIME_WAIT;
2227                         tcp_canceltimers(tp);
2228                         /* Shorten TIME_WAIT [RFC-1644, p.28] */
2229                         if (tp->cc_recv != 0 &&
2230                             (ticks - tp->t_starttime) < tcp_msl) {
2231                                 callout_reset(tp->tt_2msl,
2232                                               tp->t_rxtcur * TCPTV_TWTRUNC,
2233                                               tcp_timer_2msl, tp);
2234                                 /* For transaction client, force ACK now. */
2235                                 tp->t_flags |= TF_ACKNOW;
2236                         }
2237                         else
2238                                 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2239                                               tcp_timer_2msl, tp);
2240                         soisdisconnected(so);
2241                         break;
2242
2243                 /*
2244                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
2245                  */
2246                 case TCPS_TIME_WAIT:
2247                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2248                                       tcp_timer_2msl, tp);
2249                         break;
2250                 }
2251         }
2252 #ifdef TCPDEBUG
2253         if (so->so_options & SO_DEBUG)
2254                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2255                           &tcp_savetcp, 0);
2256 #endif
2257
2258         /*
2259          * Return any desired output.
2260          */
2261         if (needoutput || (tp->t_flags & TF_ACKNOW))
2262                 (void) tcp_output(tp);
2263         return;
2264
2265 dropafterack:
2266         /*
2267          * Generate an ACK dropping incoming segment if it occupies
2268          * sequence space, where the ACK reflects our state.
2269          *
2270          * We can now skip the test for the RST flag since all
2271          * paths to this code happen after packets containing
2272          * RST have been dropped.
2273          *
2274          * In the SYN-RECEIVED state, don't send an ACK unless the
2275          * segment we received passes the SYN-RECEIVED ACK test.
2276          * If it fails send a RST.  This breaks the loop in the
2277          * "LAND" DoS attack, and also prevents an ACK storm
2278          * between two listening ports that have been sent forged
2279          * SYN segments, each with the source address of the other.
2280          */
2281         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2282             (SEQ_GT(tp->snd_una, th->th_ack) ||
2283              SEQ_GT(th->th_ack, tp->snd_max)) ) {
2284                 rstreason = BANDLIM_RST_OPENPORT;
2285                 goto dropwithreset;
2286         }
2287 #ifdef TCPDEBUG
2288         if (so->so_options & SO_DEBUG)
2289                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2290                           &tcp_savetcp, 0);
2291 #endif
2292         m_freem(m);
2293         tp->t_flags |= TF_ACKNOW;
2294         (void) tcp_output(tp);
2295         return;
2296
2297 dropwithreset:
2298         /*
2299          * Generate a RST, dropping incoming segment.
2300          * Make ACK acceptable to originator of segment.
2301          * Don't bother to respond if destination was broadcast/multicast.
2302          */
2303         if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2304                 goto drop;
2305         if (isipv6) {
2306                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2307                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2308                         goto drop;
2309         } else {
2310                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2311                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2312                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2313                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2314                         goto drop;
2315         }
2316         /* IPv6 anycast check is done at tcp6_input() */
2317
2318         /*
2319          * Perform bandwidth limiting.
2320          */
2321 #ifdef ICMP_BANDLIM
2322         if (badport_bandlim(rstreason) < 0)
2323                 goto drop;
2324 #endif
2325
2326 #ifdef TCPDEBUG
2327         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2328                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2329                           &tcp_savetcp, 0);
2330 #endif
2331         if (thflags & TH_ACK)
2332                 /* mtod() below is safe as long as hdr dropping is delayed */
2333                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2334                             TH_RST);
2335         else {
2336                 if (thflags & TH_SYN)
2337                         tlen++;
2338                 /* mtod() below is safe as long as hdr dropping is delayed */
2339                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2340                             (tcp_seq)0, TH_RST|TH_ACK);
2341         }
2342         return;
2343
2344 drop:
2345         /*
2346          * Drop space held by incoming segment and return.
2347          */
2348 #ifdef TCPDEBUG
2349         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2350                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2351                           &tcp_savetcp, 0);
2352 #endif
2353         m_freem(m);
2354         return;
2355 }
2356
2357 /*
2358  * Parse TCP options and place in tcpopt.
2359  */
2360 static void
2361 tcp_dooptions(to, cp, cnt, is_syn)
2362         struct tcpopt *to;
2363         u_char *cp;
2364         int cnt;
2365 {
2366         int opt, optlen;
2367
2368         to->to_flags = 0;
2369         for (; cnt > 0; cnt -= optlen, cp += optlen) {
2370                 opt = cp[0];
2371                 if (opt == TCPOPT_EOL)
2372                         break;
2373                 if (opt == TCPOPT_NOP)
2374                         optlen = 1;
2375                 else {
2376                         if (cnt < 2)
2377                                 break;
2378                         optlen = cp[1];
2379                         if (optlen < 2 || optlen > cnt)
2380                                 break;
2381                 }
2382                 switch (opt) {
2383                 case TCPOPT_MAXSEG:
2384                         if (optlen != TCPOLEN_MAXSEG)
2385                                 continue;
2386                         if (!is_syn)
2387                                 continue;
2388                         to->to_flags |= TOF_MSS;
2389                         bcopy((char *)cp + 2,
2390                             (char *)&to->to_mss, sizeof(to->to_mss));
2391                         to->to_mss = ntohs(to->to_mss);
2392                         break;
2393                 case TCPOPT_WINDOW:
2394                         if (optlen != TCPOLEN_WINDOW)
2395                                 continue;
2396                         if (! is_syn)
2397                                 continue;
2398                         to->to_flags |= TOF_SCALE;
2399                         to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2400                         break;
2401                 case TCPOPT_TIMESTAMP:
2402                         if (optlen != TCPOLEN_TIMESTAMP)
2403                                 continue;
2404                         to->to_flags |= TOF_TS;
2405                         bcopy((char *)cp + 2,
2406                             (char *)&to->to_tsval, sizeof(to->to_tsval));
2407                         to->to_tsval = ntohl(to->to_tsval);
2408                         bcopy((char *)cp + 6,
2409                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2410                         to->to_tsecr = ntohl(to->to_tsecr);
2411                         break;
2412                 case TCPOPT_CC:
2413                         if (optlen != TCPOLEN_CC)
2414                                 continue;
2415                         to->to_flags |= TOF_CC;
2416                         bcopy((char *)cp + 2,
2417                             (char *)&to->to_cc, sizeof(to->to_cc));
2418                         to->to_cc = ntohl(to->to_cc);
2419                         break;
2420                 case TCPOPT_CCNEW:
2421                         if (optlen != TCPOLEN_CC)
2422                                 continue;
2423                         if (!is_syn)
2424                                 continue;
2425                         to->to_flags |= TOF_CCNEW;
2426                         bcopy((char *)cp + 2,
2427                             (char *)&to->to_cc, sizeof(to->to_cc));
2428                         to->to_cc = ntohl(to->to_cc);
2429                         break;
2430                 case TCPOPT_CCECHO:
2431                         if (optlen != TCPOLEN_CC)
2432                                 continue;
2433                         if (!is_syn)
2434                                 continue;
2435                         to->to_flags |= TOF_CCECHO;
2436                         bcopy((char *)cp + 2,
2437                             (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2438                         to->to_ccecho = ntohl(to->to_ccecho);
2439                         break;
2440                 default:
2441                         continue;
2442                 }
2443         }
2444 }
2445
2446 /*
2447  * Pull out of band byte out of a segment so
2448  * it doesn't appear in the user's data queue.
2449  * It is still reflected in the segment length for
2450  * sequencing purposes.
2451  */
2452 static void
2453 tcp_pulloutofband(so, th, m, off)
2454         struct socket *so;
2455         struct tcphdr *th;
2456         struct mbuf *m;
2457         int off;                /* delayed to be droped hdrlen */
2458 {
2459         int cnt = off + th->th_urp - 1;
2460
2461         while (cnt >= 0) {
2462                 if (m->m_len > cnt) {
2463                         char *cp = mtod(m, caddr_t) + cnt;
2464                         struct tcpcb *tp = sototcpcb(so);
2465
2466                         tp->t_iobc = *cp;
2467                         tp->t_oobflags |= TCPOOB_HAVEDATA;
2468                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2469                         m->m_len--;
2470                         if (m->m_flags & M_PKTHDR)
2471                                 m->m_pkthdr.len--;
2472                         return;
2473                 }
2474                 cnt -= m->m_len;
2475                 m = m->m_next;
2476                 if (m == 0)
2477                         break;
2478         }
2479         panic("tcp_pulloutofband");
2480 }
2481
2482 /*
2483  * Collect new round-trip time estimate
2484  * and update averages and current timeout.
2485  */
2486 static void
2487 tcp_xmit_timer(tp, rtt)
2488         struct tcpcb *tp;
2489         int rtt;
2490 {
2491         int delta;
2492
2493         tcpstat.tcps_rttupdated++;
2494         tp->t_rttupdated++;
2495         if (tp->t_srtt != 0) {
2496                 /*
2497                  * srtt is stored as fixed point with 5 bits after the
2498                  * binary point (i.e., scaled by 8).  The following magic
2499                  * is equivalent to the smoothing algorithm in rfc793 with
2500                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2501                  * point).  Adjust rtt to origin 0.
2502                  */
2503                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2504                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2505
2506                 if ((tp->t_srtt += delta) <= 0)
2507                         tp->t_srtt = 1;
2508
2509                 /*
2510                  * We accumulate a smoothed rtt variance (actually, a
2511                  * smoothed mean difference), then set the retransmit
2512                  * timer to smoothed rtt + 4 times the smoothed variance.
2513                  * rttvar is stored as fixed point with 4 bits after the
2514                  * binary point (scaled by 16).  The following is
2515                  * equivalent to rfc793 smoothing with an alpha of .75
2516                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2517                  * rfc793's wired-in beta.
2518                  */
2519                 if (delta < 0)
2520                         delta = -delta;
2521                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2522                 if ((tp->t_rttvar += delta) <= 0)
2523                         tp->t_rttvar = 1;
2524                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2525                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2526         } else {
2527                 /*
2528                  * No rtt measurement yet - use the unsmoothed rtt.
2529                  * Set the variance to half the rtt (so our first
2530                  * retransmit happens at 3*rtt).
2531                  */
2532                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2533                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2534                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2535         }
2536         tp->t_rtttime = 0;
2537         tp->t_rxtshift = 0;
2538
2539         /*
2540          * the retransmit should happen at rtt + 4 * rttvar.
2541          * Because of the way we do the smoothing, srtt and rttvar
2542          * will each average +1/2 tick of bias.  When we compute
2543          * the retransmit timer, we want 1/2 tick of rounding and
2544          * 1 extra tick because of +-1/2 tick uncertainty in the
2545          * firing of the timer.  The bias will give us exactly the
2546          * 1.5 tick we need.  But, because the bias is
2547          * statistical, we have to test that we don't drop below
2548          * the minimum feasible timer (which is 2 ticks).
2549          */
2550         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2551                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2552
2553         /*
2554          * We received an ack for a packet that wasn't retransmitted;
2555          * it is probably safe to discard any error indications we've
2556          * received recently.  This isn't quite right, but close enough
2557          * for now (a route might have failed after we sent a segment,
2558          * and the return path might not be symmetrical).
2559          */
2560         tp->t_softerror = 0;
2561 }
2562
2563 /*
2564  * Determine a reasonable value for maxseg size.
2565  * If the route is known, check route for mtu.
2566  * If none, use an mss that can be handled on the outgoing
2567  * interface without forcing IP to fragment; if bigger than
2568  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2569  * to utilize large mbufs.  If no route is found, route has no mtu,
2570  * or the destination isn't local, use a default, hopefully conservative
2571  * size (usually 512 or the default IP max size, but no more than the mtu
2572  * of the interface), as we can't discover anything about intervening
2573  * gateways or networks.  We also initialize the congestion/slow start
2574  * window to be a single segment if the destination isn't local.
2575  * While looking at the routing entry, we also initialize other path-dependent
2576  * parameters from pre-set or cached values in the routing entry.
2577  *
2578  * Also take into account the space needed for options that we
2579  * send regularly.  Make maxseg shorter by that amount to assure
2580  * that we can send maxseg amount of data even when the options
2581  * are present.  Store the upper limit of the length of options plus
2582  * data in maxopd.
2583  *
2584  * NOTE that this routine is only called when we process an incoming
2585  * segment, for outgoing segments only tcp_mssopt is called.
2586  *
2587  * In case of T/TCP, we call this routine during implicit connection
2588  * setup as well (offer = -1), to initialize maxseg from the cached
2589  * MSS of our peer.
2590  */
2591 void
2592 tcp_mss(tp, offer)
2593         struct tcpcb *tp;
2594         int offer;
2595 {
2596         struct rtentry *rt;
2597         struct ifnet *ifp;
2598         int rtt, mss;
2599         u_long bufsize;
2600         struct inpcb *inp = tp->t_inpcb;
2601         struct socket *so;
2602         struct rmxp_tao *taop;
2603         int origoffer = offer;
2604 #ifdef INET6
2605         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2606         size_t min_protoh = isipv6 ?
2607                             sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2608                             sizeof(struct tcpiphdr);
2609 #else
2610         const int isipv6 = 0;
2611         const size_t min_protoh = sizeof(struct tcpiphdr);
2612 #endif
2613
2614         if (isipv6)
2615                 rt = tcp_rtlookup6(&inp->inp_inc);
2616         else
2617                 rt = tcp_rtlookup(&inp->inp_inc);
2618         if (rt == NULL) {
2619                 tp->t_maxopd = tp->t_maxseg =
2620                                 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2621                 return;
2622         }
2623         ifp = rt->rt_ifp;
2624         so = inp->inp_socket;
2625
2626         taop = rmx_taop(rt->rt_rmx);
2627         /*
2628          * Offer == -1 means that we didn't receive SYN yet,
2629          * use cached value in that case;
2630          */
2631         if (offer == -1)
2632                 offer = taop->tao_mssopt;
2633         /*
2634          * Offer == 0 means that there was no MSS on the SYN segment,
2635          * in this case we use tcp_mssdflt.
2636          */
2637         if (offer == 0)
2638                 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2639         else
2640                 /*
2641                  * Sanity check: make sure that maxopd will be large
2642                  * enough to allow some data on segments even is the
2643                  * all the option space is used (40bytes).  Otherwise
2644                  * funny things may happen in tcp_output.
2645                  */
2646                 offer = max(offer, 64);
2647         taop->tao_mssopt = offer;
2648
2649         /*
2650          * While we're here, check if there's an initial rtt
2651          * or rttvar.  Convert from the route-table units
2652          * to scaled multiples of the slow timeout timer.
2653          */
2654         if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2655                 /*
2656                  * XXX the lock bit for RTT indicates that the value
2657                  * is also a minimum value; this is subject to time.
2658                  */
2659                 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2660                         tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2661                 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2662                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2663                 tcpstat.tcps_usedrtt++;
2664                 if (rt->rt_rmx.rmx_rttvar) {
2665                         tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2666                             (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2667                         tcpstat.tcps_usedrttvar++;
2668                 } else {
2669                         /* default variation is +- 1 rtt */
2670                         tp->t_rttvar =
2671                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2672                 }
2673                 TCPT_RANGESET(tp->t_rxtcur,
2674                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2675                               tp->t_rttmin, TCPTV_REXMTMAX);
2676         }
2677         /*
2678          * if there's an mtu associated with the route, use it
2679          * else, use the link mtu.
2680          */
2681         if (rt->rt_rmx.rmx_mtu)
2682                 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2683         else {
2684                 if (isipv6) {
2685                         mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2686                                 min_protoh;
2687                         if (!in6_localaddr(&inp->in6p_faddr))
2688                                 mss = min(mss, tcp_v6mssdflt);
2689                 } else {
2690                         mss = ifp->if_mtu - min_protoh;
2691                         if (!in_localaddr(inp->inp_faddr))
2692                                 mss = min(mss, tcp_mssdflt);
2693                 }
2694         }
2695         mss = min(mss, offer);
2696         /*
2697          * maxopd stores the maximum length of data AND options
2698          * in a segment; maxseg is the amount of data in a normal
2699          * segment.  We need to store this value (maxopd) apart
2700          * from maxseg, because now every segment carries options
2701          * and thus we normally have somewhat less data in segments.
2702          */
2703         tp->t_maxopd = mss;
2704
2705         /*
2706          * In case of T/TCP, origoffer==-1 indicates, that no segments
2707          * were received yet.  In this case we just guess, otherwise
2708          * we do the same as before T/TCP.
2709          */
2710         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2711             (origoffer == -1 ||
2712              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2713                 mss -= TCPOLEN_TSTAMP_APPA;
2714         if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2715             (origoffer == -1 ||
2716              (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2717                 mss -= TCPOLEN_CC_APPA;
2718
2719 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
2720                 if (mss > MCLBYTES)
2721                         mss &= ~(MCLBYTES-1);
2722 #else
2723                 if (mss > MCLBYTES)
2724                         mss = mss / MCLBYTES * MCLBYTES;
2725 #endif
2726         /*
2727          * If there's a pipesize, change the socket buffer
2728          * to that size.  Make the socket buffers an integral
2729          * number of mss units; if the mss is larger than
2730          * the socket buffer, decrease the mss.
2731          */
2732 #ifdef RTV_SPIPE
2733         if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2734 #endif
2735                 bufsize = so->so_snd.sb_hiwat;
2736         if (bufsize < mss)
2737                 mss = bufsize;
2738         else {
2739                 bufsize = roundup(bufsize, mss);
2740                 if (bufsize > sb_max)
2741                         bufsize = sb_max;
2742                 if (bufsize > so->so_snd.sb_hiwat)
2743                         (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2744         }
2745         tp->t_maxseg = mss;
2746
2747 #ifdef RTV_RPIPE
2748         if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2749 #endif
2750                 bufsize = so->so_rcv.sb_hiwat;
2751         if (bufsize > mss) {
2752                 bufsize = roundup(bufsize, mss);
2753                 if (bufsize > sb_max)
2754                         bufsize = sb_max;
2755                 if (bufsize > so->so_rcv.sb_hiwat)
2756                         (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2757         }
2758
2759         /*
2760          * Set the slow-start flight size depending on whether this
2761          * is a local network or not.
2762          */
2763         if (tcp_do_rfc3390)
2764                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2765         else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2766                  (!isipv6 && in_localaddr(inp->inp_faddr)))
2767                 tp->snd_cwnd = mss * ss_fltsz_local;
2768         else
2769                 tp->snd_cwnd = mss * ss_fltsz;
2770
2771         if (rt->rt_rmx.rmx_ssthresh) {
2772                 /*
2773                  * There's some sort of gateway or interface
2774                  * buffer limit on the path.  Use this to set
2775                  * the slow start threshhold, but set the
2776                  * threshold to no less than 2*mss.
2777                  */
2778                 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2779                 tcpstat.tcps_usedssthresh++;
2780         }
2781 }
2782
2783 /*
2784  * Determine the MSS option to send on an outgoing SYN.
2785  */
2786 int
2787 tcp_mssopt(tp)
2788         struct tcpcb *tp;
2789 {
2790         struct rtentry *rt;
2791 #ifdef INET6
2792         int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2793         int min_protoh = isipv6 ?
2794                              sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2795                              sizeof(struct tcpiphdr);
2796 #else
2797         const int isipv6 = 0;
2798         const size_t min_protoh = sizeof(struct tcpiphdr);
2799 #endif
2800
2801         if (isipv6)
2802                 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2803         else
2804                 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2805         if (rt == NULL)
2806                 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2807
2808         return (rt->rt_ifp->if_mtu - min_protoh);
2809 }
2810
2811
2812 /*
2813  * When a partial ack arrives, force the retransmission of the
2814  * next unacknowledged segment.  Do not clear tp->t_dupacks.
2815  * By setting snd_nxt to ti_ack, this forces retransmission timer to
2816  * be started again.
2817  */
2818 static void
2819 tcp_newreno_partial_ack(tp, th)
2820         struct tcpcb *tp;
2821         struct tcphdr *th;
2822 {
2823         tcp_seq onxt = tp->snd_nxt;
2824         u_long  ocwnd = tp->snd_cwnd;
2825
2826         callout_stop(tp->tt_rexmt);
2827         tp->t_rtttime = 0;
2828         tp->snd_nxt = th->th_ack;
2829         /*
2830          * Set snd_cwnd to one segment beyond acknowledged offset
2831          * (tp->snd_una has not yet been updated when this function is called.)
2832          */
2833         tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2834         tp->t_flags |= TF_ACKNOW;
2835         (void) tcp_output(tp);
2836         tp->snd_cwnd = ocwnd;
2837         if (SEQ_GT(onxt, tp->snd_nxt))
2838                 tp->snd_nxt = onxt;
2839         /*
2840          * Partial window deflation.  Relies on fact that tp->snd_una
2841          * not updated yet.
2842          */
2843         tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2844 }