tcp_input.c revision 1.55 1 /* $NetBSD: tcp_input.c,v 1.55 1998/05/02 04:21:58 thorpej Exp $ */
2
3 /*-
4 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
9 * Facility, NASA Ames Research Center.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
42 * The Regents of the University of California. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. All advertising materials mentioning features or use of this software
53 * must display the following acknowledgement:
54 * This product includes software developed by the University of
55 * California, Berkeley and its contributors.
56 * 4. Neither the name of the University nor the names of its contributors
57 * may be used to endorse or promote products derived from this software
58 * without specific prior written permission.
59 *
60 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 * SUCH DAMAGE.
71 *
72 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
73 */
74
75 /*
76 * TODO list for SYN cache stuff:
77 *
78 * Find room for a "state" field, which is needed to keep a
79 * compressed state for TIME_WAIT TCBs. It's been noted already
80 * that this is fairly important for very high-volume web and
81 * mail servers, which use a large number of short-lived
82 * connections.
83 */
84
85 #ifndef TUBA_INCLUDE
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/malloc.h>
89 #include <sys/mbuf.h>
90 #include <sys/protosw.h>
91 #include <sys/socket.h>
92 #include <sys/socketvar.h>
93 #include <sys/errno.h>
94 #include <sys/syslog.h>
95
96 #include <net/if.h>
97 #include <net/route.h>
98
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_var.h>
104 #include <netinet/tcp.h>
105 #include <netinet/tcp_fsm.h>
106 #include <netinet/tcp_seq.h>
107 #include <netinet/tcp_timer.h>
108 #include <netinet/tcp_var.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/tcp_debug.h>
111
112 #include <machine/stdarg.h>
113
114 int tcprexmtthresh = 3;
115 struct tcpiphdr tcp_saveti;
116
117 int tcp_ack_on_push = 0; /* set to enable immediate ACK-on-PUSH */
118
119 extern u_long sb_max;
120
121 #endif /* TUBA_INCLUDE */
122 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
123
124 /* for modulo comparisons of timestamps */
125 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
126 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
127
128 /*
129 * Macro to compute ACK transmission behavior. Delay the ACK unless
130 * we have already delayed an ACK (must send an ACK every two segments).
131 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
132 * option is enabled.
133 */
134 #define TCP_SETUP_ACK(tp, ti) \
135 do { \
136 if ((tp)->t_flags & TF_DELACK || \
137 (tcp_ack_on_push && (ti)->ti_flags & TH_PUSH)) \
138 tp->t_flags |= TF_ACKNOW; \
139 else \
140 TCP_SET_DELACK(tp); \
141 } while (0)
142
143 /*
144 * Insert segment ti into reassembly queue of tcp with
145 * control block tp. Return TH_FIN if reassembly now includes
146 * a segment with FIN. The macro form does the common case inline
147 * (segment is the next to be received on an established connection,
148 * and the queue is empty), avoiding linkage into and removal
149 * from the queue and repetition of various conversions.
150 * Set DELACK for segments received in order, but ack immediately
151 * when segments are out of order (so fast retransmit can work).
152 */
153 #define TCP_REASS(tp, ti, m, so, flags) { \
154 if ((ti)->ti_seq == (tp)->rcv_nxt && \
155 (tp)->segq.lh_first == NULL && \
156 (tp)->t_state == TCPS_ESTABLISHED) { \
157 TCP_SETUP_ACK(tp, ti); \
158 (tp)->rcv_nxt += (ti)->ti_len; \
159 flags = (ti)->ti_flags & TH_FIN; \
160 tcpstat.tcps_rcvpack++;\
161 tcpstat.tcps_rcvbyte += (ti)->ti_len;\
162 sbappend(&(so)->so_rcv, (m)); \
163 sorwakeup(so); \
164 } else { \
165 (flags) = tcp_reass((tp), (ti), (m)); \
166 tp->t_flags |= TF_ACKNOW; \
167 } \
168 }
169 #ifndef TUBA_INCLUDE
170
171 int
172 tcp_reass(tp, ti, m)
173 register struct tcpcb *tp;
174 register struct tcpiphdr *ti;
175 struct mbuf *m;
176 {
177 register struct ipqent *p, *q, *nq, *tiqe = NULL;
178 struct socket *so = tp->t_inpcb->inp_socket;
179 int pkt_flags;
180 tcp_seq pkt_seq;
181 unsigned pkt_len;
182 u_long rcvpartdupbyte = 0;
183 u_long rcvoobyte;
184
185 /*
186 * Call with ti==0 after become established to
187 * force pre-ESTABLISHED data up to user socket.
188 */
189 if (ti == 0)
190 goto present;
191
192 rcvoobyte = ti->ti_len;
193 /*
194 * Copy these to local variables because the tcpiphdr
195 * gets munged while we are collapsing mbufs.
196 */
197 pkt_seq = ti->ti_seq;
198 pkt_len = ti->ti_len;
199 pkt_flags = ti->ti_flags;
200 /*
201 * Find a segment which begins after this one does.
202 */
203 for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
204 nq = q->ipqe_q.le_next;
205 /*
206 * If the received segment is just right after this
207 * fragment, merge the two together and then check
208 * for further overlaps.
209 */
210 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
211 #ifdef TCPREASS_DEBUG
212 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
213 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
214 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
215 #endif
216 pkt_len += q->ipqe_len;
217 pkt_flags |= q->ipqe_flags;
218 pkt_seq = q->ipqe_seq;
219 m_cat(q->ipqe_m, m);
220 m = q->ipqe_m;
221 goto free_ipqe;
222 }
223 /*
224 * If the received segment is completely past this
225 * fragment, we need to go the next fragment.
226 */
227 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
228 p = q;
229 continue;
230 }
231 /*
232 * If the fragment is past the received segment,
233 * it (or any following) can't be concatenated.
234 */
235 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
236 break;
237 /*
238 * We've received all the data in this segment before.
239 * mark it as a duplicate and return.
240 */
241 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
242 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
243 tcpstat.tcps_rcvduppack++;
244 tcpstat.tcps_rcvdupbyte += pkt_len;
245 m_freem(m);
246 if (tiqe != NULL)
247 FREE(tiqe, M_IPQ);
248 return (0);
249 }
250 /*
251 * Received segment completely overlaps this fragment
252 * so we drop the fragment (this keeps the temporal
253 * ordering of segments correct).
254 */
255 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
256 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
257 rcvpartdupbyte += q->ipqe_len;
258 m_freem(q->ipqe_m);
259 goto free_ipqe;
260 }
261 /*
262 * RX'ed segment extends past the end of the
263 * fragment. Drop the overlapping bytes. Then
264 * merge the fragment and segment then treat as
265 * a longer received packet.
266 */
267 if (SEQ_LT(q->ipqe_seq, pkt_seq)
268 && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
269 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
270 #ifdef TCPREASS_DEBUG
271 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
272 tp, overlap,
273 pkt_seq, pkt_seq + pkt_len, pkt_len);
274 #endif
275 m_adj(m, overlap);
276 rcvpartdupbyte += overlap;
277 m_cat(q->ipqe_m, m);
278 m = q->ipqe_m;
279 pkt_seq = q->ipqe_seq;
280 pkt_len += q->ipqe_len - overlap;
281 rcvoobyte -= overlap;
282 goto free_ipqe;
283 }
284 /*
285 * RX'ed segment extends past the front of the
286 * fragment. Drop the overlapping bytes on the
287 * received packet. The packet will then be
288 * contatentated with this fragment a bit later.
289 */
290 if (SEQ_GT(q->ipqe_seq, pkt_seq)
291 && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
292 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
293 #ifdef TCPREASS_DEBUG
294 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
295 tp, overlap,
296 pkt_seq, pkt_seq + pkt_len, pkt_len);
297 #endif
298 m_adj(m, -overlap);
299 pkt_len -= overlap;
300 rcvpartdupbyte += overlap;
301 rcvoobyte -= overlap;
302 }
303 /*
304 * If the received segment immediates precedes this
305 * fragment then tack the fragment onto this segment
306 * and reinsert the data.
307 */
308 if (q->ipqe_seq == pkt_seq + pkt_len) {
309 #ifdef TCPREASS_DEBUG
310 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
311 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
312 pkt_seq, pkt_seq + pkt_len, pkt_len);
313 #endif
314 pkt_len += q->ipqe_len;
315 pkt_flags |= q->ipqe_flags;
316 m_cat(m, q->ipqe_m);
317 LIST_REMOVE(q, ipqe_q);
318 LIST_REMOVE(q, ipqe_timeq);
319 if (tiqe == NULL) {
320 tiqe = q;
321 } else {
322 FREE(q, M_IPQ);
323 }
324 break;
325 }
326 /*
327 * If the fragment is before the segment, remember it.
328 * When this loop is terminated, p will contain the
329 * pointer to fragment that is right before the received
330 * segment.
331 */
332 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
333 p = q;
334
335 continue;
336
337 /*
338 * This is a common operation. It also will allow
339 * to save doing a malloc/free in most instances.
340 */
341 free_ipqe:
342 LIST_REMOVE(q, ipqe_q);
343 LIST_REMOVE(q, ipqe_timeq);
344 if (tiqe == NULL) {
345 tiqe = q;
346 } else {
347 FREE(q, M_IPQ);
348 }
349 }
350
351 /*
352 * Allocate a new queue entry since the received segment did not
353 * collapse onto any other out-of-order block; thus we are allocating
354 * a new block. If it had collapsed, tiqe would not be NULL and
355 * we would be reusing it.
356 * XXX If we can't, just drop the packet. XXX
357 */
358 if (tiqe == NULL) {
359 MALLOC(tiqe, struct ipqent *, sizeof (struct ipqent), M_IPQ, M_NOWAIT);
360 if (tiqe == NULL) {
361 tcpstat.tcps_rcvmemdrop++;
362 m_freem(m);
363 return (0);
364 }
365 }
366
367 /*
368 * Update the counters.
369 */
370 tcpstat.tcps_rcvoopack++;
371 tcpstat.tcps_rcvoobyte += rcvoobyte;
372 if (rcvpartdupbyte) {
373 tcpstat.tcps_rcvpartduppack++;
374 tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
375 }
376
377 /*
378 * Insert the new fragment queue entry into both queues.
379 */
380 tiqe->ipqe_m = m;
381 tiqe->ipqe_seq = pkt_seq;
382 tiqe->ipqe_len = pkt_len;
383 tiqe->ipqe_flags = pkt_flags;
384 if (p == NULL) {
385 LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
386 #ifdef TCPREASS_DEBUG
387 if (tiqe->ipqe_seq != tp->rcv_nxt)
388 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
389 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
390 #endif
391 } else {
392 LIST_INSERT_AFTER(p, tiqe, ipqe_q);
393 #ifdef TCPREASS_DEBUG
394 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
395 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
396 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
397 #endif
398 }
399
400 LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
401
402 present:
403 /*
404 * Present data to user, advancing rcv_nxt through
405 * completed sequence space.
406 */
407 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
408 return (0);
409 q = tp->segq.lh_first;
410 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
411 return (0);
412 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
413 return (0);
414
415 tp->rcv_nxt += q->ipqe_len;
416 pkt_flags = q->ipqe_flags & TH_FIN;
417
418 LIST_REMOVE(q, ipqe_q);
419 LIST_REMOVE(q, ipqe_timeq);
420 if (so->so_state & SS_CANTRCVMORE)
421 m_freem(q->ipqe_m);
422 else
423 sbappend(&so->so_rcv, q->ipqe_m);
424 FREE(q, M_IPQ);
425 sorwakeup(so);
426 return (pkt_flags);
427 }
428
429 /*
430 * TCP input routine, follows pages 65-76 of the
431 * protocol specification dated September, 1981 very closely.
432 */
433 void
434 #if __STDC__
435 tcp_input(struct mbuf *m, ...)
436 #else
437 tcp_input(m, va_alist)
438 register struct mbuf *m;
439 #endif
440 {
441 register struct tcpiphdr *ti;
442 register struct inpcb *inp;
443 caddr_t optp = NULL;
444 int optlen = 0;
445 int len, tlen, off, hdroptlen;
446 register struct tcpcb *tp = 0;
447 register int tiflags;
448 struct socket *so = NULL;
449 int todrop, acked, ourfinisacked, needoutput = 0;
450 short ostate = 0;
451 int iss = 0;
452 u_long tiwin;
453 struct tcp_opt_info opti;
454 int iphlen;
455 va_list ap;
456
457 va_start(ap, m);
458 iphlen = va_arg(ap, int);
459 va_end(ap);
460
461 tcpstat.tcps_rcvtotal++;
462
463 opti.ts_present = 0;
464 opti.maxseg = 0;
465
466 /*
467 * Get IP and TCP header together in first mbuf.
468 * Note: IP leaves IP header in first mbuf.
469 */
470 ti = mtod(m, struct tcpiphdr *);
471 if (iphlen > sizeof (struct ip))
472 ip_stripoptions(m, (struct mbuf *)0);
473 if (m->m_len < sizeof (struct tcpiphdr)) {
474 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
475 tcpstat.tcps_rcvshort++;
476 return;
477 }
478 ti = mtod(m, struct tcpiphdr *);
479 }
480
481 /*
482 * Checksum extended TCP header and data.
483 */
484 tlen = ((struct ip *)ti)->ip_len;
485 len = sizeof (struct ip) + tlen;
486 bzero(ti->ti_x1, sizeof ti->ti_x1);
487 ti->ti_len = (u_int16_t)tlen;
488 HTONS(ti->ti_len);
489 if ((ti->ti_sum = in_cksum(m, len)) != 0) {
490 tcpstat.tcps_rcvbadsum++;
491 goto drop;
492 }
493 #endif /* TUBA_INCLUDE */
494
495 /*
496 * Check that TCP offset makes sense,
497 * pull out TCP options and adjust length. XXX
498 */
499 off = ti->ti_off << 2;
500 if (off < sizeof (struct tcphdr) || off > tlen) {
501 tcpstat.tcps_rcvbadoff++;
502 goto drop;
503 }
504 tlen -= off;
505 ti->ti_len = tlen;
506 if (off > sizeof (struct tcphdr)) {
507 if (m->m_len < sizeof(struct ip) + off) {
508 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
509 tcpstat.tcps_rcvshort++;
510 return;
511 }
512 ti = mtod(m, struct tcpiphdr *);
513 }
514 optlen = off - sizeof (struct tcphdr);
515 optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
516 /*
517 * Do quick retrieval of timestamp options ("options
518 * prediction?"). If timestamp is the only option and it's
519 * formatted as recommended in RFC 1323 appendix A, we
520 * quickly get the values now and not bother calling
521 * tcp_dooptions(), etc.
522 */
523 if ((optlen == TCPOLEN_TSTAMP_APPA ||
524 (optlen > TCPOLEN_TSTAMP_APPA &&
525 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
526 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
527 (ti->ti_flags & TH_SYN) == 0) {
528 opti.ts_present = 1;
529 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
530 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
531 optp = NULL; /* we've parsed the options */
532 }
533 }
534 tiflags = ti->ti_flags;
535
536 /*
537 * Convert TCP protocol specific fields to host format.
538 */
539 NTOHL(ti->ti_seq);
540 NTOHL(ti->ti_ack);
541 NTOHS(ti->ti_win);
542 NTOHS(ti->ti_urp);
543
544 /*
545 * Locate pcb for segment.
546 */
547 findpcb:
548 inp = in_pcblookup_connect(&tcbtable, ti->ti_src, ti->ti_sport,
549 ti->ti_dst, ti->ti_dport);
550 if (inp == 0) {
551 ++tcpstat.tcps_pcbhashmiss;
552 inp = in_pcblookup_bind(&tcbtable, ti->ti_dst, ti->ti_dport);
553 if (inp == 0) {
554 ++tcpstat.tcps_noport;
555 goto dropwithreset;
556 }
557 }
558
559 /*
560 * If the state is CLOSED (i.e., TCB does not exist) then
561 * all data in the incoming segment is discarded.
562 * If the TCB exists but is in CLOSED state, it is embryonic,
563 * but should either do a listen or a connect soon.
564 */
565 tp = intotcpcb(inp);
566 if (tp == 0)
567 goto dropwithreset;
568 if (tp->t_state == TCPS_CLOSED)
569 goto drop;
570
571 /* Unscale the window into a 32-bit value. */
572 if ((tiflags & TH_SYN) == 0)
573 tiwin = ti->ti_win << tp->snd_scale;
574 else
575 tiwin = ti->ti_win;
576
577 so = inp->inp_socket;
578 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
579 if (so->so_options & SO_DEBUG) {
580 ostate = tp->t_state;
581 tcp_saveti = *ti;
582 }
583 if (so->so_options & SO_ACCEPTCONN) {
584 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
585 if (tiflags & TH_RST) {
586 syn_cache_reset(ti);
587 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
588 (TH_ACK|TH_SYN)) {
589 /*
590 * Received a SYN,ACK. This should
591 * never happen while we are in
592 * LISTEN. Send an RST.
593 */
594 goto badsyn;
595 } else if (tiflags & TH_ACK) {
596 so = syn_cache_get(so, m);
597 if (so == NULL) {
598 /*
599 * We don't have a SYN for
600 * this ACK; send an RST.
601 */
602 goto badsyn;
603 } else if (so ==
604 (struct socket *)(-1)) {
605 /*
606 * We were unable to create
607 * the connection. If the
608 * 3-way handshake was
609 * completeed, and RST has
610 * been sent to the peer.
611 * Since the mbuf might be
612 * in use for the reply,
613 * do not free it.
614 */
615 m = NULL;
616 } else {
617 /*
618 * We have created a
619 * full-blown connection.
620 */
621 inp = sotoinpcb(so);
622 tp = intotcpcb(inp);
623 tiwin <<= tp->snd_scale;
624 goto after_listen;
625 }
626 }
627 } else {
628 /*
629 * Received a SYN.
630 */
631 if (in_hosteq(ti->ti_src, ti->ti_dst) &&
632 ti->ti_sport == ti->ti_dport) {
633 /*
634 * LISTEN socket received a SYN
635 * from itself? This can't possibly
636 * be valid; drop the packet.
637 */
638 tcpstat.tcps_badsyn++;
639 goto drop;
640 }
641 /*
642 * SYN looks ok; create compressed TCP
643 * state for it.
644 */
645 if (so->so_qlen <= so->so_qlimit &&
646 syn_cache_add(so, m, optp, optlen, &opti))
647 m = NULL;
648 }
649 goto drop;
650 }
651 }
652
653 after_listen:
654 #ifdef DIAGNOSTIC
655 /*
656 * Should not happen now that all embryonic connections
657 * are handled with compressed state.
658 */
659 if (tp->t_state == TCPS_LISTEN)
660 panic("tcp_input: TCPS_LISTEN");
661 #endif
662
663 /*
664 * Segment received on connection.
665 * Reset idle time and keep-alive timer.
666 */
667 tp->t_idle = 0;
668 if (TCPS_HAVEESTABLISHED(tp->t_state))
669 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
670
671 /*
672 * Process options.
673 */
674 if (optp)
675 tcp_dooptions(tp, optp, optlen, ti, &opti);
676
677 /*
678 * Header prediction: check for the two common cases
679 * of a uni-directional data xfer. If the packet has
680 * no control flags, is in-sequence, the window didn't
681 * change and we're not retransmitting, it's a
682 * candidate. If the length is zero and the ack moved
683 * forward, we're the sender side of the xfer. Just
684 * free the data acked & wake any higher level process
685 * that was blocked waiting for space. If the length
686 * is non-zero and the ack didn't move, we're the
687 * receiver side. If we're getting packets in-order
688 * (the reassembly queue is empty), add the data to
689 * the socket buffer and note that we need a delayed ack.
690 */
691 if (tp->t_state == TCPS_ESTABLISHED &&
692 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
693 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
694 ti->ti_seq == tp->rcv_nxt &&
695 tiwin && tiwin == tp->snd_wnd &&
696 tp->snd_nxt == tp->snd_max) {
697
698 /*
699 * If last ACK falls within this segment's sequence numbers,
700 * record the timestamp.
701 */
702 if (opti.ts_present &&
703 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
704 SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
705 tp->ts_recent_age = tcp_now;
706 tp->ts_recent = opti.ts_val;
707 }
708
709 if (ti->ti_len == 0) {
710 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
711 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
712 tp->snd_cwnd >= tp->snd_wnd &&
713 tp->t_dupacks < tcprexmtthresh) {
714 /*
715 * this is a pure ack for outstanding data.
716 */
717 ++tcpstat.tcps_predack;
718 if (opti.ts_present)
719 tcp_xmit_timer(tp,
720 tcp_now-opti.ts_ecr+1);
721 else if (tp->t_rtt &&
722 SEQ_GT(ti->ti_ack, tp->t_rtseq))
723 tcp_xmit_timer(tp, tp->t_rtt);
724 acked = ti->ti_ack - tp->snd_una;
725 tcpstat.tcps_rcvackpack++;
726 tcpstat.tcps_rcvackbyte += acked;
727 sbdrop(&so->so_snd, acked);
728 tp->snd_una = ti->ti_ack;
729 m_freem(m);
730
731 /*
732 * If all outstanding data are acked, stop
733 * retransmit timer, otherwise restart timer
734 * using current (possibly backed-off) value.
735 * If process is waiting for space,
736 * wakeup/selwakeup/signal. If data
737 * are ready to send, let tcp_output
738 * decide between more output or persist.
739 */
740 if (tp->snd_una == tp->snd_max)
741 tp->t_timer[TCPT_REXMT] = 0;
742 else if (tp->t_timer[TCPT_PERSIST] == 0)
743 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
744
745 sowwakeup(so);
746 if (so->so_snd.sb_cc)
747 (void) tcp_output(tp);
748 return;
749 }
750 } else if (ti->ti_ack == tp->snd_una &&
751 tp->segq.lh_first == NULL &&
752 ti->ti_len <= sbspace(&so->so_rcv)) {
753 /*
754 * this is a pure, in-sequence data packet
755 * with nothing on the reassembly queue and
756 * we have enough buffer space to take it.
757 */
758 ++tcpstat.tcps_preddat;
759 tp->rcv_nxt += ti->ti_len;
760 tcpstat.tcps_rcvpack++;
761 tcpstat.tcps_rcvbyte += ti->ti_len;
762 /*
763 * Drop TCP, IP headers and TCP options then add data
764 * to socket buffer.
765 */
766 m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
767 m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
768 sbappend(&so->so_rcv, m);
769 sorwakeup(so);
770 TCP_SETUP_ACK(tp, ti);
771 if (tp->t_flags & TF_ACKNOW)
772 (void) tcp_output(tp);
773 return;
774 }
775 }
776
777 /*
778 * Drop TCP, IP headers and TCP options.
779 */
780 hdroptlen = sizeof(struct tcpiphdr) + off - sizeof(struct tcphdr);
781 m->m_data += hdroptlen;
782 m->m_len -= hdroptlen;
783
784 /*
785 * Calculate amount of space in receive window,
786 * and then do TCP input processing.
787 * Receive window is amount of space in rcv queue,
788 * but not less than advertised window.
789 */
790 { int win;
791
792 win = sbspace(&so->so_rcv);
793 if (win < 0)
794 win = 0;
795 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
796 }
797
798 switch (tp->t_state) {
799
800 /*
801 * If the state is SYN_SENT:
802 * if seg contains an ACK, but not for our SYN, drop the input.
803 * if seg contains a RST, then drop the connection.
804 * if seg does not contain SYN, then drop it.
805 * Otherwise this is an acceptable SYN segment
806 * initialize tp->rcv_nxt and tp->irs
807 * if seg contains ack then advance tp->snd_una
808 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
809 * arrange for segment to be acked (eventually)
810 * continue processing rest of data/controls, beginning with URG
811 */
812 case TCPS_SYN_SENT:
813 if ((tiflags & TH_ACK) &&
814 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
815 SEQ_GT(ti->ti_ack, tp->snd_max)))
816 goto dropwithreset;
817 if (tiflags & TH_RST) {
818 if (tiflags & TH_ACK)
819 tp = tcp_drop(tp, ECONNREFUSED);
820 goto drop;
821 }
822 if ((tiflags & TH_SYN) == 0)
823 goto drop;
824 if (tiflags & TH_ACK) {
825 tp->snd_una = ti->ti_ack;
826 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
827 tp->snd_nxt = tp->snd_una;
828 }
829 tp->t_timer[TCPT_REXMT] = 0;
830 tp->irs = ti->ti_seq;
831 tcp_rcvseqinit(tp);
832 tp->t_flags |= TF_ACKNOW;
833 tcp_mss_from_peer(tp, opti.maxseg);
834
835 /*
836 * Initialize the initial congestion window. If we
837 * had to retransmit the SYN, we must initialize cwnd
838 * to 1 segment.
839 */
840 tp->snd_cwnd =
841 TCP_INITIAL_WINDOW((tp->t_flags & TF_SYN_REXMT) ? 1 :
842 tcp_init_win, tp->t_peermss);
843
844 tcp_rmx_rtt(tp);
845 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
846 tcpstat.tcps_connects++;
847 soisconnected(so);
848 tcp_established(tp);
849 /* Do window scaling on this connection? */
850 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
851 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
852 tp->snd_scale = tp->requested_s_scale;
853 tp->rcv_scale = tp->request_r_scale;
854 }
855 (void) tcp_reass(tp, (struct tcpiphdr *)0,
856 (struct mbuf *)0);
857 /*
858 * if we didn't have to retransmit the SYN,
859 * use its rtt as our initial srtt & rtt var.
860 */
861 if (tp->t_rtt)
862 tcp_xmit_timer(tp, tp->t_rtt);
863 } else
864 tp->t_state = TCPS_SYN_RECEIVED;
865
866 /*
867 * Advance ti->ti_seq to correspond to first data byte.
868 * If data, trim to stay within window,
869 * dropping FIN if necessary.
870 */
871 ti->ti_seq++;
872 if (ti->ti_len > tp->rcv_wnd) {
873 todrop = ti->ti_len - tp->rcv_wnd;
874 m_adj(m, -todrop);
875 ti->ti_len = tp->rcv_wnd;
876 tiflags &= ~TH_FIN;
877 tcpstat.tcps_rcvpackafterwin++;
878 tcpstat.tcps_rcvbyteafterwin += todrop;
879 }
880 tp->snd_wl1 = ti->ti_seq - 1;
881 tp->rcv_up = ti->ti_seq;
882 goto step6;
883
884 /*
885 * If the state is SYN_RECEIVED:
886 * If seg contains an ACK, but not for our SYN, drop the input
887 * and generate an RST. See page 36, rfc793
888 */
889 case TCPS_SYN_RECEIVED:
890 if ((tiflags & TH_ACK) &&
891 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
892 SEQ_GT(ti->ti_ack, tp->snd_max)))
893 goto dropwithreset;
894 break;
895 }
896
897 /*
898 * States other than LISTEN or SYN_SENT.
899 * First check timestamp, if present.
900 * Then check that at least some bytes of segment are within
901 * receive window. If segment begins before rcv_nxt,
902 * drop leading data (and SYN); if nothing left, just ack.
903 *
904 * RFC 1323 PAWS: If we have a timestamp reply on this segment
905 * and it's less than ts_recent, drop it.
906 */
907 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
908 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
909
910 /* Check to see if ts_recent is over 24 days old. */
911 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
912 /*
913 * Invalidate ts_recent. If this segment updates
914 * ts_recent, the age will be reset later and ts_recent
915 * will get a valid value. If it does not, setting
916 * ts_recent to zero will at least satisfy the
917 * requirement that zero be placed in the timestamp
918 * echo reply when ts_recent isn't valid. The
919 * age isn't reset until we get a valid ts_recent
920 * because we don't want out-of-order segments to be
921 * dropped when ts_recent is old.
922 */
923 tp->ts_recent = 0;
924 } else {
925 tcpstat.tcps_rcvduppack++;
926 tcpstat.tcps_rcvdupbyte += ti->ti_len;
927 tcpstat.tcps_pawsdrop++;
928 goto dropafterack;
929 }
930 }
931
932 todrop = tp->rcv_nxt - ti->ti_seq;
933 if (todrop > 0) {
934 if (tiflags & TH_SYN) {
935 tiflags &= ~TH_SYN;
936 ti->ti_seq++;
937 if (ti->ti_urp > 1)
938 ti->ti_urp--;
939 else {
940 tiflags &= ~TH_URG;
941 ti->ti_urp = 0;
942 }
943 todrop--;
944 }
945 if (todrop > ti->ti_len ||
946 (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
947 /*
948 * Any valid FIN must be to the left of the window.
949 * At this point the FIN must be a duplicate or
950 * out of sequence; drop it.
951 */
952 tiflags &= ~TH_FIN;
953 /*
954 * Send an ACK to resynchronize and drop any data.
955 * But keep on processing for RST or ACK.
956 */
957 tp->t_flags |= TF_ACKNOW;
958 todrop = ti->ti_len;
959 tcpstat.tcps_rcvdupbyte += todrop;
960 tcpstat.tcps_rcvduppack++;
961 } else {
962 tcpstat.tcps_rcvpartduppack++;
963 tcpstat.tcps_rcvpartdupbyte += todrop;
964 }
965 m_adj(m, todrop);
966 ti->ti_seq += todrop;
967 ti->ti_len -= todrop;
968 if (ti->ti_urp > todrop)
969 ti->ti_urp -= todrop;
970 else {
971 tiflags &= ~TH_URG;
972 ti->ti_urp = 0;
973 }
974 }
975
976 /*
977 * If new data are received on a connection after the
978 * user processes are gone, then RST the other end.
979 */
980 if ((so->so_state & SS_NOFDREF) &&
981 tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
982 tp = tcp_close(tp);
983 tcpstat.tcps_rcvafterclose++;
984 goto dropwithreset;
985 }
986
987 /*
988 * If segment ends after window, drop trailing data
989 * (and PUSH and FIN); if nothing left, just ACK.
990 */
991 todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
992 if (todrop > 0) {
993 tcpstat.tcps_rcvpackafterwin++;
994 if (todrop >= ti->ti_len) {
995 tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
996 /*
997 * If a new connection request is received
998 * while in TIME_WAIT, drop the old connection
999 * and start over if the sequence numbers
1000 * are above the previous ones.
1001 */
1002 if (tiflags & TH_SYN &&
1003 tp->t_state == TCPS_TIME_WAIT &&
1004 SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1005 iss = tcp_new_iss(tp, sizeof(struct tcpcb),
1006 tp->rcv_nxt);
1007 tp = tcp_close(tp);
1008 /*
1009 * We have already advanced the mbuf
1010 * pointers past the IP+TCP headers and
1011 * options. Restore those pointers before
1012 * attempting to use the TCP header again.
1013 */
1014 m->m_data -= hdroptlen;
1015 m->m_len += hdroptlen;
1016 goto findpcb;
1017 }
1018 /*
1019 * If window is closed can only take segments at
1020 * window edge, and have to drop data and PUSH from
1021 * incoming segments. Continue processing, but
1022 * remember to ack. Otherwise, drop segment
1023 * and ack.
1024 */
1025 if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1026 tp->t_flags |= TF_ACKNOW;
1027 tcpstat.tcps_rcvwinprobe++;
1028 } else
1029 goto dropafterack;
1030 } else
1031 tcpstat.tcps_rcvbyteafterwin += todrop;
1032 m_adj(m, -todrop);
1033 ti->ti_len -= todrop;
1034 tiflags &= ~(TH_PUSH|TH_FIN);
1035 }
1036
1037 /*
1038 * If last ACK falls within this segment's sequence numbers,
1039 * and the timestamp is newer, record it.
1040 */
1041 if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1042 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
1043 SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
1044 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1045 tp->ts_recent_age = tcp_now;
1046 tp->ts_recent = opti.ts_val;
1047 }
1048
1049 /*
1050 * If the RST bit is set examine the state:
1051 * SYN_RECEIVED STATE:
1052 * If passive open, return to LISTEN state.
1053 * If active open, inform user that connection was refused.
1054 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1055 * Inform user that connection was reset, and close tcb.
1056 * CLOSING, LAST_ACK, TIME_WAIT STATES
1057 * Close the tcb.
1058 */
1059 if (tiflags&TH_RST) switch (tp->t_state) {
1060
1061 case TCPS_SYN_RECEIVED:
1062 so->so_error = ECONNREFUSED;
1063 goto close;
1064
1065 case TCPS_ESTABLISHED:
1066 case TCPS_FIN_WAIT_1:
1067 case TCPS_FIN_WAIT_2:
1068 case TCPS_CLOSE_WAIT:
1069 so->so_error = ECONNRESET;
1070 close:
1071 tp->t_state = TCPS_CLOSED;
1072 tcpstat.tcps_drops++;
1073 tp = tcp_close(tp);
1074 goto drop;
1075
1076 case TCPS_CLOSING:
1077 case TCPS_LAST_ACK:
1078 case TCPS_TIME_WAIT:
1079 tp = tcp_close(tp);
1080 goto drop;
1081 }
1082
1083 /*
1084 * If a SYN is in the window, then this is an
1085 * error and we send an RST and drop the connection.
1086 */
1087 if (tiflags & TH_SYN) {
1088 tp = tcp_drop(tp, ECONNRESET);
1089 goto dropwithreset;
1090 }
1091
1092 /*
1093 * If the ACK bit is off we drop the segment and return.
1094 */
1095 if ((tiflags & TH_ACK) == 0)
1096 goto drop;
1097
1098 /*
1099 * Ack processing.
1100 */
1101 switch (tp->t_state) {
1102
1103 /*
1104 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1105 * ESTABLISHED state and continue processing, otherwise
1106 * send an RST.
1107 */
1108 case TCPS_SYN_RECEIVED:
1109 if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
1110 SEQ_GT(ti->ti_ack, tp->snd_max))
1111 goto dropwithreset;
1112 tcpstat.tcps_connects++;
1113 soisconnected(so);
1114 tcp_established(tp);
1115 /* Do window scaling? */
1116 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1117 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1118 tp->snd_scale = tp->requested_s_scale;
1119 tp->rcv_scale = tp->request_r_scale;
1120 }
1121 (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
1122 tp->snd_wl1 = ti->ti_seq - 1;
1123 /* fall into ... */
1124
1125 /*
1126 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1127 * ACKs. If the ack is in the range
1128 * tp->snd_una < ti->ti_ack <= tp->snd_max
1129 * then advance tp->snd_una to ti->ti_ack and drop
1130 * data from the retransmission queue. If this ACK reflects
1131 * more up to date window information we update our window information.
1132 */
1133 case TCPS_ESTABLISHED:
1134 case TCPS_FIN_WAIT_1:
1135 case TCPS_FIN_WAIT_2:
1136 case TCPS_CLOSE_WAIT:
1137 case TCPS_CLOSING:
1138 case TCPS_LAST_ACK:
1139 case TCPS_TIME_WAIT:
1140
1141 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1142 if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1143 tcpstat.tcps_rcvdupack++;
1144 /*
1145 * If we have outstanding data (other than
1146 * a window probe), this is a completely
1147 * duplicate ack (ie, window info didn't
1148 * change), the ack is the biggest we've
1149 * seen and we've seen exactly our rexmt
1150 * threshhold of them, assume a packet
1151 * has been dropped and retransmit it.
1152 * Kludge snd_nxt & the congestion
1153 * window so we send only this one
1154 * packet.
1155 *
1156 * We know we're losing at the current
1157 * window size so do congestion avoidance
1158 * (set ssthresh to half the current window
1159 * and pull our congestion window back to
1160 * the new ssthresh).
1161 *
1162 * Dup acks mean that packets have left the
1163 * network (they're now cached at the receiver)
1164 * so bump cwnd by the amount in the receiver
1165 * to keep a constant cwnd packets in the
1166 * network.
1167 */
1168 if (tp->t_timer[TCPT_REXMT] == 0 ||
1169 ti->ti_ack != tp->snd_una)
1170 tp->t_dupacks = 0;
1171 else if (++tp->t_dupacks == tcprexmtthresh) {
1172 tcp_seq onxt = tp->snd_nxt;
1173 u_int win =
1174 min(tp->snd_wnd, tp->snd_cwnd) /
1175 2 / tp->t_segsz;
1176
1177 if (win < 2)
1178 win = 2;
1179 tp->snd_ssthresh = win * tp->t_segsz;
1180 tp->t_timer[TCPT_REXMT] = 0;
1181 tp->t_rtt = 0;
1182 tp->snd_nxt = ti->ti_ack;
1183 tp->snd_cwnd = tp->t_segsz;
1184 (void) tcp_output(tp);
1185 tp->snd_cwnd = tp->snd_ssthresh +
1186 tp->t_segsz * tp->t_dupacks;
1187 if (SEQ_GT(onxt, tp->snd_nxt))
1188 tp->snd_nxt = onxt;
1189 goto drop;
1190 } else if (tp->t_dupacks > tcprexmtthresh) {
1191 tp->snd_cwnd += tp->t_segsz;
1192 (void) tcp_output(tp);
1193 goto drop;
1194 }
1195 } else
1196 tp->t_dupacks = 0;
1197 break;
1198 }
1199 /*
1200 * If the congestion window was inflated to account
1201 * for the other side's cached packets, retract it.
1202 */
1203 if (tp->t_dupacks >= tcprexmtthresh &&
1204 tp->snd_cwnd > tp->snd_ssthresh)
1205 tp->snd_cwnd = tp->snd_ssthresh;
1206 tp->t_dupacks = 0;
1207 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1208 tcpstat.tcps_rcvacktoomuch++;
1209 goto dropafterack;
1210 }
1211 acked = ti->ti_ack - tp->snd_una;
1212 tcpstat.tcps_rcvackpack++;
1213 tcpstat.tcps_rcvackbyte += acked;
1214
1215 /*
1216 * If we have a timestamp reply, update smoothed
1217 * round trip time. If no timestamp is present but
1218 * transmit timer is running and timed sequence
1219 * number was acked, update smoothed round trip time.
1220 * Since we now have an rtt measurement, cancel the
1221 * timer backoff (cf., Phil Karn's retransmit alg.).
1222 * Recompute the initial retransmit timer.
1223 */
1224 if (opti.ts_present)
1225 tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
1226 else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1227 tcp_xmit_timer(tp,tp->t_rtt);
1228
1229 /*
1230 * If all outstanding data is acked, stop retransmit
1231 * timer and remember to restart (more output or persist).
1232 * If there is more data to be acked, restart retransmit
1233 * timer, using current (possibly backed-off) value.
1234 */
1235 if (ti->ti_ack == tp->snd_max) {
1236 tp->t_timer[TCPT_REXMT] = 0;
1237 needoutput = 1;
1238 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1239 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1240 /*
1241 * When new data is acked, open the congestion window.
1242 * If the window gives us less than ssthresh packets
1243 * in flight, open exponentially (segsz per packet).
1244 * Otherwise open linearly: segsz per window
1245 * (segsz^2 / cwnd per packet), plus a constant
1246 * fraction of a packet (segsz/8) to help larger windows
1247 * open quickly enough.
1248 */
1249 {
1250 register u_int cw = tp->snd_cwnd;
1251 register u_int incr = tp->t_segsz;
1252
1253 if (cw > tp->snd_ssthresh)
1254 incr = incr * incr / cw;
1255 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1256 }
1257 if (acked > so->so_snd.sb_cc) {
1258 tp->snd_wnd -= so->so_snd.sb_cc;
1259 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1260 ourfinisacked = 1;
1261 } else {
1262 sbdrop(&so->so_snd, acked);
1263 tp->snd_wnd -= acked;
1264 ourfinisacked = 0;
1265 }
1266 sowwakeup(so);
1267 tp->snd_una = ti->ti_ack;
1268 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1269 tp->snd_nxt = tp->snd_una;
1270
1271 switch (tp->t_state) {
1272
1273 /*
1274 * In FIN_WAIT_1 STATE in addition to the processing
1275 * for the ESTABLISHED state if our FIN is now acknowledged
1276 * then enter FIN_WAIT_2.
1277 */
1278 case TCPS_FIN_WAIT_1:
1279 if (ourfinisacked) {
1280 /*
1281 * If we can't receive any more
1282 * data, then closing user can proceed.
1283 * Starting the timer is contrary to the
1284 * specification, but if we don't get a FIN
1285 * we'll hang forever.
1286 */
1287 if (so->so_state & SS_CANTRCVMORE) {
1288 soisdisconnected(so);
1289 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1290 }
1291 tp->t_state = TCPS_FIN_WAIT_2;
1292 }
1293 break;
1294
1295 /*
1296 * In CLOSING STATE in addition to the processing for
1297 * the ESTABLISHED state if the ACK acknowledges our FIN
1298 * then enter the TIME-WAIT state, otherwise ignore
1299 * the segment.
1300 */
1301 case TCPS_CLOSING:
1302 if (ourfinisacked) {
1303 tp->t_state = TCPS_TIME_WAIT;
1304 tcp_canceltimers(tp);
1305 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1306 soisdisconnected(so);
1307 }
1308 break;
1309
1310 /*
1311 * In LAST_ACK, we may still be waiting for data to drain
1312 * and/or to be acked, as well as for the ack of our FIN.
1313 * If our FIN is now acknowledged, delete the TCB,
1314 * enter the closed state and return.
1315 */
1316 case TCPS_LAST_ACK:
1317 if (ourfinisacked) {
1318 tp = tcp_close(tp);
1319 goto drop;
1320 }
1321 break;
1322
1323 /*
1324 * In TIME_WAIT state the only thing that should arrive
1325 * is a retransmission of the remote FIN. Acknowledge
1326 * it and restart the finack timer.
1327 */
1328 case TCPS_TIME_WAIT:
1329 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1330 goto dropafterack;
1331 }
1332 }
1333
1334 step6:
1335 /*
1336 * Update window information.
1337 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1338 */
1339 if (((tiflags & TH_ACK) && SEQ_LT(tp->snd_wl1, ti->ti_seq)) ||
1340 (tp->snd_wl1 == ti->ti_seq && SEQ_LT(tp->snd_wl2, ti->ti_ack)) ||
1341 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)) {
1342 /* keep track of pure window updates */
1343 if (ti->ti_len == 0 &&
1344 tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1345 tcpstat.tcps_rcvwinupd++;
1346 tp->snd_wnd = tiwin;
1347 tp->snd_wl1 = ti->ti_seq;
1348 tp->snd_wl2 = ti->ti_ack;
1349 if (tp->snd_wnd > tp->max_sndwnd)
1350 tp->max_sndwnd = tp->snd_wnd;
1351 needoutput = 1;
1352 }
1353
1354 /*
1355 * Process segments with URG.
1356 */
1357 if ((tiflags & TH_URG) && ti->ti_urp &&
1358 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1359 /*
1360 * This is a kludge, but if we receive and accept
1361 * random urgent pointers, we'll crash in
1362 * soreceive. It's hard to imagine someone
1363 * actually wanting to send this much urgent data.
1364 */
1365 if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1366 ti->ti_urp = 0; /* XXX */
1367 tiflags &= ~TH_URG; /* XXX */
1368 goto dodata; /* XXX */
1369 }
1370 /*
1371 * If this segment advances the known urgent pointer,
1372 * then mark the data stream. This should not happen
1373 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1374 * a FIN has been received from the remote side.
1375 * In these states we ignore the URG.
1376 *
1377 * According to RFC961 (Assigned Protocols),
1378 * the urgent pointer points to the last octet
1379 * of urgent data. We continue, however,
1380 * to consider it to indicate the first octet
1381 * of data past the urgent section as the original
1382 * spec states (in one of two places).
1383 */
1384 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1385 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1386 so->so_oobmark = so->so_rcv.sb_cc +
1387 (tp->rcv_up - tp->rcv_nxt) - 1;
1388 if (so->so_oobmark == 0)
1389 so->so_state |= SS_RCVATMARK;
1390 sohasoutofband(so);
1391 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1392 }
1393 /*
1394 * Remove out of band data so doesn't get presented to user.
1395 * This can happen independent of advancing the URG pointer,
1396 * but if two URG's are pending at once, some out-of-band
1397 * data may creep in... ick.
1398 */
1399 if (ti->ti_urp <= (u_int16_t) ti->ti_len
1400 #ifdef SO_OOBINLINE
1401 && (so->so_options & SO_OOBINLINE) == 0
1402 #endif
1403 )
1404 tcp_pulloutofband(so, ti, m);
1405 } else
1406 /*
1407 * If no out of band data is expected,
1408 * pull receive urgent pointer along
1409 * with the receive window.
1410 */
1411 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1412 tp->rcv_up = tp->rcv_nxt;
1413 dodata: /* XXX */
1414
1415 /*
1416 * Process the segment text, merging it into the TCP sequencing queue,
1417 * and arranging for acknowledgment of receipt if necessary.
1418 * This process logically involves adjusting tp->rcv_wnd as data
1419 * is presented to the user (this happens in tcp_usrreq.c,
1420 * case PRU_RCVD). If a FIN has already been received on this
1421 * connection then we just ignore the text.
1422 */
1423 if ((ti->ti_len || (tiflags & TH_FIN)) &&
1424 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1425 TCP_REASS(tp, ti, m, so, tiflags);
1426 /*
1427 * Note the amount of data that peer has sent into
1428 * our window, in order to estimate the sender's
1429 * buffer size.
1430 */
1431 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1432 } else {
1433 m_freem(m);
1434 tiflags &= ~TH_FIN;
1435 }
1436
1437 /*
1438 * If FIN is received ACK the FIN and let the user know
1439 * that the connection is closing. Ignore a FIN received before
1440 * the connection is fully established.
1441 */
1442 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1443 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1444 socantrcvmore(so);
1445 tp->t_flags |= TF_ACKNOW;
1446 tp->rcv_nxt++;
1447 }
1448 switch (tp->t_state) {
1449
1450 /*
1451 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1452 */
1453 case TCPS_ESTABLISHED:
1454 tp->t_state = TCPS_CLOSE_WAIT;
1455 break;
1456
1457 /*
1458 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1459 * enter the CLOSING state.
1460 */
1461 case TCPS_FIN_WAIT_1:
1462 tp->t_state = TCPS_CLOSING;
1463 break;
1464
1465 /*
1466 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1467 * starting the time-wait timer, turning off the other
1468 * standard timers.
1469 */
1470 case TCPS_FIN_WAIT_2:
1471 tp->t_state = TCPS_TIME_WAIT;
1472 tcp_canceltimers(tp);
1473 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1474 soisdisconnected(so);
1475 break;
1476
1477 /*
1478 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1479 */
1480 case TCPS_TIME_WAIT:
1481 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1482 break;
1483 }
1484 }
1485 if (so->so_options & SO_DEBUG)
1486 tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1487
1488 /*
1489 * Return any desired output.
1490 */
1491 if (needoutput || (tp->t_flags & TF_ACKNOW))
1492 (void) tcp_output(tp);
1493 return;
1494
1495 badsyn:
1496 /*
1497 * Received a bad SYN. Increment counters and dropwithreset.
1498 */
1499 tcpstat.tcps_badsyn++;
1500 tp = NULL;
1501 goto dropwithreset;
1502
1503 dropafterack:
1504 /*
1505 * Generate an ACK dropping incoming segment if it occupies
1506 * sequence space, where the ACK reflects our state.
1507 */
1508 if (tiflags & TH_RST)
1509 goto drop;
1510 m_freem(m);
1511 tp->t_flags |= TF_ACKNOW;
1512 (void) tcp_output(tp);
1513 return;
1514
1515 dropwithreset:
1516 /*
1517 * Generate a RST, dropping incoming segment.
1518 * Make ACK acceptable to originator of segment.
1519 * Don't bother to respond if destination was broadcast/multicast.
1520 */
1521 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1522 IN_MULTICAST(ti->ti_dst.s_addr))
1523 goto drop;
1524 if (tiflags & TH_ACK)
1525 (void)tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1526 else {
1527 if (tiflags & TH_SYN)
1528 ti->ti_len++;
1529 (void)tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1530 TH_RST|TH_ACK);
1531 }
1532 return;
1533
1534 drop:
1535 /*
1536 * Drop space held by incoming segment and return.
1537 */
1538 if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1539 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1540 m_freem(m);
1541 return;
1542 #ifndef TUBA_INCLUDE
1543 }
1544
1545 void
1546 tcp_dooptions(tp, cp, cnt, ti, oi)
1547 struct tcpcb *tp;
1548 u_char *cp;
1549 int cnt;
1550 struct tcpiphdr *ti;
1551 struct tcp_opt_info *oi;
1552 {
1553 u_int16_t mss;
1554 int opt, optlen;
1555
1556 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1557 opt = cp[0];
1558 if (opt == TCPOPT_EOL)
1559 break;
1560 if (opt == TCPOPT_NOP)
1561 optlen = 1;
1562 else {
1563 optlen = cp[1];
1564 if (optlen <= 0)
1565 break;
1566 }
1567 switch (opt) {
1568
1569 default:
1570 continue;
1571
1572 case TCPOPT_MAXSEG:
1573 if (optlen != TCPOLEN_MAXSEG)
1574 continue;
1575 if (!(ti->ti_flags & TH_SYN))
1576 continue;
1577 bcopy(cp + 2, &mss, sizeof(mss));
1578 oi->maxseg = ntohs(mss);
1579 break;
1580
1581 case TCPOPT_WINDOW:
1582 if (optlen != TCPOLEN_WINDOW)
1583 continue;
1584 if (!(ti->ti_flags & TH_SYN))
1585 continue;
1586 tp->t_flags |= TF_RCVD_SCALE;
1587 tp->requested_s_scale = cp[2];
1588 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
1589 log(LOG_ERR, "TCP: invalid wscale %d from "
1590 "0x%08x, assuming %d\n",
1591 tp->requested_s_scale,
1592 ntohl(ti->ti_src.s_addr),
1593 TCP_MAX_WINSHIFT);
1594 tp->requested_s_scale = TCP_MAX_WINSHIFT;
1595 }
1596 break;
1597
1598 case TCPOPT_TIMESTAMP:
1599 if (optlen != TCPOLEN_TIMESTAMP)
1600 continue;
1601 oi->ts_present = 1;
1602 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
1603 NTOHL(oi->ts_val);
1604 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
1605 NTOHL(oi->ts_ecr);
1606
1607 /*
1608 * A timestamp received in a SYN makes
1609 * it ok to send timestamp requests and replies.
1610 */
1611 if (ti->ti_flags & TH_SYN) {
1612 tp->t_flags |= TF_RCVD_TSTMP;
1613 tp->ts_recent = oi->ts_val;
1614 tp->ts_recent_age = tcp_now;
1615 }
1616 break;
1617 case TCPOPT_SACK_PERMITTED:
1618 if (optlen != TCPOLEN_SACK_PERMITTED)
1619 continue;
1620 if (!(ti->ti_flags & TH_SYN))
1621 continue;
1622 tp->t_flags &= ~TF_CANT_TXSACK;
1623 break;
1624
1625 case TCPOPT_SACK:
1626 if (tp->t_flags & TF_IGNR_RXSACK)
1627 continue;
1628 if (optlen % 8 != 2 || optlen < 10)
1629 continue;
1630 cp += 2;
1631 optlen -= 2;
1632 for (; optlen > 0; cp -= 8, optlen -= 8) {
1633 tcp_seq lwe, rwe;
1634 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
1635 NTOHL(lwe);
1636 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
1637 NTOHL(rwe);
1638 /* tcp_mark_sacked(tp, lwe, rwe); */
1639 }
1640 break;
1641 }
1642 }
1643 }
1644
1645 /*
1646 * Pull out of band byte out of a segment so
1647 * it doesn't appear in the user's data queue.
1648 * It is still reflected in the segment length for
1649 * sequencing purposes.
1650 */
1651 void
1652 tcp_pulloutofband(so, ti, m)
1653 struct socket *so;
1654 struct tcpiphdr *ti;
1655 register struct mbuf *m;
1656 {
1657 int cnt = ti->ti_urp - 1;
1658
1659 while (cnt >= 0) {
1660 if (m->m_len > cnt) {
1661 char *cp = mtod(m, caddr_t) + cnt;
1662 struct tcpcb *tp = sototcpcb(so);
1663
1664 tp->t_iobc = *cp;
1665 tp->t_oobflags |= TCPOOB_HAVEDATA;
1666 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1667 m->m_len--;
1668 return;
1669 }
1670 cnt -= m->m_len;
1671 m = m->m_next;
1672 if (m == 0)
1673 break;
1674 }
1675 panic("tcp_pulloutofband");
1676 }
1677
1678 /*
1679 * Collect new round-trip time estimate
1680 * and update averages and current timeout.
1681 */
1682 void
1683 tcp_xmit_timer(tp, rtt)
1684 register struct tcpcb *tp;
1685 short rtt;
1686 {
1687 register short delta;
1688 short rttmin;
1689
1690 tcpstat.tcps_rttupdated++;
1691 --rtt;
1692 if (tp->t_srtt != 0) {
1693 /*
1694 * srtt is stored as fixed point with 3 bits after the
1695 * binary point (i.e., scaled by 8). The following magic
1696 * is equivalent to the smoothing algorithm in rfc793 with
1697 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1698 * point). Adjust rtt to origin 0.
1699 */
1700 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
1701 if ((tp->t_srtt += delta) <= 0)
1702 tp->t_srtt = 1 << 2;
1703 /*
1704 * We accumulate a smoothed rtt variance (actually, a
1705 * smoothed mean difference), then set the retransmit
1706 * timer to smoothed rtt + 4 times the smoothed variance.
1707 * rttvar is stored as fixed point with 2 bits after the
1708 * binary point (scaled by 4). The following is
1709 * equivalent to rfc793 smoothing with an alpha of .75
1710 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1711 * rfc793's wired-in beta.
1712 */
1713 if (delta < 0)
1714 delta = -delta;
1715 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1716 if ((tp->t_rttvar += delta) <= 0)
1717 tp->t_rttvar = 1 << 2;
1718 } else {
1719 /*
1720 * No rtt measurement yet - use the unsmoothed rtt.
1721 * Set the variance to half the rtt (so our first
1722 * retransmit happens at 3*rtt).
1723 */
1724 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
1725 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
1726 }
1727 tp->t_rtt = 0;
1728 tp->t_rxtshift = 0;
1729
1730 /*
1731 * the retransmit should happen at rtt + 4 * rttvar.
1732 * Because of the way we do the smoothing, srtt and rttvar
1733 * will each average +1/2 tick of bias. When we compute
1734 * the retransmit timer, we want 1/2 tick of rounding and
1735 * 1 extra tick because of +-1/2 tick uncertainty in the
1736 * firing of the timer. The bias will give us exactly the
1737 * 1.5 tick we need. But, because the bias is
1738 * statistical, we have to test that we don't drop below
1739 * the minimum feasible timer (which is 2 ticks).
1740 */
1741 if (tp->t_rttmin > rtt + 2)
1742 rttmin = tp->t_rttmin;
1743 else
1744 rttmin = rtt + 2;
1745 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
1746
1747 /*
1748 * We received an ack for a packet that wasn't retransmitted;
1749 * it is probably safe to discard any error indications we've
1750 * received recently. This isn't quite right, but close enough
1751 * for now (a route might have failed after we sent a segment,
1752 * and the return path might not be symmetrical).
1753 */
1754 tp->t_softerror = 0;
1755 }
1756
1757 /*
1758 * TCP compressed state engine. Currently used to hold compressed
1759 * state for SYN_RECEIVED.
1760 */
1761
1762 u_long syn_cache_count;
1763 u_int32_t syn_hash1, syn_hash2;
1764
1765 #define SYN_HASH(sa, sp, dp) \
1766 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
1767 ((u_int32_t)(sp)))^syn_hash2)))
1768
1769 #define eptosp(ep, e, s) ((struct s *)((char *)(ep) - \
1770 ((char *)(&((struct s *)0)->e) - (char *)0)))
1771
1772 #define SYN_CACHE_RM(sc, p, scp) { \
1773 *(p) = (sc)->sc_next; \
1774 if ((sc)->sc_next) \
1775 (sc)->sc_next->sc_timer += (sc)->sc_timer; \
1776 else { \
1777 (scp)->sch_timer_sum -= (sc)->sc_timer; \
1778 if ((scp)->sch_timer_sum <= 0) \
1779 (scp)->sch_timer_sum = -1; \
1780 /* If need be, fix up the last pointer */ \
1781 if ((scp)->sch_first) \
1782 (scp)->sch_last = eptosp(p, sc_next, syn_cache); \
1783 } \
1784 (scp)->sch_length--; \
1785 syn_cache_count--; \
1786 }
1787
1788 void
1789 syn_cache_insert(sc, prevp, headp)
1790 struct syn_cache *sc;
1791 struct syn_cache ***prevp;
1792 struct syn_cache_head **headp;
1793 {
1794 struct syn_cache_head *scp, *scp2, *sce;
1795 struct syn_cache *sc2;
1796 static u_int timeo_val;
1797 int s;
1798
1799 /* Initialize the hash secrets when adding the first entry */
1800 if (syn_cache_count == 0) {
1801 struct timeval tv;
1802 microtime(&tv);
1803 syn_hash1 = random() ^ (u_long)≻
1804 syn_hash2 = random() ^ tv.tv_usec;
1805 }
1806
1807 sc->sc_hash = SYN_HASH(&sc->sc_src, sc->sc_sport, sc->sc_dport);
1808 sc->sc_next = NULL;
1809 scp = &tcp_syn_cache[sc->sc_hash % tcp_syn_cache_size];
1810 *headp = scp;
1811
1812 /*
1813 * Make sure that we don't overflow the per-bucket
1814 * limit or the total cache size limit.
1815 */
1816 s = splsoftnet();
1817 if (scp->sch_length >= tcp_syn_bucket_limit) {
1818 tcpstat.tcps_sc_bucketoverflow++;
1819 sc2 = scp->sch_first;
1820 scp->sch_first = sc2->sc_next;
1821 if (sc2->sc_ipopts)
1822 (void) m_free(sc2->sc_ipopts);
1823 FREE(sc2, M_PCB);
1824 } else if (syn_cache_count >= tcp_syn_cache_limit) {
1825 tcpstat.tcps_sc_overflowed++;
1826 /*
1827 * The cache is full. Toss the first (i.e, oldest)
1828 * element in this bucket.
1829 */
1830 scp2 = scp;
1831 if (scp2->sch_first == NULL) {
1832 sce = &tcp_syn_cache[tcp_syn_cache_size];
1833 for (++scp2; scp2 != scp; scp2++) {
1834 if (scp2 >= sce)
1835 scp2 = &tcp_syn_cache[0];
1836 if (scp2->sch_first)
1837 break;
1838 }
1839 }
1840 sc2 = scp2->sch_first;
1841 if (sc2 == NULL) {
1842 if (sc->sc_ipopts)
1843 (void) m_free(sc->sc_ipopts);
1844 FREE(sc, M_PCB);
1845 return;
1846 }
1847 if ((scp2->sch_first = sc2->sc_next) == NULL)
1848 scp2->sch_last = NULL;
1849 else
1850 sc2->sc_next->sc_timer += sc2->sc_timer;
1851 if (sc2->sc_ipopts)
1852 (void) m_free(sc2->sc_ipopts);
1853 FREE(sc2, M_PCB);
1854 } else {
1855 scp->sch_length++;
1856 syn_cache_count++;
1857 }
1858 tcpstat.tcps_sc_added++;
1859
1860 /*
1861 * Put it into the bucket.
1862 */
1863 if (scp->sch_first == NULL)
1864 *prevp = &scp->sch_first;
1865 else {
1866 *prevp = &scp->sch_last->sc_next;
1867 tcpstat.tcps_sc_collisions++;
1868 }
1869 **prevp = sc;
1870 scp->sch_last = sc;
1871
1872 /*
1873 * If the timeout value has changed
1874 * 1) force it to fit in a u_char
1875 * 2) Run the timer routine to truncate all
1876 * existing entries to the new timeout value.
1877 */
1878 if (timeo_val != tcp_syn_cache_timeo) {
1879 tcp_syn_cache_timeo = min(tcp_syn_cache_timeo, UCHAR_MAX);
1880 if (timeo_val > tcp_syn_cache_timeo)
1881 syn_cache_timer(timeo_val - tcp_syn_cache_timeo);
1882 timeo_val = tcp_syn_cache_timeo;
1883 }
1884 if (scp->sch_timer_sum > 0)
1885 sc->sc_timer = tcp_syn_cache_timeo - scp->sch_timer_sum;
1886 else {
1887 if (scp->sch_timer_sum == 0) {
1888 /*
1889 * When the bucket timer is 0, it is not in the
1890 * cache queue.
1891 */
1892 scp->sch_headq = tcp_syn_cache_first;
1893 tcp_syn_cache_first = scp;
1894 }
1895 sc->sc_timer = tcp_syn_cache_timeo;
1896 }
1897 scp->sch_timer_sum = tcp_syn_cache_timeo;
1898 splx(s);
1899 }
1900
1901 /*
1902 * Walk down the cache list, decrementing the timer of
1903 * the first element on each entry. If the timer goes
1904 * to zero, remove it and all successive entries with
1905 * a zero timer.
1906 */
1907 void
1908 syn_cache_timer(interval)
1909 int interval;
1910 {
1911 struct syn_cache_head *scp, **pscp;
1912 struct syn_cache *sc, *scn;
1913 int n, s;
1914
1915 pscp = &tcp_syn_cache_first;
1916 scp = tcp_syn_cache_first;
1917 s = splsoftnet();
1918 while (scp) {
1919 /*
1920 * Remove any empty hash buckets
1921 * from the cache queue.
1922 */
1923 if ((sc = scp->sch_first) == NULL) {
1924 *pscp = scp->sch_headq;
1925 scp->sch_headq = NULL;
1926 scp->sch_timer_sum = 0;
1927 scp->sch_first = scp->sch_last = NULL;
1928 scp->sch_length = 0;
1929 scp = *pscp;
1930 continue;
1931 }
1932
1933 scp->sch_timer_sum -= interval;
1934 if (scp->sch_timer_sum <= 0)
1935 scp->sch_timer_sum = -1;
1936 n = interval;
1937 while (sc->sc_timer <= n) {
1938 n -= sc->sc_timer;
1939 scn = sc->sc_next;
1940 tcpstat.tcps_sc_timed_out++;
1941 syn_cache_count--;
1942 if (sc->sc_ipopts)
1943 (void) m_free(sc->sc_ipopts);
1944 FREE(sc, M_PCB);
1945 scp->sch_length--;
1946 if ((sc = scn) == NULL)
1947 break;
1948 }
1949 if ((scp->sch_first = sc) != NULL) {
1950 sc->sc_timer -= n;
1951 pscp = &scp->sch_headq;
1952 scp = scp->sch_headq;
1953 }
1954 }
1955 splx(s);
1956 }
1957
1958 /*
1959 * Find an entry in the syn cache.
1960 */
1961 struct syn_cache *
1962 syn_cache_lookup(ti, prevp, headp)
1963 struct tcpiphdr *ti;
1964 struct syn_cache ***prevp;
1965 struct syn_cache_head **headp;
1966 {
1967 struct syn_cache *sc, **prev;
1968 struct syn_cache_head *head;
1969 u_int32_t hash;
1970 int s;
1971
1972 hash = SYN_HASH(&ti->ti_src, ti->ti_sport, ti->ti_dport);
1973
1974 head = &tcp_syn_cache[hash % tcp_syn_cache_size];
1975 *headp = head;
1976 prev = &head->sch_first;
1977 s = splsoftnet();
1978 for (sc = head->sch_first; sc; prev = &sc->sc_next, sc = sc->sc_next) {
1979 if (sc->sc_hash != hash)
1980 continue;
1981 if (sc->sc_src.s_addr == ti->ti_src.s_addr &&
1982 sc->sc_sport == ti->ti_sport &&
1983 sc->sc_dport == ti->ti_dport &&
1984 sc->sc_dst.s_addr == ti->ti_dst.s_addr) {
1985 *prevp = prev;
1986 splx(s);
1987 return (sc);
1988 }
1989 }
1990 splx(s);
1991 return (NULL);
1992 }
1993
1994 /*
1995 * This function gets called when we receive an ACK for a
1996 * socket in the LISTEN state. We look up the connection
1997 * in the syn cache, and if its there, we pull it out of
1998 * the cache and turn it into a full-blown connection in
1999 * the SYN-RECEIVED state.
2000 *
2001 * The return values may not be immediately obvious, and their effects
2002 * can be subtle, so here they are:
2003 *
2004 * NULL SYN was not found in cache; caller should drop the
2005 * packet and send an RST.
2006 *
2007 * -1 We were unable to create the new connection, and are
2008 * aborting it. An ACK,RST is being sent to the peer
2009 * (unless we got screwey sequence numbners; see below),
2010 * because the 3-way handshake has been completed. Caller
2011 * should not free the mbuf, since we may be using it. If
2012 * we are not, we will free it.
2013 *
2014 * Otherwise, the return value is a pointer to the new socket
2015 * associated with the connection.
2016 */
2017 struct socket *
2018 syn_cache_get(so, m)
2019 struct socket *so;
2020 struct mbuf *m;
2021 {
2022 struct syn_cache *sc, **sc_prev;
2023 struct syn_cache_head *head;
2024 register struct inpcb *inp;
2025 register struct tcpcb *tp = 0;
2026 register struct tcpiphdr *ti;
2027 struct sockaddr_in *sin;
2028 struct mbuf *am;
2029 long win;
2030 int s;
2031
2032 ti = mtod(m, struct tcpiphdr *);
2033 s = splsoftnet();
2034 if ((sc = syn_cache_lookup(ti, &sc_prev, &head)) == NULL) {
2035 splx(s);
2036 return (NULL);
2037 }
2038
2039 win = sbspace(&so->so_rcv);
2040 if (win > TCP_MAXWIN)
2041 win = TCP_MAXWIN;
2042
2043 /*
2044 * Verify the sequence and ack numbers.
2045 */
2046 if ((ti->ti_ack != sc->sc_iss + 1) ||
2047 SEQ_LEQ(ti->ti_seq, sc->sc_irs) ||
2048 SEQ_GT(ti->ti_seq, sc->sc_irs + 1 + win)) {
2049 (void) syn_cache_respond(sc, m, ti, win, 0);
2050 splx(s);
2051 return ((struct socket *)(-1));
2052 }
2053
2054 /* Remove this cache entry */
2055 SYN_CACHE_RM(sc, sc_prev, head);
2056 splx(s);
2057
2058 /*
2059 * Ok, create the full blown connection, and set things up
2060 * as they would have been set up if we had created the
2061 * connection when the SYN arrived. If we can't create
2062 * the connection, abort it.
2063 */
2064 so = sonewconn(so, SS_ISCONNECTED);
2065 if (so == NULL)
2066 goto resetandabort;
2067
2068 inp = sotoinpcb(so);
2069 inp->inp_laddr = sc->sc_dst;
2070 inp->inp_lport = sc->sc_dport;
2071 in_pcbstate(inp, INP_BOUND);
2072 inp->inp_options = ip_srcroute();
2073 if (inp->inp_options == NULL) {
2074 inp->inp_options = sc->sc_ipopts;
2075 sc->sc_ipopts = NULL;
2076 }
2077
2078 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
2079 if (am == NULL)
2080 goto resetandabort;
2081 am->m_len = sizeof(struct sockaddr_in);
2082 sin = mtod(am, struct sockaddr_in *);
2083 sin->sin_family = AF_INET;
2084 sin->sin_len = sizeof(*sin);
2085 sin->sin_addr = sc->sc_src;
2086 sin->sin_port = sc->sc_sport;
2087 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
2088 if (in_pcbconnect(inp, am)) {
2089 (void) m_free(am);
2090 goto resetandabort;
2091 }
2092 (void) m_free(am);
2093
2094 tp = intotcpcb(inp);
2095 if (sc->sc_request_r_scale != 15) {
2096 tp->requested_s_scale = sc->sc_requested_s_scale;
2097 tp->request_r_scale = sc->sc_request_r_scale;
2098 tp->snd_scale = sc->sc_requested_s_scale;
2099 tp->rcv_scale = sc->sc_request_r_scale;
2100 tp->t_flags |= TF_RCVD_SCALE;
2101 }
2102 if (sc->sc_flags & SCF_TIMESTAMP)
2103 tp->t_flags |= TF_RCVD_TSTMP;
2104
2105 tp->t_template = tcp_template(tp);
2106 if (tp->t_template == 0) {
2107 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
2108 so = NULL;
2109 m_freem(m);
2110 goto abort;
2111 }
2112
2113 tp->iss = sc->sc_iss;
2114 tp->irs = sc->sc_irs;
2115 tcp_sendseqinit(tp);
2116 tcp_rcvseqinit(tp);
2117 tp->t_state = TCPS_SYN_RECEIVED;
2118 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
2119 tcpstat.tcps_accepts++;
2120
2121 /* Initialize tp->t_ourmss before we deal with the peer's! */
2122 tp->t_ourmss = sc->sc_ourmaxseg;
2123 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2124
2125 /*
2126 * Initialize the initial congestion window. If we
2127 * had to retransmit the SYN,ACK, we must initialize cwnd
2128 * to 1 segment.
2129 */
2130 tp->snd_cwnd =
2131 TCP_INITIAL_WINDOW((sc->sc_flags & SCF_SYNACK_REXMT) ? 1 :
2132 tcp_init_win, tp->t_peermss);
2133
2134 tcp_rmx_rtt(tp);
2135 tp->snd_wl1 = sc->sc_irs;
2136 tp->rcv_up = sc->sc_irs + 1;
2137
2138 /*
2139 * This is what whould have happened in tcp_ouput() when
2140 * the SYN,ACK was sent.
2141 */
2142 tp->snd_up = tp->snd_una;
2143 tp->snd_max = tp->snd_nxt = tp->iss+1;
2144 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
2145 if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
2146 tp->rcv_adv = tp->rcv_nxt + win;
2147 tp->last_ack_sent = tp->rcv_nxt;
2148
2149 tcpstat.tcps_sc_completed++;
2150 if (sc->sc_ipopts)
2151 (void) m_free(sc->sc_ipopts);
2152 FREE(sc, M_PCB);
2153 return (so);
2154
2155 resetandabort:
2156 (void) tcp_respond(NULL, ti, m, ti->ti_seq+ti->ti_len,
2157 (tcp_seq)0, TH_RST|TH_ACK);
2158 abort:
2159 if (so != NULL)
2160 (void) soabort(so);
2161 if (sc->sc_ipopts)
2162 (void) m_free(sc->sc_ipopts);
2163 FREE(sc, M_PCB);
2164 tcpstat.tcps_sc_aborted++;
2165 return ((struct socket *)(-1));
2166 }
2167
2168 /*
2169 * This function is called when we get a RST for a
2170 * non-existant connection, so that we can see if the
2171 * connection is in the syn cache. If it is, zap it.
2172 */
2173
2174 void
2175 syn_cache_reset(ti)
2176 register struct tcpiphdr *ti;
2177 {
2178 struct syn_cache *sc, **sc_prev;
2179 struct syn_cache_head *head;
2180 int s = splsoftnet();
2181
2182 if ((sc = syn_cache_lookup(ti, &sc_prev, &head)) == NULL) {
2183 splx(s);
2184 return;
2185 }
2186 if (SEQ_LT(ti->ti_seq,sc->sc_irs) ||
2187 SEQ_GT(ti->ti_seq, sc->sc_irs+1)) {
2188 splx(s);
2189 return;
2190 }
2191 SYN_CACHE_RM(sc, sc_prev, head);
2192 splx(s);
2193 tcpstat.tcps_sc_reset++;
2194 if (sc->sc_ipopts)
2195 (void) m_free(sc->sc_ipopts);
2196 FREE(sc, M_PCB);
2197 }
2198
2199 void
2200 syn_cache_unreach(ip, th)
2201 struct ip *ip;
2202 struct tcphdr *th;
2203 {
2204 struct syn_cache *sc, **sc_prev;
2205 struct syn_cache_head *head;
2206 struct tcpiphdr ti2;
2207 int s;
2208
2209 ti2.ti_src.s_addr = ip->ip_dst.s_addr;
2210 ti2.ti_dst.s_addr = ip->ip_src.s_addr;
2211 ti2.ti_sport = th->th_dport;
2212 ti2.ti_dport = th->th_sport;
2213
2214 s = splsoftnet();
2215 if ((sc = syn_cache_lookup(&ti2, &sc_prev, &head)) == NULL) {
2216 splx(s);
2217 return;
2218 }
2219 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
2220 if (ntohl (th->th_seq) != sc->sc_iss) {
2221 splx(s);
2222 return;
2223 }
2224 SYN_CACHE_RM(sc, sc_prev, head);
2225 splx(s);
2226 tcpstat.tcps_sc_unreach++;
2227 if (sc->sc_ipopts)
2228 (void) m_free(sc->sc_ipopts);
2229 FREE(sc, M_PCB);
2230 }
2231
2232 /*
2233 * Given a LISTEN socket and an inbound SYN request, add
2234 * this to the syn cache, and send back a segment:
2235 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
2236 * to the source.
2237 *
2238 * XXX We don't properly handle SYN-with-data!
2239 */
2240
2241 int
2242 syn_cache_add(so, m, optp, optlen, oi)
2243 struct socket *so;
2244 struct mbuf *m;
2245 u_char *optp;
2246 int optlen;
2247 struct tcp_opt_info *oi;
2248 {
2249 register struct tcpiphdr *ti;
2250 struct tcpcb tb, *tp;
2251 long win;
2252 struct syn_cache *sc, **sc_prev;
2253 struct syn_cache_head *scp;
2254 struct mbuf *ipopts;
2255 extern int tcp_do_rfc1323;
2256
2257 tp = sototcpcb(so);
2258 ti = mtod(m, struct tcpiphdr *);
2259
2260 /*
2261 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2262 * in_broadcast() should never return true on a received
2263 * packet with M_BCAST not set.
2264 */
2265 if (m->m_flags & (M_BCAST|M_MCAST) ||
2266 IN_MULTICAST(ti->ti_src.s_addr) ||
2267 IN_MULTICAST(ti->ti_dst.s_addr))
2268 return (0);
2269
2270 /*
2271 * Initialize some local state.
2272 */
2273 win = sbspace(&so->so_rcv);
2274 if (win > TCP_MAXWIN)
2275 win = TCP_MAXWIN;
2276
2277 /*
2278 * Remember the IP options, if any.
2279 */
2280 ipopts = ip_srcroute();
2281
2282 if (optp) {
2283 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
2284 tcp_dooptions(&tb, optp, optlen, ti, oi);
2285 } else
2286 tb.t_flags = 0;
2287
2288 /*
2289 * See if we already have an entry for this connection.
2290 * If we do, resend the SYN,ACK, and remember since the
2291 * initial congestion window must be initialized to 1
2292 * segment when the connection completes.
2293 */
2294 if ((sc = syn_cache_lookup(ti, &sc_prev, &scp)) != NULL) {
2295 tcpstat.tcps_sc_dupesyn++;
2296 sc->sc_flags |= SCF_SYNACK_REXMT;
2297
2298 if (ipopts) {
2299 /*
2300 * If we were remembering a previous source route,
2301 * forget it and use the new one we've been given.
2302 */
2303 if (sc->sc_ipopts)
2304 (void) m_free(sc->sc_ipopts);
2305 sc->sc_ipopts = ipopts;
2306 }
2307
2308 if (syn_cache_respond(sc, m, ti, win, tb.ts_recent) == 0) {
2309 tcpstat.tcps_sndacks++;
2310 tcpstat.tcps_sndtotal++;
2311 }
2312 return (1);
2313 }
2314
2315 MALLOC(sc, struct syn_cache *, sizeof(*sc), M_PCB, M_NOWAIT);
2316 if (sc == NULL) {
2317 if (ipopts)
2318 (void) m_free(ipopts);
2319 return (0);
2320 }
2321
2322 /*
2323 * Fill in the cache, and put the necessary IP and TCP
2324 * options into the reply.
2325 */
2326 sc->sc_src.s_addr = ti->ti_src.s_addr;
2327 sc->sc_dst.s_addr = ti->ti_dst.s_addr;
2328 sc->sc_sport = ti->ti_sport;
2329 sc->sc_dport = ti->ti_dport;
2330 sc->sc_flags = 0;
2331 sc->sc_ipopts = ipopts;
2332 sc->sc_irs = ti->ti_seq;
2333 sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
2334 sc->sc_peermaxseg = oi->maxseg;
2335 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
2336 m->m_pkthdr.rcvif : NULL);
2337 if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
2338 sc->sc_flags |= SCF_TIMESTAMP;
2339 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2340 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2341 sc->sc_requested_s_scale = tb.requested_s_scale;
2342 sc->sc_request_r_scale = 0;
2343 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
2344 TCP_MAXWIN << sc->sc_request_r_scale <
2345 so->so_rcv.sb_hiwat)
2346 sc->sc_request_r_scale++;
2347 } else {
2348 sc->sc_requested_s_scale = 15;
2349 sc->sc_request_r_scale = 15;
2350 }
2351 if (syn_cache_respond(sc, m, ti, win, tb.ts_recent) == 0) {
2352 syn_cache_insert(sc, &sc_prev, &scp);
2353 tcpstat.tcps_sndacks++;
2354 tcpstat.tcps_sndtotal++;
2355 } else {
2356 if (sc->sc_ipopts)
2357 (void) m_free(sc->sc_ipopts);
2358 FREE(sc, M_PCB);
2359 tcpstat.tcps_sc_dropped++;
2360 }
2361 return (1);
2362 }
2363
2364 int
2365 syn_cache_respond(sc, m, ti, win, ts)
2366 struct syn_cache *sc;
2367 struct mbuf *m;
2368 register struct tcpiphdr *ti;
2369 long win;
2370 u_long ts;
2371 {
2372 u_int8_t *optp;
2373 int optlen;
2374
2375 /*
2376 * Tack on the TCP options. If there isn't enough trailing
2377 * space for them, move up the fixed header to make space.
2378 */
2379 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
2380 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
2381 if (optlen > M_TRAILINGSPACE(m)) {
2382 if (M_LEADINGSPACE(m) >= optlen) {
2383 m->m_data -= optlen;
2384 m->m_len += optlen;
2385 } else {
2386 struct mbuf *m0 = m;
2387 if ((m = m_gethdr(M_DONTWAIT, MT_HEADER)) == NULL) {
2388 m_freem(m0);
2389 return (ENOBUFS);
2390 }
2391 MH_ALIGN(m, sizeof(*ti) + optlen);
2392 m->m_next = m0; /* this gets freed below */
2393 }
2394 bcopy((caddr_t)ti, mtod(m, caddr_t), sizeof(*ti));
2395 ti = mtod(m, struct tcpiphdr *);
2396 }
2397
2398 optp = (u_int8_t *)(ti + 1);
2399 optp[0] = TCPOPT_MAXSEG;
2400 optp[1] = 4;
2401 optp[2] = (sc->sc_ourmaxseg >> 8) & 0xff;
2402 optp[3] = sc->sc_ourmaxseg & 0xff;
2403 optlen = 4;
2404
2405 if (sc->sc_request_r_scale != 15) {
2406 *((u_int32_t *)(optp + optlen)) = htonl(TCPOPT_NOP << 24 |
2407 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
2408 sc->sc_request_r_scale);
2409 optlen += 4;
2410 }
2411
2412 if (sc->sc_flags & SCF_TIMESTAMP) {
2413 u_int32_t *lp = (u_int32_t *)(optp + optlen);
2414 /* Form timestamp option as shown in appendix A of RFC 1323. */
2415 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
2416 *lp++ = htonl(tcp_now);
2417 *lp = htonl(ts);
2418 optlen += TCPOLEN_TSTAMP_APPA;
2419 }
2420
2421 /*
2422 * Toss any trailing mbufs. No need to worry about
2423 * m_len and m_pkthdr.len, since tcp_respond() will
2424 * unconditionally set them.
2425 */
2426 if (m->m_next) {
2427 m_freem(m->m_next);
2428 m->m_next = NULL;
2429 }
2430
2431 /*
2432 * Fill in the fields that tcp_respond() will not touch, and
2433 * then send the response.
2434 */
2435 ti->ti_off = (sizeof(struct tcphdr) + optlen) >> 2;
2436 ti->ti_win = htons(win);
2437 return (tcp_respond(NULL, ti, m, sc->sc_irs + 1, sc->sc_iss,
2438 TH_SYN|TH_ACK));
2439 }
2440 #endif /* TUBA_INCLUDE */
2441