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