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