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