syncache: Allocate syncache context on the owner cpu.
[dragonfly.git] / sys / netinet / tcp_syncache.c
blobc81d6fa32f37012e32fe8827cfe3320566726432
1 /*
2 * Copyright (c) 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
35 * All advertising materials mentioning features or use of this software
36 * must display the following acknowledgement:
37 * This product includes software developed by Jeffrey M. Hsu.
39 * Copyright (c) 2001 Networks Associates Technologies, Inc.
40 * All rights reserved.
42 * This software was developed for the FreeBSD Project by Jonathan Lemon
43 * and NAI Labs, the Security Research Division of Network Associates, Inc.
44 * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
45 * DARPA CHATS research program.
47 * Redistribution and use in source and binary forms, with or without
48 * modification, are permitted provided that the following conditions
49 * are met:
50 * 1. Redistributions of source code must retain the above copyright
51 * notice, this list of conditions and the following disclaimer.
52 * 2. Redistributions in binary form must reproduce the above copyright
53 * notice, this list of conditions and the following disclaimer in the
54 * documentation and/or other materials provided with the distribution.
55 * 3. The name of the author may not be used to endorse or promote
56 * products derived from this software without specific prior written
57 * permission.
59 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
60 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
61 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
62 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
63 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
64 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
65 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
66 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
67 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
68 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
69 * SUCH DAMAGE.
71 * $FreeBSD: src/sys/netinet/tcp_syncache.c,v 1.5.2.14 2003/02/24 04:02:27 silby Exp $
74 #include "opt_inet.h"
75 #include "opt_inet6.h"
76 #include "opt_ipsec.h"
78 #include <sys/param.h>
79 #include <sys/systm.h>
80 #include <sys/kernel.h>
81 #include <sys/sysctl.h>
82 #include <sys/malloc.h>
83 #include <sys/mbuf.h>
84 #include <sys/md5.h>
85 #include <sys/proc.h> /* for proc0 declaration */
86 #include <sys/random.h>
87 #include <sys/socket.h>
88 #include <sys/socketvar.h>
89 #include <sys/in_cksum.h>
91 #include <sys/msgport2.h>
92 #include <net/netmsg2.h>
93 #include <net/netisr2.h>
95 #include <net/if.h>
96 #include <net/route.h>
98 #include <netinet/in.h>
99 #include <netinet/in_systm.h>
100 #include <netinet/ip.h>
101 #include <netinet/in_var.h>
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_var.h>
104 #include <netinet/ip6.h>
105 #ifdef INET6
106 #include <netinet/icmp6.h>
107 #include <netinet6/nd6.h>
108 #endif
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/in6_pcb.h>
111 #include <netinet/tcp.h>
112 #include <netinet/tcp_fsm.h>
113 #include <netinet/tcp_seq.h>
114 #include <netinet/tcp_timer.h>
115 #include <netinet/tcp_timer2.h>
116 #include <netinet/tcp_var.h>
117 #include <netinet6/tcp6_var.h>
119 #ifdef IPSEC
120 #include <netinet6/ipsec.h>
121 #ifdef INET6
122 #include <netinet6/ipsec6.h>
123 #endif
124 #include <netproto/key/key.h>
125 #endif /*IPSEC*/
127 #ifdef FAST_IPSEC
128 #include <netproto/ipsec/ipsec.h>
129 #ifdef INET6
130 #include <netproto/ipsec/ipsec6.h>
131 #endif
132 #include <netproto/ipsec/key.h>
133 #define IPSEC
134 #endif /*FAST_IPSEC*/
136 static int tcp_syncookies = 1;
137 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
138 &tcp_syncookies, 0,
139 "Use TCP SYN cookies if the syncache overflows");
141 static void syncache_drop(struct syncache *, struct syncache_head *);
142 static void syncache_free(struct syncache *);
143 static void syncache_insert(struct syncache *, struct syncache_head *);
144 static struct syncache *syncache_lookup(struct in_conninfo *,
145 struct syncache_head **);
146 static int syncache_respond(struct syncache *, struct mbuf *);
147 static struct socket *syncache_socket(struct syncache *, struct socket *,
148 struct mbuf *);
149 static void syncache_timer(void *);
150 static u_int32_t syncookie_generate(struct syncache *);
151 static struct syncache *syncookie_lookup(struct in_conninfo *,
152 struct tcphdr *, struct socket *);
155 * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
156 * 4 retransmits corresponds to a timeout of (3 + 3 + 3 + 3 + 3 == 15) seconds
157 * or (1 + 1 + 2 + 4 + 8 == 16) seconds if RFC6298 is used, the odds are that
158 * the user has given up attempting to connect by then.
160 #define SYNCACHE_MAXREXMTS 4
162 /* Arbitrary values */
163 #define TCP_SYNCACHE_HASHSIZE 512
164 #define TCP_SYNCACHE_BUCKETLIMIT 30
166 static void syncache_timer_handler(netmsg_t);
168 struct tcp_syncache {
169 u_int hashsize;
170 u_int hashmask;
171 u_int bucket_limit;
172 u_int cache_limit;
173 u_int rexmt_limit;
174 u_int hash_secret;
176 static struct tcp_syncache tcp_syncache;
178 TAILQ_HEAD(syncache_list, syncache);
180 struct syncache_timerq {
181 struct syncache_list list;
182 struct callout timeo;
183 struct netmsg_base nm;
186 struct tcp_syncache_percpu {
187 struct syncache_head *hashbase;
188 u_int cache_count;
189 struct syncache_timerq timerq[SYNCACHE_MAXREXMTS + 1];
192 static struct tcp_syncache_percpu *tcp_syncache_percpu[MAXCPU];
194 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
196 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RD,
197 &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
199 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RD,
200 &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
202 /* XXX JH */
203 #if 0
204 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
205 &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
206 #endif
208 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RD,
209 &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
211 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
212 &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
214 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
216 #define SYNCACHE_HASH(inc, mask) \
217 ((tcp_syncache.hash_secret ^ \
218 (inc)->inc_faddr.s_addr ^ \
219 ((inc)->inc_faddr.s_addr >> 16) ^ \
220 (inc)->inc_fport ^ (inc)->inc_lport) & mask)
222 #define SYNCACHE_HASH6(inc, mask) \
223 ((tcp_syncache.hash_secret ^ \
224 (inc)->inc6_faddr.s6_addr32[0] ^ \
225 (inc)->inc6_faddr.s6_addr32[3] ^ \
226 (inc)->inc_fport ^ (inc)->inc_lport) & mask)
228 #define ENDPTS_EQ(a, b) ( \
229 (a)->ie_fport == (b)->ie_fport && \
230 (a)->ie_lport == (b)->ie_lport && \
231 (a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr && \
232 (a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr \
235 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
237 static __inline int
238 syncache_rto(int slot)
240 if (tcp_low_rtobase)
241 return (TCPTV_RTOBASE * tcp_syn_backoff_low[slot]);
242 else
243 return (TCPTV_RTOBASE * tcp_syn_backoff[slot]);
246 static __inline void
247 syncache_timeout(struct tcp_syncache_percpu *syncache_percpu,
248 struct syncache *sc, int slot)
250 struct syncache_timerq *tq;
251 int rto;
253 KASSERT(slot <= SYNCACHE_MAXREXMTS,
254 ("syncache: invalid slot %d", slot));
256 if (slot > 0) {
258 * Record the time that we spent in SYN|ACK
259 * retransmition.
261 * Needed by RFC3390 and RFC6298.
263 sc->sc_rxtused += syncache_rto(slot - 1);
265 sc->sc_rxtslot = slot;
267 rto = syncache_rto(slot);
268 sc->sc_rxttime = ticks + rto;
270 tq = &syncache_percpu->timerq[slot];
271 TAILQ_INSERT_TAIL(&tq->list, sc, sc_timerq);
272 if (!callout_active(&tq->timeo))
273 callout_reset(&tq->timeo, rto, syncache_timer, &tq->nm);
276 static void
277 syncache_free(struct syncache *sc)
279 struct rtentry *rt;
280 #ifdef INET6
281 const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
282 #else
283 const boolean_t isipv6 = FALSE;
284 #endif
286 if (sc->sc_ipopts)
287 m_free(sc->sc_ipopts);
289 rt = isipv6 ? sc->sc_route6.ro_rt : sc->sc_route.ro_rt;
290 if (rt != NULL) {
292 * If this is the only reference to a protocol-cloned
293 * route, remove it immediately.
295 if ((rt->rt_flags & (RTF_WASCLONED | RTF_LLINFO)) ==
296 RTF_WASCLONED && rt->rt_refcnt == 1) {
297 rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
298 rt_mask(rt), rt->rt_flags, NULL);
300 RTFREE(rt);
302 kfree(sc, M_SYNCACHE);
305 static void
306 syncache_init_dispatch(netmsg_t nm)
308 struct tcp_syncache_percpu *syncache_percpu;
309 int i;
311 ASSERT_NETISR_NCPUS(mycpuid);
313 syncache_percpu = kmalloc(sizeof(*syncache_percpu), M_SYNCACHE,
314 M_WAITOK);
316 /* Allocate the hash table. */
317 syncache_percpu->hashbase = kmalloc(
318 tcp_syncache.hashsize * sizeof(struct syncache_head),
319 M_SYNCACHE, M_WAITOK);
321 /* Initialize the hash buckets. */
322 for (i = 0; i < tcp_syncache.hashsize; i++) {
323 struct syncache_head *bucket;
325 bucket = &syncache_percpu->hashbase[i];
326 TAILQ_INIT(&bucket->sch_bucket);
327 bucket->sch_length = 0;
330 for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
331 struct syncache_timerq *tq =
332 &syncache_percpu->timerq[i];
334 /* Initialize the timer queues. */
335 TAILQ_INIT(&tq->list);
336 callout_init_mp(&tq->timeo);
338 netmsg_init(&tq->nm, NULL, &netisr_adone_rport,
339 MSGF_PRIORITY, syncache_timer_handler);
340 tq->nm.lmsg.u.ms_result = i;
343 tcp_syncache_percpu[mycpuid] = syncache_percpu;
345 netisr_forwardmsg(&nm->base, mycpuid + 1);
348 void
349 syncache_init(void)
351 struct netmsg_base nm;
353 tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
354 tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
355 tcp_syncache.cache_limit =
356 tcp_syncache.hashsize * tcp_syncache.bucket_limit;
357 tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
358 tcp_syncache.hash_secret = karc4random();
360 TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
361 &tcp_syncache.hashsize);
362 TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
363 &tcp_syncache.cache_limit);
364 TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
365 &tcp_syncache.bucket_limit);
366 if (!powerof2(tcp_syncache.hashsize)) {
367 kprintf("WARNING: syncache hash size is not a power of 2.\n");
368 tcp_syncache.hashsize = 512; /* safe default */
370 tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
372 netmsg_init(&nm, NULL, &curthread->td_msgport, 0,
373 syncache_init_dispatch);
374 netisr_domsg_global(&nm);
377 static void
378 syncache_insert(struct syncache *sc, struct syncache_head *sch)
380 struct tcp_syncache_percpu *syncache_percpu;
381 struct syncache *sc2;
382 int i;
384 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
387 * Make sure that we don't overflow the per-bucket
388 * limit or the total cache size limit.
390 if (sch->sch_length >= tcp_syncache.bucket_limit) {
392 * The bucket is full, toss the oldest element.
394 sc2 = TAILQ_FIRST(&sch->sch_bucket);
395 if (sc2->sc_tp != NULL)
396 sc2->sc_tp->ts_recent = ticks;
397 syncache_drop(sc2, sch);
398 tcpstat.tcps_sc_bucketoverflow++;
399 } else if (syncache_percpu->cache_count >= tcp_syncache.cache_limit) {
401 * The cache is full. Toss the oldest entry in the
402 * entire cache. This is the front entry in the
403 * first non-empty timer queue with the largest
404 * timeout value.
406 for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
407 sc2 = TAILQ_FIRST(&syncache_percpu->timerq[i].list);
408 while (sc2 && (sc2->sc_flags & SCF_MARKER))
409 sc2 = TAILQ_NEXT(sc2, sc_timerq);
410 if (sc2 != NULL)
411 break;
413 if (sc2->sc_tp != NULL)
414 sc2->sc_tp->ts_recent = ticks;
415 syncache_drop(sc2, NULL);
416 tcpstat.tcps_sc_cacheoverflow++;
419 /* Initialize the entry's timer. */
420 syncache_timeout(syncache_percpu, sc, 0);
422 /* Put it into the bucket. */
423 TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
424 sch->sch_length++;
425 syncache_percpu->cache_count++;
426 tcpstat.tcps_sc_added++;
429 void
430 syncache_destroy(struct tcpcb *tp, struct tcpcb *tp_inh)
432 struct tcp_syncache_percpu *syncache_percpu;
433 struct syncache_head *bucket;
434 struct syncache *sc;
435 int i;
437 ASSERT_NETISR_NCPUS(mycpuid);
439 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
440 sc = NULL;
442 for (i = 0; i < tcp_syncache.hashsize; i++) {
443 bucket = &syncache_percpu->hashbase[i];
444 TAILQ_FOREACH(sc, &bucket->sch_bucket, sc_hash) {
445 if (sc->sc_tp == tp)
446 sc->sc_tp = tp_inh;
451 static void
452 syncache_drop(struct syncache *sc, struct syncache_head *sch)
454 struct tcp_syncache_percpu *syncache_percpu;
455 #ifdef INET6
456 const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
457 #else
458 const boolean_t isipv6 = FALSE;
459 #endif
461 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
463 if (sch == NULL) {
464 if (isipv6) {
465 sch = &syncache_percpu->hashbase[
466 SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
467 } else {
468 sch = &syncache_percpu->hashbase[
469 SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
473 TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
474 sch->sch_length--;
475 syncache_percpu->cache_count--;
478 * Cleanup
480 sc->sc_tp = NULL;
483 * Remove the entry from the syncache timer/timeout queue. Note
484 * that we do not try to stop any running timer since we do not know
485 * whether the timer's message is in-transit or not. Since timeouts
486 * are fairly long, taking an unneeded callout does not detrimentally
487 * effect performance.
489 TAILQ_REMOVE(&syncache_percpu->timerq[sc->sc_rxtslot].list, sc,
490 sc_timerq);
492 syncache_free(sc);
496 * Place a timeout message on the TCP thread's message queue.
497 * This routine runs in soft interrupt context.
499 * An invariant is for this routine to be called, the callout must
500 * have been active. Note that the callout is not deactivated until
501 * after the message has been processed in syncache_timer_handler() below.
503 static void
504 syncache_timer(void *p)
506 struct netmsg_base *msg = p;
508 KKASSERT(mycpuid < netisr_ncpus);
510 crit_enter();
511 if (msg->lmsg.ms_flags & MSGF_DONE)
512 netisr_sendmsg_oncpu(msg);
513 crit_exit();
517 * Service a timer message queued by timer expiration.
518 * This routine runs in the TCP protocol thread.
520 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
521 * If we have retransmitted an entry the maximum number of times, expire it.
523 * When we finish processing timed-out entries, we restart the timer if there
524 * are any entries still on the queue and deactivate it otherwise. Only after
525 * a timer has been deactivated here can it be restarted by syncache_timeout().
527 static void
528 syncache_timer_handler(netmsg_t msg)
530 struct tcp_syncache_percpu *syncache_percpu;
531 struct syncache *sc;
532 struct syncache marker;
533 struct syncache_timerq *tq;
534 struct syncache_list *list;
535 struct inpcb *inp;
536 int slot;
538 ASSERT_NETISR_NCPUS(mycpuid);
540 /* Reply ASAP. */
541 crit_enter();
542 netisr_replymsg(&msg->base, 0);
543 crit_exit();
545 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
547 slot = msg->lmsg.u.ms_result;
548 KASSERT(slot <= SYNCACHE_MAXREXMTS,
549 ("syncache: invalid slot %d", slot));
550 tq = &syncache_percpu->timerq[slot];
551 list = &tq->list;
554 * Use a marker to keep our place in the scan. syncache_drop()
555 * can block and cause any next pointer we cache to become stale.
557 marker.sc_flags = SCF_MARKER;
558 TAILQ_INSERT_HEAD(list, &marker, sc_timerq);
560 while ((sc = TAILQ_NEXT(&marker, sc_timerq)) != NULL) {
562 * Move the marker.
564 TAILQ_REMOVE(list, &marker, sc_timerq);
565 TAILQ_INSERT_AFTER(list, sc, &marker, sc_timerq);
567 if (sc->sc_flags & SCF_MARKER)
568 continue;
570 if (ticks < sc->sc_rxttime)
571 break; /* finished because timerq sorted by time */
572 if (sc->sc_tp == NULL) {
573 syncache_drop(sc, NULL);
574 tcpstat.tcps_sc_stale++;
575 continue;
577 inp = sc->sc_tp->t_inpcb;
578 if (slot == SYNCACHE_MAXREXMTS ||
579 slot >= tcp_syncache.rexmt_limit ||
580 inp == NULL ||
581 inp->inp_gencnt != sc->sc_inp_gencnt) {
582 syncache_drop(sc, NULL);
583 tcpstat.tcps_sc_stale++;
584 continue;
587 * syncache_respond() may call back into the syncache to
588 * to modify another entry, so do not obtain the next
589 * entry on the timer chain until it has completed.
591 syncache_respond(sc, NULL);
592 tcpstat.tcps_sc_retransmitted++;
593 TAILQ_REMOVE(list, sc, sc_timerq);
594 syncache_timeout(syncache_percpu, sc, slot + 1);
596 TAILQ_REMOVE(list, &marker, sc_timerq);
598 if (sc != NULL) {
599 callout_reset(&tq->timeo, sc->sc_rxttime - ticks,
600 syncache_timer, &tq->nm);
601 } else {
602 callout_deactivate(&tq->timeo);
607 * Find an entry in the syncache.
609 static struct syncache *
610 syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
612 struct tcp_syncache_percpu *syncache_percpu;
613 struct syncache *sc;
614 struct syncache_head *sch;
616 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
617 #ifdef INET6
618 if (inc->inc_isipv6) {
619 sch = &syncache_percpu->hashbase[
620 SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
621 *schp = sch;
622 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash)
623 if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
624 return (sc);
625 } else
626 #endif
628 sch = &syncache_percpu->hashbase[
629 SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
630 *schp = sch;
631 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
632 #ifdef INET6
633 if (sc->sc_inc.inc_isipv6)
634 continue;
635 #endif
636 if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
637 return (sc);
640 return (NULL);
644 * This function is called when we get a RST for a
645 * non-existent connection, so that we can see if the
646 * connection is in the syn cache. If it is, zap it.
648 void
649 syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
651 struct syncache *sc;
652 struct syncache_head *sch;
654 ASSERT_NETISR_NCPUS(mycpuid);
656 sc = syncache_lookup(inc, &sch);
657 if (sc == NULL) {
658 return;
661 * If the RST bit is set, check the sequence number to see
662 * if this is a valid reset segment.
663 * RFC 793 page 37:
664 * In all states except SYN-SENT, all reset (RST) segments
665 * are validated by checking their SEQ-fields. A reset is
666 * valid if its sequence number is in the window.
668 * The sequence number in the reset segment is normally an
669 * echo of our outgoing acknowlegement numbers, but some hosts
670 * send a reset with the sequence number at the rightmost edge
671 * of our receive window, and we have to handle this case.
673 if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
674 SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
675 syncache_drop(sc, sch);
676 tcpstat.tcps_sc_reset++;
680 void
681 syncache_badack(struct in_conninfo *inc)
683 struct syncache *sc;
684 struct syncache_head *sch;
686 ASSERT_NETISR_NCPUS(mycpuid);
688 sc = syncache_lookup(inc, &sch);
689 if (sc != NULL) {
690 syncache_drop(sc, sch);
691 tcpstat.tcps_sc_badack++;
695 void
696 syncache_unreach(struct in_conninfo *inc, const struct tcphdr *th)
698 struct syncache *sc;
699 struct syncache_head *sch;
701 ASSERT_NETISR_NCPUS(mycpuid);
703 /* we are called at splnet() here */
704 sc = syncache_lookup(inc, &sch);
705 if (sc == NULL)
706 return;
708 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
709 if (ntohl(th->th_seq) != sc->sc_iss)
710 return;
713 * If we've rertransmitted 3 times and this is our second error,
714 * we remove the entry. Otherwise, we allow it to continue on.
715 * This prevents us from incorrectly nuking an entry during a
716 * spurious network outage.
718 * See tcp_notify().
720 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
721 sc->sc_flags |= SCF_UNREACH;
722 return;
724 syncache_drop(sc, sch);
725 tcpstat.tcps_sc_unreach++;
729 * Build a new TCP socket structure from a syncache entry.
731 * This is called from the context of the SYN+ACK
733 static struct socket *
734 syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
736 struct inpcb *inp = NULL, *linp;
737 struct socket *so;
738 struct tcpcb *tp, *ltp;
739 lwkt_port_t port;
740 #ifdef INET6
741 const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
742 #else
743 const boolean_t isipv6 = FALSE;
744 #endif
745 struct sockaddr_in sin_faddr;
746 struct sockaddr_in6 sin6_faddr;
747 struct sockaddr *faddr;
749 KASSERT(m->m_flags & M_HASH, ("mbuf has no hash"));
751 if (isipv6) {
752 faddr = (struct sockaddr *)&sin6_faddr;
753 sin6_faddr.sin6_family = AF_INET6;
754 sin6_faddr.sin6_len = sizeof(sin6_faddr);
755 sin6_faddr.sin6_addr = sc->sc_inc.inc6_faddr;
756 sin6_faddr.sin6_port = sc->sc_inc.inc_fport;
757 sin6_faddr.sin6_flowinfo = sin6_faddr.sin6_scope_id = 0;
758 } else {
759 faddr = (struct sockaddr *)&sin_faddr;
760 sin_faddr.sin_family = AF_INET;
761 sin_faddr.sin_len = sizeof(sin_faddr);
762 sin_faddr.sin_addr = sc->sc_inc.inc_faddr;
763 sin_faddr.sin_port = sc->sc_inc.inc_fport;
764 bzero(sin_faddr.sin_zero, sizeof(sin_faddr.sin_zero));
768 * Ok, create the full blown connection, and set things up
769 * as they would have been set up if we had created the
770 * connection when the SYN arrived. If we can't create
771 * the connection, abort it.
773 * Set the protocol processing port for the socket to the current
774 * port (that the connection came in on).
776 * NOTE:
777 * We don't keep a reference on the new socket, since its
778 * destruction will run in this thread (netisrN); there is no
779 * race here.
781 so = sonewconn_faddr(lso, SS_ISCONNECTED, faddr,
782 FALSE /* don't ref */);
783 if (so == NULL) {
785 * Drop the connection; we will send a RST if the peer
786 * retransmits the ACK,
788 tcpstat.tcps_listendrop++;
789 goto abort;
793 * Insert new socket into hash list.
795 inp = so->so_pcb;
796 inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
797 if (isipv6) {
798 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
799 } else {
800 KASSERT(INP_ISIPV4(inp), ("not inet pcb"));
801 inp->inp_laddr = sc->sc_inc.inc_laddr;
803 inp->inp_lport = sc->sc_inc.inc_lport;
805 linp = lso->so_pcb;
806 ltp = intotcpcb(linp);
808 tcp_pcbport_insert(ltp, inp);
810 #ifdef IPSEC
811 /* copy old policy into new socket's */
812 if (ipsec_copy_policy(linp->inp_sp, inp->inp_sp))
813 kprintf("syncache_expand: could not copy policy\n");
814 #endif
815 if (isipv6) {
816 struct in6_addr laddr6;
818 * Inherit socket options from the listening socket.
819 * Note that in6p_inputopts are not (and should not be)
820 * copied, since it stores previously received options and is
821 * used to detect if each new option is different than the
822 * previous one and hence should be passed to a user.
823 * If we copied in6p_inputopts, a user would not be able to
824 * receive options just after calling the accept system call.
826 inp->inp_flags |= linp->inp_flags & INP_CONTROLOPTS;
827 if (linp->in6p_outputopts)
828 inp->in6p_outputopts =
829 ip6_copypktopts(linp->in6p_outputopts, M_INTWAIT);
830 inp->in6p_route = sc->sc_route6;
831 sc->sc_route6.ro_rt = NULL;
833 laddr6 = inp->in6p_laddr;
834 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
835 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
836 if (in6_pcbconnect(inp, faddr, &thread0)) {
837 inp->in6p_laddr = laddr6;
838 goto abort;
840 port = tcp6_addrport();
841 } else {
842 struct in_addr laddr;
844 inp->inp_options = ip_srcroute(m);
845 if (inp->inp_options == NULL) {
846 inp->inp_options = sc->sc_ipopts;
847 sc->sc_ipopts = NULL;
849 inp->inp_route = sc->sc_route;
850 sc->sc_route.ro_rt = NULL;
852 laddr = inp->inp_laddr;
853 if (inp->inp_laddr.s_addr == INADDR_ANY)
854 inp->inp_laddr = sc->sc_inc.inc_laddr;
855 if (in_pcbconnect(inp, faddr, &thread0)) {
856 inp->inp_laddr = laddr;
857 goto abort;
860 inp->inp_flags |= INP_HASH;
861 inp->inp_hashval = m->m_pkthdr.hash;
862 port = netisr_hashport(inp->inp_hashval);
866 * The current port should be in the context of the SYN+ACK and
867 * so should match the tcp address port.
869 KASSERT(port == &curthread->td_msgport,
870 ("TCP PORT MISMATCH %p vs %p\n", port, &curthread->td_msgport));
872 tp = intotcpcb(inp);
873 TCP_STATE_CHANGE(tp, TCPS_SYN_RECEIVED);
874 tp->iss = sc->sc_iss;
875 tp->irs = sc->sc_irs;
876 tcp_rcvseqinit(tp);
877 tcp_sendseqinit(tp);
878 tp->snd_wnd = sc->sc_sndwnd;
879 tp->snd_wl1 = sc->sc_irs;
880 tp->rcv_up = sc->sc_irs + 1;
881 tp->rcv_wnd = sc->sc_wnd;
882 tp->rcv_adv += tp->rcv_wnd;
884 tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH | TF_NODELAY);
885 if (sc->sc_flags & SCF_NOOPT)
886 tp->t_flags |= TF_NOOPT;
887 if (sc->sc_flags & SCF_WINSCALE) {
888 tp->t_flags |= TF_REQ_SCALE | TF_RCVD_SCALE;
889 tp->snd_scale = sc->sc_requested_s_scale;
890 tp->request_r_scale = sc->sc_request_r_scale;
892 if (sc->sc_flags & SCF_TIMESTAMP) {
893 tp->t_flags |= TF_REQ_TSTMP | TF_RCVD_TSTMP;
894 tp->ts_recent = sc->sc_tsrecent;
895 tp->ts_recent_age = ticks;
897 if (sc->sc_flags & SCF_SACK_PERMITTED)
898 tp->t_flags |= TF_SACK_PERMITTED;
900 #ifdef TCP_SIGNATURE
901 if (sc->sc_flags & SCF_SIGNATURE)
902 tp->t_flags |= TF_SIGNATURE;
903 #endif /* TCP_SIGNATURE */
905 tp->t_rxtsyn = sc->sc_rxtused;
906 tcp_rmx_init(tp, sc->sc_peer_mss);
909 * Inherit some properties from the listen socket
911 tp->t_keepinit = ltp->t_keepinit;
912 tp->t_keepidle = ltp->t_keepidle;
913 tp->t_keepintvl = ltp->t_keepintvl;
914 tp->t_keepcnt = ltp->t_keepcnt;
915 tp->t_maxidle = ltp->t_maxidle;
917 tcp_create_timermsg(tp, port);
918 tcp_callout_reset(tp, tp->tt_keep, tp->t_keepinit, tcp_timer_keep);
920 tcpstat.tcps_accepts++;
921 return (so);
923 abort:
924 if (so != NULL)
925 soabort_direct(so);
926 return (NULL);
930 * This function gets called when we receive an ACK for a
931 * socket in the LISTEN state. We look up the connection
932 * in the syncache, and if its there, we pull it out of
933 * the cache and turn it into a full-blown connection in
934 * the SYN-RECEIVED state.
937 syncache_expand(struct in_conninfo *inc, struct tcphdr *th, struct socket **sop,
938 struct mbuf *m)
940 struct syncache *sc;
941 struct syncache_head *sch;
942 struct socket *so;
944 ASSERT_NETISR_NCPUS(mycpuid);
946 sc = syncache_lookup(inc, &sch);
947 if (sc == NULL) {
949 * There is no syncache entry, so see if this ACK is
950 * a returning syncookie. To do this, first:
951 * A. See if this socket has had a syncache entry dropped in
952 * the past. We don't want to accept a bogus syncookie
953 * if we've never received a SYN.
954 * B. check that the syncookie is valid. If it is, then
955 * cobble up a fake syncache entry, and return.
957 if (!tcp_syncookies)
958 return (0);
959 sc = syncookie_lookup(inc, th, *sop);
960 if (sc == NULL)
961 return (0);
962 sch = NULL;
963 tcpstat.tcps_sc_recvcookie++;
967 * If seg contains an ACK, but not for our SYN/ACK, send a RST.
969 if (th->th_ack != sc->sc_iss + 1)
970 return (0);
972 so = syncache_socket(sc, *sop, m);
973 if (so == NULL) {
974 #if 0
975 resetandabort:
976 /* XXXjlemon check this - is this correct? */
977 tcp_respond(NULL, m, m, th,
978 th->th_seq + tlen, (tcp_seq)0, TH_RST | TH_ACK);
979 #endif
980 m_freem(m); /* XXX only needed for above */
981 tcpstat.tcps_sc_aborted++;
982 } else {
983 tcpstat.tcps_sc_completed++;
985 if (sch == NULL)
986 syncache_free(sc);
987 else
988 syncache_drop(sc, sch);
989 *sop = so;
990 return (1);
994 * Given a LISTEN socket and an inbound SYN request, add
995 * this to the syn cache, and send back a segment:
996 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
997 * to the source.
999 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
1000 * Doing so would require that we hold onto the data and deliver it
1001 * to the application. However, if we are the target of a SYN-flood
1002 * DoS attack, an attacker could send data which would eventually
1003 * consume all available buffer space if it were ACKed. By not ACKing
1004 * the data, we avoid this DoS scenario.
1007 syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1008 struct socket *so, struct mbuf *m)
1010 struct tcp_syncache_percpu *syncache_percpu;
1011 struct tcpcb *tp;
1012 struct syncache *sc = NULL;
1013 struct syncache_head *sch;
1014 struct mbuf *ipopts = NULL;
1015 int win;
1017 ASSERT_NETISR_NCPUS(mycpuid);
1018 KASSERT(m->m_flags & M_HASH, ("mbuf has no hash"));
1020 syncache_percpu = tcp_syncache_percpu[mycpu->gd_cpuid];
1021 tp = sototcpcb(so);
1024 * Remember the IP options, if any.
1026 #ifdef INET6
1027 if (!inc->inc_isipv6)
1028 #endif
1029 ipopts = ip_srcroute(m);
1032 * See if we already have an entry for this connection.
1033 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1035 * XXX
1036 * The syncache should be re-initialized with the contents
1037 * of the new SYN which may have different options.
1039 sc = syncache_lookup(inc, &sch);
1040 if (sc != NULL) {
1041 KASSERT(sc->sc_flags & SCF_HASH, ("syncache has no hash"));
1042 KASSERT(sc->sc_hashval == m->m_pkthdr.hash,
1043 ("syncache/mbuf hash mismatches"));
1045 tcpstat.tcps_sc_dupsyn++;
1046 if (ipopts) {
1048 * If we were remembering a previous source route,
1049 * forget it and use the new one we've been given.
1051 if (sc->sc_ipopts)
1052 m_free(sc->sc_ipopts);
1053 sc->sc_ipopts = ipopts;
1056 * Update timestamp if present.
1058 if (sc->sc_flags & SCF_TIMESTAMP)
1059 sc->sc_tsrecent = to->to_tsval;
1061 /* Just update the TOF_SACK_PERMITTED for now. */
1062 if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
1063 sc->sc_flags |= SCF_SACK_PERMITTED;
1064 else
1065 sc->sc_flags &= ~SCF_SACK_PERMITTED;
1067 /* Update initial send window */
1068 sc->sc_sndwnd = th->th_win;
1071 * PCB may have changed, pick up new values.
1073 sc->sc_tp = tp;
1074 sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
1075 if (syncache_respond(sc, m) == 0) {
1076 TAILQ_REMOVE(
1077 &syncache_percpu->timerq[sc->sc_rxtslot].list,
1078 sc, sc_timerq);
1079 syncache_timeout(syncache_percpu, sc, sc->sc_rxtslot);
1080 tcpstat.tcps_sndacks++;
1081 tcpstat.tcps_sndtotal++;
1083 return (1);
1087 * Fill in the syncache values.
1089 sc = kmalloc(sizeof(struct syncache), M_SYNCACHE, M_WAITOK|M_ZERO);
1090 sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
1091 sc->sc_ipopts = ipopts;
1092 sc->sc_inc.inc_fport = inc->inc_fport;
1093 sc->sc_inc.inc_lport = inc->inc_lport;
1094 sc->sc_tp = tp;
1095 #ifdef INET6
1096 sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1097 if (inc->inc_isipv6) {
1098 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1099 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1100 sc->sc_route6.ro_rt = NULL;
1101 } else
1102 #endif
1104 sc->sc_inc.inc_faddr = inc->inc_faddr;
1105 sc->sc_inc.inc_laddr = inc->inc_laddr;
1106 sc->sc_route.ro_rt = NULL;
1108 sc->sc_irs = th->th_seq;
1109 sc->sc_flags = SCF_HASH;
1110 sc->sc_hashval = m->m_pkthdr.hash;
1111 sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
1112 if (tcp_syncookies)
1113 sc->sc_iss = syncookie_generate(sc);
1114 else
1115 sc->sc_iss = karc4random();
1117 /* Initial receive window: clip ssb_space to [0 .. TCP_MAXWIN] */
1118 win = ssb_space(&so->so_rcv);
1119 win = imax(win, 0);
1120 win = imin(win, TCP_MAXWIN);
1121 sc->sc_wnd = win;
1123 if (tcp_do_rfc1323) {
1125 * A timestamp received in a SYN makes
1126 * it ok to send timestamp requests and replies.
1128 if (to->to_flags & TOF_TS) {
1129 sc->sc_tsrecent = to->to_tsval;
1130 sc->sc_flags |= SCF_TIMESTAMP;
1132 if (to->to_flags & TOF_SCALE) {
1133 int wscale = TCP_MIN_WINSHIFT;
1135 /* Compute proper scaling value from buffer space */
1136 while (wscale < TCP_MAX_WINSHIFT &&
1137 (TCP_MAXWIN << wscale) < so->so_rcv.ssb_hiwat) {
1138 wscale++;
1140 sc->sc_request_r_scale = wscale;
1141 sc->sc_requested_s_scale = to->to_requested_s_scale;
1142 sc->sc_flags |= SCF_WINSCALE;
1145 if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
1146 sc->sc_flags |= SCF_SACK_PERMITTED;
1147 if (tp->t_flags & TF_NOOPT)
1148 sc->sc_flags = SCF_NOOPT;
1149 #ifdef TCP_SIGNATURE
1151 * If listening socket requested TCP digests, and received SYN
1152 * contains the option, flag this in the syncache so that
1153 * syncache_respond() will do the right thing with the SYN+ACK.
1154 * XXX Currently we always record the option by default and will
1155 * attempt to use it in syncache_respond().
1157 if (to->to_flags & TOF_SIGNATURE)
1158 sc->sc_flags = SCF_SIGNATURE;
1159 #endif /* TCP_SIGNATURE */
1160 sc->sc_sndwnd = th->th_win;
1162 if (syncache_respond(sc, m) == 0) {
1163 syncache_insert(sc, sch);
1164 tcpstat.tcps_sndacks++;
1165 tcpstat.tcps_sndtotal++;
1166 } else {
1167 syncache_free(sc);
1168 tcpstat.tcps_sc_dropped++;
1170 return (1);
1173 static int
1174 syncache_respond(struct syncache *sc, struct mbuf *m)
1176 u_int8_t *optp;
1177 int optlen, error;
1178 u_int16_t tlen, hlen, mssopt;
1179 struct ip *ip = NULL;
1180 struct rtentry *rt;
1181 struct tcphdr *th;
1182 struct ip6_hdr *ip6 = NULL;
1183 #ifdef INET6
1184 const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1185 #else
1186 const boolean_t isipv6 = FALSE;
1187 #endif
1189 if (isipv6) {
1190 rt = tcp_rtlookup6(&sc->sc_inc);
1191 if (rt != NULL)
1192 mssopt = rt->rt_ifp->if_mtu -
1193 (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1194 else
1195 mssopt = tcp_v6mssdflt;
1196 hlen = sizeof(struct ip6_hdr);
1197 } else {
1198 rt = tcp_rtlookup(&sc->sc_inc);
1199 if (rt != NULL)
1200 mssopt = rt->rt_ifp->if_mtu -
1201 (sizeof(struct ip) + sizeof(struct tcphdr));
1202 else
1203 mssopt = tcp_mssdflt;
1204 hlen = sizeof(struct ip);
1207 /* Compute the size of the TCP options. */
1208 if (sc->sc_flags & SCF_NOOPT) {
1209 optlen = 0;
1210 } else {
1211 optlen = TCPOLEN_MAXSEG +
1212 ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1213 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
1214 ((sc->sc_flags & SCF_SACK_PERMITTED) ?
1215 TCPOLEN_SACK_PERMITTED_ALIGNED : 0);
1216 #ifdef TCP_SIGNATURE
1217 optlen += ((sc->sc_flags & SCF_SIGNATURE) ?
1218 (TCPOLEN_SIGNATURE + 2) : 0);
1219 #endif /* TCP_SIGNATURE */
1221 tlen = hlen + sizeof(struct tcphdr) + optlen;
1224 * XXX
1225 * assume that the entire packet will fit in a header mbuf
1227 KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1230 * XXX shouldn't this reuse the mbuf if possible ?
1231 * Create the IP+TCP header from scratch.
1233 if (m)
1234 m_freem(m);
1236 m = m_gethdr(M_NOWAIT, MT_HEADER);
1237 if (m == NULL)
1238 return (ENOBUFS);
1239 m->m_data += max_linkhdr;
1240 m->m_len = tlen;
1241 m->m_pkthdr.len = tlen;
1242 m->m_pkthdr.rcvif = NULL;
1243 if (tcp_prio_synack)
1244 m->m_flags |= M_PRIO;
1246 if (isipv6) {
1247 ip6 = mtod(m, struct ip6_hdr *);
1248 ip6->ip6_vfc = IPV6_VERSION;
1249 ip6->ip6_nxt = IPPROTO_TCP;
1250 ip6->ip6_src = sc->sc_inc.inc6_laddr;
1251 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1252 ip6->ip6_plen = htons(tlen - hlen);
1253 /* ip6_hlim is set after checksum */
1254 /* ip6_flow = ??? */
1256 th = (struct tcphdr *)(ip6 + 1);
1257 } else {
1258 ip = mtod(m, struct ip *);
1259 ip->ip_v = IPVERSION;
1260 ip->ip_hl = sizeof(struct ip) >> 2;
1261 ip->ip_len = tlen;
1262 ip->ip_id = 0;
1263 ip->ip_off = 0;
1264 ip->ip_sum = 0;
1265 ip->ip_p = IPPROTO_TCP;
1266 ip->ip_src = sc->sc_inc.inc_laddr;
1267 ip->ip_dst = sc->sc_inc.inc_faddr;
1268 ip->ip_ttl = sc->sc_tp->t_inpcb->inp_ip_ttl; /* XXX */
1269 ip->ip_tos = sc->sc_tp->t_inpcb->inp_ip_tos; /* XXX */
1272 * See if we should do MTU discovery. Route lookups are
1273 * expensive, so we will only unset the DF bit if:
1275 * 1) path_mtu_discovery is disabled
1276 * 2) the SCF_UNREACH flag has been set
1278 if (path_mtu_discovery
1279 && ((sc->sc_flags & SCF_UNREACH) == 0)) {
1280 ip->ip_off |= IP_DF;
1283 th = (struct tcphdr *)(ip + 1);
1285 th->th_sport = sc->sc_inc.inc_lport;
1286 th->th_dport = sc->sc_inc.inc_fport;
1288 th->th_seq = htonl(sc->sc_iss);
1289 th->th_ack = htonl(sc->sc_irs + 1);
1290 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1291 th->th_x2 = 0;
1292 th->th_flags = TH_SYN | TH_ACK;
1293 th->th_win = htons(sc->sc_wnd);
1294 th->th_urp = 0;
1296 /* Tack on the TCP options. */
1297 if (optlen == 0)
1298 goto no_options;
1299 optp = (u_int8_t *)(th + 1);
1300 *optp++ = TCPOPT_MAXSEG;
1301 *optp++ = TCPOLEN_MAXSEG;
1302 *optp++ = (mssopt >> 8) & 0xff;
1303 *optp++ = mssopt & 0xff;
1305 if (sc->sc_flags & SCF_WINSCALE) {
1306 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1307 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1308 sc->sc_request_r_scale);
1309 optp += 4;
1312 if (sc->sc_flags & SCF_TIMESTAMP) {
1313 u_int32_t *lp = (u_int32_t *)(optp);
1315 /* Form timestamp option as shown in appendix A of RFC 1323. */
1316 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
1317 *lp++ = htonl(ticks);
1318 *lp = htonl(sc->sc_tsrecent);
1319 optp += TCPOLEN_TSTAMP_APPA;
1322 #ifdef TCP_SIGNATURE
1324 * Handle TCP-MD5 passive opener response.
1326 if (sc->sc_flags & SCF_SIGNATURE) {
1327 u_int8_t *bp = optp;
1328 int i;
1330 *bp++ = TCPOPT_SIGNATURE;
1331 *bp++ = TCPOLEN_SIGNATURE;
1332 for (i = 0; i < TCP_SIGLEN; i++)
1333 *bp++ = 0;
1334 tcpsignature_compute(m, 0, optlen,
1335 optp + 2, IPSEC_DIR_OUTBOUND);
1336 *bp++ = TCPOPT_NOP;
1337 *bp++ = TCPOPT_EOL;
1338 optp += TCPOLEN_SIGNATURE + 2;
1340 #endif /* TCP_SIGNATURE */
1342 if (sc->sc_flags & SCF_SACK_PERMITTED) {
1343 *((u_int32_t *)optp) = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
1344 optp += TCPOLEN_SACK_PERMITTED_ALIGNED;
1347 no_options:
1348 if (isipv6) {
1349 struct route_in6 *ro6 = &sc->sc_route6;
1351 th->th_sum = 0;
1352 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1353 ip6->ip6_hlim = in6_selecthlim(NULL,
1354 ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
1355 error = ip6_output(m, NULL, ro6, 0, NULL, NULL,
1356 sc->sc_tp->t_inpcb);
1357 } else {
1358 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1359 htons(tlen - hlen + IPPROTO_TCP));
1360 m->m_pkthdr.csum_flags = CSUM_TCP;
1361 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1362 m->m_pkthdr.csum_thlen = sizeof(struct tcphdr) + optlen;
1363 KASSERT(sc->sc_flags & SCF_HASH, ("syncache has no hash"));
1364 m_sethash(m, sc->sc_hashval);
1365 error = ip_output(m, sc->sc_ipopts, &sc->sc_route,
1366 IP_DEBUGROUTE, NULL, sc->sc_tp->t_inpcb);
1368 return (error);
1372 * cookie layers:
1374 * |. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1375 * | peer iss |
1376 * | MD5(laddr,faddr,secret,lport,fport) |. . . . . . .|
1377 * | 0 |(A)| |
1378 * (A): peer mss index
1382 * The values below are chosen to minimize the size of the tcp_secret
1383 * table, as well as providing roughly a 16 second lifetime for the cookie.
1386 #define SYNCOOKIE_WNDBITS 5 /* exposed bits for window indexing */
1387 #define SYNCOOKIE_TIMESHIFT 1 /* scale ticks to window time units */
1389 #define SYNCOOKIE_WNDMASK ((1 << SYNCOOKIE_WNDBITS) - 1)
1390 #define SYNCOOKIE_NSECRETS (1 << SYNCOOKIE_WNDBITS)
1391 #define SYNCOOKIE_TIMEOUT \
1392 (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1393 #define SYNCOOKIE_DATAMASK ((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1395 static struct {
1396 u_int32_t ts_secbits[4];
1397 u_int ts_expire;
1398 } tcp_secret[SYNCOOKIE_NSECRETS];
1400 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1402 static MD5_CTX syn_ctx;
1404 #define MD5Add(v) MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1406 struct md5_add {
1407 u_int32_t laddr, faddr;
1408 u_int32_t secbits[4];
1409 u_int16_t lport, fport;
1412 #ifdef CTASSERT
1413 CTASSERT(sizeof(struct md5_add) == 28);
1414 #endif
1417 * Consider the problem of a recreated (and retransmitted) cookie. If the
1418 * original SYN was accepted, the connection is established. The second
1419 * SYN is inflight, and if it arrives with an ISN that falls within the
1420 * receive window, the connection is killed.
1422 * However, since cookies have other problems, this may not be worth
1423 * worrying about.
1426 static u_int32_t
1427 syncookie_generate(struct syncache *sc)
1429 u_int32_t md5_buffer[4];
1430 u_int32_t data;
1431 int idx, i;
1432 struct md5_add add;
1433 #ifdef INET6
1434 const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1435 #else
1436 const boolean_t isipv6 = FALSE;
1437 #endif
1439 idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1440 if (tcp_secret[idx].ts_expire < ticks) {
1441 for (i = 0; i < 4; i++)
1442 tcp_secret[idx].ts_secbits[i] = karc4random();
1443 tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1445 for (data = NELEM(tcp_msstab) - 1; data > 0; data--)
1446 if (tcp_msstab[data] <= sc->sc_peer_mss)
1447 break;
1448 data = (data << SYNCOOKIE_WNDBITS) | idx;
1449 data ^= sc->sc_irs; /* peer's iss */
1450 MD5Init(&syn_ctx);
1451 if (isipv6) {
1452 MD5Add(sc->sc_inc.inc6_laddr);
1453 MD5Add(sc->sc_inc.inc6_faddr);
1454 add.laddr = 0;
1455 add.faddr = 0;
1456 } else {
1457 add.laddr = sc->sc_inc.inc_laddr.s_addr;
1458 add.faddr = sc->sc_inc.inc_faddr.s_addr;
1460 add.lport = sc->sc_inc.inc_lport;
1461 add.fport = sc->sc_inc.inc_fport;
1462 add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1463 add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1464 add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1465 add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1466 MD5Add(add);
1467 MD5Final((u_char *)&md5_buffer, &syn_ctx);
1468 data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
1469 return (data);
1472 static struct syncache *
1473 syncookie_lookup(struct in_conninfo *inc, struct tcphdr *th, struct socket *so)
1475 u_int32_t md5_buffer[4];
1476 struct syncache *sc;
1477 u_int32_t data;
1478 int wnd, idx;
1479 struct md5_add add;
1481 data = (th->th_ack - 1) ^ (th->th_seq - 1); /* remove ISS */
1482 idx = data & SYNCOOKIE_WNDMASK;
1483 if (tcp_secret[idx].ts_expire < ticks ||
1484 sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1485 return (NULL);
1486 MD5Init(&syn_ctx);
1487 #ifdef INET6
1488 if (inc->inc_isipv6) {
1489 MD5Add(inc->inc6_laddr);
1490 MD5Add(inc->inc6_faddr);
1491 add.laddr = 0;
1492 add.faddr = 0;
1493 } else
1494 #endif
1496 add.laddr = inc->inc_laddr.s_addr;
1497 add.faddr = inc->inc_faddr.s_addr;
1499 add.lport = inc->inc_lport;
1500 add.fport = inc->inc_fport;
1501 add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1502 add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1503 add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1504 add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1505 MD5Add(add);
1506 MD5Final((u_char *)&md5_buffer, &syn_ctx);
1507 data ^= md5_buffer[0];
1508 if (data & ~SYNCOOKIE_DATAMASK)
1509 return (NULL);
1510 data = data >> SYNCOOKIE_WNDBITS;
1513 * Fill in the syncache values.
1514 * XXX duplicate code from syncache_add
1516 sc = kmalloc(sizeof(struct syncache), M_SYNCACHE, M_WAITOK|M_ZERO);
1517 sc->sc_ipopts = NULL;
1518 sc->sc_inc.inc_fport = inc->inc_fport;
1519 sc->sc_inc.inc_lport = inc->inc_lport;
1520 #ifdef INET6
1521 sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1522 if (inc->inc_isipv6) {
1523 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1524 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1525 sc->sc_route6.ro_rt = NULL;
1526 } else
1527 #endif
1529 sc->sc_inc.inc_faddr = inc->inc_faddr;
1530 sc->sc_inc.inc_laddr = inc->inc_laddr;
1531 sc->sc_route.ro_rt = NULL;
1533 sc->sc_irs = th->th_seq - 1;
1534 sc->sc_iss = th->th_ack - 1;
1535 wnd = ssb_space(&so->so_rcv);
1536 wnd = imax(wnd, 0);
1537 wnd = imin(wnd, TCP_MAXWIN);
1538 sc->sc_wnd = wnd;
1539 sc->sc_flags = 0;
1540 sc->sc_rxtslot = 0;
1541 sc->sc_peer_mss = tcp_msstab[data];
1542 return (sc);