tcp_input.c revision 1.58 1 /* $NetBSD: tcp_input.c,v 1.58 1998/05/06 01:21:20 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 extern u_long sb_max;
118
119 #endif /* TUBA_INCLUDE */
120 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
121
122 /* for modulo comparisons of timestamps */
123 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
124 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
125
126 /*
127 * Macro to compute ACK transmission behavior. Delay the ACK unless
128 * we have already delayed an ACK (must send an ACK every two segments).
129 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
130 * option is enabled.
131 */
132 #define TCP_SETUP_ACK(tp, ti) \
133 do { \
134 if ((tp)->t_flags & TF_DELACK || \
135 (tcp_ack_on_push && (ti)->ti_flags & TH_PUSH)) \
136 tp->t_flags |= TF_ACKNOW; \
137 else \
138 TCP_SET_DELACK(tp); \
139 } while (0)
140
141 /*
142 * Insert segment ti into reassembly queue of tcp with
143 * control block tp. Return TH_FIN if reassembly now includes
144 * a segment with FIN. The macro form does the common case inline
145 * (segment is the next to be received on an established connection,
146 * and the queue is empty), avoiding linkage into and removal
147 * from the queue and repetition of various conversions.
148 * Set DELACK for segments received in order, but ack immediately
149 * when segments are out of order (so fast retransmit can work).
150 */
151 #define TCP_REASS(tp, ti, m, so, flags) { \
152 if ((ti)->ti_seq == (tp)->rcv_nxt && \
153 (tp)->segq.lh_first == NULL && \
154 (tp)->t_state == TCPS_ESTABLISHED) { \
155 TCP_SETUP_ACK(tp, ti); \
156 (tp)->rcv_nxt += (ti)->ti_len; \
157 flags = (ti)->ti_flags & TH_FIN; \
158 tcpstat.tcps_rcvpack++;\
159 tcpstat.tcps_rcvbyte += (ti)->ti_len;\
160 sbappend(&(so)->so_rcv, (m)); \
161 sorwakeup(so); \
162 } else { \
163 (flags) = tcp_reass((tp), (ti), (m)); \
164 tp->t_flags |= TF_ACKNOW; \
165 } \
166 }
167 #ifndef TUBA_INCLUDE
168
169 int
170 tcp_reass(tp, ti, m)
171 register struct tcpcb *tp;
172 register struct tcpiphdr *ti;
173 struct mbuf *m;
174 {
175 register struct ipqent *p, *q, *nq, *tiqe = NULL;
176 struct socket *so = tp->t_inpcb->inp_socket;
177 int pkt_flags;
178 tcp_seq pkt_seq;
179 unsigned pkt_len;
180 u_long rcvpartdupbyte = 0;
181 u_long rcvoobyte;
182
183 /*
184 * Call with ti==0 after become established to
185 * force pre-ESTABLISHED data up to user socket.
186 */
187 if (ti == 0)
188 goto present;
189
190 rcvoobyte = ti->ti_len;
191 /*
192 * Copy these to local variables because the tcpiphdr
193 * gets munged while we are collapsing mbufs.
194 */
195 pkt_seq = ti->ti_seq;
196 pkt_len = ti->ti_len;
197 pkt_flags = ti->ti_flags;
198 /*
199 * Find a segment which begins after this one does.
200 */
201 for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
202 nq = q->ipqe_q.le_next;
203 /*
204 * If the received segment is just right after this
205 * fragment, merge the two together and then check
206 * for further overlaps.
207 */
208 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
209 #ifdef TCPREASS_DEBUG
210 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
211 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
212 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
213 #endif
214 pkt_len += q->ipqe_len;
215 pkt_flags |= q->ipqe_flags;
216 pkt_seq = q->ipqe_seq;
217 m_cat(q->ipqe_m, m);
218 m = q->ipqe_m;
219 goto free_ipqe;
220 }
221 /*
222 * If the received segment is completely past this
223 * fragment, we need to go the next fragment.
224 */
225 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
226 p = q;
227 continue;
228 }
229 /*
230 * If the fragment is past the received segment,
231 * it (or any following) can't be concatenated.
232 */
233 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
234 break;
235 /*
236 * We've received all the data in this segment before.
237 * mark it as a duplicate and return.
238 */
239 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
240 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
241 tcpstat.tcps_rcvduppack++;
242 tcpstat.tcps_rcvdupbyte += pkt_len;
243 m_freem(m);
244 if (tiqe != NULL)
245 FREE(tiqe, M_IPQ);
246 return (0);
247 }
248 /*
249 * Received segment completely overlaps this fragment
250 * so we drop the fragment (this keeps the temporal
251 * ordering of segments correct).
252 */
253 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
254 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
255 rcvpartdupbyte += q->ipqe_len;
256 m_freem(q->ipqe_m);
257 goto free_ipqe;
258 }
259 /*
260 * RX'ed segment extends past the end of the
261 * fragment. Drop the overlapping bytes. Then
262 * merge the fragment and segment then treat as
263 * a longer received packet.
264 */
265 if (SEQ_LT(q->ipqe_seq, pkt_seq)
266 && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
267 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
268 #ifdef TCPREASS_DEBUG
269 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
270 tp, overlap,
271 pkt_seq, pkt_seq + pkt_len, pkt_len);
272 #endif
273 m_adj(m, overlap);
274 rcvpartdupbyte += overlap;
275 m_cat(q->ipqe_m, m);
276 m = q->ipqe_m;
277 pkt_seq = q->ipqe_seq;
278 pkt_len += q->ipqe_len - overlap;
279 rcvoobyte -= overlap;
280 goto free_ipqe;
281 }
282 /*
283 * RX'ed segment extends past the front of the
284 * fragment. Drop the overlapping bytes on the
285 * received packet. The packet will then be
286 * contatentated with this fragment a bit later.
287 */
288 if (SEQ_GT(q->ipqe_seq, pkt_seq)
289 && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
290 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
291 #ifdef TCPREASS_DEBUG
292 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
293 tp, overlap,
294 pkt_seq, pkt_seq + pkt_len, pkt_len);
295 #endif
296 m_adj(m, -overlap);
297 pkt_len -= overlap;
298 rcvpartdupbyte += overlap;
299 rcvoobyte -= overlap;
300 }
301 /*
302 * If the received segment immediates precedes this
303 * fragment then tack the fragment onto this segment
304 * and reinsert the data.
305 */
306 if (q->ipqe_seq == pkt_seq + pkt_len) {
307 #ifdef TCPREASS_DEBUG
308 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
309 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
310 pkt_seq, pkt_seq + pkt_len, pkt_len);
311 #endif
312 pkt_len += q->ipqe_len;
313 pkt_flags |= q->ipqe_flags;
314 m_cat(m, q->ipqe_m);
315 LIST_REMOVE(q, ipqe_q);
316 LIST_REMOVE(q, ipqe_timeq);
317 if (tiqe == NULL) {
318 tiqe = q;
319 } else {
320 FREE(q, M_IPQ);
321 }
322 break;
323 }
324 /*
325 * If the fragment is before the segment, remember it.
326 * When this loop is terminated, p will contain the
327 * pointer to fragment that is right before the received
328 * segment.
329 */
330 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
331 p = q;
332
333 continue;
334
335 /*
336 * This is a common operation. It also will allow
337 * to save doing a malloc/free in most instances.
338 */
339 free_ipqe:
340 LIST_REMOVE(q, ipqe_q);
341 LIST_REMOVE(q, ipqe_timeq);
342 if (tiqe == NULL) {
343 tiqe = q;
344 } else {
345 FREE(q, M_IPQ);
346 }
347 }
348
349 /*
350 * Allocate a new queue entry since the received segment did not
351 * collapse onto any other out-of-order block; thus we are allocating
352 * a new block. If it had collapsed, tiqe would not be NULL and
353 * we would be reusing it.
354 * XXX If we can't, just drop the packet. XXX
355 */
356 if (tiqe == NULL) {
357 MALLOC(tiqe, struct ipqent *, sizeof (struct ipqent), M_IPQ, M_NOWAIT);
358 if (tiqe == NULL) {
359 tcpstat.tcps_rcvmemdrop++;
360 m_freem(m);
361 return (0);
362 }
363 }
364
365 /*
366 * Update the counters.
367 */
368 tcpstat.tcps_rcvoopack++;
369 tcpstat.tcps_rcvoobyte += rcvoobyte;
370 if (rcvpartdupbyte) {
371 tcpstat.tcps_rcvpartduppack++;
372 tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
373 }
374
375 /*
376 * Insert the new fragment queue entry into both queues.
377 */
378 tiqe->ipqe_m = m;
379 tiqe->ipqe_seq = pkt_seq;
380 tiqe->ipqe_len = pkt_len;
381 tiqe->ipqe_flags = pkt_flags;
382 if (p == NULL) {
383 LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
384 #ifdef TCPREASS_DEBUG
385 if (tiqe->ipqe_seq != tp->rcv_nxt)
386 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
387 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
388 #endif
389 } else {
390 LIST_INSERT_AFTER(p, tiqe, ipqe_q);
391 #ifdef TCPREASS_DEBUG
392 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
393 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
394 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
395 #endif
396 }
397
398 LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
399
400 present:
401 /*
402 * Present data to user, advancing rcv_nxt through
403 * completed sequence space.
404 */
405 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
406 return (0);
407 q = tp->segq.lh_first;
408 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
409 return (0);
410 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
411 return (0);
412
413 tp->rcv_nxt += q->ipqe_len;
414 pkt_flags = q->ipqe_flags & TH_FIN;
415
416 LIST_REMOVE(q, ipqe_q);
417 LIST_REMOVE(q, ipqe_timeq);
418 if (so->so_state & SS_CANTRCVMORE)
419 m_freem(q->ipqe_m);
420 else
421 sbappend(&so->so_rcv, q->ipqe_m);
422 FREE(q, M_IPQ);
423 sorwakeup(so);
424 return (pkt_flags);
425 }
426
427 /*
428 * TCP input routine, follows pages 65-76 of the
429 * protocol specification dated September, 1981 very closely.
430 */
431 void
432 #if __STDC__
433 tcp_input(struct mbuf *m, ...)
434 #else
435 tcp_input(m, va_alist)
436 register struct mbuf *m;
437 #endif
438 {
439 register struct tcpiphdr *ti;
440 register struct inpcb *inp;
441 caddr_t optp = NULL;
442 int optlen = 0;
443 int len, tlen, off, hdroptlen;
444 register struct tcpcb *tp = 0;
445 register int tiflags;
446 struct socket *so = NULL;
447 int todrop, acked, ourfinisacked, needoutput = 0;
448 short ostate = 0;
449 int iss = 0;
450 u_long tiwin;
451 struct tcp_opt_info opti;
452 int iphlen;
453 va_list ap;
454
455 va_start(ap, m);
456 iphlen = va_arg(ap, int);
457 va_end(ap);
458
459 tcpstat.tcps_rcvtotal++;
460
461 opti.ts_present = 0;
462 opti.maxseg = 0;
463
464 /*
465 * Get IP and TCP header together in first mbuf.
466 * Note: IP leaves IP header in first mbuf.
467 */
468 ti = mtod(m, struct tcpiphdr *);
469 if (iphlen > sizeof (struct ip))
470 ip_stripoptions(m, (struct mbuf *)0);
471 if (m->m_len < sizeof (struct tcpiphdr)) {
472 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
473 tcpstat.tcps_rcvshort++;
474 return;
475 }
476 ti = mtod(m, struct tcpiphdr *);
477 }
478
479 /*
480 * Checksum extended TCP header and data.
481 */
482 tlen = ((struct ip *)ti)->ip_len;
483 len = sizeof (struct ip) + tlen;
484 bzero(ti->ti_x1, sizeof ti->ti_x1);
485 ti->ti_len = (u_int16_t)tlen;
486 HTONS(ti->ti_len);
487 if ((ti->ti_sum = in_cksum(m, len)) != 0) {
488 tcpstat.tcps_rcvbadsum++;
489 goto drop;
490 }
491 #endif /* TUBA_INCLUDE */
492
493 /*
494 * Check that TCP offset makes sense,
495 * pull out TCP options and adjust length. XXX
496 */
497 off = ti->ti_off << 2;
498 if (off < sizeof (struct tcphdr) || off > tlen) {
499 tcpstat.tcps_rcvbadoff++;
500 goto drop;
501 }
502 tlen -= off;
503 ti->ti_len = tlen;
504 if (off > sizeof (struct tcphdr)) {
505 if (m->m_len < sizeof(struct ip) + off) {
506 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
507 tcpstat.tcps_rcvshort++;
508 return;
509 }
510 ti = mtod(m, struct tcpiphdr *);
511 }
512 optlen = off - sizeof (struct tcphdr);
513 optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
514 /*
515 * Do quick retrieval of timestamp options ("options
516 * prediction?"). If timestamp is the only option and it's
517 * formatted as recommended in RFC 1323 appendix A, we
518 * quickly get the values now and not bother calling
519 * tcp_dooptions(), etc.
520 */
521 if ((optlen == TCPOLEN_TSTAMP_APPA ||
522 (optlen > TCPOLEN_TSTAMP_APPA &&
523 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
524 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
525 (ti->ti_flags & TH_SYN) == 0) {
526 opti.ts_present = 1;
527 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
528 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
529 optp = NULL; /* we've parsed the options */
530 }
531 }
532 tiflags = ti->ti_flags;
533
534 /*
535 * Convert TCP protocol specific fields to host format.
536 */
537 NTOHL(ti->ti_seq);
538 NTOHL(ti->ti_ack);
539 NTOHS(ti->ti_win);
540 NTOHS(ti->ti_urp);
541
542 /*
543 * Locate pcb for segment.
544 */
545 findpcb:
546 inp = in_pcblookup_connect(&tcbtable, ti->ti_src, ti->ti_sport,
547 ti->ti_dst, ti->ti_dport);
548 if (inp == 0) {
549 ++tcpstat.tcps_pcbhashmiss;
550 inp = in_pcblookup_bind(&tcbtable, ti->ti_dst, ti->ti_dport);
551 if (inp == 0) {
552 ++tcpstat.tcps_noport;
553 goto dropwithreset;
554 }
555 }
556
557 /*
558 * If the state is CLOSED (i.e., TCB does not exist) then
559 * all data in the incoming segment is discarded.
560 * If the TCB exists but is in CLOSED state, it is embryonic,
561 * but should either do a listen or a connect soon.
562 */
563 tp = intotcpcb(inp);
564 if (tp == 0)
565 goto dropwithreset;
566 if (tp->t_state == TCPS_CLOSED)
567 goto drop;
568
569 /* Unscale the window into a 32-bit value. */
570 if ((tiflags & TH_SYN) == 0)
571 tiwin = ti->ti_win << tp->snd_scale;
572 else
573 tiwin = ti->ti_win;
574
575 so = inp->inp_socket;
576 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
577 if (so->so_options & SO_DEBUG) {
578 ostate = tp->t_state;
579 tcp_saveti = *ti;
580 }
581 if (so->so_options & SO_ACCEPTCONN) {
582 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
583 if (tiflags & TH_RST) {
584 syn_cache_reset(ti);
585 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
586 (TH_ACK|TH_SYN)) {
587 /*
588 * Received a SYN,ACK. This should
589 * never happen while we are in
590 * LISTEN. Send an RST.
591 */
592 goto badsyn;
593 } else if (tiflags & TH_ACK) {
594 so = syn_cache_get(so, m);
595 if (so == NULL) {
596 /*
597 * We don't have a SYN for
598 * this ACK; send an RST.
599 */
600 goto badsyn;
601 } else if (so ==
602 (struct socket *)(-1)) {
603 /*
604 * We were unable to create
605 * the connection. If the
606 * 3-way handshake was
607 * completeed, and RST has
608 * been sent to the peer.
609 * Since the mbuf might be
610 * in use for the reply,
611 * do not free it.
612 */
613 m = NULL;
614 } else {
615 /*
616 * We have created a
617 * full-blown connection.
618 */
619 inp = sotoinpcb(so);
620 tp = intotcpcb(inp);
621 tiwin <<= tp->snd_scale;
622 goto after_listen;
623 }
624 }
625 } else {
626 /*
627 * Received a SYN.
628 */
629 if (in_hosteq(ti->ti_src, ti->ti_dst) &&
630 ti->ti_sport == ti->ti_dport) {
631 /*
632 * LISTEN socket received a SYN
633 * from itself? This can't possibly
634 * be valid; drop the packet.
635 */
636 tcpstat.tcps_badsyn++;
637 goto drop;
638 }
639 /*
640 * SYN looks ok; create compressed TCP
641 * state for it.
642 */
643 if (so->so_qlen <= so->so_qlimit &&
644 syn_cache_add(so, m, optp, optlen, &opti))
645 m = NULL;
646 }
647 goto drop;
648 }
649 }
650
651 after_listen:
652 #ifdef DIAGNOSTIC
653 /*
654 * Should not happen now that all embryonic connections
655 * are handled with compressed state.
656 */
657 if (tp->t_state == TCPS_LISTEN)
658 panic("tcp_input: TCPS_LISTEN");
659 #endif
660
661 /*
662 * Segment received on connection.
663 * Reset idle time and keep-alive timer.
664 */
665 tp->t_idle = 0;
666 if (TCPS_HAVEESTABLISHED(tp->t_state))
667 TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
668
669 /*
670 * Process options.
671 */
672 if (optp)
673 tcp_dooptions(tp, optp, optlen, ti, &opti);
674
675 /*
676 * Header prediction: check for the two common cases
677 * of a uni-directional data xfer. If the packet has
678 * no control flags, is in-sequence, the window didn't
679 * change and we're not retransmitting, it's a
680 * candidate. If the length is zero and the ack moved
681 * forward, we're the sender side of the xfer. Just
682 * free the data acked & wake any higher level process
683 * that was blocked waiting for space. If the length
684 * is non-zero and the ack didn't move, we're the
685 * receiver side. If we're getting packets in-order
686 * (the reassembly queue is empty), add the data to
687 * the socket buffer and note that we need a delayed ack.
688 */
689 if (tp->t_state == TCPS_ESTABLISHED &&
690 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
691 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
692 ti->ti_seq == tp->rcv_nxt &&
693 tiwin && tiwin == tp->snd_wnd &&
694 tp->snd_nxt == tp->snd_max) {
695
696 /*
697 * If last ACK falls within this segment's sequence numbers,
698 * record the timestamp.
699 */
700 if (opti.ts_present &&
701 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
702 SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
703 tp->ts_recent_age = tcp_now;
704 tp->ts_recent = opti.ts_val;
705 }
706
707 if (ti->ti_len == 0) {
708 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
709 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
710 tp->snd_cwnd >= tp->snd_wnd &&
711 tp->t_dupacks < tcprexmtthresh) {
712 /*
713 * this is a pure ack for outstanding data.
714 */
715 ++tcpstat.tcps_predack;
716 if (opti.ts_present)
717 tcp_xmit_timer(tp,
718 tcp_now-opti.ts_ecr+1);
719 else if (tp->t_rtt &&
720 SEQ_GT(ti->ti_ack, tp->t_rtseq))
721 tcp_xmit_timer(tp, tp->t_rtt);
722 acked = ti->ti_ack - tp->snd_una;
723 tcpstat.tcps_rcvackpack++;
724 tcpstat.tcps_rcvackbyte += acked;
725 sbdrop(&so->so_snd, acked);
726 tp->snd_una = ti->ti_ack;
727 m_freem(m);
728
729 /*
730 * If all outstanding data are acked, stop
731 * retransmit timer, otherwise restart timer
732 * using current (possibly backed-off) value.
733 * If process is waiting for space,
734 * wakeup/selwakeup/signal. If data
735 * are ready to send, let tcp_output
736 * decide between more output or persist.
737 */
738 if (tp->snd_una == tp->snd_max)
739 TCP_TIMER_DISARM(tp, TCPT_REXMT);
740 else if (TCP_TIMER_ISARMED(tp,
741 TCPT_PERSIST) == 0)
742 TCP_TIMER_ARM(tp, TCPT_REXMT,
743 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 TCP_TIMER_DISARM(tp, TCPT_REXMT);
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 (TCP_TIMER_ISARMED(tp, 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 TCP_TIMER_DISARM(tp, TCPT_REXMT);
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 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1237 needoutput = 1;
1238 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1239 TCP_TIMER_ARM(tp, 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 TCP_TIMER_ARM(tp, TCPT_2MSL,
1290 tcp_maxidle);
1291 }
1292 tp->t_state = TCPS_FIN_WAIT_2;
1293 }
1294 break;
1295
1296 /*
1297 * In CLOSING STATE in addition to the processing for
1298 * the ESTABLISHED state if the ACK acknowledges our FIN
1299 * then enter the TIME-WAIT state, otherwise ignore
1300 * the segment.
1301 */
1302 case TCPS_CLOSING:
1303 if (ourfinisacked) {
1304 tp->t_state = TCPS_TIME_WAIT;
1305 tcp_canceltimers(tp);
1306 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1307 soisdisconnected(so);
1308 }
1309 break;
1310
1311 /*
1312 * In LAST_ACK, we may still be waiting for data to drain
1313 * and/or to be acked, as well as for the ack of our FIN.
1314 * If our FIN is now acknowledged, delete the TCB,
1315 * enter the closed state and return.
1316 */
1317 case TCPS_LAST_ACK:
1318 if (ourfinisacked) {
1319 tp = tcp_close(tp);
1320 goto drop;
1321 }
1322 break;
1323
1324 /*
1325 * In TIME_WAIT state the only thing that should arrive
1326 * is a retransmission of the remote FIN. Acknowledge
1327 * it and restart the finack timer.
1328 */
1329 case TCPS_TIME_WAIT:
1330 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1331 goto dropafterack;
1332 }
1333 }
1334
1335 step6:
1336 /*
1337 * Update window information.
1338 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1339 */
1340 if (((tiflags & TH_ACK) && SEQ_LT(tp->snd_wl1, ti->ti_seq)) ||
1341 (tp->snd_wl1 == ti->ti_seq && SEQ_LT(tp->snd_wl2, ti->ti_ack)) ||
1342 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)) {
1343 /* keep track of pure window updates */
1344 if (ti->ti_len == 0 &&
1345 tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1346 tcpstat.tcps_rcvwinupd++;
1347 tp->snd_wnd = tiwin;
1348 tp->snd_wl1 = ti->ti_seq;
1349 tp->snd_wl2 = ti->ti_ack;
1350 if (tp->snd_wnd > tp->max_sndwnd)
1351 tp->max_sndwnd = tp->snd_wnd;
1352 needoutput = 1;
1353 }
1354
1355 /*
1356 * Process segments with URG.
1357 */
1358 if ((tiflags & TH_URG) && ti->ti_urp &&
1359 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1360 /*
1361 * This is a kludge, but if we receive and accept
1362 * random urgent pointers, we'll crash in
1363 * soreceive. It's hard to imagine someone
1364 * actually wanting to send this much urgent data.
1365 */
1366 if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1367 ti->ti_urp = 0; /* XXX */
1368 tiflags &= ~TH_URG; /* XXX */
1369 goto dodata; /* XXX */
1370 }
1371 /*
1372 * If this segment advances the known urgent pointer,
1373 * then mark the data stream. This should not happen
1374 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1375 * a FIN has been received from the remote side.
1376 * In these states we ignore the URG.
1377 *
1378 * According to RFC961 (Assigned Protocols),
1379 * the urgent pointer points to the last octet
1380 * of urgent data. We continue, however,
1381 * to consider it to indicate the first octet
1382 * of data past the urgent section as the original
1383 * spec states (in one of two places).
1384 */
1385 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1386 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1387 so->so_oobmark = so->so_rcv.sb_cc +
1388 (tp->rcv_up - tp->rcv_nxt) - 1;
1389 if (so->so_oobmark == 0)
1390 so->so_state |= SS_RCVATMARK;
1391 sohasoutofband(so);
1392 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1393 }
1394 /*
1395 * Remove out of band data so doesn't get presented to user.
1396 * This can happen independent of advancing the URG pointer,
1397 * but if two URG's are pending at once, some out-of-band
1398 * data may creep in... ick.
1399 */
1400 if (ti->ti_urp <= (u_int16_t) ti->ti_len
1401 #ifdef SO_OOBINLINE
1402 && (so->so_options & SO_OOBINLINE) == 0
1403 #endif
1404 )
1405 tcp_pulloutofband(so, ti, m);
1406 } else
1407 /*
1408 * If no out of band data is expected,
1409 * pull receive urgent pointer along
1410 * with the receive window.
1411 */
1412 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1413 tp->rcv_up = tp->rcv_nxt;
1414 dodata: /* XXX */
1415
1416 /*
1417 * Process the segment text, merging it into the TCP sequencing queue,
1418 * and arranging for acknowledgment of receipt if necessary.
1419 * This process logically involves adjusting tp->rcv_wnd as data
1420 * is presented to the user (this happens in tcp_usrreq.c,
1421 * case PRU_RCVD). If a FIN has already been received on this
1422 * connection then we just ignore the text.
1423 */
1424 if ((ti->ti_len || (tiflags & TH_FIN)) &&
1425 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1426 TCP_REASS(tp, ti, m, so, tiflags);
1427 /*
1428 * Note the amount of data that peer has sent into
1429 * our window, in order to estimate the sender's
1430 * buffer size.
1431 */
1432 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1433 } else {
1434 m_freem(m);
1435 tiflags &= ~TH_FIN;
1436 }
1437
1438 /*
1439 * If FIN is received ACK the FIN and let the user know
1440 * that the connection is closing. Ignore a FIN received before
1441 * the connection is fully established.
1442 */
1443 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1444 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1445 socantrcvmore(so);
1446 tp->t_flags |= TF_ACKNOW;
1447 tp->rcv_nxt++;
1448 }
1449 switch (tp->t_state) {
1450
1451 /*
1452 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1453 */
1454 case TCPS_ESTABLISHED:
1455 tp->t_state = TCPS_CLOSE_WAIT;
1456 break;
1457
1458 /*
1459 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1460 * enter the CLOSING state.
1461 */
1462 case TCPS_FIN_WAIT_1:
1463 tp->t_state = TCPS_CLOSING;
1464 break;
1465
1466 /*
1467 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1468 * starting the time-wait timer, turning off the other
1469 * standard timers.
1470 */
1471 case TCPS_FIN_WAIT_2:
1472 tp->t_state = TCPS_TIME_WAIT;
1473 tcp_canceltimers(tp);
1474 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1475 soisdisconnected(so);
1476 break;
1477
1478 /*
1479 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1480 */
1481 case TCPS_TIME_WAIT:
1482 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1483 break;
1484 }
1485 }
1486 if (so->so_options & SO_DEBUG)
1487 tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1488
1489 /*
1490 * Return any desired output.
1491 */
1492 if (needoutput || (tp->t_flags & TF_ACKNOW))
1493 (void) tcp_output(tp);
1494 return;
1495
1496 badsyn:
1497 /*
1498 * Received a bad SYN. Increment counters and dropwithreset.
1499 */
1500 tcpstat.tcps_badsyn++;
1501 tp = NULL;
1502 goto dropwithreset;
1503
1504 dropafterack:
1505 /*
1506 * Generate an ACK dropping incoming segment if it occupies
1507 * sequence space, where the ACK reflects our state.
1508 */
1509 if (tiflags & TH_RST)
1510 goto drop;
1511 m_freem(m);
1512 tp->t_flags |= TF_ACKNOW;
1513 (void) tcp_output(tp);
1514 return;
1515
1516 dropwithreset:
1517 /*
1518 * Generate a RST, dropping incoming segment.
1519 * Make ACK acceptable to originator of segment.
1520 * Don't bother to respond if destination was broadcast/multicast.
1521 */
1522 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1523 IN_MULTICAST(ti->ti_dst.s_addr))
1524 goto drop;
1525 if (tiflags & TH_ACK)
1526 (void)tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1527 else {
1528 if (tiflags & TH_SYN)
1529 ti->ti_len++;
1530 (void)tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1531 TH_RST|TH_ACK);
1532 }
1533 return;
1534
1535 drop:
1536 /*
1537 * Drop space held by incoming segment and return.
1538 */
1539 if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1540 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1541 m_freem(m);
1542 return;
1543 #ifndef TUBA_INCLUDE
1544 }
1545
1546 void
1547 tcp_dooptions(tp, cp, cnt, ti, oi)
1548 struct tcpcb *tp;
1549 u_char *cp;
1550 int cnt;
1551 struct tcpiphdr *ti;
1552 struct tcp_opt_info *oi;
1553 {
1554 u_int16_t mss;
1555 int opt, optlen;
1556
1557 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1558 opt = cp[0];
1559 if (opt == TCPOPT_EOL)
1560 break;
1561 if (opt == TCPOPT_NOP)
1562 optlen = 1;
1563 else {
1564 optlen = cp[1];
1565 if (optlen <= 0)
1566 break;
1567 }
1568 switch (opt) {
1569
1570 default:
1571 continue;
1572
1573 case TCPOPT_MAXSEG:
1574 if (optlen != TCPOLEN_MAXSEG)
1575 continue;
1576 if (!(ti->ti_flags & TH_SYN))
1577 continue;
1578 bcopy(cp + 2, &mss, sizeof(mss));
1579 oi->maxseg = ntohs(mss);
1580 break;
1581
1582 case TCPOPT_WINDOW:
1583 if (optlen != TCPOLEN_WINDOW)
1584 continue;
1585 if (!(ti->ti_flags & TH_SYN))
1586 continue;
1587 tp->t_flags |= TF_RCVD_SCALE;
1588 tp->requested_s_scale = cp[2];
1589 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
1590 log(LOG_ERR, "TCP: invalid wscale %d from "
1591 "0x%08x, assuming %d\n",
1592 tp->requested_s_scale,
1593 ntohl(ti->ti_src.s_addr),
1594 TCP_MAX_WINSHIFT);
1595 tp->requested_s_scale = TCP_MAX_WINSHIFT;
1596 }
1597 break;
1598
1599 case TCPOPT_TIMESTAMP:
1600 if (optlen != TCPOLEN_TIMESTAMP)
1601 continue;
1602 oi->ts_present = 1;
1603 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
1604 NTOHL(oi->ts_val);
1605 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
1606 NTOHL(oi->ts_ecr);
1607
1608 /*
1609 * A timestamp received in a SYN makes
1610 * it ok to send timestamp requests and replies.
1611 */
1612 if (ti->ti_flags & TH_SYN) {
1613 tp->t_flags |= TF_RCVD_TSTMP;
1614 tp->ts_recent = oi->ts_val;
1615 tp->ts_recent_age = tcp_now;
1616 }
1617 break;
1618 case TCPOPT_SACK_PERMITTED:
1619 if (optlen != TCPOLEN_SACK_PERMITTED)
1620 continue;
1621 if (!(ti->ti_flags & TH_SYN))
1622 continue;
1623 tp->t_flags &= ~TF_CANT_TXSACK;
1624 break;
1625
1626 case TCPOPT_SACK:
1627 if (tp->t_flags & TF_IGNR_RXSACK)
1628 continue;
1629 if (optlen % 8 != 2 || optlen < 10)
1630 continue;
1631 cp += 2;
1632 optlen -= 2;
1633 for (; optlen > 0; cp -= 8, optlen -= 8) {
1634 tcp_seq lwe, rwe;
1635 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
1636 NTOHL(lwe);
1637 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
1638 NTOHL(rwe);
1639 /* tcp_mark_sacked(tp, lwe, rwe); */
1640 }
1641 break;
1642 }
1643 }
1644 }
1645
1646 /*
1647 * Pull out of band byte out of a segment so
1648 * it doesn't appear in the user's data queue.
1649 * It is still reflected in the segment length for
1650 * sequencing purposes.
1651 */
1652 void
1653 tcp_pulloutofband(so, ti, m)
1654 struct socket *so;
1655 struct tcpiphdr *ti;
1656 register struct mbuf *m;
1657 {
1658 int cnt = ti->ti_urp - 1;
1659
1660 while (cnt >= 0) {
1661 if (m->m_len > cnt) {
1662 char *cp = mtod(m, caddr_t) + cnt;
1663 struct tcpcb *tp = sototcpcb(so);
1664
1665 tp->t_iobc = *cp;
1666 tp->t_oobflags |= TCPOOB_HAVEDATA;
1667 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1668 m->m_len--;
1669 return;
1670 }
1671 cnt -= m->m_len;
1672 m = m->m_next;
1673 if (m == 0)
1674 break;
1675 }
1676 panic("tcp_pulloutofband");
1677 }
1678
1679 /*
1680 * Collect new round-trip time estimate
1681 * and update averages and current timeout.
1682 */
1683 void
1684 tcp_xmit_timer(tp, rtt)
1685 register struct tcpcb *tp;
1686 short rtt;
1687 {
1688 register short delta;
1689 short rttmin;
1690
1691 tcpstat.tcps_rttupdated++;
1692 --rtt;
1693 if (tp->t_srtt != 0) {
1694 /*
1695 * srtt is stored as fixed point with 3 bits after the
1696 * binary point (i.e., scaled by 8). The following magic
1697 * is equivalent to the smoothing algorithm in rfc793 with
1698 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1699 * point). Adjust rtt to origin 0.
1700 */
1701 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
1702 if ((tp->t_srtt += delta) <= 0)
1703 tp->t_srtt = 1 << 2;
1704 /*
1705 * We accumulate a smoothed rtt variance (actually, a
1706 * smoothed mean difference), then set the retransmit
1707 * timer to smoothed rtt + 4 times the smoothed variance.
1708 * rttvar is stored as fixed point with 2 bits after the
1709 * binary point (scaled by 4). The following is
1710 * equivalent to rfc793 smoothing with an alpha of .75
1711 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1712 * rfc793's wired-in beta.
1713 */
1714 if (delta < 0)
1715 delta = -delta;
1716 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1717 if ((tp->t_rttvar += delta) <= 0)
1718 tp->t_rttvar = 1 << 2;
1719 } else {
1720 /*
1721 * No rtt measurement yet - use the unsmoothed rtt.
1722 * Set the variance to half the rtt (so our first
1723 * retransmit happens at 3*rtt).
1724 */
1725 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
1726 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
1727 }
1728 tp->t_rtt = 0;
1729 tp->t_rxtshift = 0;
1730
1731 /*
1732 * the retransmit should happen at rtt + 4 * rttvar.
1733 * Because of the way we do the smoothing, srtt and rttvar
1734 * will each average +1/2 tick of bias. When we compute
1735 * the retransmit timer, we want 1/2 tick of rounding and
1736 * 1 extra tick because of +-1/2 tick uncertainty in the
1737 * firing of the timer. The bias will give us exactly the
1738 * 1.5 tick we need. But, because the bias is
1739 * statistical, we have to test that we don't drop below
1740 * the minimum feasible timer (which is 2 ticks).
1741 */
1742 if (tp->t_rttmin > rtt + 2)
1743 rttmin = tp->t_rttmin;
1744 else
1745 rttmin = rtt + 2;
1746 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
1747
1748 /*
1749 * We received an ack for a packet that wasn't retransmitted;
1750 * it is probably safe to discard any error indications we've
1751 * received recently. This isn't quite right, but close enough
1752 * for now (a route might have failed after we sent a segment,
1753 * and the return path might not be symmetrical).
1754 */
1755 tp->t_softerror = 0;
1756 }
1757
1758 /*
1759 * TCP compressed state engine. Currently used to hold compressed
1760 * state for SYN_RECEIVED.
1761 */
1762
1763 u_long syn_cache_count;
1764 u_int32_t syn_hash1, syn_hash2;
1765
1766 #define SYN_HASH(sa, sp, dp) \
1767 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
1768 ((u_int32_t)(sp)))^syn_hash2)))
1769
1770 #define eptosp(ep, e, s) ((struct s *)((char *)(ep) - \
1771 ((char *)(&((struct s *)0)->e) - (char *)0)))
1772
1773 #define SYN_CACHE_RM(sc, p, scp) { \
1774 *(p) = (sc)->sc_next; \
1775 if ((sc)->sc_next) \
1776 (sc)->sc_next->sc_timer += (sc)->sc_timer; \
1777 else { \
1778 (scp)->sch_timer_sum -= (sc)->sc_timer; \
1779 if ((scp)->sch_timer_sum <= 0) \
1780 (scp)->sch_timer_sum = -1; \
1781 /* If need be, fix up the last pointer */ \
1782 if ((scp)->sch_first) \
1783 (scp)->sch_last = eptosp(p, sc_next, syn_cache); \
1784 } \
1785 (scp)->sch_length--; \
1786 syn_cache_count--; \
1787 }
1788
1789 void
1790 syn_cache_insert(sc, prevp, headp)
1791 struct syn_cache *sc;
1792 struct syn_cache ***prevp;
1793 struct syn_cache_head **headp;
1794 {
1795 struct syn_cache_head *scp, *scp2, *sce;
1796 struct syn_cache *sc2;
1797 static u_int timeo_val;
1798 int s;
1799
1800 /* Initialize the hash secrets when adding the first entry */
1801 if (syn_cache_count == 0) {
1802 struct timeval tv;
1803 microtime(&tv);
1804 syn_hash1 = random() ^ (u_long)≻
1805 syn_hash2 = random() ^ tv.tv_usec;
1806 }
1807
1808 sc->sc_hash = SYN_HASH(&sc->sc_src, sc->sc_sport, sc->sc_dport);
1809 sc->sc_next = NULL;
1810 scp = &tcp_syn_cache[sc->sc_hash % tcp_syn_cache_size];
1811 *headp = scp;
1812
1813 /*
1814 * Make sure that we don't overflow the per-bucket
1815 * limit or the total cache size limit.
1816 */
1817 s = splsoftnet();
1818 if (scp->sch_length >= tcp_syn_bucket_limit) {
1819 tcpstat.tcps_sc_bucketoverflow++;
1820 sc2 = scp->sch_first;
1821 scp->sch_first = sc2->sc_next;
1822 if (sc2->sc_ipopts)
1823 (void) m_free(sc2->sc_ipopts);
1824 FREE(sc2, M_PCB);
1825 } else if (syn_cache_count >= tcp_syn_cache_limit) {
1826 tcpstat.tcps_sc_overflowed++;
1827 /*
1828 * The cache is full. Toss the first (i.e, oldest)
1829 * element in this bucket.
1830 */
1831 scp2 = scp;
1832 if (scp2->sch_first == NULL) {
1833 sce = &tcp_syn_cache[tcp_syn_cache_size];
1834 for (++scp2; scp2 != scp; scp2++) {
1835 if (scp2 >= sce)
1836 scp2 = &tcp_syn_cache[0];
1837 if (scp2->sch_first)
1838 break;
1839 }
1840 }
1841 sc2 = scp2->sch_first;
1842 if (sc2 == NULL) {
1843 if (sc->sc_ipopts)
1844 (void) m_free(sc->sc_ipopts);
1845 FREE(sc, M_PCB);
1846 return;
1847 }
1848 if ((scp2->sch_first = sc2->sc_next) == NULL)
1849 scp2->sch_last = NULL;
1850 else
1851 sc2->sc_next->sc_timer += sc2->sc_timer;
1852 if (sc2->sc_ipopts)
1853 (void) m_free(sc2->sc_ipopts);
1854 FREE(sc2, M_PCB);
1855 } else {
1856 scp->sch_length++;
1857 syn_cache_count++;
1858 }
1859 tcpstat.tcps_sc_added++;
1860
1861 /*
1862 * Put it into the bucket.
1863 */
1864 if (scp->sch_first == NULL)
1865 *prevp = &scp->sch_first;
1866 else {
1867 *prevp = &scp->sch_last->sc_next;
1868 tcpstat.tcps_sc_collisions++;
1869 }
1870 **prevp = sc;
1871 scp->sch_last = sc;
1872
1873 /*
1874 * If the timeout value has changed
1875 * 1) force it to fit in a u_char
1876 * 2) Run the timer routine to truncate all
1877 * existing entries to the new timeout value.
1878 */
1879 if (timeo_val != tcp_syn_cache_timeo) {
1880 tcp_syn_cache_timeo = min(tcp_syn_cache_timeo, UCHAR_MAX);
1881 if (timeo_val > tcp_syn_cache_timeo)
1882 syn_cache_timer(timeo_val - tcp_syn_cache_timeo);
1883 timeo_val = tcp_syn_cache_timeo;
1884 }
1885 if (scp->sch_timer_sum > 0)
1886 sc->sc_timer = tcp_syn_cache_timeo - scp->sch_timer_sum;
1887 else {
1888 if (scp->sch_timer_sum == 0) {
1889 /*
1890 * When the bucket timer is 0, it is not in the
1891 * cache queue.
1892 */
1893 scp->sch_headq = tcp_syn_cache_first;
1894 tcp_syn_cache_first = scp;
1895 }
1896 sc->sc_timer = tcp_syn_cache_timeo;
1897 }
1898 scp->sch_timer_sum = tcp_syn_cache_timeo;
1899 splx(s);
1900 }
1901
1902 /*
1903 * Walk down the cache list, decrementing the timer of
1904 * the first element on each entry. If the timer goes
1905 * to zero, remove it and all successive entries with
1906 * a zero timer.
1907 */
1908 void
1909 syn_cache_timer(interval)
1910 int interval;
1911 {
1912 struct syn_cache_head *scp, **pscp;
1913 struct syn_cache *sc, *scn;
1914 int n, s;
1915
1916 pscp = &tcp_syn_cache_first;
1917 scp = tcp_syn_cache_first;
1918 s = splsoftnet();
1919 while (scp) {
1920 /*
1921 * Remove any empty hash buckets
1922 * from the cache queue.
1923 */
1924 if ((sc = scp->sch_first) == NULL) {
1925 *pscp = scp->sch_headq;
1926 scp->sch_headq = NULL;
1927 scp->sch_timer_sum = 0;
1928 scp->sch_first = scp->sch_last = NULL;
1929 scp->sch_length = 0;
1930 scp = *pscp;
1931 continue;
1932 }
1933
1934 scp->sch_timer_sum -= interval;
1935 if (scp->sch_timer_sum <= 0)
1936 scp->sch_timer_sum = -1;
1937 n = interval;
1938 while (sc->sc_timer <= n) {
1939 n -= sc->sc_timer;
1940 scn = sc->sc_next;
1941 tcpstat.tcps_sc_timed_out++;
1942 syn_cache_count--;
1943 if (sc->sc_ipopts)
1944 (void) m_free(sc->sc_ipopts);
1945 FREE(sc, M_PCB);
1946 scp->sch_length--;
1947 if ((sc = scn) == NULL)
1948 break;
1949 }
1950 if ((scp->sch_first = sc) != NULL) {
1951 sc->sc_timer -= n;
1952 pscp = &scp->sch_headq;
1953 scp = scp->sch_headq;
1954 }
1955 }
1956 splx(s);
1957 }
1958
1959 /*
1960 * Find an entry in the syn cache.
1961 */
1962 struct syn_cache *
1963 syn_cache_lookup(ti, prevp, headp)
1964 struct tcpiphdr *ti;
1965 struct syn_cache ***prevp;
1966 struct syn_cache_head **headp;
1967 {
1968 struct syn_cache *sc, **prev;
1969 struct syn_cache_head *head;
1970 u_int32_t hash;
1971 int s;
1972
1973 hash = SYN_HASH(&ti->ti_src, ti->ti_sport, ti->ti_dport);
1974
1975 head = &tcp_syn_cache[hash % tcp_syn_cache_size];
1976 *headp = head;
1977 prev = &head->sch_first;
1978 s = splsoftnet();
1979 for (sc = head->sch_first; sc; prev = &sc->sc_next, sc = sc->sc_next) {
1980 if (sc->sc_hash != hash)
1981 continue;
1982 if (sc->sc_src.s_addr == ti->ti_src.s_addr &&
1983 sc->sc_sport == ti->ti_sport &&
1984 sc->sc_dport == ti->ti_dport &&
1985 sc->sc_dst.s_addr == ti->ti_dst.s_addr) {
1986 *prevp = prev;
1987 splx(s);
1988 return (sc);
1989 }
1990 }
1991 splx(s);
1992 return (NULL);
1993 }
1994
1995 /*
1996 * This function gets called when we receive an ACK for a
1997 * socket in the LISTEN state. We look up the connection
1998 * in the syn cache, and if its there, we pull it out of
1999 * the cache and turn it into a full-blown connection in
2000 * the SYN-RECEIVED state.
2001 *
2002 * The return values may not be immediately obvious, and their effects
2003 * can be subtle, so here they are:
2004 *
2005 * NULL SYN was not found in cache; caller should drop the
2006 * packet and send an RST.
2007 *
2008 * -1 We were unable to create the new connection, and are
2009 * aborting it. An ACK,RST is being sent to the peer
2010 * (unless we got screwey sequence numbners; see below),
2011 * because the 3-way handshake has been completed. Caller
2012 * should not free the mbuf, since we may be using it. If
2013 * we are not, we will free it.
2014 *
2015 * Otherwise, the return value is a pointer to the new socket
2016 * associated with the connection.
2017 */
2018 struct socket *
2019 syn_cache_get(so, m)
2020 struct socket *so;
2021 struct mbuf *m;
2022 {
2023 struct syn_cache *sc, **sc_prev;
2024 struct syn_cache_head *head;
2025 register struct inpcb *inp;
2026 register struct tcpcb *tp = 0;
2027 register struct tcpiphdr *ti;
2028 struct sockaddr_in *sin;
2029 struct mbuf *am;
2030 long win;
2031 int s;
2032
2033 ti = mtod(m, struct tcpiphdr *);
2034 s = splsoftnet();
2035 if ((sc = syn_cache_lookup(ti, &sc_prev, &head)) == NULL) {
2036 splx(s);
2037 return (NULL);
2038 }
2039
2040 win = sbspace(&so->so_rcv);
2041 if (win > TCP_MAXWIN)
2042 win = TCP_MAXWIN;
2043
2044 /*
2045 * Verify the sequence and ack numbers.
2046 */
2047 if ((ti->ti_ack != sc->sc_iss + 1) ||
2048 SEQ_LEQ(ti->ti_seq, sc->sc_irs) ||
2049 SEQ_GT(ti->ti_seq, sc->sc_irs + 1 + win)) {
2050 (void) syn_cache_respond(sc, m, ti, win, 0);
2051 splx(s);
2052 return ((struct socket *)(-1));
2053 }
2054
2055 /* Remove this cache entry */
2056 SYN_CACHE_RM(sc, sc_prev, head);
2057 splx(s);
2058
2059 /*
2060 * Ok, create the full blown connection, and set things up
2061 * as they would have been set up if we had created the
2062 * connection when the SYN arrived. If we can't create
2063 * the connection, abort it.
2064 */
2065 so = sonewconn(so, SS_ISCONNECTED);
2066 if (so == NULL)
2067 goto resetandabort;
2068
2069 inp = sotoinpcb(so);
2070 inp->inp_laddr = sc->sc_dst;
2071 inp->inp_lport = sc->sc_dport;
2072 in_pcbstate(inp, INP_BOUND);
2073 inp->inp_options = ip_srcroute();
2074 if (inp->inp_options == NULL) {
2075 inp->inp_options = sc->sc_ipopts;
2076 sc->sc_ipopts = NULL;
2077 }
2078
2079 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
2080 if (am == NULL)
2081 goto resetandabort;
2082 am->m_len = sizeof(struct sockaddr_in);
2083 sin = mtod(am, struct sockaddr_in *);
2084 sin->sin_family = AF_INET;
2085 sin->sin_len = sizeof(*sin);
2086 sin->sin_addr = sc->sc_src;
2087 sin->sin_port = sc->sc_sport;
2088 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
2089 if (in_pcbconnect(inp, am)) {
2090 (void) m_free(am);
2091 goto resetandabort;
2092 }
2093 (void) m_free(am);
2094
2095 tp = intotcpcb(inp);
2096 if (sc->sc_request_r_scale != 15) {
2097 tp->requested_s_scale = sc->sc_requested_s_scale;
2098 tp->request_r_scale = sc->sc_request_r_scale;
2099 tp->snd_scale = sc->sc_requested_s_scale;
2100 tp->rcv_scale = sc->sc_request_r_scale;
2101 tp->t_flags |= TF_RCVD_SCALE;
2102 }
2103 if (sc->sc_flags & SCF_TIMESTAMP)
2104 tp->t_flags |= TF_RCVD_TSTMP;
2105
2106 tp->t_template = tcp_template(tp);
2107 if (tp->t_template == 0) {
2108 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
2109 so = NULL;
2110 m_freem(m);
2111 goto abort;
2112 }
2113
2114 tp->iss = sc->sc_iss;
2115 tp->irs = sc->sc_irs;
2116 tcp_sendseqinit(tp);
2117 tcp_rcvseqinit(tp);
2118 tp->t_state = TCPS_SYN_RECEIVED;
2119 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
2120 tcpstat.tcps_accepts++;
2121
2122 /* Initialize tp->t_ourmss before we deal with the peer's! */
2123 tp->t_ourmss = sc->sc_ourmaxseg;
2124 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2125
2126 /*
2127 * Initialize the initial congestion window. If we
2128 * had to retransmit the SYN,ACK, we must initialize cwnd
2129 * to 1 segment.
2130 */
2131 tp->snd_cwnd =
2132 TCP_INITIAL_WINDOW((sc->sc_flags & SCF_SYNACK_REXMT) ? 1 :
2133 tcp_init_win, tp->t_peermss);
2134
2135 tcp_rmx_rtt(tp);
2136 tp->snd_wl1 = sc->sc_irs;
2137 tp->rcv_up = sc->sc_irs + 1;
2138
2139 /*
2140 * This is what whould have happened in tcp_ouput() when
2141 * the SYN,ACK was sent.
2142 */
2143 tp->snd_up = tp->snd_una;
2144 tp->snd_max = tp->snd_nxt = tp->iss+1;
2145 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2146 if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
2147 tp->rcv_adv = tp->rcv_nxt + win;
2148 tp->last_ack_sent = tp->rcv_nxt;
2149
2150 tcpstat.tcps_sc_completed++;
2151 if (sc->sc_ipopts)
2152 (void) m_free(sc->sc_ipopts);
2153 FREE(sc, M_PCB);
2154 return (so);
2155
2156 resetandabort:
2157 (void) tcp_respond(NULL, ti, m, ti->ti_seq+ti->ti_len,
2158 (tcp_seq)0, TH_RST|TH_ACK);
2159 abort:
2160 if (so != NULL)
2161 (void) soabort(so);
2162 if (sc->sc_ipopts)
2163 (void) m_free(sc->sc_ipopts);
2164 FREE(sc, M_PCB);
2165 tcpstat.tcps_sc_aborted++;
2166 return ((struct socket *)(-1));
2167 }
2168
2169 /*
2170 * This function is called when we get a RST for a
2171 * non-existant connection, so that we can see if the
2172 * connection is in the syn cache. If it is, zap it.
2173 */
2174
2175 void
2176 syn_cache_reset(ti)
2177 register struct tcpiphdr *ti;
2178 {
2179 struct syn_cache *sc, **sc_prev;
2180 struct syn_cache_head *head;
2181 int s = splsoftnet();
2182
2183 if ((sc = syn_cache_lookup(ti, &sc_prev, &head)) == NULL) {
2184 splx(s);
2185 return;
2186 }
2187 if (SEQ_LT(ti->ti_seq,sc->sc_irs) ||
2188 SEQ_GT(ti->ti_seq, sc->sc_irs+1)) {
2189 splx(s);
2190 return;
2191 }
2192 SYN_CACHE_RM(sc, sc_prev, head);
2193 splx(s);
2194 tcpstat.tcps_sc_reset++;
2195 if (sc->sc_ipopts)
2196 (void) m_free(sc->sc_ipopts);
2197 FREE(sc, M_PCB);
2198 }
2199
2200 void
2201 syn_cache_unreach(ip, th)
2202 struct ip *ip;
2203 struct tcphdr *th;
2204 {
2205 struct syn_cache *sc, **sc_prev;
2206 struct syn_cache_head *head;
2207 struct tcpiphdr ti2;
2208 int s;
2209
2210 ti2.ti_src.s_addr = ip->ip_dst.s_addr;
2211 ti2.ti_dst.s_addr = ip->ip_src.s_addr;
2212 ti2.ti_sport = th->th_dport;
2213 ti2.ti_dport = th->th_sport;
2214
2215 s = splsoftnet();
2216 if ((sc = syn_cache_lookup(&ti2, &sc_prev, &head)) == NULL) {
2217 splx(s);
2218 return;
2219 }
2220 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
2221 if (ntohl (th->th_seq) != sc->sc_iss) {
2222 splx(s);
2223 return;
2224 }
2225 SYN_CACHE_RM(sc, sc_prev, head);
2226 splx(s);
2227 tcpstat.tcps_sc_unreach++;
2228 if (sc->sc_ipopts)
2229 (void) m_free(sc->sc_ipopts);
2230 FREE(sc, M_PCB);
2231 }
2232
2233 /*
2234 * Given a LISTEN socket and an inbound SYN request, add
2235 * this to the syn cache, and send back a segment:
2236 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
2237 * to the source.
2238 *
2239 * XXX We don't properly handle SYN-with-data!
2240 */
2241
2242 int
2243 syn_cache_add(so, m, optp, optlen, oi)
2244 struct socket *so;
2245 struct mbuf *m;
2246 u_char *optp;
2247 int optlen;
2248 struct tcp_opt_info *oi;
2249 {
2250 register struct tcpiphdr *ti;
2251 struct tcpcb tb, *tp;
2252 long win;
2253 struct syn_cache *sc, **sc_prev;
2254 struct syn_cache_head *scp;
2255 struct mbuf *ipopts;
2256 extern int tcp_do_rfc1323;
2257
2258 tp = sototcpcb(so);
2259 ti = mtod(m, struct tcpiphdr *);
2260
2261 /*
2262 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2263 * in_broadcast() should never return true on a received
2264 * packet with M_BCAST not set.
2265 */
2266 if (m->m_flags & (M_BCAST|M_MCAST) ||
2267 IN_MULTICAST(ti->ti_src.s_addr) ||
2268 IN_MULTICAST(ti->ti_dst.s_addr))
2269 return (0);
2270
2271 /*
2272 * Initialize some local state.
2273 */
2274 win = sbspace(&so->so_rcv);
2275 if (win > TCP_MAXWIN)
2276 win = TCP_MAXWIN;
2277
2278 /*
2279 * Remember the IP options, if any.
2280 */
2281 ipopts = ip_srcroute();
2282
2283 if (optp) {
2284 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
2285 tcp_dooptions(&tb, optp, optlen, ti, oi);
2286 } else
2287 tb.t_flags = 0;
2288
2289 /*
2290 * See if we already have an entry for this connection.
2291 * If we do, resend the SYN,ACK, and remember since the
2292 * initial congestion window must be initialized to 1
2293 * segment when the connection completes.
2294 */
2295 if ((sc = syn_cache_lookup(ti, &sc_prev, &scp)) != NULL) {
2296 tcpstat.tcps_sc_dupesyn++;
2297 sc->sc_flags |= SCF_SYNACK_REXMT;
2298
2299 if (ipopts) {
2300 /*
2301 * If we were remembering a previous source route,
2302 * forget it and use the new one we've been given.
2303 */
2304 if (sc->sc_ipopts)
2305 (void) m_free(sc->sc_ipopts);
2306 sc->sc_ipopts = ipopts;
2307 }
2308
2309 if (syn_cache_respond(sc, m, ti, win, tb.ts_recent) == 0) {
2310 tcpstat.tcps_sndacks++;
2311 tcpstat.tcps_sndtotal++;
2312 }
2313 return (1);
2314 }
2315
2316 MALLOC(sc, struct syn_cache *, sizeof(*sc), M_PCB, M_NOWAIT);
2317 if (sc == NULL) {
2318 if (ipopts)
2319 (void) m_free(ipopts);
2320 return (0);
2321 }
2322
2323 /*
2324 * Fill in the cache, and put the necessary IP and TCP
2325 * options into the reply.
2326 */
2327 sc->sc_src.s_addr = ti->ti_src.s_addr;
2328 sc->sc_dst.s_addr = ti->ti_dst.s_addr;
2329 sc->sc_sport = ti->ti_sport;
2330 sc->sc_dport = ti->ti_dport;
2331 sc->sc_flags = 0;
2332 sc->sc_ipopts = ipopts;
2333 sc->sc_irs = ti->ti_seq;
2334 sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
2335 sc->sc_peermaxseg = oi->maxseg;
2336 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
2337 m->m_pkthdr.rcvif : NULL);
2338 if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
2339 sc->sc_flags |= SCF_TIMESTAMP;
2340 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2341 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2342 sc->sc_requested_s_scale = tb.requested_s_scale;
2343 sc->sc_request_r_scale = 0;
2344 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
2345 TCP_MAXWIN << sc->sc_request_r_scale <
2346 so->so_rcv.sb_hiwat)
2347 sc->sc_request_r_scale++;
2348 } else {
2349 sc->sc_requested_s_scale = 15;
2350 sc->sc_request_r_scale = 15;
2351 }
2352 if (syn_cache_respond(sc, m, ti, win, tb.ts_recent) == 0) {
2353 syn_cache_insert(sc, &sc_prev, &scp);
2354 tcpstat.tcps_sndacks++;
2355 tcpstat.tcps_sndtotal++;
2356 } else {
2357 if (sc->sc_ipopts)
2358 (void) m_free(sc->sc_ipopts);
2359 FREE(sc, M_PCB);
2360 tcpstat.tcps_sc_dropped++;
2361 }
2362 return (1);
2363 }
2364
2365 int
2366 syn_cache_respond(sc, m, ti, win, ts)
2367 struct syn_cache *sc;
2368 struct mbuf *m;
2369 register struct tcpiphdr *ti;
2370 long win;
2371 u_long ts;
2372 {
2373 u_int8_t *optp;
2374 int optlen;
2375
2376 /*
2377 * Tack on the TCP options. If there isn't enough trailing
2378 * space for them, move up the fixed header to make space.
2379 */
2380 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
2381 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
2382 if (optlen > M_TRAILINGSPACE(m)) {
2383 if (M_LEADINGSPACE(m) >= optlen) {
2384 m->m_data -= optlen;
2385 m->m_len += optlen;
2386 } else {
2387 struct mbuf *m0 = m;
2388 if ((m = m_gethdr(M_DONTWAIT, MT_HEADER)) == NULL) {
2389 m_freem(m0);
2390 return (ENOBUFS);
2391 }
2392 MH_ALIGN(m, sizeof(*ti) + optlen);
2393 m->m_next = m0; /* this gets freed below */
2394 }
2395 bcopy((caddr_t)ti, mtod(m, caddr_t), sizeof(*ti));
2396 ti = mtod(m, struct tcpiphdr *);
2397 }
2398
2399 optp = (u_int8_t *)(ti + 1);
2400 optp[0] = TCPOPT_MAXSEG;
2401 optp[1] = 4;
2402 optp[2] = (sc->sc_ourmaxseg >> 8) & 0xff;
2403 optp[3] = sc->sc_ourmaxseg & 0xff;
2404 optlen = 4;
2405
2406 if (sc->sc_request_r_scale != 15) {
2407 *((u_int32_t *)(optp + optlen)) = htonl(TCPOPT_NOP << 24 |
2408 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
2409 sc->sc_request_r_scale);
2410 optlen += 4;
2411 }
2412
2413 if (sc->sc_flags & SCF_TIMESTAMP) {
2414 u_int32_t *lp = (u_int32_t *)(optp + optlen);
2415 /* Form timestamp option as shown in appendix A of RFC 1323. */
2416 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
2417 *lp++ = htonl(tcp_now);
2418 *lp = htonl(ts);
2419 optlen += TCPOLEN_TSTAMP_APPA;
2420 }
2421
2422 /*
2423 * Toss any trailing mbufs. No need to worry about
2424 * m_len and m_pkthdr.len, since tcp_respond() will
2425 * unconditionally set them.
2426 */
2427 if (m->m_next) {
2428 m_freem(m->m_next);
2429 m->m_next = NULL;
2430 }
2431
2432 /*
2433 * Fill in the fields that tcp_respond() will not touch, and
2434 * then send the response.
2435 */
2436 ti->ti_off = (sizeof(struct tcphdr) + optlen) >> 2;
2437 ti->ti_win = htons(win);
2438 return (tcp_respond(NULL, ti, m, sc->sc_irs + 1, sc->sc_iss,
2439 TH_SYN|TH_ACK));
2440 }
2441 #endif /* TUBA_INCLUDE */
2442