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