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