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