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