tcp_input.c revision 78642
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 78642 2001-06-23 03:21:46Z silby $
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		if ((taop = tcp_gettaocache(inp)) == NULL) {
1131			taop = &tao_noncached;
1132			bzero(taop, sizeof(*taop));
1133		}
1134		tcp_dooptions(tp, optp, optlen, th, &to);
1135		if (iss)
1136			tp->iss = iss;
1137		else {
1138			tp->iss = tcp_rndiss_next();
1139 		}
1140		tp->irs = th->th_seq;
1141		tcp_sendseqinit(tp);
1142		tcp_rcvseqinit(tp);
1143		tp->snd_recover = tp->snd_una;
1144		/*
1145		 * Initialization of the tcpcb for transaction;
1146		 *   set SND.WND = SEG.WND,
1147		 *   initialize CCsend and CCrecv.
1148		 */
1149		tp->snd_wnd = tiwin;	/* initial send-window */
1150		tp->cc_send = CC_INC(tcp_ccgen);
1151		tp->cc_recv = to.to_cc;
1152		/*
1153		 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1154		 * - compare SEG.CC against cached CC from the same host,
1155		 *	if any.
1156		 * - if SEG.CC > chached value, SYN must be new and is accepted
1157		 *	immediately: save new CC in the cache, mark the socket
1158		 *	connected, enter ESTABLISHED state, turn on flag to
1159		 *	send a SYN in the next segment.
1160		 *	A virtual advertised window is set in rcv_adv to
1161		 *	initialize SWS prevention.  Then enter normal segment
1162		 *	processing: drop SYN, process data and FIN.
1163		 * - otherwise do a normal 3-way handshake.
1164		 */
1165		if ((to.to_flag & TOF_CC) != 0) {
1166		    if (((tp->t_flags & TF_NOPUSH) != 0) &&
1167			taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
1168
1169			taop->tao_cc = to.to_cc;
1170			tp->t_starttime = ticks;
1171			tp->t_state = TCPS_ESTABLISHED;
1172
1173			/*
1174			 * If there is a FIN, or if there is data and the
1175			 * connection is local, then delay SYN,ACK(SYN) in
1176			 * the hope of piggy-backing it on a response
1177			 * segment.  Otherwise must send ACK now in case
1178			 * the other side is slow starting.
1179			 */
1180			if (DELAY_ACK(tp) && ((thflags & TH_FIN) ||
1181			    (tlen != 0 &&
1182#ifdef INET6
1183			      ((isipv6 && in6_localaddr(&inp->in6p_faddr))
1184			      ||
1185			      (!isipv6 &&
1186#endif
1187			    in_localaddr(inp->inp_faddr)
1188#ifdef INET6
1189			       ))
1190#endif
1191			     ))) {
1192                                callout_reset(tp->tt_delack, tcp_delacktime,
1193                                    tcp_timer_delack, tp);
1194				tp->t_flags |= TF_NEEDSYN;
1195			} else
1196				tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1197
1198			/*
1199			 * Limit the `virtual advertised window' to TCP_MAXWIN
1200			 * here.  Even if we requested window scaling, it will
1201			 * become effective only later when our SYN is acked.
1202			 */
1203			tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
1204			tcpstat.tcps_connects++;
1205			soisconnected(so);
1206			callout_reset(tp->tt_keep, tcp_keepinit,
1207				      tcp_timer_keep, tp);
1208			dropsocket = 0;		/* committed to socket */
1209			tcpstat.tcps_accepts++;
1210			goto trimthenstep6;
1211		    }
1212		/* else do standard 3-way handshake */
1213		} else {
1214		    /*
1215		     * No CC option, but maybe CC.NEW:
1216		     *   invalidate cached value.
1217		     */
1218		     taop->tao_cc = 0;
1219		}
1220		/*
1221		 * TAO test failed or there was no CC option,
1222		 *    do a standard 3-way handshake.
1223		 */
1224		tp->t_flags |= TF_ACKNOW;
1225		tp->t_state = TCPS_SYN_RECEIVED;
1226		callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
1227		dropsocket = 0;		/* committed to socket */
1228		tcpstat.tcps_accepts++;
1229		goto trimthenstep6;
1230		}
1231
1232	/*
1233	 * If the state is SYN_RECEIVED:
1234	 *	if seg contains an ACK, but not for our SYN/ACK, send a RST.
1235	 */
1236	case TCPS_SYN_RECEIVED:
1237		if ((thflags & TH_ACK) &&
1238		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1239		     SEQ_GT(th->th_ack, tp->snd_max))) {
1240				rstreason = BANDLIM_RST_OPENPORT;
1241				goto dropwithreset;
1242		}
1243		break;
1244
1245	/*
1246	 * If the state is SYN_SENT:
1247	 *	if seg contains an ACK, but not for our SYN, drop the input.
1248	 *	if seg contains a RST, then drop the connection.
1249	 *	if seg does not contain SYN, then drop it.
1250	 * Otherwise this is an acceptable SYN segment
1251	 *	initialize tp->rcv_nxt and tp->irs
1252	 *	if seg contains ack then advance tp->snd_una
1253	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1254	 *	arrange for segment to be acked (eventually)
1255	 *	continue processing rest of data/controls, beginning with URG
1256	 */
1257	case TCPS_SYN_SENT:
1258		if ((taop = tcp_gettaocache(inp)) == NULL) {
1259			taop = &tao_noncached;
1260			bzero(taop, sizeof(*taop));
1261		}
1262
1263		if ((thflags & TH_ACK) &&
1264		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1265		     SEQ_GT(th->th_ack, tp->snd_max))) {
1266			/*
1267			 * If we have a cached CCsent for the remote host,
1268			 * hence we haven't just crashed and restarted,
1269			 * do not send a RST.  This may be a retransmission
1270			 * from the other side after our earlier ACK was lost.
1271			 * Our new SYN, when it arrives, will serve as the
1272			 * needed ACK.
1273			 */
1274			if (taop->tao_ccsent != 0)
1275				goto drop;
1276			else {
1277				rstreason = BANDLIM_UNLIMITED;
1278				goto dropwithreset;
1279			}
1280		}
1281		if (thflags & TH_RST) {
1282			if (thflags & TH_ACK)
1283				tp = tcp_drop(tp, ECONNREFUSED);
1284			goto drop;
1285		}
1286		if ((thflags & TH_SYN) == 0)
1287			goto drop;
1288		tp->snd_wnd = th->th_win;	/* initial send window */
1289		tp->cc_recv = to.to_cc;		/* foreign CC */
1290
1291		tp->irs = th->th_seq;
1292		tcp_rcvseqinit(tp);
1293		if (thflags & TH_ACK) {
1294			/*
1295			 * Our SYN was acked.  If segment contains CC.ECHO
1296			 * option, check it to make sure this segment really
1297			 * matches our SYN.  If not, just drop it as old
1298			 * duplicate, but send an RST if we're still playing
1299			 * by the old rules.  If no CC.ECHO option, make sure
1300			 * we don't get fooled into using T/TCP.
1301			 */
1302			if (to.to_flag & TOF_CCECHO) {
1303				if (tp->cc_send != to.to_ccecho) {
1304					if (taop->tao_ccsent != 0)
1305						goto drop;
1306					else {
1307						rstreason = BANDLIM_UNLIMITED;
1308						goto dropwithreset;
1309					}
1310				}
1311			} else
1312				tp->t_flags &= ~TF_RCVD_CC;
1313			tcpstat.tcps_connects++;
1314			soisconnected(so);
1315			/* Do window scaling on this connection? */
1316			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1317				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1318				tp->snd_scale = tp->requested_s_scale;
1319				tp->rcv_scale = tp->request_r_scale;
1320			}
1321			/* Segment is acceptable, update cache if undefined. */
1322			if (taop->tao_ccsent == 0)
1323				taop->tao_ccsent = to.to_ccecho;
1324
1325			tp->rcv_adv += tp->rcv_wnd;
1326			tp->snd_una++;		/* SYN is acked */
1327			/*
1328			 * If there's data, delay ACK; if there's also a FIN
1329			 * ACKNOW will be turned on later.
1330			 */
1331			if (DELAY_ACK(tp) && tlen != 0)
1332                                callout_reset(tp->tt_delack, tcp_delacktime,
1333                                    tcp_timer_delack, tp);
1334			else
1335				tp->t_flags |= TF_ACKNOW;
1336			/*
1337			 * Received <SYN,ACK> in SYN_SENT[*] state.
1338			 * Transitions:
1339			 *	SYN_SENT  --> ESTABLISHED
1340			 *	SYN_SENT* --> FIN_WAIT_1
1341			 */
1342			tp->t_starttime = ticks;
1343			if (tp->t_flags & TF_NEEDFIN) {
1344				tp->t_state = TCPS_FIN_WAIT_1;
1345				tp->t_flags &= ~TF_NEEDFIN;
1346				thflags &= ~TH_SYN;
1347			} else {
1348				tp->t_state = TCPS_ESTABLISHED;
1349				callout_reset(tp->tt_keep, tcp_keepidle,
1350					      tcp_timer_keep, tp);
1351			}
1352		} else {
1353		/*
1354		 *  Received initial SYN in SYN-SENT[*] state => simul-
1355		 *  taneous open.  If segment contains CC option and there is
1356		 *  a cached CC, apply TAO test; if it succeeds, connection is
1357		 *  half-synchronized.  Otherwise, do 3-way handshake:
1358		 *        SYN-SENT -> SYN-RECEIVED
1359		 *        SYN-SENT* -> SYN-RECEIVED*
1360		 *  If there was no CC option, clear cached CC value.
1361		 */
1362			tp->t_flags |= TF_ACKNOW;
1363			callout_stop(tp->tt_rexmt);
1364			if (to.to_flag & TOF_CC) {
1365				if (taop->tao_cc != 0 &&
1366				    CC_GT(to.to_cc, taop->tao_cc)) {
1367					/*
1368					 * update cache and make transition:
1369					 *        SYN-SENT -> ESTABLISHED*
1370					 *        SYN-SENT* -> FIN-WAIT-1*
1371					 */
1372					taop->tao_cc = to.to_cc;
1373					tp->t_starttime = ticks;
1374					if (tp->t_flags & TF_NEEDFIN) {
1375						tp->t_state = TCPS_FIN_WAIT_1;
1376						tp->t_flags &= ~TF_NEEDFIN;
1377					} else {
1378						tp->t_state = TCPS_ESTABLISHED;
1379						callout_reset(tp->tt_keep,
1380							      tcp_keepidle,
1381							      tcp_timer_keep,
1382							      tp);
1383					}
1384					tp->t_flags |= TF_NEEDSYN;
1385				} else
1386					tp->t_state = TCPS_SYN_RECEIVED;
1387			} else {
1388				/* CC.NEW or no option => invalidate cache */
1389				taop->tao_cc = 0;
1390				tp->t_state = TCPS_SYN_RECEIVED;
1391			}
1392		}
1393
1394trimthenstep6:
1395		/*
1396		 * Advance th->th_seq to correspond to first data byte.
1397		 * If data, trim to stay within window,
1398		 * dropping FIN if necessary.
1399		 */
1400		th->th_seq++;
1401		if (tlen > tp->rcv_wnd) {
1402			todrop = tlen - tp->rcv_wnd;
1403			m_adj(m, -todrop);
1404			tlen = tp->rcv_wnd;
1405			thflags &= ~TH_FIN;
1406			tcpstat.tcps_rcvpackafterwin++;
1407			tcpstat.tcps_rcvbyteafterwin += todrop;
1408		}
1409		tp->snd_wl1 = th->th_seq - 1;
1410		tp->rcv_up = th->th_seq;
1411		/*
1412		 *  Client side of transaction: already sent SYN and data.
1413		 *  If the remote host used T/TCP to validate the SYN,
1414		 *  our data will be ACK'd; if so, enter normal data segment
1415		 *  processing in the middle of step 5, ack processing.
1416		 *  Otherwise, goto step 6.
1417		 */
1418 		if (thflags & TH_ACK)
1419			goto process_ACK;
1420		goto step6;
1421	/*
1422	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1423	 *	if segment contains a SYN and CC [not CC.NEW] option:
1424	 *              if state == TIME_WAIT and connection duration > MSL,
1425	 *                  drop packet and send RST;
1426	 *
1427	 *		if SEG.CC > CCrecv then is new SYN, and can implicitly
1428	 *		    ack the FIN (and data) in retransmission queue.
1429	 *                  Complete close and delete TCPCB.  Then reprocess
1430	 *                  segment, hoping to find new TCPCB in LISTEN state;
1431	 *
1432	 *		else must be old SYN; drop it.
1433	 *      else do normal processing.
1434	 */
1435	case TCPS_LAST_ACK:
1436	case TCPS_CLOSING:
1437	case TCPS_TIME_WAIT:
1438		if ((thflags & TH_SYN) &&
1439		    (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
1440			if (tp->t_state == TCPS_TIME_WAIT &&
1441					(ticks - tp->t_starttime) > tcp_msl) {
1442				rstreason = BANDLIM_UNLIMITED;
1443				goto dropwithreset;
1444			}
1445			if (CC_GT(to.to_cc, tp->cc_recv)) {
1446				tp = tcp_close(tp);
1447				goto findpcb;
1448			}
1449			else
1450				goto drop;
1451		}
1452 		break;  /* continue normal processing */
1453	}
1454
1455	/*
1456	 * States other than LISTEN or SYN_SENT.
1457	 * First check the RST flag and sequence number since reset segments
1458	 * are exempt from the timestamp and connection count tests.  This
1459	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1460	 * below which allowed reset segments in half the sequence space
1461	 * to fall though and be processed (which gives forged reset
1462	 * segments with a random sequence number a 50 percent chance of
1463	 * killing a connection).
1464	 * Then check timestamp, if present.
1465	 * Then check the connection count, if present.
1466	 * Then check that at least some bytes of segment are within
1467	 * receive window.  If segment begins before rcv_nxt,
1468	 * drop leading data (and SYN); if nothing left, just ack.
1469	 *
1470	 *
1471	 * If the RST bit is set, check the sequence number to see
1472	 * if this is a valid reset segment.
1473	 * RFC 793 page 37:
1474	 *   In all states except SYN-SENT, all reset (RST) segments
1475	 *   are validated by checking their SEQ-fields.  A reset is
1476	 *   valid if its sequence number is in the window.
1477	 * Note: this does not take into account delayed ACKs, so
1478	 *   we should test against last_ack_sent instead of rcv_nxt.
1479	 *   The sequence number in the reset segment is normally an
1480	 *   echo of our outgoing acknowlegement numbers, but some hosts
1481	 *   send a reset with the sequence number at the rightmost edge
1482	 *   of our receive window, and we have to handle this case.
1483	 * If we have multiple segments in flight, the intial reset
1484	 * segment sequence numbers will be to the left of last_ack_sent,
1485	 * but they will eventually catch up.
1486	 * In any case, it never made sense to trim reset segments to
1487	 * fit the receive window since RFC 1122 says:
1488	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1489	 *
1490	 *    A TCP SHOULD allow a received RST segment to include data.
1491	 *
1492	 *    DISCUSSION
1493	 *         It has been suggested that a RST segment could contain
1494	 *         ASCII text that encoded and explained the cause of the
1495	 *         RST.  No standard has yet been established for such
1496	 *         data.
1497	 *
1498	 * If the reset segment passes the sequence number test examine
1499	 * the state:
1500	 *    SYN_RECEIVED STATE:
1501	 *	If passive open, return to LISTEN state.
1502	 *	If active open, inform user that connection was refused.
1503	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1504	 *	Inform user that connection was reset, and close tcb.
1505	 *    CLOSING, LAST_ACK STATES:
1506	 *	Close the tcb.
1507	 *    TIME_WAIT STATE:
1508	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
1509	 *      RFC 1337.
1510	 */
1511	if (thflags & TH_RST) {
1512		if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1513		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1514			switch (tp->t_state) {
1515
1516			case TCPS_SYN_RECEIVED:
1517				so->so_error = ECONNREFUSED;
1518				goto close;
1519
1520			case TCPS_ESTABLISHED:
1521			case TCPS_FIN_WAIT_1:
1522			case TCPS_FIN_WAIT_2:
1523			case TCPS_CLOSE_WAIT:
1524				so->so_error = ECONNRESET;
1525			close:
1526				tp->t_state = TCPS_CLOSED;
1527				tcpstat.tcps_drops++;
1528				tp = tcp_close(tp);
1529				break;
1530
1531			case TCPS_CLOSING:
1532			case TCPS_LAST_ACK:
1533				tp = tcp_close(tp);
1534				break;
1535
1536			case TCPS_TIME_WAIT:
1537				break;
1538			}
1539		}
1540		goto drop;
1541	}
1542
1543	/*
1544	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1545	 * and it's less than ts_recent, drop it.
1546	 */
1547	if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1548	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1549
1550		/* Check to see if ts_recent is over 24 days old.  */
1551		if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1552			/*
1553			 * Invalidate ts_recent.  If this segment updates
1554			 * ts_recent, the age will be reset later and ts_recent
1555			 * will get a valid value.  If it does not, setting
1556			 * ts_recent to zero will at least satisfy the
1557			 * requirement that zero be placed in the timestamp
1558			 * echo reply when ts_recent isn't valid.  The
1559			 * age isn't reset until we get a valid ts_recent
1560			 * because we don't want out-of-order segments to be
1561			 * dropped when ts_recent is old.
1562			 */
1563			tp->ts_recent = 0;
1564		} else {
1565			tcpstat.tcps_rcvduppack++;
1566			tcpstat.tcps_rcvdupbyte += tlen;
1567			tcpstat.tcps_pawsdrop++;
1568			goto dropafterack;
1569		}
1570	}
1571
1572	/*
1573	 * T/TCP mechanism
1574	 *   If T/TCP was negotiated and the segment doesn't have CC,
1575	 *   or if its CC is wrong then drop the segment.
1576	 *   RST segments do not have to comply with this.
1577	 */
1578	if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1579	    ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1580 		goto dropafterack;
1581
1582	/*
1583	 * In the SYN-RECEIVED state, validate that the packet belongs to
1584	 * this connection before trimming the data to fit the receive
1585	 * window.  Check the sequence number versus IRS since we know
1586	 * the sequence numbers haven't wrapped.  This is a partial fix
1587	 * for the "LAND" DoS attack.
1588	 */
1589	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1590		rstreason = BANDLIM_RST_OPENPORT;
1591		goto dropwithreset;
1592	}
1593
1594	todrop = tp->rcv_nxt - th->th_seq;
1595	if (todrop > 0) {
1596		if (thflags & TH_SYN) {
1597			thflags &= ~TH_SYN;
1598			th->th_seq++;
1599			if (th->th_urp > 1)
1600				th->th_urp--;
1601			else
1602				thflags &= ~TH_URG;
1603			todrop--;
1604		}
1605		/*
1606		 * Following if statement from Stevens, vol. 2, p. 960.
1607		 */
1608		if (todrop > tlen
1609		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1610			/*
1611			 * Any valid FIN must be to the left of the window.
1612			 * At this point the FIN must be a duplicate or out
1613			 * of sequence; drop it.
1614			 */
1615			thflags &= ~TH_FIN;
1616
1617			/*
1618			 * Send an ACK to resynchronize and drop any data.
1619			 * But keep on processing for RST or ACK.
1620			 */
1621			tp->t_flags |= TF_ACKNOW;
1622			todrop = tlen;
1623			tcpstat.tcps_rcvduppack++;
1624			tcpstat.tcps_rcvdupbyte += todrop;
1625		} else {
1626			tcpstat.tcps_rcvpartduppack++;
1627			tcpstat.tcps_rcvpartdupbyte += todrop;
1628		}
1629		drop_hdrlen += todrop;	/* drop from the top afterwards */
1630		th->th_seq += todrop;
1631		tlen -= todrop;
1632		if (th->th_urp > todrop)
1633			th->th_urp -= todrop;
1634		else {
1635			thflags &= ~TH_URG;
1636			th->th_urp = 0;
1637		}
1638	}
1639
1640	/*
1641	 * If new data are received on a connection after the
1642	 * user processes are gone, then RST the other end.
1643	 */
1644	if ((so->so_state & SS_NOFDREF) &&
1645	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1646		tp = tcp_close(tp);
1647		tcpstat.tcps_rcvafterclose++;
1648		rstreason = BANDLIM_UNLIMITED;
1649		goto dropwithreset;
1650	}
1651
1652	/*
1653	 * If segment ends after window, drop trailing data
1654	 * (and PUSH and FIN); if nothing left, just ACK.
1655	 */
1656	todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1657	if (todrop > 0) {
1658		tcpstat.tcps_rcvpackafterwin++;
1659		if (todrop >= tlen) {
1660			tcpstat.tcps_rcvbyteafterwin += tlen;
1661			/*
1662			 * If a new connection request is received
1663			 * while in TIME_WAIT, drop the old connection
1664			 * and start over if the sequence numbers
1665			 * are above the previous ones.
1666			 */
1667			if (thflags & TH_SYN &&
1668			    tp->t_state == TCPS_TIME_WAIT &&
1669			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1670				iss = tcp_rndiss_next();
1671				tp = tcp_close(tp);
1672				goto findpcb;
1673			}
1674			/*
1675			 * If window is closed can only take segments at
1676			 * window edge, and have to drop data and PUSH from
1677			 * incoming segments.  Continue processing, but
1678			 * remember to ack.  Otherwise, drop segment
1679			 * and ack.
1680			 */
1681			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1682				tp->t_flags |= TF_ACKNOW;
1683				tcpstat.tcps_rcvwinprobe++;
1684			} else
1685				goto dropafterack;
1686		} else
1687			tcpstat.tcps_rcvbyteafterwin += todrop;
1688		m_adj(m, -todrop);
1689		tlen -= todrop;
1690		thflags &= ~(TH_PUSH|TH_FIN);
1691	}
1692
1693	/*
1694	 * If last ACK falls within this segment's sequence numbers,
1695	 * record its timestamp.
1696	 * NOTE that the test is modified according to the latest
1697	 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1698	 */
1699	if ((to.to_flag & TOF_TS) != 0 &&
1700	    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1701		tp->ts_recent_age = ticks;
1702		tp->ts_recent = to.to_tsval;
1703	}
1704
1705	/*
1706	 * If a SYN is in the window, then this is an
1707	 * error and we send an RST and drop the connection.
1708	 */
1709	if (thflags & TH_SYN) {
1710		tp = tcp_drop(tp, ECONNRESET);
1711		rstreason = BANDLIM_UNLIMITED;
1712		goto dropwithreset;
1713	}
1714
1715	/*
1716	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1717	 * flag is on (half-synchronized state), then queue data for
1718	 * later processing; else drop segment and return.
1719	 */
1720	if ((thflags & TH_ACK) == 0) {
1721		if (tp->t_state == TCPS_SYN_RECEIVED ||
1722		    (tp->t_flags & TF_NEEDSYN))
1723			goto step6;
1724		else
1725			goto drop;
1726	}
1727
1728	/*
1729	 * Ack processing.
1730	 */
1731	switch (tp->t_state) {
1732
1733	/*
1734	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1735	 * ESTABLISHED state and continue processing.
1736	 * The ACK was checked above.
1737	 */
1738	case TCPS_SYN_RECEIVED:
1739
1740		tcpstat.tcps_connects++;
1741		soisconnected(so);
1742		/* Do window scaling? */
1743		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1744			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1745			tp->snd_scale = tp->requested_s_scale;
1746			tp->rcv_scale = tp->request_r_scale;
1747		}
1748		/*
1749		 * Upon successful completion of 3-way handshake,
1750		 * update cache.CC if it was undefined, pass any queued
1751		 * data to the user, and advance state appropriately.
1752		 */
1753		if ((taop = tcp_gettaocache(inp)) != NULL &&
1754		    taop->tao_cc == 0)
1755			taop->tao_cc = tp->cc_recv;
1756
1757		/*
1758		 * Make transitions:
1759		 *      SYN-RECEIVED  -> ESTABLISHED
1760		 *      SYN-RECEIVED* -> FIN-WAIT-1
1761		 */
1762		tp->t_starttime = ticks;
1763		if (tp->t_flags & TF_NEEDFIN) {
1764			tp->t_state = TCPS_FIN_WAIT_1;
1765			tp->t_flags &= ~TF_NEEDFIN;
1766		} else {
1767			tp->t_state = TCPS_ESTABLISHED;
1768			callout_reset(tp->tt_keep, tcp_keepidle,
1769				      tcp_timer_keep, tp);
1770		}
1771		/*
1772		 * If segment contains data or ACK, will call tcp_reass()
1773		 * later; if not, do so now to pass queued data to user.
1774		 */
1775		if (tlen == 0 && (thflags & TH_FIN) == 0)
1776			(void) tcp_reass(tp, (struct tcphdr *)0, 0,
1777			    (struct mbuf *)0);
1778		tp->snd_wl1 = th->th_seq - 1;
1779		/* fall into ... */
1780
1781	/*
1782	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1783	 * ACKs.  If the ack is in the range
1784	 *	tp->snd_una < th->th_ack <= tp->snd_max
1785	 * then advance tp->snd_una to th->th_ack and drop
1786	 * data from the retransmission queue.  If this ACK reflects
1787	 * more up to date window information we update our window information.
1788	 */
1789	case TCPS_ESTABLISHED:
1790	case TCPS_FIN_WAIT_1:
1791	case TCPS_FIN_WAIT_2:
1792	case TCPS_CLOSE_WAIT:
1793	case TCPS_CLOSING:
1794	case TCPS_LAST_ACK:
1795	case TCPS_TIME_WAIT:
1796
1797		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1798			if (tlen == 0 && tiwin == tp->snd_wnd) {
1799				tcpstat.tcps_rcvdupack++;
1800				/*
1801				 * If we have outstanding data (other than
1802				 * a window probe), this is a completely
1803				 * duplicate ack (ie, window info didn't
1804				 * change), the ack is the biggest we've
1805				 * seen and we've seen exactly our rexmt
1806				 * threshhold of them, assume a packet
1807				 * has been dropped and retransmit it.
1808				 * Kludge snd_nxt & the congestion
1809				 * window so we send only this one
1810				 * packet.
1811				 *
1812				 * We know we're losing at the current
1813				 * window size so do congestion avoidance
1814				 * (set ssthresh to half the current window
1815				 * and pull our congestion window back to
1816				 * the new ssthresh).
1817				 *
1818				 * Dup acks mean that packets have left the
1819				 * network (they're now cached at the receiver)
1820				 * so bump cwnd by the amount in the receiver
1821				 * to keep a constant cwnd packets in the
1822				 * network.
1823				 */
1824				if (!callout_active(tp->tt_rexmt) ||
1825				    th->th_ack != tp->snd_una)
1826					tp->t_dupacks = 0;
1827				else if (++tp->t_dupacks == tcprexmtthresh) {
1828					tcp_seq onxt = tp->snd_nxt;
1829					u_int win =
1830					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1831						tp->t_maxseg;
1832					if (tcp_do_newreno && SEQ_LT(th->th_ack,
1833					    tp->snd_recover)) {
1834						/* False retransmit, should not
1835						 * cut window
1836						 */
1837						tp->snd_cwnd += tp->t_maxseg;
1838						tp->t_dupacks = 0;
1839						(void) tcp_output(tp);
1840						goto drop;
1841					}
1842					if (win < 2)
1843						win = 2;
1844					tp->snd_ssthresh = win * tp->t_maxseg;
1845					tp->snd_recover = tp->snd_max;
1846					callout_stop(tp->tt_rexmt);
1847					tp->t_rtttime = 0;
1848					tp->snd_nxt = th->th_ack;
1849					tp->snd_cwnd = tp->t_maxseg;
1850					(void) tcp_output(tp);
1851					tp->snd_cwnd = tp->snd_ssthresh +
1852					       tp->t_maxseg * tp->t_dupacks;
1853					if (SEQ_GT(onxt, tp->snd_nxt))
1854						tp->snd_nxt = onxt;
1855					goto drop;
1856				} else if (tp->t_dupacks > tcprexmtthresh) {
1857					tp->snd_cwnd += tp->t_maxseg;
1858					(void) tcp_output(tp);
1859					goto drop;
1860				}
1861			} else
1862				tp->t_dupacks = 0;
1863			break;
1864		}
1865		/*
1866		 * If the congestion window was inflated to account
1867		 * for the other side's cached packets, retract it.
1868		 */
1869		if (tcp_do_newreno == 0) {
1870                        if (tp->t_dupacks >= tcprexmtthresh &&
1871                                tp->snd_cwnd > tp->snd_ssthresh)
1872                                tp->snd_cwnd = tp->snd_ssthresh;
1873                        tp->t_dupacks = 0;
1874                } else if (tp->t_dupacks >= tcprexmtthresh &&
1875		    !tcp_newreno(tp, th)) {
1876                        /*
1877                         * Window inflation should have left us with approx.
1878                         * snd_ssthresh outstanding data.  But in case we
1879                         * would be inclined to send a burst, better to do
1880                         * it via the slow start mechanism.
1881                         */
1882			if (SEQ_GT(th->th_ack + tp->snd_ssthresh, tp->snd_max))
1883                                tp->snd_cwnd =
1884				    tp->snd_max - th->th_ack + tp->t_maxseg;
1885			else
1886                        	tp->snd_cwnd = tp->snd_ssthresh;
1887                        tp->t_dupacks = 0;
1888                }
1889		if (SEQ_GT(th->th_ack, tp->snd_max)) {
1890			tcpstat.tcps_rcvacktoomuch++;
1891			goto dropafterack;
1892		}
1893		/*
1894		 *  If we reach this point, ACK is not a duplicate,
1895		 *     i.e., it ACKs something we sent.
1896		 */
1897		if (tp->t_flags & TF_NEEDSYN) {
1898			/*
1899			 * T/TCP: Connection was half-synchronized, and our
1900			 * SYN has been ACK'd (so connection is now fully
1901			 * synchronized).  Go to non-starred state,
1902			 * increment snd_una for ACK of SYN, and check if
1903			 * we can do window scaling.
1904			 */
1905			tp->t_flags &= ~TF_NEEDSYN;
1906			tp->snd_una++;
1907			/* Do window scaling? */
1908			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1909				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
1910				tp->snd_scale = tp->requested_s_scale;
1911				tp->rcv_scale = tp->request_r_scale;
1912			}
1913		}
1914
1915process_ACK:
1916		acked = th->th_ack - tp->snd_una;
1917		tcpstat.tcps_rcvackpack++;
1918		tcpstat.tcps_rcvackbyte += acked;
1919
1920		/*
1921		 * If we just performed our first retransmit, and the ACK
1922		 * arrives within our recovery window, then it was a mistake
1923		 * to do the retransmit in the first place.  Recover our
1924		 * original cwnd and ssthresh, and proceed to transmit where
1925		 * we left off.
1926		 */
1927		if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1928			tp->snd_cwnd = tp->snd_cwnd_prev;
1929			tp->snd_ssthresh = tp->snd_ssthresh_prev;
1930			tp->snd_nxt = tp->snd_max;
1931			tp->t_badrxtwin = 0;	/* XXX probably not required */
1932		}
1933
1934		/*
1935		 * If we have a timestamp reply, update smoothed
1936		 * round trip time.  If no timestamp is present but
1937		 * transmit timer is running and timed sequence
1938		 * number was acked, update smoothed round trip time.
1939		 * Since we now have an rtt measurement, cancel the
1940		 * timer backoff (cf., Phil Karn's retransmit alg.).
1941		 * Recompute the initial retransmit timer.
1942		 */
1943		if (to.to_flag & TOF_TS)
1944			tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1945		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
1946			tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1947
1948		/*
1949		 * If all outstanding data is acked, stop retransmit
1950		 * timer and remember to restart (more output or persist).
1951		 * If there is more data to be acked, restart retransmit
1952		 * timer, using current (possibly backed-off) value.
1953		 */
1954		if (th->th_ack == tp->snd_max) {
1955			callout_stop(tp->tt_rexmt);
1956			needoutput = 1;
1957		} else if (!callout_active(tp->tt_persist))
1958			callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1959				      tcp_timer_rexmt, tp);
1960
1961		/*
1962		 * If no data (only SYN) was ACK'd,
1963		 *    skip rest of ACK processing.
1964		 */
1965		if (acked == 0)
1966			goto step6;
1967
1968		/*
1969		 * When new data is acked, open the congestion window.
1970		 * If the window gives us less than ssthresh packets
1971		 * in flight, open exponentially (maxseg per packet).
1972		 * Otherwise open linearly: maxseg per window
1973		 * (maxseg^2 / cwnd per packet).
1974		 */
1975		{
1976		register u_int cw = tp->snd_cwnd;
1977		register u_int incr = tp->t_maxseg;
1978
1979		if (cw > tp->snd_ssthresh)
1980			incr = incr * incr / cw;
1981		/*
1982		 * If t_dupacks != 0 here, it indicates that we are still
1983		 * in NewReno fast recovery mode, so we leave the congestion
1984		 * window alone.
1985		 */
1986		if (tcp_do_newreno == 0 || tp->t_dupacks == 0)
1987			tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
1988		}
1989		if (acked > so->so_snd.sb_cc) {
1990			tp->snd_wnd -= so->so_snd.sb_cc;
1991			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1992			ourfinisacked = 1;
1993		} else {
1994			sbdrop(&so->so_snd, acked);
1995			tp->snd_wnd -= acked;
1996			ourfinisacked = 0;
1997		}
1998		sowwakeup(so);
1999		tp->snd_una = th->th_ack;
2000		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2001			tp->snd_nxt = tp->snd_una;
2002
2003		switch (tp->t_state) {
2004
2005		/*
2006		 * In FIN_WAIT_1 STATE in addition to the processing
2007		 * for the ESTABLISHED state if our FIN is now acknowledged
2008		 * then enter FIN_WAIT_2.
2009		 */
2010		case TCPS_FIN_WAIT_1:
2011			if (ourfinisacked) {
2012				/*
2013				 * If we can't receive any more
2014				 * data, then closing user can proceed.
2015				 * Starting the timer is contrary to the
2016				 * specification, but if we don't get a FIN
2017				 * we'll hang forever.
2018				 */
2019				if (so->so_state & SS_CANTRCVMORE) {
2020					soisdisconnected(so);
2021					callout_reset(tp->tt_2msl, tcp_maxidle,
2022						      tcp_timer_2msl, tp);
2023				}
2024				tp->t_state = TCPS_FIN_WAIT_2;
2025			}
2026			break;
2027
2028	 	/*
2029		 * In CLOSING STATE in addition to the processing for
2030		 * the ESTABLISHED state if the ACK acknowledges our FIN
2031		 * then enter the TIME-WAIT state, otherwise ignore
2032		 * the segment.
2033		 */
2034		case TCPS_CLOSING:
2035			if (ourfinisacked) {
2036				tp->t_state = TCPS_TIME_WAIT;
2037				tcp_canceltimers(tp);
2038				/* Shorten TIME_WAIT [RFC-1644, p.28] */
2039				if (tp->cc_recv != 0 &&
2040				    (ticks - tp->t_starttime) < tcp_msl)
2041					callout_reset(tp->tt_2msl,
2042						      tp->t_rxtcur *
2043						      TCPTV_TWTRUNC,
2044						      tcp_timer_2msl, tp);
2045				else
2046					callout_reset(tp->tt_2msl, 2 * tcp_msl,
2047						      tcp_timer_2msl, tp);
2048				soisdisconnected(so);
2049			}
2050			break;
2051
2052		/*
2053		 * In LAST_ACK, we may still be waiting for data to drain
2054		 * and/or to be acked, as well as for the ack of our FIN.
2055		 * If our FIN is now acknowledged, delete the TCB,
2056		 * enter the closed state and return.
2057		 */
2058		case TCPS_LAST_ACK:
2059			if (ourfinisacked) {
2060				tp = tcp_close(tp);
2061				goto drop;
2062			}
2063			break;
2064
2065		/*
2066		 * In TIME_WAIT state the only thing that should arrive
2067		 * is a retransmission of the remote FIN.  Acknowledge
2068		 * it and restart the finack timer.
2069		 */
2070		case TCPS_TIME_WAIT:
2071			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2072				      tcp_timer_2msl, tp);
2073			goto dropafterack;
2074		}
2075	}
2076
2077step6:
2078	/*
2079	 * Update window information.
2080	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2081	 */
2082	if ((thflags & TH_ACK) &&
2083	    (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2084	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2085	     (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2086		/* keep track of pure window updates */
2087		if (tlen == 0 &&
2088		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2089			tcpstat.tcps_rcvwinupd++;
2090		tp->snd_wnd = tiwin;
2091		tp->snd_wl1 = th->th_seq;
2092		tp->snd_wl2 = th->th_ack;
2093		if (tp->snd_wnd > tp->max_sndwnd)
2094			tp->max_sndwnd = tp->snd_wnd;
2095		needoutput = 1;
2096	}
2097
2098	/*
2099	 * Process segments with URG.
2100	 */
2101	if ((thflags & TH_URG) && th->th_urp &&
2102	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2103		/*
2104		 * This is a kludge, but if we receive and accept
2105		 * random urgent pointers, we'll crash in
2106		 * soreceive.  It's hard to imagine someone
2107		 * actually wanting to send this much urgent data.
2108		 */
2109		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2110			th->th_urp = 0;			/* XXX */
2111			thflags &= ~TH_URG;		/* XXX */
2112			goto dodata;			/* XXX */
2113		}
2114		/*
2115		 * If this segment advances the known urgent pointer,
2116		 * then mark the data stream.  This should not happen
2117		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2118		 * a FIN has been received from the remote side.
2119		 * In these states we ignore the URG.
2120		 *
2121		 * According to RFC961 (Assigned Protocols),
2122		 * the urgent pointer points to the last octet
2123		 * of urgent data.  We continue, however,
2124		 * to consider it to indicate the first octet
2125		 * of data past the urgent section as the original
2126		 * spec states (in one of two places).
2127		 */
2128		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2129			tp->rcv_up = th->th_seq + th->th_urp;
2130			so->so_oobmark = so->so_rcv.sb_cc +
2131			    (tp->rcv_up - tp->rcv_nxt) - 1;
2132			if (so->so_oobmark == 0)
2133				so->so_state |= SS_RCVATMARK;
2134			sohasoutofband(so);
2135			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2136		}
2137		/*
2138		 * Remove out of band data so doesn't get presented to user.
2139		 * This can happen independent of advancing the URG pointer,
2140		 * but if two URG's are pending at once, some out-of-band
2141		 * data may creep in... ick.
2142		 */
2143		if (th->th_urp <= (u_long)tlen
2144#ifdef SO_OOBINLINE
2145		     && (so->so_options & SO_OOBINLINE) == 0
2146#endif
2147		     )
2148			tcp_pulloutofband(so, th, m,
2149				drop_hdrlen);	/* hdr drop is delayed */
2150	} else
2151		/*
2152		 * If no out of band data is expected,
2153		 * pull receive urgent pointer along
2154		 * with the receive window.
2155		 */
2156		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2157			tp->rcv_up = tp->rcv_nxt;
2158dodata:							/* XXX */
2159
2160	/*
2161	 * Process the segment text, merging it into the TCP sequencing queue,
2162	 * and arranging for acknowledgment of receipt if necessary.
2163	 * This process logically involves adjusting tp->rcv_wnd as data
2164	 * is presented to the user (this happens in tcp_usrreq.c,
2165	 * case PRU_RCVD).  If a FIN has already been received on this
2166	 * connection then we just ignore the text.
2167	 */
2168	if ((tlen || (thflags&TH_FIN)) &&
2169	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2170		m_adj(m, drop_hdrlen);	/* delayed header drop */
2171		/*
2172		 * Insert segment which inludes th into reassembly queue of tcp with
2173		 * control block tp.  Return TH_FIN if reassembly now includes
2174		 * a segment with FIN.  This handle the common case inline (segment
2175		 * is the next to be received on an established connection, and the
2176		 * queue is empty), avoiding linkage into and removal from the queue
2177		 * and repetition of various conversions.
2178		 * Set DELACK for segments received in order, but ack immediately
2179		 * when segments are out of order (so fast retransmit can work).
2180		 */
2181		if (th->th_seq == tp->rcv_nxt &&
2182		    LIST_EMPTY(&tp->t_segq) &&
2183		    TCPS_HAVEESTABLISHED(tp->t_state)) {
2184			if (DELAY_ACK(tp))
2185				callout_reset(tp->tt_delack, tcp_delacktime,
2186				    tcp_timer_delack, tp);
2187			else
2188				tp->t_flags |= TF_ACKNOW;
2189			tp->rcv_nxt += tlen;
2190			thflags = th->th_flags & TH_FIN;
2191			tcpstat.tcps_rcvpack++;
2192			tcpstat.tcps_rcvbyte += tlen;
2193			ND6_HINT(tp);
2194			sbappend(&so->so_rcv, m);
2195			sorwakeup(so);
2196		} else {
2197			thflags = tcp_reass(tp, th, &tlen, m);
2198			tp->t_flags |= TF_ACKNOW;
2199		}
2200
2201		/*
2202		 * Note the amount of data that peer has sent into
2203		 * our window, in order to estimate the sender's
2204		 * buffer size.
2205		 */
2206		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2207	} else {
2208		m_freem(m);
2209		thflags &= ~TH_FIN;
2210	}
2211
2212	/*
2213	 * If FIN is received ACK the FIN and let the user know
2214	 * that the connection is closing.
2215	 */
2216	if (thflags & TH_FIN) {
2217		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2218			socantrcvmore(so);
2219			/*
2220			 *  If connection is half-synchronized
2221			 *  (ie NEEDSYN flag on) then delay ACK,
2222			 *  so it may be piggybacked when SYN is sent.
2223			 *  Otherwise, since we received a FIN then no
2224			 *  more input can be expected, send ACK now.
2225			 */
2226			if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2227                                callout_reset(tp->tt_delack, tcp_delacktime,
2228                                    tcp_timer_delack, tp);
2229			else
2230				tp->t_flags |= TF_ACKNOW;
2231			tp->rcv_nxt++;
2232		}
2233		switch (tp->t_state) {
2234
2235	 	/*
2236		 * In SYN_RECEIVED and ESTABLISHED STATES
2237		 * enter the CLOSE_WAIT state.
2238		 */
2239		case TCPS_SYN_RECEIVED:
2240			tp->t_starttime = ticks;
2241			/*FALLTHROUGH*/
2242		case TCPS_ESTABLISHED:
2243			tp->t_state = TCPS_CLOSE_WAIT;
2244			break;
2245
2246	 	/*
2247		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2248		 * enter the CLOSING state.
2249		 */
2250		case TCPS_FIN_WAIT_1:
2251			tp->t_state = TCPS_CLOSING;
2252			break;
2253
2254	 	/*
2255		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2256		 * starting the time-wait timer, turning off the other
2257		 * standard timers.
2258		 */
2259		case TCPS_FIN_WAIT_2:
2260			tp->t_state = TCPS_TIME_WAIT;
2261			tcp_canceltimers(tp);
2262			/* Shorten TIME_WAIT [RFC-1644, p.28] */
2263			if (tp->cc_recv != 0 &&
2264			    (ticks - tp->t_starttime) < tcp_msl) {
2265				callout_reset(tp->tt_2msl,
2266					      tp->t_rxtcur * TCPTV_TWTRUNC,
2267					      tcp_timer_2msl, tp);
2268				/* For transaction client, force ACK now. */
2269				tp->t_flags |= TF_ACKNOW;
2270			}
2271			else
2272				callout_reset(tp->tt_2msl, 2 * tcp_msl,
2273					      tcp_timer_2msl, tp);
2274			soisdisconnected(so);
2275			break;
2276
2277		/*
2278		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2279		 */
2280		case TCPS_TIME_WAIT:
2281			callout_reset(tp->tt_2msl, 2 * tcp_msl,
2282				      tcp_timer_2msl, tp);
2283			break;
2284		}
2285	}
2286#ifdef TCPDEBUG
2287	if (so->so_options & SO_DEBUG)
2288		tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2289			  &tcp_savetcp, 0);
2290#endif
2291
2292	/*
2293	 * Return any desired output.
2294	 */
2295	if (needoutput || (tp->t_flags & TF_ACKNOW))
2296		(void) tcp_output(tp);
2297	return;
2298
2299dropafterack:
2300	/*
2301	 * Generate an ACK dropping incoming segment if it occupies
2302	 * sequence space, where the ACK reflects our state.
2303	 *
2304	 * We can now skip the test for the RST flag since all
2305	 * paths to this code happen after packets containing
2306	 * RST have been dropped.
2307	 *
2308	 * In the SYN-RECEIVED state, don't send an ACK unless the
2309	 * segment we received passes the SYN-RECEIVED ACK test.
2310	 * If it fails send a RST.  This breaks the loop in the
2311	 * "LAND" DoS attack, and also prevents an ACK storm
2312	 * between two listening ports that have been sent forged
2313	 * SYN segments, each with the source address of the other.
2314	 */
2315	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2316	    (SEQ_GT(tp->snd_una, th->th_ack) ||
2317	     SEQ_GT(th->th_ack, tp->snd_max)) ) {
2318		rstreason = BANDLIM_RST_OPENPORT;
2319		goto dropwithreset;
2320	}
2321#ifdef TCPDEBUG
2322	if (so->so_options & SO_DEBUG)
2323		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2324			  &tcp_savetcp, 0);
2325#endif
2326	m_freem(m);
2327	tp->t_flags |= TF_ACKNOW;
2328	(void) tcp_output(tp);
2329	return;
2330
2331dropwithreset:
2332	/*
2333	 * Generate a RST, dropping incoming segment.
2334	 * Make ACK acceptable to originator of segment.
2335	 * Don't bother to respond if destination was broadcast/multicast.
2336	 */
2337	if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2338		goto drop;
2339#ifdef INET6
2340	if (isipv6) {
2341		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2342		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2343			goto drop;
2344	} else
2345#endif /* INET6 */
2346	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2347	    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2348	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST))
2349		goto drop;
2350	/* IPv6 anycast check is done at tcp6_input() */
2351
2352	/*
2353	 * Perform bandwidth limiting.
2354	 */
2355	if (badport_bandlim(rstreason) < 0)
2356		goto drop;
2357
2358#ifdef TCPDEBUG
2359	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2360		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2361			  &tcp_savetcp, 0);
2362#endif
2363	if (thflags & TH_ACK)
2364		/* mtod() below is safe as long as hdr dropping is delayed */
2365		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2366			    TH_RST);
2367	else {
2368		if (thflags & TH_SYN)
2369			tlen++;
2370		/* mtod() below is safe as long as hdr dropping is delayed */
2371		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2372			    (tcp_seq)0, TH_RST|TH_ACK);
2373	}
2374	/* destroy temporarily created socket */
2375	if (dropsocket)
2376		(void) soabort(so);
2377	return;
2378
2379drop:
2380	/*
2381	 * Drop space held by incoming segment and return.
2382	 */
2383#ifdef TCPDEBUG
2384	if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2385		tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2386			  &tcp_savetcp, 0);
2387#endif
2388	m_freem(m);
2389	/* destroy temporarily created socket */
2390	if (dropsocket)
2391		(void) soabort(so);
2392	return;
2393}
2394
2395static void
2396tcp_dooptions(tp, cp, cnt, th, to)
2397	struct tcpcb *tp;
2398	u_char *cp;
2399	int cnt;
2400	struct tcphdr *th;
2401	struct tcpopt *to;
2402{
2403	u_short mss = 0;
2404	int opt, optlen;
2405
2406	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2407		opt = cp[0];
2408		if (opt == TCPOPT_EOL)
2409			break;
2410		if (opt == TCPOPT_NOP)
2411			optlen = 1;
2412		else {
2413			if (cnt < 2)
2414				break;
2415			optlen = cp[1];
2416			if (optlen < 2 || optlen > cnt)
2417				break;
2418		}
2419		switch (opt) {
2420
2421		default:
2422			continue;
2423
2424		case TCPOPT_MAXSEG:
2425			if (optlen != TCPOLEN_MAXSEG)
2426				continue;
2427			if (!(th->th_flags & TH_SYN))
2428				continue;
2429			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
2430			NTOHS(mss);
2431			break;
2432
2433		case TCPOPT_WINDOW:
2434			if (optlen != TCPOLEN_WINDOW)
2435				continue;
2436			if (!(th->th_flags & TH_SYN))
2437				continue;
2438			tp->t_flags |= TF_RCVD_SCALE;
2439			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2440			break;
2441
2442		case TCPOPT_TIMESTAMP:
2443			if (optlen != TCPOLEN_TIMESTAMP)
2444				continue;
2445			to->to_flag |= TOF_TS;
2446			bcopy((char *)cp + 2,
2447			    (char *)&to->to_tsval, sizeof(to->to_tsval));
2448			NTOHL(to->to_tsval);
2449			bcopy((char *)cp + 6,
2450			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2451			NTOHL(to->to_tsecr);
2452
2453			/*
2454			 * A timestamp received in a SYN makes
2455			 * it ok to send timestamp requests and replies.
2456			 */
2457			if (th->th_flags & TH_SYN) {
2458				tp->t_flags |= TF_RCVD_TSTMP;
2459				tp->ts_recent = to->to_tsval;
2460				tp->ts_recent_age = ticks;
2461			}
2462			break;
2463		case TCPOPT_CC:
2464			if (optlen != TCPOLEN_CC)
2465				continue;
2466			to->to_flag |= TOF_CC;
2467			bcopy((char *)cp + 2,
2468			    (char *)&to->to_cc, sizeof(to->to_cc));
2469			NTOHL(to->to_cc);
2470			/*
2471			 * A CC or CC.new option received in a SYN makes
2472			 * it ok to send CC in subsequent segments.
2473			 */
2474			if (th->th_flags & TH_SYN)
2475				tp->t_flags |= TF_RCVD_CC;
2476			break;
2477		case TCPOPT_CCNEW:
2478			if (optlen != TCPOLEN_CC)
2479				continue;
2480			if (!(th->th_flags & TH_SYN))
2481				continue;
2482			to->to_flag |= TOF_CCNEW;
2483			bcopy((char *)cp + 2,
2484			    (char *)&to->to_cc, sizeof(to->to_cc));
2485			NTOHL(to->to_cc);
2486			/*
2487			 * A CC or CC.new option received in a SYN makes
2488			 * it ok to send CC in subsequent segments.
2489			 */
2490			tp->t_flags |= TF_RCVD_CC;
2491			break;
2492		case TCPOPT_CCECHO:
2493			if (optlen != TCPOLEN_CC)
2494				continue;
2495			if (!(th->th_flags & TH_SYN))
2496				continue;
2497			to->to_flag |= TOF_CCECHO;
2498			bcopy((char *)cp + 2,
2499			    (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2500			NTOHL(to->to_ccecho);
2501			break;
2502		}
2503	}
2504	if (th->th_flags & TH_SYN)
2505		tcp_mss(tp, mss);	/* sets t_maxseg */
2506}
2507
2508/*
2509 * Pull out of band byte out of a segment so
2510 * it doesn't appear in the user's data queue.
2511 * It is still reflected in the segment length for
2512 * sequencing purposes.
2513 */
2514static void
2515tcp_pulloutofband(so, th, m, off)
2516	struct socket *so;
2517	struct tcphdr *th;
2518	register struct mbuf *m;
2519	int off;		/* delayed to be droped hdrlen */
2520{
2521	int cnt = off + th->th_urp - 1;
2522
2523	while (cnt >= 0) {
2524		if (m->m_len > cnt) {
2525			char *cp = mtod(m, caddr_t) + cnt;
2526			struct tcpcb *tp = sototcpcb(so);
2527
2528			tp->t_iobc = *cp;
2529			tp->t_oobflags |= TCPOOB_HAVEDATA;
2530			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2531			m->m_len--;
2532			if (m->m_flags & M_PKTHDR)
2533				m->m_pkthdr.len--;
2534			return;
2535		}
2536		cnt -= m->m_len;
2537		m = m->m_next;
2538		if (m == 0)
2539			break;
2540	}
2541	panic("tcp_pulloutofband");
2542}
2543
2544/*
2545 * Collect new round-trip time estimate
2546 * and update averages and current timeout.
2547 */
2548static void
2549tcp_xmit_timer(tp, rtt)
2550	register struct tcpcb *tp;
2551	int rtt;
2552{
2553	register int delta;
2554
2555	tcpstat.tcps_rttupdated++;
2556	tp->t_rttupdated++;
2557	if (tp->t_srtt != 0) {
2558		/*
2559		 * srtt is stored as fixed point with 5 bits after the
2560		 * binary point (i.e., scaled by 8).  The following magic
2561		 * is equivalent to the smoothing algorithm in rfc793 with
2562		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2563		 * point).  Adjust rtt to origin 0.
2564		 */
2565		delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2566			- (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2567
2568		if ((tp->t_srtt += delta) <= 0)
2569			tp->t_srtt = 1;
2570
2571		/*
2572		 * We accumulate a smoothed rtt variance (actually, a
2573		 * smoothed mean difference), then set the retransmit
2574		 * timer to smoothed rtt + 4 times the smoothed variance.
2575		 * rttvar is stored as fixed point with 4 bits after the
2576		 * binary point (scaled by 16).  The following is
2577		 * equivalent to rfc793 smoothing with an alpha of .75
2578		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2579		 * rfc793's wired-in beta.
2580		 */
2581		if (delta < 0)
2582			delta = -delta;
2583		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2584		if ((tp->t_rttvar += delta) <= 0)
2585			tp->t_rttvar = 1;
2586	} else {
2587		/*
2588		 * No rtt measurement yet - use the unsmoothed rtt.
2589		 * Set the variance to half the rtt (so our first
2590		 * retransmit happens at 3*rtt).
2591		 */
2592		tp->t_srtt = rtt << TCP_RTT_SHIFT;
2593		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2594	}
2595	tp->t_rtttime = 0;
2596	tp->t_rxtshift = 0;
2597
2598	/*
2599	 * the retransmit should happen at rtt + 4 * rttvar.
2600	 * Because of the way we do the smoothing, srtt and rttvar
2601	 * will each average +1/2 tick of bias.  When we compute
2602	 * the retransmit timer, we want 1/2 tick of rounding and
2603	 * 1 extra tick because of +-1/2 tick uncertainty in the
2604	 * firing of the timer.  The bias will give us exactly the
2605	 * 1.5 tick we need.  But, because the bias is
2606	 * statistical, we have to test that we don't drop below
2607	 * the minimum feasible timer (which is 2 ticks).
2608	 */
2609	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2610		      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2611
2612	/*
2613	 * We received an ack for a packet that wasn't retransmitted;
2614	 * it is probably safe to discard any error indications we've
2615	 * received recently.  This isn't quite right, but close enough
2616	 * for now (a route might have failed after we sent a segment,
2617	 * and the return path might not be symmetrical).
2618	 */
2619	tp->t_softerror = 0;
2620}
2621
2622/*
2623 * Determine a reasonable value for maxseg size.
2624 * If the route is known, check route for mtu.
2625 * If none, use an mss that can be handled on the outgoing
2626 * interface without forcing IP to fragment; if bigger than
2627 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2628 * to utilize large mbufs.  If no route is found, route has no mtu,
2629 * or the destination isn't local, use a default, hopefully conservative
2630 * size (usually 512 or the default IP max size, but no more than the mtu
2631 * of the interface), as we can't discover anything about intervening
2632 * gateways or networks.  We also initialize the congestion/slow start
2633 * window to be a single segment if the destination isn't local.
2634 * While looking at the routing entry, we also initialize other path-dependent
2635 * parameters from pre-set or cached values in the routing entry.
2636 *
2637 * Also take into account the space needed for options that we
2638 * send regularly.  Make maxseg shorter by that amount to assure
2639 * that we can send maxseg amount of data even when the options
2640 * are present.  Store the upper limit of the length of options plus
2641 * data in maxopd.
2642 *
2643 * NOTE that this routine is only called when we process an incoming
2644 * segment, for outgoing segments only tcp_mssopt is called.
2645 *
2646 * In case of T/TCP, we call this routine during implicit connection
2647 * setup as well (offer = -1), to initialize maxseg from the cached
2648 * MSS of our peer.
2649 */
2650void
2651tcp_mss(tp, offer)
2652	struct tcpcb *tp;
2653	int offer;
2654{
2655	register struct rtentry *rt;
2656	struct ifnet *ifp;
2657	register int rtt, mss;
2658	u_long bufsize;
2659	struct inpcb *inp;
2660	struct socket *so;
2661	struct rmxp_tao *taop;
2662	int origoffer = offer;
2663#ifdef INET6
2664	int isipv6;
2665	int min_protoh;
2666#endif
2667
2668	inp = tp->t_inpcb;
2669#ifdef INET6
2670	isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2671	min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
2672			    : sizeof (struct tcpiphdr);
2673#else
2674#define min_protoh  (sizeof (struct tcpiphdr))
2675#endif
2676#ifdef INET6
2677	if (isipv6)
2678		rt = tcp_rtlookup6(inp);
2679	else
2680#endif
2681	rt = tcp_rtlookup(inp);
2682	if (rt == NULL) {
2683		tp->t_maxopd = tp->t_maxseg =
2684#ifdef INET6
2685		isipv6 ? tcp_v6mssdflt :
2686#endif /* INET6 */
2687		tcp_mssdflt;
2688		return;
2689	}
2690	ifp = rt->rt_ifp;
2691	so = inp->inp_socket;
2692
2693	taop = rmx_taop(rt->rt_rmx);
2694	/*
2695	 * Offer == -1 means that we didn't receive SYN yet,
2696	 * use cached value in that case;
2697	 */
2698	if (offer == -1)
2699		offer = taop->tao_mssopt;
2700	/*
2701	 * Offer == 0 means that there was no MSS on the SYN segment,
2702	 * in this case we use tcp_mssdflt.
2703	 */
2704	if (offer == 0)
2705		offer =
2706#ifdef INET6
2707			isipv6 ? tcp_v6mssdflt :
2708#endif /* INET6 */
2709			tcp_mssdflt;
2710	else
2711		/*
2712		 * Sanity check: make sure that maxopd will be large
2713		 * enough to allow some data on segments even is the
2714		 * all the option space is used (40bytes).  Otherwise
2715		 * funny things may happen in tcp_output.
2716		 */
2717		offer = max(offer, 64);
2718	taop->tao_mssopt = offer;
2719
2720	/*
2721	 * While we're here, check if there's an initial rtt
2722	 * or rttvar.  Convert from the route-table units
2723	 * to scaled multiples of the slow timeout timer.
2724	 */
2725	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2726		/*
2727		 * XXX the lock bit for RTT indicates that the value
2728		 * is also a minimum value; this is subject to time.
2729		 */
2730		if (rt->rt_rmx.rmx_locks & RTV_RTT)
2731			tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2732		tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2733		tcpstat.tcps_usedrtt++;
2734		if (rt->rt_rmx.rmx_rttvar) {
2735			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2736			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2737			tcpstat.tcps_usedrttvar++;
2738		} else {
2739			/* default variation is +- 1 rtt */
2740			tp->t_rttvar =
2741			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2742		}
2743		TCPT_RANGESET(tp->t_rxtcur,
2744			      ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2745			      tp->t_rttmin, TCPTV_REXMTMAX);
2746	}
2747	/*
2748	 * if there's an mtu associated with the route, use it
2749	 * else, use the link mtu.
2750	 */
2751	if (rt->rt_rmx.rmx_mtu)
2752		mss = rt->rt_rmx.rmx_mtu - min_protoh;
2753	else
2754	{
2755		mss =
2756#ifdef INET6
2757			(isipv6 ? nd_ifinfo[rt->rt_ifp->if_index].linkmtu :
2758#endif
2759			 ifp->if_mtu
2760#ifdef INET6
2761			 )
2762#endif
2763			- min_protoh;
2764#ifdef INET6
2765		if (isipv6) {
2766			if (!in6_localaddr(&inp->in6p_faddr))
2767				mss = min(mss, tcp_v6mssdflt);
2768		} else
2769#endif
2770		if (!in_localaddr(inp->inp_faddr))
2771			mss = min(mss, tcp_mssdflt);
2772	}
2773	mss = min(mss, offer);
2774	/*
2775	 * maxopd stores the maximum length of data AND options
2776	 * in a segment; maxseg is the amount of data in a normal
2777	 * segment.  We need to store this value (maxopd) apart
2778	 * from maxseg, because now every segment carries options
2779	 * and thus we normally have somewhat less data in segments.
2780	 */
2781	tp->t_maxopd = mss;
2782
2783	/*
2784	 * In case of T/TCP, origoffer==-1 indicates, that no segments
2785	 * were received yet.  In this case we just guess, otherwise
2786	 * we do the same as before T/TCP.
2787	 */
2788 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2789	    (origoffer == -1 ||
2790	     (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2791		mss -= TCPOLEN_TSTAMP_APPA;
2792 	if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2793	    (origoffer == -1 ||
2794	     (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2795		mss -= TCPOLEN_CC_APPA;
2796
2797#if	(MCLBYTES & (MCLBYTES - 1)) == 0
2798		if (mss > MCLBYTES)
2799			mss &= ~(MCLBYTES-1);
2800#else
2801		if (mss > MCLBYTES)
2802			mss = mss / MCLBYTES * MCLBYTES;
2803#endif
2804	/*
2805	 * If there's a pipesize, change the socket buffer
2806	 * to that size.  Make the socket buffers an integral
2807	 * number of mss units; if the mss is larger than
2808	 * the socket buffer, decrease the mss.
2809	 */
2810#ifdef RTV_SPIPE
2811	if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2812#endif
2813		bufsize = so->so_snd.sb_hiwat;
2814	if (bufsize < mss)
2815		mss = bufsize;
2816	else {
2817		bufsize = roundup(bufsize, mss);
2818		if (bufsize > sb_max)
2819			bufsize = sb_max;
2820		(void)sbreserve(&so->so_snd, bufsize, so, NULL);
2821	}
2822	tp->t_maxseg = mss;
2823
2824#ifdef RTV_RPIPE
2825	if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2826#endif
2827		bufsize = so->so_rcv.sb_hiwat;
2828	if (bufsize > mss) {
2829		bufsize = roundup(bufsize, mss);
2830		if (bufsize > sb_max)
2831			bufsize = sb_max;
2832		(void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2833	}
2834
2835	/*
2836	 * Set the slow-start flight size depending on whether this
2837	 * is a local network or not.
2838	 */
2839	if (
2840#ifdef INET6
2841	    (isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2842	    (!isipv6 &&
2843#endif
2844	     in_localaddr(inp->inp_faddr)
2845#ifdef INET6
2846	     )
2847#endif
2848	    )
2849		tp->snd_cwnd = mss * ss_fltsz_local;
2850	else
2851		tp->snd_cwnd = mss * ss_fltsz;
2852
2853	if (rt->rt_rmx.rmx_ssthresh) {
2854		/*
2855		 * There's some sort of gateway or interface
2856		 * buffer limit on the path.  Use this to set
2857		 * the slow start threshhold, but set the
2858		 * threshold to no less than 2*mss.
2859		 */
2860		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2861		tcpstat.tcps_usedssthresh++;
2862	}
2863}
2864
2865/*
2866 * Determine the MSS option to send on an outgoing SYN.
2867 */
2868int
2869tcp_mssopt(tp)
2870	struct tcpcb *tp;
2871{
2872	struct rtentry *rt;
2873#ifdef INET6
2874	int isipv6;
2875	int min_protoh;
2876#endif
2877
2878#ifdef INET6
2879	isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2880	min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
2881			    : sizeof (struct tcpiphdr);
2882#else
2883#define min_protoh  (sizeof (struct tcpiphdr))
2884#endif
2885#ifdef INET6
2886	if (isipv6)
2887		rt = tcp_rtlookup6(tp->t_inpcb);
2888	else
2889#endif /* INET6 */
2890	rt = tcp_rtlookup(tp->t_inpcb);
2891	if (rt == NULL)
2892		return
2893#ifdef INET6
2894			isipv6 ? tcp_v6mssdflt :
2895#endif /* INET6 */
2896			tcp_mssdflt;
2897
2898	return rt->rt_ifp->if_mtu - min_protoh;
2899}
2900
2901
2902/*
2903 * Checks for partial ack.  If partial ack arrives, force the retransmission
2904 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2905 * 1.  By setting snd_nxt to ti_ack, this forces retransmission timer to
2906 * be started again.  If the ack advances at least to tp->snd_recover, return 0.
2907 */
2908static int
2909tcp_newreno(tp, th)
2910	struct tcpcb *tp;
2911	struct tcphdr *th;
2912{
2913	if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2914		tcp_seq onxt = tp->snd_nxt;
2915		u_long  ocwnd = tp->snd_cwnd;
2916
2917		callout_stop(tp->tt_rexmt);
2918		tp->t_rtttime = 0;
2919		tp->snd_nxt = th->th_ack;
2920		/*
2921		 * Set snd_cwnd to one segment beyond acknowledged offset
2922		 * (tp->snd_una has not yet been updated when this function
2923		 *  is called)
2924		 */
2925		tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2926		(void) tcp_output(tp);
2927		tp->snd_cwnd = ocwnd;
2928		if (SEQ_GT(onxt, tp->snd_nxt))
2929			tp->snd_nxt = onxt;
2930		/*
2931		 * Partial window deflation.  Relies on fact that tp->snd_una
2932		 * not updated yet.
2933		 */
2934		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2935		return (1);
2936	}
2937	return (0);
2938}
2939