nf_conntrack_core.c revision be00c8e48993368663e2714bd1e7c886b7736406
1/* Connection state tracking for netfilter.  This is separated from,
2   but required by, the NAT layer; it can also be used by an iptables
3   extension. */
4
5/* (C) 1999-2001 Paul `Rusty' Russell
6 * (C) 2002-2006 Netfilter Core Team <coreteam@netfilter.org>
7 * (C) 2003,2004 USAGI/WIDE Project <http://www.linux-ipv6.org>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License version 2 as
11 * published by the Free Software Foundation.
12 *
13 * 23 Apr 2001: Harald Welte <laforge@gnumonks.org>
14 *	- new API and handling of conntrack/nat helpers
15 *	- now capable of multiple expectations for one master
16 * 16 Jul 2002: Harald Welte <laforge@gnumonks.org>
17 *	- add usage/reference counts to ip_conntrack_expect
18 *	- export ip_conntrack[_expect]_{find_get,put} functions
19 * 16 Dec 2003: Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
20 *	- generalize L3 protocol denendent part.
21 * 23 Mar 2004: Yasuyuki Kozakai @USAGI <yasuyuki.kozakai@toshiba.co.jp>
22 *	- add support various size of conntrack structures.
23 * 26 Jan 2006: Harald Welte <laforge@netfilter.org>
24 * 	- restructure nf_conn (introduce nf_conn_help)
25 * 	- redesign 'features' how they were originally intended
26 * 26 Feb 2006: Pablo Neira Ayuso <pablo@eurodev.net>
27 * 	- add support for L3 protocol module load on demand.
28 *
29 * Derived from net/ipv4/netfilter/ip_conntrack_core.c
30 */
31
32#include <linux/types.h>
33#include <linux/netfilter.h>
34#include <linux/module.h>
35#include <linux/skbuff.h>
36#include <linux/proc_fs.h>
37#include <linux/vmalloc.h>
38#include <linux/stddef.h>
39#include <linux/slab.h>
40#include <linux/random.h>
41#include <linux/jhash.h>
42#include <linux/err.h>
43#include <linux/percpu.h>
44#include <linux/moduleparam.h>
45#include <linux/notifier.h>
46#include <linux/kernel.h>
47#include <linux/netdevice.h>
48#include <linux/socket.h>
49
50#include <net/netfilter/nf_conntrack.h>
51#include <net/netfilter/nf_conntrack_l3proto.h>
52#include <net/netfilter/nf_conntrack_l4proto.h>
53#include <net/netfilter/nf_conntrack_expect.h>
54#include <net/netfilter/nf_conntrack_helper.h>
55#include <net/netfilter/nf_conntrack_core.h>
56
57#define NF_CONNTRACK_VERSION	"0.5.0"
58
59#if 0
60#define DEBUGP printk
61#else
62#define DEBUGP(format, args...)
63#endif
64
65DEFINE_RWLOCK(nf_conntrack_lock);
66
67/* nf_conntrack_standalone needs this */
68atomic_t nf_conntrack_count = ATOMIC_INIT(0);
69
70void (*nf_conntrack_destroyed)(struct nf_conn *conntrack) = NULL;
71unsigned int nf_conntrack_htable_size __read_mostly;
72int nf_conntrack_max __read_mostly;
73struct list_head *nf_conntrack_hash __read_mostly;
74struct nf_conn nf_conntrack_untracked __read_mostly;
75unsigned int nf_ct_log_invalid __read_mostly;
76LIST_HEAD(unconfirmed);
77static int nf_conntrack_vmalloc __read_mostly;
78
79static unsigned int nf_conntrack_next_id;
80
81DEFINE_PER_CPU(struct ip_conntrack_stat, nf_conntrack_stat);
82EXPORT_PER_CPU_SYMBOL(nf_conntrack_stat);
83
84/*
85 * This scheme offers various size of "struct nf_conn" dependent on
86 * features(helper, nat, ...)
87 */
88
89#define NF_CT_FEATURES_NAMELEN	256
90static struct {
91	/* name of slab cache. printed in /proc/slabinfo */
92	char *name;
93
94	/* size of slab cache */
95	size_t size;
96
97	/* slab cache pointer */
98	kmem_cache_t *cachep;
99
100	/* allocated slab cache + modules which uses this slab cache */
101	int use;
102
103} nf_ct_cache[NF_CT_F_NUM];
104
105/* protect members of nf_ct_cache except of "use" */
106DEFINE_RWLOCK(nf_ct_cache_lock);
107
108/* This avoids calling kmem_cache_create() with same name simultaneously */
109static DEFINE_MUTEX(nf_ct_cache_mutex);
110
111static int nf_conntrack_hash_rnd_initted;
112static unsigned int nf_conntrack_hash_rnd;
113
114static u_int32_t __hash_conntrack(const struct nf_conntrack_tuple *tuple,
115				  unsigned int size, unsigned int rnd)
116{
117	unsigned int a, b;
118	a = jhash((void *)tuple->src.u3.all, sizeof(tuple->src.u3.all),
119		  ((tuple->src.l3num) << 16) | tuple->dst.protonum);
120	b = jhash((void *)tuple->dst.u3.all, sizeof(tuple->dst.u3.all),
121			(tuple->src.u.all << 16) | tuple->dst.u.all);
122
123	return jhash_2words(a, b, rnd) % size;
124}
125
126static inline u_int32_t hash_conntrack(const struct nf_conntrack_tuple *tuple)
127{
128	return __hash_conntrack(tuple, nf_conntrack_htable_size,
129				nf_conntrack_hash_rnd);
130}
131
132int nf_conntrack_register_cache(u_int32_t features, const char *name,
133				size_t size)
134{
135	int ret = 0;
136	char *cache_name;
137	kmem_cache_t *cachep;
138
139	DEBUGP("nf_conntrack_register_cache: features=0x%x, name=%s, size=%d\n",
140	       features, name, size);
141
142	if (features < NF_CT_F_BASIC || features >= NF_CT_F_NUM) {
143		DEBUGP("nf_conntrack_register_cache: invalid features.: 0x%x\n",
144			features);
145		return -EINVAL;
146	}
147
148	mutex_lock(&nf_ct_cache_mutex);
149
150	write_lock_bh(&nf_ct_cache_lock);
151	/* e.g: multiple helpers are loaded */
152	if (nf_ct_cache[features].use > 0) {
153		DEBUGP("nf_conntrack_register_cache: already resisterd.\n");
154		if ((!strncmp(nf_ct_cache[features].name, name,
155			      NF_CT_FEATURES_NAMELEN))
156		    && nf_ct_cache[features].size == size) {
157			DEBUGP("nf_conntrack_register_cache: reusing.\n");
158			nf_ct_cache[features].use++;
159			ret = 0;
160		} else
161			ret = -EBUSY;
162
163		write_unlock_bh(&nf_ct_cache_lock);
164		mutex_unlock(&nf_ct_cache_mutex);
165		return ret;
166	}
167	write_unlock_bh(&nf_ct_cache_lock);
168
169	/*
170	 * The memory space for name of slab cache must be alive until
171	 * cache is destroyed.
172	 */
173	cache_name = kmalloc(sizeof(char)*NF_CT_FEATURES_NAMELEN, GFP_ATOMIC);
174	if (cache_name == NULL) {
175		DEBUGP("nf_conntrack_register_cache: can't alloc cache_name\n");
176		ret = -ENOMEM;
177		goto out_up_mutex;
178	}
179
180	if (strlcpy(cache_name, name, NF_CT_FEATURES_NAMELEN)
181						>= NF_CT_FEATURES_NAMELEN) {
182		printk("nf_conntrack_register_cache: name too long\n");
183		ret = -EINVAL;
184		goto out_free_name;
185	}
186
187	cachep = kmem_cache_create(cache_name, size, 0, 0,
188				   NULL, NULL);
189	if (!cachep) {
190		printk("nf_conntrack_register_cache: Can't create slab cache "
191		       "for the features = 0x%x\n", features);
192		ret = -ENOMEM;
193		goto out_free_name;
194	}
195
196	write_lock_bh(&nf_ct_cache_lock);
197	nf_ct_cache[features].use = 1;
198	nf_ct_cache[features].size = size;
199	nf_ct_cache[features].cachep = cachep;
200	nf_ct_cache[features].name = cache_name;
201	write_unlock_bh(&nf_ct_cache_lock);
202
203	goto out_up_mutex;
204
205out_free_name:
206	kfree(cache_name);
207out_up_mutex:
208	mutex_unlock(&nf_ct_cache_mutex);
209	return ret;
210}
211
212/* FIXME: In the current, only nf_conntrack_cleanup() can call this function. */
213void nf_conntrack_unregister_cache(u_int32_t features)
214{
215	kmem_cache_t *cachep;
216	char *name;
217
218	/*
219	 * This assures that kmem_cache_create() isn't called before destroying
220	 * slab cache.
221	 */
222	DEBUGP("nf_conntrack_unregister_cache: 0x%04x\n", features);
223	mutex_lock(&nf_ct_cache_mutex);
224
225	write_lock_bh(&nf_ct_cache_lock);
226	if (--nf_ct_cache[features].use > 0) {
227		write_unlock_bh(&nf_ct_cache_lock);
228		mutex_unlock(&nf_ct_cache_mutex);
229		return;
230	}
231	cachep = nf_ct_cache[features].cachep;
232	name = nf_ct_cache[features].name;
233	nf_ct_cache[features].cachep = NULL;
234	nf_ct_cache[features].name = NULL;
235	nf_ct_cache[features].size = 0;
236	write_unlock_bh(&nf_ct_cache_lock);
237
238	synchronize_net();
239
240	kmem_cache_destroy(cachep);
241	kfree(name);
242
243	mutex_unlock(&nf_ct_cache_mutex);
244}
245
246int
247nf_ct_get_tuple(const struct sk_buff *skb,
248		unsigned int nhoff,
249		unsigned int dataoff,
250		u_int16_t l3num,
251		u_int8_t protonum,
252		struct nf_conntrack_tuple *tuple,
253		const struct nf_conntrack_l3proto *l3proto,
254		const struct nf_conntrack_l4proto *l4proto)
255{
256	NF_CT_TUPLE_U_BLANK(tuple);
257
258	tuple->src.l3num = l3num;
259	if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
260		return 0;
261
262	tuple->dst.protonum = protonum;
263	tuple->dst.dir = IP_CT_DIR_ORIGINAL;
264
265	return l4proto->pkt_to_tuple(skb, dataoff, tuple);
266}
267
268int
269nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
270		   const struct nf_conntrack_tuple *orig,
271		   const struct nf_conntrack_l3proto *l3proto,
272		   const struct nf_conntrack_l4proto *l4proto)
273{
274	NF_CT_TUPLE_U_BLANK(inverse);
275
276	inverse->src.l3num = orig->src.l3num;
277	if (l3proto->invert_tuple(inverse, orig) == 0)
278		return 0;
279
280	inverse->dst.dir = !orig->dst.dir;
281
282	inverse->dst.protonum = orig->dst.protonum;
283	return l4proto->invert_tuple(inverse, orig);
284}
285
286static void
287clean_from_lists(struct nf_conn *ct)
288{
289	DEBUGP("clean_from_lists(%p)\n", ct);
290	list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
291	list_del(&ct->tuplehash[IP_CT_DIR_REPLY].list);
292
293	/* Destroy all pending expectations */
294	nf_ct_remove_expectations(ct);
295}
296
297static void
298destroy_conntrack(struct nf_conntrack *nfct)
299{
300	struct nf_conn *ct = (struct nf_conn *)nfct;
301	struct nf_conntrack_l3proto *l3proto;
302	struct nf_conntrack_l4proto *l4proto;
303
304	DEBUGP("destroy_conntrack(%p)\n", ct);
305	NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
306	NF_CT_ASSERT(!timer_pending(&ct->timeout));
307
308	nf_conntrack_event(IPCT_DESTROY, ct);
309	set_bit(IPS_DYING_BIT, &ct->status);
310
311	/* To make sure we don't get any weird locking issues here:
312	 * destroy_conntrack() MUST NOT be called with a write lock
313	 * to nf_conntrack_lock!!! -HW */
314	l3proto = __nf_ct_l3proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num);
315	if (l3proto && l3proto->destroy)
316		l3proto->destroy(ct);
317
318	l4proto = __nf_ct_l4proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num, ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.protonum);
319	if (l4proto && l4proto->destroy)
320		l4proto->destroy(ct);
321
322	if (nf_conntrack_destroyed)
323		nf_conntrack_destroyed(ct);
324
325	write_lock_bh(&nf_conntrack_lock);
326	/* Expectations will have been removed in clean_from_lists,
327	 * except TFTP can create an expectation on the first packet,
328	 * before connection is in the list, so we need to clean here,
329	 * too. */
330	nf_ct_remove_expectations(ct);
331
332	/* We overload first tuple to link into unconfirmed list. */
333	if (!nf_ct_is_confirmed(ct)) {
334		BUG_ON(list_empty(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list));
335		list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
336	}
337
338	NF_CT_STAT_INC(delete);
339	write_unlock_bh(&nf_conntrack_lock);
340
341	if (ct->master)
342		nf_ct_put(ct->master);
343
344	DEBUGP("destroy_conntrack: returning ct=%p to slab\n", ct);
345	nf_conntrack_free(ct);
346}
347
348static void death_by_timeout(unsigned long ul_conntrack)
349{
350	struct nf_conn *ct = (void *)ul_conntrack;
351
352	write_lock_bh(&nf_conntrack_lock);
353	/* Inside lock so preempt is disabled on module removal path.
354	 * Otherwise we can get spurious warnings. */
355	NF_CT_STAT_INC(delete_list);
356	clean_from_lists(ct);
357	write_unlock_bh(&nf_conntrack_lock);
358	nf_ct_put(ct);
359}
360
361struct nf_conntrack_tuple_hash *
362__nf_conntrack_find(const struct nf_conntrack_tuple *tuple,
363		    const struct nf_conn *ignored_conntrack)
364{
365	struct nf_conntrack_tuple_hash *h;
366	unsigned int hash = hash_conntrack(tuple);
367
368	list_for_each_entry(h, &nf_conntrack_hash[hash], list) {
369		if (nf_ct_tuplehash_to_ctrack(h) != ignored_conntrack &&
370		    nf_ct_tuple_equal(tuple, &h->tuple)) {
371			NF_CT_STAT_INC(found);
372			return h;
373		}
374		NF_CT_STAT_INC(searched);
375	}
376
377	return NULL;
378}
379
380/* Find a connection corresponding to a tuple. */
381struct nf_conntrack_tuple_hash *
382nf_conntrack_find_get(const struct nf_conntrack_tuple *tuple,
383		      const struct nf_conn *ignored_conntrack)
384{
385	struct nf_conntrack_tuple_hash *h;
386
387	read_lock_bh(&nf_conntrack_lock);
388	h = __nf_conntrack_find(tuple, ignored_conntrack);
389	if (h)
390		atomic_inc(&nf_ct_tuplehash_to_ctrack(h)->ct_general.use);
391	read_unlock_bh(&nf_conntrack_lock);
392
393	return h;
394}
395
396static void __nf_conntrack_hash_insert(struct nf_conn *ct,
397				       unsigned int hash,
398				       unsigned int repl_hash)
399{
400	ct->id = ++nf_conntrack_next_id;
401	list_add(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list,
402		 &nf_conntrack_hash[hash]);
403	list_add(&ct->tuplehash[IP_CT_DIR_REPLY].list,
404		 &nf_conntrack_hash[repl_hash]);
405}
406
407void nf_conntrack_hash_insert(struct nf_conn *ct)
408{
409	unsigned int hash, repl_hash;
410
411	hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
412	repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
413
414	write_lock_bh(&nf_conntrack_lock);
415	__nf_conntrack_hash_insert(ct, hash, repl_hash);
416	write_unlock_bh(&nf_conntrack_lock);
417}
418
419/* Confirm a connection given skb; places it in hash table */
420int
421__nf_conntrack_confirm(struct sk_buff **pskb)
422{
423	unsigned int hash, repl_hash;
424	struct nf_conntrack_tuple_hash *h;
425	struct nf_conn *ct;
426	struct nf_conn_help *help;
427	enum ip_conntrack_info ctinfo;
428
429	ct = nf_ct_get(*pskb, &ctinfo);
430
431	/* ipt_REJECT uses nf_conntrack_attach to attach related
432	   ICMP/TCP RST packets in other direction.  Actual packet
433	   which created connection will be IP_CT_NEW or for an
434	   expected connection, IP_CT_RELATED. */
435	if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
436		return NF_ACCEPT;
437
438	hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
439	repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
440
441	/* We're not in hash table, and we refuse to set up related
442	   connections for unconfirmed conns.  But packet copies and
443	   REJECT will give spurious warnings here. */
444	/* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
445
446	/* No external references means noone else could have
447	   confirmed us. */
448	NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
449	DEBUGP("Confirming conntrack %p\n", ct);
450
451	write_lock_bh(&nf_conntrack_lock);
452
453	/* See if there's one in the list already, including reverse:
454	   NAT could have grabbed it without realizing, since we're
455	   not in the hash.  If there is, we lost race. */
456	list_for_each_entry(h, &nf_conntrack_hash[hash], list)
457		if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
458				      &h->tuple))
459			goto out;
460	list_for_each_entry(h, &nf_conntrack_hash[repl_hash], list)
461		if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
462				      &h->tuple))
463			goto out;
464
465	/* Remove from unconfirmed list */
466	list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
467
468	__nf_conntrack_hash_insert(ct, hash, repl_hash);
469	/* Timer relative to confirmation time, not original
470	   setting time, otherwise we'd get timer wrap in
471	   weird delay cases. */
472	ct->timeout.expires += jiffies;
473	add_timer(&ct->timeout);
474	atomic_inc(&ct->ct_general.use);
475	set_bit(IPS_CONFIRMED_BIT, &ct->status);
476	NF_CT_STAT_INC(insert);
477	write_unlock_bh(&nf_conntrack_lock);
478	help = nfct_help(ct);
479	if (help && help->helper)
480		nf_conntrack_event_cache(IPCT_HELPER, *pskb);
481#ifdef CONFIG_NF_NAT_NEEDED
482	if (test_bit(IPS_SRC_NAT_DONE_BIT, &ct->status) ||
483	    test_bit(IPS_DST_NAT_DONE_BIT, &ct->status))
484		nf_conntrack_event_cache(IPCT_NATINFO, *pskb);
485#endif
486	nf_conntrack_event_cache(master_ct(ct) ?
487				 IPCT_RELATED : IPCT_NEW, *pskb);
488	return NF_ACCEPT;
489
490out:
491	NF_CT_STAT_INC(insert_failed);
492	write_unlock_bh(&nf_conntrack_lock);
493	return NF_DROP;
494}
495
496/* Returns true if a connection correspondings to the tuple (required
497   for NAT). */
498int
499nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
500			 const struct nf_conn *ignored_conntrack)
501{
502	struct nf_conntrack_tuple_hash *h;
503
504	read_lock_bh(&nf_conntrack_lock);
505	h = __nf_conntrack_find(tuple, ignored_conntrack);
506	read_unlock_bh(&nf_conntrack_lock);
507
508	return h != NULL;
509}
510
511/* There's a small race here where we may free a just-assured
512   connection.  Too bad: we're in trouble anyway. */
513static int early_drop(struct list_head *chain)
514{
515	/* Traverse backwards: gives us oldest, which is roughly LRU */
516	struct nf_conntrack_tuple_hash *h;
517	struct nf_conn *ct = NULL, *tmp;
518	int dropped = 0;
519
520	read_lock_bh(&nf_conntrack_lock);
521	list_for_each_entry_reverse(h, chain, list) {
522		tmp = nf_ct_tuplehash_to_ctrack(h);
523		if (!test_bit(IPS_ASSURED_BIT, &tmp->status)) {
524			ct = tmp;
525			atomic_inc(&ct->ct_general.use);
526			break;
527		}
528	}
529	read_unlock_bh(&nf_conntrack_lock);
530
531	if (!ct)
532		return dropped;
533
534	if (del_timer(&ct->timeout)) {
535		death_by_timeout((unsigned long)ct);
536		dropped = 1;
537		NF_CT_STAT_INC(early_drop);
538	}
539	nf_ct_put(ct);
540	return dropped;
541}
542
543static struct nf_conn *
544__nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
545		     const struct nf_conntrack_tuple *repl,
546		     const struct nf_conntrack_l3proto *l3proto)
547{
548	struct nf_conn *conntrack = NULL;
549	u_int32_t features = 0;
550	struct nf_conntrack_helper *helper;
551
552	if (unlikely(!nf_conntrack_hash_rnd_initted)) {
553		get_random_bytes(&nf_conntrack_hash_rnd, 4);
554		nf_conntrack_hash_rnd_initted = 1;
555	}
556
557	/* We don't want any race condition at early drop stage */
558	atomic_inc(&nf_conntrack_count);
559
560	if (nf_conntrack_max
561	    && atomic_read(&nf_conntrack_count) > nf_conntrack_max) {
562		unsigned int hash = hash_conntrack(orig);
563		/* Try dropping from this hash chain. */
564		if (!early_drop(&nf_conntrack_hash[hash])) {
565			atomic_dec(&nf_conntrack_count);
566			if (net_ratelimit())
567				printk(KERN_WARNING
568				       "nf_conntrack: table full, dropping"
569				       " packet.\n");
570			return ERR_PTR(-ENOMEM);
571		}
572	}
573
574	/*  find features needed by this conntrack. */
575	features = l3proto->get_features(orig);
576
577	/* FIXME: protect helper list per RCU */
578	read_lock_bh(&nf_conntrack_lock);
579	helper = __nf_ct_helper_find(repl);
580	if (helper)
581		features |= NF_CT_F_HELP;
582	read_unlock_bh(&nf_conntrack_lock);
583
584	DEBUGP("nf_conntrack_alloc: features=0x%x\n", features);
585
586	read_lock_bh(&nf_ct_cache_lock);
587
588	if (unlikely(!nf_ct_cache[features].use)) {
589		DEBUGP("nf_conntrack_alloc: not supported features = 0x%x\n",
590			features);
591		goto out;
592	}
593
594	conntrack = kmem_cache_alloc(nf_ct_cache[features].cachep, GFP_ATOMIC);
595	if (conntrack == NULL) {
596		DEBUGP("nf_conntrack_alloc: Can't alloc conntrack from cache\n");
597		goto out;
598	}
599
600	memset(conntrack, 0, nf_ct_cache[features].size);
601	conntrack->features = features;
602	atomic_set(&conntrack->ct_general.use, 1);
603	conntrack->ct_general.destroy = destroy_conntrack;
604	conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
605	conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
606	/* Don't set timer yet: wait for confirmation */
607	init_timer(&conntrack->timeout);
608	conntrack->timeout.data = (unsigned long)conntrack;
609	conntrack->timeout.function = death_by_timeout;
610	read_unlock_bh(&nf_ct_cache_lock);
611
612	return conntrack;
613out:
614	read_unlock_bh(&nf_ct_cache_lock);
615	atomic_dec(&nf_conntrack_count);
616	return conntrack;
617}
618
619struct nf_conn *nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
620				   const struct nf_conntrack_tuple *repl)
621{
622	struct nf_conntrack_l3proto *l3proto;
623
624	l3proto = __nf_ct_l3proto_find(orig->src.l3num);
625	return __nf_conntrack_alloc(orig, repl, l3proto);
626}
627
628void nf_conntrack_free(struct nf_conn *conntrack)
629{
630	u_int32_t features = conntrack->features;
631	NF_CT_ASSERT(features >= NF_CT_F_BASIC && features < NF_CT_F_NUM);
632	DEBUGP("nf_conntrack_free: features = 0x%x, conntrack=%p\n", features,
633	       conntrack);
634	kmem_cache_free(nf_ct_cache[features].cachep, conntrack);
635	atomic_dec(&nf_conntrack_count);
636}
637
638/* Allocate a new conntrack: we return -ENOMEM if classification
639   failed due to stress.  Otherwise it really is unclassifiable. */
640static struct nf_conntrack_tuple_hash *
641init_conntrack(const struct nf_conntrack_tuple *tuple,
642	       struct nf_conntrack_l3proto *l3proto,
643	       struct nf_conntrack_l4proto *l4proto,
644	       struct sk_buff *skb,
645	       unsigned int dataoff)
646{
647	struct nf_conn *conntrack;
648	struct nf_conntrack_tuple repl_tuple;
649	struct nf_conntrack_expect *exp;
650
651	if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
652		DEBUGP("Can't invert tuple.\n");
653		return NULL;
654	}
655
656	conntrack = __nf_conntrack_alloc(tuple, &repl_tuple, l3proto);
657	if (conntrack == NULL || IS_ERR(conntrack)) {
658		DEBUGP("Can't allocate conntrack.\n");
659		return (struct nf_conntrack_tuple_hash *)conntrack;
660	}
661
662	if (!l4proto->new(conntrack, skb, dataoff)) {
663		nf_conntrack_free(conntrack);
664		DEBUGP("init conntrack: can't track with proto module\n");
665		return NULL;
666	}
667
668	write_lock_bh(&nf_conntrack_lock);
669	exp = find_expectation(tuple);
670
671	if (exp) {
672		DEBUGP("conntrack: expectation arrives ct=%p exp=%p\n",
673			conntrack, exp);
674		/* Welcome, Mr. Bond.  We've been expecting you... */
675		__set_bit(IPS_EXPECTED_BIT, &conntrack->status);
676		conntrack->master = exp->master;
677#ifdef CONFIG_NF_CONNTRACK_MARK
678		conntrack->mark = exp->master->mark;
679#endif
680#ifdef CONFIG_NF_CONNTRACK_SECMARK
681		conntrack->secmark = exp->master->secmark;
682#endif
683		nf_conntrack_get(&conntrack->master->ct_general);
684		NF_CT_STAT_INC(expect_new);
685	} else {
686		struct nf_conn_help *help = nfct_help(conntrack);
687
688		if (help)
689			help->helper = __nf_ct_helper_find(&repl_tuple);
690		NF_CT_STAT_INC(new);
691	}
692
693	/* Overload tuple linked list to put us in unconfirmed list. */
694	list_add(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL].list, &unconfirmed);
695
696	write_unlock_bh(&nf_conntrack_lock);
697
698	if (exp) {
699		if (exp->expectfn)
700			exp->expectfn(conntrack, exp);
701		nf_conntrack_expect_put(exp);
702	}
703
704	return &conntrack->tuplehash[IP_CT_DIR_ORIGINAL];
705}
706
707/* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
708static inline struct nf_conn *
709resolve_normal_ct(struct sk_buff *skb,
710		  unsigned int dataoff,
711		  u_int16_t l3num,
712		  u_int8_t protonum,
713		  struct nf_conntrack_l3proto *l3proto,
714		  struct nf_conntrack_l4proto *l4proto,
715		  int *set_reply,
716		  enum ip_conntrack_info *ctinfo)
717{
718	struct nf_conntrack_tuple tuple;
719	struct nf_conntrack_tuple_hash *h;
720	struct nf_conn *ct;
721
722	if (!nf_ct_get_tuple(skb, (unsigned int)(skb->nh.raw - skb->data),
723			     dataoff, l3num, protonum, &tuple, l3proto,
724			     l4proto)) {
725		DEBUGP("resolve_normal_ct: Can't get tuple\n");
726		return NULL;
727	}
728
729	/* look for tuple match */
730	h = nf_conntrack_find_get(&tuple, NULL);
731	if (!h) {
732		h = init_conntrack(&tuple, l3proto, l4proto, skb, dataoff);
733		if (!h)
734			return NULL;
735		if (IS_ERR(h))
736			return (void *)h;
737	}
738	ct = nf_ct_tuplehash_to_ctrack(h);
739
740	/* It exists; we have (non-exclusive) reference. */
741	if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
742		*ctinfo = IP_CT_ESTABLISHED + IP_CT_IS_REPLY;
743		/* Please set reply bit if this packet OK */
744		*set_reply = 1;
745	} else {
746		/* Once we've had two way comms, always ESTABLISHED. */
747		if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
748			DEBUGP("nf_conntrack_in: normal packet for %p\n", ct);
749			*ctinfo = IP_CT_ESTABLISHED;
750		} else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
751			DEBUGP("nf_conntrack_in: related packet for %p\n", ct);
752			*ctinfo = IP_CT_RELATED;
753		} else {
754			DEBUGP("nf_conntrack_in: new packet for %p\n", ct);
755			*ctinfo = IP_CT_NEW;
756		}
757		*set_reply = 0;
758	}
759	skb->nfct = &ct->ct_general;
760	skb->nfctinfo = *ctinfo;
761	return ct;
762}
763
764unsigned int
765nf_conntrack_in(int pf, unsigned int hooknum, struct sk_buff **pskb)
766{
767	struct nf_conn *ct;
768	enum ip_conntrack_info ctinfo;
769	struct nf_conntrack_l3proto *l3proto;
770	struct nf_conntrack_l4proto *l4proto;
771	unsigned int dataoff;
772	u_int8_t protonum;
773	int set_reply = 0;
774	int ret;
775
776	/* Previously seen (loopback or untracked)?  Ignore. */
777	if ((*pskb)->nfct) {
778		NF_CT_STAT_INC(ignore);
779		return NF_ACCEPT;
780	}
781
782	l3proto = __nf_ct_l3proto_find((u_int16_t)pf);
783	if ((ret = l3proto->prepare(pskb, hooknum, &dataoff, &protonum)) <= 0) {
784		DEBUGP("not prepared to track yet or error occured\n");
785		return -ret;
786	}
787
788	l4proto = __nf_ct_l4proto_find((u_int16_t)pf, protonum);
789
790	/* It may be an special packet, error, unclean...
791	 * inverse of the return code tells to the netfilter
792	 * core what to do with the packet. */
793	if (l4proto->error != NULL &&
794	    (ret = l4proto->error(*pskb, dataoff, &ctinfo, pf, hooknum)) <= 0) {
795		NF_CT_STAT_INC(error);
796		NF_CT_STAT_INC(invalid);
797		return -ret;
798	}
799
800	ct = resolve_normal_ct(*pskb, dataoff, pf, protonum, l3proto, l4proto,
801			       &set_reply, &ctinfo);
802	if (!ct) {
803		/* Not valid part of a connection */
804		NF_CT_STAT_INC(invalid);
805		return NF_ACCEPT;
806	}
807
808	if (IS_ERR(ct)) {
809		/* Too stressed to deal. */
810		NF_CT_STAT_INC(drop);
811		return NF_DROP;
812	}
813
814	NF_CT_ASSERT((*pskb)->nfct);
815
816	ret = l4proto->packet(ct, *pskb, dataoff, ctinfo, pf, hooknum);
817	if (ret < 0) {
818		/* Invalid: inverse of the return code tells
819		 * the netfilter core what to do */
820		DEBUGP("nf_conntrack_in: Can't track with proto module\n");
821		nf_conntrack_put((*pskb)->nfct);
822		(*pskb)->nfct = NULL;
823		NF_CT_STAT_INC(invalid);
824		return -ret;
825	}
826
827	if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
828		nf_conntrack_event_cache(IPCT_STATUS, *pskb);
829
830	return ret;
831}
832
833int nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
834			 const struct nf_conntrack_tuple *orig)
835{
836	return nf_ct_invert_tuple(inverse, orig,
837				  __nf_ct_l3proto_find(orig->src.l3num),
838				  __nf_ct_l4proto_find(orig->src.l3num,
839						     orig->dst.protonum));
840}
841
842/* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
843void __nf_ct_refresh_acct(struct nf_conn *ct,
844			  enum ip_conntrack_info ctinfo,
845			  const struct sk_buff *skb,
846			  unsigned long extra_jiffies,
847			  int do_acct)
848{
849	int event = 0;
850
851	NF_CT_ASSERT(ct->timeout.data == (unsigned long)ct);
852	NF_CT_ASSERT(skb);
853
854	write_lock_bh(&nf_conntrack_lock);
855
856	/* Only update if this is not a fixed timeout */
857	if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status)) {
858		write_unlock_bh(&nf_conntrack_lock);
859		return;
860	}
861
862	/* If not in hash table, timer will not be active yet */
863	if (!nf_ct_is_confirmed(ct)) {
864		ct->timeout.expires = extra_jiffies;
865		event = IPCT_REFRESH;
866	} else {
867		unsigned long newtime = jiffies + extra_jiffies;
868
869		/* Only update the timeout if the new timeout is at least
870		   HZ jiffies from the old timeout. Need del_timer for race
871		   avoidance (may already be dying). */
872		if (newtime - ct->timeout.expires >= HZ
873		    && del_timer(&ct->timeout)) {
874			ct->timeout.expires = newtime;
875			add_timer(&ct->timeout);
876			event = IPCT_REFRESH;
877		}
878	}
879
880#ifdef CONFIG_NF_CT_ACCT
881	if (do_acct) {
882		ct->counters[CTINFO2DIR(ctinfo)].packets++;
883		ct->counters[CTINFO2DIR(ctinfo)].bytes +=
884			skb->len - (unsigned int)(skb->nh.raw - skb->data);
885
886		if ((ct->counters[CTINFO2DIR(ctinfo)].packets & 0x80000000)
887		    || (ct->counters[CTINFO2DIR(ctinfo)].bytes & 0x80000000))
888			event |= IPCT_COUNTER_FILLING;
889	}
890#endif
891
892	write_unlock_bh(&nf_conntrack_lock);
893
894	/* must be unlocked when calling event cache */
895	if (event)
896		nf_conntrack_event_cache(event, skb);
897}
898
899#if defined(CONFIG_NF_CT_NETLINK) || \
900    defined(CONFIG_NF_CT_NETLINK_MODULE)
901
902#include <linux/netfilter/nfnetlink.h>
903#include <linux/netfilter/nfnetlink_conntrack.h>
904#include <linux/mutex.h>
905
906
907/* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
908 * in ip_conntrack_core, since we don't want the protocols to autoload
909 * or depend on ctnetlink */
910int nf_ct_port_tuple_to_nfattr(struct sk_buff *skb,
911			       const struct nf_conntrack_tuple *tuple)
912{
913	NFA_PUT(skb, CTA_PROTO_SRC_PORT, sizeof(u_int16_t),
914		&tuple->src.u.tcp.port);
915	NFA_PUT(skb, CTA_PROTO_DST_PORT, sizeof(u_int16_t),
916		&tuple->dst.u.tcp.port);
917	return 0;
918
919nfattr_failure:
920	return -1;
921}
922
923static const size_t cta_min_proto[CTA_PROTO_MAX] = {
924	[CTA_PROTO_SRC_PORT-1]  = sizeof(u_int16_t),
925	[CTA_PROTO_DST_PORT-1]  = sizeof(u_int16_t)
926};
927
928int nf_ct_port_nfattr_to_tuple(struct nfattr *tb[],
929			       struct nf_conntrack_tuple *t)
930{
931	if (!tb[CTA_PROTO_SRC_PORT-1] || !tb[CTA_PROTO_DST_PORT-1])
932		return -EINVAL;
933
934	if (nfattr_bad_size(tb, CTA_PROTO_MAX, cta_min_proto))
935		return -EINVAL;
936
937	t->src.u.tcp.port =
938		*(u_int16_t *)NFA_DATA(tb[CTA_PROTO_SRC_PORT-1]);
939	t->dst.u.tcp.port =
940		*(u_int16_t *)NFA_DATA(tb[CTA_PROTO_DST_PORT-1]);
941
942	return 0;
943}
944#endif
945
946/* Used by ipt_REJECT and ip6t_REJECT. */
947void __nf_conntrack_attach(struct sk_buff *nskb, struct sk_buff *skb)
948{
949	struct nf_conn *ct;
950	enum ip_conntrack_info ctinfo;
951
952	/* This ICMP is in reverse direction to the packet which caused it */
953	ct = nf_ct_get(skb, &ctinfo);
954	if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
955		ctinfo = IP_CT_RELATED + IP_CT_IS_REPLY;
956	else
957		ctinfo = IP_CT_RELATED;
958
959	/* Attach to new skbuff, and increment count */
960	nskb->nfct = &ct->ct_general;
961	nskb->nfctinfo = ctinfo;
962	nf_conntrack_get(nskb->nfct);
963}
964
965static inline int
966do_iter(const struct nf_conntrack_tuple_hash *i,
967	int (*iter)(struct nf_conn *i, void *data),
968	void *data)
969{
970	return iter(nf_ct_tuplehash_to_ctrack(i), data);
971}
972
973/* Bring out ya dead! */
974static struct nf_conn *
975get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
976		void *data, unsigned int *bucket)
977{
978	struct nf_conntrack_tuple_hash *h;
979	struct nf_conn *ct;
980
981	write_lock_bh(&nf_conntrack_lock);
982	for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
983		list_for_each_entry(h, &nf_conntrack_hash[*bucket], list) {
984			ct = nf_ct_tuplehash_to_ctrack(h);
985			if (iter(ct, data))
986				goto found;
987		}
988 	}
989	list_for_each_entry(h, &unconfirmed, list) {
990		ct = nf_ct_tuplehash_to_ctrack(h);
991		if (iter(ct, data))
992			goto found;
993	}
994	write_unlock_bh(&nf_conntrack_lock);
995	return NULL;
996found:
997	atomic_inc(&ct->ct_general.use);
998	write_unlock_bh(&nf_conntrack_lock);
999	return ct;
1000}
1001
1002void
1003nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data), void *data)
1004{
1005	struct nf_conn *ct;
1006	unsigned int bucket = 0;
1007
1008	while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1009		/* Time to push up daises... */
1010		if (del_timer(&ct->timeout))
1011			death_by_timeout((unsigned long)ct);
1012		/* ... else the timer will get him soon. */
1013
1014		nf_ct_put(ct);
1015	}
1016}
1017
1018static int kill_all(struct nf_conn *i, void *data)
1019{
1020	return 1;
1021}
1022
1023static void free_conntrack_hash(struct list_head *hash, int vmalloced, int size)
1024{
1025	if (vmalloced)
1026		vfree(hash);
1027	else
1028		free_pages((unsigned long)hash,
1029			   get_order(sizeof(struct list_head) * size));
1030}
1031
1032void nf_conntrack_flush()
1033{
1034	nf_ct_iterate_cleanup(kill_all, NULL);
1035}
1036
1037/* Mishearing the voices in his head, our hero wonders how he's
1038   supposed to kill the mall. */
1039void nf_conntrack_cleanup(void)
1040{
1041	int i;
1042
1043	ip_ct_attach = NULL;
1044
1045	/* This makes sure all current packets have passed through
1046	   netfilter framework.  Roll on, two-stage module
1047	   delete... */
1048	synchronize_net();
1049
1050	nf_ct_event_cache_flush();
1051 i_see_dead_people:
1052	nf_conntrack_flush();
1053	if (atomic_read(&nf_conntrack_count) != 0) {
1054		schedule();
1055		goto i_see_dead_people;
1056	}
1057	/* wait until all references to nf_conntrack_untracked are dropped */
1058	while (atomic_read(&nf_conntrack_untracked.ct_general.use) > 1)
1059		schedule();
1060
1061	for (i = 0; i < NF_CT_F_NUM; i++) {
1062		if (nf_ct_cache[i].use == 0)
1063			continue;
1064
1065		NF_CT_ASSERT(nf_ct_cache[i].use == 1);
1066		nf_ct_cache[i].use = 1;
1067		nf_conntrack_unregister_cache(i);
1068	}
1069	kmem_cache_destroy(nf_conntrack_expect_cachep);
1070	free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1071			    nf_conntrack_htable_size);
1072
1073	/* free l3proto protocol tables */
1074	for (i = 0; i < PF_MAX; i++)
1075		if (nf_ct_protos[i]) {
1076			kfree(nf_ct_protos[i]);
1077			nf_ct_protos[i] = NULL;
1078		}
1079}
1080
1081static struct list_head *alloc_hashtable(int size, int *vmalloced)
1082{
1083	struct list_head *hash;
1084	unsigned int i;
1085
1086	*vmalloced = 0;
1087	hash = (void*)__get_free_pages(GFP_KERNEL,
1088				       get_order(sizeof(struct list_head)
1089						 * size));
1090	if (!hash) {
1091		*vmalloced = 1;
1092		printk(KERN_WARNING "nf_conntrack: falling back to vmalloc.\n");
1093		hash = vmalloc(sizeof(struct list_head) * size);
1094	}
1095
1096	if (hash)
1097		for (i = 0; i < size; i++)
1098			INIT_LIST_HEAD(&hash[i]);
1099
1100	return hash;
1101}
1102
1103int set_hashsize(const char *val, struct kernel_param *kp)
1104{
1105	int i, bucket, hashsize, vmalloced;
1106	int old_vmalloced, old_size;
1107	int rnd;
1108	struct list_head *hash, *old_hash;
1109	struct nf_conntrack_tuple_hash *h;
1110
1111	/* On boot, we can set this without any fancy locking. */
1112	if (!nf_conntrack_htable_size)
1113		return param_set_uint(val, kp);
1114
1115	hashsize = simple_strtol(val, NULL, 0);
1116	if (!hashsize)
1117		return -EINVAL;
1118
1119	hash = alloc_hashtable(hashsize, &vmalloced);
1120	if (!hash)
1121		return -ENOMEM;
1122
1123	/* We have to rehahs for the new table anyway, so we also can
1124	 * use a newrandom seed */
1125	get_random_bytes(&rnd, 4);
1126
1127	write_lock_bh(&nf_conntrack_lock);
1128	for (i = 0; i < nf_conntrack_htable_size; i++) {
1129		while (!list_empty(&nf_conntrack_hash[i])) {
1130			h = list_entry(nf_conntrack_hash[i].next,
1131				       struct nf_conntrack_tuple_hash, list);
1132			list_del(&h->list);
1133			bucket = __hash_conntrack(&h->tuple, hashsize, rnd);
1134			list_add_tail(&h->list, &hash[bucket]);
1135		}
1136	}
1137	old_size = nf_conntrack_htable_size;
1138	old_vmalloced = nf_conntrack_vmalloc;
1139	old_hash = nf_conntrack_hash;
1140
1141	nf_conntrack_htable_size = hashsize;
1142	nf_conntrack_vmalloc = vmalloced;
1143	nf_conntrack_hash = hash;
1144	nf_conntrack_hash_rnd = rnd;
1145	write_unlock_bh(&nf_conntrack_lock);
1146
1147	free_conntrack_hash(old_hash, old_vmalloced, old_size);
1148	return 0;
1149}
1150
1151module_param_call(hashsize, set_hashsize, param_get_uint,
1152		  &nf_conntrack_htable_size, 0600);
1153
1154int __init nf_conntrack_init(void)
1155{
1156	unsigned int i;
1157	int ret;
1158
1159	/* Idea from tcp.c: use 1/16384 of memory.  On i386: 32MB
1160	 * machine has 256 buckets.  >= 1GB machines have 8192 buckets. */
1161	if (!nf_conntrack_htable_size) {
1162		nf_conntrack_htable_size
1163			= (((num_physpages << PAGE_SHIFT) / 16384)
1164			   / sizeof(struct list_head));
1165		if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
1166			nf_conntrack_htable_size = 8192;
1167		if (nf_conntrack_htable_size < 16)
1168			nf_conntrack_htable_size = 16;
1169	}
1170	nf_conntrack_max = 8 * nf_conntrack_htable_size;
1171
1172	printk("nf_conntrack version %s (%u buckets, %d max)\n",
1173	       NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1174	       nf_conntrack_max);
1175
1176	nf_conntrack_hash = alloc_hashtable(nf_conntrack_htable_size,
1177					    &nf_conntrack_vmalloc);
1178	if (!nf_conntrack_hash) {
1179		printk(KERN_ERR "Unable to create nf_conntrack_hash\n");
1180		goto err_out;
1181	}
1182
1183	ret = nf_conntrack_register_cache(NF_CT_F_BASIC, "nf_conntrack:basic",
1184					  sizeof(struct nf_conn));
1185	if (ret < 0) {
1186		printk(KERN_ERR "Unable to create nf_conn slab cache\n");
1187		goto err_free_hash;
1188	}
1189
1190	nf_conntrack_expect_cachep = kmem_cache_create("nf_conntrack_expect",
1191					sizeof(struct nf_conntrack_expect),
1192					0, 0, NULL, NULL);
1193	if (!nf_conntrack_expect_cachep) {
1194		printk(KERN_ERR "Unable to create nf_expect slab cache\n");
1195		goto err_free_conntrack_slab;
1196	}
1197
1198	/* Don't NEED lock here, but good form anyway. */
1199	write_lock_bh(&nf_conntrack_lock);
1200        for (i = 0; i < AF_MAX; i++)
1201		nf_ct_l3protos[i] = &nf_conntrack_l3proto_generic;
1202        write_unlock_bh(&nf_conntrack_lock);
1203
1204	/* For use by REJECT target */
1205	ip_ct_attach = __nf_conntrack_attach;
1206
1207	/* Set up fake conntrack:
1208	    - to never be deleted, not in any hashes */
1209	atomic_set(&nf_conntrack_untracked.ct_general.use, 1);
1210	/*  - and look it like as a confirmed connection */
1211	set_bit(IPS_CONFIRMED_BIT, &nf_conntrack_untracked.status);
1212
1213	return ret;
1214
1215err_free_conntrack_slab:
1216	nf_conntrack_unregister_cache(NF_CT_F_BASIC);
1217err_free_hash:
1218	free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1219			    nf_conntrack_htable_size);
1220err_out:
1221	return -ENOMEM;
1222}
1223