tcp_input.c revision 1.212 1 /* $NetBSD: tcp_input.c,v 1.212 2004/12/21 05:51:31 yamt Exp $ */
2
3 /*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 /*
33 * @(#)COPYRIGHT 1.1 (NRL) 17 January 1995
34 *
35 * NRL grants permission for redistribution and use in source and binary
36 * forms, with or without modification, of the software and documentation
37 * created at NRL provided that the following conditions are met:
38 *
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. All advertising materials mentioning features or use of this software
45 * must display the following acknowledgements:
46 * This product includes software developed by the University of
47 * California, Berkeley and its contributors.
48 * This product includes software developed at the Information
49 * Technology Division, US Naval Research Laboratory.
50 * 4. Neither the name of the NRL nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
55 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
57 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NRL OR
58 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
59 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
60 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
61 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
62 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
63 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65 *
66 * The views and conclusions contained in the software and documentation
67 * are those of the authors and should not be interpreted as representing
68 * official policies, either expressed or implied, of the US Naval
69 * Research Laboratory (NRL).
70 */
71
72 /*-
73 * Copyright (c) 1997, 1998, 1999, 2001 The NetBSD Foundation, Inc.
74 * All rights reserved.
75 *
76 * This code is derived from software contributed to The NetBSD Foundation
77 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
78 * Facility, NASA Ames Research Center.
79 *
80 * Redistribution and use in source and binary forms, with or without
81 * modification, are permitted provided that the following conditions
82 * are met:
83 * 1. Redistributions of source code must retain the above copyright
84 * notice, this list of conditions and the following disclaimer.
85 * 2. Redistributions in binary form must reproduce the above copyright
86 * notice, this list of conditions and the following disclaimer in the
87 * documentation and/or other materials provided with the distribution.
88 * 3. All advertising materials mentioning features or use of this software
89 * must display the following acknowledgement:
90 * This product includes software developed by the NetBSD
91 * Foundation, Inc. and its contributors.
92 * 4. Neither the name of The NetBSD Foundation nor the names of its
93 * contributors may be used to endorse or promote products derived
94 * from this software without specific prior written permission.
95 *
96 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
97 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
98 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
99 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
100 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106 * POSSIBILITY OF SUCH DAMAGE.
107 */
108
109 /*
110 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
111 * The Regents of the University of California. All rights reserved.
112 *
113 * Redistribution and use in source and binary forms, with or without
114 * modification, are permitted provided that the following conditions
115 * are met:
116 * 1. Redistributions of source code must retain the above copyright
117 * notice, this list of conditions and the following disclaimer.
118 * 2. Redistributions in binary form must reproduce the above copyright
119 * notice, this list of conditions and the following disclaimer in the
120 * documentation and/or other materials provided with the distribution.
121 * 3. Neither the name of the University nor the names of its contributors
122 * may be used to endorse or promote products derived from this software
123 * without specific prior written permission.
124 *
125 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
126 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
127 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
128 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
129 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
130 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
131 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
132 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
133 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
134 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
135 * SUCH DAMAGE.
136 *
137 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
138 */
139
140 /*
141 * TODO list for SYN cache stuff:
142 *
143 * Find room for a "state" field, which is needed to keep a
144 * compressed state for TIME_WAIT TCBs. It's been noted already
145 * that this is fairly important for very high-volume web and
146 * mail servers, which use a large number of short-lived
147 * connections.
148 */
149
150 #include <sys/cdefs.h>
151 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.212 2004/12/21 05:51:31 yamt Exp $");
152
153 #include "opt_inet.h"
154 #include "opt_ipsec.h"
155 #include "opt_inet_csum.h"
156 #include "opt_tcp_debug.h"
157
158 #include <sys/param.h>
159 #include <sys/systm.h>
160 #include <sys/malloc.h>
161 #include <sys/mbuf.h>
162 #include <sys/protosw.h>
163 #include <sys/socket.h>
164 #include <sys/socketvar.h>
165 #include <sys/errno.h>
166 #include <sys/syslog.h>
167 #include <sys/pool.h>
168 #include <sys/domain.h>
169 #include <sys/kernel.h>
170 #ifdef TCP_SIGNATURE
171 #include <sys/md5.h>
172 #endif
173
174 #include <net/if.h>
175 #include <net/route.h>
176 #include <net/if_types.h>
177
178 #include <netinet/in.h>
179 #include <netinet/in_systm.h>
180 #include <netinet/ip.h>
181 #include <netinet/in_pcb.h>
182 #include <netinet/in_var.h>
183 #include <netinet/ip_var.h>
184
185 #ifdef INET6
186 #ifndef INET
187 #include <netinet/in.h>
188 #endif
189 #include <netinet/ip6.h>
190 #include <netinet6/ip6_var.h>
191 #include <netinet6/in6_pcb.h>
192 #include <netinet6/ip6_var.h>
193 #include <netinet6/in6_var.h>
194 #include <netinet/icmp6.h>
195 #include <netinet6/nd6.h>
196 #endif
197
198 #ifndef INET6
199 /* always need ip6.h for IP6_EXTHDR_GET */
200 #include <netinet/ip6.h>
201 #endif
202
203 #include <netinet/tcp.h>
204 #include <netinet/tcp_fsm.h>
205 #include <netinet/tcp_seq.h>
206 #include <netinet/tcp_timer.h>
207 #include <netinet/tcp_var.h>
208 #include <netinet/tcpip.h>
209 #include <netinet/tcp_debug.h>
210
211 #include <machine/stdarg.h>
212
213 #ifdef IPSEC
214 #include <netinet6/ipsec.h>
215 #include <netkey/key.h>
216 #endif /*IPSEC*/
217 #ifdef INET6
218 #include "faith.h"
219 #if defined(NFAITH) && NFAITH > 0
220 #include <net/if_faith.h>
221 #endif
222 #endif /* IPSEC */
223
224 #ifdef FAST_IPSEC
225 #include <netipsec/ipsec.h>
226 #include <netipsec/ipsec_var.h> /* XXX ipsecstat namespace */
227 #include <netipsec/key.h>
228 #ifdef INET6
229 #include <netipsec/ipsec6.h>
230 #endif
231 #endif /* FAST_IPSEC*/
232
233 int tcprexmtthresh = 3;
234 int tcp_log_refused;
235
236 static int tcp_rst_ppslim_count = 0;
237 static struct timeval tcp_rst_ppslim_last;
238 static int tcp_ackdrop_ppslim_count = 0;
239 static struct timeval tcp_ackdrop_ppslim_last;
240
241 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
242
243 /* for modulo comparisons of timestamps */
244 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
245 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
246
247 /*
248 * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
249 */
250 #ifdef INET6
251 #define ND6_HINT(tp) \
252 do { \
253 if (tp && tp->t_in6pcb && tp->t_family == AF_INET6 && \
254 tp->t_in6pcb->in6p_route.ro_rt) { \
255 nd6_nud_hint(tp->t_in6pcb->in6p_route.ro_rt, NULL, 0); \
256 } \
257 } while (/*CONSTCOND*/ 0)
258 #else
259 #define ND6_HINT(tp)
260 #endif
261
262 /*
263 * Macro to compute ACK transmission behavior. Delay the ACK unless
264 * we have already delayed an ACK (must send an ACK every two segments).
265 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
266 * option is enabled.
267 */
268 #define TCP_SETUP_ACK(tp, th) \
269 do { \
270 if ((tp)->t_flags & TF_DELACK || \
271 (tcp_ack_on_push && (th)->th_flags & TH_PUSH)) \
272 tp->t_flags |= TF_ACKNOW; \
273 else \
274 TCP_SET_DELACK(tp); \
275 } while (/*CONSTCOND*/ 0)
276
277 /*
278 * Convert TCP protocol fields to host order for easier processing.
279 */
280 #define TCP_FIELDS_TO_HOST(th) \
281 do { \
282 NTOHL((th)->th_seq); \
283 NTOHL((th)->th_ack); \
284 NTOHS((th)->th_win); \
285 NTOHS((th)->th_urp); \
286 } while (/*CONSTCOND*/ 0)
287
288 /*
289 * ... and reverse the above.
290 */
291 #define TCP_FIELDS_TO_NET(th) \
292 do { \
293 HTONL((th)->th_seq); \
294 HTONL((th)->th_ack); \
295 HTONS((th)->th_win); \
296 HTONS((th)->th_urp); \
297 } while (/*CONSTCOND*/ 0)
298
299 #ifdef TCP_CSUM_COUNTERS
300 #include <sys/device.h>
301
302 extern struct evcnt tcp_hwcsum_ok;
303 extern struct evcnt tcp_hwcsum_bad;
304 extern struct evcnt tcp_hwcsum_data;
305 extern struct evcnt tcp_swcsum;
306
307 #define TCP_CSUM_COUNTER_INCR(ev) (ev)->ev_count++
308
309 #else
310
311 #define TCP_CSUM_COUNTER_INCR(ev) /* nothing */
312
313 #endif /* TCP_CSUM_COUNTERS */
314
315 #ifdef TCP_REASS_COUNTERS
316 #include <sys/device.h>
317
318 extern struct evcnt tcp_reass_;
319 extern struct evcnt tcp_reass_empty;
320 extern struct evcnt tcp_reass_iteration[8];
321 extern struct evcnt tcp_reass_prependfirst;
322 extern struct evcnt tcp_reass_prepend;
323 extern struct evcnt tcp_reass_insert;
324 extern struct evcnt tcp_reass_inserttail;
325 extern struct evcnt tcp_reass_append;
326 extern struct evcnt tcp_reass_appendtail;
327 extern struct evcnt tcp_reass_overlaptail;
328 extern struct evcnt tcp_reass_overlapfront;
329 extern struct evcnt tcp_reass_segdup;
330 extern struct evcnt tcp_reass_fragdup;
331
332 #define TCP_REASS_COUNTER_INCR(ev) (ev)->ev_count++
333
334 #else
335
336 #define TCP_REASS_COUNTER_INCR(ev) /* nothing */
337
338 #endif /* TCP_REASS_COUNTERS */
339
340 #ifdef INET
341 static void tcp4_log_refused __P((const struct ip *, const struct tcphdr *));
342 #endif
343 #ifdef INET6
344 static void tcp6_log_refused
345 __P((const struct ip6_hdr *, const struct tcphdr *));
346 #endif
347
348 #define TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next
349
350 POOL_INIT(tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl", NULL);
351
352 int
353 tcp_reass(tp, th, m, tlen)
354 struct tcpcb *tp;
355 struct tcphdr *th;
356 struct mbuf *m;
357 int *tlen;
358 {
359 struct ipqent *p, *q, *nq, *tiqe = NULL;
360 struct socket *so = NULL;
361 int pkt_flags;
362 tcp_seq pkt_seq;
363 unsigned pkt_len;
364 u_long rcvpartdupbyte = 0;
365 u_long rcvoobyte;
366 #ifdef TCP_REASS_COUNTERS
367 u_int count = 0;
368 #endif
369
370 if (tp->t_inpcb)
371 so = tp->t_inpcb->inp_socket;
372 #ifdef INET6
373 else if (tp->t_in6pcb)
374 so = tp->t_in6pcb->in6p_socket;
375 #endif
376
377 TCP_REASS_LOCK_CHECK(tp);
378
379 /*
380 * Call with th==0 after become established to
381 * force pre-ESTABLISHED data up to user socket.
382 */
383 if (th == 0)
384 goto present;
385
386 rcvoobyte = *tlen;
387 /*
388 * Copy these to local variables because the tcpiphdr
389 * gets munged while we are collapsing mbufs.
390 */
391 pkt_seq = th->th_seq;
392 pkt_len = *tlen;
393 pkt_flags = th->th_flags;
394
395 TCP_REASS_COUNTER_INCR(&tcp_reass_);
396
397 if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
398 /*
399 * When we miss a packet, the vast majority of time we get
400 * packets that follow it in order. So optimize for that.
401 */
402 if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
403 p->ipqe_len += pkt_len;
404 p->ipqe_flags |= pkt_flags;
405 m_cat(p->ipre_mlast, m);
406 TRAVERSE(p->ipre_mlast);
407 m = NULL;
408 tiqe = p;
409 TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
410 TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
411 goto skip_replacement;
412 }
413 /*
414 * While we're here, if the pkt is completely beyond
415 * anything we have, just insert it at the tail.
416 */
417 if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
418 TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
419 goto insert_it;
420 }
421 }
422
423 q = TAILQ_FIRST(&tp->segq);
424
425 if (q != NULL) {
426 /*
427 * If this segment immediately precedes the first out-of-order
428 * block, simply slap the segment in front of it and (mostly)
429 * skip the complicated logic.
430 */
431 if (pkt_seq + pkt_len == q->ipqe_seq) {
432 q->ipqe_seq = pkt_seq;
433 q->ipqe_len += pkt_len;
434 q->ipqe_flags |= pkt_flags;
435 m_cat(m, q->ipqe_m);
436 q->ipqe_m = m;
437 q->ipre_mlast = m; /* last mbuf may have changed */
438 TRAVERSE(q->ipre_mlast);
439 tiqe = q;
440 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
441 TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
442 goto skip_replacement;
443 }
444 } else {
445 TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
446 }
447
448 /*
449 * Find a segment which begins after this one does.
450 */
451 for (p = NULL; q != NULL; q = nq) {
452 nq = TAILQ_NEXT(q, ipqe_q);
453 #ifdef TCP_REASS_COUNTERS
454 count++;
455 #endif
456 /*
457 * If the received segment is just right after this
458 * fragment, merge the two together and then check
459 * for further overlaps.
460 */
461 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
462 #ifdef TCPREASS_DEBUG
463 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
464 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
465 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
466 #endif
467 pkt_len += q->ipqe_len;
468 pkt_flags |= q->ipqe_flags;
469 pkt_seq = q->ipqe_seq;
470 m_cat(q->ipre_mlast, m);
471 TRAVERSE(q->ipre_mlast);
472 m = q->ipqe_m;
473 TCP_REASS_COUNTER_INCR(&tcp_reass_append);
474 goto free_ipqe;
475 }
476 /*
477 * If the received segment is completely past this
478 * fragment, we need to go the next fragment.
479 */
480 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
481 p = q;
482 continue;
483 }
484 /*
485 * If the fragment is past the received segment,
486 * it (or any following) can't be concatenated.
487 */
488 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
489 TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
490 break;
491 }
492
493 /*
494 * We've received all the data in this segment before.
495 * mark it as a duplicate and return.
496 */
497 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
498 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
499 tcpstat.tcps_rcvduppack++;
500 tcpstat.tcps_rcvdupbyte += pkt_len;
501 m_freem(m);
502 if (tiqe != NULL)
503 pool_put(&tcpipqent_pool, tiqe);
504 TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
505 return (0);
506 }
507 /*
508 * Received segment completely overlaps this fragment
509 * so we drop the fragment (this keeps the temporal
510 * ordering of segments correct).
511 */
512 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
513 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
514 rcvpartdupbyte += q->ipqe_len;
515 m_freem(q->ipqe_m);
516 TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
517 goto free_ipqe;
518 }
519 /*
520 * RX'ed segment extends past the end of the
521 * fragment. Drop the overlapping bytes. Then
522 * merge the fragment and segment then treat as
523 * a longer received packet.
524 */
525 if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
526 SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
527 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
528 #ifdef TCPREASS_DEBUG
529 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
530 tp, overlap,
531 pkt_seq, pkt_seq + pkt_len, pkt_len);
532 #endif
533 m_adj(m, overlap);
534 rcvpartdupbyte += overlap;
535 m_cat(q->ipre_mlast, m);
536 TRAVERSE(q->ipre_mlast);
537 m = q->ipqe_m;
538 pkt_seq = q->ipqe_seq;
539 pkt_len += q->ipqe_len - overlap;
540 rcvoobyte -= overlap;
541 TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
542 goto free_ipqe;
543 }
544 /*
545 * RX'ed segment extends past the front of the
546 * fragment. Drop the overlapping bytes on the
547 * received packet. The packet will then be
548 * contatentated with this fragment a bit later.
549 */
550 if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
551 SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
552 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
553 #ifdef TCPREASS_DEBUG
554 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
555 tp, overlap,
556 pkt_seq, pkt_seq + pkt_len, pkt_len);
557 #endif
558 m_adj(m, -overlap);
559 pkt_len -= overlap;
560 rcvpartdupbyte += overlap;
561 TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
562 rcvoobyte -= overlap;
563 }
564 /*
565 * If the received segment immediates precedes this
566 * fragment then tack the fragment onto this segment
567 * and reinsert the data.
568 */
569 if (q->ipqe_seq == pkt_seq + pkt_len) {
570 #ifdef TCPREASS_DEBUG
571 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
572 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
573 pkt_seq, pkt_seq + pkt_len, pkt_len);
574 #endif
575 pkt_len += q->ipqe_len;
576 pkt_flags |= q->ipqe_flags;
577 m_cat(m, q->ipqe_m);
578 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
579 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
580 if (tiqe == NULL)
581 tiqe = q;
582 else
583 pool_put(&tcpipqent_pool, q);
584 TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
585 break;
586 }
587 /*
588 * If the fragment is before the segment, remember it.
589 * When this loop is terminated, p will contain the
590 * pointer to fragment that is right before the received
591 * segment.
592 */
593 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
594 p = q;
595
596 continue;
597
598 /*
599 * This is a common operation. It also will allow
600 * to save doing a malloc/free in most instances.
601 */
602 free_ipqe:
603 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
604 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
605 if (tiqe == NULL)
606 tiqe = q;
607 else
608 pool_put(&tcpipqent_pool, q);
609 }
610
611 #ifdef TCP_REASS_COUNTERS
612 if (count > 7)
613 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
614 else if (count > 0)
615 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
616 #endif
617
618 insert_it:
619
620 /*
621 * Allocate a new queue entry since the received segment did not
622 * collapse onto any other out-of-order block; thus we are allocating
623 * a new block. If it had collapsed, tiqe would not be NULL and
624 * we would be reusing it.
625 * XXX If we can't, just drop the packet. XXX
626 */
627 if (tiqe == NULL) {
628 tiqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
629 if (tiqe == NULL) {
630 tcpstat.tcps_rcvmemdrop++;
631 m_freem(m);
632 return (0);
633 }
634 }
635
636 /*
637 * Update the counters.
638 */
639 tcpstat.tcps_rcvoopack++;
640 tcpstat.tcps_rcvoobyte += rcvoobyte;
641 if (rcvpartdupbyte) {
642 tcpstat.tcps_rcvpartduppack++;
643 tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
644 }
645
646 /*
647 * Insert the new fragment queue entry into both queues.
648 */
649 tiqe->ipqe_m = m;
650 tiqe->ipre_mlast = m;
651 tiqe->ipqe_seq = pkt_seq;
652 tiqe->ipqe_len = pkt_len;
653 tiqe->ipqe_flags = pkt_flags;
654 if (p == NULL) {
655 TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
656 #ifdef TCPREASS_DEBUG
657 if (tiqe->ipqe_seq != tp->rcv_nxt)
658 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
659 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
660 #endif
661 } else {
662 TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
663 #ifdef TCPREASS_DEBUG
664 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
665 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
666 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
667 #endif
668 }
669
670 skip_replacement:
671
672 TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
673
674 present:
675 /*
676 * Present data to user, advancing rcv_nxt through
677 * completed sequence space.
678 */
679 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
680 return (0);
681 q = TAILQ_FIRST(&tp->segq);
682 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
683 return (0);
684 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
685 return (0);
686
687 tp->rcv_nxt += q->ipqe_len;
688 pkt_flags = q->ipqe_flags & TH_FIN;
689 ND6_HINT(tp);
690
691 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
692 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
693 if (so->so_state & SS_CANTRCVMORE)
694 m_freem(q->ipqe_m);
695 else
696 sbappendstream(&so->so_rcv, q->ipqe_m);
697 pool_put(&tcpipqent_pool, q);
698 sorwakeup(so);
699 return (pkt_flags);
700 }
701
702 #ifdef INET6
703 int
704 tcp6_input(mp, offp, proto)
705 struct mbuf **mp;
706 int *offp, proto;
707 {
708 struct mbuf *m = *mp;
709
710 /*
711 * draft-itojun-ipv6-tcp-to-anycast
712 * better place to put this in?
713 */
714 if (m->m_flags & M_ANYCAST6) {
715 struct ip6_hdr *ip6;
716 if (m->m_len < sizeof(struct ip6_hdr)) {
717 if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
718 tcpstat.tcps_rcvshort++;
719 return IPPROTO_DONE;
720 }
721 }
722 ip6 = mtod(m, struct ip6_hdr *);
723 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
724 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
725 return IPPROTO_DONE;
726 }
727
728 tcp_input(m, *offp, proto);
729 return IPPROTO_DONE;
730 }
731 #endif
732
733 #ifdef INET
734 static void
735 tcp4_log_refused(ip, th)
736 const struct ip *ip;
737 const struct tcphdr *th;
738 {
739 char src[4*sizeof "123"];
740 char dst[4*sizeof "123"];
741
742 if (ip) {
743 strlcpy(src, inet_ntoa(ip->ip_src), sizeof(src));
744 strlcpy(dst, inet_ntoa(ip->ip_dst), sizeof(dst));
745 }
746 else {
747 strlcpy(src, "(unknown)", sizeof(src));
748 strlcpy(dst, "(unknown)", sizeof(dst));
749 }
750 log(LOG_INFO,
751 "Connection attempt to TCP %s:%d from %s:%d\n",
752 dst, ntohs(th->th_dport),
753 src, ntohs(th->th_sport));
754 }
755 #endif
756
757 #ifdef INET6
758 static void
759 tcp6_log_refused(ip6, th)
760 const struct ip6_hdr *ip6;
761 const struct tcphdr *th;
762 {
763 char src[INET6_ADDRSTRLEN];
764 char dst[INET6_ADDRSTRLEN];
765
766 if (ip6) {
767 strlcpy(src, ip6_sprintf(&ip6->ip6_src), sizeof(src));
768 strlcpy(dst, ip6_sprintf(&ip6->ip6_dst), sizeof(dst));
769 }
770 else {
771 strlcpy(src, "(unknown v6)", sizeof(src));
772 strlcpy(dst, "(unknown v6)", sizeof(dst));
773 }
774 log(LOG_INFO,
775 "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
776 dst, ntohs(th->th_dport),
777 src, ntohs(th->th_sport));
778 }
779 #endif
780
781 /*
782 * Checksum extended TCP header and data.
783 */
784 int
785 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th, int toff,
786 int off, int tlen)
787 {
788
789 /*
790 * XXX it's better to record and check if this mbuf is
791 * already checked.
792 */
793
794 switch (af) {
795 #ifdef INET
796 case AF_INET:
797 switch (m->m_pkthdr.csum_flags &
798 ((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
799 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
800 case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
801 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
802 goto badcsum;
803
804 case M_CSUM_TCPv4|M_CSUM_DATA: {
805 u_int32_t hw_csum = m->m_pkthdr.csum_data;
806
807 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
808 if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
809 const struct ip *ip =
810 mtod(m, const struct ip *);
811
812 hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
813 ip->ip_dst.s_addr,
814 htons(hw_csum + tlen + off + IPPROTO_TCP));
815 }
816 if ((hw_csum ^ 0xffff) != 0)
817 goto badcsum;
818 break;
819 }
820
821 case M_CSUM_TCPv4:
822 /* Checksum was okay. */
823 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
824 break;
825
826 default:
827 /*
828 * Must compute it ourselves. Maybe skip checksum
829 * on loopback interfaces.
830 */
831 if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
832 IFF_LOOPBACK) ||
833 tcp_do_loopback_cksum)) {
834 TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
835 if (in4_cksum(m, IPPROTO_TCP, toff,
836 tlen + off) != 0)
837 goto badcsum;
838 }
839 break;
840 }
841 break;
842 #endif /* INET4 */
843
844 #ifdef INET6
845 case AF_INET6:
846 if (__predict_true((m->m_flags & M_LOOP) == 0 ||
847 tcp_do_loopback_cksum)) {
848 if (in6_cksum(m, IPPROTO_TCP, toff, tlen + off) != 0)
849 goto badcsum;
850 }
851 break;
852 #endif /* INET6 */
853 }
854
855 return 0;
856
857 badcsum:
858 tcpstat.tcps_rcvbadsum++;
859 return -1;
860 }
861
862 /*
863 * TCP input routine, follows pages 65-76 of the
864 * protocol specification dated September, 1981 very closely.
865 */
866 void
867 tcp_input(struct mbuf *m, ...)
868 {
869 struct tcphdr *th;
870 struct ip *ip;
871 struct inpcb *inp;
872 #ifdef INET6
873 struct ip6_hdr *ip6;
874 struct in6pcb *in6p;
875 #endif
876 u_int8_t *optp = NULL;
877 int optlen = 0;
878 int len, tlen, toff, hdroptlen = 0;
879 struct tcpcb *tp = 0;
880 int tiflags;
881 struct socket *so = NULL;
882 int todrop, acked, ourfinisacked, needoutput = 0;
883 #ifdef TCP_DEBUG
884 short ostate = 0;
885 #endif
886 int iss = 0;
887 u_long tiwin;
888 struct tcp_opt_info opti;
889 int off, iphlen;
890 va_list ap;
891 int af; /* af on the wire */
892 struct mbuf *tcp_saveti = NULL;
893
894 MCLAIM(m, &tcp_rx_mowner);
895 va_start(ap, m);
896 toff = va_arg(ap, int);
897 (void)va_arg(ap, int); /* ignore value, advance ap */
898 va_end(ap);
899
900 tcpstat.tcps_rcvtotal++;
901
902 bzero(&opti, sizeof(opti));
903 opti.ts_present = 0;
904 opti.maxseg = 0;
905
906 /*
907 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
908 *
909 * TCP is, by definition, unicast, so we reject all
910 * multicast outright.
911 *
912 * Note, there are additional src/dst address checks in
913 * the AF-specific code below.
914 */
915 if (m->m_flags & (M_BCAST|M_MCAST)) {
916 /* XXX stat */
917 goto drop;
918 }
919 #ifdef INET6
920 if (m->m_flags & M_ANYCAST6) {
921 /* XXX stat */
922 goto drop;
923 }
924 #endif
925
926 /*
927 * Get IP and TCP header.
928 * Note: IP leaves IP header in first mbuf.
929 */
930 ip = mtod(m, struct ip *);
931 #ifdef INET6
932 ip6 = NULL;
933 #endif
934 switch (ip->ip_v) {
935 #ifdef INET
936 case 4:
937 af = AF_INET;
938 iphlen = sizeof(struct ip);
939 ip = mtod(m, struct ip *);
940 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
941 sizeof(struct tcphdr));
942 if (th == NULL) {
943 tcpstat.tcps_rcvshort++;
944 return;
945 }
946 /* We do the checksum after PCB lookup... */
947 len = ntohs(ip->ip_len);
948 tlen = len - toff;
949 break;
950 #endif
951 #ifdef INET6
952 case 6:
953 ip = NULL;
954 iphlen = sizeof(struct ip6_hdr);
955 af = AF_INET6;
956 ip6 = mtod(m, struct ip6_hdr *);
957 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
958 sizeof(struct tcphdr));
959 if (th == NULL) {
960 tcpstat.tcps_rcvshort++;
961 return;
962 }
963
964 /* Be proactive about malicious use of IPv4 mapped address */
965 if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
966 IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
967 /* XXX stat */
968 goto drop;
969 }
970
971 /*
972 * Be proactive about unspecified IPv6 address in source.
973 * As we use all-zero to indicate unbounded/unconnected pcb,
974 * unspecified IPv6 address can be used to confuse us.
975 *
976 * Note that packets with unspecified IPv6 destination is
977 * already dropped in ip6_input.
978 */
979 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
980 /* XXX stat */
981 goto drop;
982 }
983
984 /*
985 * Make sure destination address is not multicast.
986 * Source address checked in ip6_input().
987 */
988 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
989 /* XXX stat */
990 goto drop;
991 }
992
993 /* We do the checksum after PCB lookup... */
994 len = m->m_pkthdr.len;
995 tlen = len - toff;
996 break;
997 #endif
998 default:
999 m_freem(m);
1000 return;
1001 }
1002
1003 KASSERT(TCP_HDR_ALIGNED_P(th));
1004
1005 /*
1006 * Check that TCP offset makes sense,
1007 * pull out TCP options and adjust length. XXX
1008 */
1009 off = th->th_off << 2;
1010 if (off < sizeof (struct tcphdr) || off > tlen) {
1011 tcpstat.tcps_rcvbadoff++;
1012 goto drop;
1013 }
1014 tlen -= off;
1015
1016 /*
1017 * tcp_input() has been modified to use tlen to mean the TCP data
1018 * length throughout the function. Other functions can use
1019 * m->m_pkthdr.len as the basis for calculating the TCP data length.
1020 * rja
1021 */
1022
1023 if (off > sizeof (struct tcphdr)) {
1024 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1025 if (th == NULL) {
1026 tcpstat.tcps_rcvshort++;
1027 return;
1028 }
1029 /*
1030 * NOTE: ip/ip6 will not be affected by m_pulldown()
1031 * (as they're before toff) and we don't need to update those.
1032 */
1033 KASSERT(TCP_HDR_ALIGNED_P(th));
1034 optlen = off - sizeof (struct tcphdr);
1035 optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1036 /*
1037 * Do quick retrieval of timestamp options ("options
1038 * prediction?"). If timestamp is the only option and it's
1039 * formatted as recommended in RFC 1323 appendix A, we
1040 * quickly get the values now and not bother calling
1041 * tcp_dooptions(), etc.
1042 */
1043 if ((optlen == TCPOLEN_TSTAMP_APPA ||
1044 (optlen > TCPOLEN_TSTAMP_APPA &&
1045 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1046 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1047 (th->th_flags & TH_SYN) == 0) {
1048 opti.ts_present = 1;
1049 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1050 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1051 optp = NULL; /* we've parsed the options */
1052 }
1053 }
1054 tiflags = th->th_flags;
1055
1056 /*
1057 * Locate pcb for segment.
1058 */
1059 findpcb:
1060 inp = NULL;
1061 #ifdef INET6
1062 in6p = NULL;
1063 #endif
1064 switch (af) {
1065 #ifdef INET
1066 case AF_INET:
1067 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1068 ip->ip_dst, th->th_dport);
1069 if (inp == 0) {
1070 ++tcpstat.tcps_pcbhashmiss;
1071 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
1072 }
1073 #ifdef INET6
1074 if (inp == 0) {
1075 struct in6_addr s, d;
1076
1077 /* mapped addr case */
1078 bzero(&s, sizeof(s));
1079 s.s6_addr16[5] = htons(0xffff);
1080 bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
1081 bzero(&d, sizeof(d));
1082 d.s6_addr16[5] = htons(0xffff);
1083 bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
1084 in6p = in6_pcblookup_connect(&tcbtable, &s,
1085 th->th_sport, &d, th->th_dport, 0);
1086 if (in6p == 0) {
1087 ++tcpstat.tcps_pcbhashmiss;
1088 in6p = in6_pcblookup_bind(&tcbtable, &d,
1089 th->th_dport, 0);
1090 }
1091 }
1092 #endif
1093 #ifndef INET6
1094 if (inp == 0)
1095 #else
1096 if (inp == 0 && in6p == 0)
1097 #endif
1098 {
1099 ++tcpstat.tcps_noport;
1100 if (tcp_log_refused &&
1101 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1102 tcp4_log_refused(ip, th);
1103 }
1104 TCP_FIELDS_TO_HOST(th);
1105 goto dropwithreset_ratelim;
1106 }
1107 #if defined(IPSEC) || defined(FAST_IPSEC)
1108 if (inp && (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 &&
1109 ipsec4_in_reject(m, inp)) {
1110 ipsecstat.in_polvio++;
1111 goto drop;
1112 }
1113 #ifdef INET6
1114 else if (in6p &&
1115 (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1116 ipsec4_in_reject_so(m, in6p->in6p_socket)) {
1117 ipsecstat.in_polvio++;
1118 goto drop;
1119 }
1120 #endif
1121 #endif /*IPSEC*/
1122 break;
1123 #endif /*INET*/
1124 #ifdef INET6
1125 case AF_INET6:
1126 {
1127 int faith;
1128
1129 #if defined(NFAITH) && NFAITH > 0
1130 faith = faithprefix(&ip6->ip6_dst);
1131 #else
1132 faith = 0;
1133 #endif
1134 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1135 th->th_sport, &ip6->ip6_dst, th->th_dport, faith);
1136 if (in6p == NULL) {
1137 ++tcpstat.tcps_pcbhashmiss;
1138 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1139 th->th_dport, faith);
1140 }
1141 if (in6p == NULL) {
1142 ++tcpstat.tcps_noport;
1143 if (tcp_log_refused &&
1144 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1145 tcp6_log_refused(ip6, th);
1146 }
1147 TCP_FIELDS_TO_HOST(th);
1148 goto dropwithreset_ratelim;
1149 }
1150 #if defined(IPSEC) || defined(FAST_IPSEC)
1151 if ((in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1152 ipsec6_in_reject(m, in6p)) {
1153 ipsec6stat.in_polvio++;
1154 goto drop;
1155 }
1156 #endif /*IPSEC*/
1157 break;
1158 }
1159 #endif
1160 }
1161
1162 /*
1163 * If the state is CLOSED (i.e., TCB does not exist) then
1164 * all data in the incoming segment is discarded.
1165 * If the TCB exists but is in CLOSED state, it is embryonic,
1166 * but should either do a listen or a connect soon.
1167 */
1168 tp = NULL;
1169 so = NULL;
1170 if (inp) {
1171 tp = intotcpcb(inp);
1172 so = inp->inp_socket;
1173 }
1174 #ifdef INET6
1175 else if (in6p) {
1176 tp = in6totcpcb(in6p);
1177 so = in6p->in6p_socket;
1178 }
1179 #endif
1180 if (tp == 0) {
1181 TCP_FIELDS_TO_HOST(th);
1182 goto dropwithreset_ratelim;
1183 }
1184 if (tp->t_state == TCPS_CLOSED)
1185 goto drop;
1186
1187 /*
1188 * Checksum extended TCP header and data.
1189 */
1190 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1191 goto badcsum;
1192
1193 TCP_FIELDS_TO_HOST(th);
1194
1195 /* Unscale the window into a 32-bit value. */
1196 if ((tiflags & TH_SYN) == 0)
1197 tiwin = th->th_win << tp->snd_scale;
1198 else
1199 tiwin = th->th_win;
1200
1201 #ifdef INET6
1202 /* save packet options if user wanted */
1203 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1204 if (in6p->in6p_options) {
1205 m_freem(in6p->in6p_options);
1206 in6p->in6p_options = 0;
1207 }
1208 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1209 }
1210 #endif
1211
1212 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
1213 union syn_cache_sa src;
1214 union syn_cache_sa dst;
1215
1216 bzero(&src, sizeof(src));
1217 bzero(&dst, sizeof(dst));
1218 switch (af) {
1219 #ifdef INET
1220 case AF_INET:
1221 src.sin.sin_len = sizeof(struct sockaddr_in);
1222 src.sin.sin_family = AF_INET;
1223 src.sin.sin_addr = ip->ip_src;
1224 src.sin.sin_port = th->th_sport;
1225
1226 dst.sin.sin_len = sizeof(struct sockaddr_in);
1227 dst.sin.sin_family = AF_INET;
1228 dst.sin.sin_addr = ip->ip_dst;
1229 dst.sin.sin_port = th->th_dport;
1230 break;
1231 #endif
1232 #ifdef INET6
1233 case AF_INET6:
1234 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1235 src.sin6.sin6_family = AF_INET6;
1236 src.sin6.sin6_addr = ip6->ip6_src;
1237 src.sin6.sin6_port = th->th_sport;
1238
1239 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1240 dst.sin6.sin6_family = AF_INET6;
1241 dst.sin6.sin6_addr = ip6->ip6_dst;
1242 dst.sin6.sin6_port = th->th_dport;
1243 break;
1244 #endif /* INET6 */
1245 default:
1246 goto badsyn; /*sanity*/
1247 }
1248
1249 if (so->so_options & SO_DEBUG) {
1250 #ifdef TCP_DEBUG
1251 ostate = tp->t_state;
1252 #endif
1253
1254 tcp_saveti = NULL;
1255 if (iphlen + sizeof(struct tcphdr) > MHLEN)
1256 goto nosave;
1257
1258 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1259 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1260 if (!tcp_saveti)
1261 goto nosave;
1262 } else {
1263 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1264 if (!tcp_saveti)
1265 goto nosave;
1266 MCLAIM(m, &tcp_mowner);
1267 tcp_saveti->m_len = iphlen;
1268 m_copydata(m, 0, iphlen,
1269 mtod(tcp_saveti, caddr_t));
1270 }
1271
1272 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1273 m_freem(tcp_saveti);
1274 tcp_saveti = NULL;
1275 } else {
1276 tcp_saveti->m_len += sizeof(struct tcphdr);
1277 bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
1278 sizeof(struct tcphdr));
1279 }
1280 nosave:;
1281 }
1282 if (so->so_options & SO_ACCEPTCONN) {
1283 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1284 if (tiflags & TH_RST) {
1285 syn_cache_reset(&src.sa, &dst.sa, th);
1286 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
1287 (TH_ACK|TH_SYN)) {
1288 /*
1289 * Received a SYN,ACK. This should
1290 * never happen while we are in
1291 * LISTEN. Send an RST.
1292 */
1293 goto badsyn;
1294 } else if (tiflags & TH_ACK) {
1295 so = syn_cache_get(&src.sa, &dst.sa,
1296 th, toff, tlen, so, m);
1297 if (so == NULL) {
1298 /*
1299 * We don't have a SYN for
1300 * this ACK; send an RST.
1301 */
1302 goto badsyn;
1303 } else if (so ==
1304 (struct socket *)(-1)) {
1305 /*
1306 * We were unable to create
1307 * the connection. If the
1308 * 3-way handshake was
1309 * completed, and RST has
1310 * been sent to the peer.
1311 * Since the mbuf might be
1312 * in use for the reply,
1313 * do not free it.
1314 */
1315 m = NULL;
1316 } else {
1317 /*
1318 * We have created a
1319 * full-blown connection.
1320 */
1321 tp = NULL;
1322 inp = NULL;
1323 #ifdef INET6
1324 in6p = NULL;
1325 #endif
1326 switch (so->so_proto->pr_domain->dom_family) {
1327 #ifdef INET
1328 case AF_INET:
1329 inp = sotoinpcb(so);
1330 tp = intotcpcb(inp);
1331 break;
1332 #endif
1333 #ifdef INET6
1334 case AF_INET6:
1335 in6p = sotoin6pcb(so);
1336 tp = in6totcpcb(in6p);
1337 break;
1338 #endif
1339 }
1340 if (tp == NULL)
1341 goto badsyn; /*XXX*/
1342 tiwin <<= tp->snd_scale;
1343 goto after_listen;
1344 }
1345 } else {
1346 /*
1347 * None of RST, SYN or ACK was set.
1348 * This is an invalid packet for a
1349 * TCB in LISTEN state. Send a RST.
1350 */
1351 goto badsyn;
1352 }
1353 } else {
1354 /*
1355 * Received a SYN.
1356 */
1357
1358 #ifdef INET6
1359 /*
1360 * If deprecated address is forbidden, we do
1361 * not accept SYN to deprecated interface
1362 * address to prevent any new inbound
1363 * connection from getting established.
1364 * When we do not accept SYN, we send a TCP
1365 * RST, with deprecated source address (instead
1366 * of dropping it). We compromise it as it is
1367 * much better for peer to send a RST, and
1368 * RST will be the final packet for the
1369 * exchange.
1370 *
1371 * If we do not forbid deprecated addresses, we
1372 * accept the SYN packet. RFC2462 does not
1373 * suggest dropping SYN in this case.
1374 * If we decipher RFC2462 5.5.4, it says like
1375 * this:
1376 * 1. use of deprecated addr with existing
1377 * communication is okay - "SHOULD continue
1378 * to be used"
1379 * 2. use of it with new communication:
1380 * (2a) "SHOULD NOT be used if alternate
1381 * address with sufficient scope is
1382 * available"
1383 * (2b) nothing mentioned otherwise.
1384 * Here we fall into (2b) case as we have no
1385 * choice in our source address selection - we
1386 * must obey the peer.
1387 *
1388 * The wording in RFC2462 is confusing, and
1389 * there are multiple description text for
1390 * deprecated address handling - worse, they
1391 * are not exactly the same. I believe 5.5.4
1392 * is the best one, so we follow 5.5.4.
1393 */
1394 if (af == AF_INET6 && !ip6_use_deprecated) {
1395 struct in6_ifaddr *ia6;
1396 if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
1397 &ip6->ip6_dst)) &&
1398 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1399 tp = NULL;
1400 goto dropwithreset;
1401 }
1402 }
1403 #endif
1404
1405 #ifdef IPSEC
1406 switch (af) {
1407 #ifdef INET
1408 case AF_INET:
1409 if (ipsec4_in_reject_so(m, so)) {
1410 ipsecstat.in_polvio++;
1411 tp = NULL;
1412 goto dropwithreset;
1413 }
1414 break;
1415 #endif
1416 #ifdef INET6
1417 case AF_INET6:
1418 if (ipsec6_in_reject_so(m, so)) {
1419 ipsec6stat.in_polvio++;
1420 tp = NULL;
1421 goto dropwithreset;
1422 }
1423 break;
1424 #endif
1425 }
1426 #endif
1427
1428 /*
1429 * LISTEN socket received a SYN
1430 * from itself? This can't possibly
1431 * be valid; drop the packet.
1432 */
1433 if (th->th_sport == th->th_dport) {
1434 int i;
1435
1436 switch (af) {
1437 #ifdef INET
1438 case AF_INET:
1439 i = in_hosteq(ip->ip_src, ip->ip_dst);
1440 break;
1441 #endif
1442 #ifdef INET6
1443 case AF_INET6:
1444 i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1445 break;
1446 #endif
1447 default:
1448 i = 1;
1449 }
1450 if (i) {
1451 tcpstat.tcps_badsyn++;
1452 goto drop;
1453 }
1454 }
1455
1456 /*
1457 * SYN looks ok; create compressed TCP
1458 * state for it.
1459 */
1460 if (so->so_qlen <= so->so_qlimit &&
1461 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1462 so, m, optp, optlen, &opti))
1463 m = NULL;
1464 }
1465 goto drop;
1466 }
1467 }
1468
1469 after_listen:
1470 #ifdef DIAGNOSTIC
1471 /*
1472 * Should not happen now that all embryonic connections
1473 * are handled with compressed state.
1474 */
1475 if (tp->t_state == TCPS_LISTEN)
1476 panic("tcp_input: TCPS_LISTEN");
1477 #endif
1478
1479 /*
1480 * Segment received on connection.
1481 * Reset idle time and keep-alive timer.
1482 */
1483 tp->t_rcvtime = tcp_now;
1484 if (TCPS_HAVEESTABLISHED(tp->t_state))
1485 TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1486
1487 /*
1488 * Process options.
1489 */
1490 #ifdef TCP_SIGNATURE
1491 if (optp || (tp->t_flags & TF_SIGNATURE))
1492 #else
1493 if (optp)
1494 #endif
1495 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1496 goto drop;
1497
1498 /*
1499 * Header prediction: check for the two common cases
1500 * of a uni-directional data xfer. If the packet has
1501 * no control flags, is in-sequence, the window didn't
1502 * change and we're not retransmitting, it's a
1503 * candidate. If the length is zero and the ack moved
1504 * forward, we're the sender side of the xfer. Just
1505 * free the data acked & wake any higher level process
1506 * that was blocked waiting for space. If the length
1507 * is non-zero and the ack didn't move, we're the
1508 * receiver side. If we're getting packets in-order
1509 * (the reassembly queue is empty), add the data to
1510 * the socket buffer and note that we need a delayed ack.
1511 */
1512 if (tp->t_state == TCPS_ESTABLISHED &&
1513 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1514 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1515 th->th_seq == tp->rcv_nxt &&
1516 tiwin && tiwin == tp->snd_wnd &&
1517 tp->snd_nxt == tp->snd_max) {
1518
1519 /*
1520 * If last ACK falls within this segment's sequence numbers,
1521 * record the timestamp.
1522 */
1523 if (opti.ts_present &&
1524 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1525 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
1526 tp->ts_recent_age = TCP_TIMESTAMP(tp);
1527 tp->ts_recent = opti.ts_val;
1528 }
1529
1530 if (tlen == 0) {
1531 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1532 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1533 tp->snd_cwnd >= tp->snd_wnd &&
1534 tp->t_dupacks < tcprexmtthresh) {
1535 /*
1536 * this is a pure ack for outstanding data.
1537 */
1538 ++tcpstat.tcps_predack;
1539 if (opti.ts_present && opti.ts_ecr)
1540 tcp_xmit_timer(tp,
1541 TCP_TIMESTAMP(tp) - opti.ts_ecr + 1);
1542 else if (tp->t_rtttime &&
1543 SEQ_GT(th->th_ack, tp->t_rtseq))
1544 tcp_xmit_timer(tp,
1545 tcp_now - tp->t_rtttime);
1546 acked = th->th_ack - tp->snd_una;
1547 tcpstat.tcps_rcvackpack++;
1548 tcpstat.tcps_rcvackbyte += acked;
1549 ND6_HINT(tp);
1550
1551 if (acked > (tp->t_lastoff - tp->t_inoff))
1552 tp->t_lastm = NULL;
1553 sbdrop(&so->so_snd, acked);
1554 tp->t_lastoff -= acked;
1555
1556 /*
1557 * We want snd_recover to track snd_una to
1558 * avoid sequence wraparound problems for
1559 * very large transfers.
1560 */
1561 tp->snd_una = tp->snd_recover = th->th_ack;
1562 m_freem(m);
1563
1564 /*
1565 * If all outstanding data are acked, stop
1566 * retransmit timer, otherwise restart timer
1567 * using current (possibly backed-off) value.
1568 * If process is waiting for space,
1569 * wakeup/selwakeup/signal. If data
1570 * are ready to send, let tcp_output
1571 * decide between more output or persist.
1572 */
1573 if (tp->snd_una == tp->snd_max)
1574 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1575 else if (TCP_TIMER_ISARMED(tp,
1576 TCPT_PERSIST) == 0)
1577 TCP_TIMER_ARM(tp, TCPT_REXMT,
1578 tp->t_rxtcur);
1579
1580 sowwakeup(so);
1581 if (so->so_snd.sb_cc)
1582 (void) tcp_output(tp);
1583 if (tcp_saveti)
1584 m_freem(tcp_saveti);
1585 return;
1586 }
1587 } else if (th->th_ack == tp->snd_una &&
1588 TAILQ_FIRST(&tp->segq) == NULL &&
1589 tlen <= sbspace(&so->so_rcv)) {
1590 /*
1591 * this is a pure, in-sequence data packet
1592 * with nothing on the reassembly queue and
1593 * we have enough buffer space to take it.
1594 */
1595 ++tcpstat.tcps_preddat;
1596 tp->rcv_nxt += tlen;
1597 tcpstat.tcps_rcvpack++;
1598 tcpstat.tcps_rcvbyte += tlen;
1599 ND6_HINT(tp);
1600 /*
1601 * Drop TCP, IP headers and TCP options then add data
1602 * to socket buffer.
1603 */
1604 if (so->so_state & SS_CANTRCVMORE)
1605 m_freem(m);
1606 else {
1607 m_adj(m, toff + off);
1608 sbappendstream(&so->so_rcv, m);
1609 }
1610 sorwakeup(so);
1611 TCP_SETUP_ACK(tp, th);
1612 if (tp->t_flags & TF_ACKNOW)
1613 (void) tcp_output(tp);
1614 if (tcp_saveti)
1615 m_freem(tcp_saveti);
1616 return;
1617 }
1618 }
1619
1620 /*
1621 * Compute mbuf offset to TCP data segment.
1622 */
1623 hdroptlen = toff + off;
1624
1625 /*
1626 * Calculate amount of space in receive window,
1627 * and then do TCP input processing.
1628 * Receive window is amount of space in rcv queue,
1629 * but not less than advertised window.
1630 */
1631 { int win;
1632
1633 win = sbspace(&so->so_rcv);
1634 if (win < 0)
1635 win = 0;
1636 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1637 }
1638
1639 switch (tp->t_state) {
1640 case TCPS_LISTEN:
1641 /*
1642 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1643 */
1644 if (m->m_flags & (M_BCAST|M_MCAST))
1645 goto drop;
1646 switch (af) {
1647 #ifdef INET6
1648 case AF_INET6:
1649 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1650 goto drop;
1651 break;
1652 #endif /* INET6 */
1653 case AF_INET:
1654 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1655 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1656 goto drop;
1657 break;
1658 }
1659 break;
1660
1661 /*
1662 * If the state is SYN_SENT:
1663 * if seg contains an ACK, but not for our SYN, drop the input.
1664 * if seg contains a RST, then drop the connection.
1665 * if seg does not contain SYN, then drop it.
1666 * Otherwise this is an acceptable SYN segment
1667 * initialize tp->rcv_nxt and tp->irs
1668 * if seg contains ack then advance tp->snd_una
1669 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1670 * arrange for segment to be acked (eventually)
1671 * continue processing rest of data/controls, beginning with URG
1672 */
1673 case TCPS_SYN_SENT:
1674 if ((tiflags & TH_ACK) &&
1675 (SEQ_LEQ(th->th_ack, tp->iss) ||
1676 SEQ_GT(th->th_ack, tp->snd_max)))
1677 goto dropwithreset;
1678 if (tiflags & TH_RST) {
1679 if (tiflags & TH_ACK)
1680 tp = tcp_drop(tp, ECONNREFUSED);
1681 goto drop;
1682 }
1683 if ((tiflags & TH_SYN) == 0)
1684 goto drop;
1685 if (tiflags & TH_ACK) {
1686 tp->snd_una = tp->snd_recover = th->th_ack;
1687 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1688 tp->snd_nxt = tp->snd_una;
1689 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1690 }
1691 tp->irs = th->th_seq;
1692 tcp_rcvseqinit(tp);
1693 tp->t_flags |= TF_ACKNOW;
1694 tcp_mss_from_peer(tp, opti.maxseg);
1695
1696 /*
1697 * Initialize the initial congestion window. If we
1698 * had to retransmit the SYN, we must initialize cwnd
1699 * to 1 segment (i.e. the Loss Window).
1700 */
1701 if (tp->t_flags & TF_SYN_REXMT)
1702 tp->snd_cwnd = tp->t_peermss;
1703 else {
1704 int ss = tcp_init_win;
1705 #ifdef INET
1706 if (inp != NULL && in_localaddr(inp->inp_faddr))
1707 ss = tcp_init_win_local;
1708 #endif
1709 #ifdef INET6
1710 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
1711 ss = tcp_init_win_local;
1712 #endif
1713 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
1714 }
1715
1716 tcp_rmx_rtt(tp);
1717 if (tiflags & TH_ACK) {
1718 tcpstat.tcps_connects++;
1719 soisconnected(so);
1720 tcp_established(tp);
1721 /* Do window scaling on this connection? */
1722 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1723 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1724 tp->snd_scale = tp->requested_s_scale;
1725 tp->rcv_scale = tp->request_r_scale;
1726 }
1727 TCP_REASS_LOCK(tp);
1728 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1729 TCP_REASS_UNLOCK(tp);
1730 /*
1731 * if we didn't have to retransmit the SYN,
1732 * use its rtt as our initial srtt & rtt var.
1733 */
1734 if (tp->t_rtttime)
1735 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
1736 } else
1737 tp->t_state = TCPS_SYN_RECEIVED;
1738
1739 /*
1740 * Advance th->th_seq to correspond to first data byte.
1741 * If data, trim to stay within window,
1742 * dropping FIN if necessary.
1743 */
1744 th->th_seq++;
1745 if (tlen > tp->rcv_wnd) {
1746 todrop = tlen - tp->rcv_wnd;
1747 m_adj(m, -todrop);
1748 tlen = tp->rcv_wnd;
1749 tiflags &= ~TH_FIN;
1750 tcpstat.tcps_rcvpackafterwin++;
1751 tcpstat.tcps_rcvbyteafterwin += todrop;
1752 }
1753 tp->snd_wl1 = th->th_seq - 1;
1754 tp->rcv_up = th->th_seq;
1755 goto step6;
1756
1757 /*
1758 * If the state is SYN_RECEIVED:
1759 * If seg contains an ACK, but not for our SYN, drop the input
1760 * and generate an RST. See page 36, rfc793
1761 */
1762 case TCPS_SYN_RECEIVED:
1763 if ((tiflags & TH_ACK) &&
1764 (SEQ_LEQ(th->th_ack, tp->iss) ||
1765 SEQ_GT(th->th_ack, tp->snd_max)))
1766 goto dropwithreset;
1767 break;
1768 }
1769
1770 /*
1771 * States other than LISTEN or SYN_SENT.
1772 * First check timestamp, if present.
1773 * Then check that at least some bytes of segment are within
1774 * receive window. If segment begins before rcv_nxt,
1775 * drop leading data (and SYN); if nothing left, just ack.
1776 *
1777 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1778 * and it's less than ts_recent, drop it.
1779 */
1780 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1781 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1782
1783 /* Check to see if ts_recent is over 24 days old. */
1784 if ((int)(TCP_TIMESTAMP(tp) - tp->ts_recent_age) >
1785 TCP_PAWS_IDLE) {
1786 /*
1787 * Invalidate ts_recent. If this segment updates
1788 * ts_recent, the age will be reset later and ts_recent
1789 * will get a valid value. If it does not, setting
1790 * ts_recent to zero will at least satisfy the
1791 * requirement that zero be placed in the timestamp
1792 * echo reply when ts_recent isn't valid. The
1793 * age isn't reset until we get a valid ts_recent
1794 * because we don't want out-of-order segments to be
1795 * dropped when ts_recent is old.
1796 */
1797 tp->ts_recent = 0;
1798 } else {
1799 tcpstat.tcps_rcvduppack++;
1800 tcpstat.tcps_rcvdupbyte += tlen;
1801 tcpstat.tcps_pawsdrop++;
1802 goto dropafterack;
1803 }
1804 }
1805
1806 todrop = tp->rcv_nxt - th->th_seq;
1807 if (todrop > 0) {
1808 if (tiflags & TH_SYN) {
1809 tiflags &= ~TH_SYN;
1810 th->th_seq++;
1811 if (th->th_urp > 1)
1812 th->th_urp--;
1813 else {
1814 tiflags &= ~TH_URG;
1815 th->th_urp = 0;
1816 }
1817 todrop--;
1818 }
1819 if (todrop > tlen ||
1820 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1821 /*
1822 * Any valid FIN or RST must be to the left of the
1823 * window. At this point the FIN or RST must be a
1824 * duplicate or out of sequence; drop it.
1825 */
1826 if (tiflags & TH_RST)
1827 goto drop;
1828 tiflags &= ~(TH_FIN|TH_RST);
1829 /*
1830 * Send an ACK to resynchronize and drop any data.
1831 * But keep on processing for RST or ACK.
1832 */
1833 tp->t_flags |= TF_ACKNOW;
1834 todrop = tlen;
1835 tcpstat.tcps_rcvdupbyte += todrop;
1836 tcpstat.tcps_rcvduppack++;
1837 } else if ((tiflags & TH_RST) &&
1838 th->th_seq != tp->last_ack_sent) {
1839 /*
1840 * Test for reset before adjusting the sequence
1841 * number for overlapping data.
1842 */
1843 goto dropafterack_ratelim;
1844 } else {
1845 tcpstat.tcps_rcvpartduppack++;
1846 tcpstat.tcps_rcvpartdupbyte += todrop;
1847 }
1848 hdroptlen += todrop; /*drop from head afterwards*/
1849 th->th_seq += todrop;
1850 tlen -= todrop;
1851 if (th->th_urp > todrop)
1852 th->th_urp -= todrop;
1853 else {
1854 tiflags &= ~TH_URG;
1855 th->th_urp = 0;
1856 }
1857 }
1858
1859 /*
1860 * If new data are received on a connection after the
1861 * user processes are gone, then RST the other end.
1862 */
1863 if ((so->so_state & SS_NOFDREF) &&
1864 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1865 tp = tcp_close(tp);
1866 tcpstat.tcps_rcvafterclose++;
1867 goto dropwithreset;
1868 }
1869
1870 /*
1871 * If segment ends after window, drop trailing data
1872 * (and PUSH and FIN); if nothing left, just ACK.
1873 */
1874 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1875 if (todrop > 0) {
1876 tcpstat.tcps_rcvpackafterwin++;
1877 if (todrop >= tlen) {
1878 /*
1879 * The segment actually starts after the window.
1880 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
1881 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
1882 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
1883 */
1884 tcpstat.tcps_rcvbyteafterwin += tlen;
1885 /*
1886 * If a new connection request is received
1887 * while in TIME_WAIT, drop the old connection
1888 * and start over if the sequence numbers
1889 * are above the previous ones.
1890 *
1891 * NOTE: We will checksum the packet again, and
1892 * so we need to put the header fields back into
1893 * network order!
1894 * XXX This kind of sucks, but we don't expect
1895 * XXX this to happen very often, so maybe it
1896 * XXX doesn't matter so much.
1897 */
1898 if (tiflags & TH_SYN &&
1899 tp->t_state == TCPS_TIME_WAIT &&
1900 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1901 iss = tcp_new_iss(tp, tp->snd_nxt);
1902 tp = tcp_close(tp);
1903 TCP_FIELDS_TO_NET(th);
1904 goto findpcb;
1905 }
1906 /*
1907 * If window is closed can only take segments at
1908 * window edge, and have to drop data and PUSH from
1909 * incoming segments. Continue processing, but
1910 * remember to ack. Otherwise, drop segment
1911 * and (if not RST) ack.
1912 */
1913 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1914 tp->t_flags |= TF_ACKNOW;
1915 tcpstat.tcps_rcvwinprobe++;
1916 } else
1917 goto dropafterack;
1918 } else
1919 tcpstat.tcps_rcvbyteafterwin += todrop;
1920 m_adj(m, -todrop);
1921 tlen -= todrop;
1922 tiflags &= ~(TH_PUSH|TH_FIN);
1923 }
1924
1925 /*
1926 * If last ACK falls within this segment's sequence numbers,
1927 * and the timestamp is newer, record it.
1928 */
1929 if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1930 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1931 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
1932 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1933 tp->ts_recent_age = TCP_TIMESTAMP(tp);
1934 tp->ts_recent = opti.ts_val;
1935 }
1936
1937 /*
1938 * If the RST bit is set examine the state:
1939 * SYN_RECEIVED STATE:
1940 * If passive open, return to LISTEN state.
1941 * If active open, inform user that connection was refused.
1942 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1943 * Inform user that connection was reset, and close tcb.
1944 * CLOSING, LAST_ACK, TIME_WAIT STATES
1945 * Close the tcb.
1946 */
1947 if (tiflags & TH_RST) {
1948 if (th->th_seq != tp->last_ack_sent)
1949 goto dropafterack_ratelim;
1950
1951 switch (tp->t_state) {
1952 case TCPS_SYN_RECEIVED:
1953 so->so_error = ECONNREFUSED;
1954 goto close;
1955
1956 case TCPS_ESTABLISHED:
1957 case TCPS_FIN_WAIT_1:
1958 case TCPS_FIN_WAIT_2:
1959 case TCPS_CLOSE_WAIT:
1960 so->so_error = ECONNRESET;
1961 close:
1962 tp->t_state = TCPS_CLOSED;
1963 tcpstat.tcps_drops++;
1964 tp = tcp_close(tp);
1965 goto drop;
1966
1967 case TCPS_CLOSING:
1968 case TCPS_LAST_ACK:
1969 case TCPS_TIME_WAIT:
1970 tp = tcp_close(tp);
1971 goto drop;
1972 }
1973 }
1974
1975 /*
1976 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
1977 * we must be in a synchronized state. RFC791 states (under RST
1978 * generation) that any unacceptable segment (an out-of-order SYN
1979 * qualifies) received in a synchronized state must elicit only an
1980 * empty acknowledgment segment ... and the connection remains in
1981 * the same state.
1982 */
1983 if (tiflags & TH_SYN) {
1984 if (tp->rcv_nxt == th->th_seq) {
1985 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
1986 TH_ACK);
1987 if (tcp_saveti)
1988 m_freem(tcp_saveti);
1989 return;
1990 }
1991
1992 goto dropafterack_ratelim;
1993 }
1994
1995 /*
1996 * If the ACK bit is off we drop the segment and return.
1997 */
1998 if ((tiflags & TH_ACK) == 0) {
1999 if (tp->t_flags & TF_ACKNOW)
2000 goto dropafterack;
2001 else
2002 goto drop;
2003 }
2004
2005 /*
2006 * Ack processing.
2007 */
2008 switch (tp->t_state) {
2009
2010 /*
2011 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2012 * ESTABLISHED state and continue processing, otherwise
2013 * send an RST.
2014 */
2015 case TCPS_SYN_RECEIVED:
2016 if (SEQ_GT(tp->snd_una, th->th_ack) ||
2017 SEQ_GT(th->th_ack, tp->snd_max))
2018 goto dropwithreset;
2019 tcpstat.tcps_connects++;
2020 soisconnected(so);
2021 tcp_established(tp);
2022 /* Do window scaling? */
2023 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2024 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2025 tp->snd_scale = tp->requested_s_scale;
2026 tp->rcv_scale = tp->request_r_scale;
2027 }
2028 TCP_REASS_LOCK(tp);
2029 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
2030 TCP_REASS_UNLOCK(tp);
2031 tp->snd_wl1 = th->th_seq - 1;
2032 /* fall into ... */
2033
2034 /*
2035 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2036 * ACKs. If the ack is in the range
2037 * tp->snd_una < th->th_ack <= tp->snd_max
2038 * then advance tp->snd_una to th->th_ack and drop
2039 * data from the retransmission queue. If this ACK reflects
2040 * more up to date window information we update our window information.
2041 */
2042 case TCPS_ESTABLISHED:
2043 case TCPS_FIN_WAIT_1:
2044 case TCPS_FIN_WAIT_2:
2045 case TCPS_CLOSE_WAIT:
2046 case TCPS_CLOSING:
2047 case TCPS_LAST_ACK:
2048 case TCPS_TIME_WAIT:
2049
2050 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2051 if (tlen == 0 && tiwin == tp->snd_wnd) {
2052 tcpstat.tcps_rcvdupack++;
2053 /*
2054 * If we have outstanding data (other than
2055 * a window probe), this is a completely
2056 * duplicate ack (ie, window info didn't
2057 * change), the ack is the biggest we've
2058 * seen and we've seen exactly our rexmt
2059 * threshhold of them, assume a packet
2060 * has been dropped and retransmit it.
2061 * Kludge snd_nxt & the congestion
2062 * window so we send only this one
2063 * packet.
2064 *
2065 * We know we're losing at the current
2066 * window size so do congestion avoidance
2067 * (set ssthresh to half the current window
2068 * and pull our congestion window back to
2069 * the new ssthresh).
2070 *
2071 * Dup acks mean that packets have left the
2072 * network (they're now cached at the receiver)
2073 * so bump cwnd by the amount in the receiver
2074 * to keep a constant cwnd packets in the
2075 * network.
2076 */
2077 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2078 th->th_ack != tp->snd_una)
2079 tp->t_dupacks = 0;
2080 else if (++tp->t_dupacks == tcprexmtthresh) {
2081 tcp_seq onxt = tp->snd_nxt;
2082 u_int win =
2083 min(tp->snd_wnd, tp->snd_cwnd) /
2084 2 / tp->t_segsz;
2085 if (tcp_do_newreno && SEQ_LT(th->th_ack,
2086 tp->snd_recover)) {
2087 /*
2088 * False fast retransmit after
2089 * timeout. Do not cut window.
2090 */
2091 tp->snd_cwnd += tp->t_segsz;
2092 tp->t_dupacks = 0;
2093 (void) tcp_output(tp);
2094 goto drop;
2095 }
2096
2097 if (win < 2)
2098 win = 2;
2099 tp->snd_ssthresh = win * tp->t_segsz;
2100 tp->snd_recover = tp->snd_max;
2101 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2102 tp->t_rtttime = 0;
2103 tp->snd_nxt = th->th_ack;
2104 tp->snd_cwnd = tp->t_segsz;
2105 (void) tcp_output(tp);
2106 tp->snd_cwnd = tp->snd_ssthresh +
2107 tp->t_segsz * tp->t_dupacks;
2108 if (SEQ_GT(onxt, tp->snd_nxt))
2109 tp->snd_nxt = onxt;
2110 goto drop;
2111 } else if (tp->t_dupacks > tcprexmtthresh) {
2112 tp->snd_cwnd += tp->t_segsz;
2113 (void) tcp_output(tp);
2114 goto drop;
2115 }
2116 } else if (tlen) {
2117 tp->t_dupacks = 0; /*XXX*/
2118 /* drop very old ACKs unless th_seq matches */
2119 if (th->th_seq != tp->rcv_nxt &&
2120 SEQ_LT(th->th_ack,
2121 tp->snd_una - tp->max_sndwnd)) {
2122 goto drop;
2123 }
2124 break;
2125 } else
2126 tp->t_dupacks = 0;
2127 break;
2128 }
2129 /*
2130 * If the congestion window was inflated to account
2131 * for the other side's cached packets, retract it.
2132 */
2133 if (tcp_do_newreno == 0) {
2134 if (tp->t_dupacks >= tcprexmtthresh &&
2135 tp->snd_cwnd > tp->snd_ssthresh)
2136 tp->snd_cwnd = tp->snd_ssthresh;
2137 tp->t_dupacks = 0;
2138 } else if (tp->t_dupacks >= tcprexmtthresh &&
2139 tcp_newreno(tp, th) == 0) {
2140 tp->snd_cwnd = tp->snd_ssthresh;
2141 /*
2142 * Window inflation should have left us with approx.
2143 * snd_ssthresh outstanding data. But in case we
2144 * would be inclined to send a burst, better to do
2145 * it via the slow start mechanism.
2146 */
2147 if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
2148 tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
2149 + tp->t_segsz;
2150 tp->t_dupacks = 0;
2151 }
2152 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2153 tcpstat.tcps_rcvacktoomuch++;
2154 goto dropafterack;
2155 }
2156 acked = th->th_ack - tp->snd_una;
2157 tcpstat.tcps_rcvackpack++;
2158 tcpstat.tcps_rcvackbyte += acked;
2159
2160 /*
2161 * If we have a timestamp reply, update smoothed
2162 * round trip time. If no timestamp is present but
2163 * transmit timer is running and timed sequence
2164 * number was acked, update smoothed round trip time.
2165 * Since we now have an rtt measurement, cancel the
2166 * timer backoff (cf., Phil Karn's retransmit alg.).
2167 * Recompute the initial retransmit timer.
2168 */
2169 if (opti.ts_present && opti.ts_ecr)
2170 tcp_xmit_timer(tp, TCP_TIMESTAMP(tp) - opti.ts_ecr + 1);
2171 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2172 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2173
2174 /*
2175 * If all outstanding data is acked, stop retransmit
2176 * timer and remember to restart (more output or persist).
2177 * If there is more data to be acked, restart retransmit
2178 * timer, using current (possibly backed-off) value.
2179 */
2180 if (th->th_ack == tp->snd_max) {
2181 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2182 needoutput = 1;
2183 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2184 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2185 /*
2186 * When new data is acked, open the congestion window.
2187 * If the window gives us less than ssthresh packets
2188 * in flight, open exponentially (segsz per packet).
2189 * Otherwise open linearly: segsz per window
2190 * (segsz^2 / cwnd per packet), plus a constant
2191 * fraction of a packet (segsz/8) to help larger windows
2192 * open quickly enough.
2193 */
2194 {
2195 u_int cw = tp->snd_cwnd;
2196 u_int incr = tp->t_segsz;
2197
2198 if (cw > tp->snd_ssthresh)
2199 incr = incr * incr / cw;
2200 if (tcp_do_newreno == 0 || SEQ_GEQ(th->th_ack, tp->snd_recover))
2201 tp->snd_cwnd = min(cw + incr,
2202 TCP_MAXWIN << tp->snd_scale);
2203 }
2204 ND6_HINT(tp);
2205 if (acked > so->so_snd.sb_cc) {
2206 tp->snd_wnd -= so->so_snd.sb_cc;
2207 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2208 ourfinisacked = 1;
2209 } else {
2210 if (acked > (tp->t_lastoff - tp->t_inoff))
2211 tp->t_lastm = NULL;
2212 sbdrop(&so->so_snd, acked);
2213 tp->t_lastoff -= acked;
2214 tp->snd_wnd -= acked;
2215 ourfinisacked = 0;
2216 }
2217 sowwakeup(so);
2218 /*
2219 * We want snd_recover to track snd_una to
2220 * avoid sequence wraparound problems for
2221 * very large transfers.
2222 */
2223 tp->snd_una = tp->snd_recover = th->th_ack;
2224 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2225 tp->snd_nxt = tp->snd_una;
2226
2227 switch (tp->t_state) {
2228
2229 /*
2230 * In FIN_WAIT_1 STATE in addition to the processing
2231 * for the ESTABLISHED state if our FIN is now acknowledged
2232 * then enter FIN_WAIT_2.
2233 */
2234 case TCPS_FIN_WAIT_1:
2235 if (ourfinisacked) {
2236 /*
2237 * If we can't receive any more
2238 * data, then closing user can proceed.
2239 * Starting the timer is contrary to the
2240 * specification, but if we don't get a FIN
2241 * we'll hang forever.
2242 */
2243 if (so->so_state & SS_CANTRCVMORE) {
2244 soisdisconnected(so);
2245 if (tcp_maxidle > 0)
2246 TCP_TIMER_ARM(tp, TCPT_2MSL,
2247 tcp_maxidle);
2248 }
2249 tp->t_state = TCPS_FIN_WAIT_2;
2250 }
2251 break;
2252
2253 /*
2254 * In CLOSING STATE in addition to the processing for
2255 * the ESTABLISHED state if the ACK acknowledges our FIN
2256 * then enter the TIME-WAIT state, otherwise ignore
2257 * the segment.
2258 */
2259 case TCPS_CLOSING:
2260 if (ourfinisacked) {
2261 tp->t_state = TCPS_TIME_WAIT;
2262 tcp_canceltimers(tp);
2263 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2264 soisdisconnected(so);
2265 }
2266 break;
2267
2268 /*
2269 * In LAST_ACK, we may still be waiting for data to drain
2270 * and/or to be acked, as well as for the ack of our FIN.
2271 * If our FIN is now acknowledged, delete the TCB,
2272 * enter the closed state and return.
2273 */
2274 case TCPS_LAST_ACK:
2275 if (ourfinisacked) {
2276 tp = tcp_close(tp);
2277 goto drop;
2278 }
2279 break;
2280
2281 /*
2282 * In TIME_WAIT state the only thing that should arrive
2283 * is a retransmission of the remote FIN. Acknowledge
2284 * it and restart the finack timer.
2285 */
2286 case TCPS_TIME_WAIT:
2287 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2288 goto dropafterack;
2289 }
2290 }
2291
2292 step6:
2293 /*
2294 * Update window information.
2295 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2296 */
2297 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2298 (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
2299 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
2300 /* keep track of pure window updates */
2301 if (tlen == 0 &&
2302 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2303 tcpstat.tcps_rcvwinupd++;
2304 tp->snd_wnd = tiwin;
2305 tp->snd_wl1 = th->th_seq;
2306 tp->snd_wl2 = th->th_ack;
2307 if (tp->snd_wnd > tp->max_sndwnd)
2308 tp->max_sndwnd = tp->snd_wnd;
2309 needoutput = 1;
2310 }
2311
2312 /*
2313 * Process segments with URG.
2314 */
2315 if ((tiflags & TH_URG) && th->th_urp &&
2316 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2317 /*
2318 * This is a kludge, but if we receive and accept
2319 * random urgent pointers, we'll crash in
2320 * soreceive. It's hard to imagine someone
2321 * actually wanting to send this much urgent data.
2322 */
2323 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2324 th->th_urp = 0; /* XXX */
2325 tiflags &= ~TH_URG; /* XXX */
2326 goto dodata; /* XXX */
2327 }
2328 /*
2329 * If this segment advances the known urgent pointer,
2330 * then mark the data stream. This should not happen
2331 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2332 * a FIN has been received from the remote side.
2333 * In these states we ignore the URG.
2334 *
2335 * According to RFC961 (Assigned Protocols),
2336 * the urgent pointer points to the last octet
2337 * of urgent data. We continue, however,
2338 * to consider it to indicate the first octet
2339 * of data past the urgent section as the original
2340 * spec states (in one of two places).
2341 */
2342 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2343 tp->rcv_up = th->th_seq + th->th_urp;
2344 so->so_oobmark = so->so_rcv.sb_cc +
2345 (tp->rcv_up - tp->rcv_nxt) - 1;
2346 if (so->so_oobmark == 0)
2347 so->so_state |= SS_RCVATMARK;
2348 sohasoutofband(so);
2349 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2350 }
2351 /*
2352 * Remove out of band data so doesn't get presented to user.
2353 * This can happen independent of advancing the URG pointer,
2354 * but if two URG's are pending at once, some out-of-band
2355 * data may creep in... ick.
2356 */
2357 if (th->th_urp <= (u_int16_t) tlen
2358 #ifdef SO_OOBINLINE
2359 && (so->so_options & SO_OOBINLINE) == 0
2360 #endif
2361 )
2362 tcp_pulloutofband(so, th, m, hdroptlen);
2363 } else
2364 /*
2365 * If no out of band data is expected,
2366 * pull receive urgent pointer along
2367 * with the receive window.
2368 */
2369 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2370 tp->rcv_up = tp->rcv_nxt;
2371 dodata: /* XXX */
2372
2373 /*
2374 * Process the segment text, merging it into the TCP sequencing queue,
2375 * and arranging for acknowledgement of receipt if necessary.
2376 * This process logically involves adjusting tp->rcv_wnd as data
2377 * is presented to the user (this happens in tcp_usrreq.c,
2378 * case PRU_RCVD). If a FIN has already been received on this
2379 * connection then we just ignore the text.
2380 */
2381 if ((tlen || (tiflags & TH_FIN)) &&
2382 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2383 /*
2384 * Insert segment ti into reassembly queue of tcp with
2385 * control block tp. Return TH_FIN if reassembly now includes
2386 * a segment with FIN. The macro form does the common case
2387 * inline (segment is the next to be received on an
2388 * established connection, and the queue is empty),
2389 * avoiding linkage into and removal from the queue and
2390 * repetition of various conversions.
2391 * Set DELACK for segments received in order, but ack
2392 * immediately when segments are out of order
2393 * (so fast retransmit can work).
2394 */
2395 /* NOTE: this was TCP_REASS() macro, but used only once */
2396 TCP_REASS_LOCK(tp);
2397 if (th->th_seq == tp->rcv_nxt &&
2398 TAILQ_FIRST(&tp->segq) == NULL &&
2399 tp->t_state == TCPS_ESTABLISHED) {
2400 TCP_SETUP_ACK(tp, th);
2401 tp->rcv_nxt += tlen;
2402 tiflags = th->th_flags & TH_FIN;
2403 tcpstat.tcps_rcvpack++;
2404 tcpstat.tcps_rcvbyte += tlen;
2405 ND6_HINT(tp);
2406 if (so->so_state & SS_CANTRCVMORE)
2407 m_freem(m);
2408 else {
2409 m_adj(m, hdroptlen);
2410 sbappendstream(&(so)->so_rcv, m);
2411 }
2412 sorwakeup(so);
2413 } else {
2414 m_adj(m, hdroptlen);
2415 tiflags = tcp_reass(tp, th, m, &tlen);
2416 tp->t_flags |= TF_ACKNOW;
2417 }
2418 TCP_REASS_UNLOCK(tp);
2419
2420 /*
2421 * Note the amount of data that peer has sent into
2422 * our window, in order to estimate the sender's
2423 * buffer size.
2424 */
2425 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2426 } else {
2427 m_freem(m);
2428 m = NULL;
2429 tiflags &= ~TH_FIN;
2430 }
2431
2432 /*
2433 * If FIN is received ACK the FIN and let the user know
2434 * that the connection is closing. Ignore a FIN received before
2435 * the connection is fully established.
2436 */
2437 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2438 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2439 socantrcvmore(so);
2440 tp->t_flags |= TF_ACKNOW;
2441 tp->rcv_nxt++;
2442 }
2443 switch (tp->t_state) {
2444
2445 /*
2446 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2447 */
2448 case TCPS_ESTABLISHED:
2449 tp->t_state = TCPS_CLOSE_WAIT;
2450 break;
2451
2452 /*
2453 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2454 * enter the CLOSING state.
2455 */
2456 case TCPS_FIN_WAIT_1:
2457 tp->t_state = TCPS_CLOSING;
2458 break;
2459
2460 /*
2461 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2462 * starting the time-wait timer, turning off the other
2463 * standard timers.
2464 */
2465 case TCPS_FIN_WAIT_2:
2466 tp->t_state = TCPS_TIME_WAIT;
2467 tcp_canceltimers(tp);
2468 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2469 soisdisconnected(so);
2470 break;
2471
2472 /*
2473 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2474 */
2475 case TCPS_TIME_WAIT:
2476 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2477 break;
2478 }
2479 }
2480 #ifdef TCP_DEBUG
2481 if (so->so_options & SO_DEBUG)
2482 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2483 #endif
2484
2485 /*
2486 * Return any desired output.
2487 */
2488 if (needoutput || (tp->t_flags & TF_ACKNOW))
2489 (void) tcp_output(tp);
2490 if (tcp_saveti)
2491 m_freem(tcp_saveti);
2492 return;
2493
2494 badsyn:
2495 /*
2496 * Received a bad SYN. Increment counters and dropwithreset.
2497 */
2498 tcpstat.tcps_badsyn++;
2499 tp = NULL;
2500 goto dropwithreset;
2501
2502 dropafterack:
2503 /*
2504 * Generate an ACK dropping incoming segment if it occupies
2505 * sequence space, where the ACK reflects our state.
2506 */
2507 if (tiflags & TH_RST)
2508 goto drop;
2509 goto dropafterack2;
2510
2511 dropafterack_ratelim:
2512 /*
2513 * We may want to rate-limit ACKs against SYN/RST attack.
2514 */
2515 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2516 tcp_ackdrop_ppslim) == 0) {
2517 /* XXX stat */
2518 goto drop;
2519 }
2520 /* ...fall into dropafterack2... */
2521
2522 dropafterack2:
2523 m_freem(m);
2524 tp->t_flags |= TF_ACKNOW;
2525 (void) tcp_output(tp);
2526 if (tcp_saveti)
2527 m_freem(tcp_saveti);
2528 return;
2529
2530 dropwithreset_ratelim:
2531 /*
2532 * We may want to rate-limit RSTs in certain situations,
2533 * particularly if we are sending an RST in response to
2534 * an attempt to connect to or otherwise communicate with
2535 * a port for which we have no socket.
2536 */
2537 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2538 tcp_rst_ppslim) == 0) {
2539 /* XXX stat */
2540 goto drop;
2541 }
2542 /* ...fall into dropwithreset... */
2543
2544 dropwithreset:
2545 /*
2546 * Generate a RST, dropping incoming segment.
2547 * Make ACK acceptable to originator of segment.
2548 */
2549 if (tiflags & TH_RST)
2550 goto drop;
2551
2552 switch (af) {
2553 #ifdef INET6
2554 case AF_INET6:
2555 /* For following calls to tcp_respond */
2556 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2557 goto drop;
2558 break;
2559 #endif /* INET6 */
2560 case AF_INET:
2561 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
2562 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2563 goto drop;
2564 }
2565
2566 if (tiflags & TH_ACK)
2567 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2568 else {
2569 if (tiflags & TH_SYN)
2570 tlen++;
2571 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2572 TH_RST|TH_ACK);
2573 }
2574 if (tcp_saveti)
2575 m_freem(tcp_saveti);
2576 return;
2577
2578 badcsum:
2579 drop:
2580 /*
2581 * Drop space held by incoming segment and return.
2582 */
2583 if (tp) {
2584 if (tp->t_inpcb)
2585 so = tp->t_inpcb->inp_socket;
2586 #ifdef INET6
2587 else if (tp->t_in6pcb)
2588 so = tp->t_in6pcb->in6p_socket;
2589 #endif
2590 else
2591 so = NULL;
2592 #ifdef TCP_DEBUG
2593 if (so && (so->so_options & SO_DEBUG) != 0)
2594 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2595 #endif
2596 }
2597 if (tcp_saveti)
2598 m_freem(tcp_saveti);
2599 m_freem(m);
2600 return;
2601 }
2602
2603 #ifdef TCP_SIGNATURE
2604 int
2605 tcp_signature_apply(void *fstate, caddr_t data, u_int len)
2606 {
2607
2608 MD5Update(fstate, (u_char *)data, len);
2609 return (0);
2610 }
2611
2612 struct secasvar *
2613 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
2614 {
2615 struct secasvar *sav;
2616 #ifdef FAST_IPSEC
2617 union sockaddr_union dst;
2618 #endif
2619 struct ip *ip;
2620 struct ip6_hdr *ip6;
2621
2622 ip = mtod(m, struct ip *);
2623 switch (ip->ip_v) {
2624 case 4:
2625 ip = mtod(m, struct ip *);
2626 ip6 = NULL;
2627 break;
2628 case 6:
2629 ip = NULL;
2630 ip6 = mtod(m, struct ip6_hdr *);
2631 break;
2632 default:
2633 return (NULL);
2634 }
2635
2636 #ifdef FAST_IPSEC
2637 /* Extract the destination from the IP header in the mbuf. */
2638 bzero(&dst, sizeof(union sockaddr_union));
2639 dst.sa.sa_len = sizeof(struct sockaddr_in);
2640 dst.sa.sa_family = AF_INET;
2641 dst.sin.sin_addr = ip->ip_dst;
2642
2643 /*
2644 * Look up an SADB entry which matches the address of the peer.
2645 */
2646 sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2647 #else
2648 if (ip)
2649 sav = key_allocsa(AF_INET, (caddr_t)&ip->ip_src,
2650 (caddr_t)&ip->ip_dst, IPPROTO_TCP,
2651 htonl(TCP_SIG_SPI));
2652 else
2653 sav = key_allocsa(AF_INET6, (caddr_t)&ip6->ip6_src,
2654 (caddr_t)&ip6->ip6_dst, IPPROTO_TCP,
2655 htonl(TCP_SIG_SPI));
2656 #endif
2657
2658 return (sav); /* freesav must be performed by caller */
2659 }
2660
2661 int
2662 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
2663 struct secasvar *sav, char *sig)
2664 {
2665 MD5_CTX ctx;
2666 struct ip *ip;
2667 struct ipovly *ipovly;
2668 struct ip6_hdr *ip6;
2669 struct ippseudo ippseudo;
2670 struct ip6_hdr_pseudo ip6pseudo;
2671 struct tcphdr th0;
2672 int l, tcphdrlen;
2673
2674 if (sav == NULL)
2675 return (-1);
2676
2677 tcphdrlen = th->th_off * 4;
2678
2679 switch (mtod(m, struct ip *)->ip_v) {
2680 case 4:
2681 ip = mtod(m, struct ip *);
2682 ip6 = NULL;
2683 break;
2684 case 6:
2685 ip = NULL;
2686 ip6 = mtod(m, struct ip6_hdr *);
2687 break;
2688 default:
2689 return (-1);
2690 }
2691
2692 MD5Init(&ctx);
2693
2694 if (ip) {
2695 memset(&ippseudo, 0, sizeof(ippseudo));
2696 ipovly = (struct ipovly *)ip;
2697 ippseudo.ippseudo_src = ipovly->ih_src;
2698 ippseudo.ippseudo_dst = ipovly->ih_dst;
2699 ippseudo.ippseudo_pad = 0;
2700 ippseudo.ippseudo_p = IPPROTO_TCP;
2701 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
2702 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
2703 } else {
2704 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
2705 ip6pseudo.ip6ph_src = ip6->ip6_src;
2706 in6_clearscope(&ip6pseudo.ip6ph_src);
2707 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
2708 in6_clearscope(&ip6pseudo.ip6ph_dst);
2709 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
2710 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
2711 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
2712 }
2713
2714 th0 = *th;
2715 th0.th_sum = 0;
2716 MD5Update(&ctx, (char *)&th0, sizeof(th0));
2717
2718 l = m->m_pkthdr.len - thoff - tcphdrlen;
2719 if (l > 0)
2720 m_apply(m, thoff + tcphdrlen,
2721 m->m_pkthdr.len - thoff - tcphdrlen,
2722 tcp_signature_apply, &ctx);
2723
2724 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2725 MD5Final(sig, &ctx);
2726
2727 return (0);
2728 }
2729 #endif
2730
2731 int
2732 tcp_dooptions(tp, cp, cnt, th, m, toff, oi)
2733 struct tcpcb *tp;
2734 u_char *cp;
2735 int cnt;
2736 struct tcphdr *th;
2737 struct mbuf *m;
2738 int toff;
2739 struct tcp_opt_info *oi;
2740 {
2741 u_int16_t mss;
2742 int opt, optlen = 0;
2743 #ifdef TCP_SIGNATURE
2744 caddr_t sigp = NULL;
2745 char sigbuf[TCP_SIGLEN];
2746 struct secasvar *sav = NULL;
2747 #endif
2748
2749 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
2750 opt = cp[0];
2751 if (opt == TCPOPT_EOL)
2752 break;
2753 if (opt == TCPOPT_NOP)
2754 optlen = 1;
2755 else {
2756 if (cnt < 2)
2757 break;
2758 optlen = cp[1];
2759 if (optlen < 2 || optlen > cnt)
2760 break;
2761 }
2762 switch (opt) {
2763
2764 default:
2765 continue;
2766
2767 case TCPOPT_MAXSEG:
2768 if (optlen != TCPOLEN_MAXSEG)
2769 continue;
2770 if (!(th->th_flags & TH_SYN))
2771 continue;
2772 bcopy(cp + 2, &mss, sizeof(mss));
2773 oi->maxseg = ntohs(mss);
2774 break;
2775
2776 case TCPOPT_WINDOW:
2777 if (optlen != TCPOLEN_WINDOW)
2778 continue;
2779 if (!(th->th_flags & TH_SYN))
2780 continue;
2781 tp->t_flags |= TF_RCVD_SCALE;
2782 tp->requested_s_scale = cp[2];
2783 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2784 #if 0 /*XXX*/
2785 char *p;
2786
2787 if (ip)
2788 p = ntohl(ip->ip_src);
2789 #ifdef INET6
2790 else if (ip6)
2791 p = ip6_sprintf(&ip6->ip6_src);
2792 #endif
2793 else
2794 p = "(unknown)";
2795 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2796 "assuming %d\n",
2797 tp->requested_s_scale, p,
2798 TCP_MAX_WINSHIFT);
2799 #else
2800 log(LOG_ERR, "TCP: invalid wscale %d, "
2801 "assuming %d\n",
2802 tp->requested_s_scale,
2803 TCP_MAX_WINSHIFT);
2804 #endif
2805 tp->requested_s_scale = TCP_MAX_WINSHIFT;
2806 }
2807 break;
2808
2809 case TCPOPT_TIMESTAMP:
2810 if (optlen != TCPOLEN_TIMESTAMP)
2811 continue;
2812 oi->ts_present = 1;
2813 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2814 NTOHL(oi->ts_val);
2815 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2816 NTOHL(oi->ts_ecr);
2817
2818 /*
2819 * A timestamp received in a SYN makes
2820 * it ok to send timestamp requests and replies.
2821 */
2822 if (th->th_flags & TH_SYN) {
2823 tp->t_flags |= TF_RCVD_TSTMP;
2824 tp->ts_recent = oi->ts_val;
2825 tp->ts_recent_age = TCP_TIMESTAMP(tp);
2826 }
2827 break;
2828 case TCPOPT_SACK_PERMITTED:
2829 if (optlen != TCPOLEN_SACK_PERMITTED)
2830 continue;
2831 if (!(th->th_flags & TH_SYN))
2832 continue;
2833 tp->t_flags &= ~TF_CANT_TXSACK;
2834 break;
2835
2836 case TCPOPT_SACK:
2837 if (tp->t_flags & TF_IGNR_RXSACK)
2838 continue;
2839 if (optlen % 8 != 2 || optlen < 10)
2840 continue;
2841 cp += 2;
2842 optlen -= 2;
2843 for (; optlen > 0; cp -= 8, optlen -= 8) {
2844 tcp_seq lwe, rwe;
2845 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
2846 NTOHL(lwe);
2847 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
2848 NTOHL(rwe);
2849 /* tcp_mark_sacked(tp, lwe, rwe); */
2850 }
2851 break;
2852 #ifdef TCP_SIGNATURE
2853 case TCPOPT_SIGNATURE:
2854 if (optlen != TCPOLEN_SIGNATURE)
2855 continue;
2856 if (sigp && bcmp(sigp, cp + 2, TCP_SIGLEN))
2857 return (-1);
2858
2859 sigp = sigbuf;
2860 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
2861 memset(cp + 2, 0, TCP_SIGLEN);
2862 tp->t_flags |= TF_SIGNATURE;
2863 break;
2864 #endif
2865 }
2866 }
2867
2868 #ifdef TCP_SIGNATURE
2869 if (tp->t_flags & TF_SIGNATURE) {
2870
2871 sav = tcp_signature_getsav(m, th);
2872
2873 if (sav == NULL && tp->t_state == TCPS_LISTEN)
2874 return (-1);
2875 }
2876
2877 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) {
2878 if (sav == NULL)
2879 return (-1);
2880 #ifdef FAST_IPSEC
2881 KEY_FREESAV(&sav);
2882 #else
2883 key_freesav(sav);
2884 #endif
2885 return (-1);
2886 }
2887
2888 if (sigp) {
2889 char sig[TCP_SIGLEN];
2890
2891 TCP_FIELDS_TO_NET(th);
2892 if (tcp_signature(m, th, toff, sav, sig) < 0) {
2893 TCP_FIELDS_TO_HOST(th);
2894 if (sav == NULL)
2895 return (-1);
2896 #ifdef FAST_IPSEC
2897 KEY_FREESAV(&sav);
2898 #else
2899 key_freesav(sav);
2900 #endif
2901 return (-1);
2902 }
2903 TCP_FIELDS_TO_HOST(th);
2904
2905 if (bcmp(sig, sigp, TCP_SIGLEN)) {
2906 tcpstat.tcps_badsig++;
2907 if (sav == NULL)
2908 return (-1);
2909 #ifdef FAST_IPSEC
2910 KEY_FREESAV(&sav);
2911 #else
2912 key_freesav(sav);
2913 #endif
2914 return (-1);
2915 } else
2916 tcpstat.tcps_goodsig++;
2917
2918 key_sa_recordxfer(sav, m);
2919 #ifdef FAST_IPSEC
2920 KEY_FREESAV(&sav);
2921 #else
2922 key_freesav(sav);
2923 #endif
2924 }
2925 #endif
2926
2927 return (0);
2928 }
2929
2930 /*
2931 * Pull out of band byte out of a segment so
2932 * it doesn't appear in the user's data queue.
2933 * It is still reflected in the segment length for
2934 * sequencing purposes.
2935 */
2936 void
2937 tcp_pulloutofband(so, th, m, off)
2938 struct socket *so;
2939 struct tcphdr *th;
2940 struct mbuf *m;
2941 int off;
2942 {
2943 int cnt = off + th->th_urp - 1;
2944
2945 while (cnt >= 0) {
2946 if (m->m_len > cnt) {
2947 char *cp = mtod(m, caddr_t) + cnt;
2948 struct tcpcb *tp = sototcpcb(so);
2949
2950 tp->t_iobc = *cp;
2951 tp->t_oobflags |= TCPOOB_HAVEDATA;
2952 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2953 m->m_len--;
2954 return;
2955 }
2956 cnt -= m->m_len;
2957 m = m->m_next;
2958 if (m == 0)
2959 break;
2960 }
2961 panic("tcp_pulloutofband");
2962 }
2963
2964 /*
2965 * Collect new round-trip time estimate
2966 * and update averages and current timeout.
2967 */
2968 void
2969 tcp_xmit_timer(tp, rtt)
2970 struct tcpcb *tp;
2971 uint32_t rtt;
2972 {
2973 int32_t delta;
2974
2975 tcpstat.tcps_rttupdated++;
2976 if (tp->t_srtt != 0) {
2977 /*
2978 * srtt is stored as fixed point with 3 bits after the
2979 * binary point (i.e., scaled by 8). The following magic
2980 * is equivalent to the smoothing algorithm in rfc793 with
2981 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2982 * point). Adjust rtt to origin 0.
2983 */
2984 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2985 if ((tp->t_srtt += delta) <= 0)
2986 tp->t_srtt = 1 << 2;
2987 /*
2988 * We accumulate a smoothed rtt variance (actually, a
2989 * smoothed mean difference), then set the retransmit
2990 * timer to smoothed rtt + 4 times the smoothed variance.
2991 * rttvar is stored as fixed point with 2 bits after the
2992 * binary point (scaled by 4). The following is
2993 * equivalent to rfc793 smoothing with an alpha of .75
2994 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2995 * rfc793's wired-in beta.
2996 */
2997 if (delta < 0)
2998 delta = -delta;
2999 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3000 if ((tp->t_rttvar += delta) <= 0)
3001 tp->t_rttvar = 1 << 2;
3002 } else {
3003 /*
3004 * No rtt measurement yet - use the unsmoothed rtt.
3005 * Set the variance to half the rtt (so our first
3006 * retransmit happens at 3*rtt).
3007 */
3008 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3009 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3010 }
3011 tp->t_rtttime = 0;
3012 tp->t_rxtshift = 0;
3013
3014 /*
3015 * the retransmit should happen at rtt + 4 * rttvar.
3016 * Because of the way we do the smoothing, srtt and rttvar
3017 * will each average +1/2 tick of bias. When we compute
3018 * the retransmit timer, we want 1/2 tick of rounding and
3019 * 1 extra tick because of +-1/2 tick uncertainty in the
3020 * firing of the timer. The bias will give us exactly the
3021 * 1.5 tick we need. But, because the bias is
3022 * statistical, we have to test that we don't drop below
3023 * the minimum feasible timer (which is 2 ticks).
3024 */
3025 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3026 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3027
3028 /*
3029 * We received an ack for a packet that wasn't retransmitted;
3030 * it is probably safe to discard any error indications we've
3031 * received recently. This isn't quite right, but close enough
3032 * for now (a route might have failed after we sent a segment,
3033 * and the return path might not be symmetrical).
3034 */
3035 tp->t_softerror = 0;
3036 }
3037
3038 /*
3039 * Checks for partial ack. If partial ack arrives, force the retransmission
3040 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
3041 * 1. By setting snd_nxt to th_ack, this forces retransmission timer to
3042 * be started again. If the ack advances at least to tp->snd_recover, return 0.
3043 */
3044 int
3045 tcp_newreno(tp, th)
3046 struct tcpcb *tp;
3047 struct tcphdr *th;
3048 {
3049 tcp_seq onxt = tp->snd_nxt;
3050 u_long ocwnd = tp->snd_cwnd;
3051
3052 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
3053 /*
3054 * snd_una has not yet been updated and the socket's send
3055 * buffer has not yet drained off the ACK'd data, so we
3056 * have to leave snd_una as it was to get the correct data
3057 * offset in tcp_output().
3058 */
3059 TCP_TIMER_DISARM(tp, TCPT_REXMT);
3060 tp->t_rtttime = 0;
3061 tp->snd_nxt = th->th_ack;
3062 /*
3063 * Set snd_cwnd to one segment beyond ACK'd offset. snd_una
3064 * is not yet updated when we're called.
3065 */
3066 tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
3067 (void) tcp_output(tp);
3068 tp->snd_cwnd = ocwnd;
3069 if (SEQ_GT(onxt, tp->snd_nxt))
3070 tp->snd_nxt = onxt;
3071 /*
3072 * Partial window deflation. Relies on fact that tp->snd_una
3073 * not updated yet.
3074 */
3075 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
3076 return 1;
3077 }
3078 return 0;
3079 }
3080
3081
3082 /*
3083 * TCP compressed state engine. Currently used to hold compressed
3084 * state for SYN_RECEIVED.
3085 */
3086
3087 u_long syn_cache_count;
3088 u_int32_t syn_hash1, syn_hash2;
3089
3090 #define SYN_HASH(sa, sp, dp) \
3091 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3092 ((u_int32_t)(sp)))^syn_hash2)))
3093 #ifndef INET6
3094 #define SYN_HASHALL(hash, src, dst) \
3095 do { \
3096 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
3097 ((struct sockaddr_in *)(src))->sin_port, \
3098 ((struct sockaddr_in *)(dst))->sin_port); \
3099 } while (/*CONSTCOND*/ 0)
3100 #else
3101 #define SYN_HASH6(sa, sp, dp) \
3102 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3103 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3104 & 0x7fffffff)
3105
3106 #define SYN_HASHALL(hash, src, dst) \
3107 do { \
3108 switch ((src)->sa_family) { \
3109 case AF_INET: \
3110 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
3111 ((struct sockaddr_in *)(src))->sin_port, \
3112 ((struct sockaddr_in *)(dst))->sin_port); \
3113 break; \
3114 case AF_INET6: \
3115 hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
3116 ((struct sockaddr_in6 *)(src))->sin6_port, \
3117 ((struct sockaddr_in6 *)(dst))->sin6_port); \
3118 break; \
3119 default: \
3120 hash = 0; \
3121 } \
3122 } while (/*CONSTCOND*/0)
3123 #endif /* INET6 */
3124
3125 #define SYN_CACHE_RM(sc) \
3126 do { \
3127 TAILQ_REMOVE(&tcp_syn_cache[(sc)->sc_bucketidx].sch_bucket, \
3128 (sc), sc_bucketq); \
3129 (sc)->sc_tp = NULL; \
3130 LIST_REMOVE((sc), sc_tpq); \
3131 tcp_syn_cache[(sc)->sc_bucketidx].sch_length--; \
3132 callout_stop(&(sc)->sc_timer); \
3133 syn_cache_count--; \
3134 } while (/*CONSTCOND*/0)
3135
3136 #define SYN_CACHE_PUT(sc) \
3137 do { \
3138 if ((sc)->sc_ipopts) \
3139 (void) m_free((sc)->sc_ipopts); \
3140 if ((sc)->sc_route4.ro_rt != NULL) \
3141 RTFREE((sc)->sc_route4.ro_rt); \
3142 if (callout_invoking(&(sc)->sc_timer)) \
3143 (sc)->sc_flags |= SCF_DEAD; \
3144 else \
3145 pool_put(&syn_cache_pool, (sc)); \
3146 } while (/*CONSTCOND*/0)
3147
3148 POOL_INIT(syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, "synpl", NULL);
3149
3150 /*
3151 * We don't estimate RTT with SYNs, so each packet starts with the default
3152 * RTT and each timer step has a fixed timeout value.
3153 */
3154 #define SYN_CACHE_TIMER_ARM(sc) \
3155 do { \
3156 TCPT_RANGESET((sc)->sc_rxtcur, \
3157 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
3158 TCPTV_REXMTMAX); \
3159 callout_reset(&(sc)->sc_timer, \
3160 (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc)); \
3161 } while (/*CONSTCOND*/0)
3162
3163 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3164
3165 void
3166 syn_cache_init()
3167 {
3168 int i;
3169
3170 /* Initialize the hash buckets. */
3171 for (i = 0; i < tcp_syn_cache_size; i++)
3172 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3173 }
3174
3175 void
3176 syn_cache_insert(sc, tp)
3177 struct syn_cache *sc;
3178 struct tcpcb *tp;
3179 {
3180 struct syn_cache_head *scp;
3181 struct syn_cache *sc2;
3182 int s;
3183
3184 /*
3185 * If there are no entries in the hash table, reinitialize
3186 * the hash secrets.
3187 */
3188 if (syn_cache_count == 0) {
3189 syn_hash1 = arc4random();
3190 syn_hash2 = arc4random();
3191 }
3192
3193 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3194 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3195 scp = &tcp_syn_cache[sc->sc_bucketidx];
3196
3197 /*
3198 * Make sure that we don't overflow the per-bucket
3199 * limit or the total cache size limit.
3200 */
3201 s = splsoftnet();
3202 if (scp->sch_length >= tcp_syn_bucket_limit) {
3203 tcpstat.tcps_sc_bucketoverflow++;
3204 /*
3205 * The bucket is full. Toss the oldest element in the
3206 * bucket. This will be the first entry in the bucket.
3207 */
3208 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3209 #ifdef DIAGNOSTIC
3210 /*
3211 * This should never happen; we should always find an
3212 * entry in our bucket.
3213 */
3214 if (sc2 == NULL)
3215 panic("syn_cache_insert: bucketoverflow: impossible");
3216 #endif
3217 SYN_CACHE_RM(sc2);
3218 SYN_CACHE_PUT(sc2);
3219 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3220 struct syn_cache_head *scp2, *sce;
3221
3222 tcpstat.tcps_sc_overflowed++;
3223 /*
3224 * The cache is full. Toss the oldest entry in the
3225 * first non-empty bucket we can find.
3226 *
3227 * XXX We would really like to toss the oldest
3228 * entry in the cache, but we hope that this
3229 * condition doesn't happen very often.
3230 */
3231 scp2 = scp;
3232 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3233 sce = &tcp_syn_cache[tcp_syn_cache_size];
3234 for (++scp2; scp2 != scp; scp2++) {
3235 if (scp2 >= sce)
3236 scp2 = &tcp_syn_cache[0];
3237 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3238 break;
3239 }
3240 #ifdef DIAGNOSTIC
3241 /*
3242 * This should never happen; we should always find a
3243 * non-empty bucket.
3244 */
3245 if (scp2 == scp)
3246 panic("syn_cache_insert: cacheoverflow: "
3247 "impossible");
3248 #endif
3249 }
3250 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3251 SYN_CACHE_RM(sc2);
3252 SYN_CACHE_PUT(sc2);
3253 }
3254
3255 /*
3256 * Initialize the entry's timer.
3257 */
3258 sc->sc_rxttot = 0;
3259 sc->sc_rxtshift = 0;
3260 SYN_CACHE_TIMER_ARM(sc);
3261
3262 /* Link it from tcpcb entry */
3263 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3264
3265 /* Put it into the bucket. */
3266 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3267 scp->sch_length++;
3268 syn_cache_count++;
3269
3270 tcpstat.tcps_sc_added++;
3271 splx(s);
3272 }
3273
3274 /*
3275 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3276 * If we have retransmitted an entry the maximum number of times, expire
3277 * that entry.
3278 */
3279 void
3280 syn_cache_timer(void *arg)
3281 {
3282 struct syn_cache *sc = arg;
3283 int s;
3284
3285 s = splsoftnet();
3286 callout_ack(&sc->sc_timer);
3287
3288 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3289 tcpstat.tcps_sc_delayed_free++;
3290 pool_put(&syn_cache_pool, sc);
3291 splx(s);
3292 return;
3293 }
3294
3295 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3296 /* Drop it -- too many retransmissions. */
3297 goto dropit;
3298 }
3299
3300 /*
3301 * Compute the total amount of time this entry has
3302 * been on a queue. If this entry has been on longer
3303 * than the keep alive timer would allow, expire it.
3304 */
3305 sc->sc_rxttot += sc->sc_rxtcur;
3306 if (sc->sc_rxttot >= TCPTV_KEEP_INIT)
3307 goto dropit;
3308
3309 tcpstat.tcps_sc_retransmitted++;
3310 (void) syn_cache_respond(sc, NULL);
3311
3312 /* Advance the timer back-off. */
3313 sc->sc_rxtshift++;
3314 SYN_CACHE_TIMER_ARM(sc);
3315
3316 splx(s);
3317 return;
3318
3319 dropit:
3320 tcpstat.tcps_sc_timed_out++;
3321 SYN_CACHE_RM(sc);
3322 SYN_CACHE_PUT(sc);
3323 splx(s);
3324 }
3325
3326 /*
3327 * Remove syn cache created by the specified tcb entry,
3328 * because this does not make sense to keep them
3329 * (if there's no tcb entry, syn cache entry will never be used)
3330 */
3331 void
3332 syn_cache_cleanup(tp)
3333 struct tcpcb *tp;
3334 {
3335 struct syn_cache *sc, *nsc;
3336 int s;
3337
3338 s = splsoftnet();
3339
3340 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3341 nsc = LIST_NEXT(sc, sc_tpq);
3342
3343 #ifdef DIAGNOSTIC
3344 if (sc->sc_tp != tp)
3345 panic("invalid sc_tp in syn_cache_cleanup");
3346 #endif
3347 SYN_CACHE_RM(sc);
3348 SYN_CACHE_PUT(sc);
3349 }
3350 /* just for safety */
3351 LIST_INIT(&tp->t_sc);
3352
3353 splx(s);
3354 }
3355
3356 /*
3357 * Find an entry in the syn cache.
3358 */
3359 struct syn_cache *
3360 syn_cache_lookup(src, dst, headp)
3361 struct sockaddr *src;
3362 struct sockaddr *dst;
3363 struct syn_cache_head **headp;
3364 {
3365 struct syn_cache *sc;
3366 struct syn_cache_head *scp;
3367 u_int32_t hash;
3368 int s;
3369
3370 SYN_HASHALL(hash, src, dst);
3371
3372 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3373 *headp = scp;
3374 s = splsoftnet();
3375 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3376 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3377 if (sc->sc_hash != hash)
3378 continue;
3379 if (!bcmp(&sc->sc_src, src, src->sa_len) &&
3380 !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
3381 splx(s);
3382 return (sc);
3383 }
3384 }
3385 splx(s);
3386 return (NULL);
3387 }
3388
3389 /*
3390 * This function gets called when we receive an ACK for a
3391 * socket in the LISTEN state. We look up the connection
3392 * in the syn cache, and if its there, we pull it out of
3393 * the cache and turn it into a full-blown connection in
3394 * the SYN-RECEIVED state.
3395 *
3396 * The return values may not be immediately obvious, and their effects
3397 * can be subtle, so here they are:
3398 *
3399 * NULL SYN was not found in cache; caller should drop the
3400 * packet and send an RST.
3401 *
3402 * -1 We were unable to create the new connection, and are
3403 * aborting it. An ACK,RST is being sent to the peer
3404 * (unless we got screwey sequence numbners; see below),
3405 * because the 3-way handshake has been completed. Caller
3406 * should not free the mbuf, since we may be using it. If
3407 * we are not, we will free it.
3408 *
3409 * Otherwise, the return value is a pointer to the new socket
3410 * associated with the connection.
3411 */
3412 struct socket *
3413 syn_cache_get(src, dst, th, hlen, tlen, so, m)
3414 struct sockaddr *src;
3415 struct sockaddr *dst;
3416 struct tcphdr *th;
3417 unsigned int hlen, tlen;
3418 struct socket *so;
3419 struct mbuf *m;
3420 {
3421 struct syn_cache *sc;
3422 struct syn_cache_head *scp;
3423 struct inpcb *inp = NULL;
3424 #ifdef INET6
3425 struct in6pcb *in6p = NULL;
3426 #endif
3427 struct tcpcb *tp = 0;
3428 struct mbuf *am;
3429 int s;
3430 struct socket *oso;
3431
3432 s = splsoftnet();
3433 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3434 splx(s);
3435 return (NULL);
3436 }
3437
3438 /*
3439 * Verify the sequence and ack numbers. Try getting the correct
3440 * response again.
3441 */
3442 if ((th->th_ack != sc->sc_iss + 1) ||
3443 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3444 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3445 (void) syn_cache_respond(sc, m);
3446 splx(s);
3447 return ((struct socket *)(-1));
3448 }
3449
3450 /* Remove this cache entry */
3451 SYN_CACHE_RM(sc);
3452 splx(s);
3453
3454 /*
3455 * Ok, create the full blown connection, and set things up
3456 * as they would have been set up if we had created the
3457 * connection when the SYN arrived. If we can't create
3458 * the connection, abort it.
3459 */
3460 /*
3461 * inp still has the OLD in_pcb stuff, set the
3462 * v6-related flags on the new guy, too. This is
3463 * done particularly for the case where an AF_INET6
3464 * socket is bound only to a port, and a v4 connection
3465 * comes in on that port.
3466 * we also copy the flowinfo from the original pcb
3467 * to the new one.
3468 */
3469 oso = so;
3470 so = sonewconn(so, SS_ISCONNECTED);
3471 if (so == NULL)
3472 goto resetandabort;
3473
3474 switch (so->so_proto->pr_domain->dom_family) {
3475 #ifdef INET
3476 case AF_INET:
3477 inp = sotoinpcb(so);
3478 break;
3479 #endif
3480 #ifdef INET6
3481 case AF_INET6:
3482 in6p = sotoin6pcb(so);
3483 break;
3484 #endif
3485 }
3486 switch (src->sa_family) {
3487 #ifdef INET
3488 case AF_INET:
3489 if (inp) {
3490 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3491 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3492 inp->inp_options = ip_srcroute();
3493 in_pcbstate(inp, INP_BOUND);
3494 if (inp->inp_options == NULL) {
3495 inp->inp_options = sc->sc_ipopts;
3496 sc->sc_ipopts = NULL;
3497 }
3498 }
3499 #ifdef INET6
3500 else if (in6p) {
3501 /* IPv4 packet to AF_INET6 socket */
3502 bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
3503 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3504 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3505 &in6p->in6p_laddr.s6_addr32[3],
3506 sizeof(((struct sockaddr_in *)dst)->sin_addr));
3507 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3508 in6totcpcb(in6p)->t_family = AF_INET;
3509 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3510 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3511 else
3512 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3513 in6_pcbstate(in6p, IN6P_BOUND);
3514 }
3515 #endif
3516 break;
3517 #endif
3518 #ifdef INET6
3519 case AF_INET6:
3520 if (in6p) {
3521 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3522 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3523 in6_pcbstate(in6p, IN6P_BOUND);
3524 }
3525 break;
3526 #endif
3527 }
3528 #ifdef INET6
3529 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3530 struct in6pcb *oin6p = sotoin6pcb(oso);
3531 /* inherit socket options from the listening socket */
3532 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3533 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3534 m_freem(in6p->in6p_options);
3535 in6p->in6p_options = 0;
3536 }
3537 ip6_savecontrol(in6p, &in6p->in6p_options,
3538 mtod(m, struct ip6_hdr *), m);
3539 }
3540 #endif
3541
3542 #if defined(IPSEC) || defined(FAST_IPSEC)
3543 /*
3544 * we make a copy of policy, instead of sharing the policy,
3545 * for better behavior in terms of SA lookup and dead SA removal.
3546 */
3547 if (inp) {
3548 /* copy old policy into new socket's */
3549 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
3550 printf("tcp_input: could not copy policy\n");
3551 }
3552 #ifdef INET6
3553 else if (in6p) {
3554 /* copy old policy into new socket's */
3555 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
3556 in6p->in6p_sp))
3557 printf("tcp_input: could not copy policy\n");
3558 }
3559 #endif
3560 #endif
3561
3562 /*
3563 * Give the new socket our cached route reference.
3564 */
3565 if (inp)
3566 inp->inp_route = sc->sc_route4; /* struct assignment */
3567 #ifdef INET6
3568 else
3569 in6p->in6p_route = sc->sc_route6;
3570 #endif
3571 sc->sc_route4.ro_rt = NULL;
3572
3573 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
3574 if (am == NULL)
3575 goto resetandabort;
3576 MCLAIM(am, &tcp_mowner);
3577 am->m_len = src->sa_len;
3578 bcopy(src, mtod(am, caddr_t), src->sa_len);
3579 if (inp) {
3580 if (in_pcbconnect(inp, am)) {
3581 (void) m_free(am);
3582 goto resetandabort;
3583 }
3584 }
3585 #ifdef INET6
3586 else if (in6p) {
3587 if (src->sa_family == AF_INET) {
3588 /* IPv4 packet to AF_INET6 socket */
3589 struct sockaddr_in6 *sin6;
3590 sin6 = mtod(am, struct sockaddr_in6 *);
3591 am->m_len = sizeof(*sin6);
3592 bzero(sin6, sizeof(*sin6));
3593 sin6->sin6_family = AF_INET6;
3594 sin6->sin6_len = sizeof(*sin6);
3595 sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
3596 sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
3597 bcopy(&((struct sockaddr_in *)src)->sin_addr,
3598 &sin6->sin6_addr.s6_addr32[3],
3599 sizeof(sin6->sin6_addr.s6_addr32[3]));
3600 }
3601 if (in6_pcbconnect(in6p, am)) {
3602 (void) m_free(am);
3603 goto resetandabort;
3604 }
3605 }
3606 #endif
3607 else {
3608 (void) m_free(am);
3609 goto resetandabort;
3610 }
3611 (void) m_free(am);
3612
3613 if (inp)
3614 tp = intotcpcb(inp);
3615 #ifdef INET6
3616 else if (in6p)
3617 tp = in6totcpcb(in6p);
3618 #endif
3619 else
3620 tp = NULL;
3621 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
3622 if (sc->sc_request_r_scale != 15) {
3623 tp->requested_s_scale = sc->sc_requested_s_scale;
3624 tp->request_r_scale = sc->sc_request_r_scale;
3625 tp->snd_scale = sc->sc_requested_s_scale;
3626 tp->rcv_scale = sc->sc_request_r_scale;
3627 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
3628 }
3629 if (sc->sc_flags & SCF_TIMESTAMP)
3630 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
3631 tp->ts_timebase = sc->sc_timebase;
3632
3633 tp->t_template = tcp_template(tp);
3634 if (tp->t_template == 0) {
3635 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
3636 so = NULL;
3637 m_freem(m);
3638 goto abort;
3639 }
3640
3641 tp->iss = sc->sc_iss;
3642 tp->irs = sc->sc_irs;
3643 tcp_sendseqinit(tp);
3644 tcp_rcvseqinit(tp);
3645 tp->t_state = TCPS_SYN_RECEIVED;
3646 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
3647 tcpstat.tcps_accepts++;
3648
3649 #ifdef TCP_SIGNATURE
3650 if (sc->sc_flags & SCF_SIGNATURE)
3651 tp->t_flags |= TF_SIGNATURE;
3652 #endif
3653
3654 /* Initialize tp->t_ourmss before we deal with the peer's! */
3655 tp->t_ourmss = sc->sc_ourmaxseg;
3656 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
3657
3658 /*
3659 * Initialize the initial congestion window. If we
3660 * had to retransmit the SYN,ACK, we must initialize cwnd
3661 * to 1 segment (i.e. the Loss Window).
3662 */
3663 if (sc->sc_rxtshift)
3664 tp->snd_cwnd = tp->t_peermss;
3665 else {
3666 int ss = tcp_init_win;
3667 #ifdef INET
3668 if (inp != NULL && in_localaddr(inp->inp_faddr))
3669 ss = tcp_init_win_local;
3670 #endif
3671 #ifdef INET6
3672 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
3673 ss = tcp_init_win_local;
3674 #endif
3675 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
3676 }
3677
3678 tcp_rmx_rtt(tp);
3679 tp->snd_wl1 = sc->sc_irs;
3680 tp->rcv_up = sc->sc_irs + 1;
3681
3682 /*
3683 * This is what whould have happened in tcp_output() when
3684 * the SYN,ACK was sent.
3685 */
3686 tp->snd_up = tp->snd_una;
3687 tp->snd_max = tp->snd_nxt = tp->iss+1;
3688 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
3689 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
3690 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
3691 tp->last_ack_sent = tp->rcv_nxt;
3692
3693 tcpstat.tcps_sc_completed++;
3694 SYN_CACHE_PUT(sc);
3695 return (so);
3696
3697 resetandabort:
3698 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3699 abort:
3700 if (so != NULL)
3701 (void) soabort(so);
3702 SYN_CACHE_PUT(sc);
3703 tcpstat.tcps_sc_aborted++;
3704 return ((struct socket *)(-1));
3705 }
3706
3707 /*
3708 * This function is called when we get a RST for a
3709 * non-existent connection, so that we can see if the
3710 * connection is in the syn cache. If it is, zap it.
3711 */
3712
3713 void
3714 syn_cache_reset(src, dst, th)
3715 struct sockaddr *src;
3716 struct sockaddr *dst;
3717 struct tcphdr *th;
3718 {
3719 struct syn_cache *sc;
3720 struct syn_cache_head *scp;
3721 int s = splsoftnet();
3722
3723 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3724 splx(s);
3725 return;
3726 }
3727 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
3728 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
3729 splx(s);
3730 return;
3731 }
3732 SYN_CACHE_RM(sc);
3733 splx(s);
3734 tcpstat.tcps_sc_reset++;
3735 SYN_CACHE_PUT(sc);
3736 }
3737
3738 void
3739 syn_cache_unreach(src, dst, th)
3740 struct sockaddr *src;
3741 struct sockaddr *dst;
3742 struct tcphdr *th;
3743 {
3744 struct syn_cache *sc;
3745 struct syn_cache_head *scp;
3746 int s;
3747
3748 s = splsoftnet();
3749 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3750 splx(s);
3751 return;
3752 }
3753 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
3754 if (ntohl (th->th_seq) != sc->sc_iss) {
3755 splx(s);
3756 return;
3757 }
3758
3759 /*
3760 * If we've retransmitted 3 times and this is our second error,
3761 * we remove the entry. Otherwise, we allow it to continue on.
3762 * This prevents us from incorrectly nuking an entry during a
3763 * spurious network outage.
3764 *
3765 * See tcp_notify().
3766 */
3767 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3768 sc->sc_flags |= SCF_UNREACH;
3769 splx(s);
3770 return;
3771 }
3772
3773 SYN_CACHE_RM(sc);
3774 splx(s);
3775 tcpstat.tcps_sc_unreach++;
3776 SYN_CACHE_PUT(sc);
3777 }
3778
3779 /*
3780 * Given a LISTEN socket and an inbound SYN request, add
3781 * this to the syn cache, and send back a segment:
3782 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3783 * to the source.
3784 *
3785 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3786 * Doing so would require that we hold onto the data and deliver it
3787 * to the application. However, if we are the target of a SYN-flood
3788 * DoS attack, an attacker could send data which would eventually
3789 * consume all available buffer space if it were ACKed. By not ACKing
3790 * the data, we avoid this DoS scenario.
3791 */
3792
3793 int
3794 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
3795 struct sockaddr *src;
3796 struct sockaddr *dst;
3797 struct tcphdr *th;
3798 unsigned int hlen;
3799 struct socket *so;
3800 struct mbuf *m;
3801 u_char *optp;
3802 int optlen;
3803 struct tcp_opt_info *oi;
3804 {
3805 struct tcpcb tb, *tp;
3806 long win;
3807 struct syn_cache *sc;
3808 struct syn_cache_head *scp;
3809 struct mbuf *ipopts;
3810 struct tcp_opt_info opti;
3811
3812 tp = sototcpcb(so);
3813
3814 bzero(&opti, sizeof(opti));
3815
3816 /*
3817 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3818 *
3819 * Note this check is performed in tcp_input() very early on.
3820 */
3821
3822 /*
3823 * Initialize some local state.
3824 */
3825 win = sbspace(&so->so_rcv);
3826 if (win > TCP_MAXWIN)
3827 win = TCP_MAXWIN;
3828
3829 switch (src->sa_family) {
3830 #ifdef INET
3831 case AF_INET:
3832 /*
3833 * Remember the IP options, if any.
3834 */
3835 ipopts = ip_srcroute();
3836 break;
3837 #endif
3838 default:
3839 ipopts = NULL;
3840 }
3841
3842 #ifdef TCP_SIGNATURE
3843 if (optp || (tp->t_flags & TF_SIGNATURE))
3844 #else
3845 if (optp)
3846 #endif
3847 {
3848 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3849 #ifdef TCP_SIGNATURE
3850 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
3851 #endif
3852 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
3853 sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
3854 return (0);
3855 } else
3856 tb.t_flags = 0;
3857
3858 /*
3859 * See if we already have an entry for this connection.
3860 * If we do, resend the SYN,ACK. We do not count this
3861 * as a retransmission (XXX though maybe we should).
3862 */
3863 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3864 tcpstat.tcps_sc_dupesyn++;
3865 if (ipopts) {
3866 /*
3867 * If we were remembering a previous source route,
3868 * forget it and use the new one we've been given.
3869 */
3870 if (sc->sc_ipopts)
3871 (void) m_free(sc->sc_ipopts);
3872 sc->sc_ipopts = ipopts;
3873 }
3874 sc->sc_timestamp = tb.ts_recent;
3875 if (syn_cache_respond(sc, m) == 0) {
3876 tcpstat.tcps_sndacks++;
3877 tcpstat.tcps_sndtotal++;
3878 }
3879 return (1);
3880 }
3881
3882 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3883 if (sc == NULL) {
3884 if (ipopts)
3885 (void) m_free(ipopts);
3886 return (0);
3887 }
3888
3889 /*
3890 * Fill in the cache, and put the necessary IP and TCP
3891 * options into the reply.
3892 */
3893 bzero(sc, sizeof(struct syn_cache));
3894 callout_init(&sc->sc_timer);
3895 bcopy(src, &sc->sc_src, src->sa_len);
3896 bcopy(dst, &sc->sc_dst, dst->sa_len);
3897 sc->sc_flags = 0;
3898 sc->sc_ipopts = ipopts;
3899 sc->sc_irs = th->th_seq;
3900 switch (src->sa_family) {
3901 #ifdef INET
3902 case AF_INET:
3903 {
3904 struct sockaddr_in *srcin = (void *) src;
3905 struct sockaddr_in *dstin = (void *) dst;
3906
3907 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
3908 &srcin->sin_addr, dstin->sin_port,
3909 srcin->sin_port, sizeof(dstin->sin_addr), 0);
3910 break;
3911 }
3912 #endif /* INET */
3913 #ifdef INET6
3914 case AF_INET6:
3915 {
3916 struct sockaddr_in6 *srcin6 = (void *) src;
3917 struct sockaddr_in6 *dstin6 = (void *) dst;
3918
3919 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
3920 &srcin6->sin6_addr, dstin6->sin6_port,
3921 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
3922 break;
3923 }
3924 #endif /* INET6 */
3925 }
3926 sc->sc_peermaxseg = oi->maxseg;
3927 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
3928 m->m_pkthdr.rcvif : NULL,
3929 sc->sc_src.sa.sa_family);
3930 sc->sc_win = win;
3931 sc->sc_timebase = tcp_now; /* see tcp_newtcpcb() */
3932 sc->sc_timestamp = tb.ts_recent;
3933 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
3934 (TF_REQ_TSTMP|TF_RCVD_TSTMP))
3935 sc->sc_flags |= SCF_TIMESTAMP;
3936 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
3937 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
3938 sc->sc_requested_s_scale = tb.requested_s_scale;
3939 sc->sc_request_r_scale = 0;
3940 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
3941 TCP_MAXWIN << sc->sc_request_r_scale <
3942 so->so_rcv.sb_hiwat)
3943 sc->sc_request_r_scale++;
3944 } else {
3945 sc->sc_requested_s_scale = 15;
3946 sc->sc_request_r_scale = 15;
3947 }
3948 #ifdef TCP_SIGNATURE
3949 if (tb.t_flags & TF_SIGNATURE)
3950 sc->sc_flags |= SCF_SIGNATURE;
3951 #endif
3952 sc->sc_tp = tp;
3953 if (syn_cache_respond(sc, m) == 0) {
3954 syn_cache_insert(sc, tp);
3955 tcpstat.tcps_sndacks++;
3956 tcpstat.tcps_sndtotal++;
3957 } else {
3958 SYN_CACHE_PUT(sc);
3959 tcpstat.tcps_sc_dropped++;
3960 }
3961 return (1);
3962 }
3963
3964 int
3965 syn_cache_respond(sc, m)
3966 struct syn_cache *sc;
3967 struct mbuf *m;
3968 {
3969 struct route *ro;
3970 u_int8_t *optp;
3971 int optlen, error;
3972 u_int16_t tlen;
3973 struct ip *ip = NULL;
3974 #ifdef INET6
3975 struct ip6_hdr *ip6 = NULL;
3976 #endif
3977 struct tcpcb *tp;
3978 struct tcphdr *th;
3979 u_int hlen;
3980 struct socket *so;
3981
3982 switch (sc->sc_src.sa.sa_family) {
3983 case AF_INET:
3984 hlen = sizeof(struct ip);
3985 ro = &sc->sc_route4;
3986 break;
3987 #ifdef INET6
3988 case AF_INET6:
3989 hlen = sizeof(struct ip6_hdr);
3990 ro = (struct route *)&sc->sc_route6;
3991 break;
3992 #endif
3993 default:
3994 if (m)
3995 m_freem(m);
3996 return (EAFNOSUPPORT);
3997 }
3998
3999 /* Compute the size of the TCP options. */
4000 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
4001 #ifdef TCP_SIGNATURE
4002 ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
4003 #endif
4004 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
4005
4006 tlen = hlen + sizeof(struct tcphdr) + optlen;
4007
4008 /*
4009 * Create the IP+TCP header from scratch.
4010 */
4011 if (m)
4012 m_freem(m);
4013 #ifdef DIAGNOSTIC
4014 if (max_linkhdr + tlen > MCLBYTES)
4015 return (ENOBUFS);
4016 #endif
4017 MGETHDR(m, M_DONTWAIT, MT_DATA);
4018 if (m && tlen > MHLEN) {
4019 MCLGET(m, M_DONTWAIT);
4020 if ((m->m_flags & M_EXT) == 0) {
4021 m_freem(m);
4022 m = NULL;
4023 }
4024 }
4025 if (m == NULL)
4026 return (ENOBUFS);
4027 MCLAIM(m, &tcp_tx_mowner);
4028
4029 /* Fixup the mbuf. */
4030 m->m_data += max_linkhdr;
4031 m->m_len = m->m_pkthdr.len = tlen;
4032 if (sc->sc_tp) {
4033 tp = sc->sc_tp;
4034 if (tp->t_inpcb)
4035 so = tp->t_inpcb->inp_socket;
4036 #ifdef INET6
4037 else if (tp->t_in6pcb)
4038 so = tp->t_in6pcb->in6p_socket;
4039 #endif
4040 else
4041 so = NULL;
4042 } else
4043 so = NULL;
4044 m->m_pkthdr.rcvif = NULL;
4045 memset(mtod(m, u_char *), 0, tlen);
4046
4047 switch (sc->sc_src.sa.sa_family) {
4048 case AF_INET:
4049 ip = mtod(m, struct ip *);
4050 ip->ip_v = 4;
4051 ip->ip_dst = sc->sc_src.sin.sin_addr;
4052 ip->ip_src = sc->sc_dst.sin.sin_addr;
4053 ip->ip_p = IPPROTO_TCP;
4054 th = (struct tcphdr *)(ip + 1);
4055 th->th_dport = sc->sc_src.sin.sin_port;
4056 th->th_sport = sc->sc_dst.sin.sin_port;
4057 break;
4058 #ifdef INET6
4059 case AF_INET6:
4060 ip6 = mtod(m, struct ip6_hdr *);
4061 ip6->ip6_vfc = IPV6_VERSION;
4062 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4063 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4064 ip6->ip6_nxt = IPPROTO_TCP;
4065 /* ip6_plen will be updated in ip6_output() */
4066 th = (struct tcphdr *)(ip6 + 1);
4067 th->th_dport = sc->sc_src.sin6.sin6_port;
4068 th->th_sport = sc->sc_dst.sin6.sin6_port;
4069 break;
4070 #endif
4071 default:
4072 th = NULL;
4073 }
4074
4075 th->th_seq = htonl(sc->sc_iss);
4076 th->th_ack = htonl(sc->sc_irs + 1);
4077 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4078 th->th_flags = TH_SYN|TH_ACK;
4079 th->th_win = htons(sc->sc_win);
4080 /* th_sum already 0 */
4081 /* th_urp already 0 */
4082
4083 /* Tack on the TCP options. */
4084 optp = (u_int8_t *)(th + 1);
4085 *optp++ = TCPOPT_MAXSEG;
4086 *optp++ = 4;
4087 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4088 *optp++ = sc->sc_ourmaxseg & 0xff;
4089
4090 if (sc->sc_request_r_scale != 15) {
4091 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4092 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4093 sc->sc_request_r_scale);
4094 optp += 4;
4095 }
4096
4097 if (sc->sc_flags & SCF_TIMESTAMP) {
4098 u_int32_t *lp = (u_int32_t *)(optp);
4099 /* Form timestamp option as shown in appendix A of RFC 1323. */
4100 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
4101 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4102 *lp = htonl(sc->sc_timestamp);
4103 optp += TCPOLEN_TSTAMP_APPA;
4104 }
4105
4106 #ifdef TCP_SIGNATURE
4107 if (sc->sc_flags & SCF_SIGNATURE) {
4108 struct secasvar *sav;
4109 u_int8_t *sigp;
4110
4111 sav = tcp_signature_getsav(m, th);
4112
4113 if (sav == NULL) {
4114 if (m)
4115 m_freem(m);
4116 return (EPERM);
4117 }
4118
4119 *optp++ = TCPOPT_SIGNATURE;
4120 *optp++ = TCPOLEN_SIGNATURE;
4121 sigp = optp;
4122 bzero(optp, TCP_SIGLEN);
4123 optp += TCP_SIGLEN;
4124 *optp++ = TCPOPT_NOP;
4125 *optp++ = TCPOPT_EOL;
4126
4127 (void)tcp_signature(m, th, hlen, sav, sigp);
4128
4129 key_sa_recordxfer(sav, m);
4130 #ifdef FAST_IPSEC
4131 KEY_FREESAV(&sav);
4132 #else
4133 key_freesav(sav);
4134 #endif
4135 }
4136 #endif
4137
4138 /* Compute the packet's checksum. */
4139 switch (sc->sc_src.sa.sa_family) {
4140 case AF_INET:
4141 ip->ip_len = htons(tlen - hlen);
4142 th->th_sum = 0;
4143 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4144 break;
4145 #ifdef INET6
4146 case AF_INET6:
4147 ip6->ip6_plen = htons(tlen - hlen);
4148 th->th_sum = 0;
4149 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4150 break;
4151 #endif
4152 }
4153
4154 /*
4155 * Fill in some straggling IP bits. Note the stack expects
4156 * ip_len to be in host order, for convenience.
4157 */
4158 switch (sc->sc_src.sa.sa_family) {
4159 #ifdef INET
4160 case AF_INET:
4161 ip->ip_len = htons(tlen);
4162 ip->ip_ttl = ip_defttl;
4163 /* XXX tos? */
4164 break;
4165 #endif
4166 #ifdef INET6
4167 case AF_INET6:
4168 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4169 ip6->ip6_vfc |= IPV6_VERSION;
4170 ip6->ip6_plen = htons(tlen - hlen);
4171 /* ip6_hlim will be initialized afterwards */
4172 /* XXX flowlabel? */
4173 break;
4174 #endif
4175 }
4176
4177 /* XXX use IPsec policy on listening socket, on SYN ACK */
4178 tp = sc->sc_tp;
4179
4180 switch (sc->sc_src.sa.sa_family) {
4181 #ifdef INET
4182 case AF_INET:
4183 error = ip_output(m, sc->sc_ipopts, ro,
4184 (ip_mtudisc ? IP_MTUDISC : 0),
4185 (struct ip_moptions *)NULL, so);
4186 break;
4187 #endif
4188 #ifdef INET6
4189 case AF_INET6:
4190 ip6->ip6_hlim = in6_selecthlim(NULL,
4191 ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
4192
4193 error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro, 0,
4194 (struct ip6_moptions *)0, so, NULL);
4195 break;
4196 #endif
4197 default:
4198 error = EAFNOSUPPORT;
4199 break;
4200 }
4201 return (error);
4202 }
4203