]> git.karo-electronics.de Git - karo-tx-linux.git/blob - net/netfilter/nf_conntrack_core.c
netfilter: nf_conntrack: make sequence number adjustments usuable without NAT
[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  * (C) 2005-2012 Patrick McHardy <kaber@trash.net>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License version 2 as
12  * published by the Free Software Foundation.
13  */
14
15 #include <linux/types.h>
16 #include <linux/netfilter.h>
17 #include <linux/module.h>
18 #include <linux/sched.h>
19 #include <linux/skbuff.h>
20 #include <linux/proc_fs.h>
21 #include <linux/vmalloc.h>
22 #include <linux/stddef.h>
23 #include <linux/slab.h>
24 #include <linux/random.h>
25 #include <linux/jhash.h>
26 #include <linux/err.h>
27 #include <linux/percpu.h>
28 #include <linux/moduleparam.h>
29 #include <linux/notifier.h>
30 #include <linux/kernel.h>
31 #include <linux/netdevice.h>
32 #include <linux/socket.h>
33 #include <linux/mm.h>
34 #include <linux/nsproxy.h>
35 #include <linux/rculist_nulls.h>
36
37 #include <net/netfilter/nf_conntrack.h>
38 #include <net/netfilter/nf_conntrack_l3proto.h>
39 #include <net/netfilter/nf_conntrack_l4proto.h>
40 #include <net/netfilter/nf_conntrack_expect.h>
41 #include <net/netfilter/nf_conntrack_helper.h>
42 #include <net/netfilter/nf_conntrack_seqadj.h>
43 #include <net/netfilter/nf_conntrack_core.h>
44 #include <net/netfilter/nf_conntrack_extend.h>
45 #include <net/netfilter/nf_conntrack_acct.h>
46 #include <net/netfilter/nf_conntrack_ecache.h>
47 #include <net/netfilter/nf_conntrack_zones.h>
48 #include <net/netfilter/nf_conntrack_timestamp.h>
49 #include <net/netfilter/nf_conntrack_timeout.h>
50 #include <net/netfilter/nf_conntrack_labels.h>
51 #include <net/netfilter/nf_nat.h>
52 #include <net/netfilter/nf_nat_core.h>
53 #include <net/netfilter/nf_nat_helper.h>
54
55 #define NF_CONNTRACK_VERSION    "0.5.0"
56
57 int (*nfnetlink_parse_nat_setup_hook)(struct nf_conn *ct,
58                                       enum nf_nat_manip_type manip,
59                                       const struct nlattr *attr) __read_mostly;
60 EXPORT_SYMBOL_GPL(nfnetlink_parse_nat_setup_hook);
61
62 int (*nf_nat_seq_adjust_hook)(struct sk_buff *skb,
63                               struct nf_conn *ct,
64                               enum ip_conntrack_info ctinfo,
65                               unsigned int protoff);
66 EXPORT_SYMBOL_GPL(nf_nat_seq_adjust_hook);
67
68 DEFINE_SPINLOCK(nf_conntrack_lock);
69 EXPORT_SYMBOL_GPL(nf_conntrack_lock);
70
71 unsigned int nf_conntrack_htable_size __read_mostly;
72 EXPORT_SYMBOL_GPL(nf_conntrack_htable_size);
73
74 unsigned int nf_conntrack_max __read_mostly;
75 EXPORT_SYMBOL_GPL(nf_conntrack_max);
76
77 DEFINE_PER_CPU(struct nf_conn, nf_conntrack_untracked);
78 EXPORT_PER_CPU_SYMBOL(nf_conntrack_untracked);
79
80 unsigned int nf_conntrack_hash_rnd __read_mostly;
81 EXPORT_SYMBOL_GPL(nf_conntrack_hash_rnd);
82
83 static u32 hash_conntrack_raw(const struct nf_conntrack_tuple *tuple, u16 zone)
84 {
85         unsigned int n;
86
87         /* The direction must be ignored, so we hash everything up to the
88          * destination ports (which is a multiple of 4) and treat the last
89          * three bytes manually.
90          */
91         n = (sizeof(tuple->src) + sizeof(tuple->dst.u3)) / sizeof(u32);
92         return jhash2((u32 *)tuple, n, zone ^ nf_conntrack_hash_rnd ^
93                       (((__force __u16)tuple->dst.u.all << 16) |
94                       tuple->dst.protonum));
95 }
96
97 static u32 __hash_bucket(u32 hash, unsigned int size)
98 {
99         return ((u64)hash * size) >> 32;
100 }
101
102 static u32 hash_bucket(u32 hash, const struct net *net)
103 {
104         return __hash_bucket(hash, net->ct.htable_size);
105 }
106
107 static u_int32_t __hash_conntrack(const struct nf_conntrack_tuple *tuple,
108                                   u16 zone, unsigned int size)
109 {
110         return __hash_bucket(hash_conntrack_raw(tuple, zone), size);
111 }
112
113 static inline u_int32_t hash_conntrack(const struct net *net, u16 zone,
114                                        const struct nf_conntrack_tuple *tuple)
115 {
116         return __hash_conntrack(tuple, zone, net->ct.htable_size);
117 }
118
119 bool
120 nf_ct_get_tuple(const struct sk_buff *skb,
121                 unsigned int nhoff,
122                 unsigned int dataoff,
123                 u_int16_t l3num,
124                 u_int8_t protonum,
125                 struct nf_conntrack_tuple *tuple,
126                 const struct nf_conntrack_l3proto *l3proto,
127                 const struct nf_conntrack_l4proto *l4proto)
128 {
129         memset(tuple, 0, sizeof(*tuple));
130
131         tuple->src.l3num = l3num;
132         if (l3proto->pkt_to_tuple(skb, nhoff, tuple) == 0)
133                 return false;
134
135         tuple->dst.protonum = protonum;
136         tuple->dst.dir = IP_CT_DIR_ORIGINAL;
137
138         return l4proto->pkt_to_tuple(skb, dataoff, tuple);
139 }
140 EXPORT_SYMBOL_GPL(nf_ct_get_tuple);
141
142 bool nf_ct_get_tuplepr(const struct sk_buff *skb, unsigned int nhoff,
143                        u_int16_t l3num, struct nf_conntrack_tuple *tuple)
144 {
145         struct nf_conntrack_l3proto *l3proto;
146         struct nf_conntrack_l4proto *l4proto;
147         unsigned int protoff;
148         u_int8_t protonum;
149         int ret;
150
151         rcu_read_lock();
152
153         l3proto = __nf_ct_l3proto_find(l3num);
154         ret = l3proto->get_l4proto(skb, nhoff, &protoff, &protonum);
155         if (ret != NF_ACCEPT) {
156                 rcu_read_unlock();
157                 return false;
158         }
159
160         l4proto = __nf_ct_l4proto_find(l3num, protonum);
161
162         ret = nf_ct_get_tuple(skb, nhoff, protoff, l3num, protonum, tuple,
163                               l3proto, l4proto);
164
165         rcu_read_unlock();
166         return ret;
167 }
168 EXPORT_SYMBOL_GPL(nf_ct_get_tuplepr);
169
170 bool
171 nf_ct_invert_tuple(struct nf_conntrack_tuple *inverse,
172                    const struct nf_conntrack_tuple *orig,
173                    const struct nf_conntrack_l3proto *l3proto,
174                    const struct nf_conntrack_l4proto *l4proto)
175 {
176         memset(inverse, 0, sizeof(*inverse));
177
178         inverse->src.l3num = orig->src.l3num;
179         if (l3proto->invert_tuple(inverse, orig) == 0)
180                 return false;
181
182         inverse->dst.dir = !orig->dst.dir;
183
184         inverse->dst.protonum = orig->dst.protonum;
185         return l4proto->invert_tuple(inverse, orig);
186 }
187 EXPORT_SYMBOL_GPL(nf_ct_invert_tuple);
188
189 static void
190 clean_from_lists(struct nf_conn *ct)
191 {
192         pr_debug("clean_from_lists(%p)\n", ct);
193         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
194         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode);
195
196         /* Destroy all pending expectations */
197         nf_ct_remove_expectations(ct);
198 }
199
200 static void
201 destroy_conntrack(struct nf_conntrack *nfct)
202 {
203         struct nf_conn *ct = (struct nf_conn *)nfct;
204         struct net *net = nf_ct_net(ct);
205         struct nf_conntrack_l4proto *l4proto;
206
207         pr_debug("destroy_conntrack(%p)\n", ct);
208         NF_CT_ASSERT(atomic_read(&nfct->use) == 0);
209         NF_CT_ASSERT(!timer_pending(&ct->timeout));
210
211         /* To make sure we don't get any weird locking issues here:
212          * destroy_conntrack() MUST NOT be called with a write lock
213          * to nf_conntrack_lock!!! -HW */
214         rcu_read_lock();
215         l4proto = __nf_ct_l4proto_find(nf_ct_l3num(ct), nf_ct_protonum(ct));
216         if (l4proto && l4proto->destroy)
217                 l4proto->destroy(ct);
218
219         rcu_read_unlock();
220
221         spin_lock_bh(&nf_conntrack_lock);
222         /* Expectations will have been removed in clean_from_lists,
223          * except TFTP can create an expectation on the first packet,
224          * before connection is in the list, so we need to clean here,
225          * too. */
226         nf_ct_remove_expectations(ct);
227
228         /* We overload first tuple to link into unconfirmed or dying list.*/
229         BUG_ON(hlist_nulls_unhashed(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode));
230         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
231
232         NF_CT_STAT_INC(net, delete);
233         spin_unlock_bh(&nf_conntrack_lock);
234
235         if (ct->master)
236                 nf_ct_put(ct->master);
237
238         pr_debug("destroy_conntrack: returning ct=%p to slab\n", ct);
239         nf_conntrack_free(ct);
240 }
241
242 static void nf_ct_delete_from_lists(struct nf_conn *ct)
243 {
244         struct net *net = nf_ct_net(ct);
245
246         nf_ct_helper_destroy(ct);
247         spin_lock_bh(&nf_conntrack_lock);
248         /* Inside lock so preempt is disabled on module removal path.
249          * Otherwise we can get spurious warnings. */
250         NF_CT_STAT_INC(net, delete_list);
251         clean_from_lists(ct);
252         /* add this conntrack to the dying list */
253         hlist_nulls_add_head(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
254                              &net->ct.dying);
255         spin_unlock_bh(&nf_conntrack_lock);
256 }
257
258 static void death_by_event(unsigned long ul_conntrack)
259 {
260         struct nf_conn *ct = (void *)ul_conntrack;
261         struct net *net = nf_ct_net(ct);
262         struct nf_conntrack_ecache *ecache = nf_ct_ecache_find(ct);
263
264         BUG_ON(ecache == NULL);
265
266         if (nf_conntrack_event(IPCT_DESTROY, ct) < 0) {
267                 /* bad luck, let's retry again */
268                 ecache->timeout.expires = jiffies +
269                         (prandom_u32() % net->ct.sysctl_events_retry_timeout);
270                 add_timer(&ecache->timeout);
271                 return;
272         }
273         /* we've got the event delivered, now it's dying */
274         set_bit(IPS_DYING_BIT, &ct->status);
275         nf_ct_put(ct);
276 }
277
278 static void nf_ct_dying_timeout(struct nf_conn *ct)
279 {
280         struct net *net = nf_ct_net(ct);
281         struct nf_conntrack_ecache *ecache = nf_ct_ecache_find(ct);
282
283         BUG_ON(ecache == NULL);
284
285         /* set a new timer to retry event delivery */
286         setup_timer(&ecache->timeout, death_by_event, (unsigned long)ct);
287         ecache->timeout.expires = jiffies +
288                 (prandom_u32() % net->ct.sysctl_events_retry_timeout);
289         add_timer(&ecache->timeout);
290 }
291
292 bool nf_ct_delete(struct nf_conn *ct, u32 portid, int report)
293 {
294         struct nf_conn_tstamp *tstamp;
295
296         tstamp = nf_conn_tstamp_find(ct);
297         if (tstamp && tstamp->stop == 0)
298                 tstamp->stop = ktime_to_ns(ktime_get_real());
299
300         if (!nf_ct_is_dying(ct) &&
301             unlikely(nf_conntrack_event_report(IPCT_DESTROY, ct,
302             portid, report) < 0)) {
303                 /* destroy event was not delivered */
304                 nf_ct_delete_from_lists(ct);
305                 nf_ct_dying_timeout(ct);
306                 return false;
307         }
308         set_bit(IPS_DYING_BIT, &ct->status);
309         nf_ct_delete_from_lists(ct);
310         nf_ct_put(ct);
311         return true;
312 }
313 EXPORT_SYMBOL_GPL(nf_ct_delete);
314
315 static void death_by_timeout(unsigned long ul_conntrack)
316 {
317         nf_ct_delete((struct nf_conn *)ul_conntrack, 0, 0);
318 }
319
320 /*
321  * Warning :
322  * - Caller must take a reference on returned object
323  *   and recheck nf_ct_tuple_equal(tuple, &h->tuple)
324  * OR
325  * - Caller must lock nf_conntrack_lock before calling this function
326  */
327 static struct nf_conntrack_tuple_hash *
328 ____nf_conntrack_find(struct net *net, u16 zone,
329                       const struct nf_conntrack_tuple *tuple, u32 hash)
330 {
331         struct nf_conntrack_tuple_hash *h;
332         struct hlist_nulls_node *n;
333         unsigned int bucket = hash_bucket(hash, net);
334
335         /* Disable BHs the entire time since we normally need to disable them
336          * at least once for the stats anyway.
337          */
338         local_bh_disable();
339 begin:
340         hlist_nulls_for_each_entry_rcu(h, n, &net->ct.hash[bucket], hnnode) {
341                 if (nf_ct_tuple_equal(tuple, &h->tuple) &&
342                     nf_ct_zone(nf_ct_tuplehash_to_ctrack(h)) == zone) {
343                         NF_CT_STAT_INC(net, found);
344                         local_bh_enable();
345                         return h;
346                 }
347                 NF_CT_STAT_INC(net, searched);
348         }
349         /*
350          * if the nulls value we got at the end of this lookup is
351          * not the expected one, we must restart lookup.
352          * We probably met an item that was moved to another chain.
353          */
354         if (get_nulls_value(n) != bucket) {
355                 NF_CT_STAT_INC(net, search_restart);
356                 goto begin;
357         }
358         local_bh_enable();
359
360         return NULL;
361 }
362
363 struct nf_conntrack_tuple_hash *
364 __nf_conntrack_find(struct net *net, u16 zone,
365                     const struct nf_conntrack_tuple *tuple)
366 {
367         return ____nf_conntrack_find(net, zone, tuple,
368                                      hash_conntrack_raw(tuple, zone));
369 }
370 EXPORT_SYMBOL_GPL(__nf_conntrack_find);
371
372 /* Find a connection corresponding to a tuple. */
373 static struct nf_conntrack_tuple_hash *
374 __nf_conntrack_find_get(struct net *net, u16 zone,
375                         const struct nf_conntrack_tuple *tuple, u32 hash)
376 {
377         struct nf_conntrack_tuple_hash *h;
378         struct nf_conn *ct;
379
380         rcu_read_lock();
381 begin:
382         h = ____nf_conntrack_find(net, zone, tuple, hash);
383         if (h) {
384                 ct = nf_ct_tuplehash_to_ctrack(h);
385                 if (unlikely(nf_ct_is_dying(ct) ||
386                              !atomic_inc_not_zero(&ct->ct_general.use)))
387                         h = NULL;
388                 else {
389                         if (unlikely(!nf_ct_tuple_equal(tuple, &h->tuple) ||
390                                      nf_ct_zone(ct) != zone)) {
391                                 nf_ct_put(ct);
392                                 goto begin;
393                         }
394                 }
395         }
396         rcu_read_unlock();
397
398         return h;
399 }
400
401 struct nf_conntrack_tuple_hash *
402 nf_conntrack_find_get(struct net *net, u16 zone,
403                       const struct nf_conntrack_tuple *tuple)
404 {
405         return __nf_conntrack_find_get(net, zone, tuple,
406                                        hash_conntrack_raw(tuple, zone));
407 }
408 EXPORT_SYMBOL_GPL(nf_conntrack_find_get);
409
410 static void __nf_conntrack_hash_insert(struct nf_conn *ct,
411                                        unsigned int hash,
412                                        unsigned int repl_hash)
413 {
414         struct net *net = nf_ct_net(ct);
415
416         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
417                            &net->ct.hash[hash]);
418         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode,
419                            &net->ct.hash[repl_hash]);
420 }
421
422 int
423 nf_conntrack_hash_check_insert(struct nf_conn *ct)
424 {
425         struct net *net = nf_ct_net(ct);
426         unsigned int hash, repl_hash;
427         struct nf_conntrack_tuple_hash *h;
428         struct hlist_nulls_node *n;
429         u16 zone;
430
431         zone = nf_ct_zone(ct);
432         hash = hash_conntrack(net, zone,
433                               &ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
434         repl_hash = hash_conntrack(net, zone,
435                                    &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
436
437         spin_lock_bh(&nf_conntrack_lock);
438
439         /* See if there's one in the list already, including reverse */
440         hlist_nulls_for_each_entry(h, n, &net->ct.hash[hash], hnnode)
441                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
442                                       &h->tuple) &&
443                     zone == nf_ct_zone(nf_ct_tuplehash_to_ctrack(h)))
444                         goto out;
445         hlist_nulls_for_each_entry(h, n, &net->ct.hash[repl_hash], hnnode)
446                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
447                                       &h->tuple) &&
448                     zone == nf_ct_zone(nf_ct_tuplehash_to_ctrack(h)))
449                         goto out;
450
451         add_timer(&ct->timeout);
452         nf_conntrack_get(&ct->ct_general);
453         __nf_conntrack_hash_insert(ct, hash, repl_hash);
454         NF_CT_STAT_INC(net, insert);
455         spin_unlock_bh(&nf_conntrack_lock);
456
457         return 0;
458
459 out:
460         NF_CT_STAT_INC(net, insert_failed);
461         spin_unlock_bh(&nf_conntrack_lock);
462         return -EEXIST;
463 }
464 EXPORT_SYMBOL_GPL(nf_conntrack_hash_check_insert);
465
466 /* Confirm a connection given skb; places it in hash table */
467 int
468 __nf_conntrack_confirm(struct sk_buff *skb)
469 {
470         unsigned int hash, repl_hash;
471         struct nf_conntrack_tuple_hash *h;
472         struct nf_conn *ct;
473         struct nf_conn_help *help;
474         struct nf_conn_tstamp *tstamp;
475         struct hlist_nulls_node *n;
476         enum ip_conntrack_info ctinfo;
477         struct net *net;
478         u16 zone;
479
480         ct = nf_ct_get(skb, &ctinfo);
481         net = nf_ct_net(ct);
482
483         /* ipt_REJECT uses nf_conntrack_attach to attach related
484            ICMP/TCP RST packets in other direction.  Actual packet
485            which created connection will be IP_CT_NEW or for an
486            expected connection, IP_CT_RELATED. */
487         if (CTINFO2DIR(ctinfo) != IP_CT_DIR_ORIGINAL)
488                 return NF_ACCEPT;
489
490         zone = nf_ct_zone(ct);
491         /* reuse the hash saved before */
492         hash = *(unsigned long *)&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev;
493         hash = hash_bucket(hash, net);
494         repl_hash = hash_conntrack(net, zone,
495                                    &ct->tuplehash[IP_CT_DIR_REPLY].tuple);
496
497         /* We're not in hash table, and we refuse to set up related
498            connections for unconfirmed conns.  But packet copies and
499            REJECT will give spurious warnings here. */
500         /* NF_CT_ASSERT(atomic_read(&ct->ct_general.use) == 1); */
501
502         /* No external references means no one else could have
503            confirmed us. */
504         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
505         pr_debug("Confirming conntrack %p\n", ct);
506
507         spin_lock_bh(&nf_conntrack_lock);
508
509         /* We have to check the DYING flag inside the lock to prevent
510            a race against nf_ct_get_next_corpse() possibly called from
511            user context, else we insert an already 'dead' hash, blocking
512            further use of that particular connection -JM */
513
514         if (unlikely(nf_ct_is_dying(ct))) {
515                 spin_unlock_bh(&nf_conntrack_lock);
516                 return NF_ACCEPT;
517         }
518
519         /* See if there's one in the list already, including reverse:
520            NAT could have grabbed it without realizing, since we're
521            not in the hash.  If there is, we lost race. */
522         hlist_nulls_for_each_entry(h, n, &net->ct.hash[hash], hnnode)
523                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple,
524                                       &h->tuple) &&
525                     zone == nf_ct_zone(nf_ct_tuplehash_to_ctrack(h)))
526                         goto out;
527         hlist_nulls_for_each_entry(h, n, &net->ct.hash[repl_hash], hnnode)
528                 if (nf_ct_tuple_equal(&ct->tuplehash[IP_CT_DIR_REPLY].tuple,
529                                       &h->tuple) &&
530                     zone == nf_ct_zone(nf_ct_tuplehash_to_ctrack(h)))
531                         goto out;
532
533         /* Remove from unconfirmed list */
534         hlist_nulls_del_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode);
535
536         /* Timer relative to confirmation time, not original
537            setting time, otherwise we'd get timer wrap in
538            weird delay cases. */
539         ct->timeout.expires += jiffies;
540         add_timer(&ct->timeout);
541         atomic_inc(&ct->ct_general.use);
542         ct->status |= IPS_CONFIRMED;
543
544         /* set conntrack timestamp, if enabled. */
545         tstamp = nf_conn_tstamp_find(ct);
546         if (tstamp) {
547                 if (skb->tstamp.tv64 == 0)
548                         __net_timestamp(skb);
549
550                 tstamp->start = ktime_to_ns(skb->tstamp);
551         }
552         /* Since the lookup is lockless, hash insertion must be done after
553          * starting the timer and setting the CONFIRMED bit. The RCU barriers
554          * guarantee that no other CPU can find the conntrack before the above
555          * stores are visible.
556          */
557         __nf_conntrack_hash_insert(ct, hash, repl_hash);
558         NF_CT_STAT_INC(net, insert);
559         spin_unlock_bh(&nf_conntrack_lock);
560
561         help = nfct_help(ct);
562         if (help && help->helper)
563                 nf_conntrack_event_cache(IPCT_HELPER, ct);
564
565         nf_conntrack_event_cache(master_ct(ct) ?
566                                  IPCT_RELATED : IPCT_NEW, ct);
567         return NF_ACCEPT;
568
569 out:
570         NF_CT_STAT_INC(net, insert_failed);
571         spin_unlock_bh(&nf_conntrack_lock);
572         return NF_DROP;
573 }
574 EXPORT_SYMBOL_GPL(__nf_conntrack_confirm);
575
576 /* Returns true if a connection correspondings to the tuple (required
577    for NAT). */
578 int
579 nf_conntrack_tuple_taken(const struct nf_conntrack_tuple *tuple,
580                          const struct nf_conn *ignored_conntrack)
581 {
582         struct net *net = nf_ct_net(ignored_conntrack);
583         struct nf_conntrack_tuple_hash *h;
584         struct hlist_nulls_node *n;
585         struct nf_conn *ct;
586         u16 zone = nf_ct_zone(ignored_conntrack);
587         unsigned int hash = hash_conntrack(net, zone, tuple);
588
589         /* Disable BHs the entire time since we need to disable them at
590          * least once for the stats anyway.
591          */
592         rcu_read_lock_bh();
593         hlist_nulls_for_each_entry_rcu(h, n, &net->ct.hash[hash], hnnode) {
594                 ct = nf_ct_tuplehash_to_ctrack(h);
595                 if (ct != ignored_conntrack &&
596                     nf_ct_tuple_equal(tuple, &h->tuple) &&
597                     nf_ct_zone(ct) == zone) {
598                         NF_CT_STAT_INC(net, found);
599                         rcu_read_unlock_bh();
600                         return 1;
601                 }
602                 NF_CT_STAT_INC(net, searched);
603         }
604         rcu_read_unlock_bh();
605
606         return 0;
607 }
608 EXPORT_SYMBOL_GPL(nf_conntrack_tuple_taken);
609
610 #define NF_CT_EVICTION_RANGE    8
611
612 /* There's a small race here where we may free a just-assured
613    connection.  Too bad: we're in trouble anyway. */
614 static noinline int early_drop(struct net *net, unsigned int hash)
615 {
616         /* Use oldest entry, which is roughly LRU */
617         struct nf_conntrack_tuple_hash *h;
618         struct nf_conn *ct = NULL, *tmp;
619         struct hlist_nulls_node *n;
620         unsigned int i, cnt = 0;
621         int dropped = 0;
622
623         rcu_read_lock();
624         for (i = 0; i < net->ct.htable_size; i++) {
625                 hlist_nulls_for_each_entry_rcu(h, n, &net->ct.hash[hash],
626                                          hnnode) {
627                         tmp = nf_ct_tuplehash_to_ctrack(h);
628                         if (!test_bit(IPS_ASSURED_BIT, &tmp->status))
629                                 ct = tmp;
630                         cnt++;
631                 }
632
633                 if (ct != NULL) {
634                         if (likely(!nf_ct_is_dying(ct) &&
635                                    atomic_inc_not_zero(&ct->ct_general.use)))
636                                 break;
637                         else
638                                 ct = NULL;
639                 }
640
641                 if (cnt >= NF_CT_EVICTION_RANGE)
642                         break;
643
644                 hash = (hash + 1) % net->ct.htable_size;
645         }
646         rcu_read_unlock();
647
648         if (!ct)
649                 return dropped;
650
651         if (del_timer(&ct->timeout)) {
652                 if (nf_ct_delete(ct, 0, 0)) {
653                         dropped = 1;
654                         NF_CT_STAT_INC_ATOMIC(net, early_drop);
655                 }
656         }
657         nf_ct_put(ct);
658         return dropped;
659 }
660
661 void init_nf_conntrack_hash_rnd(void)
662 {
663         unsigned int rand;
664
665         /*
666          * Why not initialize nf_conntrack_rnd in a "init()" function ?
667          * Because there isn't enough entropy when system initializing,
668          * and we initialize it as late as possible.
669          */
670         do {
671                 get_random_bytes(&rand, sizeof(rand));
672         } while (!rand);
673         cmpxchg(&nf_conntrack_hash_rnd, 0, rand);
674 }
675
676 static struct nf_conn *
677 __nf_conntrack_alloc(struct net *net, u16 zone,
678                      const struct nf_conntrack_tuple *orig,
679                      const struct nf_conntrack_tuple *repl,
680                      gfp_t gfp, u32 hash)
681 {
682         struct nf_conn *ct;
683
684         if (unlikely(!nf_conntrack_hash_rnd)) {
685                 init_nf_conntrack_hash_rnd();
686                 /* recompute the hash as nf_conntrack_hash_rnd is initialized */
687                 hash = hash_conntrack_raw(orig, zone);
688         }
689
690         /* We don't want any race condition at early drop stage */
691         atomic_inc(&net->ct.count);
692
693         if (nf_conntrack_max &&
694             unlikely(atomic_read(&net->ct.count) > nf_conntrack_max)) {
695                 if (!early_drop(net, hash_bucket(hash, net))) {
696                         atomic_dec(&net->ct.count);
697                         net_warn_ratelimited("nf_conntrack: table full, dropping packet\n");
698                         return ERR_PTR(-ENOMEM);
699                 }
700         }
701
702         /*
703          * Do not use kmem_cache_zalloc(), as this cache uses
704          * SLAB_DESTROY_BY_RCU.
705          */
706         ct = kmem_cache_alloc(net->ct.nf_conntrack_cachep, gfp);
707         if (ct == NULL) {
708                 atomic_dec(&net->ct.count);
709                 return ERR_PTR(-ENOMEM);
710         }
711         /*
712          * Let ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.next
713          * and ct->tuplehash[IP_CT_DIR_REPLY].hnnode.next unchanged.
714          */
715         memset(&ct->tuplehash[IP_CT_DIR_MAX], 0,
716                offsetof(struct nf_conn, proto) -
717                offsetof(struct nf_conn, tuplehash[IP_CT_DIR_MAX]));
718         spin_lock_init(&ct->lock);
719         ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple = *orig;
720         ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode.pprev = NULL;
721         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *repl;
722         /* save hash for reusing when confirming */
723         *(unsigned long *)(&ct->tuplehash[IP_CT_DIR_REPLY].hnnode.pprev) = hash;
724         /* Don't set timer yet: wait for confirmation */
725         setup_timer(&ct->timeout, death_by_timeout, (unsigned long)ct);
726         write_pnet(&ct->ct_net, net);
727 #ifdef CONFIG_NF_CONNTRACK_ZONES
728         if (zone) {
729                 struct nf_conntrack_zone *nf_ct_zone;
730
731                 nf_ct_zone = nf_ct_ext_add(ct, NF_CT_EXT_ZONE, GFP_ATOMIC);
732                 if (!nf_ct_zone)
733                         goto out_free;
734                 nf_ct_zone->id = zone;
735         }
736 #endif
737         /*
738          * changes to lookup keys must be done before setting refcnt to 1
739          */
740         smp_wmb();
741         atomic_set(&ct->ct_general.use, 1);
742         return ct;
743
744 #ifdef CONFIG_NF_CONNTRACK_ZONES
745 out_free:
746         atomic_dec(&net->ct.count);
747         kmem_cache_free(net->ct.nf_conntrack_cachep, ct);
748         return ERR_PTR(-ENOMEM);
749 #endif
750 }
751
752 struct nf_conn *nf_conntrack_alloc(struct net *net, u16 zone,
753                                    const struct nf_conntrack_tuple *orig,
754                                    const struct nf_conntrack_tuple *repl,
755                                    gfp_t gfp)
756 {
757         return __nf_conntrack_alloc(net, zone, orig, repl, gfp, 0);
758 }
759 EXPORT_SYMBOL_GPL(nf_conntrack_alloc);
760
761 void nf_conntrack_free(struct nf_conn *ct)
762 {
763         struct net *net = nf_ct_net(ct);
764
765         nf_ct_ext_destroy(ct);
766         atomic_dec(&net->ct.count);
767         nf_ct_ext_free(ct);
768         kmem_cache_free(net->ct.nf_conntrack_cachep, ct);
769 }
770 EXPORT_SYMBOL_GPL(nf_conntrack_free);
771
772
773 /* Allocate a new conntrack: we return -ENOMEM if classification
774    failed due to stress.  Otherwise it really is unclassifiable. */
775 static struct nf_conntrack_tuple_hash *
776 init_conntrack(struct net *net, struct nf_conn *tmpl,
777                const struct nf_conntrack_tuple *tuple,
778                struct nf_conntrack_l3proto *l3proto,
779                struct nf_conntrack_l4proto *l4proto,
780                struct sk_buff *skb,
781                unsigned int dataoff, u32 hash)
782 {
783         struct nf_conn *ct;
784         struct nf_conn_help *help;
785         struct nf_conntrack_tuple repl_tuple;
786         struct nf_conntrack_ecache *ecache;
787         struct nf_conntrack_expect *exp;
788         u16 zone = tmpl ? nf_ct_zone(tmpl) : NF_CT_DEFAULT_ZONE;
789         struct nf_conn_timeout *timeout_ext;
790         unsigned int *timeouts;
791
792         if (!nf_ct_invert_tuple(&repl_tuple, tuple, l3proto, l4proto)) {
793                 pr_debug("Can't invert tuple.\n");
794                 return NULL;
795         }
796
797         ct = __nf_conntrack_alloc(net, zone, tuple, &repl_tuple, GFP_ATOMIC,
798                                   hash);
799         if (IS_ERR(ct))
800                 return (struct nf_conntrack_tuple_hash *)ct;
801
802         timeout_ext = tmpl ? nf_ct_timeout_find(tmpl) : NULL;
803         if (timeout_ext)
804                 timeouts = NF_CT_TIMEOUT_EXT_DATA(timeout_ext);
805         else
806                 timeouts = l4proto->get_timeouts(net);
807
808         if (!l4proto->new(ct, skb, dataoff, timeouts)) {
809                 nf_conntrack_free(ct);
810                 pr_debug("init conntrack: can't track with proto module\n");
811                 return NULL;
812         }
813
814         if (timeout_ext)
815                 nf_ct_timeout_ext_add(ct, timeout_ext->timeout, GFP_ATOMIC);
816
817         nf_ct_acct_ext_add(ct, GFP_ATOMIC);
818         nf_ct_tstamp_ext_add(ct, GFP_ATOMIC);
819         nf_ct_labels_ext_add(ct);
820
821         ecache = tmpl ? nf_ct_ecache_find(tmpl) : NULL;
822         nf_ct_ecache_ext_add(ct, ecache ? ecache->ctmask : 0,
823                                  ecache ? ecache->expmask : 0,
824                              GFP_ATOMIC);
825
826         spin_lock_bh(&nf_conntrack_lock);
827         exp = nf_ct_find_expectation(net, zone, tuple);
828         if (exp) {
829                 pr_debug("conntrack: expectation arrives ct=%p exp=%p\n",
830                          ct, exp);
831                 /* Welcome, Mr. Bond.  We've been expecting you... */
832                 __set_bit(IPS_EXPECTED_BIT, &ct->status);
833                 ct->master = exp->master;
834                 if (exp->helper) {
835                         help = nf_ct_helper_ext_add(ct, exp->helper,
836                                                     GFP_ATOMIC);
837                         if (help)
838                                 rcu_assign_pointer(help->helper, exp->helper);
839                 }
840
841 #ifdef CONFIG_NF_CONNTRACK_MARK
842                 ct->mark = exp->master->mark;
843 #endif
844 #ifdef CONFIG_NF_CONNTRACK_SECMARK
845                 ct->secmark = exp->master->secmark;
846 #endif
847                 nf_conntrack_get(&ct->master->ct_general);
848                 NF_CT_STAT_INC(net, expect_new);
849         } else {
850                 __nf_ct_try_assign_helper(ct, tmpl, GFP_ATOMIC);
851                 NF_CT_STAT_INC(net, new);
852         }
853
854         /* Overload tuple linked list to put us in unconfirmed list. */
855         hlist_nulls_add_head_rcu(&ct->tuplehash[IP_CT_DIR_ORIGINAL].hnnode,
856                        &net->ct.unconfirmed);
857
858         spin_unlock_bh(&nf_conntrack_lock);
859
860         if (exp) {
861                 if (exp->expectfn)
862                         exp->expectfn(ct, exp);
863                 nf_ct_expect_put(exp);
864         }
865
866         return &ct->tuplehash[IP_CT_DIR_ORIGINAL];
867 }
868
869 /* On success, returns conntrack ptr, sets skb->nfct and ctinfo */
870 static inline struct nf_conn *
871 resolve_normal_ct(struct net *net, struct nf_conn *tmpl,
872                   struct sk_buff *skb,
873                   unsigned int dataoff,
874                   u_int16_t l3num,
875                   u_int8_t protonum,
876                   struct nf_conntrack_l3proto *l3proto,
877                   struct nf_conntrack_l4proto *l4proto,
878                   int *set_reply,
879                   enum ip_conntrack_info *ctinfo)
880 {
881         struct nf_conntrack_tuple tuple;
882         struct nf_conntrack_tuple_hash *h;
883         struct nf_conn *ct;
884         u16 zone = tmpl ? nf_ct_zone(tmpl) : NF_CT_DEFAULT_ZONE;
885         u32 hash;
886
887         if (!nf_ct_get_tuple(skb, skb_network_offset(skb),
888                              dataoff, l3num, protonum, &tuple, l3proto,
889                              l4proto)) {
890                 pr_debug("resolve_normal_ct: Can't get tuple\n");
891                 return NULL;
892         }
893
894         /* look for tuple match */
895         hash = hash_conntrack_raw(&tuple, zone);
896         h = __nf_conntrack_find_get(net, zone, &tuple, hash);
897         if (!h) {
898                 h = init_conntrack(net, tmpl, &tuple, l3proto, l4proto,
899                                    skb, dataoff, hash);
900                 if (!h)
901                         return NULL;
902                 if (IS_ERR(h))
903                         return (void *)h;
904         }
905         ct = nf_ct_tuplehash_to_ctrack(h);
906
907         /* It exists; we have (non-exclusive) reference. */
908         if (NF_CT_DIRECTION(h) == IP_CT_DIR_REPLY) {
909                 *ctinfo = IP_CT_ESTABLISHED_REPLY;
910                 /* Please set reply bit if this packet OK */
911                 *set_reply = 1;
912         } else {
913                 /* Once we've had two way comms, always ESTABLISHED. */
914                 if (test_bit(IPS_SEEN_REPLY_BIT, &ct->status)) {
915                         pr_debug("nf_conntrack_in: normal packet for %p\n", ct);
916                         *ctinfo = IP_CT_ESTABLISHED;
917                 } else if (test_bit(IPS_EXPECTED_BIT, &ct->status)) {
918                         pr_debug("nf_conntrack_in: related packet for %p\n",
919                                  ct);
920                         *ctinfo = IP_CT_RELATED;
921                 } else {
922                         pr_debug("nf_conntrack_in: new packet for %p\n", ct);
923                         *ctinfo = IP_CT_NEW;
924                 }
925                 *set_reply = 0;
926         }
927         skb->nfct = &ct->ct_general;
928         skb->nfctinfo = *ctinfo;
929         return ct;
930 }
931
932 unsigned int
933 nf_conntrack_in(struct net *net, u_int8_t pf, unsigned int hooknum,
934                 struct sk_buff *skb)
935 {
936         struct nf_conn *ct, *tmpl = NULL;
937         enum ip_conntrack_info ctinfo;
938         struct nf_conntrack_l3proto *l3proto;
939         struct nf_conntrack_l4proto *l4proto;
940         unsigned int *timeouts;
941         unsigned int dataoff;
942         u_int8_t protonum;
943         int set_reply = 0;
944         int ret;
945
946         if (skb->nfct) {
947                 /* Previously seen (loopback or untracked)?  Ignore. */
948                 tmpl = (struct nf_conn *)skb->nfct;
949                 if (!nf_ct_is_template(tmpl)) {
950                         NF_CT_STAT_INC_ATOMIC(net, ignore);
951                         return NF_ACCEPT;
952                 }
953                 skb->nfct = NULL;
954         }
955
956         /* rcu_read_lock()ed by nf_hook_slow */
957         l3proto = __nf_ct_l3proto_find(pf);
958         ret = l3proto->get_l4proto(skb, skb_network_offset(skb),
959                                    &dataoff, &protonum);
960         if (ret <= 0) {
961                 pr_debug("not prepared to track yet or error occurred\n");
962                 NF_CT_STAT_INC_ATOMIC(net, error);
963                 NF_CT_STAT_INC_ATOMIC(net, invalid);
964                 ret = -ret;
965                 goto out;
966         }
967
968         l4proto = __nf_ct_l4proto_find(pf, protonum);
969
970         /* It may be an special packet, error, unclean...
971          * inverse of the return code tells to the netfilter
972          * core what to do with the packet. */
973         if (l4proto->error != NULL) {
974                 ret = l4proto->error(net, tmpl, skb, dataoff, &ctinfo,
975                                      pf, hooknum);
976                 if (ret <= 0) {
977                         NF_CT_STAT_INC_ATOMIC(net, error);
978                         NF_CT_STAT_INC_ATOMIC(net, invalid);
979                         ret = -ret;
980                         goto out;
981                 }
982                 /* ICMP[v6] protocol trackers may assign one conntrack. */
983                 if (skb->nfct)
984                         goto out;
985         }
986
987         ct = resolve_normal_ct(net, tmpl, skb, dataoff, pf, protonum,
988                                l3proto, l4proto, &set_reply, &ctinfo);
989         if (!ct) {
990                 /* Not valid part of a connection */
991                 NF_CT_STAT_INC_ATOMIC(net, invalid);
992                 ret = NF_ACCEPT;
993                 goto out;
994         }
995
996         if (IS_ERR(ct)) {
997                 /* Too stressed to deal. */
998                 NF_CT_STAT_INC_ATOMIC(net, drop);
999                 ret = NF_DROP;
1000                 goto out;
1001         }
1002
1003         NF_CT_ASSERT(skb->nfct);
1004
1005         /* Decide what timeout policy we want to apply to this flow. */
1006         timeouts = nf_ct_timeout_lookup(net, ct, l4proto);
1007
1008         ret = l4proto->packet(ct, skb, dataoff, ctinfo, pf, hooknum, timeouts);
1009         if (ret <= 0) {
1010                 /* Invalid: inverse of the return code tells
1011                  * the netfilter core what to do */
1012                 pr_debug("nf_conntrack_in: Can't track with proto module\n");
1013                 nf_conntrack_put(skb->nfct);
1014                 skb->nfct = NULL;
1015                 NF_CT_STAT_INC_ATOMIC(net, invalid);
1016                 if (ret == -NF_DROP)
1017                         NF_CT_STAT_INC_ATOMIC(net, drop);
1018                 ret = -ret;
1019                 goto out;
1020         }
1021
1022         if (set_reply && !test_and_set_bit(IPS_SEEN_REPLY_BIT, &ct->status))
1023                 nf_conntrack_event_cache(IPCT_REPLY, ct);
1024 out:
1025         if (tmpl) {
1026                 /* Special case: we have to repeat this hook, assign the
1027                  * template again to this packet. We assume that this packet
1028                  * has no conntrack assigned. This is used by nf_ct_tcp. */
1029                 if (ret == NF_REPEAT)
1030                         skb->nfct = (struct nf_conntrack *)tmpl;
1031                 else
1032                         nf_ct_put(tmpl);
1033         }
1034
1035         return ret;
1036 }
1037 EXPORT_SYMBOL_GPL(nf_conntrack_in);
1038
1039 bool nf_ct_invert_tuplepr(struct nf_conntrack_tuple *inverse,
1040                           const struct nf_conntrack_tuple *orig)
1041 {
1042         bool ret;
1043
1044         rcu_read_lock();
1045         ret = nf_ct_invert_tuple(inverse, orig,
1046                                  __nf_ct_l3proto_find(orig->src.l3num),
1047                                  __nf_ct_l4proto_find(orig->src.l3num,
1048                                                       orig->dst.protonum));
1049         rcu_read_unlock();
1050         return ret;
1051 }
1052 EXPORT_SYMBOL_GPL(nf_ct_invert_tuplepr);
1053
1054 /* Alter reply tuple (maybe alter helper).  This is for NAT, and is
1055    implicitly racy: see __nf_conntrack_confirm */
1056 void nf_conntrack_alter_reply(struct nf_conn *ct,
1057                               const struct nf_conntrack_tuple *newreply)
1058 {
1059         struct nf_conn_help *help = nfct_help(ct);
1060
1061         /* Should be unconfirmed, so not in hash table yet */
1062         NF_CT_ASSERT(!nf_ct_is_confirmed(ct));
1063
1064         pr_debug("Altering reply tuple of %p to ", ct);
1065         nf_ct_dump_tuple(newreply);
1066
1067         ct->tuplehash[IP_CT_DIR_REPLY].tuple = *newreply;
1068         if (ct->master || (help && !hlist_empty(&help->expectations)))
1069                 return;
1070
1071         rcu_read_lock();
1072         __nf_ct_try_assign_helper(ct, NULL, GFP_ATOMIC);
1073         rcu_read_unlock();
1074 }
1075 EXPORT_SYMBOL_GPL(nf_conntrack_alter_reply);
1076
1077 /* Refresh conntrack for this many jiffies and do accounting if do_acct is 1 */
1078 void __nf_ct_refresh_acct(struct nf_conn *ct,
1079                           enum ip_conntrack_info ctinfo,
1080                           const struct sk_buff *skb,
1081                           unsigned long extra_jiffies,
1082                           int do_acct)
1083 {
1084         NF_CT_ASSERT(ct->timeout.data == (unsigned long)ct);
1085         NF_CT_ASSERT(skb);
1086
1087         /* Only update if this is not a fixed timeout */
1088         if (test_bit(IPS_FIXED_TIMEOUT_BIT, &ct->status))
1089                 goto acct;
1090
1091         /* If not in hash table, timer will not be active yet */
1092         if (!nf_ct_is_confirmed(ct)) {
1093                 ct->timeout.expires = extra_jiffies;
1094         } else {
1095                 unsigned long newtime = jiffies + extra_jiffies;
1096
1097                 /* Only update the timeout if the new timeout is at least
1098                    HZ jiffies from the old timeout. Need del_timer for race
1099                    avoidance (may already be dying). */
1100                 if (newtime - ct->timeout.expires >= HZ)
1101                         mod_timer_pending(&ct->timeout, newtime);
1102         }
1103
1104 acct:
1105         if (do_acct) {
1106                 struct nf_conn_counter *acct;
1107
1108                 acct = nf_conn_acct_find(ct);
1109                 if (acct) {
1110                         atomic64_inc(&acct[CTINFO2DIR(ctinfo)].packets);
1111                         atomic64_add(skb->len, &acct[CTINFO2DIR(ctinfo)].bytes);
1112                 }
1113         }
1114 }
1115 EXPORT_SYMBOL_GPL(__nf_ct_refresh_acct);
1116
1117 bool __nf_ct_kill_acct(struct nf_conn *ct,
1118                        enum ip_conntrack_info ctinfo,
1119                        const struct sk_buff *skb,
1120                        int do_acct)
1121 {
1122         if (do_acct) {
1123                 struct nf_conn_counter *acct;
1124
1125                 acct = nf_conn_acct_find(ct);
1126                 if (acct) {
1127                         atomic64_inc(&acct[CTINFO2DIR(ctinfo)].packets);
1128                         atomic64_add(skb->len - skb_network_offset(skb),
1129                                      &acct[CTINFO2DIR(ctinfo)].bytes);
1130                 }
1131         }
1132
1133         if (del_timer(&ct->timeout)) {
1134                 ct->timeout.function((unsigned long)ct);
1135                 return true;
1136         }
1137         return false;
1138 }
1139 EXPORT_SYMBOL_GPL(__nf_ct_kill_acct);
1140
1141 #ifdef CONFIG_NF_CONNTRACK_ZONES
1142 static struct nf_ct_ext_type nf_ct_zone_extend __read_mostly = {
1143         .len    = sizeof(struct nf_conntrack_zone),
1144         .align  = __alignof__(struct nf_conntrack_zone),
1145         .id     = NF_CT_EXT_ZONE,
1146 };
1147 #endif
1148
1149 #if IS_ENABLED(CONFIG_NF_CT_NETLINK)
1150
1151 #include <linux/netfilter/nfnetlink.h>
1152 #include <linux/netfilter/nfnetlink_conntrack.h>
1153 #include <linux/mutex.h>
1154
1155 /* Generic function for tcp/udp/sctp/dccp and alike. This needs to be
1156  * in ip_conntrack_core, since we don't want the protocols to autoload
1157  * or depend on ctnetlink */
1158 int nf_ct_port_tuple_to_nlattr(struct sk_buff *skb,
1159                                const struct nf_conntrack_tuple *tuple)
1160 {
1161         if (nla_put_be16(skb, CTA_PROTO_SRC_PORT, tuple->src.u.tcp.port) ||
1162             nla_put_be16(skb, CTA_PROTO_DST_PORT, tuple->dst.u.tcp.port))
1163                 goto nla_put_failure;
1164         return 0;
1165
1166 nla_put_failure:
1167         return -1;
1168 }
1169 EXPORT_SYMBOL_GPL(nf_ct_port_tuple_to_nlattr);
1170
1171 const struct nla_policy nf_ct_port_nla_policy[CTA_PROTO_MAX+1] = {
1172         [CTA_PROTO_SRC_PORT]  = { .type = NLA_U16 },
1173         [CTA_PROTO_DST_PORT]  = { .type = NLA_U16 },
1174 };
1175 EXPORT_SYMBOL_GPL(nf_ct_port_nla_policy);
1176
1177 int nf_ct_port_nlattr_to_tuple(struct nlattr *tb[],
1178                                struct nf_conntrack_tuple *t)
1179 {
1180         if (!tb[CTA_PROTO_SRC_PORT] || !tb[CTA_PROTO_DST_PORT])
1181                 return -EINVAL;
1182
1183         t->src.u.tcp.port = nla_get_be16(tb[CTA_PROTO_SRC_PORT]);
1184         t->dst.u.tcp.port = nla_get_be16(tb[CTA_PROTO_DST_PORT]);
1185
1186         return 0;
1187 }
1188 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_to_tuple);
1189
1190 int nf_ct_port_nlattr_tuple_size(void)
1191 {
1192         return nla_policy_len(nf_ct_port_nla_policy, CTA_PROTO_MAX + 1);
1193 }
1194 EXPORT_SYMBOL_GPL(nf_ct_port_nlattr_tuple_size);
1195 #endif
1196
1197 /* Used by ipt_REJECT and ip6t_REJECT. */
1198 static void nf_conntrack_attach(struct sk_buff *nskb, const struct sk_buff *skb)
1199 {
1200         struct nf_conn *ct;
1201         enum ip_conntrack_info ctinfo;
1202
1203         /* This ICMP is in reverse direction to the packet which caused it */
1204         ct = nf_ct_get(skb, &ctinfo);
1205         if (CTINFO2DIR(ctinfo) == IP_CT_DIR_ORIGINAL)
1206                 ctinfo = IP_CT_RELATED_REPLY;
1207         else
1208                 ctinfo = IP_CT_RELATED;
1209
1210         /* Attach to new skbuff, and increment count */
1211         nskb->nfct = &ct->ct_general;
1212         nskb->nfctinfo = ctinfo;
1213         nf_conntrack_get(nskb->nfct);
1214 }
1215
1216 /* Bring out ya dead! */
1217 static struct nf_conn *
1218 get_next_corpse(struct net *net, int (*iter)(struct nf_conn *i, void *data),
1219                 void *data, unsigned int *bucket)
1220 {
1221         struct nf_conntrack_tuple_hash *h;
1222         struct nf_conn *ct;
1223         struct hlist_nulls_node *n;
1224
1225         spin_lock_bh(&nf_conntrack_lock);
1226         for (; *bucket < net->ct.htable_size; (*bucket)++) {
1227                 hlist_nulls_for_each_entry(h, n, &net->ct.hash[*bucket], hnnode) {
1228                         if (NF_CT_DIRECTION(h) != IP_CT_DIR_ORIGINAL)
1229                                 continue;
1230                         ct = nf_ct_tuplehash_to_ctrack(h);
1231                         if (iter(ct, data))
1232                                 goto found;
1233                 }
1234         }
1235         hlist_nulls_for_each_entry(h, n, &net->ct.unconfirmed, hnnode) {
1236                 ct = nf_ct_tuplehash_to_ctrack(h);
1237                 if (iter(ct, data))
1238                         set_bit(IPS_DYING_BIT, &ct->status);
1239         }
1240         spin_unlock_bh(&nf_conntrack_lock);
1241         return NULL;
1242 found:
1243         atomic_inc(&ct->ct_general.use);
1244         spin_unlock_bh(&nf_conntrack_lock);
1245         return ct;
1246 }
1247
1248 void nf_ct_iterate_cleanup(struct net *net,
1249                            int (*iter)(struct nf_conn *i, void *data),
1250                            void *data, u32 portid, int report)
1251 {
1252         struct nf_conn *ct;
1253         unsigned int bucket = 0;
1254
1255         while ((ct = get_next_corpse(net, iter, data, &bucket)) != NULL) {
1256                 /* Time to push up daises... */
1257                 if (del_timer(&ct->timeout))
1258                         nf_ct_delete(ct, portid, report);
1259
1260                 /* ... else the timer will get him soon. */
1261
1262                 nf_ct_put(ct);
1263         }
1264 }
1265 EXPORT_SYMBOL_GPL(nf_ct_iterate_cleanup);
1266
1267 static int kill_all(struct nf_conn *i, void *data)
1268 {
1269         return 1;
1270 }
1271
1272 void nf_ct_free_hashtable(void *hash, unsigned int size)
1273 {
1274         if (is_vmalloc_addr(hash))
1275                 vfree(hash);
1276         else
1277                 free_pages((unsigned long)hash,
1278                            get_order(sizeof(struct hlist_head) * size));
1279 }
1280 EXPORT_SYMBOL_GPL(nf_ct_free_hashtable);
1281
1282 void nf_conntrack_flush_report(struct net *net, u32 portid, int report)
1283 {
1284         nf_ct_iterate_cleanup(net, kill_all, NULL, portid, report);
1285 }
1286 EXPORT_SYMBOL_GPL(nf_conntrack_flush_report);
1287
1288 static void nf_ct_release_dying_list(struct net *net)
1289 {
1290         struct nf_conntrack_tuple_hash *h;
1291         struct nf_conn *ct;
1292         struct hlist_nulls_node *n;
1293
1294         spin_lock_bh(&nf_conntrack_lock);
1295         hlist_nulls_for_each_entry(h, n, &net->ct.dying, hnnode) {
1296                 ct = nf_ct_tuplehash_to_ctrack(h);
1297                 /* never fails to remove them, no listeners at this point */
1298                 nf_ct_kill(ct);
1299         }
1300         spin_unlock_bh(&nf_conntrack_lock);
1301 }
1302
1303 static int untrack_refs(void)
1304 {
1305         int cnt = 0, cpu;
1306
1307         for_each_possible_cpu(cpu) {
1308                 struct nf_conn *ct = &per_cpu(nf_conntrack_untracked, cpu);
1309
1310                 cnt += atomic_read(&ct->ct_general.use) - 1;
1311         }
1312         return cnt;
1313 }
1314
1315 void nf_conntrack_cleanup_start(void)
1316 {
1317         RCU_INIT_POINTER(ip_ct_attach, NULL);
1318 }
1319
1320 void nf_conntrack_cleanup_end(void)
1321 {
1322         RCU_INIT_POINTER(nf_ct_destroy, NULL);
1323         while (untrack_refs() > 0)
1324                 schedule();
1325
1326 #ifdef CONFIG_NF_CONNTRACK_ZONES
1327         nf_ct_extend_unregister(&nf_ct_zone_extend);
1328 #endif
1329         nf_conntrack_proto_fini();
1330         nf_conntrack_seqadj_fini();
1331         nf_conntrack_labels_fini();
1332         nf_conntrack_helper_fini();
1333         nf_conntrack_timeout_fini();
1334         nf_conntrack_ecache_fini();
1335         nf_conntrack_tstamp_fini();
1336         nf_conntrack_acct_fini();
1337         nf_conntrack_expect_fini();
1338 }
1339
1340 /*
1341  * Mishearing the voices in his head, our hero wonders how he's
1342  * supposed to kill the mall.
1343  */
1344 void nf_conntrack_cleanup_net(struct net *net)
1345 {
1346         LIST_HEAD(single);
1347
1348         list_add(&net->exit_list, &single);
1349         nf_conntrack_cleanup_net_list(&single);
1350 }
1351
1352 void nf_conntrack_cleanup_net_list(struct list_head *net_exit_list)
1353 {
1354         int busy;
1355         struct net *net;
1356
1357         /*
1358          * This makes sure all current packets have passed through
1359          *  netfilter framework.  Roll on, two-stage module
1360          *  delete...
1361          */
1362         synchronize_net();
1363 i_see_dead_people:
1364         busy = 0;
1365         list_for_each_entry(net, net_exit_list, exit_list) {
1366                 nf_ct_iterate_cleanup(net, kill_all, NULL, 0, 0);
1367                 nf_ct_release_dying_list(net);
1368                 if (atomic_read(&net->ct.count) != 0)
1369                         busy = 1;
1370         }
1371         if (busy) {
1372                 schedule();
1373                 goto i_see_dead_people;
1374         }
1375
1376         list_for_each_entry(net, net_exit_list, exit_list) {
1377                 nf_ct_free_hashtable(net->ct.hash, net->ct.htable_size);
1378                 nf_conntrack_proto_pernet_fini(net);
1379                 nf_conntrack_helper_pernet_fini(net);
1380                 nf_conntrack_ecache_pernet_fini(net);
1381                 nf_conntrack_tstamp_pernet_fini(net);
1382                 nf_conntrack_acct_pernet_fini(net);
1383                 nf_conntrack_expect_pernet_fini(net);
1384                 kmem_cache_destroy(net->ct.nf_conntrack_cachep);
1385                 kfree(net->ct.slabname);
1386                 free_percpu(net->ct.stat);
1387         }
1388 }
1389
1390 void *nf_ct_alloc_hashtable(unsigned int *sizep, int nulls)
1391 {
1392         struct hlist_nulls_head *hash;
1393         unsigned int nr_slots, i;
1394         size_t sz;
1395
1396         BUILD_BUG_ON(sizeof(struct hlist_nulls_head) != sizeof(struct hlist_head));
1397         nr_slots = *sizep = roundup(*sizep, PAGE_SIZE / sizeof(struct hlist_nulls_head));
1398         sz = nr_slots * sizeof(struct hlist_nulls_head);
1399         hash = (void *)__get_free_pages(GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO,
1400                                         get_order(sz));
1401         if (!hash) {
1402                 printk(KERN_WARNING "nf_conntrack: falling back to vmalloc.\n");
1403                 hash = vzalloc(sz);
1404         }
1405
1406         if (hash && nulls)
1407                 for (i = 0; i < nr_slots; i++)
1408                         INIT_HLIST_NULLS_HEAD(&hash[i], i);
1409
1410         return hash;
1411 }
1412 EXPORT_SYMBOL_GPL(nf_ct_alloc_hashtable);
1413
1414 int nf_conntrack_set_hashsize(const char *val, struct kernel_param *kp)
1415 {
1416         int i, bucket, rc;
1417         unsigned int hashsize, old_size;
1418         struct hlist_nulls_head *hash, *old_hash;
1419         struct nf_conntrack_tuple_hash *h;
1420         struct nf_conn *ct;
1421
1422         if (current->nsproxy->net_ns != &init_net)
1423                 return -EOPNOTSUPP;
1424
1425         /* On boot, we can set this without any fancy locking. */
1426         if (!nf_conntrack_htable_size)
1427                 return param_set_uint(val, kp);
1428
1429         rc = kstrtouint(val, 0, &hashsize);
1430         if (rc)
1431                 return rc;
1432         if (!hashsize)
1433                 return -EINVAL;
1434
1435         hash = nf_ct_alloc_hashtable(&hashsize, 1);
1436         if (!hash)
1437                 return -ENOMEM;
1438
1439         /* Lookups in the old hash might happen in parallel, which means we
1440          * might get false negatives during connection lookup. New connections
1441          * created because of a false negative won't make it into the hash
1442          * though since that required taking the lock.
1443          */
1444         spin_lock_bh(&nf_conntrack_lock);
1445         for (i = 0; i < init_net.ct.htable_size; i++) {
1446                 while (!hlist_nulls_empty(&init_net.ct.hash[i])) {
1447                         h = hlist_nulls_entry(init_net.ct.hash[i].first,
1448                                         struct nf_conntrack_tuple_hash, hnnode);
1449                         ct = nf_ct_tuplehash_to_ctrack(h);
1450                         hlist_nulls_del_rcu(&h->hnnode);
1451                         bucket = __hash_conntrack(&h->tuple, nf_ct_zone(ct),
1452                                                   hashsize);
1453                         hlist_nulls_add_head_rcu(&h->hnnode, &hash[bucket]);
1454                 }
1455         }
1456         old_size = init_net.ct.htable_size;
1457         old_hash = init_net.ct.hash;
1458
1459         init_net.ct.htable_size = nf_conntrack_htable_size = hashsize;
1460         init_net.ct.hash = hash;
1461         spin_unlock_bh(&nf_conntrack_lock);
1462
1463         nf_ct_free_hashtable(old_hash, old_size);
1464         return 0;
1465 }
1466 EXPORT_SYMBOL_GPL(nf_conntrack_set_hashsize);
1467
1468 module_param_call(hashsize, nf_conntrack_set_hashsize, param_get_uint,
1469                   &nf_conntrack_htable_size, 0600);
1470
1471 void nf_ct_untracked_status_or(unsigned long bits)
1472 {
1473         int cpu;
1474
1475         for_each_possible_cpu(cpu)
1476                 per_cpu(nf_conntrack_untracked, cpu).status |= bits;
1477 }
1478 EXPORT_SYMBOL_GPL(nf_ct_untracked_status_or);
1479
1480 int nf_conntrack_init_start(void)
1481 {
1482         int max_factor = 8;
1483         int ret, cpu;
1484
1485         /* Idea from tcp.c: use 1/16384 of memory.  On i386: 32MB
1486          * machine has 512 buckets. >= 1GB machines have 16384 buckets. */
1487         if (!nf_conntrack_htable_size) {
1488                 nf_conntrack_htable_size
1489                         = (((totalram_pages << PAGE_SHIFT) / 16384)
1490                            / sizeof(struct hlist_head));
1491                 if (totalram_pages > (1024 * 1024 * 1024 / PAGE_SIZE))
1492                         nf_conntrack_htable_size = 16384;
1493                 if (nf_conntrack_htable_size < 32)
1494                         nf_conntrack_htable_size = 32;
1495
1496                 /* Use a max. factor of four by default to get the same max as
1497                  * with the old struct list_heads. When a table size is given
1498                  * we use the old value of 8 to avoid reducing the max.
1499                  * entries. */
1500                 max_factor = 4;
1501         }
1502         nf_conntrack_max = max_factor * nf_conntrack_htable_size;
1503
1504         printk(KERN_INFO "nf_conntrack version %s (%u buckets, %d max)\n",
1505                NF_CONNTRACK_VERSION, nf_conntrack_htable_size,
1506                nf_conntrack_max);
1507
1508         ret = nf_conntrack_expect_init();
1509         if (ret < 0)
1510                 goto err_expect;
1511
1512         ret = nf_conntrack_acct_init();
1513         if (ret < 0)
1514                 goto err_acct;
1515
1516         ret = nf_conntrack_tstamp_init();
1517         if (ret < 0)
1518                 goto err_tstamp;
1519
1520         ret = nf_conntrack_ecache_init();
1521         if (ret < 0)
1522                 goto err_ecache;
1523
1524         ret = nf_conntrack_timeout_init();
1525         if (ret < 0)
1526                 goto err_timeout;
1527
1528         ret = nf_conntrack_helper_init();
1529         if (ret < 0)
1530                 goto err_helper;
1531
1532         ret = nf_conntrack_labels_init();
1533         if (ret < 0)
1534                 goto err_labels;
1535
1536         ret = nf_conntrack_seqadj_init();
1537         if (ret < 0)
1538                 goto err_seqadj;
1539
1540 #ifdef CONFIG_NF_CONNTRACK_ZONES
1541         ret = nf_ct_extend_register(&nf_ct_zone_extend);
1542         if (ret < 0)
1543                 goto err_extend;
1544 #endif
1545         ret = nf_conntrack_proto_init();
1546         if (ret < 0)
1547                 goto err_proto;
1548
1549         /* Set up fake conntrack: to never be deleted, not in any hashes */
1550         for_each_possible_cpu(cpu) {
1551                 struct nf_conn *ct = &per_cpu(nf_conntrack_untracked, cpu);
1552                 write_pnet(&ct->ct_net, &init_net);
1553                 atomic_set(&ct->ct_general.use, 1);
1554         }
1555         /*  - and look it like as a confirmed connection */
1556         nf_ct_untracked_status_or(IPS_CONFIRMED | IPS_UNTRACKED);
1557         return 0;
1558
1559 err_proto:
1560 #ifdef CONFIG_NF_CONNTRACK_ZONES
1561         nf_ct_extend_unregister(&nf_ct_zone_extend);
1562 err_extend:
1563 #endif
1564         nf_conntrack_seqadj_fini();
1565 err_seqadj:
1566         nf_conntrack_labels_fini();
1567 err_labels:
1568         nf_conntrack_helper_fini();
1569 err_helper:
1570         nf_conntrack_timeout_fini();
1571 err_timeout:
1572         nf_conntrack_ecache_fini();
1573 err_ecache:
1574         nf_conntrack_tstamp_fini();
1575 err_tstamp:
1576         nf_conntrack_acct_fini();
1577 err_acct:
1578         nf_conntrack_expect_fini();
1579 err_expect:
1580         return ret;
1581 }
1582
1583 void nf_conntrack_init_end(void)
1584 {
1585         /* For use by REJECT target */
1586         RCU_INIT_POINTER(ip_ct_attach, nf_conntrack_attach);
1587         RCU_INIT_POINTER(nf_ct_destroy, destroy_conntrack);
1588 }
1589
1590 /*
1591  * We need to use special "null" values, not used in hash table
1592  */
1593 #define UNCONFIRMED_NULLS_VAL   ((1<<30)+0)
1594 #define DYING_NULLS_VAL         ((1<<30)+1)
1595 #define TEMPLATE_NULLS_VAL      ((1<<30)+2)
1596
1597 int nf_conntrack_init_net(struct net *net)
1598 {
1599         int ret;
1600
1601         atomic_set(&net->ct.count, 0);
1602         INIT_HLIST_NULLS_HEAD(&net->ct.unconfirmed, UNCONFIRMED_NULLS_VAL);
1603         INIT_HLIST_NULLS_HEAD(&net->ct.dying, DYING_NULLS_VAL);
1604         INIT_HLIST_NULLS_HEAD(&net->ct.tmpl, TEMPLATE_NULLS_VAL);
1605         net->ct.stat = alloc_percpu(struct ip_conntrack_stat);
1606         if (!net->ct.stat) {
1607                 ret = -ENOMEM;
1608                 goto err_stat;
1609         }
1610
1611         net->ct.slabname = kasprintf(GFP_KERNEL, "nf_conntrack_%p", net);
1612         if (!net->ct.slabname) {
1613                 ret = -ENOMEM;
1614                 goto err_slabname;
1615         }
1616
1617         net->ct.nf_conntrack_cachep = kmem_cache_create(net->ct.slabname,
1618                                                         sizeof(struct nf_conn), 0,
1619                                                         SLAB_DESTROY_BY_RCU, NULL);
1620         if (!net->ct.nf_conntrack_cachep) {
1621                 printk(KERN_ERR "Unable to create nf_conn slab cache\n");
1622                 ret = -ENOMEM;
1623                 goto err_cache;
1624         }
1625
1626         net->ct.htable_size = nf_conntrack_htable_size;
1627         net->ct.hash = nf_ct_alloc_hashtable(&net->ct.htable_size, 1);
1628         if (!net->ct.hash) {
1629                 ret = -ENOMEM;
1630                 printk(KERN_ERR "Unable to create nf_conntrack_hash\n");
1631                 goto err_hash;
1632         }
1633         ret = nf_conntrack_expect_pernet_init(net);
1634         if (ret < 0)
1635                 goto err_expect;
1636         ret = nf_conntrack_acct_pernet_init(net);
1637         if (ret < 0)
1638                 goto err_acct;
1639         ret = nf_conntrack_tstamp_pernet_init(net);
1640         if (ret < 0)
1641                 goto err_tstamp;
1642         ret = nf_conntrack_ecache_pernet_init(net);
1643         if (ret < 0)
1644                 goto err_ecache;
1645         ret = nf_conntrack_helper_pernet_init(net);
1646         if (ret < 0)
1647                 goto err_helper;
1648         ret = nf_conntrack_proto_pernet_init(net);
1649         if (ret < 0)
1650                 goto err_proto;
1651         return 0;
1652
1653 err_proto:
1654         nf_conntrack_helper_pernet_fini(net);
1655 err_helper:
1656         nf_conntrack_ecache_pernet_fini(net);
1657 err_ecache:
1658         nf_conntrack_tstamp_pernet_fini(net);
1659 err_tstamp:
1660         nf_conntrack_acct_pernet_fini(net);
1661 err_acct:
1662         nf_conntrack_expect_pernet_fini(net);
1663 err_expect:
1664         nf_ct_free_hashtable(net->ct.hash, net->ct.htable_size);
1665 err_hash:
1666         kmem_cache_destroy(net->ct.nf_conntrack_cachep);
1667 err_cache:
1668         kfree(net->ct.slabname);
1669 err_slabname:
1670         free_percpu(net->ct.stat);
1671 err_stat:
1672         return ret;
1673 }