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 #ifdef CONFIG_NF_CONNTRACK_EVENTS
89 ATOMIC_NOTIFIER_HEAD(nf_conntrack_chain);
90 ATOMIC_NOTIFIER_HEAD(nf_conntrack_expect_chain);
92 DEFINE_PER_CPU(struct nf_conntrack_ecache, nf_conntrack_ecache);
94 /* deliver cached events and clear cache entry - must be called with locally
95 * disabled softirqs */
97 __nf_ct_deliver_cached_events(struct nf_conntrack_ecache *ecache)
99 DEBUGP("ecache: delivering events for %p\n", ecache->ct);
100 if (nf_ct_is_confirmed(ecache->ct) && !nf_ct_is_dying(ecache->ct)
102 atomic_notifier_call_chain(&nf_conntrack_chain, ecache->events,
106 nf_ct_put(ecache->ct);
110 /* Deliver all cached events for a particular conntrack. This is called
111 * by code prior to async packet handling for freeing the skb */
112 void nf_ct_deliver_cached_events(const struct nf_conn *ct)
114 struct nf_conntrack_ecache *ecache;
117 ecache = &__get_cpu_var(nf_conntrack_ecache);
118 if (ecache->ct == ct)
119 __nf_ct_deliver_cached_events(ecache);
123 /* Deliver cached events for old pending events, if current conntrack != old */
124 void __nf_ct_event_cache_init(struct nf_conn *ct)
126 struct nf_conntrack_ecache *ecache;
128 /* take care of delivering potentially old events */
129 ecache = &__get_cpu_var(nf_conntrack_ecache);
130 BUG_ON(ecache->ct == ct);
132 __nf_ct_deliver_cached_events(ecache);
133 /* initialize for this conntrack/packet */
135 nf_conntrack_get(&ct->ct_general);
138 /* flush the event cache - touches other CPU's data and must not be called
139 * while packets are still passing through the code */
140 static void nf_ct_event_cache_flush(void)
142 struct nf_conntrack_ecache *ecache;
145 for_each_possible_cpu(cpu) {
146 ecache = &per_cpu(nf_conntrack_ecache, cpu);
148 nf_ct_put(ecache->ct);
152 static inline void nf_ct_event_cache_flush(void) {}
153 #endif /* CONFIG_NF_CONNTRACK_EVENTS */
155 DEFINE_PER_CPU(struct ip_conntrack_stat, nf_conntrack_stat);
156 EXPORT_PER_CPU_SYMBOL(nf_conntrack_stat);
159 * This scheme offers various size of "struct nf_conn" dependent on
160 * features(helper, nat, ...)
163 #define NF_CT_FEATURES_NAMELEN 256
165 /* name of slab cache. printed in /proc/slabinfo */
168 /* size of slab cache */
171 /* slab cache pointer */
172 kmem_cache_t *cachep;
174 /* allocated slab cache + modules which uses this slab cache */
177 } nf_ct_cache[NF_CT_F_NUM];
179 /* protect members of nf_ct_cache except of "use" */
180 DEFINE_RWLOCK(nf_ct_cache_lock);
182 /* This avoids calling kmem_cache_create() with same name simultaneously */
183 static DEFINE_MUTEX(nf_ct_cache_mutex);
185 extern struct nf_conntrack_protocol nf_conntrack_generic_protocol;
186 struct nf_conntrack_protocol *
187 __nf_ct_proto_find(u_int16_t l3proto, u_int8_t protocol)
189 if (unlikely(l3proto >= AF_MAX || nf_ct_protos[l3proto] == NULL))
190 return &nf_conntrack_generic_protocol;
192 return nf_ct_protos[l3proto][protocol];
195 /* this is guaranteed to always return a valid protocol helper, since
196 * it falls back to generic_protocol */
197 struct nf_conntrack_protocol *
198 nf_ct_proto_find_get(u_int16_t l3proto, u_int8_t protocol)
200 struct nf_conntrack_protocol *p;
203 p = __nf_ct_proto_find(l3proto, protocol);
204 if (!try_module_get(p->me))
205 p = &nf_conntrack_generic_protocol;
211 void nf_ct_proto_put(struct nf_conntrack_protocol *p)
216 struct nf_conntrack_l3proto *
217 nf_ct_l3proto_find_get(u_int16_t l3proto)
219 struct nf_conntrack_l3proto *p;
222 p = __nf_ct_l3proto_find(l3proto);
223 if (!try_module_get(p->me))
224 p = &nf_conntrack_generic_l3proto;
230 void nf_ct_l3proto_put(struct nf_conntrack_l3proto *p)
236 nf_ct_l3proto_try_module_get(unsigned short l3proto)
239 struct nf_conntrack_l3proto *p;
241 retry: p = nf_ct_l3proto_find_get(l3proto);
242 if (p == &nf_conntrack_generic_l3proto) {
243 ret = request_module("nf_conntrack-%d", l3proto);
253 void nf_ct_l3proto_module_put(unsigned short l3proto)
255 struct nf_conntrack_l3proto *p;
258 p = __nf_ct_l3proto_find(l3proto);
264 static int nf_conntrack_hash_rnd_initted;
265 static unsigned int nf_conntrack_hash_rnd;
267 static u_int32_t __hash_conntrack(const struct nf_conntrack_tuple *tuple,
268 unsigned int size, unsigned int rnd)
271 a = jhash((void *)tuple->src.u3.all, sizeof(tuple->src.u3.all),
272 ((tuple->src.l3num) << 16) | tuple->dst.protonum);
273 b = jhash((void *)tuple->dst.u3.all, sizeof(tuple->dst.u3.all),
274 (tuple->src.u.all << 16) | tuple->dst.u.all);
276 return jhash_2words(a, b, rnd) % size;
279 static inline u_int32_t hash_conntrack(const struct nf_conntrack_tuple *tuple)
281 return __hash_conntrack(tuple, nf_conntrack_htable_size,
282 nf_conntrack_hash_rnd);
285 int nf_conntrack_register_cache(u_int32_t features, const char *name,
290 kmem_cache_t *cachep;
292 DEBUGP("nf_conntrack_register_cache: features=0x%x, name=%s, size=%d\n",
293 features, name, size);
295 if (features < NF_CT_F_BASIC || features >= NF_CT_F_NUM) {
296 DEBUGP("nf_conntrack_register_cache: invalid features.: 0x%x\n",
301 mutex_lock(&nf_ct_cache_mutex);
303 write_lock_bh(&nf_ct_cache_lock);
304 /* e.g: multiple helpers are loaded */
305 if (nf_ct_cache[features].use > 0) {
306 DEBUGP("nf_conntrack_register_cache: already resisterd.\n");
307 if ((!strncmp(nf_ct_cache[features].name, name,
308 NF_CT_FEATURES_NAMELEN))
309 && nf_ct_cache[features].size == size) {
310 DEBUGP("nf_conntrack_register_cache: reusing.\n");
311 nf_ct_cache[features].use++;
316 write_unlock_bh(&nf_ct_cache_lock);
317 mutex_unlock(&nf_ct_cache_mutex);
320 write_unlock_bh(&nf_ct_cache_lock);
323 * The memory space for name of slab cache must be alive until
324 * cache is destroyed.
326 cache_name = kmalloc(sizeof(char)*NF_CT_FEATURES_NAMELEN, GFP_ATOMIC);
327 if (cache_name == NULL) {
328 DEBUGP("nf_conntrack_register_cache: can't alloc cache_name\n");
333 if (strlcpy(cache_name, name, NF_CT_FEATURES_NAMELEN)
334 >= NF_CT_FEATURES_NAMELEN) {
335 printk("nf_conntrack_register_cache: name too long\n");
340 cachep = kmem_cache_create(cache_name, size, 0, 0,
343 printk("nf_conntrack_register_cache: Can't create slab cache "
344 "for the features = 0x%x\n", features);
349 write_lock_bh(&nf_ct_cache_lock);
350 nf_ct_cache[features].use = 1;
351 nf_ct_cache[features].size = size;
352 nf_ct_cache[features].cachep = cachep;
353 nf_ct_cache[features].name = cache_name;
354 write_unlock_bh(&nf_ct_cache_lock);
361 mutex_unlock(&nf_ct_cache_mutex);
365 /* FIXME: In the current, only nf_conntrack_cleanup() can call this function. */
366 void nf_conntrack_unregister_cache(u_int32_t features)
368 kmem_cache_t *cachep;
372 * This assures that kmem_cache_create() isn't called before destroying
375 DEBUGP("nf_conntrack_unregister_cache: 0x%04x\n", features);
376 mutex_lock(&nf_ct_cache_mutex);
378 write_lock_bh(&nf_ct_cache_lock);
379 if (--nf_ct_cache[features].use > 0) {
380 write_unlock_bh(&nf_ct_cache_lock);
381 mutex_unlock(&nf_ct_cache_mutex);
384 cachep = nf_ct_cache[features].cachep;
385 name = nf_ct_cache[features].name;
386 nf_ct_cache[features].cachep = NULL;
387 nf_ct_cache[features].name = NULL;
388 nf_ct_cache[features].size = 0;
389 write_unlock_bh(&nf_ct_cache_lock);
393 kmem_cache_destroy(cachep);
396 mutex_unlock(&nf_ct_cache_mutex);
400 nf_ct_get_tuple(const struct sk_buff *skb,
402 unsigned int dataoff,
405 struct nf_conntrack_tuple *tuple,
406 const struct nf_conntrack_l3proto *l3proto,
407 const struct nf_conntrack_protocol *protocol)
409 NF_CT_TUPLE_U_BLANK(tuple);
411 tuple->src.l3num = l3num;
412 if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
415 tuple->dst.protonum = protonum;
416 tuple->dst.dir = IP_CT_DIR_ORIGINAL;
418 return protocol->pkt_to_tuple(skb, dataoff, tuple);
422 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
423 const struct nf_conntrack_tuple *orig,
424 const struct nf_conntrack_l3proto *l3proto,
425 const struct nf_conntrack_protocol *protocol)
427 NF_CT_TUPLE_U_BLANK(inverse);
429 inverse->src.l3num = orig->src.l3num;
430 if (l3proto->invert_tuple(inverse, orig) == 0)
433 inverse->dst.dir = !orig->dst.dir;
435 inverse->dst.protonum = orig->dst.protonum;
436 return protocol->invert_tuple(inverse, orig);
440 clean_from_lists(struct nf_conn *ct)
442 DEBUGP("clean_from_lists(%p)\n", ct);
443 ASSERT_WRITE_LOCK(&nf_conntrack_lock);
444 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
445 list_del(&ct->tuplehash[IP_CT_DIR_REPLY].list);
447 /* Destroy all pending expectations */
448 nf_ct_remove_expectations(ct);
452 destroy_conntrack(struct nf_conntrack *nfct)
454 struct nf_conn *ct = (struct nf_conn *)nfct;
455 struct nf_conntrack_l3proto *l3proto;
456 struct nf_conntrack_protocol *proto;
458 DEBUGP("destroy_conntrack(%p)\n", ct);
459 NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
460 NF_CT_ASSERT(!timer_pending(&ct->timeout));
462 nf_conntrack_event(IPCT_DESTROY, ct);
463 set_bit(IPS_DYING_BIT, &ct->status);
465 /* To make sure we don't get any weird locking issues here:
466 * destroy_conntrack() MUST NOT be called with a write lock
467 * to nf_conntrack_lock!!! -HW */
468 l3proto = __nf_ct_l3proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num);
469 if (l3proto && l3proto->destroy)
470 l3proto->destroy(ct);
472 proto = __nf_ct_proto_find(ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.l3num, ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.protonum);
473 if (proto && proto->destroy)
476 if (nf_conntrack_destroyed)
477 nf_conntrack_destroyed(ct);
479 write_lock_bh(&nf_conntrack_lock);
480 /* Expectations will have been removed in clean_from_lists,
481 * except TFTP can create an expectation on the first packet,
482 * before connection is in the list, so we need to clean here,
484 nf_ct_remove_expectations(ct);
486 /* We overload first tuple to link into unconfirmed list. */
487 if (!nf_ct_is_confirmed(ct)) {
488 BUG_ON(list_empty(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list));
489 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
492 NF_CT_STAT_INC(delete);
493 write_unlock_bh(&nf_conntrack_lock);
496 nf_ct_put(ct->master);
498 DEBUGP("destroy_conntrack: returning ct=%p to slab\n", ct);
499 nf_conntrack_free(ct);
502 static void death_by_timeout(unsigned long ul_conntrack)
504 struct nf_conn *ct = (void *)ul_conntrack;
506 write_lock_bh(&nf_conntrack_lock);
507 /* Inside lock so preempt is disabled on module removal path.
508 * Otherwise we can get spurious warnings. */
509 NF_CT_STAT_INC(delete_list);
510 clean_from_lists(ct);
511 write_unlock_bh(&nf_conntrack_lock);
515 struct nf_conntrack_tuple_hash *
516 __nf_conntrack_find(const struct nf_conntrack_tuple *tuple,
517 const struct nf_conn *ignored_conntrack)
519 struct nf_conntrack_tuple_hash *h;
520 unsigned int hash = hash_conntrack(tuple);
522 ASSERT_READ_LOCK(&nf_conntrack_lock);
523 list_for_each_entry(h, &nf_conntrack_hash[hash], list) {
524 if (nf_ct_tuplehash_to_ctrack(h) != ignored_conntrack &&
525 nf_ct_tuple_equal(tuple, &h->tuple)) {
526 NF_CT_STAT_INC(found);
529 NF_CT_STAT_INC(searched);
535 /* Find a connection corresponding to a tuple. */
536 struct nf_conntrack_tuple_hash *
537 nf_conntrack_find_get(const struct nf_conntrack_tuple *tuple,
538 const struct nf_conn *ignored_conntrack)
540 struct nf_conntrack_tuple_hash *h;
542 read_lock_bh(&nf_conntrack_lock);
543 h = __nf_conntrack_find(tuple, ignored_conntrack);
545 atomic_inc(&nf_ct_tuplehash_to_ctrack(h)->ct_general.use);
546 read_unlock_bh(&nf_conntrack_lock);
551 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
553 unsigned int repl_hash)
555 ct->id = ++nf_conntrack_next_id;
556 list_add(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list,
557 &nf_conntrack_hash[hash]);
558 list_add(&ct->tuplehash[IP_CT_DIR_REPLY].list,
559 &nf_conntrack_hash[repl_hash]);
562 void nf_conntrack_hash_insert(struct nf_conn *ct)
564 unsigned int hash, repl_hash;
566 hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
567 repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
569 write_lock_bh(&nf_conntrack_lock);
570 __nf_conntrack_hash_insert(ct, hash, repl_hash);
571 write_unlock_bh(&nf_conntrack_lock);
574 /* Confirm a connection given skb; places it in hash table */
576 __nf_conntrack_confirm(struct sk_buff **pskb)
578 unsigned int hash, repl_hash;
579 struct nf_conntrack_tuple_hash *h;
581 struct nf_conn_help *help;
582 enum ip_conntrack_info ctinfo;
584 ct = nf_ct_get(*pskb, &ctinfo);
586 /* ipt_REJECT uses nf_conntrack_attach to attach related
587 ICMP/TCP RST packets in other direction. Actual packet
588 which created connection will be IP_CT_NEW or for an
589 expected connection, IP_CT_RELATED. */
590 if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
593 hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
594 repl_hash = hash_conntrack(&ct->tuplehash[IP_CT_DIR_REPLY].tuple);
596 /* We're not in hash table, and we refuse to set up related
597 connections for unconfirmed conns. But packet copies and
598 REJECT will give spurious warnings here. */
599 /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
601 /* No external references means noone else could have
603 NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
604 DEBUGP("Confirming conntrack %p\n", ct);
606 write_lock_bh(&nf_conntrack_lock);
608 /* See if there's one in the list already, including reverse:
609 NAT could have grabbed it without realizing, since we're
610 not in the hash. If there is, we lost race. */
611 list_for_each_entry(h, &nf_conntrack_hash[hash], list)
612 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
615 list_for_each_entry(h, &nf_conntrack_hash[repl_hash], list)
616 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
620 /* Remove from unconfirmed list */
621 list_del(&ct->tuplehash[IP_CT_DIR_ORIGINAL].list);
623 __nf_conntrack_hash_insert(ct, hash, repl_hash);
624 /* Timer relative to confirmation time, not original
625 setting time, otherwise we'd get timer wrap in
626 weird delay cases. */
627 ct->timeout.expires += jiffies;
628 add_timer(&ct->timeout);
629 atomic_inc(&ct->ct_general.use);
630 set_bit(IPS_CONFIRMED_BIT, &ct->status);
631 NF_CT_STAT_INC(insert);
632 write_unlock_bh(&nf_conntrack_lock);
633 help = nfct_help(ct);
634 if (help && help->helper)
635 nf_conntrack_event_cache(IPCT_HELPER, *pskb);
636 #ifdef CONFIG_NF_NAT_NEEDED
637 if (test_bit(IPS_SRC_NAT_DONE_BIT, &ct->status) ||
638 test_bit(IPS_DST_NAT_DONE_BIT, &ct->status))
639 nf_conntrack_event_cache(IPCT_NATINFO, *pskb);
641 nf_conntrack_event_cache(master_ct(ct) ?
642 IPCT_RELATED : IPCT_NEW, *pskb);
646 NF_CT_STAT_INC(insert_failed);
647 write_unlock_bh(&nf_conntrack_lock);
651 /* Returns true if a connection correspondings to the tuple (required
654 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
655 const struct nf_conn *ignored_conntrack)
657 struct nf_conntrack_tuple_hash *h;
659 read_lock_bh(&nf_conntrack_lock);
660 h = __nf_conntrack_find(tuple, ignored_conntrack);
661 read_unlock_bh(&nf_conntrack_lock);
666 /* There's a small race here where we may free a just-assured
667 connection. Too bad: we're in trouble anyway. */
668 static int early_drop(struct list_head *chain)
670 /* Traverse backwards: gives us oldest, which is roughly LRU */
671 struct nf_conntrack_tuple_hash *h;
672 struct nf_conn *ct = NULL, *tmp;
675 read_lock_bh(&nf_conntrack_lock);
676 list_for_each_entry_reverse(h, chain, list) {
677 tmp = nf_ct_tuplehash_to_ctrack(h);
678 if (!test_bit(IPS_ASSURED_BIT, &tmp->status)) {
680 atomic_inc(&ct->ct_general.use);
684 read_unlock_bh(&nf_conntrack_lock);
689 if (del_timer(&ct->timeout)) {
690 death_by_timeout((unsigned long)ct);
692 NF_CT_STAT_INC(early_drop);
698 static struct nf_conn *
699 __nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
700 const struct nf_conntrack_tuple *repl,
701 const struct nf_conntrack_l3proto *l3proto)
703 struct nf_conn *conntrack = NULL;
704 u_int32_t features = 0;
705 struct nf_conntrack_helper *helper;
707 if (unlikely(!nf_conntrack_hash_rnd_initted)) {
708 get_random_bytes(&nf_conntrack_hash_rnd, 4);
709 nf_conntrack_hash_rnd_initted = 1;
712 /* We don't want any race condition at early drop stage */
713 atomic_inc(&nf_conntrack_count);
716 && atomic_read(&nf_conntrack_count) > nf_conntrack_max) {
717 unsigned int hash = hash_conntrack(orig);
718 /* Try dropping from this hash chain. */
719 if (!early_drop(&nf_conntrack_hash[hash])) {
720 atomic_dec(&nf_conntrack_count);
723 "nf_conntrack: table full, dropping"
725 return ERR_PTR(-ENOMEM);
729 /* find features needed by this conntrack. */
730 features = l3proto->get_features(orig);
732 /* FIXME: protect helper list per RCU */
733 read_lock_bh(&nf_conntrack_lock);
734 helper = __nf_ct_helper_find(repl);
736 features |= NF_CT_F_HELP;
737 read_unlock_bh(&nf_conntrack_lock);
739 DEBUGP("nf_conntrack_alloc: features=0x%x\n", features);
741 read_lock_bh(&nf_ct_cache_lock);
743 if (unlikely(!nf_ct_cache[features].use)) {
744 DEBUGP("nf_conntrack_alloc: not supported features = 0x%x\n",
749 conntrack = kmem_cache_alloc(nf_ct_cache[features].cachep, GFP_ATOMIC);
750 if (conntrack == NULL) {
751 DEBUGP("nf_conntrack_alloc: Can't alloc conntrack from cache\n");
755 memset(conntrack, 0, nf_ct_cache[features].size);
756 conntrack->features = features;
757 atomic_set(&conntrack->ct_general.use, 1);
758 conntrack->ct_general.destroy = destroy_conntrack;
759 conntrack->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
760 conntrack->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
761 /* Don't set timer yet: wait for confirmation */
762 init_timer(&conntrack->timeout);
763 conntrack->timeout.data = (unsigned long)conntrack;
764 conntrack->timeout.function = death_by_timeout;
765 read_unlock_bh(&nf_ct_cache_lock);
769 read_unlock_bh(&nf_ct_cache_lock);
770 atomic_dec(&nf_conntrack_count);
774 struct nf_conn *nf_conntrack_alloc(const struct nf_conntrack_tuple *orig,
775 const struct nf_conntrack_tuple *repl)
777 struct nf_conntrack_l3proto *l3proto;
779 l3proto = __nf_ct_l3proto_find(orig->src.l3num);
780 return __nf_conntrack_alloc(orig, repl, l3proto);
783 void nf_conntrack_free(struct nf_conn *conntrack)
785 u_int32_t features = conntrack->features;
786 NF_CT_ASSERT(features >= NF_CT_F_BASIC && features < NF_CT_F_NUM);
787 DEBUGP("nf_conntrack_free: features = 0x%x, conntrack=%p\n", features,
789 kmem_cache_free(nf_ct_cache[features].cachep, conntrack);
790 atomic_dec(&nf_conntrack_count);
793 /* Allocate a new conntrack: we return -ENOMEM if classification
794 failed due to stress. Otherwise it really is unclassifiable. */
795 static struct nf_conntrack_tuple_hash *
796 init_conntrack(const struct nf_conntrack_tuple *tuple,
797 struct nf_conntrack_l3proto *l3proto,
798 struct nf_conntrack_protocol *protocol,
800 unsigned int dataoff)
802 struct nf_conn *conntrack;
803 struct nf_conntrack_tuple repl_tuple;
804 struct nf_conntrack_expect *exp;
806 if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, protocol)) {
807 DEBUGP("Can't invert tuple.\n");
811 conntrack = __nf_conntrack_alloc(tuple, &repl_tuple, l3proto);
812 if (conntrack == NULL || IS_ERR(conntrack)) {
813 DEBUGP("Can't allocate conntrack.\n");
814 return (struct nf_conntrack_tuple_hash *)conntrack;
817 if (!protocol->new(conntrack, skb, dataoff)) {
818 nf_conntrack_free(conntrack);
819 DEBUGP("init conntrack: can't track with proto module\n");
823 write_lock_bh(&nf_conntrack_lock);
824 exp = find_expectation(tuple);
827 DEBUGP("conntrack: expectation arrives ct=%p exp=%p\n",
829 /* Welcome, Mr. Bond. We've been expecting you... */
830 __set_bit(IPS_EXPECTED_BIT, &conntrack->status);
831 conntrack->master = exp->master;
832 #ifdef CONFIG_NF_CONNTRACK_MARK
833 conntrack->mark = exp->master->mark;
835 #ifdef CONFIG_NF_CONNTRACK_SECMARK
836 conntrack->secmark = exp->master->secmark;
838 nf_conntrack_get(&conntrack->master->ct_general);
839 NF_CT_STAT_INC(expect_new);
841 struct nf_conn_help *help = nfct_help(conntrack);
844 help->helper = __nf_ct_helper_find(&repl_tuple);
848 /* Overload tuple linked list to put us in unconfirmed list. */
849 list_add(&conntrack->tuplehash[IP_CT_DIR_ORIGINAL].list, &unconfirmed);
851 write_unlock_bh(&nf_conntrack_lock);
855 exp->expectfn(conntrack, exp);
856 nf_conntrack_expect_put(exp);
859 return &conntrack->tuplehash[IP_CT_DIR_ORIGINAL];
862 /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
863 static inline struct nf_conn *
864 resolve_normal_ct(struct sk_buff *skb,
865 unsigned int dataoff,
868 struct nf_conntrack_l3proto *l3proto,
869 struct nf_conntrack_protocol *proto,
871 enum ip_conntrack_info *ctinfo)
873 struct nf_conntrack_tuple tuple;
874 struct nf_conntrack_tuple_hash *h;
877 if (!nf_ct_get_tuple(skb, (unsigned int)(skb->nh.raw - skb->data),
878 dataoff, l3num, protonum, &tuple, l3proto,
880 DEBUGP("resolve_normal_ct: Can't get tuple\n");
884 /* look for tuple match */
885 h = nf_conntrack_find_get(&tuple, NULL);
887 h = init_conntrack(&tuple, l3proto, proto, skb, dataoff);
893 ct = nf_ct_tuplehash_to_ctrack(h);
895 /* It exists; we have (non-exclusive) reference. */
896 if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
897 *ctinfo = IP_CT_ESTABLISHED + IP_CT_IS_REPLY;
898 /* Please set reply bit if this packet OK */
901 /* Once we've had two way comms, always ESTABLISHED. */
902 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
903 DEBUGP("nf_conntrack_in: normal packet for %p\n", ct);
904 *ctinfo = IP_CT_ESTABLISHED;
905 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
906 DEBUGP("nf_conntrack_in: related packet for %p\n", ct);
907 *ctinfo = IP_CT_RELATED;
909 DEBUGP("nf_conntrack_in: new packet for %p\n", ct);
914 skb->nfct = &ct->ct_general;
915 skb->nfctinfo = *ctinfo;
920 nf_conntrack_in(int pf, unsigned int hooknum, struct sk_buff **pskb)
923 enum ip_conntrack_info ctinfo;
924 struct nf_conntrack_l3proto *l3proto;
925 struct nf_conntrack_protocol *proto;
926 unsigned int dataoff;
931 /* Previously seen (loopback or untracked)? Ignore. */
933 NF_CT_STAT_INC(ignore);
937 l3proto = __nf_ct_l3proto_find((u_int16_t)pf);
938 if ((ret = l3proto->prepare(pskb, hooknum, &dataoff, &protonum)) <= 0) {
939 DEBUGP("not prepared to track yet or error occured\n");
943 proto = __nf_ct_proto_find((u_int16_t)pf, protonum);
945 /* It may be an special packet, error, unclean...
946 * inverse of the return code tells to the netfilter
947 * core what to do with the packet. */
948 if (proto->error != NULL &&
949 (ret = proto->error(*pskb, dataoff, &ctinfo, pf, hooknum)) <= 0) {
950 NF_CT_STAT_INC(error);
951 NF_CT_STAT_INC(invalid);
955 ct = resolve_normal_ct(*pskb, dataoff, pf, protonum, l3proto, proto,
956 &set_reply, &ctinfo);
958 /* Not valid part of a connection */
959 NF_CT_STAT_INC(invalid);
964 /* Too stressed to deal. */
965 NF_CT_STAT_INC(drop);
969 NF_CT_ASSERT((*pskb)->nfct);
971 ret = proto->packet(ct, *pskb, dataoff, ctinfo, pf, hooknum);
973 /* Invalid: inverse of the return code tells
974 * the netfilter core what to do */
975 DEBUGP("nf_conntrack_in: Can't track with proto module\n");
976 nf_conntrack_put((*pskb)->nfct);
977 (*pskb)->nfct = NULL;
978 NF_CT_STAT_INC(invalid);
982 if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
983 nf_conntrack_event_cache(IPCT_STATUS, *pskb);
988 int nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
989 const struct nf_conntrack_tuple *orig)
991 return nf_ct_invert_tuple(inverse, orig,
992 __nf_ct_l3proto_find(orig->src.l3num),
993 __nf_ct_proto_find(orig->src.l3num,
994 orig->dst.protonum));
997 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
998 void __nf_ct_refresh_acct(struct nf_conn *ct,
999 enum ip_conntrack_info ctinfo,
1000 const struct sk_buff *skb,
1001 unsigned long extra_jiffies,
1006 NF_CT_ASSERT(ct->timeout.data == (unsigned long)ct);
1009 write_lock_bh(&nf_conntrack_lock);
1011 /* Only update if this is not a fixed timeout */
1012 if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status)) {
1013 write_unlock_bh(&nf_conntrack_lock);
1017 /* If not in hash table, timer will not be active yet */
1018 if (!nf_ct_is_confirmed(ct)) {
1019 ct->timeout.expires = extra_jiffies;
1020 event = IPCT_REFRESH;
1022 /* Need del_timer for race avoidance (may already be dying). */
1023 if (del_timer(&ct->timeout)) {
1024 ct->timeout.expires = jiffies + extra_jiffies;
1025 add_timer(&ct->timeout);
1026 event = IPCT_REFRESH;
1030 #ifdef CONFIG_NF_CT_ACCT
1032 ct->counters[CTINFO2DIR(ctinfo)].packets++;
1033 ct->counters[CTINFO2DIR(ctinfo)].bytes +=
1034 skb->len - (unsigned int)(skb->nh.raw - skb->data);
1035 if ((ct->counters[CTINFO2DIR(ctinfo)].packets & 0x80000000)
1036 || (ct->counters[CTINFO2DIR(ctinfo)].bytes & 0x80000000))
1037 event |= IPCT_COUNTER_FILLING;
1041 write_unlock_bh(&nf_conntrack_lock);
1043 /* must be unlocked when calling event cache */
1045 nf_conntrack_event_cache(event, skb);
1048 #if defined(CONFIG_NF_CT_NETLINK) || \
1049 defined(CONFIG_NF_CT_NETLINK_MODULE)
1051 #include <linux/netfilter/nfnetlink.h>
1052 #include <linux/netfilter/nfnetlink_conntrack.h>
1053 #include <linux/mutex.h>
1056 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1057 * in ip_conntrack_core, since we don't want the protocols to autoload
1058 * or depend on ctnetlink */
1059 int nf_ct_port_tuple_to_nfattr(struct sk_buff *skb,
1060 const struct nf_conntrack_tuple *tuple)
1062 NFA_PUT(skb, CTA_PROTO_SRC_PORT, sizeof(u_int16_t),
1063 &tuple->src.u.tcp.port);
1064 NFA_PUT(skb, CTA_PROTO_DST_PORT, sizeof(u_int16_t),
1065 &tuple->dst.u.tcp.port);
1072 static const size_t cta_min_proto[CTA_PROTO_MAX] = {
1073 [CTA_PROTO_SRC_PORT-1] = sizeof(u_int16_t),
1074 [CTA_PROTO_DST_PORT-1] = sizeof(u_int16_t)
1077 int nf_ct_port_nfattr_to_tuple(struct nfattr *tb[],
1078 struct nf_conntrack_tuple *t)
1080 if (!tb[CTA_PROTO_SRC_PORT-1] || !tb[CTA_PROTO_DST_PORT-1])
1083 if (nfattr_bad_size(tb, CTA_PROTO_MAX, cta_min_proto))
1087 *(u_int16_t *)NFA_DATA(tb[CTA_PROTO_SRC_PORT-1]);
1089 *(u_int16_t *)NFA_DATA(tb[CTA_PROTO_DST_PORT-1]);
1095 /* Used by ipt_REJECT and ip6t_REJECT. */
1096 void __nf_conntrack_attach(struct sk_buff *nskb, struct sk_buff *skb)
1099 enum ip_conntrack_info ctinfo;
1101 /* This ICMP is in reverse direction to the packet which caused it */
1102 ct = nf_ct_get(skb, &ctinfo);
1103 if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1104 ctinfo = IP_CT_RELATED + IP_CT_IS_REPLY;
1106 ctinfo = IP_CT_RELATED;
1108 /* Attach to new skbuff, and increment count */
1109 nskb->nfct = &ct->ct_general;
1110 nskb->nfctinfo = ctinfo;
1111 nf_conntrack_get(nskb->nfct);
1115 do_iter(const struct nf_conntrack_tuple_hash *i,
1116 int (*iter)(struct nf_conn *i, void *data),
1119 return iter(nf_ct_tuplehash_to_ctrack(i), data);
1122 /* Bring out ya dead! */
1123 static struct nf_conn *
1124 get_next_corpse(int (*iter)(struct nf_conn *i, void *data),
1125 void *data, unsigned int *bucket)
1127 struct nf_conntrack_tuple_hash *h;
1130 write_lock_bh(&nf_conntrack_lock);
1131 for (; *bucket < nf_conntrack_htable_size; (*bucket)++) {
1132 list_for_each_entry(h, &nf_conntrack_hash[*bucket], list) {
1133 ct = nf_ct_tuplehash_to_ctrack(h);
1138 list_for_each_entry(h, &unconfirmed, list) {
1139 ct = nf_ct_tuplehash_to_ctrack(h);
1143 write_unlock_bh(&nf_conntrack_lock);
1146 atomic_inc(&ct->ct_general.use);
1147 write_unlock_bh(&nf_conntrack_lock);
1152 nf_ct_iterate_cleanup(int (*iter)(struct nf_conn *i, void *data), void *data)
1155 unsigned int bucket = 0;
1157 while ((ct = get_next_corpse(iter, data, &bucket)) != NULL) {
1158 /* Time to push up daises... */
1159 if (del_timer(&ct->timeout))
1160 death_by_timeout((unsigned long)ct);
1161 /* ... else the timer will get him soon. */
1167 static int kill_all(struct nf_conn *i, void *data)
1172 static void free_conntrack_hash(struct list_head *hash, int vmalloced, int size)
1177 free_pages((unsigned long)hash,
1178 get_order(sizeof(struct list_head) * size));
1181 void nf_conntrack_flush()
1183 nf_ct_iterate_cleanup(kill_all, NULL);
1186 /* Mishearing the voices in his head, our hero wonders how he's
1187 supposed to kill the mall. */
1188 void nf_conntrack_cleanup(void)
1192 ip_ct_attach = NULL;
1194 /* This makes sure all current packets have passed through
1195 netfilter framework. Roll on, two-stage module
1199 nf_ct_event_cache_flush();
1201 nf_conntrack_flush();
1202 if (atomic_read(&nf_conntrack_count) != 0) {
1204 goto i_see_dead_people;
1206 /* wait until all references to nf_conntrack_untracked are dropped */
1207 while (atomic_read(&nf_conntrack_untracked.ct_general.use) > 1)
1210 for (i = 0; i < NF_CT_F_NUM; i++) {
1211 if (nf_ct_cache[i].use == 0)
1214 NF_CT_ASSERT(nf_ct_cache[i].use == 1);
1215 nf_ct_cache[i].use = 1;
1216 nf_conntrack_unregister_cache(i);
1218 kmem_cache_destroy(nf_conntrack_expect_cachep);
1219 free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1220 nf_conntrack_htable_size);
1222 /* free l3proto protocol tables */
1223 for (i = 0; i < PF_MAX; i++)
1224 if (nf_ct_protos[i]) {
1225 kfree(nf_ct_protos[i]);
1226 nf_ct_protos[i] = NULL;
1230 static struct list_head *alloc_hashtable(int size, int *vmalloced)
1232 struct list_head *hash;
1236 hash = (void*)__get_free_pages(GFP_KERNEL,
1237 get_order(sizeof(struct list_head)
1241 printk(KERN_WARNING "nf_conntrack: falling back to vmalloc.\n");
1242 hash = vmalloc(sizeof(struct list_head) * size);
1246 for (i = 0; i < size; i++)
1247 INIT_LIST_HEAD(&hash[i]);
1252 int set_hashsize(const char *val, struct kernel_param *kp)
1254 int i, bucket, hashsize, vmalloced;
1255 int old_vmalloced, old_size;
1257 struct list_head *hash, *old_hash;
1258 struct nf_conntrack_tuple_hash *h;
1260 /* On boot, we can set this without any fancy locking. */
1261 if (!nf_conntrack_htable_size)
1262 return param_set_uint(val, kp);
1264 hashsize = simple_strtol(val, NULL, 0);
1268 hash = alloc_hashtable(hashsize, &vmalloced);
1272 /* We have to rehahs for the new table anyway, so we also can
1273 * use a newrandom seed */
1274 get_random_bytes(&rnd, 4);
1276 write_lock_bh(&nf_conntrack_lock);
1277 for (i = 0; i < nf_conntrack_htable_size; i++) {
1278 while (!list_empty(&nf_conntrack_hash[i])) {
1279 h = list_entry(nf_conntrack_hash[i].next,
1280 struct nf_conntrack_tuple_hash, list);
1282 bucket = __hash_conntrack(&h->tuple, hashsize, rnd);
1283 list_add_tail(&h->list, &hash[bucket]);
1286 old_size = nf_conntrack_htable_size;
1287 old_vmalloced = nf_conntrack_vmalloc;
1288 old_hash = nf_conntrack_hash;
1290 nf_conntrack_htable_size = hashsize;
1291 nf_conntrack_vmalloc = vmalloced;
1292 nf_conntrack_hash = hash;
1293 nf_conntrack_hash_rnd = rnd;
1294 write_unlock_bh(&nf_conntrack_lock);
1296 free_conntrack_hash(old_hash, old_vmalloced, old_size);
1300 module_param_call(hashsize, set_hashsize, param_get_uint,
1301 &nf_conntrack_htable_size, 0600);
1303 int __init nf_conntrack_init(void)
1308 /* Idea from tcp.c: use 1/16384 of memory. On i386: 32MB
1309 * machine has 256 buckets. >= 1GB machines have 8192 buckets. */
1310 if (!nf_conntrack_htable_size) {
1311 nf_conntrack_htable_size
1312 = (((num_physpages << PAGE_SHIFT) / 16384)
1313 / sizeof(struct list_head));
1314 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
1315 nf_conntrack_htable_size = 8192;
1316 if (nf_conntrack_htable_size < 16)
1317 nf_conntrack_htable_size = 16;
1319 nf_conntrack_max = 8 * nf_conntrack_htable_size;
1321 printk("nf_conntrack version %s (%u buckets, %d max)\n",
1322 NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1325 nf_conntrack_hash = alloc_hashtable(nf_conntrack_htable_size,
1326 &nf_conntrack_vmalloc);
1327 if (!nf_conntrack_hash) {
1328 printk(KERN_ERR "Unable to create nf_conntrack_hash\n");
1332 ret = nf_conntrack_register_cache(NF_CT_F_BASIC, "nf_conntrack:basic",
1333 sizeof(struct nf_conn));
1335 printk(KERN_ERR "Unable to create nf_conn slab cache\n");
1339 nf_conntrack_expect_cachep = kmem_cache_create("nf_conntrack_expect",
1340 sizeof(struct nf_conntrack_expect),
1342 if (!nf_conntrack_expect_cachep) {
1343 printk(KERN_ERR "Unable to create nf_expect slab cache\n");
1344 goto err_free_conntrack_slab;
1347 /* Don't NEED lock here, but good form anyway. */
1348 write_lock_bh(&nf_conntrack_lock);
1349 for (i = 0; i < PF_MAX; i++)
1350 nf_ct_l3protos[i] = &nf_conntrack_generic_l3proto;
1351 write_unlock_bh(&nf_conntrack_lock);
1353 /* For use by REJECT target */
1354 ip_ct_attach = __nf_conntrack_attach;
1356 /* Set up fake conntrack:
1357 - to never be deleted, not in any hashes */
1358 atomic_set(&nf_conntrack_untracked.ct_general.use, 1);
1359 /* - and look it like as a confirmed connection */
1360 set_bit(IPS_CONFIRMED_BIT, &nf_conntrack_untracked.status);
1364 err_free_conntrack_slab:
1365 nf_conntrack_unregister_cache(NF_CT_F_BASIC);
1367 free_conntrack_hash(nf_conntrack_hash, nf_conntrack_vmalloc,
1368 nf_conntrack_htable_size);