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