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