Add a missing initialization for the error variable which resulted in netstat
[dragonfly.git] / sys / netinet / tcp_syncache.c
1 /*
2  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
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.
19  *
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.
32  */
33
34 /*
35  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
36  *
37  * License terms: all terms for the DragonFly license above plus the following:
38  *
39  * 4. All advertising materials mentioning features or use of this software
40  *    must display the following acknowledgement:
41  *
42  *      This product includes software developed by Jeffrey M. Hsu
43  *      for the DragonFly Project.
44  *
45  *    This requirement may be waived with permission from Jeffrey Hsu.
46  *    This requirement will sunset and may be removed on July 8 2005,
47  *    after which the standard DragonFly license (as shown above) will
48  *    apply.
49  */
50
51 /*
52  * All advertising materials mentioning features or use of this software
53  * must display the following acknowledgement:
54  *   This product includes software developed by Jeffrey M. Hsu.
55  *
56  * Copyright (c) 2001 Networks Associates Technologies, Inc.
57  * All rights reserved.
58  *
59  * This software was developed for the FreeBSD Project by Jonathan Lemon
60  * and NAI Labs, the Security Research Division of Network Associates, Inc.
61  * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
62  * DARPA CHATS research program.
63  *
64  * Redistribution and use in source and binary forms, with or without
65  * modification, are permitted provided that the following conditions
66  * are met:
67  * 1. Redistributions of source code must retain the above copyright
68  *    notice, this list of conditions and the following disclaimer.
69  * 2. Redistributions in binary form must reproduce the above copyright
70  *    notice, this list of conditions and the following disclaimer in the
71  *    documentation and/or other materials provided with the distribution.
72  * 3. The name of the author may not be used to endorse or promote
73  *    products derived from this software without specific prior written
74  *    permission.
75  *
76  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
77  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
80  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
81  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
82  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
83  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
84  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
85  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
86  * SUCH DAMAGE.
87  *
88  * $FreeBSD: src/sys/netinet/tcp_syncache.c,v 1.5.2.14 2003/02/24 04:02:27 silby Exp $
89  * $DragonFly: src/sys/netinet/tcp_syncache.c,v 1.20 2004/12/21 02:54:15 hsu Exp $
90  */
91
92 #include "opt_inet6.h"
93 #include "opt_ipsec.h"
94
95 #include <sys/param.h>
96 #include <sys/systm.h>
97 #include <sys/kernel.h>
98 #include <sys/sysctl.h>
99 #include <sys/malloc.h>
100 #include <sys/mbuf.h>
101 #include <sys/md5.h>
102 #include <sys/proc.h>           /* for proc0 declaration */
103 #include <sys/random.h>
104 #include <sys/socket.h>
105 #include <sys/socketvar.h>
106 #include <sys/in_cksum.h>
107
108 #include <sys/msgport2.h>
109
110 #include <net/if.h>
111 #include <net/route.h>
112
113 #include <netinet/in.h>
114 #include <netinet/in_systm.h>
115 #include <netinet/ip.h>
116 #include <netinet/in_var.h>
117 #include <netinet/in_pcb.h>
118 #include <netinet/ip_var.h>
119 #include <netinet/ip6.h>
120 #ifdef INET6
121 #include <netinet/icmp6.h>
122 #include <netinet6/nd6.h>
123 #endif
124 #include <netinet6/ip6_var.h>
125 #include <netinet6/in6_pcb.h>
126 #include <netinet/tcp.h>
127 #include <netinet/tcp_fsm.h>
128 #include <netinet/tcp_seq.h>
129 #include <netinet/tcp_timer.h>
130 #include <netinet/tcp_var.h>
131 #include <netinet6/tcp6_var.h>
132
133 #ifdef IPSEC
134 #include <netinet6/ipsec.h>
135 #ifdef INET6
136 #include <netinet6/ipsec6.h>
137 #endif
138 #include <netproto/key/key.h>
139 #endif /*IPSEC*/
140
141 #ifdef FAST_IPSEC
142 #include <netproto/ipsec/ipsec.h>
143 #ifdef INET6
144 #include <netproto/ipsec/ipsec6.h>
145 #endif
146 #include <netproto/ipsec/key.h>
147 #define IPSEC
148 #endif /*FAST_IPSEC*/
149
150 #include <vm/vm_zone.h>
151
152 static int tcp_syncookies = 1;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, syncookies, CTLFLAG_RW,
154     &tcp_syncookies, 0,
155     "Use TCP SYN cookies if the syncache overflows");
156
157 static void      syncache_drop(struct syncache *, struct syncache_head *);
158 static void      syncache_free(struct syncache *);
159 static void      syncache_insert(struct syncache *, struct syncache_head *);
160 struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
161 static int       syncache_respond(struct syncache *, struct mbuf *);
162 static struct    socket *syncache_socket(struct syncache *, struct socket *);
163 static void      syncache_timer(void *);
164 static u_int32_t syncookie_generate(struct syncache *);
165 static struct syncache *syncookie_lookup(struct in_conninfo *,
166                     struct tcphdr *, struct socket *);
167
168 /*
169  * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
170  * 3 retransmits corresponds to a timeout of (1 + 2 + 4 + 8 == 15) seconds,
171  * the odds are that the user has given up attempting to connect by then.
172  */
173 #define SYNCACHE_MAXREXMTS              3
174
175 /* Arbitrary values */
176 #define TCP_SYNCACHE_HASHSIZE           512
177 #define TCP_SYNCACHE_BUCKETLIMIT        30
178
179 struct netmsg_sc_timer {
180         struct lwkt_msg nm_lmsg;
181         struct msgrec *nm_mrec;         /* back pointer to containing msgrec */
182 };
183
184 struct msgrec {
185         struct netmsg_sc_timer msg;
186         lwkt_port_t port;               /* constant after init */
187         int slot;                       /* constant after init */
188 };
189
190 static int syncache_timer_handler(lwkt_msg_t);
191
192 struct tcp_syncache {
193         struct  vm_zone *zone;
194         u_int   hashsize;
195         u_int   hashmask;
196         u_int   bucket_limit;
197         u_int   cache_limit;
198         u_int   rexmt_limit;
199         u_int   hash_secret;
200 };
201 static struct tcp_syncache tcp_syncache;
202
203 struct tcp_syncache_percpu {
204         struct syncache_head    *hashbase;
205         u_int                   cache_count;
206         TAILQ_HEAD(, syncache)  timerq[SYNCACHE_MAXREXMTS + 1];
207         struct callout          tt_timerq[SYNCACHE_MAXREXMTS + 1];
208         struct msgrec           mrec[SYNCACHE_MAXREXMTS + 1];
209 };
210 static struct tcp_syncache_percpu tcp_syncache_percpu[MAXCPU];
211
212 static struct lwkt_port syncache_null_rport;
213
214 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
215
216 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, bucketlimit, CTLFLAG_RD,
217      &tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
218
219 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, cachelimit, CTLFLAG_RD,
220      &tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
221
222 /* XXX JH */
223 #if 0
224 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, count, CTLFLAG_RD,
225      &tcp_syncache.cache_count, 0, "Current number of entries in syncache");
226 #endif
227
228 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, hashsize, CTLFLAG_RD,
229      &tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
230
231 SYSCTL_INT(_net_inet_tcp_syncache, OID_AUTO, rexmtlimit, CTLFLAG_RW,
232      &tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
233
234 static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
235
236 #define SYNCACHE_HASH(inc, mask)                                        \
237         ((tcp_syncache.hash_secret ^                                    \
238           (inc)->inc_faddr.s_addr ^                                     \
239           ((inc)->inc_faddr.s_addr >> 16) ^                             \
240           (inc)->inc_fport ^ (inc)->inc_lport) & mask)
241
242 #define SYNCACHE_HASH6(inc, mask)                                       \
243         ((tcp_syncache.hash_secret ^                                    \
244           (inc)->inc6_faddr.s6_addr32[0] ^                              \
245           (inc)->inc6_faddr.s6_addr32[3] ^                              \
246           (inc)->inc_fport ^ (inc)->inc_lport) & mask)
247
248 #define ENDPTS_EQ(a, b) (                                               \
249         (a)->ie_fport == (b)->ie_fport &&                               \
250         (a)->ie_lport == (b)->ie_lport &&                               \
251         (a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&                 \
252         (a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr                    \
253 )
254
255 #define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
256
257 static __inline void
258 syncache_timeout(struct tcp_syncache_percpu *syncache_percpu,
259                  struct syncache *sc, int slot)
260 {
261         sc->sc_rxtslot = slot;
262         sc->sc_rxttime = ticks + TCPTV_RTOBASE * tcp_backoff[slot];
263         TAILQ_INSERT_TAIL(&syncache_percpu->timerq[slot], sc, sc_timerq);
264         if (!callout_active(&syncache_percpu->tt_timerq[slot])) {
265                 callout_reset(&syncache_percpu->tt_timerq[slot],
266                               TCPTV_RTOBASE * tcp_backoff[slot],
267                               syncache_timer,
268                               &syncache_percpu->mrec[slot]);
269         }
270 }
271
272 static void
273 syncache_free(struct syncache *sc)
274 {
275         struct rtentry *rt;
276 #ifdef INET6
277         const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
278 #else
279         const boolean_t isipv6 = FALSE;
280 #endif
281
282         if (sc->sc_ipopts)
283                 m_free(sc->sc_ipopts);
284         if (isipv6)
285                 rt = sc->sc_route6.ro_rt;
286         else
287                 rt = sc->sc_route.ro_rt;
288         if (rt != NULL) {
289                 /*
290                  * If this is the only reference to a protocol cloned
291                  * route, remove it immediately.
292                  */
293                 if (rt->rt_flags & RTF_WASCLONED &&
294                     !(sc->sc_flags & SCF_KEEPROUTE) &&
295                     rt->rt_refcnt == 1) {
296                         rtrequest(RTM_DELETE, rt_key(rt), rt->rt_gateway,
297                                   rt_mask(rt), rt->rt_flags, NULL);
298                 }
299                 RTFREE(rt);
300         }
301         zfree(tcp_syncache.zone, sc);
302 }
303
304 void
305 syncache_init(void)
306 {
307         int i, cpu;
308
309         tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
310         tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
311         tcp_syncache.cache_limit =
312             tcp_syncache.hashsize * tcp_syncache.bucket_limit;
313         tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
314         tcp_syncache.hash_secret = arc4random();
315
316         TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
317             &tcp_syncache.hashsize);
318         TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
319             &tcp_syncache.cache_limit);
320         TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
321             &tcp_syncache.bucket_limit);
322         if (!powerof2(tcp_syncache.hashsize)) {
323                 printf("WARNING: syncache hash size is not a power of 2.\n");
324                 tcp_syncache.hashsize = 512;    /* safe default */
325         }
326         tcp_syncache.hashmask = tcp_syncache.hashsize - 1;
327
328         lwkt_initport_null_rport(&syncache_null_rport, NULL);
329
330         for (cpu = 0; cpu < ncpus2; cpu++) {
331                 struct tcp_syncache_percpu *syncache_percpu;
332
333                 syncache_percpu = &tcp_syncache_percpu[cpu];
334                 /* Allocate the hash table. */
335                 MALLOC(syncache_percpu->hashbase, struct syncache_head *,
336                     tcp_syncache.hashsize * sizeof(struct syncache_head),
337                     M_SYNCACHE, M_WAITOK);
338
339                 /* Initialize the hash buckets. */
340                 for (i = 0; i < tcp_syncache.hashsize; i++) {
341                         struct syncache_head *bucket;
342
343                         bucket = &syncache_percpu->hashbase[i];
344                         TAILQ_INIT(&bucket->sch_bucket);
345                         bucket->sch_length = 0;
346                 }
347
348                 for (i = 0; i <= SYNCACHE_MAXREXMTS; i++) {
349                         /* Initialize the timer queues. */
350                         TAILQ_INIT(&syncache_percpu->timerq[i]);
351                         callout_init(&syncache_percpu->tt_timerq[i]);
352
353                         syncache_percpu->mrec[i].slot = i;
354                         syncache_percpu->mrec[i].port = tcp_cport(cpu);
355                         syncache_percpu->mrec[i].msg.nm_mrec =
356                             &syncache_percpu->mrec[i];
357                         lwkt_initmsg(&syncache_percpu->mrec[i].msg.nm_lmsg,
358                             &syncache_null_rport, 0,
359                             lwkt_cmd_func(syncache_timer_handler),
360                             lwkt_cmd_op_none);
361                 }
362         }
363
364         /*
365          * Allocate the syncache entries.  Allow the zone to allocate one
366          * more entry than cache limit, so a new entry can bump out an
367          * older one.
368          */
369         tcp_syncache.zone = zinit("syncache", sizeof(struct syncache),
370             tcp_syncache.cache_limit, ZONE_INTERRUPT, 0);
371         tcp_syncache.cache_limit -= 1;
372 }
373
374 static void
375 syncache_insert(sc, sch)
376         struct syncache *sc;
377         struct syncache_head *sch;
378 {
379         struct tcp_syncache_percpu *syncache_percpu;
380         struct syncache *sc2;
381         int i;
382
383         syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
384
385         /*
386          * Make sure that we don't overflow the per-bucket
387          * limit or the total cache size limit.
388          */
389         if (sch->sch_length >= tcp_syncache.bucket_limit) {
390                 /*
391                  * The bucket is full, toss the oldest element.
392                  */
393                 sc2 = TAILQ_FIRST(&sch->sch_bucket);
394                 sc2->sc_tp->ts_recent = ticks;
395                 syncache_drop(sc2, sch);
396                 tcpstat.tcps_sc_bucketoverflow++;
397         } else if (syncache_percpu->cache_count >= tcp_syncache.cache_limit) {
398                 /*
399                  * The cache is full.  Toss the oldest entry in the
400                  * entire cache.  This is the front entry in the
401                  * first non-empty timer queue with the largest
402                  * timeout value.
403                  */
404                 for (i = SYNCACHE_MAXREXMTS; i >= 0; i--) {
405                         sc2 = TAILQ_FIRST(&syncache_percpu->timerq[i]);
406                         if (sc2 != NULL)
407                                 break;
408                 }
409                 sc2->sc_tp->ts_recent = ticks;
410                 syncache_drop(sc2, NULL);
411                 tcpstat.tcps_sc_cacheoverflow++;
412         }
413
414         /* Initialize the entry's timer. */
415         syncache_timeout(syncache_percpu, sc, 0);
416
417         /* Put it into the bucket. */
418         TAILQ_INSERT_TAIL(&sch->sch_bucket, sc, sc_hash);
419         sch->sch_length++;
420         syncache_percpu->cache_count++;
421         tcpstat.tcps_sc_added++;
422 }
423
424 static void
425 syncache_drop(sc, sch)
426         struct syncache *sc;
427         struct syncache_head *sch;
428 {
429         struct tcp_syncache_percpu *syncache_percpu;
430 #ifdef INET6
431         const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
432 #else
433         const boolean_t isipv6 = FALSE;
434 #endif
435
436         syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
437
438         if (sch == NULL) {
439                 if (isipv6) {
440                         sch = &syncache_percpu->hashbase[
441                             SYNCACHE_HASH6(&sc->sc_inc, tcp_syncache.hashmask)];
442                 } else {
443                         sch = &syncache_percpu->hashbase[
444                             SYNCACHE_HASH(&sc->sc_inc, tcp_syncache.hashmask)];
445                 }
446         }
447
448         TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
449         sch->sch_length--;
450         syncache_percpu->cache_count--;
451
452         /*
453          * Remove the entry from the syncache timer/timeout queue.  Note
454          * that we do not try to stop any running timer since we do not know
455          * whether the timer's message is in-transit or not.  Since timeouts
456          * are fairly long, taking an unneeded callout does not detrimentally
457          * effect performance.
458          */
459         TAILQ_REMOVE(&syncache_percpu->timerq[sc->sc_rxtslot], sc, sc_timerq);
460
461         syncache_free(sc);
462 }
463
464 /*
465  * Place a timeout message on the TCP thread's message queue.
466  * This routine runs in soft interrupt context.
467  *
468  * An invariant is for this routine to be called, the callout must
469  * have been active.  Note that the callout is not deactivated until
470  * after the message has been processed in syncache_timer_handler() below.
471  */
472 static void
473 syncache_timer(void *p)
474 {
475         struct netmsg_sc_timer *msg = p;
476
477         lwkt_sendmsg(msg->nm_mrec->port, &msg->nm_lmsg);
478 }
479
480 /*
481  * Service a timer message queued by timer expiration.
482  * This routine runs in the TCP protocol thread.
483  *
484  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
485  * If we have retransmitted an entry the maximum number of times, expire it.
486  *
487  * When we finish processing timed-out entries, we restart the timer if there
488  * are any entries still on the queue and deactivate it otherwise.  Only after
489  * a timer has been deactivated here can it be restarted by syncache_timeout().
490  */
491 static int
492 syncache_timer_handler(lwkt_msg_t msg)
493 {
494         struct tcp_syncache_percpu *syncache_percpu;
495         struct syncache *sc, *nsc;
496         struct inpcb *inp;
497         int slot;
498
499         slot = ((struct netmsg_sc_timer *)msg)->nm_mrec->slot;
500         syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
501
502         nsc = TAILQ_FIRST(&syncache_percpu->timerq[slot]);
503         while (nsc != NULL) {
504                 if (ticks < nsc->sc_rxttime)
505                         break;  /* finished because timerq sorted by time */
506                 sc = nsc;
507                 inp = sc->sc_tp->t_inpcb;
508                 if (slot == SYNCACHE_MAXREXMTS ||
509                     slot >= tcp_syncache.rexmt_limit ||
510                     inp->inp_gencnt != sc->sc_inp_gencnt) {
511                         nsc = TAILQ_NEXT(sc, sc_timerq);
512                         syncache_drop(sc, NULL);
513                         tcpstat.tcps_sc_stale++;
514                         continue;
515                 }
516                 /*
517                  * syncache_respond() may call back into the syncache to
518                  * to modify another entry, so do not obtain the next
519                  * entry on the timer chain until it has completed.
520                  */
521                 syncache_respond(sc, NULL);
522                 nsc = TAILQ_NEXT(sc, sc_timerq);
523                 tcpstat.tcps_sc_retransmitted++;
524                 TAILQ_REMOVE(&syncache_percpu->timerq[slot], sc, sc_timerq);
525                 syncache_timeout(syncache_percpu, sc, slot + 1);
526         }
527         if (nsc != NULL)
528                 callout_reset(&syncache_percpu->tt_timerq[slot],
529                     nsc->sc_rxttime - ticks, syncache_timer,
530                     &syncache_percpu->mrec[slot]);
531         else
532                 callout_deactivate(&syncache_percpu->tt_timerq[slot]);
533
534         lwkt_replymsg(msg, 0);
535         return (EASYNC);
536 }
537
538 /*
539  * Find an entry in the syncache.
540  */
541 struct syncache *
542 syncache_lookup(inc, schp)
543         struct in_conninfo *inc;
544         struct syncache_head **schp;
545 {
546         struct tcp_syncache_percpu *syncache_percpu;
547         struct syncache *sc;
548         struct syncache_head *sch;
549
550         syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
551 #ifdef INET6
552         if (inc->inc_isipv6) {
553                 sch = &syncache_percpu->hashbase[
554                     SYNCACHE_HASH6(inc, tcp_syncache.hashmask)];
555                 *schp = sch;
556                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash)
557                         if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
558                                 return (sc);
559         } else
560 #endif
561         {
562                 sch = &syncache_percpu->hashbase[
563                     SYNCACHE_HASH(inc, tcp_syncache.hashmask)];
564                 *schp = sch;
565                 TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
566 #ifdef INET6
567                         if (sc->sc_inc.inc_isipv6)
568                                 continue;
569 #endif
570                         if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
571                                 return (sc);
572                 }
573         }
574         return (NULL);
575 }
576
577 /*
578  * This function is called when we get a RST for a
579  * non-existent connection, so that we can see if the
580  * connection is in the syn cache.  If it is, zap it.
581  */
582 void
583 syncache_chkrst(inc, th)
584         struct in_conninfo *inc;
585         struct tcphdr *th;
586 {
587         struct syncache *sc;
588         struct syncache_head *sch;
589
590         sc = syncache_lookup(inc, &sch);
591         if (sc == NULL)
592                 return;
593         /*
594          * If the RST bit is set, check the sequence number to see
595          * if this is a valid reset segment.
596          * RFC 793 page 37:
597          *   In all states except SYN-SENT, all reset (RST) segments
598          *   are validated by checking their SEQ-fields.  A reset is
599          *   valid if its sequence number is in the window.
600          *
601          *   The sequence number in the reset segment is normally an
602          *   echo of our outgoing acknowlegement numbers, but some hosts
603          *   send a reset with the sequence number at the rightmost edge
604          *   of our receive window, and we have to handle this case.
605          */
606         if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
607             SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
608                 syncache_drop(sc, sch);
609                 tcpstat.tcps_sc_reset++;
610         }
611 }
612
613 void
614 syncache_badack(inc)
615         struct in_conninfo *inc;
616 {
617         struct syncache *sc;
618         struct syncache_head *sch;
619
620         sc = syncache_lookup(inc, &sch);
621         if (sc != NULL) {
622                 syncache_drop(sc, sch);
623                 tcpstat.tcps_sc_badack++;
624         }
625 }
626
627 void
628 syncache_unreach(inc, th)
629         struct in_conninfo *inc;
630         struct tcphdr *th;
631 {
632         struct syncache *sc;
633         struct syncache_head *sch;
634
635         /* we are called at splnet() here */
636         sc = syncache_lookup(inc, &sch);
637         if (sc == NULL)
638                 return;
639
640         /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
641         if (ntohl(th->th_seq) != sc->sc_iss)
642                 return;
643
644         /*
645          * If we've rertransmitted 3 times and this is our second error,
646          * we remove the entry.  Otherwise, we allow it to continue on.
647          * This prevents us from incorrectly nuking an entry during a
648          * spurious network outage.
649          *
650          * See tcp_notify().
651          */
652         if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtslot < 3) {
653                 sc->sc_flags |= SCF_UNREACH;
654                 return;
655         }
656         syncache_drop(sc, sch);
657         tcpstat.tcps_sc_unreach++;
658 }
659
660 /*
661  * Build a new TCP socket structure from a syncache entry.
662  */
663 static struct socket *
664 syncache_socket(sc, lso)
665         struct syncache *sc;
666         struct socket *lso;
667 {
668         struct inpcb *inp = NULL;
669         struct socket *so;
670         struct tcpcb *tp;
671 #ifdef INET6
672         const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
673 #else
674         const boolean_t isipv6 = FALSE;
675 #endif
676
677         /*
678          * Ok, create the full blown connection, and set things up
679          * as they would have been set up if we had created the
680          * connection when the SYN arrived.  If we can't create
681          * the connection, abort it.
682          */
683         so = sonewconn(lso, SS_ISCONNECTED);
684         if (so == NULL) {
685                 /*
686                  * Drop the connection; we will send a RST if the peer
687                  * retransmits the ACK,
688                  */
689                 tcpstat.tcps_listendrop++;
690                 goto abort;
691         }
692
693         inp = sotoinpcb(so);
694
695         /*
696          * Insert new socket into hash list.
697          */
698         inp->inp_inc.inc_isipv6 = sc->sc_inc.inc_isipv6;
699         if (isipv6) {
700                 inp->in6p_laddr = sc->sc_inc.inc6_laddr;
701         } else {
702 #ifdef INET6
703                 inp->inp_vflag &= ~INP_IPV6;
704                 inp->inp_vflag |= INP_IPV4;
705 #endif
706                 inp->inp_laddr = sc->sc_inc.inc_laddr;
707         }
708         inp->inp_lport = sc->sc_inc.inc_lport;
709         if (in_pcbinsporthash(inp) != 0) {
710                 /*
711                  * Undo the assignments above if we failed to
712                  * put the PCB on the hash lists.
713                  */
714                 if (isipv6)
715                         inp->in6p_laddr = in6addr_any;
716                 else
717                         inp->inp_laddr.s_addr = INADDR_ANY;
718                 inp->inp_lport = 0;
719                 goto abort;
720         }
721 #ifdef IPSEC
722         /* copy old policy into new socket's */
723         if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
724                 printf("syncache_expand: could not copy policy\n");
725 #endif
726         if (isipv6) {
727                 struct inpcb *oinp = sotoinpcb(lso);
728                 struct in6_addr laddr6;
729                 struct sockaddr_in6 sin6;
730                 /*
731                  * Inherit socket options from the listening socket.
732                  * Note that in6p_inputopts are not (and should not be)
733                  * copied, since it stores previously received options and is
734                  * used to detect if each new option is different than the
735                  * previous one and hence should be passed to a user.
736                  * If we copied in6p_inputopts, a user would not be able to
737                  * receive options just after calling the accept system call.
738                  */
739                 inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
740                 if (oinp->in6p_outputopts)
741                         inp->in6p_outputopts =
742                             ip6_copypktopts(oinp->in6p_outputopts, M_INTWAIT);
743                 inp->in6p_route = sc->sc_route6;
744                 sc->sc_route6.ro_rt = NULL;
745
746                 sin6.sin6_family = AF_INET6;
747                 sin6.sin6_len = sizeof sin6;
748                 sin6.sin6_addr = sc->sc_inc.inc6_faddr;
749                 sin6.sin6_port = sc->sc_inc.inc_fport;
750                 sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
751                 laddr6 = inp->in6p_laddr;
752                 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
753                         inp->in6p_laddr = sc->sc_inc.inc6_laddr;
754                 if (in6_pcbconnect(inp, (struct sockaddr *)&sin6, &thread0)) {
755                         inp->in6p_laddr = laddr6;
756                         goto abort;
757                 }
758         } else {
759                 struct in_addr laddr;
760                 struct sockaddr_in sin;
761
762                 inp->inp_options = ip_srcroute();
763                 if (inp->inp_options == NULL) {
764                         inp->inp_options = sc->sc_ipopts;
765                         sc->sc_ipopts = NULL;
766                 }
767                 inp->inp_route = sc->sc_route;
768                 sc->sc_route.ro_rt = NULL;
769
770                 sin.sin_family = AF_INET;
771                 sin.sin_len = sizeof sin;
772                 sin.sin_addr = sc->sc_inc.inc_faddr;
773                 sin.sin_port = sc->sc_inc.inc_fport;
774                 bzero(sin.sin_zero, sizeof sin.sin_zero);
775                 laddr = inp->inp_laddr;
776                 if (inp->inp_laddr.s_addr == INADDR_ANY)
777                         inp->inp_laddr = sc->sc_inc.inc_laddr;
778                 if (in_pcbconnect(inp, (struct sockaddr *)&sin, &thread0)) {
779                         inp->inp_laddr = laddr;
780                         goto abort;
781                 }
782         }
783
784         tp = intotcpcb(inp);
785         tp->t_state = TCPS_SYN_RECEIVED;
786         tp->iss = sc->sc_iss;
787         tp->irs = sc->sc_irs;
788         tcp_rcvseqinit(tp);
789         tcp_sendseqinit(tp);
790         tp->snd_wl1 = sc->sc_irs;
791         tp->rcv_up = sc->sc_irs + 1;
792         tp->rcv_wnd = sc->sc_wnd;
793         tp->rcv_adv += tp->rcv_wnd;
794
795         tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH | TF_NODELAY);
796         if (sc->sc_flags & SCF_NOOPT)
797                 tp->t_flags |= TF_NOOPT;
798         if (sc->sc_flags & SCF_WINSCALE) {
799                 tp->t_flags |= TF_REQ_SCALE | TF_RCVD_SCALE;
800                 tp->requested_s_scale = sc->sc_requested_s_scale;
801                 tp->request_r_scale = sc->sc_request_r_scale;
802         }
803         if (sc->sc_flags & SCF_TIMESTAMP) {
804                 tp->t_flags |= TF_REQ_TSTMP | TF_RCVD_TSTMP;
805                 tp->ts_recent = sc->sc_tsrecent;
806                 tp->ts_recent_age = ticks;
807         }
808         if (sc->sc_flags & SCF_CC) {
809                 /*
810                  * Initialization of the tcpcb for transaction;
811                  *   set SND.WND = SEG.WND,
812                  *   initialize CCsend and CCrecv.
813                  */
814                 tp->t_flags |= TF_REQ_CC | TF_RCVD_CC;
815                 tp->cc_send = sc->sc_cc_send;
816                 tp->cc_recv = sc->sc_cc_recv;
817         }
818         if (sc->sc_flags & SCF_SACK_PERMITTED)
819                 tp->t_flags |= TF_SACK_PERMITTED;
820
821         tcp_mss(tp, sc->sc_peer_mss);
822
823         /*
824          * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
825          */
826         if (sc->sc_rxtslot != 0)
827                 tp->snd_cwnd = tp->t_maxseg;
828         callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
829
830         tcpstat.tcps_accepts++;
831         return (so);
832
833 abort:
834         if (so != NULL)
835                 soabort(so);
836         return (NULL);
837 }
838
839 /*
840  * This function gets called when we receive an ACK for a
841  * socket in the LISTEN state.  We look up the connection
842  * in the syncache, and if its there, we pull it out of
843  * the cache and turn it into a full-blown connection in
844  * the SYN-RECEIVED state.
845  */
846 int
847 syncache_expand(inc, th, sop, m)
848         struct in_conninfo *inc;
849         struct tcphdr *th;
850         struct socket **sop;
851         struct mbuf *m;
852 {
853         struct syncache *sc;
854         struct syncache_head *sch;
855         struct socket *so;
856
857         sc = syncache_lookup(inc, &sch);
858         if (sc == NULL) {
859                 /*
860                  * There is no syncache entry, so see if this ACK is
861                  * a returning syncookie.  To do this, first:
862                  *  A. See if this socket has had a syncache entry dropped in
863                  *     the past.  We don't want to accept a bogus syncookie
864                  *     if we've never received a SYN.
865                  *  B. check that the syncookie is valid.  If it is, then
866                  *     cobble up a fake syncache entry, and return.
867                  */
868                 if (!tcp_syncookies)
869                         return (0);
870                 sc = syncookie_lookup(inc, th, *sop);
871                 if (sc == NULL)
872                         return (0);
873                 sch = NULL;
874                 tcpstat.tcps_sc_recvcookie++;
875         }
876
877         /*
878          * If seg contains an ACK, but not for our SYN/ACK, send a RST.
879          */
880         if (th->th_ack != sc->sc_iss + 1)
881                 return (0);
882
883         so = syncache_socket(sc, *sop);
884         if (so == NULL) {
885 #if 0
886 resetandabort:
887                 /* XXXjlemon check this - is this correct? */
888                 tcp_respond(NULL, m, m, th,
889                     th->th_seq + tlen, (tcp_seq)0, TH_RST | TH_ACK);
890 #endif
891                 m_freem(m);                     /* XXX only needed for above */
892                 tcpstat.tcps_sc_aborted++;
893         } else {
894                 sc->sc_flags |= SCF_KEEPROUTE;
895                 tcpstat.tcps_sc_completed++;
896         }
897         if (sch == NULL)
898                 syncache_free(sc);
899         else
900                 syncache_drop(sc, sch);
901         *sop = so;
902         return (1);
903 }
904
905 /*
906  * Given a LISTEN socket and an inbound SYN request, add
907  * this to the syn cache, and send back a segment:
908  *      <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
909  * to the source.
910  *
911  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
912  * Doing so would require that we hold onto the data and deliver it
913  * to the application.  However, if we are the target of a SYN-flood
914  * DoS attack, an attacker could send data which would eventually
915  * consume all available buffer space if it were ACKed.  By not ACKing
916  * the data, we avoid this DoS scenario.
917  */
918 int
919 syncache_add(inc, to, th, sop, m)
920         struct in_conninfo *inc;
921         struct tcpopt *to;
922         struct tcphdr *th;
923         struct socket **sop;
924         struct mbuf *m;
925 {
926         struct tcp_syncache_percpu *syncache_percpu;
927         struct tcpcb *tp;
928         struct socket *so;
929         struct syncache *sc = NULL;
930         struct syncache_head *sch;
931         struct mbuf *ipopts = NULL;
932         struct rmxp_tao *taop;
933         int win;
934
935         syncache_percpu = &tcp_syncache_percpu[mycpu->gd_cpuid];
936         so = *sop;
937         tp = sototcpcb(so);
938
939         /*
940          * Remember the IP options, if any.
941          */
942 #ifdef INET6
943         if (!inc->inc_isipv6)
944 #endif
945                 ipopts = ip_srcroute();
946
947         /*
948          * See if we already have an entry for this connection.
949          * If we do, resend the SYN,ACK, and reset the retransmit timer.
950          *
951          * XXX
952          * The syncache should be re-initialized with the contents
953          * of the new SYN which may have different options.
954          */
955         sc = syncache_lookup(inc, &sch);
956         if (sc != NULL) {
957                 tcpstat.tcps_sc_dupsyn++;
958                 if (ipopts) {
959                         /*
960                          * If we were remembering a previous source route,
961                          * forget it and use the new one we've been given.
962                          */
963                         if (sc->sc_ipopts)
964                                 m_free(sc->sc_ipopts);
965                         sc->sc_ipopts = ipopts;
966                 }
967                 /*
968                  * Update timestamp if present.
969                  */
970                 if (sc->sc_flags & SCF_TIMESTAMP)
971                         sc->sc_tsrecent = to->to_tsval;
972
973                 /* Just update the TOF_SACK_PERMITTED for now. */
974                 if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
975                         sc->sc_flags |= SCF_SACK_PERMITTED;
976                 else
977                         sc->sc_flags &= ~SCF_SACK_PERMITTED;
978
979                 /*
980                  * PCB may have changed, pick up new values.
981                  */
982                 sc->sc_tp = tp;
983                 sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
984                 if (syncache_respond(sc, m) == 0) {
985                         TAILQ_REMOVE(&syncache_percpu->timerq[sc->sc_rxtslot],
986                             sc, sc_timerq);
987                         syncache_timeout(syncache_percpu, sc, sc->sc_rxtslot);
988                         tcpstat.tcps_sndacks++;
989                         tcpstat.tcps_sndtotal++;
990                 }
991                 *sop = NULL;
992                 return (1);
993         }
994
995         /*
996          * This allocation is guaranteed to succeed because we
997          * preallocate one more syncache entry than cache_limit.
998          */
999         sc = zalloc(tcp_syncache.zone);
1000
1001         /*
1002          * Fill in the syncache values.
1003          */
1004         sc->sc_tp = tp;
1005         sc->sc_inp_gencnt = tp->t_inpcb->inp_gencnt;
1006         sc->sc_ipopts = ipopts;
1007         sc->sc_inc.inc_fport = inc->inc_fport;
1008         sc->sc_inc.inc_lport = inc->inc_lport;
1009 #ifdef INET6
1010         sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1011         if (inc->inc_isipv6) {
1012                 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1013                 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1014                 sc->sc_route6.ro_rt = NULL;
1015         } else
1016 #endif
1017         {
1018                 sc->sc_inc.inc_faddr = inc->inc_faddr;
1019                 sc->sc_inc.inc_laddr = inc->inc_laddr;
1020                 sc->sc_route.ro_rt = NULL;
1021         }
1022         sc->sc_irs = th->th_seq;
1023         sc->sc_flags = 0;
1024         sc->sc_peer_mss = to->to_flags & TOF_MSS ? to->to_mss : 0;
1025         if (tcp_syncookies)
1026                 sc->sc_iss = syncookie_generate(sc);
1027         else
1028                 sc->sc_iss = arc4random();
1029
1030         /* Initial receive window: clip sbspace to [0 .. TCP_MAXWIN] */
1031         win = sbspace(&so->so_rcv);
1032         win = imax(win, 0);
1033         win = imin(win, TCP_MAXWIN);
1034         sc->sc_wnd = win;
1035
1036         if (tcp_do_rfc1323) {
1037                 /*
1038                  * A timestamp received in a SYN makes
1039                  * it ok to send timestamp requests and replies.
1040                  */
1041                 if (to->to_flags & TOF_TS) {
1042                         sc->sc_tsrecent = to->to_tsval;
1043                         sc->sc_flags |= SCF_TIMESTAMP;
1044                 }
1045                 if (to->to_flags & TOF_SCALE) {
1046                         int wscale = 0;
1047
1048                         /* Compute proper scaling value from buffer space */
1049                         while (wscale < TCP_MAX_WINSHIFT &&
1050                             (TCP_MAXWIN << wscale) < so->so_rcv.sb_hiwat)
1051                                 wscale++;
1052                         sc->sc_request_r_scale = wscale;
1053                         sc->sc_requested_s_scale = to->to_requested_s_scale;
1054                         sc->sc_flags |= SCF_WINSCALE;
1055                 }
1056         }
1057         if (tcp_do_rfc1644) {
1058                 /*
1059                  * A CC or CC.new option received in a SYN makes
1060                  * it ok to send CC in subsequent segments.
1061                  */
1062                 if (to->to_flags & (TOF_CC | TOF_CCNEW)) {
1063                         sc->sc_cc_recv = to->to_cc;
1064                         sc->sc_cc_send = CC_INC(tcp_ccgen);
1065                         sc->sc_flags |= SCF_CC;
1066                 }
1067         }
1068         if (tcp_do_sack && (to->to_flags & TOF_SACK_PERMITTED))
1069                 sc->sc_flags |= SCF_SACK_PERMITTED;
1070         if (tp->t_flags & TF_NOOPT)
1071                 sc->sc_flags = SCF_NOOPT;
1072
1073         /*
1074          * XXX
1075          * We have the option here of not doing TAO (even if the segment
1076          * qualifies) and instead fall back to a normal 3WHS via the syncache.
1077          * This allows us to apply synflood protection to TAO-qualifying SYNs
1078          * also. However, there should be a hueristic to determine when to
1079          * do this, and is not present at the moment.
1080          */
1081
1082         /*
1083          * Perform TAO test on incoming CC (SEG.CC) option, if any.
1084          * - compare SEG.CC against cached CC from the same host, if any.
1085          * - if SEG.CC > chached value, SYN must be new and is accepted
1086          *      immediately: save new CC in the cache, mark the socket
1087          *      connected, enter ESTABLISHED state, turn on flag to
1088          *      send a SYN in the next segment.
1089          *      A virtual advertised window is set in rcv_adv to
1090          *      initialize SWS prevention.  Then enter normal segment
1091          *      processing: drop SYN, process data and FIN.
1092          * - otherwise do a normal 3-way handshake.
1093          */
1094         taop = tcp_gettaocache(&sc->sc_inc);
1095         if (to->to_flags & TOF_CC) {
1096                 if ((tp->t_flags & TF_NOPUSH) &&
1097                     sc->sc_flags & SCF_CC &&
1098                     taop != NULL && taop->tao_cc != 0 &&
1099                     CC_GT(to->to_cc, taop->tao_cc)) {
1100                         sc->sc_rxtslot = 0;
1101                         so = syncache_socket(sc, *sop);
1102                         if (so != NULL) {
1103                                 sc->sc_flags |= SCF_KEEPROUTE;
1104                                 taop->tao_cc = to->to_cc;
1105                                 *sop = so;
1106                         }
1107                         syncache_free(sc);
1108                         return (so != NULL);
1109                 }
1110         } else {
1111                 /*
1112                  * No CC option, but maybe CC.NEW: invalidate cached value.
1113                  */
1114                 if (taop != NULL)
1115                         taop->tao_cc = 0;
1116         }
1117         /*
1118          * TAO test failed or there was no CC option,
1119          *    do a standard 3-way handshake.
1120          */
1121         if (syncache_respond(sc, m) == 0) {
1122                 syncache_insert(sc, sch);
1123                 tcpstat.tcps_sndacks++;
1124                 tcpstat.tcps_sndtotal++;
1125         } else {
1126                 syncache_free(sc);
1127                 tcpstat.tcps_sc_dropped++;
1128         }
1129         *sop = NULL;
1130         return (1);
1131 }
1132
1133 static int
1134 syncache_respond(sc, m)
1135         struct syncache *sc;
1136         struct mbuf *m;
1137 {
1138         u_int8_t *optp;
1139         int optlen, error;
1140         u_int16_t tlen, hlen, mssopt;
1141         struct ip *ip = NULL;
1142         struct rtentry *rt;
1143         struct tcphdr *th;
1144         struct ip6_hdr *ip6 = NULL;
1145 #ifdef INET6
1146         const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1147 #else
1148         const boolean_t isipv6 = FALSE;
1149 #endif
1150
1151         if (isipv6) {
1152                 rt = tcp_rtlookup6(&sc->sc_inc);
1153                 if (rt != NULL)
1154                         mssopt = rt->rt_ifp->if_mtu -
1155                              (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
1156                 else
1157                         mssopt = tcp_v6mssdflt;
1158                 hlen = sizeof(struct ip6_hdr);
1159         } else {
1160                 rt = tcp_rtlookup(&sc->sc_inc);
1161                 if (rt != NULL)
1162                         mssopt = rt->rt_ifp->if_mtu -
1163                              (sizeof(struct ip) + sizeof(struct tcphdr));
1164                 else
1165                         mssopt = tcp_mssdflt;
1166                 hlen = sizeof(struct ip);
1167         }
1168
1169         /* Compute the size of the TCP options. */
1170         if (sc->sc_flags & SCF_NOOPT) {
1171                 optlen = 0;
1172         } else {
1173                 optlen = TCPOLEN_MAXSEG +
1174                     ((sc->sc_flags & SCF_WINSCALE) ? 4 : 0) +
1175                     ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0) +
1176                     ((sc->sc_flags & SCF_CC) ? TCPOLEN_CC_APPA * 2 : 0) +
1177                     ((sc->sc_flags & SCF_SACK_PERMITTED) ?
1178                         TCPOLEN_SACK_PERMITTED_ALIGNED : 0);
1179         }
1180         tlen = hlen + sizeof(struct tcphdr) + optlen;
1181
1182         /*
1183          * XXX
1184          * assume that the entire packet will fit in a header mbuf
1185          */
1186         KASSERT(max_linkhdr + tlen <= MHLEN, ("syncache: mbuf too small"));
1187
1188         /*
1189          * XXX shouldn't this reuse the mbuf if possible ?
1190          * Create the IP+TCP header from scratch.
1191          */
1192         if (m)
1193                 m_freem(m);
1194
1195         m = m_gethdr(MB_DONTWAIT, MT_HEADER);
1196         if (m == NULL)
1197                 return (ENOBUFS);
1198         m->m_data += max_linkhdr;
1199         m->m_len = tlen;
1200         m->m_pkthdr.len = tlen;
1201         m->m_pkthdr.rcvif = NULL;
1202
1203         if (isipv6) {
1204                 ip6 = mtod(m, struct ip6_hdr *);
1205                 ip6->ip6_vfc = IPV6_VERSION;
1206                 ip6->ip6_nxt = IPPROTO_TCP;
1207                 ip6->ip6_src = sc->sc_inc.inc6_laddr;
1208                 ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1209                 ip6->ip6_plen = htons(tlen - hlen);
1210                 /* ip6_hlim is set after checksum */
1211                 /* ip6_flow = ??? */
1212
1213                 th = (struct tcphdr *)(ip6 + 1);
1214         } else {
1215                 ip = mtod(m, struct ip *);
1216                 ip->ip_v = IPVERSION;
1217                 ip->ip_hl = sizeof(struct ip) >> 2;
1218                 ip->ip_len = tlen;
1219                 ip->ip_id = 0;
1220                 ip->ip_off = 0;
1221                 ip->ip_sum = 0;
1222                 ip->ip_p = IPPROTO_TCP;
1223                 ip->ip_src = sc->sc_inc.inc_laddr;
1224                 ip->ip_dst = sc->sc_inc.inc_faddr;
1225                 ip->ip_ttl = sc->sc_tp->t_inpcb->inp_ip_ttl;   /* XXX */
1226                 ip->ip_tos = sc->sc_tp->t_inpcb->inp_ip_tos;   /* XXX */
1227
1228                 /*
1229                  * See if we should do MTU discovery.  Route lookups are
1230                  * expensive, so we will only unset the DF bit if:
1231                  *
1232                  *      1) path_mtu_discovery is disabled
1233                  *      2) the SCF_UNREACH flag has been set
1234                  */
1235                 if (path_mtu_discovery
1236                     && ((sc->sc_flags & SCF_UNREACH) == 0)) {
1237                        ip->ip_off |= IP_DF;
1238                 }
1239
1240                 th = (struct tcphdr *)(ip + 1);
1241         }
1242         th->th_sport = sc->sc_inc.inc_lport;
1243         th->th_dport = sc->sc_inc.inc_fport;
1244
1245         th->th_seq = htonl(sc->sc_iss);
1246         th->th_ack = htonl(sc->sc_irs + 1);
1247         th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1248         th->th_x2 = 0;
1249         th->th_flags = TH_SYN | TH_ACK;
1250         th->th_win = htons(sc->sc_wnd);
1251         th->th_urp = 0;
1252
1253         /* Tack on the TCP options. */
1254         if (optlen == 0)
1255                 goto no_options;
1256         optp = (u_int8_t *)(th + 1);
1257         *optp++ = TCPOPT_MAXSEG;
1258         *optp++ = TCPOLEN_MAXSEG;
1259         *optp++ = (mssopt >> 8) & 0xff;
1260         *optp++ = mssopt & 0xff;
1261
1262         if (sc->sc_flags & SCF_WINSCALE) {
1263                 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
1264                     TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
1265                     sc->sc_request_r_scale);
1266                 optp += 4;
1267         }
1268
1269         if (sc->sc_flags & SCF_TIMESTAMP) {
1270                 u_int32_t *lp = (u_int32_t *)(optp);
1271
1272                 /* Form timestamp option as shown in appendix A of RFC 1323. */
1273                 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
1274                 *lp++ = htonl(ticks);
1275                 *lp   = htonl(sc->sc_tsrecent);
1276                 optp += TCPOLEN_TSTAMP_APPA;
1277         }
1278
1279         /*
1280          * Send CC and CC.echo if we received CC from our peer.
1281          */
1282         if (sc->sc_flags & SCF_CC) {
1283                 u_int32_t *lp = (u_int32_t *)(optp);
1284
1285                 *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1286                 *lp++ = htonl(sc->sc_cc_send);
1287                 *lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CCECHO));
1288                 *lp   = htonl(sc->sc_cc_recv);
1289                 optp += TCPOLEN_CC_APPA * 2;
1290         }
1291
1292         if (sc->sc_flags & SCF_SACK_PERMITTED) {
1293                 *((u_int32_t *)optp) = htonl(TCPOPT_SACK_PERMITTED_ALIGNED);
1294                 optp += TCPOLEN_SACK_PERMITTED_ALIGNED;
1295         }
1296
1297 no_options:
1298         if (isipv6) {
1299                 struct route_in6 *ro6 = &sc->sc_route6;
1300
1301                 th->th_sum = 0;
1302                 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
1303                 ip6->ip6_hlim = in6_selecthlim(NULL,
1304                     ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
1305                 error = ip6_output(m, NULL, ro6, 0, NULL, NULL,
1306                                 sc->sc_tp->t_inpcb);
1307         } else {
1308                 th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1309                                        htons(tlen - hlen + IPPROTO_TCP));
1310                 m->m_pkthdr.csum_flags = CSUM_TCP;
1311                 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1312                 error = ip_output(m, sc->sc_ipopts, &sc->sc_route, 0, NULL,
1313                                 sc->sc_tp->t_inpcb);
1314         }
1315         return (error);
1316 }
1317
1318 /*
1319  * cookie layers:
1320  *
1321  *      |. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .|
1322  *      | peer iss                                                      |
1323  *      | MD5(laddr,faddr,secret,lport,fport)             |. . . . . . .|
1324  *      |                     0                       |(A)|             |
1325  * (A): peer mss index
1326  */
1327
1328 /*
1329  * The values below are chosen to minimize the size of the tcp_secret
1330  * table, as well as providing roughly a 16 second lifetime for the cookie.
1331  */
1332
1333 #define SYNCOOKIE_WNDBITS       5       /* exposed bits for window indexing */
1334 #define SYNCOOKIE_TIMESHIFT     1       /* scale ticks to window time units */
1335
1336 #define SYNCOOKIE_WNDMASK       ((1 << SYNCOOKIE_WNDBITS) - 1)
1337 #define SYNCOOKIE_NSECRETS      (1 << SYNCOOKIE_WNDBITS)
1338 #define SYNCOOKIE_TIMEOUT \
1339     (hz * (1 << SYNCOOKIE_WNDBITS) / (1 << SYNCOOKIE_TIMESHIFT))
1340 #define SYNCOOKIE_DATAMASK      ((3 << SYNCOOKIE_WNDBITS) | SYNCOOKIE_WNDMASK)
1341
1342 static struct {
1343         u_int32_t       ts_secbits[4];
1344         u_int           ts_expire;
1345 } tcp_secret[SYNCOOKIE_NSECRETS];
1346
1347 static int tcp_msstab[] = { 0, 536, 1460, 8960 };
1348
1349 static MD5_CTX syn_ctx;
1350
1351 #define MD5Add(v)       MD5Update(&syn_ctx, (u_char *)&v, sizeof(v))
1352
1353 struct md5_add {
1354         u_int32_t laddr, faddr;
1355         u_int32_t secbits[4];
1356         u_int16_t lport, fport;
1357 };
1358
1359 #ifdef CTASSERT
1360 CTASSERT(sizeof(struct md5_add) == 28);
1361 #endif
1362
1363 /*
1364  * Consider the problem of a recreated (and retransmitted) cookie.  If the
1365  * original SYN was accepted, the connection is established.  The second
1366  * SYN is inflight, and if it arrives with an ISN that falls within the
1367  * receive window, the connection is killed.
1368  *
1369  * However, since cookies have other problems, this may not be worth
1370  * worrying about.
1371  */
1372
1373 static u_int32_t
1374 syncookie_generate(struct syncache *sc)
1375 {
1376         u_int32_t md5_buffer[4];
1377         u_int32_t data;
1378         int idx, i;
1379         struct md5_add add;
1380 #ifdef INET6
1381         const boolean_t isipv6 = sc->sc_inc.inc_isipv6;
1382 #else
1383         const boolean_t isipv6 = FALSE;
1384 #endif
1385
1386         idx = ((ticks << SYNCOOKIE_TIMESHIFT) / hz) & SYNCOOKIE_WNDMASK;
1387         if (tcp_secret[idx].ts_expire < ticks) {
1388                 for (i = 0; i < 4; i++)
1389                         tcp_secret[idx].ts_secbits[i] = arc4random();
1390                 tcp_secret[idx].ts_expire = ticks + SYNCOOKIE_TIMEOUT;
1391         }
1392         for (data = sizeof(tcp_msstab) / sizeof(int) - 1; data > 0; data--)
1393                 if (tcp_msstab[data] <= sc->sc_peer_mss)
1394                         break;
1395         data = (data << SYNCOOKIE_WNDBITS) | idx;
1396         data ^= sc->sc_irs;                             /* peer's iss */
1397         MD5Init(&syn_ctx);
1398         if (isipv6) {
1399                 MD5Add(sc->sc_inc.inc6_laddr);
1400                 MD5Add(sc->sc_inc.inc6_faddr);
1401                 add.laddr = 0;
1402                 add.faddr = 0;
1403         } else {
1404                 add.laddr = sc->sc_inc.inc_laddr.s_addr;
1405                 add.faddr = sc->sc_inc.inc_faddr.s_addr;
1406         }
1407         add.lport = sc->sc_inc.inc_lport;
1408         add.fport = sc->sc_inc.inc_fport;
1409         add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1410         add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1411         add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1412         add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1413         MD5Add(add);
1414         MD5Final((u_char *)&md5_buffer, &syn_ctx);
1415         data ^= (md5_buffer[0] & ~SYNCOOKIE_WNDMASK);
1416         return (data);
1417 }
1418
1419 static struct syncache *
1420 syncookie_lookup(inc, th, so)
1421         struct in_conninfo *inc;
1422         struct tcphdr *th;
1423         struct socket *so;
1424 {
1425         u_int32_t md5_buffer[4];
1426         struct syncache *sc;
1427         u_int32_t data;
1428         int wnd, idx;
1429         struct md5_add add;
1430
1431         data = (th->th_ack - 1) ^ (th->th_seq - 1);     /* remove ISS */
1432         idx = data & SYNCOOKIE_WNDMASK;
1433         if (tcp_secret[idx].ts_expire < ticks ||
1434             sototcpcb(so)->ts_recent + SYNCOOKIE_TIMEOUT < ticks)
1435                 return (NULL);
1436         MD5Init(&syn_ctx);
1437 #ifdef INET6
1438         if (inc->inc_isipv6) {
1439                 MD5Add(inc->inc6_laddr);
1440                 MD5Add(inc->inc6_faddr);
1441                 add.laddr = 0;
1442                 add.faddr = 0;
1443         } else
1444 #endif
1445         {
1446                 add.laddr = inc->inc_laddr.s_addr;
1447                 add.faddr = inc->inc_faddr.s_addr;
1448         }
1449         add.lport = inc->inc_lport;
1450         add.fport = inc->inc_fport;
1451         add.secbits[0] = tcp_secret[idx].ts_secbits[0];
1452         add.secbits[1] = tcp_secret[idx].ts_secbits[1];
1453         add.secbits[2] = tcp_secret[idx].ts_secbits[2];
1454         add.secbits[3] = tcp_secret[idx].ts_secbits[3];
1455         MD5Add(add);
1456         MD5Final((u_char *)&md5_buffer, &syn_ctx);
1457         data ^= md5_buffer[0];
1458         if (data & ~SYNCOOKIE_DATAMASK)
1459                 return (NULL);
1460         data = data >> SYNCOOKIE_WNDBITS;
1461
1462         /*
1463          * This allocation is guaranteed to succeed because we
1464          * preallocate one more syncache entry than cache_limit.
1465          */
1466         sc = zalloc(tcp_syncache.zone);
1467
1468         /*
1469          * Fill in the syncache values.
1470          * XXX duplicate code from syncache_add
1471          */
1472         sc->sc_ipopts = NULL;
1473         sc->sc_inc.inc_fport = inc->inc_fport;
1474         sc->sc_inc.inc_lport = inc->inc_lport;
1475 #ifdef INET6
1476         sc->sc_inc.inc_isipv6 = inc->inc_isipv6;
1477         if (inc->inc_isipv6) {
1478                 sc->sc_inc.inc6_faddr = inc->inc6_faddr;
1479                 sc->sc_inc.inc6_laddr = inc->inc6_laddr;
1480                 sc->sc_route6.ro_rt = NULL;
1481         } else
1482 #endif
1483         {
1484                 sc->sc_inc.inc_faddr = inc->inc_faddr;
1485                 sc->sc_inc.inc_laddr = inc->inc_laddr;
1486                 sc->sc_route.ro_rt = NULL;
1487         }
1488         sc->sc_irs = th->th_seq - 1;
1489         sc->sc_iss = th->th_ack - 1;
1490         wnd = sbspace(&so->so_rcv);
1491         wnd = imax(wnd, 0);
1492         wnd = imin(wnd, TCP_MAXWIN);
1493         sc->sc_wnd = wnd;
1494         sc->sc_flags = 0;
1495         sc->sc_rxtslot = 0;
1496         sc->sc_peer_mss = tcp_msstab[data];
1497         return (sc);
1498 }