xref: /csrg-svn/sys/netinet/tcp_input.c (revision 31749)
1 /*
2  * Copyright (c) 1982, 1986 Regents of the University of California.
3  * All rights reserved.  The Berkeley software License Agreement
4  * specifies the terms and conditions for redistribution.
5  *
6  *	@(#)tcp_input.c	7.9 (Berkeley) 07/02/87
7  */
8 
9 #include "param.h"
10 #include "systm.h"
11 #include "mbuf.h"
12 #include "protosw.h"
13 #include "socket.h"
14 #include "socketvar.h"
15 #include "errno.h"
16 
17 #include "../net/if.h"
18 #include "../net/route.h"
19 
20 #include "in.h"
21 #include "in_pcb.h"
22 #include "in_systm.h"
23 #include "ip.h"
24 #include "ip_var.h"
25 #include "tcp.h"
26 #include "tcp_fsm.h"
27 #include "tcp_seq.h"
28 #include "tcp_timer.h"
29 #include "tcp_var.h"
30 #include "tcpip.h"
31 #include "tcp_debug.h"
32 
33 int	tcpprintfs = 0;
34 int	tcpcksum = 1;
35 struct	tcpiphdr tcp_saveti;
36 extern	tcpnodelack;
37 
38 struct	tcpcb *tcp_newtcpcb();
39 
40 /*
41  * Insert segment ti into reassembly queue of tcp with
42  * control block tp.  Return TH_FIN if reassembly now includes
43  * a segment with FIN.  The macro form does the common case inline
44  * (segment is the next to be received on an established connection,
45  * and the queue is empty), avoiding linkage into and removal
46  * from the queue and repetition of various conversions.
47  */
48 #define	TCP_REASS(tp, ti, m, so, flags) { \
49 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
50 	    (tp)->seg_next == (struct tcpiphdr *)(tp) && \
51 	    (tp)->t_state == TCPS_ESTABLISHED) { \
52 		(tp)->rcv_nxt += (ti)->ti_len; \
53 		flags = (ti)->ti_flags & TH_FIN; \
54 		tcpstat.tcps_rcvpack++;\
55 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
56 		sbappend(&(so)->so_rcv, (m)); \
57 		sorwakeup(so); \
58 	} else \
59 		(flags) = tcp_reass((tp), (ti)); \
60 }
61 
62 tcp_reass(tp, ti)
63 	register struct tcpcb *tp;
64 	register struct tcpiphdr *ti;
65 {
66 	register struct tcpiphdr *q;
67 	struct socket *so = tp->t_inpcb->inp_socket;
68 	struct mbuf *m;
69 	int flags;
70 
71 	/*
72 	 * Call with ti==0 after become established to
73 	 * force pre-ESTABLISHED data up to user socket.
74 	 */
75 	if (ti == 0)
76 		goto present;
77 
78 	/*
79 	 * Find a segment which begins after this one does.
80 	 */
81 	for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
82 	    q = (struct tcpiphdr *)q->ti_next)
83 		if (SEQ_GT(q->ti_seq, ti->ti_seq))
84 			break;
85 
86 	/*
87 	 * If there is a preceding segment, it may provide some of
88 	 * our data already.  If so, drop the data from the incoming
89 	 * segment.  If it provides all of our data, drop us.
90 	 */
91 	if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
92 		register int i;
93 		q = (struct tcpiphdr *)q->ti_prev;
94 		/* conversion to int (in i) handles seq wraparound */
95 		i = q->ti_seq + q->ti_len - ti->ti_seq;
96 		if (i > 0) {
97 			if (i >= ti->ti_len) {
98 				tcpstat.tcps_rcvduppack++;
99 				tcpstat.tcps_rcvdupbyte += ti->ti_len;
100 				goto drop;
101 			}
102 			m_adj(dtom(ti), i);
103 			ti->ti_len -= i;
104 			ti->ti_seq += i;
105 		}
106 		q = (struct tcpiphdr *)(q->ti_next);
107 	}
108 	tcpstat.tcps_rcvoopack++;
109 	tcpstat.tcps_rcvoobyte += ti->ti_len;
110 
111 	/*
112 	 * While we overlap succeeding segments trim them or,
113 	 * if they are completely covered, dequeue them.
114 	 */
115 	while (q != (struct tcpiphdr *)tp) {
116 		register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
117 		if (i <= 0)
118 			break;
119 		if (i < q->ti_len) {
120 			q->ti_seq += i;
121 			q->ti_len -= i;
122 			m_adj(dtom(q), i);
123 			break;
124 		}
125 		q = (struct tcpiphdr *)q->ti_next;
126 		m = dtom(q->ti_prev);
127 		remque(q->ti_prev);
128 		m_freem(m);
129 	}
130 
131 	/*
132 	 * Stick new segment in its place.
133 	 */
134 	insque(ti, q->ti_prev);
135 
136 present:
137 	/*
138 	 * Present data to user, advancing rcv_nxt through
139 	 * completed sequence space.
140 	 */
141 	if (TCPS_HAVERCVDSYN(tp->t_state) == 0)
142 		return (0);
143 	ti = tp->seg_next;
144 	if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
145 		return (0);
146 	if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
147 		return (0);
148 	do {
149 		tp->rcv_nxt += ti->ti_len;
150 		flags = ti->ti_flags & TH_FIN;
151 		remque(ti);
152 		m = dtom(ti);
153 		ti = (struct tcpiphdr *)ti->ti_next;
154 		if (so->so_state & SS_CANTRCVMORE)
155 			m_freem(m);
156 		else
157 			sbappend(&so->so_rcv, m);
158 	} while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
159 	sorwakeup(so);
160 	return (flags);
161 drop:
162 	m_freem(dtom(ti));
163 	return (0);
164 }
165 
166 /*
167  * TCP input routine, follows pages 65-76 of the
168  * protocol specification dated September, 1981 very closely.
169  */
170 tcp_input(m0)
171 	struct mbuf *m0;
172 {
173 	register struct tcpiphdr *ti;
174 	struct inpcb *inp;
175 	register struct mbuf *m;
176 	struct mbuf *om = 0;
177 	int len, tlen, off;
178 	register struct tcpcb *tp = 0;
179 	register int tiflags;
180 	struct socket *so;
181 	int todrop, acked, ourfinisacked, needoutput = 0;
182 	short ostate;
183 	struct in_addr laddr;
184 	int dropsocket = 0;
185 	int iss = 0;
186 
187 	tcpstat.tcps_rcvtotal++;
188 	/*
189 	 * Get IP and TCP header together in first mbuf.
190 	 * Note: IP leaves IP header in first mbuf.
191 	 */
192 	m = m0;
193 	ti = mtod(m, struct tcpiphdr *);
194 	if (((struct ip *)ti)->ip_hl > (sizeof (struct ip) >> 2))
195 		ip_stripoptions((struct ip *)ti, (struct mbuf *)0);
196 	if (m->m_off > MMAXOFF || m->m_len < sizeof (struct tcpiphdr)) {
197 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
198 			tcpstat.tcps_rcvshort++;
199 			return;
200 		}
201 		ti = mtod(m, struct tcpiphdr *);
202 	}
203 
204 	/*
205 	 * Checksum extended TCP header and data.
206 	 */
207 	tlen = ((struct ip *)ti)->ip_len;
208 	len = sizeof (struct ip) + tlen;
209 	if (tcpcksum) {
210 		ti->ti_next = ti->ti_prev = 0;
211 		ti->ti_x1 = 0;
212 		ti->ti_len = (u_short)tlen;
213 		ti->ti_len = htons((u_short)ti->ti_len);
214 		if (ti->ti_sum = in_cksum(m, len)) {
215 			if (tcpprintfs)
216 				printf("tcp sum: src %x\n", ti->ti_src);
217 			tcpstat.tcps_rcvbadsum++;
218 			goto drop;
219 		}
220 	}
221 
222 	/*
223 	 * Check that TCP offset makes sense,
224 	 * pull out TCP options and adjust length.
225 	 */
226 	off = ti->ti_off << 2;
227 	if (off < sizeof (struct tcphdr) || off > tlen) {
228 		if (tcpprintfs)
229 			printf("tcp off: src %x off %d\n", ti->ti_src, off);
230 		tcpstat.tcps_rcvbadoff++;
231 		goto drop;
232 	}
233 	tlen -= off;
234 	ti->ti_len = tlen;
235 	if (off > sizeof (struct tcphdr)) {
236 		if (m->m_len < sizeof(struct ip) + off) {
237 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
238 				tcpstat.tcps_rcvshort++;
239 				return;
240 			}
241 			ti = mtod(m, struct tcpiphdr *);
242 		}
243 		om = m_get(M_DONTWAIT, MT_DATA);
244 		if (om == 0)
245 			goto drop;
246 		om->m_len = off - sizeof (struct tcphdr);
247 		{ caddr_t op = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
248 		  bcopy(op, mtod(om, caddr_t), (unsigned)om->m_len);
249 		  m->m_len -= om->m_len;
250 		  bcopy(op+om->m_len, op,
251 		   (unsigned)(m->m_len-sizeof (struct tcpiphdr)));
252 		}
253 	}
254 	tiflags = ti->ti_flags;
255 
256 	/*
257 	 * Drop TCP and IP headers; TCP options were dropped above.
258 	 */
259 	m->m_off += sizeof(struct tcpiphdr);
260 	m->m_len -= sizeof(struct tcpiphdr);
261 
262 	/*
263 	 * Convert TCP protocol specific fields to host format.
264 	 */
265 	ti->ti_seq = ntohl(ti->ti_seq);
266 	ti->ti_ack = ntohl(ti->ti_ack);
267 	ti->ti_win = ntohs(ti->ti_win);
268 	ti->ti_urp = ntohs(ti->ti_urp);
269 
270 	/*
271 	 * Locate pcb for segment.
272 	 */
273 findpcb:
274 	inp = in_pcblookup
275 		(&tcb, ti->ti_src, ti->ti_sport, ti->ti_dst, ti->ti_dport,
276 		INPLOOKUP_WILDCARD);
277 
278 	/*
279 	 * If the state is CLOSED (i.e., TCB does not exist) then
280 	 * all data in the incoming segment is discarded.
281 	 */
282 	if (inp == 0)
283 		goto dropwithreset;
284 	tp = intotcpcb(inp);
285 	if (tp == 0)
286 		goto dropwithreset;
287 	so = inp->inp_socket;
288 	if (so->so_options & SO_DEBUG) {
289 		ostate = tp->t_state;
290 		tcp_saveti = *ti;
291 	}
292 	if (so->so_options & SO_ACCEPTCONN) {
293 		so = sonewconn(so);
294 		if (so == 0)
295 			goto drop;
296 		/*
297 		 * This is ugly, but ....
298 		 *
299 		 * Mark socket as temporary until we're
300 		 * committed to keeping it.  The code at
301 		 * ``drop'' and ``dropwithreset'' check the
302 		 * flag dropsocket to see if the temporary
303 		 * socket created here should be discarded.
304 		 * We mark the socket as discardable until
305 		 * we're committed to it below in TCPS_LISTEN.
306 		 */
307 		dropsocket++;
308 		inp = (struct inpcb *)so->so_pcb;
309 		inp->inp_laddr = ti->ti_dst;
310 		inp->inp_lport = ti->ti_dport;
311 		inp->inp_options = ip_srcroute();
312 		tp = intotcpcb(inp);
313 		tp->t_state = TCPS_LISTEN;
314 	}
315 
316 	/*
317 	 * Segment received on connection.
318 	 * Reset idle time and keep-alive timer.
319 	 */
320 	tp->t_idle = 0;
321 	tp->t_timer[TCPT_KEEP] = TCPTV_KEEP;
322 
323 	/*
324 	 * Process options if not in LISTEN state,
325 	 * else do it below (after getting remote address).
326 	 */
327 	if (om && tp->t_state != TCPS_LISTEN) {
328 		tcp_dooptions(tp, om, ti);
329 		om = 0;
330 	}
331 
332 	/*
333 	 * Calculate amount of space in receive window,
334 	 * and then do TCP input processing.
335 	 * Receive window is amount of space in rcv queue,
336 	 * but not less than advertised window.
337 	 */
338 	{ int win;
339 
340 	win = sbspace(&so->so_rcv);
341 	if (win < 0)
342 		win = 0;
343 	tp->rcv_wnd = MAX(win, (int)(tp->rcv_adv - tp->rcv_nxt));
344 	}
345 
346 	switch (tp->t_state) {
347 
348 	/*
349 	 * If the state is LISTEN then ignore segment if it contains an RST.
350 	 * If the segment contains an ACK then it is bad and send a RST.
351 	 * If it does not contain a SYN then it is not interesting; drop it.
352 	 * Don't bother responding if the destination was a broadcast.
353 	 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
354 	 * tp->iss, and send a segment:
355 	 *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
356 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
357 	 * Fill in remote peer address fields if not previously specified.
358 	 * Enter SYN_RECEIVED state, and process any other fields of this
359 	 * segment in this state.
360 	 */
361 	case TCPS_LISTEN: {
362 		struct mbuf *am;
363 		register struct sockaddr_in *sin;
364 
365 		if (tiflags & TH_RST)
366 			goto drop;
367 		if (tiflags & TH_ACK)
368 			goto dropwithreset;
369 		if ((tiflags & TH_SYN) == 0)
370 			goto drop;
371 		if (in_broadcast(ti->ti_dst))
372 			goto drop;
373 		am = m_get(M_DONTWAIT, MT_SONAME);
374 		if (am == NULL)
375 			goto drop;
376 		am->m_len = sizeof (struct sockaddr_in);
377 		sin = mtod(am, struct sockaddr_in *);
378 		sin->sin_family = AF_INET;
379 		sin->sin_addr = ti->ti_src;
380 		sin->sin_port = ti->ti_sport;
381 		laddr = inp->inp_laddr;
382 		if (inp->inp_laddr.s_addr == INADDR_ANY)
383 			inp->inp_laddr = ti->ti_dst;
384 		if (in_pcbconnect(inp, am)) {
385 			inp->inp_laddr = laddr;
386 			(void) m_free(am);
387 			goto drop;
388 		}
389 		(void) m_free(am);
390 		tp->t_template = tcp_template(tp);
391 		if (tp->t_template == 0) {
392 			tp = tcp_drop(tp, ENOBUFS);
393 			dropsocket = 0;		/* socket is already gone */
394 			goto drop;
395 		}
396 		if (om) {
397 			tcp_dooptions(tp, om, ti);
398 			om = 0;
399 		}
400 		if (iss)
401 			tp->iss = iss;
402 		else
403 			tp->iss = tcp_iss;
404 		tcp_iss += TCP_ISSINCR/2;
405 		tp->irs = ti->ti_seq;
406 		tcp_sendseqinit(tp);
407 		tcp_rcvseqinit(tp);
408 		tp->t_flags |= TF_ACKNOW;
409 		tp->t_state = TCPS_SYN_RECEIVED;
410 		tp->t_timer[TCPT_KEEP] = TCPTV_KEEP;
411 		dropsocket = 0;		/* committed to socket */
412 		tcpstat.tcps_accepts++;
413 		goto trimthenstep6;
414 		}
415 
416 	/*
417 	 * If the state is SYN_SENT:
418 	 *	if seg contains an ACK, but not for our SYN, drop the input.
419 	 *	if seg contains a RST, then drop the connection.
420 	 *	if seg does not contain SYN, then drop it.
421 	 * Otherwise this is an acceptable SYN segment
422 	 *	initialize tp->rcv_nxt and tp->irs
423 	 *	if seg contains ack then advance tp->snd_una
424 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
425 	 *	arrange for segment to be acked (eventually)
426 	 *	continue processing rest of data/controls, beginning with URG
427 	 */
428 	case TCPS_SYN_SENT:
429 		if ((tiflags & TH_ACK) &&
430 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
431 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
432 			goto dropwithreset;
433 		if (tiflags & TH_RST) {
434 			if (tiflags & TH_ACK)
435 				tp = tcp_drop(tp, ECONNREFUSED);
436 			goto drop;
437 		}
438 		if ((tiflags & TH_SYN) == 0)
439 			goto drop;
440 		if (tiflags & TH_ACK) {
441 			tp->snd_una = ti->ti_ack;
442 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
443 				tp->snd_nxt = tp->snd_una;
444 		}
445 		tp->t_timer[TCPT_REXMT] = 0;
446 		tp->irs = ti->ti_seq;
447 		tcp_rcvseqinit(tp);
448 		tp->t_flags |= TF_ACKNOW;
449 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
450 			tcpstat.tcps_connects++;
451 			soisconnected(so);
452 			tp->t_state = TCPS_ESTABLISHED;
453 			tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
454 			(void) tcp_reass(tp, (struct tcpiphdr *)0);
455 		} else
456 			tp->t_state = TCPS_SYN_RECEIVED;
457 
458 trimthenstep6:
459 		/*
460 		 * Advance ti->ti_seq to correspond to first data byte.
461 		 * If data, trim to stay within window,
462 		 * dropping FIN if necessary.
463 		 */
464 		ti->ti_seq++;
465 		if (ti->ti_len > tp->rcv_wnd) {
466 			todrop = ti->ti_len - tp->rcv_wnd;
467 			m_adj(m, -todrop);
468 			ti->ti_len = tp->rcv_wnd;
469 			tiflags &= ~TH_FIN;
470 			tcpstat.tcps_rcvpackafterwin++;
471 			tcpstat.tcps_rcvbyteafterwin += todrop;
472 		}
473 		tp->snd_wl1 = ti->ti_seq - 1;
474 		tp->rcv_up = ti->ti_seq;
475 		goto step6;
476 	}
477 
478 	/*
479 	 * States other than LISTEN or SYN_SENT.
480 	 * First check that at least some bytes of segment are within
481 	 * receive window.  If segment begins before rcv_nxt,
482 	 * drop leading data (and SYN); if nothing left, just ack.
483 	 */
484 	todrop = tp->rcv_nxt - ti->ti_seq;
485 	if (todrop > 0) {
486 		if (tiflags & TH_SYN) {
487 			tiflags &= ~TH_SYN;
488 			ti->ti_seq++;
489 			if (ti->ti_urp > 1)
490 				ti->ti_urp--;
491 			else
492 				tiflags &= ~TH_URG;
493 			todrop--;
494 		}
495 		if (todrop > ti->ti_len ||
496 		    todrop == ti->ti_len && (tiflags&TH_FIN) == 0) {
497 #ifdef TCP_COMPAT_42
498 			/*
499 			 * Don't toss RST in response to 4.2-style keepalive.
500 			 */
501 			if (ti->ti_seq == tp->rcv_nxt - 1 && tiflags & TH_RST)
502 				goto do_rst;
503 #endif
504 			tcpstat.tcps_rcvduppack++;
505 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
506 			goto dropafterack;
507 		}
508 		tcpstat.tcps_rcvpartduppack++;
509 		tcpstat.tcps_rcvpartdupbyte += todrop;
510 		m_adj(m, todrop);
511 		ti->ti_seq += todrop;
512 		ti->ti_len -= todrop;
513 		if (ti->ti_urp > todrop)
514 			ti->ti_urp -= todrop;
515 		else {
516 			tiflags &= ~TH_URG;
517 			ti->ti_urp = 0;
518 		}
519 	}
520 
521 	if (tp->rcv_wnd == 0) {
522 		/*
523 		 * If window is closed can only take segments at
524 		 * window edge, and have to drop data and PUSH from
525 		 * incoming segments.
526 		 *
527 		 * If new data is received on a connection after the
528 		 * user processes are gone, then RST the other end.
529 		 */
530 		if ((so->so_state & SS_NOFDREF) &&
531 		    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
532 			tp = tcp_close(tp);
533 			tcpstat.tcps_rcvafterclose++;
534 			goto dropwithreset;
535 		}
536 		if (tp->rcv_nxt != ti->ti_seq) {
537 			tcpstat.tcps_rcvpackafterwin++;
538 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
539 			goto dropafterack;
540 		}
541 		if (ti->ti_len > 0) {
542 			if (ti->ti_len == 1)
543 				tcpstat.tcps_rcvwinprobe++;
544 			else {
545 				tcpstat.tcps_rcvpackafterwin++;
546 				tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
547 			}
548 			m_adj(m, ti->ti_len);
549 			ti->ti_len = 0;
550 			tiflags &= ~(TH_PUSH|TH_FIN);
551 		}
552 	} else {
553 		/*
554 		 * If segment ends after window, drop trailing data
555 		 * (and PUSH and FIN); if nothing left, just ACK.
556 		 */
557 		todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
558 		if (todrop > 0) {
559 			if (todrop >= ti->ti_len) {
560 				/*
561 				 * If a new connection request is received
562 				 * while in TIME_WAIT, drop the old connection
563 				 * and start over if the sequence numbers
564 				 * are above the previous ones.
565 				 */
566 				if (tiflags & TH_SYN &&
567 				    tp->t_state == TCPS_TIME_WAIT &&
568 				    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
569 					iss = tp->rcv_nxt + TCP_ISSINCR;
570 					(void) tcp_close(tp);
571 					goto findpcb;
572 				}
573 				if (todrop == 1)
574 					tcpstat.tcps_rcvwinprobe++;
575 				else {
576 					tcpstat.tcps_rcvpackafterwin++;
577 					tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
578 				}
579 				goto dropafterack;
580 			}
581 			tcpstat.tcps_rcvpackafterwin++;
582 			tcpstat.tcps_rcvbyteafterwin += todrop;
583 			m_adj(m, -todrop);
584 			ti->ti_len -= todrop;
585 			tiflags &= ~(TH_PUSH|TH_FIN);
586 		}
587 	}
588 
589 #ifdef TCP_COMPAT_42
590 do_rst:
591 #endif
592 	/*
593 	 * If the RST bit is set examine the state:
594 	 *    SYN_RECEIVED STATE:
595 	 *	If passive open, return to LISTEN state.
596 	 *	If active open, inform user that connection was refused.
597 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
598 	 *	Inform user that connection was reset, and close tcb.
599 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
600 	 *	Close the tcb.
601 	 */
602 	if (tiflags&TH_RST) switch (tp->t_state) {
603 
604 	case TCPS_SYN_RECEIVED:
605 		tp = tcp_drop(tp, ECONNREFUSED);
606 		goto drop;
607 
608 	case TCPS_ESTABLISHED:
609 	case TCPS_FIN_WAIT_1:
610 	case TCPS_FIN_WAIT_2:
611 	case TCPS_CLOSE_WAIT:
612 		tp = tcp_drop(tp, ECONNRESET);
613 		goto drop;
614 
615 	case TCPS_CLOSING:
616 	case TCPS_LAST_ACK:
617 	case TCPS_TIME_WAIT:
618 		tp = tcp_close(tp);
619 		goto drop;
620 	}
621 
622 	/*
623 	 * If a SYN is in the window, then this is an
624 	 * error and we send an RST and drop the connection.
625 	 */
626 	if (tiflags & TH_SYN) {
627 		tp = tcp_drop(tp, ECONNRESET);
628 		goto dropwithreset;
629 	}
630 
631 	/*
632 	 * If the ACK bit is off we drop the segment and return.
633 	 */
634 	if ((tiflags & TH_ACK) == 0)
635 		goto drop;
636 
637 	/*
638 	 * Ack processing.
639 	 */
640 	switch (tp->t_state) {
641 
642 	/*
643 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
644 	 * ESTABLISHED state and continue processing, otherwise
645 	 * send an RST.
646 	 */
647 	case TCPS_SYN_RECEIVED:
648 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
649 		    SEQ_GT(ti->ti_ack, tp->snd_max))
650 			goto dropwithreset;
651 		tcpstat.tcps_connects++;
652 		soisconnected(so);
653 		tp->t_state = TCPS_ESTABLISHED;
654 		tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
655 		(void) tcp_reass(tp, (struct tcpiphdr *)0);
656 		tp->snd_wl1 = ti->ti_seq - 1;
657 		/* fall into ... */
658 
659 	/*
660 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
661 	 * ACKs.  If the ack is in the range
662 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
663 	 * then advance tp->snd_una to ti->ti_ack and drop
664 	 * data from the retransmission queue.  If this ACK reflects
665 	 * more up to date window information we update our window information.
666 	 */
667 	case TCPS_ESTABLISHED:
668 	case TCPS_FIN_WAIT_1:
669 	case TCPS_FIN_WAIT_2:
670 	case TCPS_CLOSE_WAIT:
671 	case TCPS_CLOSING:
672 	case TCPS_LAST_ACK:
673 	case TCPS_TIME_WAIT:
674 
675 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
676 			if (ti->ti_len == 0)
677 				tcpstat.tcps_rcvdupack++;
678 			break;
679 		}
680 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
681 			tcpstat.tcps_rcvacktoomuch++;
682 			goto dropafterack;
683 		}
684 		acked = ti->ti_ack - tp->snd_una;
685 		tcpstat.tcps_rcvackpack++;
686 		tcpstat.tcps_rcvackbyte += acked;
687 
688 		/*
689 		 * If transmit timer is running and timed sequence
690 		 * number was acked, update smoothed round trip time.
691 		 */
692 		if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq)) {
693 			tcpstat.tcps_rttupdated++;
694 			if (tp->t_srtt != 0) {
695 				register short delta;
696 
697 				/*
698 				 * srtt is stored as fixed point with 3 bits
699 				 * after the binary point (i.e., scaled by 8).
700 				 * The following magic is equivalent
701 				 * to the smoothing algorithm in rfc793
702 				 * with an alpha of .875
703 				 * (srtt = rtt/8 + srtt*7/8 in fixed point).
704 				 */
705 				delta = tp->t_rtt - (tp->t_srtt >> 3);
706 				if ((tp->t_srtt += delta) <= 0)
707 					tp->t_srtt = 1;
708 				/*
709 				 * We accumulate a smoothed rtt variance,
710 				 * then set the retransmit timer to smoothed
711 				 * rtt + 2 times the smoothed variance.
712 				 * rttvar is strored as fixed point
713 				 * with 2 bits after the binary point
714 				 * (scaled by 4).  The following is equivalent
715 				 * to rfc793 smoothing with an alpha of .75
716 				 * (rttvar = rttvar*3/4 + |delta| / 4).
717 				 * This replaces rfc793's wired-in beta.
718 				 */
719 				if (delta < 0)
720 					delta = -delta;
721 				delta -= (tp->t_rttvar >> 2);
722 				if ((tp->t_rttvar += delta) <= 0)
723 					tp->t_rttvar = 1;
724 			} else {
725 				/*
726 				 * No rtt measurement yet - use the
727 				 * unsmoothed rtt.  Set the variance
728 				 * to half the rtt (so our first
729 				 * retransmit happens at 2*rtt)
730 				 */
731 				tp->t_srtt = tp->t_rtt << 3;
732 				tp->t_rttvar = tp->t_rtt << 1;
733 			}
734 			tp->t_rtt = 0;
735 		}
736 
737 		/*
738 		 * If all outstanding data is acked, stop retransmit
739 		 * timer and remember to restart (more output or persist).
740 		 * If there is more data to be acked, restart retransmit
741 		 * timer; set to smoothed rtt + 2*rttvar.
742 		 */
743 		if (ti->ti_ack == tp->snd_max) {
744 			tp->t_timer[TCPT_REXMT] = 0;
745 			needoutput = 1;
746 		} else if (tp->t_timer[TCPT_PERSIST] == 0) {
747 			TCPT_RANGESET(tp->t_timer[TCPT_REXMT],
748 			    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
749 			    TCPTV_MIN, TCPTV_REXMTMAX);
750 			tp->t_rxtshift = 0;
751 		}
752 		/*
753 		 * When new data is acked, open the congestion window
754 		 * by one max sized segment.
755 		 */
756 		tp->snd_cwnd = MIN(tp->snd_cwnd + tp->t_maxseg, 65535);
757 		if (acked > so->so_snd.sb_cc) {
758 			tp->snd_wnd -= so->so_snd.sb_cc;
759 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
760 			ourfinisacked = 1;
761 		} else {
762 			sbdrop(&so->so_snd, acked);
763 			tp->snd_wnd -= acked;
764 			ourfinisacked = 0;
765 		}
766 		if ((so->so_snd.sb_flags & SB_WAIT) || so->so_snd.sb_sel)
767 			sowwakeup(so);
768 		tp->snd_una = ti->ti_ack;
769 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
770 			tp->snd_nxt = tp->snd_una;
771 
772 		switch (tp->t_state) {
773 
774 		/*
775 		 * In FIN_WAIT_1 STATE in addition to the processing
776 		 * for the ESTABLISHED state if our FIN is now acknowledged
777 		 * then enter FIN_WAIT_2.
778 		 */
779 		case TCPS_FIN_WAIT_1:
780 			if (ourfinisacked) {
781 				/*
782 				 * If we can't receive any more
783 				 * data, then closing user can proceed.
784 				 * Starting the timer is contrary to the
785 				 * specification, but if we don't get a FIN
786 				 * we'll hang forever.
787 				 */
788 				if (so->so_state & SS_CANTRCVMORE) {
789 					soisdisconnected(so);
790 					tp->t_timer[TCPT_2MSL] = TCPTV_MAXIDLE;
791 				}
792 				tp->t_state = TCPS_FIN_WAIT_2;
793 			}
794 			break;
795 
796 	 	/*
797 		 * In CLOSING STATE in addition to the processing for
798 		 * the ESTABLISHED state if the ACK acknowledges our FIN
799 		 * then enter the TIME-WAIT state, otherwise ignore
800 		 * the segment.
801 		 */
802 		case TCPS_CLOSING:
803 			if (ourfinisacked) {
804 				tp->t_state = TCPS_TIME_WAIT;
805 				tcp_canceltimers(tp);
806 				tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
807 				soisdisconnected(so);
808 			}
809 			break;
810 
811 		/*
812 		 * In LAST_ACK, we may still be waiting for data to drain
813 		 * and/or to be acked, as well as for the ack of our FIN.
814 		 * If our FIN is now acknowledged, delete the TCB,
815 		 * enter the closed state and return.
816 		 */
817 		case TCPS_LAST_ACK:
818 			if (ourfinisacked) {
819 				tp = tcp_close(tp);
820 				goto drop;
821 			}
822 			break;
823 
824 		/*
825 		 * In TIME_WAIT state the only thing that should arrive
826 		 * is a retransmission of the remote FIN.  Acknowledge
827 		 * it and restart the finack timer.
828 		 */
829 		case TCPS_TIME_WAIT:
830 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
831 			goto dropafterack;
832 		}
833 	}
834 
835 step6:
836 	/*
837 	 * Update window information.
838 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
839 	 */
840 	if ((tiflags & TH_ACK) &&
841 	    (SEQ_LT(tp->snd_wl1, ti->ti_seq) || tp->snd_wl1 == ti->ti_seq &&
842 	    (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
843 	     tp->snd_wl2 == ti->ti_ack && ti->ti_win > tp->snd_wnd))) {
844 		/* keep track of pure window updates */
845 		if (ti->ti_len == 0 &&
846 		    tp->snd_wl2 == ti->ti_ack && ti->ti_win > tp->snd_wnd) {
847 			tcpstat.tcps_rcvwinupd++;
848 			tcpstat.tcps_rcvdupack--;
849 		}
850 		tp->snd_wnd = ti->ti_win;
851 		tp->snd_wl1 = ti->ti_seq;
852 		tp->snd_wl2 = ti->ti_ack;
853 		if (tp->snd_wnd > tp->max_sndwnd)
854 			tp->max_sndwnd = tp->snd_wnd;
855 		needoutput = 1;
856 	}
857 
858 	/*
859 	 * Process segments with URG.
860 	 */
861 	if ((tiflags & TH_URG) && ti->ti_urp &&
862 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
863 		/*
864 		 * This is a kludge, but if we receive and accept
865 		 * random urgent pointers, we'll crash in
866 		 * soreceive.  It's hard to imagine someone
867 		 * actually wanting to send this much urgent data.
868 		 */
869 		if (ti->ti_urp + so->so_rcv.sb_cc > SB_MAX) {
870 			ti->ti_urp = 0;			/* XXX */
871 			tiflags &= ~TH_URG;		/* XXX */
872 			goto dodata;			/* XXX */
873 		}
874 		/*
875 		 * If this segment advances the known urgent pointer,
876 		 * then mark the data stream.  This should not happen
877 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
878 		 * a FIN has been received from the remote side.
879 		 * In these states we ignore the URG.
880 		 *
881 		 * According to RFC961 (Assigned Protocols),
882 		 * the urgent pointer points to the last octet
883 		 * of urgent data.  We continue, however,
884 		 * to consider it to indicate the first octet
885 		 * of data past the urgent section
886 		 * as the original spec states.
887 		 */
888 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
889 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
890 			so->so_oobmark = so->so_rcv.sb_cc +
891 			    (tp->rcv_up - tp->rcv_nxt) - 1;
892 			if (so->so_oobmark == 0)
893 				so->so_state |= SS_RCVATMARK;
894 			sohasoutofband(so);
895 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
896 		}
897 		/*
898 		 * Remove out of band data so doesn't get presented to user.
899 		 * This can happen independent of advancing the URG pointer,
900 		 * but if two URG's are pending at once, some out-of-band
901 		 * data may creep in... ick.
902 		 */
903 		if (ti->ti_urp <= ti->ti_len &&
904 		    (so->so_options & SO_OOBINLINE) == 0)
905 			tcp_pulloutofband(so, ti);
906 	} else
907 		/*
908 		 * If no out of band data is expected,
909 		 * pull receive urgent pointer along
910 		 * with the receive window.
911 		 */
912 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
913 			tp->rcv_up = tp->rcv_nxt;
914 dodata:							/* XXX */
915 
916 	/*
917 	 * Process the segment text, merging it into the TCP sequencing queue,
918 	 * and arranging for acknowledgment of receipt if necessary.
919 	 * This process logically involves adjusting tp->rcv_wnd as data
920 	 * is presented to the user (this happens in tcp_usrreq.c,
921 	 * case PRU_RCVD).  If a FIN has already been received on this
922 	 * connection then we just ignore the text.
923 	 */
924 	if ((ti->ti_len || (tiflags&TH_FIN)) &&
925 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
926 		TCP_REASS(tp, ti, m, so, tiflags);
927 		if (tcpnodelack == 0)
928 			tp->t_flags |= TF_DELACK;
929 		else
930 			tp->t_flags |= TF_ACKNOW;
931 		/*
932 		 * Note the amount of data that peer has sent into
933 		 * our window, in order to estimate the sender's
934 		 * buffer size.
935 		 */
936 		len = so->so_rcv.sb_hiwat - (tp->rcv_nxt - tp->rcv_adv);
937 		if (len > tp->max_rcvd)
938 			tp->max_rcvd = len;
939 	} else {
940 		m_freem(m);
941 		tiflags &= ~TH_FIN;
942 	}
943 
944 	/*
945 	 * If FIN is received ACK the FIN and let the user know
946 	 * that the connection is closing.
947 	 */
948 	if (tiflags & TH_FIN) {
949 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
950 			socantrcvmore(so);
951 			tp->t_flags |= TF_ACKNOW;
952 			tp->rcv_nxt++;
953 		}
954 		switch (tp->t_state) {
955 
956 	 	/*
957 		 * In SYN_RECEIVED and ESTABLISHED STATES
958 		 * enter the CLOSE_WAIT state.
959 		 */
960 		case TCPS_SYN_RECEIVED:
961 		case TCPS_ESTABLISHED:
962 			tp->t_state = TCPS_CLOSE_WAIT;
963 			break;
964 
965 	 	/*
966 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
967 		 * enter the CLOSING state.
968 		 */
969 		case TCPS_FIN_WAIT_1:
970 			tp->t_state = TCPS_CLOSING;
971 			break;
972 
973 	 	/*
974 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
975 		 * starting the time-wait timer, turning off the other
976 		 * standard timers.
977 		 */
978 		case TCPS_FIN_WAIT_2:
979 			tp->t_state = TCPS_TIME_WAIT;
980 			tcp_canceltimers(tp);
981 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
982 			soisdisconnected(so);
983 			break;
984 
985 		/*
986 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
987 		 */
988 		case TCPS_TIME_WAIT:
989 			tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
990 			break;
991 		}
992 	}
993 	if (so->so_options & SO_DEBUG)
994 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
995 
996 	/*
997 	 * Return any desired output.
998 	 */
999 	if (needoutput || (tp->t_flags & TF_ACKNOW))
1000 		(void) tcp_output(tp);
1001 	return;
1002 
1003 dropafterack:
1004 	/*
1005 	 * Generate an ACK dropping incoming segment if it occupies
1006 	 * sequence space, where the ACK reflects our state.
1007 	 */
1008 	if (tiflags & TH_RST)
1009 		goto drop;
1010 	m_freem(m);
1011 	tp->t_flags |= TF_ACKNOW;
1012 	(void) tcp_output(tp);
1013 	return;
1014 
1015 dropwithreset:
1016 	if (om) {
1017 		(void) m_free(om);
1018 		om = 0;
1019 	}
1020 	/*
1021 	 * Generate a RST, dropping incoming segment.
1022 	 * Make ACK acceptable to originator of segment.
1023 	 * Don't bother to respond if destination was broadcast.
1024 	 */
1025 	if ((tiflags & TH_RST) || in_broadcast(ti->ti_dst))
1026 		goto drop;
1027 	if (tiflags & TH_ACK)
1028 		tcp_respond(tp, ti, (tcp_seq)0, ti->ti_ack, TH_RST);
1029 	else {
1030 		if (tiflags & TH_SYN)
1031 			ti->ti_len++;
1032 		tcp_respond(tp, ti, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1033 		    TH_RST|TH_ACK);
1034 	}
1035 	/* destroy temporarily created socket */
1036 	if (dropsocket)
1037 		(void) soabort(so);
1038 	return;
1039 
1040 drop:
1041 	if (om)
1042 		(void) m_free(om);
1043 	/*
1044 	 * Drop space held by incoming segment and return.
1045 	 */
1046 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1047 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1048 	m_freem(m);
1049 	/* destroy temporarily created socket */
1050 	if (dropsocket)
1051 		(void) soabort(so);
1052 	return;
1053 }
1054 
1055 tcp_dooptions(tp, om, ti)
1056 	struct tcpcb *tp;
1057 	struct mbuf *om;
1058 	struct tcpiphdr *ti;
1059 {
1060 	register u_char *cp;
1061 	int opt, optlen, cnt;
1062 
1063 	cp = mtod(om, u_char *);
1064 	cnt = om->m_len;
1065 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1066 		opt = cp[0];
1067 		if (opt == TCPOPT_EOL)
1068 			break;
1069 		if (opt == TCPOPT_NOP)
1070 			optlen = 1;
1071 		else {
1072 			optlen = cp[1];
1073 			if (optlen <= 0)
1074 				break;
1075 		}
1076 		switch (opt) {
1077 
1078 		default:
1079 			break;
1080 
1081 		case TCPOPT_MAXSEG:
1082 			if (optlen != 4)
1083 				continue;
1084 			if (!(ti->ti_flags & TH_SYN))
1085 				continue;
1086 			tp->t_maxseg = *(u_short *)(cp + 2);
1087 			tp->t_maxseg = ntohs((u_short)tp->t_maxseg);
1088 			tp->t_maxseg = MIN(tp->t_maxseg, tcp_mss(tp));
1089 			break;
1090 		}
1091 	}
1092 	(void) m_free(om);
1093 }
1094 
1095 /*
1096  * Pull out of band byte out of a segment so
1097  * it doesn't appear in the user's data queue.
1098  * It is still reflected in the segment length for
1099  * sequencing purposes.
1100  */
1101 tcp_pulloutofband(so, ti)
1102 	struct socket *so;
1103 	struct tcpiphdr *ti;
1104 {
1105 	register struct mbuf *m;
1106 	int cnt = ti->ti_urp - 1;
1107 
1108 	m = dtom(ti);
1109 	while (cnt >= 0) {
1110 		if (m->m_len > cnt) {
1111 			char *cp = mtod(m, caddr_t) + cnt;
1112 			struct tcpcb *tp = sototcpcb(so);
1113 
1114 			tp->t_iobc = *cp;
1115 			tp->t_oobflags |= TCPOOB_HAVEDATA;
1116 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1117 			m->m_len--;
1118 			return;
1119 		}
1120 		cnt -= m->m_len;
1121 		m = m->m_next;
1122 		if (m == 0)
1123 			break;
1124 	}
1125 	panic("tcp_pulloutofband");
1126 }
1127 
1128 /*
1129  *  Determine a reasonable value for maxseg size.
1130  *  If the route is known, use one that can be handled
1131  *  on the given interface without forcing IP to fragment.
1132  *  If bigger than an mbuf cluster (MCLBYTES), round down to nearest size
1133  *  to utilize large mbufs.
1134  *  If interface pointer is unavailable, or the destination isn't local,
1135  *  use a conservative size (512 or the default IP max size, but no more
1136  *  than the mtu of the interface through which we route),
1137  *  as we can't discover anything about intervening gateways or networks.
1138  *
1139  *  This is ugly, and doesn't belong at this level, but has to happen somehow.
1140  */
1141 tcp_mss(tp)
1142 	register struct tcpcb *tp;
1143 {
1144 	struct route *ro;
1145 	struct ifnet *ifp;
1146 	int mss;
1147 	struct inpcb *inp;
1148 
1149 	inp = tp->t_inpcb;
1150 	ro = &inp->inp_route;
1151 	if ((ro->ro_rt == (struct rtentry *)0) ||
1152 	    (ifp = ro->ro_rt->rt_ifp) == (struct ifnet *)0) {
1153 		/* No route yet, so try to acquire one */
1154 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1155 			ro->ro_dst.sa_family = AF_INET;
1156 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1157 				inp->inp_faddr;
1158 			rtalloc(ro);
1159 		}
1160 		if ((ro->ro_rt == 0) || (ifp = ro->ro_rt->rt_ifp) == 0)
1161 			return (TCP_MSS);
1162 	}
1163 
1164 	mss = ifp->if_mtu - sizeof(struct tcpiphdr);
1165 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1166 	if (mss > MCLBYTES)
1167 		mss &= ~(MCLBYTES-1);
1168 #else
1169 	if (mss > MCLBYTES)
1170 		mss = mss / MCLBYTES * MCLBYTES;
1171 #endif
1172 	if (in_localaddr(inp->inp_faddr))
1173 		return (mss);
1174 	return (MIN(mss, TCP_MSS));
1175 }
1176