tcp_syncache.c revision 193731
1/*-
2 * Copyright (c) 2001 McAfee, Inc.
3 * Copyright (c) 2006 Andre Oppermann, Internet Business Solutions AG
4 * All rights reserved.
5 *
6 * This software was developed for the FreeBSD Project by Jonathan Lemon
7 * and McAfee Research, the Security Research Division of McAfee, Inc. under
8 * DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the
9 * DARPA CHATS research program.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33#include <sys/cdefs.h>
34__FBSDID("$FreeBSD: head/sys/netinet/tcp_syncache.c 193731 2009-06-08 17:15:40Z zec $");
35
36#include "opt_inet.h"
37#include "opt_inet6.h"
38#include "opt_ipsec.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/kernel.h>
43#include <sys/sysctl.h>
44#include <sys/limits.h>
45#include <sys/lock.h>
46#include <sys/mutex.h>
47#include <sys/malloc.h>
48#include <sys/mbuf.h>
49#include <sys/md5.h>
50#include <sys/proc.h>		/* for proc0 declaration */
51#include <sys/random.h>
52#include <sys/socket.h>
53#include <sys/socketvar.h>
54#include <sys/syslog.h>
55#include <sys/ucred.h>
56#include <sys/vimage.h>
57
58#include <vm/uma.h>
59
60#include <net/if.h>
61#include <net/route.h>
62
63#include <netinet/in.h>
64#include <netinet/in_systm.h>
65#include <netinet/ip.h>
66#include <netinet/in_var.h>
67#include <netinet/in_pcb.h>
68#include <netinet/ip_var.h>
69#include <netinet/ip_options.h>
70#ifdef INET6
71#include <netinet/ip6.h>
72#include <netinet/icmp6.h>
73#include <netinet6/nd6.h>
74#include <netinet6/ip6_var.h>
75#include <netinet6/in6_pcb.h>
76#endif
77#include <netinet/tcp.h>
78#include <netinet/tcp_fsm.h>
79#include <netinet/tcp_seq.h>
80#include <netinet/tcp_timer.h>
81#include <netinet/tcp_var.h>
82#include <netinet/tcp_syncache.h>
83#include <netinet/tcp_offload.h>
84#ifdef INET6
85#include <netinet6/tcp6_var.h>
86#endif
87#include <netinet/vinet.h>
88
89#ifdef IPSEC
90#include <netipsec/ipsec.h>
91#ifdef INET6
92#include <netipsec/ipsec6.h>
93#endif
94#include <netipsec/key.h>
95#endif /*IPSEC*/
96
97#include <machine/in_cksum.h>
98
99#include <security/mac/mac_framework.h>
100
101#ifdef VIMAGE_GLOBALS
102static struct tcp_syncache tcp_syncache;
103static int tcp_syncookies;
104static int tcp_syncookiesonly;
105int tcp_sc_rst_sock_fail;
106#endif
107
108SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, syncookies,
109    CTLFLAG_RW, tcp_syncookies, 0,
110    "Use TCP SYN cookies if the syncache overflows");
111
112SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp, OID_AUTO, syncookies_only,
113    CTLFLAG_RW, tcp_syncookiesonly, 0,
114    "Use only TCP SYN cookies");
115
116#ifdef TCP_OFFLOAD_DISABLE
117#define TOEPCB_ISSET(sc) (0)
118#else
119#define TOEPCB_ISSET(sc) ((sc)->sc_toepcb != NULL)
120#endif
121
122static void	 syncache_drop(struct syncache *, struct syncache_head *);
123static void	 syncache_free(struct syncache *);
124static void	 syncache_insert(struct syncache *, struct syncache_head *);
125struct syncache *syncache_lookup(struct in_conninfo *, struct syncache_head **);
126static int	 syncache_respond(struct syncache *);
127static struct	 socket *syncache_socket(struct syncache *, struct socket *,
128		    struct mbuf *m);
129static void	 syncache_timeout(struct syncache *sc, struct syncache_head *sch,
130		    int docallout);
131static void	 syncache_timer(void *);
132static void	 syncookie_generate(struct syncache_head *, struct syncache *,
133		    u_int32_t *);
134static struct syncache
135		*syncookie_lookup(struct in_conninfo *, struct syncache_head *,
136		    struct syncache *, struct tcpopt *, struct tcphdr *,
137		    struct socket *);
138
139/*
140 * Transmit the SYN,ACK fewer times than TCP_MAXRXTSHIFT specifies.
141 * 3 retransmits corresponds to a timeout of 3 * (1 + 2 + 4 + 8) == 45 seconds,
142 * the odds are that the user has given up attempting to connect by then.
143 */
144#define SYNCACHE_MAXREXMTS		3
145
146/* Arbitrary values */
147#define TCP_SYNCACHE_HASHSIZE		512
148#define TCP_SYNCACHE_BUCKETLIMIT	30
149
150SYSCTL_NODE(_net_inet_tcp, OID_AUTO, syncache, CTLFLAG_RW, 0, "TCP SYN cache");
151
152SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
153    bucketlimit, CTLFLAG_RDTUN,
154    tcp_syncache.bucket_limit, 0, "Per-bucket hash limit for syncache");
155
156SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
157    cachelimit, CTLFLAG_RDTUN,
158    tcp_syncache.cache_limit, 0, "Overall entry limit for syncache");
159
160SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
161    count, CTLFLAG_RD,
162    tcp_syncache.cache_count, 0, "Current number of entries in syncache");
163
164SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
165    hashsize, CTLFLAG_RDTUN,
166    tcp_syncache.hashsize, 0, "Size of TCP syncache hashtable");
167
168SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
169    rexmtlimit, CTLFLAG_RW,
170    tcp_syncache.rexmt_limit, 0, "Limit on SYN/ACK retransmissions");
171
172SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_tcp_syncache, OID_AUTO,
173     rst_on_sock_fail, CTLFLAG_RW,
174     tcp_sc_rst_sock_fail, 0, "Send reset on socket allocation failure");
175
176static MALLOC_DEFINE(M_SYNCACHE, "syncache", "TCP syncache");
177
178#define SYNCACHE_HASH(inc, mask)					\
179	((V_tcp_syncache.hash_secret ^					\
180	  (inc)->inc_faddr.s_addr ^					\
181	  ((inc)->inc_faddr.s_addr >> 16) ^				\
182	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
183
184#define SYNCACHE_HASH6(inc, mask)					\
185	((V_tcp_syncache.hash_secret ^					\
186	  (inc)->inc6_faddr.s6_addr32[0] ^				\
187	  (inc)->inc6_faddr.s6_addr32[3] ^				\
188	  (inc)->inc_fport ^ (inc)->inc_lport) & mask)
189
190#define ENDPTS_EQ(a, b) (						\
191	(a)->ie_fport == (b)->ie_fport &&				\
192	(a)->ie_lport == (b)->ie_lport &&				\
193	(a)->ie_faddr.s_addr == (b)->ie_faddr.s_addr &&			\
194	(a)->ie_laddr.s_addr == (b)->ie_laddr.s_addr			\
195)
196
197#define ENDPTS6_EQ(a, b) (memcmp(a, b, sizeof(*a)) == 0)
198
199#define	SCH_LOCK(sch)		mtx_lock(&(sch)->sch_mtx)
200#define	SCH_UNLOCK(sch)		mtx_unlock(&(sch)->sch_mtx)
201#define	SCH_LOCK_ASSERT(sch)	mtx_assert(&(sch)->sch_mtx, MA_OWNED)
202
203/*
204 * Requires the syncache entry to be already removed from the bucket list.
205 */
206static void
207syncache_free(struct syncache *sc)
208{
209	INIT_VNET_INET(curvnet);
210
211	if (sc->sc_ipopts)
212		(void) m_free(sc->sc_ipopts);
213	if (sc->sc_cred)
214		crfree(sc->sc_cred);
215#ifdef MAC
216	mac_syncache_destroy(&sc->sc_label);
217#endif
218
219	uma_zfree(V_tcp_syncache.zone, sc);
220}
221
222void
223syncache_init(void)
224{
225	INIT_VNET_INET(curvnet);
226	int i;
227
228	V_tcp_syncookies = 1;
229	V_tcp_syncookiesonly = 0;
230	V_tcp_sc_rst_sock_fail = 1;
231
232	V_tcp_syncache.cache_count = 0;
233	V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
234	V_tcp_syncache.bucket_limit = TCP_SYNCACHE_BUCKETLIMIT;
235	V_tcp_syncache.rexmt_limit = SYNCACHE_MAXREXMTS;
236	V_tcp_syncache.hash_secret = arc4random();
237
238	TUNABLE_INT_FETCH("net.inet.tcp.syncache.hashsize",
239	    &V_tcp_syncache.hashsize);
240	TUNABLE_INT_FETCH("net.inet.tcp.syncache.bucketlimit",
241	    &V_tcp_syncache.bucket_limit);
242	if (!powerof2(V_tcp_syncache.hashsize) ||
243	    V_tcp_syncache.hashsize == 0) {
244		printf("WARNING: syncache hash size is not a power of 2.\n");
245		V_tcp_syncache.hashsize = TCP_SYNCACHE_HASHSIZE;
246	}
247	V_tcp_syncache.hashmask = V_tcp_syncache.hashsize - 1;
248
249	/* Set limits. */
250	V_tcp_syncache.cache_limit =
251	    V_tcp_syncache.hashsize * V_tcp_syncache.bucket_limit;
252	TUNABLE_INT_FETCH("net.inet.tcp.syncache.cachelimit",
253	    &V_tcp_syncache.cache_limit);
254
255	/* Allocate the hash table. */
256	V_tcp_syncache.hashbase = malloc(V_tcp_syncache.hashsize *
257	    sizeof(struct syncache_head), M_SYNCACHE, M_WAITOK | M_ZERO);
258
259	/* Initialize the hash buckets. */
260	for (i = 0; i < V_tcp_syncache.hashsize; i++) {
261#ifdef VIMAGE
262		V_tcp_syncache.hashbase[i].sch_vnet = curvnet;
263#endif
264		TAILQ_INIT(&V_tcp_syncache.hashbase[i].sch_bucket);
265		mtx_init(&V_tcp_syncache.hashbase[i].sch_mtx, "tcp_sc_head",
266			 NULL, MTX_DEF);
267		callout_init_mtx(&V_tcp_syncache.hashbase[i].sch_timer,
268			 &V_tcp_syncache.hashbase[i].sch_mtx, 0);
269		V_tcp_syncache.hashbase[i].sch_length = 0;
270	}
271
272	/* Create the syncache entry zone. */
273	V_tcp_syncache.zone = uma_zcreate("syncache", sizeof(struct syncache),
274	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
275	uma_zone_set_max(V_tcp_syncache.zone, V_tcp_syncache.cache_limit);
276}
277
278#ifdef VIMAGE
279void
280syncache_destroy(void)
281{
282	INIT_VNET_INET(curvnet);
283
284	/* XXX walk the cache, free remaining objects, stop timers */
285
286	uma_zdestroy(V_tcp_syncache.zone);
287	FREE(V_tcp_syncache.hashbase, M_SYNCACHE);
288}
289#endif
290
291/*
292 * Inserts a syncache entry into the specified bucket row.
293 * Locks and unlocks the syncache_head autonomously.
294 */
295static void
296syncache_insert(struct syncache *sc, struct syncache_head *sch)
297{
298	INIT_VNET_INET(sch->sch_vnet);
299	struct syncache *sc2;
300
301	SCH_LOCK(sch);
302
303	/*
304	 * Make sure that we don't overflow the per-bucket limit.
305	 * If the bucket is full, toss the oldest element.
306	 */
307	if (sch->sch_length >= V_tcp_syncache.bucket_limit) {
308		KASSERT(!TAILQ_EMPTY(&sch->sch_bucket),
309			("sch->sch_length incorrect"));
310		sc2 = TAILQ_LAST(&sch->sch_bucket, sch_head);
311		syncache_drop(sc2, sch);
312		TCPSTAT_INC(tcps_sc_bucketoverflow);
313	}
314
315	/* Put it into the bucket. */
316	TAILQ_INSERT_HEAD(&sch->sch_bucket, sc, sc_hash);
317	sch->sch_length++;
318
319	/* Reinitialize the bucket row's timer. */
320	if (sch->sch_length == 1)
321		sch->sch_nextc = ticks + INT_MAX;
322	syncache_timeout(sc, sch, 1);
323
324	SCH_UNLOCK(sch);
325
326	V_tcp_syncache.cache_count++;
327	TCPSTAT_INC(tcps_sc_added);
328}
329
330/*
331 * Remove and free entry from syncache bucket row.
332 * Expects locked syncache head.
333 */
334static void
335syncache_drop(struct syncache *sc, struct syncache_head *sch)
336{
337	INIT_VNET_INET(sch->sch_vnet);
338
339	SCH_LOCK_ASSERT(sch);
340
341	TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
342	sch->sch_length--;
343
344#ifndef TCP_OFFLOAD_DISABLE
345	if (sc->sc_tu)
346		sc->sc_tu->tu_syncache_event(TOE_SC_DROP, sc->sc_toepcb);
347#endif
348	syncache_free(sc);
349	V_tcp_syncache.cache_count--;
350}
351
352/*
353 * Engage/reengage time on bucket row.
354 */
355static void
356syncache_timeout(struct syncache *sc, struct syncache_head *sch, int docallout)
357{
358	sc->sc_rxttime = ticks +
359		TCPTV_RTOBASE * (tcp_backoff[sc->sc_rxmits]);
360	sc->sc_rxmits++;
361	if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc)) {
362		sch->sch_nextc = sc->sc_rxttime;
363		if (docallout)
364			callout_reset(&sch->sch_timer, sch->sch_nextc - ticks,
365			    syncache_timer, (void *)sch);
366	}
367}
368
369/*
370 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
371 * If we have retransmitted an entry the maximum number of times, expire it.
372 * One separate timer for each bucket row.
373 */
374static void
375syncache_timer(void *xsch)
376{
377	struct syncache_head *sch = (struct syncache_head *)xsch;
378	struct syncache *sc, *nsc;
379	int tick = ticks;
380	char *s;
381
382	CURVNET_SET(sch->sch_vnet);
383	INIT_VNET_INET(sch->sch_vnet);
384
385	/* NB: syncache_head has already been locked by the callout. */
386	SCH_LOCK_ASSERT(sch);
387
388	/*
389	 * In the following cycle we may remove some entries and/or
390	 * advance some timeouts, so re-initialize the bucket timer.
391	 */
392	sch->sch_nextc = tick + INT_MAX;
393
394	TAILQ_FOREACH_SAFE(sc, &sch->sch_bucket, sc_hash, nsc) {
395		/*
396		 * We do not check if the listen socket still exists
397		 * and accept the case where the listen socket may be
398		 * gone by the time we resend the SYN/ACK.  We do
399		 * not expect this to happens often. If it does,
400		 * then the RST will be sent by the time the remote
401		 * host does the SYN/ACK->ACK.
402		 */
403		if (TSTMP_GT(sc->sc_rxttime, tick)) {
404			if (TSTMP_LT(sc->sc_rxttime, sch->sch_nextc))
405				sch->sch_nextc = sc->sc_rxttime;
406			continue;
407		}
408		if (sc->sc_rxmits > V_tcp_syncache.rexmt_limit) {
409			if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
410				log(LOG_DEBUG, "%s; %s: Retransmits exhausted, "
411				    "giving up and removing syncache entry\n",
412				    s, __func__);
413				free(s, M_TCPLOG);
414			}
415			syncache_drop(sc, sch);
416			TCPSTAT_INC(tcps_sc_stale);
417			continue;
418		}
419		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
420			log(LOG_DEBUG, "%s; %s: Response timeout, "
421			    "retransmitting (%u) SYN|ACK\n",
422			    s, __func__, sc->sc_rxmits);
423			free(s, M_TCPLOG);
424		}
425
426		(void) syncache_respond(sc);
427		TCPSTAT_INC(tcps_sc_retransmitted);
428		syncache_timeout(sc, sch, 0);
429	}
430	if (!TAILQ_EMPTY(&(sch)->sch_bucket))
431		callout_reset(&(sch)->sch_timer, (sch)->sch_nextc - tick,
432			syncache_timer, (void *)(sch));
433	CURVNET_RESTORE();
434}
435
436/*
437 * Find an entry in the syncache.
438 * Returns always with locked syncache_head plus a matching entry or NULL.
439 */
440struct syncache *
441syncache_lookup(struct in_conninfo *inc, struct syncache_head **schp)
442{
443	INIT_VNET_INET(curvnet);
444	struct syncache *sc;
445	struct syncache_head *sch;
446
447#ifdef INET6
448	if (inc->inc_flags & INC_ISIPV6) {
449		sch = &V_tcp_syncache.hashbase[
450		    SYNCACHE_HASH6(inc, V_tcp_syncache.hashmask)];
451		*schp = sch;
452
453		SCH_LOCK(sch);
454
455		/* Circle through bucket row to find matching entry. */
456		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
457			if (ENDPTS6_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
458				return (sc);
459		}
460	} else
461#endif
462	{
463		sch = &V_tcp_syncache.hashbase[
464		    SYNCACHE_HASH(inc, V_tcp_syncache.hashmask)];
465		*schp = sch;
466
467		SCH_LOCK(sch);
468
469		/* Circle through bucket row to find matching entry. */
470		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
471#ifdef INET6
472			if (sc->sc_inc.inc_flags & INC_ISIPV6)
473				continue;
474#endif
475			if (ENDPTS_EQ(&inc->inc_ie, &sc->sc_inc.inc_ie))
476				return (sc);
477		}
478	}
479	SCH_LOCK_ASSERT(*schp);
480	return (NULL);			/* always returns with locked sch */
481}
482
483/*
484 * This function is called when we get a RST for a
485 * non-existent connection, so that we can see if the
486 * connection is in the syn cache.  If it is, zap it.
487 */
488void
489syncache_chkrst(struct in_conninfo *inc, struct tcphdr *th)
490{
491	INIT_VNET_INET(curvnet);
492	struct syncache *sc;
493	struct syncache_head *sch;
494	char *s = NULL;
495
496	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
497	SCH_LOCK_ASSERT(sch);
498
499	/*
500	 * Any RST to our SYN|ACK must not carry ACK, SYN or FIN flags.
501	 * See RFC 793 page 65, section SEGMENT ARRIVES.
502	 */
503	if (th->th_flags & (TH_ACK|TH_SYN|TH_FIN)) {
504		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
505			log(LOG_DEBUG, "%s; %s: Spurious RST with ACK, SYN or "
506			    "FIN flag set, segment ignored\n", s, __func__);
507		TCPSTAT_INC(tcps_badrst);
508		goto done;
509	}
510
511	/*
512	 * No corresponding connection was found in syncache.
513	 * If syncookies are enabled and possibly exclusively
514	 * used, or we are under memory pressure, a valid RST
515	 * may not find a syncache entry.  In that case we're
516	 * done and no SYN|ACK retransmissions will happen.
517	 * Otherwise the the RST was misdirected or spoofed.
518	 */
519	if (sc == NULL) {
520		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
521			log(LOG_DEBUG, "%s; %s: Spurious RST without matching "
522			    "syncache entry (possibly syncookie only), "
523			    "segment ignored\n", s, __func__);
524		TCPSTAT_INC(tcps_badrst);
525		goto done;
526	}
527
528	/*
529	 * If the RST bit is set, check the sequence number to see
530	 * if this is a valid reset segment.
531	 * RFC 793 page 37:
532	 *   In all states except SYN-SENT, all reset (RST) segments
533	 *   are validated by checking their SEQ-fields.  A reset is
534	 *   valid if its sequence number is in the window.
535	 *
536	 *   The sequence number in the reset segment is normally an
537	 *   echo of our outgoing acknowlegement numbers, but some hosts
538	 *   send a reset with the sequence number at the rightmost edge
539	 *   of our receive window, and we have to handle this case.
540	 */
541	if (SEQ_GEQ(th->th_seq, sc->sc_irs) &&
542	    SEQ_LEQ(th->th_seq, sc->sc_irs + sc->sc_wnd)) {
543		syncache_drop(sc, sch);
544		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
545			log(LOG_DEBUG, "%s; %s: Our SYN|ACK was rejected, "
546			    "connection attempt aborted by remote endpoint\n",
547			    s, __func__);
548		TCPSTAT_INC(tcps_sc_reset);
549	} else {
550		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
551			log(LOG_DEBUG, "%s; %s: RST with invalid SEQ %u != "
552			    "IRS %u (+WND %u), segment ignored\n",
553			    s, __func__, th->th_seq, sc->sc_irs, sc->sc_wnd);
554		TCPSTAT_INC(tcps_badrst);
555	}
556
557done:
558	if (s != NULL)
559		free(s, M_TCPLOG);
560	SCH_UNLOCK(sch);
561}
562
563void
564syncache_badack(struct in_conninfo *inc)
565{
566	INIT_VNET_INET(curvnet);
567	struct syncache *sc;
568	struct syncache_head *sch;
569
570	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
571	SCH_LOCK_ASSERT(sch);
572	if (sc != NULL) {
573		syncache_drop(sc, sch);
574		TCPSTAT_INC(tcps_sc_badack);
575	}
576	SCH_UNLOCK(sch);
577}
578
579void
580syncache_unreach(struct in_conninfo *inc, struct tcphdr *th)
581{
582	INIT_VNET_INET(curvnet);
583	struct syncache *sc;
584	struct syncache_head *sch;
585
586	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
587	SCH_LOCK_ASSERT(sch);
588	if (sc == NULL)
589		goto done;
590
591	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
592	if (ntohl(th->th_seq) != sc->sc_iss)
593		goto done;
594
595	/*
596	 * If we've rertransmitted 3 times and this is our second error,
597	 * we remove the entry.  Otherwise, we allow it to continue on.
598	 * This prevents us from incorrectly nuking an entry during a
599	 * spurious network outage.
600	 *
601	 * See tcp_notify().
602	 */
603	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxmits < 3 + 1) {
604		sc->sc_flags |= SCF_UNREACH;
605		goto done;
606	}
607	syncache_drop(sc, sch);
608	TCPSTAT_INC(tcps_sc_unreach);
609done:
610	SCH_UNLOCK(sch);
611}
612
613/*
614 * Build a new TCP socket structure from a syncache entry.
615 */
616static struct socket *
617syncache_socket(struct syncache *sc, struct socket *lso, struct mbuf *m)
618{
619	INIT_VNET_INET(lso->so_vnet);
620	struct inpcb *inp = NULL;
621	struct socket *so;
622	struct tcpcb *tp;
623	char *s;
624
625	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
626
627	/*
628	 * Ok, create the full blown connection, and set things up
629	 * as they would have been set up if we had created the
630	 * connection when the SYN arrived.  If we can't create
631	 * the connection, abort it.
632	 */
633	so = sonewconn(lso, SS_ISCONNECTED);
634	if (so == NULL) {
635		/*
636		 * Drop the connection; we will either send a RST or
637		 * have the peer retransmit its SYN again after its
638		 * RTO and try again.
639		 */
640		TCPSTAT_INC(tcps_listendrop);
641		if ((s = tcp_log_addrs(&sc->sc_inc, NULL, NULL, NULL))) {
642			log(LOG_DEBUG, "%s; %s: Socket create failed "
643			    "due to limits or memory shortage\n",
644			    s, __func__);
645			free(s, M_TCPLOG);
646		}
647		goto abort2;
648	}
649#ifdef MAC
650	mac_socketpeer_set_from_mbuf(m, so);
651#endif
652
653	inp = sotoinpcb(so);
654	inp->inp_inc.inc_fibnum = sc->sc_inc.inc_fibnum;
655	so->so_fibnum = sc->sc_inc.inc_fibnum;
656	INP_WLOCK(inp);
657
658	/* Insert new socket into PCB hash list. */
659	inp->inp_inc.inc_flags = sc->sc_inc.inc_flags;
660#ifdef INET6
661	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
662		inp->in6p_laddr = sc->sc_inc.inc6_laddr;
663	} else {
664		inp->inp_vflag &= ~INP_IPV6;
665		inp->inp_vflag |= INP_IPV4;
666#endif
667		inp->inp_laddr = sc->sc_inc.inc_laddr;
668#ifdef INET6
669	}
670#endif
671	inp->inp_lport = sc->sc_inc.inc_lport;
672	if (in_pcbinshash(inp) != 0) {
673		/*
674		 * Undo the assignments above if we failed to
675		 * put the PCB on the hash lists.
676		 */
677#ifdef INET6
678		if (sc->sc_inc.inc_flags & INC_ISIPV6)
679			inp->in6p_laddr = in6addr_any;
680		else
681#endif
682			inp->inp_laddr.s_addr = INADDR_ANY;
683		inp->inp_lport = 0;
684		goto abort;
685	}
686#ifdef IPSEC
687	/* Copy old policy into new socket's. */
688	if (ipsec_copy_policy(sotoinpcb(lso)->inp_sp, inp->inp_sp))
689		printf("syncache_socket: could not copy policy\n");
690#endif
691#ifdef INET6
692	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
693		struct inpcb *oinp = sotoinpcb(lso);
694		struct in6_addr laddr6;
695		struct sockaddr_in6 sin6;
696		/*
697		 * Inherit socket options from the listening socket.
698		 * Note that in6p_inputopts are not (and should not be)
699		 * copied, since it stores previously received options and is
700		 * used to detect if each new option is different than the
701		 * previous one and hence should be passed to a user.
702		 * If we copied in6p_inputopts, a user would not be able to
703		 * receive options just after calling the accept system call.
704		 */
705		inp->inp_flags |= oinp->inp_flags & INP_CONTROLOPTS;
706		if (oinp->in6p_outputopts)
707			inp->in6p_outputopts =
708			    ip6_copypktopts(oinp->in6p_outputopts, M_NOWAIT);
709
710		sin6.sin6_family = AF_INET6;
711		sin6.sin6_len = sizeof(sin6);
712		sin6.sin6_addr = sc->sc_inc.inc6_faddr;
713		sin6.sin6_port = sc->sc_inc.inc_fport;
714		sin6.sin6_flowinfo = sin6.sin6_scope_id = 0;
715		laddr6 = inp->in6p_laddr;
716		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
717			inp->in6p_laddr = sc->sc_inc.inc6_laddr;
718		if (in6_pcbconnect(inp, (struct sockaddr *)&sin6,
719		    thread0.td_ucred)) {
720			inp->in6p_laddr = laddr6;
721			goto abort;
722		}
723		/* Override flowlabel from in6_pcbconnect. */
724		inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
725		inp->inp_flow |= sc->sc_flowlabel;
726	} else
727#endif
728	{
729		struct in_addr laddr;
730		struct sockaddr_in sin;
731
732		inp->inp_options = (m) ? ip_srcroute(m) : NULL;
733
734		if (inp->inp_options == NULL) {
735			inp->inp_options = sc->sc_ipopts;
736			sc->sc_ipopts = NULL;
737		}
738
739		sin.sin_family = AF_INET;
740		sin.sin_len = sizeof(sin);
741		sin.sin_addr = sc->sc_inc.inc_faddr;
742		sin.sin_port = sc->sc_inc.inc_fport;
743		bzero((caddr_t)sin.sin_zero, sizeof(sin.sin_zero));
744		laddr = inp->inp_laddr;
745		if (inp->inp_laddr.s_addr == INADDR_ANY)
746			inp->inp_laddr = sc->sc_inc.inc_laddr;
747		if (in_pcbconnect(inp, (struct sockaddr *)&sin,
748		    thread0.td_ucred)) {
749			inp->inp_laddr = laddr;
750			goto abort;
751		}
752	}
753	tp = intotcpcb(inp);
754	tp->t_state = TCPS_SYN_RECEIVED;
755	tp->iss = sc->sc_iss;
756	tp->irs = sc->sc_irs;
757	tcp_rcvseqinit(tp);
758	tcp_sendseqinit(tp);
759	tp->snd_wl1 = sc->sc_irs;
760	tp->snd_max = tp->iss + 1;
761	tp->snd_nxt = tp->iss + 1;
762	tp->rcv_up = sc->sc_irs + 1;
763	tp->rcv_wnd = sc->sc_wnd;
764	tp->rcv_adv += tp->rcv_wnd;
765	tp->last_ack_sent = tp->rcv_nxt;
766
767	tp->t_flags = sototcpcb(lso)->t_flags & (TF_NOPUSH|TF_NODELAY);
768	if (sc->sc_flags & SCF_NOOPT)
769		tp->t_flags |= TF_NOOPT;
770	else {
771		if (sc->sc_flags & SCF_WINSCALE) {
772			tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
773			tp->snd_scale = sc->sc_requested_s_scale;
774			tp->request_r_scale = sc->sc_requested_r_scale;
775		}
776		if (sc->sc_flags & SCF_TIMESTAMP) {
777			tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
778			tp->ts_recent = sc->sc_tsreflect;
779			tp->ts_recent_age = ticks;
780			tp->ts_offset = sc->sc_tsoff;
781		}
782#ifdef TCP_SIGNATURE
783		if (sc->sc_flags & SCF_SIGNATURE)
784			tp->t_flags |= TF_SIGNATURE;
785#endif
786		if (sc->sc_flags & SCF_SACK)
787			tp->t_flags |= TF_SACK_PERMIT;
788	}
789
790	if (sc->sc_flags & SCF_ECN)
791		tp->t_flags |= TF_ECN_PERMIT;
792
793	/*
794	 * Set up MSS and get cached values from tcp_hostcache.
795	 * This might overwrite some of the defaults we just set.
796	 */
797	tcp_mss(tp, sc->sc_peer_mss);
798
799	/*
800	 * If the SYN,ACK was retransmitted, reset cwnd to 1 segment.
801	 */
802	if (sc->sc_rxmits)
803		tp->snd_cwnd = tp->t_maxseg;
804	tcp_timer_activate(tp, TT_KEEP, tcp_keepinit);
805
806	INP_WUNLOCK(inp);
807
808	TCPSTAT_INC(tcps_accepts);
809	return (so);
810
811abort:
812	INP_WUNLOCK(inp);
813abort2:
814	if (so != NULL)
815		soabort(so);
816	return (NULL);
817}
818
819/*
820 * This function gets called when we receive an ACK for a
821 * socket in the LISTEN state.  We look up the connection
822 * in the syncache, and if its there, we pull it out of
823 * the cache and turn it into a full-blown connection in
824 * the SYN-RECEIVED state.
825 */
826int
827syncache_expand(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
828    struct socket **lsop, struct mbuf *m)
829{
830	INIT_VNET_INET(curvnet);
831	struct syncache *sc;
832	struct syncache_head *sch;
833	struct syncache scs;
834	char *s;
835
836	/*
837	 * Global TCP locks are held because we manipulate the PCB lists
838	 * and create a new socket.
839	 */
840	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
841	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK,
842	    ("%s: can handle only ACK", __func__));
843
844	sc = syncache_lookup(inc, &sch);	/* returns locked sch */
845	SCH_LOCK_ASSERT(sch);
846	if (sc == NULL) {
847		/*
848		 * There is no syncache entry, so see if this ACK is
849		 * a returning syncookie.  To do this, first:
850		 *  A. See if this socket has had a syncache entry dropped in
851		 *     the past.  We don't want to accept a bogus syncookie
852		 *     if we've never received a SYN.
853		 *  B. check that the syncookie is valid.  If it is, then
854		 *     cobble up a fake syncache entry, and return.
855		 */
856		if (!V_tcp_syncookies) {
857			SCH_UNLOCK(sch);
858			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
859				log(LOG_DEBUG, "%s; %s: Spurious ACK, "
860				    "segment rejected (syncookies disabled)\n",
861				    s, __func__);
862			goto failed;
863		}
864		bzero(&scs, sizeof(scs));
865		sc = syncookie_lookup(inc, sch, &scs, to, th, *lsop);
866		SCH_UNLOCK(sch);
867		if (sc == NULL) {
868			if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
869				log(LOG_DEBUG, "%s; %s: Segment failed "
870				    "SYNCOOKIE authentication, segment rejected "
871				    "(probably spoofed)\n", s, __func__);
872			goto failed;
873		}
874	} else {
875		/* Pull out the entry to unlock the bucket row. */
876		TAILQ_REMOVE(&sch->sch_bucket, sc, sc_hash);
877		sch->sch_length--;
878		V_tcp_syncache.cache_count--;
879		SCH_UNLOCK(sch);
880	}
881
882	/*
883	 * Segment validation:
884	 * ACK must match our initial sequence number + 1 (the SYN|ACK).
885	 */
886	if (th->th_ack != sc->sc_iss + 1 && !TOEPCB_ISSET(sc)) {
887		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
888			log(LOG_DEBUG, "%s; %s: ACK %u != ISS+1 %u, segment "
889			    "rejected\n", s, __func__, th->th_ack, sc->sc_iss);
890		goto failed;
891	}
892
893	/*
894	 * The SEQ must fall in the window starting at the received
895	 * initial receive sequence number + 1 (the SYN).
896	 */
897	if ((SEQ_LEQ(th->th_seq, sc->sc_irs) ||
898	    SEQ_GT(th->th_seq, sc->sc_irs + sc->sc_wnd)) &&
899	    !TOEPCB_ISSET(sc)) {
900		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
901			log(LOG_DEBUG, "%s; %s: SEQ %u != IRS+1 %u, segment "
902			    "rejected\n", s, __func__, th->th_seq, sc->sc_irs);
903		goto failed;
904	}
905
906	if (!(sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS)) {
907		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
908			log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
909			    "segment rejected\n", s, __func__);
910		goto failed;
911	}
912	/*
913	 * If timestamps were negotiated the reflected timestamp
914	 * must be equal to what we actually sent in the SYN|ACK.
915	 */
916	if ((to->to_flags & TOF_TS) && to->to_tsecr != sc->sc_ts &&
917	    !TOEPCB_ISSET(sc)) {
918		if ((s = tcp_log_addrs(inc, th, NULL, NULL)))
919			log(LOG_DEBUG, "%s; %s: TSECR %u != TS %u, "
920			    "segment rejected\n",
921			    s, __func__, to->to_tsecr, sc->sc_ts);
922		goto failed;
923	}
924
925	*lsop = syncache_socket(sc, *lsop, m);
926
927	if (*lsop == NULL)
928		TCPSTAT_INC(tcps_sc_aborted);
929	else
930		TCPSTAT_INC(tcps_sc_completed);
931
932/* how do we find the inp for the new socket? */
933	if (sc != &scs)
934		syncache_free(sc);
935	return (1);
936failed:
937	if (sc != NULL && sc != &scs)
938		syncache_free(sc);
939	if (s != NULL)
940		free(s, M_TCPLOG);
941	*lsop = NULL;
942	return (0);
943}
944
945int
946tcp_offload_syncache_expand(struct in_conninfo *inc, struct tcpopt *to,
947    struct tcphdr *th, struct socket **lsop, struct mbuf *m)
948{
949	INIT_VNET_INET(curvnet);
950	int rc;
951
952	INP_INFO_WLOCK(&V_tcbinfo);
953	rc = syncache_expand(inc, to, th, lsop, m);
954	INP_INFO_WUNLOCK(&V_tcbinfo);
955
956	return (rc);
957}
958
959/*
960 * Given a LISTEN socket and an inbound SYN request, add
961 * this to the syn cache, and send back a segment:
962 *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
963 * to the source.
964 *
965 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
966 * Doing so would require that we hold onto the data and deliver it
967 * to the application.  However, if we are the target of a SYN-flood
968 * DoS attack, an attacker could send data which would eventually
969 * consume all available buffer space if it were ACKed.  By not ACKing
970 * the data, we avoid this DoS scenario.
971 */
972static void
973_syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
974    struct inpcb *inp, struct socket **lsop, struct mbuf *m,
975    struct toe_usrreqs *tu, void *toepcb)
976{
977	INIT_VNET_INET(inp->inp_vnet);
978	struct tcpcb *tp;
979	struct socket *so;
980	struct syncache *sc = NULL;
981	struct syncache_head *sch;
982	struct mbuf *ipopts = NULL;
983	u_int32_t flowtmp;
984	int win, sb_hiwat, ip_ttl, ip_tos, noopt;
985	char *s;
986#ifdef INET6
987	int autoflowlabel = 0;
988#endif
989#ifdef MAC
990	struct label *maclabel;
991#endif
992	struct syncache scs;
993	struct ucred *cred;
994
995	INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
996	INP_WLOCK_ASSERT(inp);			/* listen socket */
997	KASSERT((th->th_flags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN,
998	    ("%s: unexpected tcp flags", __func__));
999
1000	/*
1001	 * Combine all so/tp operations very early to drop the INP lock as
1002	 * soon as possible.
1003	 */
1004	so = *lsop;
1005	tp = sototcpcb(so);
1006	cred = crhold(so->so_cred);
1007
1008#ifdef INET6
1009	if ((inc->inc_flags & INC_ISIPV6) &&
1010	    (inp->inp_flags & IN6P_AUTOFLOWLABEL))
1011		autoflowlabel = 1;
1012#endif
1013	ip_ttl = inp->inp_ip_ttl;
1014	ip_tos = inp->inp_ip_tos;
1015	win = sbspace(&so->so_rcv);
1016	sb_hiwat = so->so_rcv.sb_hiwat;
1017	noopt = (tp->t_flags & TF_NOOPT);
1018
1019	/* By the time we drop the lock these should no longer be used. */
1020	so = NULL;
1021	tp = NULL;
1022
1023#ifdef MAC
1024	if (mac_syncache_init(&maclabel) != 0) {
1025		INP_WUNLOCK(inp);
1026		INP_INFO_WUNLOCK(&V_tcbinfo);
1027		goto done;
1028	} else
1029		mac_syncache_create(maclabel, inp);
1030#endif
1031	INP_WUNLOCK(inp);
1032	INP_INFO_WUNLOCK(&V_tcbinfo);
1033
1034	/*
1035	 * Remember the IP options, if any.
1036	 */
1037#ifdef INET6
1038	if (!(inc->inc_flags & INC_ISIPV6))
1039#endif
1040		ipopts = (m) ? ip_srcroute(m) : NULL;
1041
1042	/*
1043	 * See if we already have an entry for this connection.
1044	 * If we do, resend the SYN,ACK, and reset the retransmit timer.
1045	 *
1046	 * XXX: should the syncache be re-initialized with the contents
1047	 * of the new SYN here (which may have different options?)
1048	 *
1049	 * XXX: We do not check the sequence number to see if this is a
1050	 * real retransmit or a new connection attempt.  The question is
1051	 * how to handle such a case; either ignore it as spoofed, or
1052	 * drop the current entry and create a new one?
1053	 */
1054	sc = syncache_lookup(inc, &sch);	/* returns locked entry */
1055	SCH_LOCK_ASSERT(sch);
1056	if (sc != NULL) {
1057#ifndef TCP_OFFLOAD_DISABLE
1058		if (sc->sc_tu)
1059			sc->sc_tu->tu_syncache_event(TOE_SC_ENTRY_PRESENT,
1060			    sc->sc_toepcb);
1061#endif
1062		TCPSTAT_INC(tcps_sc_dupsyn);
1063		if (ipopts) {
1064			/*
1065			 * If we were remembering a previous source route,
1066			 * forget it and use the new one we've been given.
1067			 */
1068			if (sc->sc_ipopts)
1069				(void) m_free(sc->sc_ipopts);
1070			sc->sc_ipopts = ipopts;
1071		}
1072		/*
1073		 * Update timestamp if present.
1074		 */
1075		if ((sc->sc_flags & SCF_TIMESTAMP) && (to->to_flags & TOF_TS))
1076			sc->sc_tsreflect = to->to_tsval;
1077		else
1078			sc->sc_flags &= ~SCF_TIMESTAMP;
1079#ifdef MAC
1080		/*
1081		 * Since we have already unconditionally allocated label
1082		 * storage, free it up.  The syncache entry will already
1083		 * have an initialized label we can use.
1084		 */
1085		mac_syncache_destroy(&maclabel);
1086#endif
1087		/* Retransmit SYN|ACK and reset retransmit count. */
1088		if ((s = tcp_log_addrs(&sc->sc_inc, th, NULL, NULL))) {
1089			log(LOG_DEBUG, "%s; %s: Received duplicate SYN, "
1090			    "resetting timer and retransmitting SYN|ACK\n",
1091			    s, __func__);
1092			free(s, M_TCPLOG);
1093		}
1094		if (!TOEPCB_ISSET(sc) && syncache_respond(sc) == 0) {
1095			sc->sc_rxmits = 0;
1096			syncache_timeout(sc, sch, 1);
1097			TCPSTAT_INC(tcps_sndacks);
1098			TCPSTAT_INC(tcps_sndtotal);
1099		}
1100		SCH_UNLOCK(sch);
1101		goto done;
1102	}
1103
1104	sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1105	if (sc == NULL) {
1106		/*
1107		 * The zone allocator couldn't provide more entries.
1108		 * Treat this as if the cache was full; drop the oldest
1109		 * entry and insert the new one.
1110		 */
1111		TCPSTAT_INC(tcps_sc_zonefail);
1112		if ((sc = TAILQ_LAST(&sch->sch_bucket, sch_head)) != NULL)
1113			syncache_drop(sc, sch);
1114		sc = uma_zalloc(V_tcp_syncache.zone, M_NOWAIT | M_ZERO);
1115		if (sc == NULL) {
1116			if (V_tcp_syncookies) {
1117				bzero(&scs, sizeof(scs));
1118				sc = &scs;
1119			} else {
1120				SCH_UNLOCK(sch);
1121				if (ipopts)
1122					(void) m_free(ipopts);
1123				goto done;
1124			}
1125		}
1126	}
1127
1128	/*
1129	 * Fill in the syncache values.
1130	 */
1131#ifdef MAC
1132	sc->sc_label = maclabel;
1133#endif
1134	sc->sc_cred = cred;
1135	cred = NULL;
1136	sc->sc_ipopts = ipopts;
1137	/* XXX-BZ this fib assignment is just useless. */
1138	sc->sc_inc.inc_fibnum = inp->inp_inc.inc_fibnum;
1139	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1140#ifdef INET6
1141	if (!(inc->inc_flags & INC_ISIPV6))
1142#endif
1143	{
1144		sc->sc_ip_tos = ip_tos;
1145		sc->sc_ip_ttl = ip_ttl;
1146	}
1147#ifndef TCP_OFFLOAD_DISABLE
1148	sc->sc_tu = tu;
1149	sc->sc_toepcb = toepcb;
1150#endif
1151	sc->sc_irs = th->th_seq;
1152	sc->sc_iss = arc4random();
1153	sc->sc_flags = 0;
1154	sc->sc_flowlabel = 0;
1155
1156	/*
1157	 * Initial receive window: clip sbspace to [0 .. TCP_MAXWIN].
1158	 * win was derived from socket earlier in the function.
1159	 */
1160	win = imax(win, 0);
1161	win = imin(win, TCP_MAXWIN);
1162	sc->sc_wnd = win;
1163
1164	if (V_tcp_do_rfc1323) {
1165		/*
1166		 * A timestamp received in a SYN makes
1167		 * it ok to send timestamp requests and replies.
1168		 */
1169		if (to->to_flags & TOF_TS) {
1170			sc->sc_tsreflect = to->to_tsval;
1171			sc->sc_ts = ticks;
1172			sc->sc_flags |= SCF_TIMESTAMP;
1173		}
1174		if (to->to_flags & TOF_SCALE) {
1175			int wscale = 0;
1176
1177			/*
1178			 * Pick the smallest possible scaling factor that
1179			 * will still allow us to scale up to sb_max, aka
1180			 * kern.ipc.maxsockbuf.
1181			 *
1182			 * We do this because there are broken firewalls that
1183			 * will corrupt the window scale option, leading to
1184			 * the other endpoint believing that our advertised
1185			 * window is unscaled.  At scale factors larger than
1186			 * 5 the unscaled window will drop below 1500 bytes,
1187			 * leading to serious problems when traversing these
1188			 * broken firewalls.
1189			 *
1190			 * With the default maxsockbuf of 256K, a scale factor
1191			 * of 3 will be chosen by this algorithm.  Those who
1192			 * choose a larger maxsockbuf should watch out
1193			 * for the compatiblity problems mentioned above.
1194			 *
1195			 * RFC1323: The Window field in a SYN (i.e., a <SYN>
1196			 * or <SYN,ACK>) segment itself is never scaled.
1197			 */
1198			while (wscale < TCP_MAX_WINSHIFT &&
1199			    (TCP_MAXWIN << wscale) < sb_max)
1200				wscale++;
1201			sc->sc_requested_r_scale = wscale;
1202			sc->sc_requested_s_scale = to->to_wscale;
1203			sc->sc_flags |= SCF_WINSCALE;
1204		}
1205	}
1206#ifdef TCP_SIGNATURE
1207	/*
1208	 * If listening socket requested TCP digests, and received SYN
1209	 * contains the option, flag this in the syncache so that
1210	 * syncache_respond() will do the right thing with the SYN+ACK.
1211	 * XXX: Currently we always record the option by default and will
1212	 * attempt to use it in syncache_respond().
1213	 */
1214	if (to->to_flags & TOF_SIGNATURE)
1215		sc->sc_flags |= SCF_SIGNATURE;
1216#endif
1217	if (to->to_flags & TOF_SACKPERM)
1218		sc->sc_flags |= SCF_SACK;
1219	if (to->to_flags & TOF_MSS)
1220		sc->sc_peer_mss = to->to_mss;	/* peer mss may be zero */
1221	if (noopt)
1222		sc->sc_flags |= SCF_NOOPT;
1223	if ((th->th_flags & (TH_ECE|TH_CWR)) && V_tcp_do_ecn)
1224		sc->sc_flags |= SCF_ECN;
1225
1226	if (V_tcp_syncookies) {
1227		syncookie_generate(sch, sc, &flowtmp);
1228#ifdef INET6
1229		if (autoflowlabel)
1230			sc->sc_flowlabel = flowtmp;
1231#endif
1232	} else {
1233#ifdef INET6
1234		if (autoflowlabel)
1235			sc->sc_flowlabel =
1236			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
1237#endif
1238	}
1239	SCH_UNLOCK(sch);
1240
1241	/*
1242	 * Do a standard 3-way handshake.
1243	 */
1244	if (TOEPCB_ISSET(sc) || syncache_respond(sc) == 0) {
1245		if (V_tcp_syncookies && V_tcp_syncookiesonly && sc != &scs)
1246			syncache_free(sc);
1247		else if (sc != &scs)
1248			syncache_insert(sc, sch);   /* locks and unlocks sch */
1249		TCPSTAT_INC(tcps_sndacks);
1250		TCPSTAT_INC(tcps_sndtotal);
1251	} else {
1252		if (sc != &scs)
1253			syncache_free(sc);
1254		TCPSTAT_INC(tcps_sc_dropped);
1255	}
1256
1257done:
1258	if (cred != NULL)
1259		crfree(cred);
1260#ifdef MAC
1261	if (sc == &scs)
1262		mac_syncache_destroy(&maclabel);
1263#endif
1264	if (m) {
1265
1266		*lsop = NULL;
1267		m_freem(m);
1268	}
1269}
1270
1271static int
1272syncache_respond(struct syncache *sc)
1273{
1274	INIT_VNET_INET(curvnet);
1275	struct ip *ip = NULL;
1276	struct mbuf *m;
1277	struct tcphdr *th;
1278	int optlen, error;
1279	u_int16_t hlen, tlen, mssopt;
1280	struct tcpopt to;
1281#ifdef INET6
1282	struct ip6_hdr *ip6 = NULL;
1283#endif
1284
1285	hlen =
1286#ifdef INET6
1287	       (sc->sc_inc.inc_flags & INC_ISIPV6) ? sizeof(struct ip6_hdr) :
1288#endif
1289		sizeof(struct ip);
1290	tlen = hlen + sizeof(struct tcphdr);
1291
1292	/* Determine MSS we advertize to other end of connection. */
1293	mssopt = tcp_mssopt(&sc->sc_inc);
1294	if (sc->sc_peer_mss)
1295		mssopt = max( min(sc->sc_peer_mss, mssopt), V_tcp_minmss);
1296
1297	/* XXX: Assume that the entire packet will fit in a header mbuf. */
1298	KASSERT(max_linkhdr + tlen + TCP_MAXOLEN <= MHLEN,
1299	    ("syncache: mbuf too small"));
1300
1301	/* Create the IP+TCP header from scratch. */
1302	m = m_gethdr(M_DONTWAIT, MT_DATA);
1303	if (m == NULL)
1304		return (ENOBUFS);
1305#ifdef MAC
1306	mac_syncache_create_mbuf(sc->sc_label, m);
1307#endif
1308	m->m_data += max_linkhdr;
1309	m->m_len = tlen;
1310	m->m_pkthdr.len = tlen;
1311	m->m_pkthdr.rcvif = NULL;
1312
1313#ifdef INET6
1314	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1315		ip6 = mtod(m, struct ip6_hdr *);
1316		ip6->ip6_vfc = IPV6_VERSION;
1317		ip6->ip6_nxt = IPPROTO_TCP;
1318		ip6->ip6_src = sc->sc_inc.inc6_laddr;
1319		ip6->ip6_dst = sc->sc_inc.inc6_faddr;
1320		ip6->ip6_plen = htons(tlen - hlen);
1321		/* ip6_hlim is set after checksum */
1322		ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
1323		ip6->ip6_flow |= sc->sc_flowlabel;
1324
1325		th = (struct tcphdr *)(ip6 + 1);
1326	} else
1327#endif
1328	{
1329		ip = mtod(m, struct ip *);
1330		ip->ip_v = IPVERSION;
1331		ip->ip_hl = sizeof(struct ip) >> 2;
1332		ip->ip_len = tlen;
1333		ip->ip_id = 0;
1334		ip->ip_off = 0;
1335		ip->ip_sum = 0;
1336		ip->ip_p = IPPROTO_TCP;
1337		ip->ip_src = sc->sc_inc.inc_laddr;
1338		ip->ip_dst = sc->sc_inc.inc_faddr;
1339		ip->ip_ttl = sc->sc_ip_ttl;
1340		ip->ip_tos = sc->sc_ip_tos;
1341
1342		/*
1343		 * See if we should do MTU discovery.  Route lookups are
1344		 * expensive, so we will only unset the DF bit if:
1345		 *
1346		 *	1) path_mtu_discovery is disabled
1347		 *	2) the SCF_UNREACH flag has been set
1348		 */
1349		if (V_path_mtu_discovery && ((sc->sc_flags & SCF_UNREACH) == 0))
1350		       ip->ip_off |= IP_DF;
1351
1352		th = (struct tcphdr *)(ip + 1);
1353	}
1354	th->th_sport = sc->sc_inc.inc_lport;
1355	th->th_dport = sc->sc_inc.inc_fport;
1356
1357	th->th_seq = htonl(sc->sc_iss);
1358	th->th_ack = htonl(sc->sc_irs + 1);
1359	th->th_off = sizeof(struct tcphdr) >> 2;
1360	th->th_x2 = 0;
1361	th->th_flags = TH_SYN|TH_ACK;
1362	th->th_win = htons(sc->sc_wnd);
1363	th->th_urp = 0;
1364
1365	if (sc->sc_flags & SCF_ECN) {
1366		th->th_flags |= TH_ECE;
1367		TCPSTAT_INC(tcps_ecn_shs);
1368	}
1369
1370	/* Tack on the TCP options. */
1371	if ((sc->sc_flags & SCF_NOOPT) == 0) {
1372		to.to_flags = 0;
1373
1374		to.to_mss = mssopt;
1375		to.to_flags = TOF_MSS;
1376		if (sc->sc_flags & SCF_WINSCALE) {
1377			to.to_wscale = sc->sc_requested_r_scale;
1378			to.to_flags |= TOF_SCALE;
1379		}
1380		if (sc->sc_flags & SCF_TIMESTAMP) {
1381			/* Virgin timestamp or TCP cookie enhanced one. */
1382			to.to_tsval = sc->sc_ts;
1383			to.to_tsecr = sc->sc_tsreflect;
1384			to.to_flags |= TOF_TS;
1385		}
1386		if (sc->sc_flags & SCF_SACK)
1387			to.to_flags |= TOF_SACKPERM;
1388#ifdef TCP_SIGNATURE
1389		if (sc->sc_flags & SCF_SIGNATURE)
1390			to.to_flags |= TOF_SIGNATURE;
1391#endif
1392		optlen = tcp_addoptions(&to, (u_char *)(th + 1));
1393
1394		/* Adjust headers by option size. */
1395		th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1396		m->m_len += optlen;
1397		m->m_pkthdr.len += optlen;
1398
1399#ifdef TCP_SIGNATURE
1400		if (sc->sc_flags & SCF_SIGNATURE)
1401			tcp_signature_compute(m, 0, 0, optlen,
1402			    to.to_signature, IPSEC_DIR_OUTBOUND);
1403#endif
1404#ifdef INET6
1405		if (sc->sc_inc.inc_flags & INC_ISIPV6)
1406			ip6->ip6_plen = htons(ntohs(ip6->ip6_plen) + optlen);
1407		else
1408#endif
1409			ip->ip_len += optlen;
1410	} else
1411		optlen = 0;
1412
1413#ifdef INET6
1414	if (sc->sc_inc.inc_flags & INC_ISIPV6) {
1415		th->th_sum = 0;
1416		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen,
1417				       tlen + optlen - hlen);
1418		ip6->ip6_hlim = in6_selecthlim(NULL, NULL);
1419		error = ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1420	} else
1421#endif
1422	{
1423		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1424		    htons(tlen + optlen - hlen + IPPROTO_TCP));
1425		m->m_pkthdr.csum_flags = CSUM_TCP;
1426		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1427		error = ip_output(m, sc->sc_ipopts, NULL, 0, NULL, NULL);
1428	}
1429	return (error);
1430}
1431
1432void
1433syncache_add(struct in_conninfo *inc, struct tcpopt *to, struct tcphdr *th,
1434    struct inpcb *inp, struct socket **lsop, struct mbuf *m)
1435{
1436	_syncache_add(inc, to, th, inp, lsop, m, NULL, NULL);
1437}
1438
1439void
1440tcp_offload_syncache_add(struct in_conninfo *inc, struct tcpopt *to,
1441    struct tcphdr *th, struct inpcb *inp, struct socket **lsop,
1442    struct toe_usrreqs *tu, void *toepcb)
1443{
1444	INIT_VNET_INET(curvnet);
1445
1446	INP_INFO_WLOCK(&V_tcbinfo);
1447	INP_WLOCK(inp);
1448	_syncache_add(inc, to, th, inp, lsop, NULL, tu, toepcb);
1449}
1450
1451/*
1452 * The purpose of SYN cookies is to avoid keeping track of all SYN's we
1453 * receive and to be able to handle SYN floods from bogus source addresses
1454 * (where we will never receive any reply).  SYN floods try to exhaust all
1455 * our memory and available slots in the SYN cache table to cause a denial
1456 * of service to legitimate users of the local host.
1457 *
1458 * The idea of SYN cookies is to encode and include all necessary information
1459 * about the connection setup state within the SYN-ACK we send back and thus
1460 * to get along without keeping any local state until the ACK to the SYN-ACK
1461 * arrives (if ever).  Everything we need to know should be available from
1462 * the information we encoded in the SYN-ACK.
1463 *
1464 * More information about the theory behind SYN cookies and its first
1465 * discussion and specification can be found at:
1466 *  http://cr.yp.to/syncookies.html    (overview)
1467 *  http://cr.yp.to/syncookies/archive (gory details)
1468 *
1469 * This implementation extends the orginal idea and first implementation
1470 * of FreeBSD by using not only the initial sequence number field to store
1471 * information but also the timestamp field if present.  This way we can
1472 * keep track of the entire state we need to know to recreate the session in
1473 * its original form.  Almost all TCP speakers implement RFC1323 timestamps
1474 * these days.  For those that do not we still have to live with the known
1475 * shortcomings of the ISN only SYN cookies.
1476 *
1477 * Cookie layers:
1478 *
1479 * Initial sequence number we send:
1480 * 31|................................|0
1481 *    DDDDDDDDDDDDDDDDDDDDDDDDDMMMRRRP
1482 *    D = MD5 Digest (first dword)
1483 *    M = MSS index
1484 *    R = Rotation of secret
1485 *    P = Odd or Even secret
1486 *
1487 * The MD5 Digest is computed with over following parameters:
1488 *  a) randomly rotated secret
1489 *  b) struct in_conninfo containing the remote/local ip/port (IPv4&IPv6)
1490 *  c) the received initial sequence number from remote host
1491 *  d) the rotation offset and odd/even bit
1492 *
1493 * Timestamp we send:
1494 * 31|................................|0
1495 *    DDDDDDDDDDDDDDDDDDDDDDSSSSRRRRA5
1496 *    D = MD5 Digest (third dword) (only as filler)
1497 *    S = Requested send window scale
1498 *    R = Requested receive window scale
1499 *    A = SACK allowed
1500 *    5 = TCP-MD5 enabled (not implemented yet)
1501 *    XORed with MD5 Digest (forth dword)
1502 *
1503 * The timestamp isn't cryptographically secure and doesn't need to be.
1504 * The double use of the MD5 digest dwords ties it to a specific remote/
1505 * local host/port, remote initial sequence number and our local time
1506 * limited secret.  A received timestamp is reverted (XORed) and then
1507 * the contained MD5 dword is compared to the computed one to ensure the
1508 * timestamp belongs to the SYN-ACK we sent.  The other parameters may
1509 * have been tampered with but this isn't different from supplying bogus
1510 * values in the SYN in the first place.
1511 *
1512 * Some problems with SYN cookies remain however:
1513 * Consider the problem of a recreated (and retransmitted) cookie.  If the
1514 * original SYN was accepted, the connection is established.  The second
1515 * SYN is inflight, and if it arrives with an ISN that falls within the
1516 * receive window, the connection is killed.
1517 *
1518 * Notes:
1519 * A heuristic to determine when to accept syn cookies is not necessary.
1520 * An ACK flood would cause the syncookie verification to be attempted,
1521 * but a SYN flood causes syncookies to be generated.  Both are of equal
1522 * cost, so there's no point in trying to optimize the ACK flood case.
1523 * Also, if you don't process certain ACKs for some reason, then all someone
1524 * would have to do is launch a SYN and ACK flood at the same time, which
1525 * would stop cookie verification and defeat the entire purpose of syncookies.
1526 */
1527static int tcp_sc_msstab[] = { 0, 256, 468, 536, 996, 1452, 1460, 8960 };
1528
1529static void
1530syncookie_generate(struct syncache_head *sch, struct syncache *sc,
1531    u_int32_t *flowlabel)
1532{
1533	INIT_VNET_INET(curvnet);
1534	MD5_CTX ctx;
1535	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1536	u_int32_t data;
1537	u_int32_t *secbits;
1538	u_int off, pmss, mss;
1539	int i;
1540
1541	SCH_LOCK_ASSERT(sch);
1542
1543	/* Which of the two secrets to use. */
1544	secbits = sch->sch_oddeven ?
1545			sch->sch_secbits_odd : sch->sch_secbits_even;
1546
1547	/* Reseed secret if too old. */
1548	if (sch->sch_reseed < time_uptime) {
1549		sch->sch_oddeven = sch->sch_oddeven ? 0 : 1;	/* toggle */
1550		secbits = sch->sch_oddeven ?
1551				sch->sch_secbits_odd : sch->sch_secbits_even;
1552		for (i = 0; i < SYNCOOKIE_SECRET_SIZE; i++)
1553			secbits[i] = arc4random();
1554		sch->sch_reseed = time_uptime + SYNCOOKIE_LIFETIME;
1555	}
1556
1557	/* Secret rotation offset. */
1558	off = sc->sc_iss & 0x7;			/* iss was randomized before */
1559
1560	/* Maximum segment size calculation. */
1561	pmss =
1562	    max( min(sc->sc_peer_mss, tcp_mssopt(&sc->sc_inc)),	V_tcp_minmss);
1563	for (mss = sizeof(tcp_sc_msstab) / sizeof(int) - 1; mss > 0; mss--)
1564		if (tcp_sc_msstab[mss] <= pmss)
1565			break;
1566
1567	/* Fold parameters and MD5 digest into the ISN we will send. */
1568	data = sch->sch_oddeven;/* odd or even secret, 1 bit */
1569	data |= off << 1;	/* secret offset, derived from iss, 3 bits */
1570	data |= mss << 4;	/* mss, 3 bits */
1571
1572	MD5Init(&ctx);
1573	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1574	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1575	MD5Update(&ctx, secbits, off);
1576	MD5Update(&ctx, &sc->sc_inc, sizeof(sc->sc_inc));
1577	MD5Update(&ctx, &sc->sc_irs, sizeof(sc->sc_irs));
1578	MD5Update(&ctx, &data, sizeof(data));
1579	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1580
1581	data |= (md5_buffer[0] << 7);
1582	sc->sc_iss = data;
1583
1584#ifdef INET6
1585	*flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1586#endif
1587
1588	/* Additional parameters are stored in the timestamp if present. */
1589	if (sc->sc_flags & SCF_TIMESTAMP) {
1590		data =  ((sc->sc_flags & SCF_SIGNATURE) ? 1 : 0); /* TCP-MD5, 1 bit */
1591		data |= ((sc->sc_flags & SCF_SACK) ? 1 : 0) << 1; /* SACK, 1 bit */
1592		data |= sc->sc_requested_s_scale << 2;  /* SWIN scale, 4 bits */
1593		data |= sc->sc_requested_r_scale << 6;  /* RWIN scale, 4 bits */
1594		data |= md5_buffer[2] << 10;		/* more digest bits */
1595		data ^= md5_buffer[3];
1596		sc->sc_ts = data;
1597		sc->sc_tsoff = data - ticks;		/* after XOR */
1598	}
1599
1600	TCPSTAT_INC(tcps_sc_sendcookie);
1601}
1602
1603static struct syncache *
1604syncookie_lookup(struct in_conninfo *inc, struct syncache_head *sch,
1605    struct syncache *sc, struct tcpopt *to, struct tcphdr *th,
1606    struct socket *so)
1607{
1608	INIT_VNET_INET(curvnet);
1609	MD5_CTX ctx;
1610	u_int32_t md5_buffer[MD5_DIGEST_LENGTH / sizeof(u_int32_t)];
1611	u_int32_t data = 0;
1612	u_int32_t *secbits;
1613	tcp_seq ack, seq;
1614	int off, mss, wnd, flags;
1615
1616	SCH_LOCK_ASSERT(sch);
1617
1618	/*
1619	 * Pull information out of SYN-ACK/ACK and
1620	 * revert sequence number advances.
1621	 */
1622	ack = th->th_ack - 1;
1623	seq = th->th_seq - 1;
1624	off = (ack >> 1) & 0x7;
1625	mss = (ack >> 4) & 0x7;
1626	flags = ack & 0x7f;
1627
1628	/* Which of the two secrets to use. */
1629	secbits = (flags & 0x1) ? sch->sch_secbits_odd : sch->sch_secbits_even;
1630
1631	/*
1632	 * The secret wasn't updated for the lifetime of a syncookie,
1633	 * so this SYN-ACK/ACK is either too old (replay) or totally bogus.
1634	 */
1635	if (sch->sch_reseed + SYNCOOKIE_LIFETIME < time_uptime) {
1636		return (NULL);
1637	}
1638
1639	/* Recompute the digest so we can compare it. */
1640	MD5Init(&ctx);
1641	MD5Update(&ctx, ((u_int8_t *)secbits) + off,
1642	    SYNCOOKIE_SECRET_SIZE * sizeof(*secbits) - off);
1643	MD5Update(&ctx, secbits, off);
1644	MD5Update(&ctx, inc, sizeof(*inc));
1645	MD5Update(&ctx, &seq, sizeof(seq));
1646	MD5Update(&ctx, &flags, sizeof(flags));
1647	MD5Final((u_int8_t *)&md5_buffer, &ctx);
1648
1649	/* Does the digest part of or ACK'ed ISS match? */
1650	if ((ack & (~0x7f)) != (md5_buffer[0] << 7))
1651		return (NULL);
1652
1653	/* Does the digest part of our reflected timestamp match? */
1654	if (to->to_flags & TOF_TS) {
1655		data = md5_buffer[3] ^ to->to_tsecr;
1656		if ((data & (~0x3ff)) != (md5_buffer[2] << 10))
1657			return (NULL);
1658	}
1659
1660	/* Fill in the syncache values. */
1661	bcopy(inc, &sc->sc_inc, sizeof(struct in_conninfo));
1662	sc->sc_ipopts = NULL;
1663
1664	sc->sc_irs = seq;
1665	sc->sc_iss = ack;
1666
1667#ifdef INET6
1668	if (inc->inc_flags & INC_ISIPV6) {
1669		if (sotoinpcb(so)->inp_flags & IN6P_AUTOFLOWLABEL)
1670			sc->sc_flowlabel = md5_buffer[1] & IPV6_FLOWLABEL_MASK;
1671	} else
1672#endif
1673	{
1674		sc->sc_ip_ttl = sotoinpcb(so)->inp_ip_ttl;
1675		sc->sc_ip_tos = sotoinpcb(so)->inp_ip_tos;
1676	}
1677
1678	/* Additional parameters that were encoded in the timestamp. */
1679	if (data) {
1680		sc->sc_flags |= SCF_TIMESTAMP;
1681		sc->sc_tsreflect = to->to_tsval;
1682		sc->sc_ts = to->to_tsecr;
1683		sc->sc_tsoff = to->to_tsecr - ticks;
1684		sc->sc_flags |= (data & 0x1) ? SCF_SIGNATURE : 0;
1685		sc->sc_flags |= ((data >> 1) & 0x1) ? SCF_SACK : 0;
1686		sc->sc_requested_s_scale = min((data >> 2) & 0xf,
1687		    TCP_MAX_WINSHIFT);
1688		sc->sc_requested_r_scale = min((data >> 6) & 0xf,
1689		    TCP_MAX_WINSHIFT);
1690		if (sc->sc_requested_s_scale || sc->sc_requested_r_scale)
1691			sc->sc_flags |= SCF_WINSCALE;
1692	} else
1693		sc->sc_flags |= SCF_NOOPT;
1694
1695	wnd = sbspace(&so->so_rcv);
1696	wnd = imax(wnd, 0);
1697	wnd = imin(wnd, TCP_MAXWIN);
1698	sc->sc_wnd = wnd;
1699
1700	sc->sc_rxmits = 0;
1701	sc->sc_peer_mss = tcp_sc_msstab[mss];
1702
1703	TCPSTAT_INC(tcps_sc_recvcookie);
1704	return (sc);
1705}
1706
1707/*
1708 * Returns the current number of syncache entries.  This number
1709 * will probably change before you get around to calling
1710 * syncache_pcblist.
1711 */
1712
1713int
1714syncache_pcbcount(void)
1715{
1716	INIT_VNET_INET(curvnet);
1717	struct syncache_head *sch;
1718	int count, i;
1719
1720	for (count = 0, i = 0; i < V_tcp_syncache.hashsize; i++) {
1721		/* No need to lock for a read. */
1722		sch = &V_tcp_syncache.hashbase[i];
1723		count += sch->sch_length;
1724	}
1725	return count;
1726}
1727
1728/*
1729 * Exports the syncache entries to userland so that netstat can display
1730 * them alongside the other sockets.  This function is intended to be
1731 * called only from tcp_pcblist.
1732 *
1733 * Due to concurrency on an active system, the number of pcbs exported
1734 * may have no relation to max_pcbs.  max_pcbs merely indicates the
1735 * amount of space the caller allocated for this function to use.
1736 */
1737int
1738syncache_pcblist(struct sysctl_req *req, int max_pcbs, int *pcbs_exported)
1739{
1740	INIT_VNET_INET(curvnet);
1741	struct xtcpcb xt;
1742	struct syncache *sc;
1743	struct syncache_head *sch;
1744	int count, error, i;
1745
1746	for (count = 0, error = 0, i = 0; i < V_tcp_syncache.hashsize; i++) {
1747		sch = &V_tcp_syncache.hashbase[i];
1748		SCH_LOCK(sch);
1749		TAILQ_FOREACH(sc, &sch->sch_bucket, sc_hash) {
1750			if (count >= max_pcbs) {
1751				SCH_UNLOCK(sch);
1752				goto exit;
1753			}
1754			if (cr_cansee(req->td->td_ucred, sc->sc_cred) != 0)
1755				continue;
1756			bzero(&xt, sizeof(xt));
1757			xt.xt_len = sizeof(xt);
1758			if (sc->sc_inc.inc_flags & INC_ISIPV6)
1759				xt.xt_inp.inp_vflag = INP_IPV6;
1760			else
1761				xt.xt_inp.inp_vflag = INP_IPV4;
1762			bcopy(&sc->sc_inc, &xt.xt_inp.inp_inc, sizeof (struct in_conninfo));
1763			xt.xt_tp.t_inpcb = &xt.xt_inp;
1764			xt.xt_tp.t_state = TCPS_SYN_RECEIVED;
1765			xt.xt_socket.xso_protocol = IPPROTO_TCP;
1766			xt.xt_socket.xso_len = sizeof (struct xsocket);
1767			xt.xt_socket.so_type = SOCK_STREAM;
1768			xt.xt_socket.so_state = SS_ISCONNECTING;
1769			error = SYSCTL_OUT(req, &xt, sizeof xt);
1770			if (error) {
1771				SCH_UNLOCK(sch);
1772				goto exit;
1773			}
1774			count++;
1775		}
1776		SCH_UNLOCK(sch);
1777	}
1778exit:
1779	*pcbs_exported = count;
1780	return error;
1781}
1782