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