xref: /freebsd/sys/netinet/tcp_reass.c (revision afe61c15161c324a7af299a9b8457aba5afc92db)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
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.5 (Berkeley) 4/10/94
34  */
35 
36 #ifndef TUBA_INCLUDE
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/errno.h>
45 
46 #include <net/if.h>
47 #include <net/route.h>
48 
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h>
51 #include <netinet/ip.h>
52 #include <netinet/in_pcb.h>
53 #include <netinet/ip_var.h>
54 #include <netinet/tcp.h>
55 #include <netinet/tcp_fsm.h>
56 #include <netinet/tcp_seq.h>
57 #include <netinet/tcp_timer.h>
58 #include <netinet/tcp_var.h>
59 #include <netinet/tcpip.h>
60 #include <netinet/tcp_debug.h>
61 
62 int	tcprexmtthresh = 3;
63 struct	tcpiphdr tcp_saveti;
64 struct	inpcb *tcp_last_inpcb = &tcb;
65 
66 extern u_long sb_max;
67 
68 #endif /* TUBA_INCLUDE */
69 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
70 
71 /* for modulo comparisons of timestamps */
72 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
73 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
74 
75 
76 /*
77  * Insert segment ti into reassembly queue of tcp with
78  * control block tp.  Return TH_FIN if reassembly now includes
79  * a segment with FIN.  The macro form does the common case inline
80  * (segment is the next to be received on an established connection,
81  * and the queue is empty), avoiding linkage into and removal
82  * from the queue and repetition of various conversions.
83  * Set DELACK for segments received in order, but ack immediately
84  * when segments are out of order (so fast retransmit can work).
85  */
86 #define	TCP_REASS(tp, ti, m, so, flags) { \
87 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
88 	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
89 	    (tp)->t_state == TCPS_ESTABLISHED) { \
90 		tp->t_flags |= TF_DELACK; \
91 		(tp)->rcv_nxt += (ti)->ti_len; \
92 		flags = (ti)->ti_flags & TH_FIN; \
93 		tcpstat.tcps_rcvpack++;\
94 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
95 		sbappend(&(so)->so_rcv, (m)); \
96 		sorwakeup(so); \
97 	} else { \
98 		(flags) = tcp_reass((tp), (ti), (m)); \
99 		tp->t_flags |= TF_ACKNOW; \
100 	} \
101 }
102 #ifndef TUBA_INCLUDE
103 
104 int
105 tcp_reass(tp, ti, m)
106 	register struct tcpcb *tp;
107 	register struct tcpiphdr *ti;
108 	struct mbuf *m;
109 {
110 	register struct tcpiphdr *q;
111 	struct socket *so = tp->t_inpcb->inp_socket;
112 	int flags;
113 
114 	/*
115 	 * Call with ti==0 after become established to
116 	 * force pre-ESTABLISHED data up to user socket.
117 	 */
118 	if (ti == 0)
119 		goto present;
120 
121 	/*
122 	 * Find a segment which begins after this one does.
123 	 */
124 	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
125 	    q = (struct tcpiphdr *)q->ti_next)
126 		if (SEQ_GT(q->ti_seq, ti->ti_seq))
127 			break;
128 
129 	/*
130 	 * If there is a preceding segment, it may provide some of
131 	 * our data already.  If so, drop the data from the incoming
132 	 * segment.  If it provides all of our data, drop us.
133 	 */
134 	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
135 		register int i;
136 		q = (struct tcpiphdr *)q->ti_prev;
137 		/* conversion to int (in i) handles seq wraparound */
138 		i = q->ti_seq + q->ti_len - ti->ti_seq;
139 		if (i > 0) {
140 			if (i >= ti->ti_len) {
141 				tcpstat.tcps_rcvduppack++;
142 				tcpstat.tcps_rcvdupbyte += ti->ti_len;
143 				m_freem(m);
144 				return (0);
145 			}
146 			m_adj(m, i);
147 			ti->ti_len -= i;
148 			ti->ti_seq += i;
149 		}
150 		q = (struct tcpiphdr *)(q->ti_next);
151 	}
152 	tcpstat.tcps_rcvoopack++;
153 	tcpstat.tcps_rcvoobyte += ti->ti_len;
154 	REASS_MBUF(ti) = m;		/* XXX */
155 
156 	/*
157 	 * While we overlap succeeding segments trim them or,
158 	 * if they are completely covered, dequeue them.
159 	 */
160 	while (q != (struct tcpiphdr *)tp) {
161 		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
162 		if (i <= 0)
163 			break;
164 		if (i < q->ti_len) {
165 			q->ti_seq += i;
166 			q->ti_len -= i;
167 			m_adj(REASS_MBUF(q), i);
168 			break;
169 		}
170 		q = (struct tcpiphdr *)q->ti_next;
171 		m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
172 		remque(q->ti_prev);
173 		m_freem(m);
174 	}
175 
176 	/*
177 	 * Stick new segment in its place.
178 	 */
179 	insque(ti, q->ti_prev);
180 
181 present:
182 	/*
183 	 * Present data to user, advancing rcv_nxt through
184 	 * completed sequence space.
185 	 */
186 	if (TCPS_HAVERCVDSYN(tp->t_state) == 0)
187 		return (0);
188 	ti = tp->seg_next;
189 	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
190 		return (0);
191 	if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
192 		return (0);
193 	do {
194 		tp->rcv_nxt += ti->ti_len;
195 		flags = ti->ti_flags & TH_FIN;
196 		remque(ti);
197 		m = REASS_MBUF(ti);
198 		ti = (struct tcpiphdr *)ti->ti_next;
199 		if (so->so_state & SS_CANTRCVMORE)
200 			m_freem(m);
201 		else
202 			sbappend(&so->so_rcv, m);
203 	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
204 	sorwakeup(so);
205 	return (flags);
206 }
207 
208 /*
209  * TCP input routine, follows pages 65-76 of the
210  * protocol specification dated September, 1981 very closely.
211  */
212 void
213 tcp_input(m, iphlen)
214 	register struct mbuf *m;
215 	int iphlen;
216 {
217 	register struct tcpiphdr *ti;
218 	register struct inpcb *inp;
219 	caddr_t optp = NULL;
220 	int optlen = 0;
221 	int len, tlen, off;
222 	register struct tcpcb *tp = 0;
223 	register int tiflags;
224 	struct socket *so = 0;
225 	int todrop, acked, ourfinisacked, needoutput = 0;
226 	short ostate = 0;
227 	struct in_addr laddr;
228 	int dropsocket = 0;
229 	int iss = 0;
230 	u_long tiwin, ts_val, ts_ecr;
231 	int ts_present = 0;
232 
233 	tcpstat.tcps_rcvtotal++;
234 	/*
235 	 * Get IP and TCP header together in first mbuf.
236 	 * Note: IP leaves IP header in first mbuf.
237 	 */
238 	ti = mtod(m, struct tcpiphdr *);
239 	if (iphlen > sizeof (struct ip))
240 		ip_stripoptions(m, (struct mbuf *)0);
241 	if (m->m_len < sizeof (struct tcpiphdr)) {
242 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
243 			tcpstat.tcps_rcvshort++;
244 			return;
245 		}
246 		ti = mtod(m, struct tcpiphdr *);
247 	}
248 
249 	/*
250 	 * Checksum extended TCP header and data.
251 	 */
252 	tlen = ((struct ip *)ti)->ip_len;
253 	len = sizeof (struct ip) + tlen;
254 	ti->ti_next = ti->ti_prev = 0;
255 	ti->ti_x1 = 0;
256 	ti->ti_len = (u_short)tlen;
257 	HTONS(ti->ti_len);
258 	if (ti->ti_sum = in_cksum(m, len)) {
259 		tcpstat.tcps_rcvbadsum++;
260 		goto drop;
261 	}
262 #endif /* TUBA_INCLUDE */
263 
264 	/*
265 	 * Check that TCP offset makes sense,
266 	 * pull out TCP options and adjust length.		XXX
267 	 */
268 	off = ti->ti_off << 2;
269 	if (off < sizeof (struct tcphdr) || off > tlen) {
270 		tcpstat.tcps_rcvbadoff++;
271 		goto drop;
272 	}
273 	tlen -= off;
274 	ti->ti_len = tlen;
275 	if (off > sizeof (struct tcphdr)) {
276 		if (m->m_len < sizeof(struct ip) + off) {
277 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
278 				tcpstat.tcps_rcvshort++;
279 				return;
280 			}
281 			ti = mtod(m, struct tcpiphdr *);
282 		}
283 		optlen = off - sizeof (struct tcphdr);
284 		optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
285 		/*
286 		 * Do quick retrieval of timestamp options ("options
287 		 * prediction?").  If timestamp is the only option and it's
288 		 * formatted as recommended in RFC 1323 appendix A, we
289 		 * quickly get the values now and not bother calling
290 		 * tcp_dooptions(), etc.
291 		 */
292 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
293 		     (optlen > TCPOLEN_TSTAMP_APPA &&
294 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
295 		     *(u_long *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
296 		     (ti->ti_flags & TH_SYN) == 0) {
297 			ts_present = 1;
298 			ts_val = ntohl(*(u_long *)(optp + 4));
299 			ts_ecr = ntohl(*(u_long *)(optp + 8));
300 			optp = NULL;	/* we've parsed the options */
301 		}
302 	}
303 	tiflags = ti->ti_flags;
304 
305 	/*
306 	 * Convert TCP protocol specific fields to host format.
307 	 */
308 	NTOHL(ti->ti_seq);
309 	NTOHL(ti->ti_ack);
310 	NTOHS(ti->ti_win);
311 	NTOHS(ti->ti_urp);
312 
313 	/*
314 	 * Locate pcb for segment.
315 	 */
316 findpcb:
317 	inp = tcp_last_inpcb;
318 	if (inp->inp_lport != ti->ti_dport ||
319 	    inp->inp_fport != ti->ti_sport ||
320 	    inp->inp_faddr.s_addr != ti->ti_src.s_addr ||
321 	    inp->inp_laddr.s_addr != ti->ti_dst.s_addr) {
322 		inp = in_pcblookup(&tcb, ti->ti_src, ti->ti_sport,
323 		    ti->ti_dst, ti->ti_dport, INPLOOKUP_WILDCARD);
324 		if (inp)
325 			tcp_last_inpcb = inp;
326 		++tcpstat.tcps_pcbcachemiss;
327 	}
328 
329 	/*
330 	 * If the state is CLOSED (i.e., TCB does not exist) then
331 	 * all data in the incoming segment is discarded.
332 	 * If the TCB exists but is in CLOSED state, it is embryonic,
333 	 * but should either do a listen or a connect soon.
334 	 */
335 	if (inp == 0)
336 		goto dropwithreset;
337 	tp = intotcpcb(inp);
338 	if (tp == 0)
339 		goto dropwithreset;
340 	if (tp->t_state == TCPS_CLOSED)
341 		goto drop;
342 
343 	/* Unscale the window into a 32-bit value. */
344 	if ((tiflags & TH_SYN) == 0)
345 		tiwin = ti->ti_win << tp->snd_scale;
346 	else
347 		tiwin = ti->ti_win;
348 
349 	so = inp->inp_socket;
350 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
351 		if (so->so_options & SO_DEBUG) {
352 			ostate = tp->t_state;
353 			tcp_saveti = *ti;
354 		}
355 		if (so->so_options & SO_ACCEPTCONN) {
356 			so = sonewconn(so, 0);
357 			if (so == 0)
358 				goto drop;
359 			/*
360 			 * This is ugly, but ....
361 			 *
362 			 * Mark socket as temporary until we're
363 			 * committed to keeping it.  The code at
364 			 * ``drop'' and ``dropwithreset'' check the
365 			 * flag dropsocket to see if the temporary
366 			 * socket created here should be discarded.
367 			 * We mark the socket as discardable until
368 			 * we're committed to it below in TCPS_LISTEN.
369 			 */
370 			dropsocket++;
371 			inp = (struct inpcb *)so->so_pcb;
372 			inp->inp_laddr = ti->ti_dst;
373 			inp->inp_lport = ti->ti_dport;
374 #if BSD>=43
375 			inp->inp_options = ip_srcroute();
376 #endif
377 			tp = intotcpcb(inp);
378 			tp->t_state = TCPS_LISTEN;
379 
380 			/* Compute proper scaling value from buffer space
381 			 */
382 			while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
383 			   TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
384 				tp->request_r_scale++;
385 		}
386 	}
387 
388 	/*
389 	 * Segment received on connection.
390 	 * Reset idle time and keep-alive timer.
391 	 */
392 	tp->t_idle = 0;
393 	tp->t_timer[TCPT_KEEP] = tcp_keepidle;
394 
395 	/*
396 	 * Process options if not in LISTEN state,
397 	 * else do it below (after getting remote address).
398 	 */
399 	if (optp && tp->t_state != TCPS_LISTEN)
400 		tcp_dooptions(tp, optp, optlen, ti,
401 			&ts_present, &ts_val, &ts_ecr);
402 
403 	/*
404 	 * Header prediction: check for the two common cases
405 	 * of a uni-directional data xfer.  If the packet has
406 	 * no control flags, is in-sequence, the window didn't
407 	 * change and we're not retransmitting, it's a
408 	 * candidate.  If the length is zero and the ack moved
409 	 * forward, we're the sender side of the xfer.  Just
410 	 * free the data acked & wake any higher level process
411 	 * that was blocked waiting for space.  If the length
412 	 * is non-zero and the ack didn't move, we're the
413 	 * receiver side.  If we're getting packets in-order
414 	 * (the reassembly queue is empty), add the data to
415 	 * the socket buffer and note that we need a delayed ack.
416 	 */
417 	if (tp->t_state == TCPS_ESTABLISHED &&
418 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
419 	    (!ts_present || TSTMP_GEQ(ts_val, tp->ts_recent)) &&
420 	    ti->ti_seq == tp->rcv_nxt &&
421 	    tiwin && tiwin == tp->snd_wnd &&
422 	    tp->snd_nxt == tp->snd_max) {
423 
424 		/*
425 		 * If last ACK falls within this segment's sequence numbers,
426 		 *  record the timestamp.
427 		 */
428 		if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
429 		   SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
430 			tp->ts_recent_age = tcp_now;
431 			tp->ts_recent = ts_val;
432 		}
433 
434 		if (ti->ti_len == 0) {
435 			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
436 			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
437 			    tp->snd_cwnd >= tp->snd_wnd) {
438 				/*
439 				 * this is a pure ack for outstanding data.
440 				 */
441 				++tcpstat.tcps_predack;
442 				if (ts_present)
443 					tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
444 				else if (tp->t_rtt &&
445 					    SEQ_GT(ti->ti_ack, tp->t_rtseq))
446 					tcp_xmit_timer(tp, tp->t_rtt);
447 				acked = ti->ti_ack - tp->snd_una;
448 				tcpstat.tcps_rcvackpack++;
449 				tcpstat.tcps_rcvackbyte += acked;
450 				sbdrop(&so->so_snd, acked);
451 				tp->snd_una = ti->ti_ack;
452 				m_freem(m);
453 
454 				/*
455 				 * If all outstanding data are acked, stop
456 				 * retransmit timer, otherwise restart timer
457 				 * using current (possibly backed-off) value.
458 				 * If process is waiting for space,
459 				 * wakeup/selwakeup/signal.  If data
460 				 * are ready to send, let tcp_output
461 				 * decide between more output or persist.
462 				 */
463 				if (tp->snd_una == tp->snd_max)
464 					tp->t_timer[TCPT_REXMT] = 0;
465 				else if (tp->t_timer[TCPT_PERSIST] == 0)
466 					tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
467 
468 				if (so->so_snd.sb_flags & SB_NOTIFY)
469 					sowwakeup(so);
470 				if (so->so_snd.sb_cc)
471 					(void) tcp_output(tp);
472 				return;
473 			}
474 		} else if (ti->ti_ack == tp->snd_una &&
475 		    tp->seg_next == (struct tcpiphdr *)tp &&
476 		    ti->ti_len <= sbspace(&so->so_rcv)) {
477 			/*
478 			 * this is a pure, in-sequence data packet
479 			 * with nothing on the reassembly queue and
480 			 * we have enough buffer space to take it.
481 			 */
482 			++tcpstat.tcps_preddat;
483 			tp->rcv_nxt += ti->ti_len;
484 			tcpstat.tcps_rcvpack++;
485 			tcpstat.tcps_rcvbyte += ti->ti_len;
486 			/*
487 			 * Drop TCP, IP headers and TCP options then add data
488 			 * to socket buffer.
489 			 */
490 			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
491 			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
492 			sbappend(&so->so_rcv, m);
493 			sorwakeup(so);
494 			tp->t_flags |= TF_DELACK;
495 			return;
496 		}
497 	}
498 
499 	/*
500 	 * Drop TCP, IP headers and TCP options.
501 	 */
502 	m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
503 	m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
504 
505 	/*
506 	 * Calculate amount of space in receive window,
507 	 * and then do TCP input processing.
508 	 * Receive window is amount of space in rcv queue,
509 	 * but not less than advertised window.
510 	 */
511 	{ int win;
512 
513 	win = sbspace(&so->so_rcv);
514 	if (win < 0)
515 		win = 0;
516 	tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
517 	}
518 
519 	switch (tp->t_state) {
520 
521 	/*
522 	 * If the state is LISTEN then ignore segment if it contains an RST.
523 	 * If the segment contains an ACK then it is bad and send a RST.
524 	 * If it does not contain a SYN then it is not interesting; drop it.
525 	 * Don't bother responding if the destination was a broadcast.
526 	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
527 	 * tp->iss, and send a segment:
528 	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
529 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
530 	 * Fill in remote peer address fields if not previously specified.
531 	 * Enter SYN_RECEIVED state, and process any other fields of this
532 	 * segment in this state.
533 	 */
534 	case TCPS_LISTEN: {
535 		struct mbuf *am;
536 		register struct sockaddr_in *sin;
537 
538 		if (tiflags & TH_RST)
539 			goto drop;
540 		if (tiflags & TH_ACK)
541 			goto dropwithreset;
542 		if ((tiflags & TH_SYN) == 0)
543 			goto drop;
544 		/*
545 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
546 		 * in_broadcast() should never return true on a received
547 		 * packet with M_BCAST not set.
548 		 */
549 		if (m->m_flags & (M_BCAST|M_MCAST) ||
550 		    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
551 			goto drop;
552 		am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
553 		if (am == NULL)
554 			goto drop;
555 		am->m_len = sizeof (struct sockaddr_in);
556 		sin = mtod(am, struct sockaddr_in *);
557 		sin->sin_family = AF_INET;
558 		sin->sin_len = sizeof(*sin);
559 		sin->sin_addr = ti->ti_src;
560 		sin->sin_port = ti->ti_sport;
561 		bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
562 		laddr = inp->inp_laddr;
563 		if (inp->inp_laddr.s_addr == INADDR_ANY)
564 			inp->inp_laddr = ti->ti_dst;
565 		if (in_pcbconnect(inp, am)) {
566 			inp->inp_laddr = laddr;
567 			(void) m_free(am);
568 			goto drop;
569 		}
570 		(void) m_free(am);
571 		tp->t_template = tcp_template(tp);
572 		if (tp->t_template == 0) {
573 			tp = tcp_drop(tp, ENOBUFS);
574 			dropsocket = 0;		/* socket is already gone */
575 			goto drop;
576 		}
577 		if (optp)
578 			tcp_dooptions(tp, optp, optlen, ti,
579 				&ts_present, &ts_val, &ts_ecr);
580 		if (iss)
581 			tp->iss = iss;
582 		else
583 			tp->iss = tcp_iss;
584 		tcp_iss += TCP_ISSINCR/2;
585 		tp->irs = ti->ti_seq;
586 		tcp_sendseqinit(tp);
587 		tcp_rcvseqinit(tp);
588 		tp->t_flags |= TF_ACKNOW;
589 		tp->t_state = TCPS_SYN_RECEIVED;
590 		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
591 		dropsocket = 0;		/* committed to socket */
592 		tcpstat.tcps_accepts++;
593 		goto trimthenstep6;
594 		}
595 
596 	/*
597 	 * If the state is SYN_SENT:
598 	 *	if seg contains an ACK, but not for our SYN, drop the input.
599 	 *	if seg contains a RST, then drop the connection.
600 	 *	if seg does not contain SYN, then drop it.
601 	 * Otherwise this is an acceptable SYN segment
602 	 *	initialize tp->rcv_nxt and tp->irs
603 	 *	if seg contains ack then advance tp->snd_una
604 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
605 	 *	arrange for segment to be acked (eventually)
606 	 *	continue processing rest of data/controls, beginning with URG
607 	 */
608 	case TCPS_SYN_SENT:
609 		if ((tiflags & TH_ACK) &&
610 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
611 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
612 			goto dropwithreset;
613 		if (tiflags & TH_RST) {
614 			if (tiflags & TH_ACK)
615 				tp = tcp_drop(tp, ECONNREFUSED);
616 			goto drop;
617 		}
618 		if ((tiflags & TH_SYN) == 0)
619 			goto drop;
620 		if (tiflags & TH_ACK) {
621 			tp->snd_una = ti->ti_ack;
622 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
623 				tp->snd_nxt = tp->snd_una;
624 		}
625 		tp->t_timer[TCPT_REXMT] = 0;
626 		tp->irs = ti->ti_seq;
627 		tcp_rcvseqinit(tp);
628 		tp->t_flags |= TF_ACKNOW;
629 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
630 			tcpstat.tcps_connects++;
631 			soisconnected(so);
632 			tp->t_state = TCPS_ESTABLISHED;
633 			/* Do window scaling on this connection? */
634 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
635 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
636 				tp->snd_scale = tp->requested_s_scale;
637 				tp->rcv_scale = tp->request_r_scale;
638 			}
639 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
640 				(struct mbuf *)0);
641 			/*
642 			 * if we didn't have to retransmit the SYN,
643 			 * use its rtt as our initial srtt & rtt var.
644 			 */
645 			if (tp->t_rtt)
646 				tcp_xmit_timer(tp, tp->t_rtt);
647 		} else
648 			tp->t_state = TCPS_SYN_RECEIVED;
649 
650 trimthenstep6:
651 		/*
652 		 * Advance ti->ti_seq to correspond to first data byte.
653 		 * If data, trim to stay within window,
654 		 * dropping FIN if necessary.
655 		 */
656 		ti->ti_seq++;
657 		if (ti->ti_len > tp->rcv_wnd) {
658 			todrop = ti->ti_len - tp->rcv_wnd;
659 			m_adj(m, -todrop);
660 			ti->ti_len = tp->rcv_wnd;
661 			tiflags &= ~TH_FIN;
662 			tcpstat.tcps_rcvpackafterwin++;
663 			tcpstat.tcps_rcvbyteafterwin += todrop;
664 		}
665 		tp->snd_wl1 = ti->ti_seq - 1;
666 		tp->rcv_up = ti->ti_seq;
667 		goto step6;
668 	}
669 
670 	/*
671 	 * States other than LISTEN or SYN_SENT.
672 	 * First check timestamp, if present.
673 	 * Then check that at least some bytes of segment are within
674 	 * receive window.  If segment begins before rcv_nxt,
675 	 * drop leading data (and SYN); if nothing left, just ack.
676 	 *
677 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
678 	 * and it's less than ts_recent, drop it.
679 	 */
680 	if (ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
681 	    TSTMP_LT(ts_val, tp->ts_recent)) {
682 
683 		/* Check to see if ts_recent is over 24 days old.  */
684 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
685 			/*
686 			 * Invalidate ts_recent.  If this segment updates
687 			 * ts_recent, the age will be reset later and ts_recent
688 			 * will get a valid value.  If it does not, setting
689 			 * ts_recent to zero will at least satisfy the
690 			 * requirement that zero be placed in the timestamp
691 			 * echo reply when ts_recent isn't valid.  The
692 			 * age isn't reset until we get a valid ts_recent
693 			 * because we don't want out-of-order segments to be
694 			 * dropped when ts_recent is old.
695 			 */
696 			tp->ts_recent = 0;
697 		} else {
698 			tcpstat.tcps_rcvduppack++;
699 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
700 			tcpstat.tcps_pawsdrop++;
701 			goto dropafterack;
702 		}
703 	}
704 
705 	todrop = tp->rcv_nxt - ti->ti_seq;
706 	if (todrop > 0) {
707 		if (tiflags & TH_SYN) {
708 			tiflags &= ~TH_SYN;
709 			ti->ti_seq++;
710 			if (ti->ti_urp > 1)
711 				ti->ti_urp--;
712 			else
713 				tiflags &= ~TH_URG;
714 			todrop--;
715 		}
716 		if (todrop >= ti->ti_len) {
717 			tcpstat.tcps_rcvduppack++;
718 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
719 			/*
720 			 * If segment is just one to the left of the window,
721 			 * check two special cases:
722 			 * 1. Don't toss RST in response to 4.2-style keepalive.
723 			 * 2. If the only thing to drop is a FIN, we can drop
724 			 *    it, but check the ACK or we will get into FIN
725 			 *    wars if our FINs crossed (both CLOSING).
726 			 * In either case, send ACK to resynchronize,
727 			 * but keep on processing for RST or ACK.
728 			 */
729 			if ((tiflags & TH_FIN && todrop == ti->ti_len + 1)
730 #ifdef TCP_COMPAT_42
731 			  || (tiflags & TH_RST && ti->ti_seq == tp->rcv_nxt - 1)
732 #endif
733 			   ) {
734 				todrop = ti->ti_len;
735 				tiflags &= ~TH_FIN;
736 				tp->t_flags |= TF_ACKNOW;
737 			} else {
738 				/*
739 				 * Handle the case when a bound socket connects
740 				 * to itself. Allow packets with a SYN and
741 				 * an ACK to continue with the processing.
742 				 */
743 				if (todrop != 0 || (tiflags & TH_ACK) == 0)
744 					goto dropafterack;
745 			}
746 		} else {
747 			tcpstat.tcps_rcvpartduppack++;
748 			tcpstat.tcps_rcvpartdupbyte += todrop;
749 		}
750 		m_adj(m, todrop);
751 		ti->ti_seq += todrop;
752 		ti->ti_len -= todrop;
753 		if (ti->ti_urp > todrop)
754 			ti->ti_urp -= todrop;
755 		else {
756 			tiflags &= ~TH_URG;
757 			ti->ti_urp = 0;
758 		}
759 	}
760 
761 	/*
762 	 * If new data are received on a connection after the
763 	 * user processes are gone, then RST the other end.
764 	 */
765 	if ((so->so_state & SS_NOFDREF) &&
766 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
767 		tp = tcp_close(tp);
768 		tcpstat.tcps_rcvafterclose++;
769 		goto dropwithreset;
770 	}
771 
772 	/*
773 	 * If segment ends after window, drop trailing data
774 	 * (and PUSH and FIN); if nothing left, just ACK.
775 	 */
776 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
777 	if (todrop > 0) {
778 		tcpstat.tcps_rcvpackafterwin++;
779 		if (todrop >= ti->ti_len) {
780 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
781 			/*
782 			 * If a new connection request is received
783 			 * while in TIME_WAIT, drop the old connection
784 			 * and start over if the sequence numbers
785 			 * are above the previous ones.
786 			 */
787 			if (tiflags & TH_SYN &&
788 			    tp->t_state == TCPS_TIME_WAIT &&
789 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
790 				iss = tp->rcv_nxt + TCP_ISSINCR;
791 				tp = tcp_close(tp);
792 				goto findpcb;
793 			}
794 			/*
795 			 * If window is closed can only take segments at
796 			 * window edge, and have to drop data and PUSH from
797 			 * incoming segments.  Continue processing, but
798 			 * remember to ack.  Otherwise, drop segment
799 			 * and ack.
800 			 */
801 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
802 				tp->t_flags |= TF_ACKNOW;
803 				tcpstat.tcps_rcvwinprobe++;
804 			} else
805 				goto dropafterack;
806 		} else
807 			tcpstat.tcps_rcvbyteafterwin += todrop;
808 		m_adj(m, -todrop);
809 		ti->ti_len -= todrop;
810 		tiflags &= ~(TH_PUSH|TH_FIN);
811 	}
812 
813 	/*
814 	 * If last ACK falls within this segment's sequence numbers,
815 	 * record its timestamp.
816 	 */
817 	if (ts_present && SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
818 	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
819 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
820 		tp->ts_recent_age = tcp_now;
821 		tp->ts_recent = ts_val;
822 	}
823 
824 	/*
825 	 * If the RST bit is set examine the state:
826 	 *    SYN_RECEIVED STATE:
827 	 *	If passive open, return to LISTEN state.
828 	 *	If active open, inform user that connection was refused.
829 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
830 	 *	Inform user that connection was reset, and close tcb.
831 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
832 	 *	Close the tcb.
833 	 */
834 	if (tiflags&TH_RST) switch (tp->t_state) {
835 
836 	case TCPS_SYN_RECEIVED:
837 		so->so_error = ECONNREFUSED;
838 		goto close;
839 
840 	case TCPS_ESTABLISHED:
841 	case TCPS_FIN_WAIT_1:
842 	case TCPS_FIN_WAIT_2:
843 	case TCPS_CLOSE_WAIT:
844 		so->so_error = ECONNRESET;
845 	close:
846 		tp->t_state = TCPS_CLOSED;
847 		tcpstat.tcps_drops++;
848 		tp = tcp_close(tp);
849 		goto drop;
850 
851 	case TCPS_CLOSING:
852 	case TCPS_LAST_ACK:
853 	case TCPS_TIME_WAIT:
854 		tp = tcp_close(tp);
855 		goto drop;
856 	}
857 
858 	/*
859 	 * If a SYN is in the window, then this is an
860 	 * error and we send an RST and drop the connection.
861 	 */
862 	if (tiflags & TH_SYN) {
863 		tp = tcp_drop(tp, ECONNRESET);
864 		goto dropwithreset;
865 	}
866 
867 	/*
868 	 * If the ACK bit is off we drop the segment and return.
869 	 */
870 	if ((tiflags & TH_ACK) == 0)
871 		goto drop;
872 
873 	/*
874 	 * Ack processing.
875 	 */
876 	switch (tp->t_state) {
877 
878 	/*
879 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
880 	 * ESTABLISHED state and continue processing, otherwise
881 	 * send an RST.
882 	 */
883 	case TCPS_SYN_RECEIVED:
884 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
885 		    SEQ_GT(ti->ti_ack, tp->snd_max))
886 			goto dropwithreset;
887 		tcpstat.tcps_connects++;
888 		soisconnected(so);
889 		tp->t_state = TCPS_ESTABLISHED;
890 		/* Do window scaling? */
891 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
892 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
893 			tp->snd_scale = tp->requested_s_scale;
894 			tp->rcv_scale = tp->request_r_scale;
895 		}
896 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
897 		tp->snd_wl1 = ti->ti_seq - 1;
898 		/* fall into ... */
899 
900 	/*
901 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
902 	 * ACKs.  If the ack is in the range
903 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
904 	 * then advance tp->snd_una to ti->ti_ack and drop
905 	 * data from the retransmission queue.  If this ACK reflects
906 	 * more up to date window information we update our window information.
907 	 */
908 	case TCPS_ESTABLISHED:
909 	case TCPS_FIN_WAIT_1:
910 	case TCPS_FIN_WAIT_2:
911 	case TCPS_CLOSE_WAIT:
912 	case TCPS_CLOSING:
913 	case TCPS_LAST_ACK:
914 	case TCPS_TIME_WAIT:
915 
916 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
917 			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
918 				tcpstat.tcps_rcvdupack++;
919 				/*
920 				 * If we have outstanding data (other than
921 				 * a window probe), this is a completely
922 				 * duplicate ack (ie, window info didn't
923 				 * change), the ack is the biggest we've
924 				 * seen and we've seen exactly our rexmt
925 				 * threshhold of them, assume a packet
926 				 * has been dropped and retransmit it.
927 				 * Kludge snd_nxt & the congestion
928 				 * window so we send only this one
929 				 * packet.
930 				 *
931 				 * We know we're losing at the current
932 				 * window size so do congestion avoidance
933 				 * (set ssthresh to half the current window
934 				 * and pull our congestion window back to
935 				 * the new ssthresh).
936 				 *
937 				 * Dup acks mean that packets have left the
938 				 * network (they're now cached at the receiver)
939 				 * so bump cwnd by the amount in the receiver
940 				 * to keep a constant cwnd packets in the
941 				 * network.
942 				 */
943 				if (tp->t_timer[TCPT_REXMT] == 0 ||
944 				    ti->ti_ack != tp->snd_una)
945 					tp->t_dupacks = 0;
946 				else if (++tp->t_dupacks == tcprexmtthresh) {
947 					tcp_seq onxt = tp->snd_nxt;
948 					u_int win =
949 					    min(tp->snd_wnd, tp->snd_cwnd) / 2 /
950 						tp->t_maxseg;
951 
952 					if (win < 2)
953 						win = 2;
954 					tp->snd_ssthresh = win * tp->t_maxseg;
955 					tp->t_timer[TCPT_REXMT] = 0;
956 					tp->t_rtt = 0;
957 					tp->snd_nxt = ti->ti_ack;
958 					tp->snd_cwnd = tp->t_maxseg;
959 					(void) tcp_output(tp);
960 					tp->snd_cwnd = tp->snd_ssthresh +
961 					       tp->t_maxseg * tp->t_dupacks;
962 					if (SEQ_GT(onxt, tp->snd_nxt))
963 						tp->snd_nxt = onxt;
964 					goto drop;
965 				} else if (tp->t_dupacks > tcprexmtthresh) {
966 					tp->snd_cwnd += tp->t_maxseg;
967 					(void) tcp_output(tp);
968 					goto drop;
969 				}
970 			} else
971 				tp->t_dupacks = 0;
972 			break;
973 		}
974 		/*
975 		 * If the congestion window was inflated to account
976 		 * for the other side's cached packets, retract it.
977 		 */
978 		if (tp->t_dupacks > tcprexmtthresh &&
979 		    tp->snd_cwnd > tp->snd_ssthresh)
980 			tp->snd_cwnd = tp->snd_ssthresh;
981 		tp->t_dupacks = 0;
982 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
983 			tcpstat.tcps_rcvacktoomuch++;
984 			goto dropafterack;
985 		}
986 		acked = ti->ti_ack - tp->snd_una;
987 		tcpstat.tcps_rcvackpack++;
988 		tcpstat.tcps_rcvackbyte += acked;
989 
990 		/*
991 		 * If we have a timestamp reply, update smoothed
992 		 * round trip time.  If no timestamp is present but
993 		 * transmit timer is running and timed sequence
994 		 * number was acked, update smoothed round trip time.
995 		 * Since we now have an rtt measurement, cancel the
996 		 * timer backoff (cf., Phil Karn's retransmit alg.).
997 		 * Recompute the initial retransmit timer.
998 		 */
999 		if (ts_present)
1000 			tcp_xmit_timer(tp, tcp_now-ts_ecr+1);
1001 		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1002 			tcp_xmit_timer(tp,tp->t_rtt);
1003 
1004 		/*
1005 		 * If all outstanding data is acked, stop retransmit
1006 		 * timer and remember to restart (more output or persist).
1007 		 * If there is more data to be acked, restart retransmit
1008 		 * timer, using current (possibly backed-off) value.
1009 		 */
1010 		if (ti->ti_ack == tp->snd_max) {
1011 			tp->t_timer[TCPT_REXMT] = 0;
1012 			needoutput = 1;
1013 		} else if (tp->t_timer[TCPT_PERSIST] == 0)
1014 			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1015 		/*
1016 		 * When new data is acked, open the congestion window.
1017 		 * If the window gives us less than ssthresh packets
1018 		 * in flight, open exponentially (maxseg per packet).
1019 		 * Otherwise open linearly: maxseg per window
1020 		 * (maxseg^2 / cwnd per packet), plus a constant
1021 		 * fraction of a packet (maxseg/8) to help larger windows
1022 		 * open quickly enough.
1023 		 */
1024 		{
1025 		register u_int cw = tp->snd_cwnd;
1026 		register u_int incr = tp->t_maxseg;
1027 
1028 		if (cw > tp->snd_ssthresh)
1029 			incr = incr * incr / cw + incr / 8;
1030 		tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1031 		}
1032 		if (acked > so->so_snd.sb_cc) {
1033 			tp->snd_wnd -= so->so_snd.sb_cc;
1034 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1035 			ourfinisacked = 1;
1036 		} else {
1037 			sbdrop(&so->so_snd, acked);
1038 			tp->snd_wnd -= acked;
1039 			ourfinisacked = 0;
1040 		}
1041 		if (so->so_snd.sb_flags & SB_NOTIFY)
1042 			sowwakeup(so);
1043 		tp->snd_una = ti->ti_ack;
1044 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1045 			tp->snd_nxt = tp->snd_una;
1046 
1047 		switch (tp->t_state) {
1048 
1049 		/*
1050 		 * In FIN_WAIT_1 STATE in addition to the processing
1051 		 * for the ESTABLISHED state if our FIN is now acknowledged
1052 		 * then enter FIN_WAIT_2.
1053 		 */
1054 		case TCPS_FIN_WAIT_1:
1055 			if (ourfinisacked) {
1056 				/*
1057 				 * If we can't receive any more
1058 				 * data, then closing user can proceed.
1059 				 * Starting the timer is contrary to the
1060 				 * specification, but if we don't get a FIN
1061 				 * we'll hang forever.
1062 				 */
1063 				if (so->so_state & SS_CANTRCVMORE) {
1064 					soisdisconnected(so);
1065 					tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1066 				}
1067 				tp->t_state = TCPS_FIN_WAIT_2;
1068 			}
1069 			break;
1070 
1071 	 	/*
1072 		 * In CLOSING STATE in addition to the processing for
1073 		 * the ESTABLISHED state if the ACK acknowledges our FIN
1074 		 * then enter the TIME-WAIT state, otherwise ignore
1075 		 * the segment.
1076 		 */
1077 		case TCPS_CLOSING:
1078 			if (ourfinisacked) {
1079 				tp->t_state = TCPS_TIME_WAIT;
1080 				tcp_canceltimers(tp);
1081 				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1082 				soisdisconnected(so);
1083 			}
1084 			break;
1085 
1086 		/*
1087 		 * In LAST_ACK, we may still be waiting for data to drain
1088 		 * and/or to be acked, as well as for the ack of our FIN.
1089 		 * If our FIN is now acknowledged, delete the TCB,
1090 		 * enter the closed state and return.
1091 		 */
1092 		case TCPS_LAST_ACK:
1093 			if (ourfinisacked) {
1094 				tp = tcp_close(tp);
1095 				goto drop;
1096 			}
1097 			break;
1098 
1099 		/*
1100 		 * In TIME_WAIT state the only thing that should arrive
1101 		 * is a retransmission of the remote FIN.  Acknowledge
1102 		 * it and restart the finack timer.
1103 		 */
1104 		case TCPS_TIME_WAIT:
1105 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1106 			goto dropafterack;
1107 		}
1108 	}
1109 
1110 step6:
1111 	/*
1112 	 * Update window information.
1113 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1114 	 */
1115 	if ((tiflags & TH_ACK) &&
1116 	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
1117 	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1118 	     tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
1119 		/* keep track of pure window updates */
1120 		if (ti->ti_len == 0 &&
1121 		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1122 			tcpstat.tcps_rcvwinupd++;
1123 		tp->snd_wnd = tiwin;
1124 		tp->snd_wl1 = ti->ti_seq;
1125 		tp->snd_wl2 = ti->ti_ack;
1126 		if (tp->snd_wnd > tp->max_sndwnd)
1127 			tp->max_sndwnd = tp->snd_wnd;
1128 		needoutput = 1;
1129 	}
1130 
1131 	/*
1132 	 * Process segments with URG.
1133 	 */
1134 	if ((tiflags & TH_URG) && ti->ti_urp &&
1135 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1136 		/*
1137 		 * This is a kludge, but if we receive and accept
1138 		 * random urgent pointers, we'll crash in
1139 		 * soreceive.  It's hard to imagine someone
1140 		 * actually wanting to send this much urgent data.
1141 		 */
1142 		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1143 			ti->ti_urp = 0;			/* XXX */
1144 			tiflags &= ~TH_URG;		/* XXX */
1145 			goto dodata;			/* XXX */
1146 		}
1147 		/*
1148 		 * If this segment advances the known urgent pointer,
1149 		 * then mark the data stream.  This should not happen
1150 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1151 		 * a FIN has been received from the remote side.
1152 		 * In these states we ignore the URG.
1153 		 *
1154 		 * According to RFC961 (Assigned Protocols),
1155 		 * the urgent pointer points to the last octet
1156 		 * of urgent data.  We continue, however,
1157 		 * to consider it to indicate the first octet
1158 		 * of data past the urgent section as the original
1159 		 * spec states (in one of two places).
1160 		 */
1161 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1162 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
1163 			so->so_oobmark = so->so_rcv.sb_cc +
1164 			    (tp->rcv_up - tp->rcv_nxt) - 1;
1165 			if (so->so_oobmark == 0)
1166 				so->so_state |= SS_RCVATMARK;
1167 			sohasoutofband(so);
1168 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1169 		}
1170 		/*
1171 		 * Remove out of band data so doesn't get presented to user.
1172 		 * This can happen independent of advancing the URG pointer,
1173 		 * but if two URG's are pending at once, some out-of-band
1174 		 * data may creep in... ick.
1175 		 */
1176 		if (ti->ti_urp <= (u_long)ti->ti_len
1177 #ifdef SO_OOBINLINE
1178 		     && (so->so_options & SO_OOBINLINE) == 0
1179 #endif
1180 		     )
1181 			tcp_pulloutofband(so, ti, m);
1182 	} else
1183 		/*
1184 		 * If no out of band data is expected,
1185 		 * pull receive urgent pointer along
1186 		 * with the receive window.
1187 		 */
1188 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1189 			tp->rcv_up = tp->rcv_nxt;
1190 dodata:							/* XXX */
1191 
1192 	/*
1193 	 * Process the segment text, merging it into the TCP sequencing queue,
1194 	 * and arranging for acknowledgment of receipt if necessary.
1195 	 * This process logically involves adjusting tp->rcv_wnd as data
1196 	 * is presented to the user (this happens in tcp_usrreq.c,
1197 	 * case PRU_RCVD).  If a FIN has already been received on this
1198 	 * connection then we just ignore the text.
1199 	 */
1200 	if ((ti->ti_len || (tiflags&TH_FIN)) &&
1201 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1202 		TCP_REASS(tp, ti, m, so, tiflags);
1203 		/*
1204 		 * Note the amount of data that peer has sent into
1205 		 * our window, in order to estimate the sender's
1206 		 * buffer size.
1207 		 */
1208 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1209 	} else {
1210 		m_freem(m);
1211 		tiflags &= ~TH_FIN;
1212 	}
1213 
1214 	/*
1215 	 * If FIN is received ACK the FIN and let the user know
1216 	 * that the connection is closing.
1217 	 */
1218 	if (tiflags & TH_FIN) {
1219 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1220 			socantrcvmore(so);
1221 			tp->t_flags |= TF_ACKNOW;
1222 			tp->rcv_nxt++;
1223 		}
1224 		switch (tp->t_state) {
1225 
1226 	 	/*
1227 		 * In SYN_RECEIVED and ESTABLISHED STATES
1228 		 * enter the CLOSE_WAIT state.
1229 		 */
1230 		case TCPS_SYN_RECEIVED:
1231 		case TCPS_ESTABLISHED:
1232 			tp->t_state = TCPS_CLOSE_WAIT;
1233 			break;
1234 
1235 	 	/*
1236 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1237 		 * enter the CLOSING state.
1238 		 */
1239 		case TCPS_FIN_WAIT_1:
1240 			tp->t_state = TCPS_CLOSING;
1241 			break;
1242 
1243 	 	/*
1244 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1245 		 * starting the time-wait timer, turning off the other
1246 		 * standard timers.
1247 		 */
1248 		case TCPS_FIN_WAIT_2:
1249 			tp->t_state = TCPS_TIME_WAIT;
1250 			tcp_canceltimers(tp);
1251 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1252 			soisdisconnected(so);
1253 			break;
1254 
1255 		/*
1256 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1257 		 */
1258 		case TCPS_TIME_WAIT:
1259 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1260 			break;
1261 		}
1262 	}
1263 	if (so->so_options & SO_DEBUG)
1264 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1265 
1266 	/*
1267 	 * Return any desired output.
1268 	 */
1269 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1270 		(void) tcp_output(tp);
1271 	return;
1272 
1273 dropafterack:
1274 	/*
1275 	 * Generate an ACK dropping incoming segment if it occupies
1276 	 * sequence space, where the ACK reflects our state.
1277 	 */
1278 	if (tiflags & TH_RST)
1279 		goto drop;
1280 	m_freem(m);
1281 	tp->t_flags |= TF_ACKNOW;
1282 	(void) tcp_output(tp);
1283 	return;
1284 
1285 dropwithreset:
1286 	/*
1287 	 * Generate a RST, dropping incoming segment.
1288 	 * Make ACK acceptable to originator of segment.
1289 	 * Don't bother to respond if destination was broadcast/multicast.
1290 	 */
1291 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1292 	    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1293 		goto drop;
1294 	if (tiflags & TH_ACK)
1295 		tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1296 	else {
1297 		if (tiflags & TH_SYN)
1298 			ti->ti_len++;
1299 		tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1300 		    TH_RST|TH_ACK);
1301 	}
1302 	/* destroy temporarily created socket */
1303 	if (dropsocket)
1304 		(void) soabort(so);
1305 	return;
1306 
1307 drop:
1308 	/*
1309 	 * Drop space held by incoming segment and return.
1310 	 */
1311 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1312 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1313 	m_freem(m);
1314 	/* destroy temporarily created socket */
1315 	if (dropsocket)
1316 		(void) soabort(so);
1317 	return;
1318 #ifndef TUBA_INCLUDE
1319 }
1320 
1321 void
1322 tcp_dooptions(tp, cp, cnt, ti, ts_present, ts_val, ts_ecr)
1323 	struct tcpcb *tp;
1324 	u_char *cp;
1325 	int cnt;
1326 	struct tcpiphdr *ti;
1327 	int *ts_present;
1328 	u_long *ts_val, *ts_ecr;
1329 {
1330 	u_short mss;
1331 	int opt, optlen;
1332 
1333 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1334 		opt = cp[0];
1335 		if (opt == TCPOPT_EOL)
1336 			break;
1337 		if (opt == TCPOPT_NOP)
1338 			optlen = 1;
1339 		else {
1340 			optlen = cp[1];
1341 			if (optlen <= 0)
1342 				break;
1343 		}
1344 		switch (opt) {
1345 
1346 		default:
1347 			continue;
1348 
1349 		case TCPOPT_MAXSEG:
1350 			if (optlen != TCPOLEN_MAXSEG)
1351 				continue;
1352 			if (!(ti->ti_flags & TH_SYN))
1353 				continue;
1354 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1355 			NTOHS(mss);
1356 			(void) tcp_mss(tp, mss);	/* sets t_maxseg */
1357 			break;
1358 
1359 		case TCPOPT_WINDOW:
1360 			if (optlen != TCPOLEN_WINDOW)
1361 				continue;
1362 			if (!(ti->ti_flags & TH_SYN))
1363 				continue;
1364 			tp->t_flags |= TF_RCVD_SCALE;
1365 			tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1366 			break;
1367 
1368 		case TCPOPT_TIMESTAMP:
1369 			if (optlen != TCPOLEN_TIMESTAMP)
1370 				continue;
1371 			*ts_present = 1;
1372 			bcopy((char *)cp + 2, (char *) ts_val, sizeof(*ts_val));
1373 			NTOHL(*ts_val);
1374 			bcopy((char *)cp + 6, (char *) ts_ecr, sizeof(*ts_ecr));
1375 			NTOHL(*ts_ecr);
1376 
1377 			/*
1378 			 * A timestamp received in a SYN makes
1379 			 * it ok to send timestamp requests and replies.
1380 			 */
1381 			if (ti->ti_flags & TH_SYN) {
1382 				tp->t_flags |= TF_RCVD_TSTMP;
1383 				tp->ts_recent = *ts_val;
1384 				tp->ts_recent_age = tcp_now;
1385 			}
1386 			break;
1387 		}
1388 	}
1389 }
1390 
1391 /*
1392  * Pull out of band byte out of a segment so
1393  * it doesn't appear in the user's data queue.
1394  * It is still reflected in the segment length for
1395  * sequencing purposes.
1396  */
1397 void
1398 tcp_pulloutofband(so, ti, m)
1399 	struct socket *so;
1400 	struct tcpiphdr *ti;
1401 	register struct mbuf *m;
1402 {
1403 	int cnt = ti->ti_urp - 1;
1404 
1405 	while (cnt >= 0) {
1406 		if (m->m_len > cnt) {
1407 			char *cp = mtod(m, caddr_t) + cnt;
1408 			struct tcpcb *tp = sototcpcb(so);
1409 
1410 			tp->t_iobc = *cp;
1411 			tp->t_oobflags |= TCPOOB_HAVEDATA;
1412 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1413 			m->m_len--;
1414 			return;
1415 		}
1416 		cnt -= m->m_len;
1417 		m = m->m_next;
1418 		if (m == 0)
1419 			break;
1420 	}
1421 	panic("tcp_pulloutofband");
1422 }
1423 
1424 /*
1425  * Collect new round-trip time estimate
1426  * and update averages and current timeout.
1427  */
1428 void
1429 tcp_xmit_timer(tp, rtt)
1430 	register struct tcpcb *tp;
1431 	short rtt;
1432 {
1433 	register short delta;
1434 
1435 	tcpstat.tcps_rttupdated++;
1436 	if (tp->t_srtt != 0) {
1437 		/*
1438 		 * srtt is stored as fixed point with 3 bits after the
1439 		 * binary point (i.e., scaled by 8).  The following magic
1440 		 * is equivalent to the smoothing algorithm in rfc793 with
1441 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1442 		 * point).  Adjust rtt to origin 0.
1443 		 */
1444 		delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1445 		if ((tp->t_srtt += delta) <= 0)
1446 			tp->t_srtt = 1;
1447 		/*
1448 		 * We accumulate a smoothed rtt variance (actually, a
1449 		 * smoothed mean difference), then set the retransmit
1450 		 * timer to smoothed rtt + 4 times the smoothed variance.
1451 		 * rttvar is stored as fixed point with 2 bits after the
1452 		 * binary point (scaled by 4).  The following is
1453 		 * equivalent to rfc793 smoothing with an alpha of .75
1454 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1455 		 * rfc793's wired-in beta.
1456 		 */
1457 		if (delta < 0)
1458 			delta = -delta;
1459 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1460 		if ((tp->t_rttvar += delta) <= 0)
1461 			tp->t_rttvar = 1;
1462 	} else {
1463 		/*
1464 		 * No rtt measurement yet - use the unsmoothed rtt.
1465 		 * Set the variance to half the rtt (so our first
1466 		 * retransmit happens at 3*rtt).
1467 		 */
1468 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
1469 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1470 	}
1471 	tp->t_rtt = 0;
1472 	tp->t_rxtshift = 0;
1473 
1474 	/*
1475 	 * the retransmit should happen at rtt + 4 * rttvar.
1476 	 * Because of the way we do the smoothing, srtt and rttvar
1477 	 * will each average +1/2 tick of bias.  When we compute
1478 	 * the retransmit timer, we want 1/2 tick of rounding and
1479 	 * 1 extra tick because of +-1/2 tick uncertainty in the
1480 	 * firing of the timer.  The bias will give us exactly the
1481 	 * 1.5 tick we need.  But, because the bias is
1482 	 * statistical, we have to test that we don't drop below
1483 	 * the minimum feasible timer (which is 2 ticks).
1484 	 */
1485 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1486 	    tp->t_rttmin, TCPTV_REXMTMAX);
1487 
1488 	/*
1489 	 * We received an ack for a packet that wasn't retransmitted;
1490 	 * it is probably safe to discard any error indications we've
1491 	 * received recently.  This isn't quite right, but close enough
1492 	 * for now (a route might have failed after we sent a segment,
1493 	 * and the return path might not be symmetrical).
1494 	 */
1495 	tp->t_softerror = 0;
1496 }
1497 
1498 /*
1499  * Determine a reasonable value for maxseg size.
1500  * If the route is known, check route for mtu.
1501  * If none, use an mss that can be handled on the outgoing
1502  * interface without forcing IP to fragment; if bigger than
1503  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1504  * to utilize large mbufs.  If no route is found, route has no mtu,
1505  * or the destination isn't local, use a default, hopefully conservative
1506  * size (usually 512 or the default IP max size, but no more than the mtu
1507  * of the interface), as we can't discover anything about intervening
1508  * gateways or networks.  We also initialize the congestion/slow start
1509  * window to be a single segment if the destination isn't local.
1510  * While looking at the routing entry, we also initialize other path-dependent
1511  * parameters from pre-set or cached values in the routing entry.
1512  */
1513 int
1514 tcp_mss(tp, offer)
1515 	register struct tcpcb *tp;
1516 	u_int offer;
1517 {
1518 	struct route *ro;
1519 	register struct rtentry *rt;
1520 	struct ifnet *ifp;
1521 	register int rtt, mss;
1522 	u_long bufsize;
1523 	struct inpcb *inp;
1524 	struct socket *so;
1525 	extern int tcp_mssdflt;
1526 
1527 	inp = tp->t_inpcb;
1528 	ro = &inp->inp_route;
1529 
1530 	if ((rt = ro->ro_rt) == (struct rtentry *)0) {
1531 		/* No route yet, so try to acquire one */
1532 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1533 			ro->ro_dst.sa_family = AF_INET;
1534 			ro->ro_dst.sa_len = sizeof(ro->ro_dst);
1535 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1536 				inp->inp_faddr;
1537 			rtalloc(ro);
1538 		}
1539 		if ((rt = ro->ro_rt) == (struct rtentry *)0)
1540 			return (tcp_mssdflt);
1541 	}
1542 	ifp = rt->rt_ifp;
1543 	so = inp->inp_socket;
1544 
1545 #ifdef RTV_MTU	/* if route characteristics exist ... */
1546 	/*
1547 	 * While we're here, check if there's an initial rtt
1548 	 * or rttvar.  Convert from the route-table units
1549 	 * to scaled multiples of the slow timeout timer.
1550 	 */
1551 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1552 		/*
1553 		 * XXX the lock bit for MTU indicates that the value
1554 		 * is also a minimum value; this is subject to time.
1555 		 */
1556 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1557 			tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
1558 		tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
1559 		if (rt->rt_rmx.rmx_rttvar)
1560 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1561 			    (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
1562 		else
1563 			/* default variation is +- 1 rtt */
1564 			tp->t_rttvar =
1565 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1566 		TCPT_RANGESET(tp->t_rxtcur,
1567 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
1568 		    tp->t_rttmin, TCPTV_REXMTMAX);
1569 	}
1570 	/*
1571 	 * if there's an mtu associated with the route, use it
1572 	 */
1573 	if (rt->rt_rmx.rmx_mtu)
1574 		mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
1575 	else
1576 #endif /* RTV_MTU */
1577 	{
1578 		mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1579 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1580 		if (mss > MCLBYTES)
1581 			mss &= ~(MCLBYTES-1);
1582 #else
1583 		if (mss > MCLBYTES)
1584 			mss = mss / MCLBYTES * MCLBYTES;
1585 #endif
1586 		if (!in_localaddr(inp->inp_faddr))
1587 			mss = min(mss, tcp_mssdflt);
1588 	}
1589 	/*
1590 	 * The current mss, t_maxseg, is initialized to the default value.
1591 	 * If we compute a smaller value, reduce the current mss.
1592 	 * If we compute a larger value, return it for use in sending
1593 	 * a max seg size option, but don't store it for use
1594 	 * unless we received an offer at least that large from peer.
1595 	 * However, do not accept offers under 32 bytes.
1596 	 */
1597 	if (offer)
1598 		mss = min(mss, offer);
1599 	mss = max(mss, 32);		/* sanity */
1600 	if (mss < tp->t_maxseg || offer != 0) {
1601 		/*
1602 		 * If there's a pipesize, change the socket buffer
1603 		 * to that size.  Make the socket buffers an integral
1604 		 * number of mss units; if the mss is larger than
1605 		 * the socket buffer, decrease the mss.
1606 		 */
1607 #ifdef RTV_SPIPE
1608 		if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
1609 #endif
1610 			bufsize = so->so_snd.sb_hiwat;
1611 		if (bufsize < mss)
1612 			mss = bufsize;
1613 		else {
1614 			bufsize = roundup(bufsize, mss);
1615 			if (bufsize > sb_max)
1616 				bufsize = sb_max;
1617 			(void)sbreserve(&so->so_snd, bufsize);
1618 		}
1619 		tp->t_maxseg = mss;
1620 
1621 #ifdef RTV_RPIPE
1622 		if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
1623 #endif
1624 			bufsize = so->so_rcv.sb_hiwat;
1625 		if (bufsize > mss) {
1626 			bufsize = roundup(bufsize, mss);
1627 			if (bufsize > sb_max)
1628 				bufsize = sb_max;
1629 			(void)sbreserve(&so->so_rcv, bufsize);
1630 		}
1631 	}
1632 	tp->snd_cwnd = mss;
1633 
1634 #ifdef RTV_SSTHRESH
1635 	if (rt->rt_rmx.rmx_ssthresh) {
1636 		/*
1637 		 * There's some sort of gateway or interface
1638 		 * buffer limit on the path.  Use this to set
1639 		 * the slow start threshhold, but set the
1640 		 * threshold to no less than 2*mss.
1641 		 */
1642 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1643 	}
1644 #endif /* RTV_MTU */
1645 	return (mss);
1646 }
1647 #endif /* TUBA_INCLUDE */
1648