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
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>
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.
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.
29 * Derived from net/ipv4/netfilter/ip_conntrack_core.c
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>
50 /* This rwlock protects the main hash table, protocol/helper/expected
51 registrations, conntrack timers*/
52 #define ASSERT_READ_LOCK(x)
53 #define ASSERT_WRITE_LOCK(x)
55 #include <net/netfilter/nf_conntrack.h>
56 #include <net/netfilter/nf_conntrack_l3proto.h>
57 #include <net/netfilter/nf_conntrack_protocol.h>
58 #include <net/netfilter/nf_conntrack_expect.h>
59 #include <net/netfilter/nf_conntrack_helper.h>
60 #include <net/netfilter/nf_conntrack_core.h>
62 #define NF_CONNTRACK_VERSION "0.5.0"
67 #define DEBUGP(format, args...)
70 DEFINE_RWLOCK(nf_conntrack_lock);
72 /* nf_conntrack_standalone needs this */
73 atomic_t nf_conntrack_count = ATOMIC_INIT(0);
75 void (*nf_conntrack_destroyed)(struct nf_conn *conntrack) = NULL;
76 struct nf_conntrack_protocol **nf_ct_protos[PF_MAX] __read_mostly;
77 struct nf_conntrack_l3proto *nf_ct_l3protos[PF_MAX] __read_mostly;
78 unsigned int nf_conntrack_htable_size __read_mostly = 0;
79 int nf_conntrack_max __read_mostly;
80 struct list_head *nf_conntrack_hash __read_mostly;
81 struct nf_conn nf_conntrack_untracked;
82 unsigned int nf_ct_log_invalid __read_mostly;
83 LIST_HEAD(unconfirmed);
84 static int nf_conntrack_vmalloc __read_mostly;
86 static unsigned int nf_conntrack_next_id;
88 DEFINE_PER_CPU(struct ip_conntrack_stat, nf_conntrack_stat);
89 EXPORT_PER_CPU_SYMBOL(nf_conntrack_stat);
92 * This scheme offers various size of "struct nf_conn" dependent on
93 * features(helper, nat, ...)
96 #define NF_CT_FEATURES_NAMELEN 256
98 /* name of slab cache. printed in /proc/slabinfo */
101 /* size of slab cache */
104 /* slab cache pointer */
105 kmem_cache_t *cachep;
107 /* allocated slab cache + modules which uses this slab cache */
110 } nf_ct_cache[NF_CT_F_NUM];
112 /* protect members of nf_ct_cache except of "use" */
113 DEFINE_RWLOCK(nf_ct_cache_lock);
115 /* This avoids calling kmem_cache_create() with same name simultaneously */
116 static DEFINE_MUTEX(nf_ct_cache_mutex);
118 extern struct nf_conntrack_protocol nf_conntrack_generic_protocol;
119 struct nf_conntrack_protocol *
120 __nf_ct_proto_find(u_int16_t l3proto, u_int8_t protocol)
122 if (unlikely(l3proto >= AF_MAX || nf_ct_protos[l3proto] == NULL))
123 return &nf_conntrack_generic_protocol;
125 return nf_ct_protos[l3proto][protocol];
128 /* this is guaranteed to always return a valid protocol helper, since
129 * it falls back to generic_protocol */
130 struct nf_conntrack_protocol *
131 nf_ct_proto_find_get(u_int16_t l3proto, u_int8_t protocol)
133 struct nf_conntrack_protocol *p;
136 p = __nf_ct_proto_find(l3proto, protocol);
137 if (!try_module_get(p->me))
138 p = &nf_conntrack_generic_protocol;
144 void nf_ct_proto_put(struct nf_conntrack_protocol *p)
149 struct nf_conntrack_l3proto *
150 nf_ct_l3proto_find_get(u_int16_t l3proto)
152 struct nf_conntrack_l3proto *p;
155 p = __nf_ct_l3proto_find(l3proto);
156 if (!try_module_get(p->me))
157 p = &nf_conntrack_generic_l3proto;
163 void nf_ct_l3proto_put(struct nf_conntrack_l3proto *p)
169 nf_ct_l3proto_try_module_get(unsigned short l3proto)
172 struct nf_conntrack_l3proto *p;
174 retry: p = nf_ct_l3proto_find_get(l3proto);
175 if (p == &nf_conntrack_generic_l3proto) {
176 ret = request_module("nf_conntrack-%d", l3proto);
186 void nf_ct_l3proto_module_put(unsigned short l3proto)
188 struct nf_conntrack_l3proto *p;
191 p = __nf_ct_l3proto_find(l3proto);
197 static int nf_conntrack_hash_rnd_initted;
198 static unsigned int nf_conntrack_hash_rnd;
200 static u_int32_t __hash_conntrack(const struct nf_conntrack_tuple *tuple,
201 unsigned int size, unsigned int rnd)
204 a = jhash((void *)tuple->src.u3.all, sizeof(tuple->src.u3.all),
205 ((tuple->src.l3num) << 16) | tuple->dst.protonum);
206 b = jhash((void *)tuple->dst.u3.all, sizeof(tuple->dst.u3.all),
207 (tuple->src.u.all << 16) | tuple->dst.u.all);
209 return jhash_2words(a, b, rnd) % size;
212 static inline u_int32_t hash_conntrack(const struct nf_conntrack_tuple *tuple)
214 return __hash_conntrack(tuple, nf_conntrack_htable_size,
215 nf_conntrack_hash_rnd);
218 int nf_conntrack_register_cache(u_int32_t features, const char *name,
223 kmem_cache_t *cachep;
225 DEBUGP("nf_conntrack_register_cache: features=0x%x, name=%s, size=%d\n",
226 features, name, size);
228 if (features < NF_CT_F_BASIC || features >= NF_CT_F_NUM) {
229 DEBUGP("nf_conntrack_register_cache: invalid features.: 0x%x\n",
234 mutex_lock(&nf_ct_cache_mutex);
236 write_lock_bh(&nf_ct_cache_lock);
237 /* e.g: multiple helpers are loaded */
238 if (nf_ct_cache[features].use > 0) {
239 DEBUGP("nf_conntrack_register_cache: already resisterd.\n");
240 if ((!strncmp(nf_ct_cache[features].name, name,
241 NF_CT_FEATURES_NAMELEN))
242 && nf_ct_cache[features].size == size) {
243 DEBUGP("nf_conntrack_register_cache: reusing.\n");
244 nf_ct_cache[features].use++;
249 write_unlock_bh(&nf_ct_cache_lock);
250 mutex_unlock(&nf_ct_cache_mutex);
253 write_unlock_bh(&nf_ct_cache_lock);
256 * The memory space for name of slab cache must be alive until
257 * cache is destroyed.
259 cache_name = kmalloc(sizeof(char)*NF_CT_FEATURES_NAMELEN, GFP_ATOMIC);
260 if (cache_name == NULL) {
261 DEBUGP("nf_conntrack_register_cache: can't alloc cache_name\n");
266 if (strlcpy(cache_name, name, NF_CT_FEATURES_NAMELEN)
267 >= NF_CT_FEATURES_NAMELEN) {
268 printk("nf_conntrack_register_cache: name too long\n");
273 cachep = kmem_cache_create(cache_name, size, 0, 0,
276 printk("nf_conntrack_register_cache: Can't create slab cache "
277 "for the features = 0x%x\n", features);
282 write_lock_bh(&nf_ct_cache_lock);
283 nf_ct_cache[features].use = 1;
284 nf_ct_cache[features].size = size;
285 nf_ct_cache[features].cachep = cachep;
286 nf_ct_cache[features].name = cache_name;
287 write_unlock_bh(&nf_ct_cache_lock);
294 mutex_unlock(&nf_ct_cache_mutex);
298 /* FIXME: In the current, only nf_conntrack_cleanup() can call this function. */
299 void nf_conntrack_unregister_cache(u_int32_t features)
301 kmem_cache_t *cachep;
305 * This assures that kmem_cache_create() isn't called before destroying
308 DEBUGP("nf_conntrack_unregister_cache: 0x%04x\n", features);
309 mutex_lock(&nf_ct_cache_mutex);
311 write_lock_bh(&nf_ct_cache_lock);
312 if (--nf_ct_cache[features].use > 0) {
313 write_unlock_bh(&nf_ct_cache_lock);
314 mutex_unlock(&nf_ct_cache_mutex);
317 cachep = nf_ct_cache[features].cachep;
318 name = nf_ct_cache[features].name;
319 nf_ct_cache[features].cachep = NULL;
320 nf_ct_cache[features].name = NULL;
321 nf_ct_cache[features].size = 0;
322 write_unlock_bh(&nf_ct_cache_lock);
326 kmem_cache_destroy(cachep);
329 mutex_unlock(&nf_ct_cache_mutex);
333 nf_ct_get_tuple(const struct sk_buff *skb,
335 unsigned int dataoff,
338 struct nf_conntrack_tuple *tuple,
339 const struct nf_conntrack_l3proto *l3proto,
340 const struct nf_conntrack_protocol *protocol)
342 NF_CT_TUPLE_U_BLANK(tuple);
344 tuple->src.l3num = l3num;
345 if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
348 tuple->dst.protonum = protonum;
349 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
351 return protocol->pkt_to_tuple(skb, dataoff, tuple);
355 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
356 const struct nf_conntrack_tuple *orig,
357 const struct nf_conntrack_l3proto *l3proto,
358 const struct nf_conntrack_protocol *protocol)
360 NF_CT_TUPLE_U_BLANK(inverse);
362 inverse->src.l3num = orig->src.l3num;
363 if (l3proto->invert_tuple(inverse, orig) == 0)
366 inverse->dst.dir = !orig->dst.dir;
368 inverse->dst.protonum = orig->dst.protonum;
369 return protocol->invert_tuple(inverse, orig);
373 clean_from_lists(struct nf_conn *ct)
375 DEBUGP("clean_from_lists(%p)\n", ct);
376 ASSERT_WRITE_LOCK(&nf_conntrack_lock);
377 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
378 list_del(&ct->tuplehash[IP_CT_DIR_REPLY].list);
380 /* Destroy all pending expectations */
381 nf_ct_remove_expectations(ct);
385 destroy_conntrack(struct nf_conntrack *nfct)
387 struct nf_conn *ct = (struct nf_conn *)nfct;
388 struct nf_conntrack_l3proto *l3proto;
389 struct nf_conntrack_protocol *proto;
391 DEBUGP("destroy_conntrack(%p)\n", ct);
392 NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
393 NF_CT_ASSERT(!timer_pending(&ct->timeout));
395 nf_conntrack_event(IPCT_DESTROY, ct);
396 set_bit(IPS_DYING_BIT, &ct->status);
398 /* To make sure we don't get any weird locking issues here:
399 * destroy_conntrack() MUST NOT be called with a write lock
400 * to nf_conntrack_lock!!! -HW */
401 l3proto = __nf_ct_l3proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num);
402 if (l3proto && l3proto->destroy)
403 l3proto->destroy(ct);
405 proto = __nf_ct_proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num, ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.protonum);
406 if (proto && proto->destroy)
409 if (nf_conntrack_destroyed)
410 nf_conntrack_destroyed(ct);
412 write_lock_bh(&nf_conntrack_lock);
413 /* Expectations will have been removed in clean_from_lists,
414 * except TFTP can create an expectation on the first packet,
415 * before connection is in the list, so we need to clean here,
417 nf_ct_remove_expectations(ct);
419 /* We overload first tuple to link into unconfirmed list. */
420 if (!nf_ct_is_confirmed(ct)) {
421 BUG_ON(list_empty(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list));
422 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
425 NF_CT_STAT_INC(delete);
426 write_unlock_bh(&nf_conntrack_lock);
429 nf_ct_put(ct->master);
431 DEBUGP("destroy_conntrack: returning ct=%p to slab\n", ct);
432 nf_conntrack_free(ct);
435 static void death_by_timeout(unsigned long ul_conntrack)
437 struct nf_conn *ct = (void *)ul_conntrack;
439 write_lock_bh(&nf_conntrack_lock);
440 /* Inside lock so preempt is disabled on module removal path.
441 * Otherwise we can get spurious warnings. */
442 NF_CT_STAT_INC(delete_list);
443 clean_from_lists(ct);
444 write_unlock_bh(&nf_conntrack_lock);
448 struct nf_conntrack_tuple_hash *
449 __nf_conntrack_find(const struct nf_conntrack_tuple *tuple,
450 const struct nf_conn *ignored_conntrack)
452 struct nf_conntrack_tuple_hash *h;
453 unsigned int hash = hash_conntrack(tuple);
455 ASSERT_READ_LOCK(&nf_conntrack_lock);
456 list_for_each_entry(h, &nf_conntrack_hash[hash], list) {
457 if (nf_ct_tuplehash_to_ctrack(h) != ignored_conntrack &&
458 nf_ct_tuple_equal(tuple, &h->tuple)) {
459 NF_CT_STAT_INC(found);
462 NF_CT_STAT_INC(searched);
468 /* Find a connection corresponding to a tuple. */
469 struct nf_conntrack_tuple_hash *
470 nf_conntrack_find_get(const struct nf_conntrack_tuple *tuple,
471 const struct nf_conn *ignored_conntrack)
473 struct nf_conntrack_tuple_hash *h;
475 read_lock_bh(&nf_conntrack_lock);
476 h = __nf_conntrack_find(tuple, ignored_conntrack);
478 atomic_inc(&nf_ct_tuplehash_to_ctrack(h)->ct_general.use);
479 read_unlock_bh(&nf_conntrack_lock);
484 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
486 unsigned int repl_hash)
488 ct->id = ++nf_conntrack_next_id;
489 list_add(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list,
490 &nf_conntrack_hash[hash]);
491 list_add(&ct->tuplehash[IP_CT_DIR_REPLY].list,
492 &nf_conntrack_hash[repl_hash]);
495 void nf_conntrack_hash_insert(struct nf_conn *ct)
497 unsigned int hash, repl_hash;
499 hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
500 repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
502 write_lock_bh(&nf_conntrack_lock);
503 __nf_conntrack_hash_insert(ct, hash, repl_hash);
504 write_unlock_bh(&nf_conntrack_lock);
507 /* Confirm a connection given skb; places it in hash table */
509 __nf_conntrack_confirm(struct sk_buff **pskb)
511 unsigned int hash, repl_hash;
512 struct nf_conntrack_tuple_hash *h;
514 struct nf_conn_help *help;
515 enum ip_conntrack_info ctinfo;
517 ct = nf_ct_get(*pskb, &ctinfo);
519 /* ipt_REJECT uses nf_conntrack_attach to attach related
520 ICMP/TCP RST packets in other direction. Actual packet
521 which created connection will be IP_CT_NEW or for an
522 expected connection, IP_CT_RELATED. */
523 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
526 hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
527 repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
529 /* We're not in hash table, and we refuse to set up related
530 connections for unconfirmed conns. But packet copies and
531 REJECT will give spurious warnings here. */
532 /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
534 /* No external references means noone else could have
536 NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
537 DEBUGP("Confirming conntrack %p\n", ct);
539 write_lock_bh(&nf_conntrack_lock);
541 /* See if there's one in the list already, including reverse:
542 NAT could have grabbed it without realizing, since we're
543 not in the hash. If there is, we lost race. */
544 list_for_each_entry(h, &nf_conntrack_hash[hash], list)
545 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
548 list_for_each_entry(h, &nf_conntrack_hash[repl_hash], list)
549 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
553 /* Remove from unconfirmed list */
554 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
556 __nf_conntrack_hash_insert(ct, hash, repl_hash);
557 /* Timer relative to confirmation time, not original
558 setting time, otherwise we'd get timer wrap in
559 weird delay cases. */
560 ct->timeout.expires += jiffies;
561 add_timer(&ct->timeout);
562 atomic_inc(&ct->ct_general.use);
563 set_bit(IPS_CONFIRMED_BIT, &ct->status);
564 NF_CT_STAT_INC(insert);
565 write_unlock_bh(&nf_conntrack_lock);
566 help = nfct_help(ct);
567 if (help && help->helper)
568 nf_conntrack_event_cache(IPCT_HELPER, *pskb);
569 #ifdef CONFIG_NF_NAT_NEEDED
570 if (test_bit(IPS_SRC_NAT_DONE_BIT, &ct->status) ||
571 test_bit(IPS_DST_NAT_DONE_BIT, &ct->status))
572 nf_conntrack_event_cache(IPCT_NATINFO, *pskb);
574 nf_conntrack_event_cache(master_ct(ct) ?
575 IPCT_RELATED : IPCT_NEW, *pskb);
579 NF_CT_STAT_INC(insert_failed);
580 write_unlock_bh(&nf_conntrack_lock);
584 /* Returns true if a connection correspondings to the tuple (required
587 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
588 const struct nf_conn *ignored_conntrack)
590 struct nf_conntrack_tuple_hash *h;
592 read_lock_bh(&nf_conntrack_lock);
593 h = __nf_conntrack_find(tuple, ignored_conntrack);
594 read_unlock_bh(&nf_conntrack_lock);
599 /* There's a small race here where we may free a just-assured
600 connection. Too bad: we're in trouble anyway. */
601 static int early_drop(struct list_head *chain)
603 /* Traverse backwards: gives us oldest, which is roughly LRU */
604 struct nf_conntrack_tuple_hash *h;
605 struct nf_conn *ct = NULL, *tmp;
608 read_lock_bh(&nf_conntrack_lock);
609 list_for_each_entry_reverse(h, chain, list) {
610 tmp = nf_ct_tuplehash_to_ctrack(h);
611 if (!test_bit(IPS_ASSURED_BIT, &tmp->status)) {
613 atomic_inc(&ct->ct_general.use);
617 read_unlock_bh(&nf_conntrack_lock);
622 if (del_timer(&ct->timeout)) {
623 death_by_timeout((unsigned long)ct);
625 NF_CT_STAT_INC(early_drop);
631 static struct nf_conn *
632 __nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
633 const struct nf_conntrack_tuple *repl,
634 const struct nf_conntrack_l3proto *l3proto)
636 struct nf_conn *conntrack = NULL;
637 u_int32_t features = 0;
638 struct nf_conntrack_helper *helper;
640 if (unlikely(!nf_conntrack_hash_rnd_initted)) {
641 get_random_bytes(&nf_conntrack_hash_rnd, 4);
642 nf_conntrack_hash_rnd_initted = 1;
645 /* We don't want any race condition at early drop stage */
646 atomic_inc(&nf_conntrack_count);
649 && atomic_read(&nf_conntrack_count) > nf_conntrack_max) {
650 unsigned int hash = hash_conntrack(orig);
651 /* Try dropping from this hash chain. */
652 if (!early_drop(&nf_conntrack_hash[hash])) {
653 atomic_dec(&nf_conntrack_count);
656 "nf_conntrack: table full, dropping"
658 return ERR_PTR(-ENOMEM);
662 /* find features needed by this conntrack. */
663 features = l3proto->get_features(orig);
665 /* FIXME: protect helper list per RCU */
666 read_lock_bh(&nf_conntrack_lock);
667 helper = __nf_ct_helper_find(repl);
669 features |= NF_CT_F_HELP;
670 read_unlock_bh(&nf_conntrack_lock);
672 DEBUGP("nf_conntrack_alloc: features=0x%x\n", features);
674 read_lock_bh(&nf_ct_cache_lock);
676 if (unlikely(!nf_ct_cache[features].use)) {
677 DEBUGP("nf_conntrack_alloc: not supported features = 0x%x\n",
682 conntrack = kmem_cache_alloc(nf_ct_cache[features].cachep, GFP_ATOMIC);
683 if (conntrack == NULL) {
684 DEBUGP("nf_conntrack_alloc: Can't alloc conntrack from cache\n");
688 memset(conntrack, 0, nf_ct_cache[features].size);
689 conntrack->features = features;
690 atomic_set(&conntrack->ct_general.use, 1);
691 conntrack->ct_general.destroy = destroy_conntrack;
692 conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
693 conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
694 /* Don't set timer yet: wait for confirmation */
695 init_timer(&conntrack->timeout);
696 conntrack->timeout.data = (unsigned long)conntrack;
697 conntrack->timeout.function = death_by_timeout;
698 read_unlock_bh(&nf_ct_cache_lock);
702 read_unlock_bh(&nf_ct_cache_lock);
703 atomic_dec(&nf_conntrack_count);
707 struct nf_conn *nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
708 const struct nf_conntrack_tuple *repl)
710 struct nf_conntrack_l3proto *l3proto;
712 l3proto = __nf_ct_l3proto_find(orig->src.l3num);
713 return __nf_conntrack_alloc(orig, repl, l3proto);
716 void nf_conntrack_free(struct nf_conn *conntrack)
718 u_int32_t features = conntrack->features;
719 NF_CT_ASSERT(features >= NF_CT_F_BASIC && features < NF_CT_F_NUM);
720 DEBUGP("nf_conntrack_free: features = 0x%x, conntrack=%p\n", features,
722 kmem_cache_free(nf_ct_cache[features].cachep, conntrack);
723 atomic_dec(&nf_conntrack_count);
726 /* Allocate a new conntrack: we return -ENOMEM if classification
727 failed due to stress. Otherwise it really is unclassifiable. */
728 static struct nf_conntrack_tuple_hash *
729 init_conntrack(const struct nf_conntrack_tuple *tuple,
730 struct nf_conntrack_l3proto *l3proto,
731 struct nf_conntrack_protocol *protocol,
733 unsigned int dataoff)
735 struct nf_conn *conntrack;
736 struct nf_conntrack_tuple repl_tuple;
737 struct nf_conntrack_expect *exp;
739 if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, protocol)) {
740 DEBUGP("Can't invert tuple.\n");
744 conntrack = __nf_conntrack_alloc(tuple, &repl_tuple, l3proto);
745 if (conntrack == NULL || IS_ERR(conntrack)) {
746 DEBUGP("Can't allocate conntrack.\n");
747 return (struct nf_conntrack_tuple_hash *)conntrack;
750 if (!protocol->new(conntrack, skb, dataoff)) {
751 nf_conntrack_free(conntrack);
752 DEBUGP("init conntrack: can't track with proto module\n");
756 write_lock_bh(&nf_conntrack_lock);
757 exp = find_expectation(tuple);
760 DEBUGP("conntrack: expectation arrives ct=%p exp=%p\n",
762 /* Welcome, Mr. Bond. We've been expecting you... */
763 __set_bit(IPS_EXPECTED_BIT, &conntrack->status);
764 conntrack->master = exp->master;
765 #ifdef CONFIG_NF_CONNTRACK_MARK
766 conntrack->mark = exp->master->mark;
768 #ifdef CONFIG_NF_CONNTRACK_SECMARK
769 conntrack->secmark = exp->master->secmark;
771 nf_conntrack_get(&conntrack->master->ct_general);
772 NF_CT_STAT_INC(expect_new);
774 struct nf_conn_help *help = nfct_help(conntrack);
777 help->helper = __nf_ct_helper_find(&repl_tuple);
781 /* Overload tuple linked list to put us in unconfirmed list. */
782 list_add(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL].list, &unconfirmed);
784 write_unlock_bh(&nf_conntrack_lock);
788 exp->expectfn(conntrack, exp);
789 nf_conntrack_expect_put(exp);
792 return &conntrack->tuplehash[IP_CT_DIR_ORIGINAL];
795 /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
796 static inline struct nf_conn *
797 resolve_normal_ct(struct sk_buff *skb,
798 unsigned int dataoff,
801 struct nf_conntrack_l3proto *l3proto,
802 struct nf_conntrack_protocol *proto,
804 enum ip_conntrack_info *ctinfo)
806 struct nf_conntrack_tuple tuple;
807 struct nf_conntrack_tuple_hash *h;
810 if (!nf_ct_get_tuple(skb, (unsigned int)(skb->nh.raw - skb->data),
811 dataoff, l3num, protonum, &tuple, l3proto,
813 DEBUGP("resolve_normal_ct: Can't get tuple\n");
817 /* look for tuple match */
818 h = nf_conntrack_find_get(&tuple, NULL);
820 h = init_conntrack(&tuple, l3proto, proto, skb, dataoff);
826 ct = nf_ct_tuplehash_to_ctrack(h);
828 /* It exists; we have (non-exclusive) reference. */
829 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
830 *ctinfo = IP_CT_ESTABLISHED + IP_CT_IS_REPLY;
831 /* Please set reply bit if this packet OK */
834 /* Once we've had two way comms, always ESTABLISHED. */
835 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
836 DEBUGP("nf_conntrack_in: normal packet for %p\n", ct);
837 *ctinfo = IP_CT_ESTABLISHED;
838 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
839 DEBUGP("nf_conntrack_in: related packet for %p\n", ct);
840 *ctinfo = IP_CT_RELATED;
842 DEBUGP("nf_conntrack_in: new packet for %p\n", ct);
847 skb->nfct = &ct->ct_general;
848 skb->nfctinfo = *ctinfo;
853 nf_conntrack_in(int pf, unsigned int hooknum, struct sk_buff **pskb)
856 enum ip_conntrack_info ctinfo;
857 struct nf_conntrack_l3proto *l3proto;
858 struct nf_conntrack_protocol *proto;
859 unsigned int dataoff;
864 /* Previously seen (loopback or untracked)? Ignore. */
866 NF_CT_STAT_INC(ignore);
870 l3proto = __nf_ct_l3proto_find((u_int16_t)pf);
871 if ((ret = l3proto->prepare(pskb, hooknum, &dataoff, &protonum)) <= 0) {
872 DEBUGP("not prepared to track yet or error occured\n");
876 proto = __nf_ct_proto_find((u_int16_t)pf, protonum);
878 /* It may be an special packet, error, unclean...
879 * inverse of the return code tells to the netfilter
880 * core what to do with the packet. */
881 if (proto->error != NULL &&
882 (ret = proto->error(*pskb, dataoff, &ctinfo, pf, hooknum)) <= 0) {
883 NF_CT_STAT_INC(error);
884 NF_CT_STAT_INC(invalid);
888 ct = resolve_normal_ct(*pskb, dataoff, pf, protonum, l3proto, proto,
889 &set_reply, &ctinfo);
891 /* Not valid part of a connection */
892 NF_CT_STAT_INC(invalid);
897 /* Too stressed to deal. */
898 NF_CT_STAT_INC(drop);
902 NF_CT_ASSERT((*pskb)->nfct);
904 ret = proto->packet(ct, *pskb, dataoff, ctinfo, pf, hooknum);
906 /* Invalid: inverse of the return code tells
907 * the netfilter core what to do */
908 DEBUGP("nf_conntrack_in: Can't track with proto module\n");
909 nf_conntrack_put((*pskb)->nfct);
910 (*pskb)->nfct = NULL;
911 NF_CT_STAT_INC(invalid);
915 if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
916 nf_conntrack_event_cache(IPCT_STATUS, *pskb);
921 int nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
922 const struct nf_conntrack_tuple *orig)
924 return nf_ct_invert_tuple(inverse, orig,
925 __nf_ct_l3proto_find(orig->src.l3num),
926 __nf_ct_proto_find(orig->src.l3num,
927 orig->dst.protonum));
930 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
931 void __nf_ct_refresh_acct(struct nf_conn *ct,
932 enum ip_conntrack_info ctinfo,
933 const struct sk_buff *skb,
934 unsigned long extra_jiffies,
939 NF_CT_ASSERT(ct->timeout.data == (unsigned long)ct);
942 write_lock_bh(&nf_conntrack_lock);
944 /* Only update if this is not a fixed timeout */
945 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status)) {
946 write_unlock_bh(&nf_conntrack_lock);
950 /* If not in hash table, timer will not be active yet */
951 if (!nf_ct_is_confirmed(ct)) {
952 ct->timeout.expires = extra_jiffies;
953 event = IPCT_REFRESH;
955 /* Need del_timer for race avoidance (may already be dying). */
956 if (del_timer(&ct->timeout)) {
957 ct->timeout.expires = jiffies + extra_jiffies;
958 add_timer(&ct->timeout);
959 event = IPCT_REFRESH;
963 #ifdef CONFIG_NF_CT_ACCT
965 ct->counters[CTINFO2DIR(ctinfo)].packets++;
966 ct->counters[CTINFO2DIR(ctinfo)].bytes +=
967 skb->len - (unsigned int)(skb->nh.raw - skb->data);
968 if ((ct->counters[CTINFO2DIR(ctinfo)].packets & 0x80000000)
969 || (ct->counters[CTINFO2DIR(ctinfo)].bytes & 0x80000000))
970 event |= IPCT_COUNTER_FILLING;
974 write_unlock_bh(&nf_conntrack_lock);
976 /* must be unlocked when calling event cache */
978 nf_conntrack_event_cache(event, skb);
981 #if defined(CONFIG_NF_CT_NETLINK) || \
982 defined(CONFIG_NF_CT_NETLINK_MODULE)
984 #include <linux/netfilter/nfnetlink.h>
985 #include <linux/netfilter/nfnetlink_conntrack.h>
986 #include <linux/mutex.h>
989 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
990 * in ip_conntrack_core, since we don't want the protocols to autoload
991 * or depend on ctnetlink */
992 int nf_ct_port_tuple_to_nfattr(struct sk_buff *skb,
993 const struct nf_conntrack_tuple *tuple)
995 NFA_PUT(skb, CTA_PROTO_SRC_PORT, sizeof(u_int16_t),
996 &tuple->src.u.tcp.port);
997 NFA_PUT(skb, CTA_PROTO_DST_PORT, sizeof(u_int16_t),
998 &tuple->dst.u.tcp.port);
1005 static const size_t cta_min_proto[CTA_PROTO_MAX] = {
1006 [CTA_PROTO_SRC_PORT-1] = sizeof(u_int16_t),
1007 [CTA_PROTO_DST_PORT-1] = sizeof(u_int16_t)
1010 int nf_ct_port_nfattr_to_tuple(struct nfattr *tb[],
1011 struct nf_conntrack_tuple *t)
1013 if (!tb[CTA_PROTO_SRC_PORT-1] || !tb[CTA_PROTO_DST_PORT-1])
1016 if (nfattr_bad_size(tb, CTA_PROTO_MAX, cta_min_proto))
1020 *(u_int16_t *)NFA_DATA(tb[CTA_PROTO_SRC_PORT-1]);
1022 *(u_int16_t *)NFA_DATA(tb[CTA_PROTO_DST_PORT-1]);
1028 /* Used by ipt_REJECT and ip6t_REJECT. */
1029 void __nf_conntrack_attach(struct sk_buff *nskb, struct sk_buff *skb)
1032 enum ip_conntrack_info ctinfo;
1034 /* This ICMP is in reverse direction to the packet which caused it */
1035 ct = nf_ct_get(skb, &ctinfo);
1036 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1037 ctinfo = IP_CT_RELATED + IP_CT_IS_REPLY;
1039 ctinfo = IP_CT_RELATED;
1041 /* Attach to new skbuff, and increment count */
1042 nskb->nfct = &ct->ct_general;
1043 nskb->nfctinfo = ctinfo;
1044 nf_conntrack_get(nskb->nfct);
1048 do_iter(const struct nf_conntrack_tuple_hash *i,
1049 int (*iter)(struct nf_conn *i, void *data),
1052 return iter(nf_ct_tuplehash_to_ctrack(i), data);
1055 /* Bring out ya dead! */
1056 static struct nf_conn *
1057 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1058 void *data, unsigned int *bucket)
1060 struct nf_conntrack_tuple_hash *h;
1063 write_lock_bh(&nf_conntrack_lock);
1064 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1065 list_for_each_entry(h, &nf_conntrack_hash[*bucket], list) {
1066 ct = nf_ct_tuplehash_to_ctrack(h);
1071 list_for_each_entry(h, &unconfirmed, list) {
1072 ct = nf_ct_tuplehash_to_ctrack(h);
1076 write_unlock_bh(&nf_conntrack_lock);
1079 atomic_inc(&ct->ct_general.use);
1080 write_unlock_bh(&nf_conntrack_lock);
1085 nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data), void *data)
1088 unsigned int bucket = 0;
1090 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1091 /* Time to push up daises... */
1092 if (del_timer(&ct->timeout))
1093 death_by_timeout((unsigned long)ct);
1094 /* ... else the timer will get him soon. */
1100 static int kill_all(struct nf_conn *i, void *data)
1105 static void free_conntrack_hash(struct list_head *hash, int vmalloced, int size)
1110 free_pages((unsigned long)hash,
1111 get_order(sizeof(struct list_head) * size));
1114 void nf_conntrack_flush()
1116 nf_ct_iterate_cleanup(kill_all, NULL);
1119 /* Mishearing the voices in his head, our hero wonders how he's
1120 supposed to kill the mall. */
1121 void nf_conntrack_cleanup(void)
1125 ip_ct_attach = NULL;
1127 /* This makes sure all current packets have passed through
1128 netfilter framework. Roll on, two-stage module
1132 nf_ct_event_cache_flush();
1134 nf_conntrack_flush();
1135 if (atomic_read(&nf_conntrack_count) != 0) {
1137 goto i_see_dead_people;
1139 /* wait until all references to nf_conntrack_untracked are dropped */
1140 while (atomic_read(&nf_conntrack_untracked.ct_general.use) > 1)
1143 for (i = 0; i < NF_CT_F_NUM; i++) {
1144 if (nf_ct_cache[i].use == 0)
1147 NF_CT_ASSERT(nf_ct_cache[i].use == 1);
1148 nf_ct_cache[i].use = 1;
1149 nf_conntrack_unregister_cache(i);
1151 kmem_cache_destroy(nf_conntrack_expect_cachep);
1152 free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1153 nf_conntrack_htable_size);
1155 /* free l3proto protocol tables */
1156 for (i = 0; i < PF_MAX; i++)
1157 if (nf_ct_protos[i]) {
1158 kfree(nf_ct_protos[i]);
1159 nf_ct_protos[i] = NULL;
1163 static struct list_head *alloc_hashtable(int size, int *vmalloced)
1165 struct list_head *hash;
1169 hash = (void*)__get_free_pages(GFP_KERNEL,
1170 get_order(sizeof(struct list_head)
1174 printk(KERN_WARNING "nf_conntrack: falling back to vmalloc.\n");
1175 hash = vmalloc(sizeof(struct list_head) * size);
1179 for (i = 0; i < size; i++)
1180 INIT_LIST_HEAD(&hash[i]);
1185 int set_hashsize(const char *val, struct kernel_param *kp)
1187 int i, bucket, hashsize, vmalloced;
1188 int old_vmalloced, old_size;
1190 struct list_head *hash, *old_hash;
1191 struct nf_conntrack_tuple_hash *h;
1193 /* On boot, we can set this without any fancy locking. */
1194 if (!nf_conntrack_htable_size)
1195 return param_set_uint(val, kp);
1197 hashsize = simple_strtol(val, NULL, 0);
1201 hash = alloc_hashtable(hashsize, &vmalloced);
1205 /* We have to rehahs for the new table anyway, so we also can
1206 * use a newrandom seed */
1207 get_random_bytes(&rnd, 4);
1209 write_lock_bh(&nf_conntrack_lock);
1210 for (i = 0; i < nf_conntrack_htable_size; i++) {
1211 while (!list_empty(&nf_conntrack_hash[i])) {
1212 h = list_entry(nf_conntrack_hash[i].next,
1213 struct nf_conntrack_tuple_hash, list);
1215 bucket = __hash_conntrack(&h->tuple, hashsize, rnd);
1216 list_add_tail(&h->list, &hash[bucket]);
1219 old_size = nf_conntrack_htable_size;
1220 old_vmalloced = nf_conntrack_vmalloc;
1221 old_hash = nf_conntrack_hash;
1223 nf_conntrack_htable_size = hashsize;
1224 nf_conntrack_vmalloc = vmalloced;
1225 nf_conntrack_hash = hash;
1226 nf_conntrack_hash_rnd = rnd;
1227 write_unlock_bh(&nf_conntrack_lock);
1229 free_conntrack_hash(old_hash, old_vmalloced, old_size);
1233 module_param_call(hashsize, set_hashsize, param_get_uint,
1234 &nf_conntrack_htable_size, 0600);
1236 int __init nf_conntrack_init(void)
1241 /* Idea from tcp.c: use 1/16384 of memory. On i386: 32MB
1242 * machine has 256 buckets. >= 1GB machines have 8192 buckets. */
1243 if (!nf_conntrack_htable_size) {
1244 nf_conntrack_htable_size
1245 = (((num_physpages << PAGE_SHIFT) / 16384)
1246 / sizeof(struct list_head));
1247 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
1248 nf_conntrack_htable_size = 8192;
1249 if (nf_conntrack_htable_size < 16)
1250 nf_conntrack_htable_size = 16;
1252 nf_conntrack_max = 8 * nf_conntrack_htable_size;
1254 printk("nf_conntrack version %s (%u buckets, %d max)\n",
1255 NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1258 nf_conntrack_hash = alloc_hashtable(nf_conntrack_htable_size,
1259 &nf_conntrack_vmalloc);
1260 if (!nf_conntrack_hash) {
1261 printk(KERN_ERR "Unable to create nf_conntrack_hash\n");
1265 ret = nf_conntrack_register_cache(NF_CT_F_BASIC, "nf_conntrack:basic",
1266 sizeof(struct nf_conn));
1268 printk(KERN_ERR "Unable to create nf_conn slab cache\n");
1272 nf_conntrack_expect_cachep = kmem_cache_create("nf_conntrack_expect",
1273 sizeof(struct nf_conntrack_expect),
1275 if (!nf_conntrack_expect_cachep) {
1276 printk(KERN_ERR "Unable to create nf_expect slab cache\n");
1277 goto err_free_conntrack_slab;
1280 /* Don't NEED lock here, but good form anyway. */
1281 write_lock_bh(&nf_conntrack_lock);
1282 for (i = 0; i < PF_MAX; i++)
1283 nf_ct_l3protos[i] = &nf_conntrack_generic_l3proto;
1284 write_unlock_bh(&nf_conntrack_lock);
1286 /* For use by REJECT target */
1287 ip_ct_attach = __nf_conntrack_attach;
1289 /* Set up fake conntrack:
1290 - to never be deleted, not in any hashes */
1291 atomic_set(&nf_conntrack_untracked.ct_general.use, 1);
1292 /* - and look it like as a confirmed connection */
1293 set_bit(IPS_CONFIRMED_BIT, &nf_conntrack_untracked.status);
1297 err_free_conntrack_slab:
1298 nf_conntrack_unregister_cache(NF_CT_F_BASIC);
1300 free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1301 nf_conntrack_htable_size);