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