netfilter: Use unsigned types for hooknum and pf vars
[pandora-kernel.git] / net / netfilter / xt_hashlimit.c
1 /*
2  *      xt_hashlimit - Netfilter module to limit the number of packets per time
3  *      seperately for each hashbucket (sourceip/sourceport/dstip/dstport)
4  *
5  *      (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
6  *      Copyright © CC Computer Consultants GmbH, 2007 - 2008
7  *
8  * Development of this code was funded by Astaro AG, http://www.astaro.com/
9  */
10 #include <linux/module.h>
11 #include <linux/spinlock.h>
12 #include <linux/random.h>
13 #include <linux/jhash.h>
14 #include <linux/slab.h>
15 #include <linux/vmalloc.h>
16 #include <linux/proc_fs.h>
17 #include <linux/seq_file.h>
18 #include <linux/list.h>
19 #include <linux/skbuff.h>
20 #include <linux/mm.h>
21 #include <linux/in.h>
22 #include <linux/ip.h>
23 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
24 #include <linux/ipv6.h>
25 #include <net/ipv6.h>
26 #endif
27
28 #include <net/net_namespace.h>
29
30 #include <linux/netfilter/x_tables.h>
31 #include <linux/netfilter_ipv4/ip_tables.h>
32 #include <linux/netfilter_ipv6/ip6_tables.h>
33 #include <linux/netfilter/xt_hashlimit.h>
34 #include <linux/mutex.h>
35
36 MODULE_LICENSE("GPL");
37 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
38 MODULE_AUTHOR("Jan Engelhardt <jengelh@computergmbh.de>");
39 MODULE_DESCRIPTION("Xtables: per hash-bucket rate-limit match");
40 MODULE_ALIAS("ipt_hashlimit");
41 MODULE_ALIAS("ip6t_hashlimit");
42
43 /* need to declare this at the top */
44 static struct proc_dir_entry *hashlimit_procdir4;
45 static struct proc_dir_entry *hashlimit_procdir6;
46 static const struct file_operations dl_file_ops;
47
48 /* hash table crap */
49 struct dsthash_dst {
50         union {
51                 struct {
52                         __be32 src;
53                         __be32 dst;
54                 } ip;
55 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
56                 struct {
57                         __be32 src[4];
58                         __be32 dst[4];
59                 } ip6;
60 #endif
61         };
62         __be16 src_port;
63         __be16 dst_port;
64 };
65
66 struct dsthash_ent {
67         /* static / read-only parts in the beginning */
68         struct hlist_node node;
69         struct dsthash_dst dst;
70
71         /* modified structure members in the end */
72         unsigned long expires;          /* precalculated expiry time */
73         struct {
74                 unsigned long prev;     /* last modification */
75                 u_int32_t credit;
76                 u_int32_t credit_cap, cost;
77         } rateinfo;
78 };
79
80 struct xt_hashlimit_htable {
81         struct hlist_node node;         /* global list of all htables */
82         atomic_t use;
83         u_int8_t family;
84
85         struct hashlimit_cfg1 cfg;      /* config */
86
87         /* used internally */
88         spinlock_t lock;                /* lock for list_head */
89         u_int32_t rnd;                  /* random seed for hash */
90         int rnd_initialized;
91         unsigned int count;             /* number entries in table */
92         struct timer_list timer;        /* timer for gc */
93
94         /* seq_file stuff */
95         struct proc_dir_entry *pde;
96
97         struct hlist_head hash[0];      /* hashtable itself */
98 };
99
100 static DEFINE_SPINLOCK(hashlimit_lock); /* protects htables list */
101 static DEFINE_MUTEX(hlimit_mutex);      /* additional checkentry protection */
102 static HLIST_HEAD(hashlimit_htables);
103 static struct kmem_cache *hashlimit_cachep __read_mostly;
104
105 static inline bool dst_cmp(const struct dsthash_ent *ent,
106                            const struct dsthash_dst *b)
107 {
108         return !memcmp(&ent->dst, b, sizeof(ent->dst));
109 }
110
111 static u_int32_t
112 hash_dst(const struct xt_hashlimit_htable *ht, const struct dsthash_dst *dst)
113 {
114         u_int32_t hash = jhash2((const u32 *)dst,
115                                 sizeof(*dst)/sizeof(u32),
116                                 ht->rnd);
117         /*
118          * Instead of returning hash % ht->cfg.size (implying a divide)
119          * we return the high 32 bits of the (hash * ht->cfg.size) that will
120          * give results between [0 and cfg.size-1] and same hash distribution,
121          * but using a multiply, less expensive than a divide
122          */
123         return ((u64)hash * ht->cfg.size) >> 32;
124 }
125
126 static struct dsthash_ent *
127 dsthash_find(const struct xt_hashlimit_htable *ht,
128              const struct dsthash_dst *dst)
129 {
130         struct dsthash_ent *ent;
131         struct hlist_node *pos;
132         u_int32_t hash = hash_dst(ht, dst);
133
134         if (!hlist_empty(&ht->hash[hash])) {
135                 hlist_for_each_entry(ent, pos, &ht->hash[hash], node)
136                         if (dst_cmp(ent, dst))
137                                 return ent;
138         }
139         return NULL;
140 }
141
142 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
143 static struct dsthash_ent *
144 dsthash_alloc_init(struct xt_hashlimit_htable *ht,
145                    const struct dsthash_dst *dst)
146 {
147         struct dsthash_ent *ent;
148
149         /* initialize hash with random val at the time we allocate
150          * the first hashtable entry */
151         if (!ht->rnd_initialized) {
152                 get_random_bytes(&ht->rnd, 4);
153                 ht->rnd_initialized = 1;
154         }
155
156         if (ht->cfg.max && ht->count >= ht->cfg.max) {
157                 /* FIXME: do something. question is what.. */
158                 if (net_ratelimit())
159                         printk(KERN_WARNING
160                                 "xt_hashlimit: max count of %u reached\n",
161                                 ht->cfg.max);
162                 return NULL;
163         }
164
165         ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
166         if (!ent) {
167                 if (net_ratelimit())
168                         printk(KERN_ERR
169                                 "xt_hashlimit: can't allocate dsthash_ent\n");
170                 return NULL;
171         }
172         memcpy(&ent->dst, dst, sizeof(ent->dst));
173
174         hlist_add_head(&ent->node, &ht->hash[hash_dst(ht, dst)]);
175         ht->count++;
176         return ent;
177 }
178
179 static inline void
180 dsthash_free(struct xt_hashlimit_htable *ht, struct dsthash_ent *ent)
181 {
182         hlist_del(&ent->node);
183         kmem_cache_free(hashlimit_cachep, ent);
184         ht->count--;
185 }
186 static void htable_gc(unsigned long htlong);
187
188 static int htable_create_v0(struct xt_hashlimit_info *minfo, u_int8_t family)
189 {
190         struct xt_hashlimit_htable *hinfo;
191         unsigned int size;
192         unsigned int i;
193
194         if (minfo->cfg.size)
195                 size = minfo->cfg.size;
196         else {
197                 size = ((num_physpages << PAGE_SHIFT) / 16384) /
198                        sizeof(struct list_head);
199                 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
200                         size = 8192;
201                 if (size < 16)
202                         size = 16;
203         }
204         /* FIXME: don't use vmalloc() here or anywhere else -HW */
205         hinfo = vmalloc(sizeof(struct xt_hashlimit_htable) +
206                         sizeof(struct list_head) * size);
207         if (!hinfo) {
208                 printk(KERN_ERR "xt_hashlimit: unable to create hashtable\n");
209                 return -1;
210         }
211         minfo->hinfo = hinfo;
212
213         /* copy match config into hashtable config */
214         hinfo->cfg.mode        = minfo->cfg.mode;
215         hinfo->cfg.avg         = minfo->cfg.avg;
216         hinfo->cfg.burst       = minfo->cfg.burst;
217         hinfo->cfg.max         = minfo->cfg.max;
218         hinfo->cfg.gc_interval = minfo->cfg.gc_interval;
219         hinfo->cfg.expire      = minfo->cfg.expire;
220
221         if (family == AF_INET)
222                 hinfo->cfg.srcmask = hinfo->cfg.dstmask = 32;
223         else
224                 hinfo->cfg.srcmask = hinfo->cfg.dstmask = 128;
225
226         hinfo->cfg.size = size;
227         if (!hinfo->cfg.max)
228                 hinfo->cfg.max = 8 * hinfo->cfg.size;
229         else if (hinfo->cfg.max < hinfo->cfg.size)
230                 hinfo->cfg.max = hinfo->cfg.size;
231
232         for (i = 0; i < hinfo->cfg.size; i++)
233                 INIT_HLIST_HEAD(&hinfo->hash[i]);
234
235         atomic_set(&hinfo->use, 1);
236         hinfo->count = 0;
237         hinfo->family = family;
238         hinfo->rnd_initialized = 0;
239         spin_lock_init(&hinfo->lock);
240         hinfo->pde =
241                 proc_create_data(minfo->name, 0,
242                                  family == AF_INET ? hashlimit_procdir4 :
243                                                      hashlimit_procdir6,
244                                  &dl_file_ops, hinfo);
245         if (!hinfo->pde) {
246                 vfree(hinfo);
247                 return -1;
248         }
249
250         setup_timer(&hinfo->timer, htable_gc, (unsigned long )hinfo);
251         hinfo->timer.expires = jiffies + msecs_to_jiffies(hinfo->cfg.gc_interval);
252         add_timer(&hinfo->timer);
253
254         spin_lock_bh(&hashlimit_lock);
255         hlist_add_head(&hinfo->node, &hashlimit_htables);
256         spin_unlock_bh(&hashlimit_lock);
257
258         return 0;
259 }
260
261 static int htable_create(struct xt_hashlimit_mtinfo1 *minfo, u_int8_t family)
262 {
263         struct xt_hashlimit_htable *hinfo;
264         unsigned int size;
265         unsigned int i;
266
267         if (minfo->cfg.size) {
268                 size = minfo->cfg.size;
269         } else {
270                 size = (num_physpages << PAGE_SHIFT) / 16384 /
271                        sizeof(struct list_head);
272                 if (num_physpages > 1024 * 1024 * 1024 / PAGE_SIZE)
273                         size = 8192;
274                 if (size < 16)
275                         size = 16;
276         }
277         /* FIXME: don't use vmalloc() here or anywhere else -HW */
278         hinfo = vmalloc(sizeof(struct xt_hashlimit_htable) +
279                         sizeof(struct list_head) * size);
280         if (hinfo == NULL) {
281                 printk(KERN_ERR "xt_hashlimit: unable to create hashtable\n");
282                 return -1;
283         }
284         minfo->hinfo = hinfo;
285
286         /* copy match config into hashtable config */
287         memcpy(&hinfo->cfg, &minfo->cfg, sizeof(hinfo->cfg));
288         hinfo->cfg.size = size;
289         if (hinfo->cfg.max == 0)
290                 hinfo->cfg.max = 8 * hinfo->cfg.size;
291         else if (hinfo->cfg.max < hinfo->cfg.size)
292                 hinfo->cfg.max = hinfo->cfg.size;
293
294         for (i = 0; i < hinfo->cfg.size; i++)
295                 INIT_HLIST_HEAD(&hinfo->hash[i]);
296
297         atomic_set(&hinfo->use, 1);
298         hinfo->count = 0;
299         hinfo->family = family;
300         hinfo->rnd_initialized = 0;
301         spin_lock_init(&hinfo->lock);
302
303         hinfo->pde =
304                 proc_create_data(minfo->name, 0,
305                                  family == AF_INET ? hashlimit_procdir4 :
306                                                      hashlimit_procdir6,
307                                  &dl_file_ops, hinfo);
308         if (hinfo->pde == NULL) {
309                 vfree(hinfo);
310                 return -1;
311         }
312
313         setup_timer(&hinfo->timer, htable_gc, (unsigned long)hinfo);
314         hinfo->timer.expires = jiffies + msecs_to_jiffies(hinfo->cfg.gc_interval);
315         add_timer(&hinfo->timer);
316
317         spin_lock_bh(&hashlimit_lock);
318         hlist_add_head(&hinfo->node, &hashlimit_htables);
319         spin_unlock_bh(&hashlimit_lock);
320
321         return 0;
322 }
323
324 static bool select_all(const struct xt_hashlimit_htable *ht,
325                        const struct dsthash_ent *he)
326 {
327         return 1;
328 }
329
330 static bool select_gc(const struct xt_hashlimit_htable *ht,
331                       const struct dsthash_ent *he)
332 {
333         return time_after_eq(jiffies, he->expires);
334 }
335
336 static void htable_selective_cleanup(struct xt_hashlimit_htable *ht,
337                         bool (*select)(const struct xt_hashlimit_htable *ht,
338                                       const struct dsthash_ent *he))
339 {
340         unsigned int i;
341
342         /* lock hash table and iterate over it */
343         spin_lock_bh(&ht->lock);
344         for (i = 0; i < ht->cfg.size; i++) {
345                 struct dsthash_ent *dh;
346                 struct hlist_node *pos, *n;
347                 hlist_for_each_entry_safe(dh, pos, n, &ht->hash[i], node) {
348                         if ((*select)(ht, dh))
349                                 dsthash_free(ht, dh);
350                 }
351         }
352         spin_unlock_bh(&ht->lock);
353 }
354
355 /* hash table garbage collector, run by timer */
356 static void htable_gc(unsigned long htlong)
357 {
358         struct xt_hashlimit_htable *ht = (struct xt_hashlimit_htable *)htlong;
359
360         htable_selective_cleanup(ht, select_gc);
361
362         /* re-add the timer accordingly */
363         ht->timer.expires = jiffies + msecs_to_jiffies(ht->cfg.gc_interval);
364         add_timer(&ht->timer);
365 }
366
367 static void htable_destroy(struct xt_hashlimit_htable *hinfo)
368 {
369         del_timer_sync(&hinfo->timer);
370
371         /* remove proc entry */
372         remove_proc_entry(hinfo->pde->name,
373                           hinfo->family == AF_INET ? hashlimit_procdir4 :
374                                                      hashlimit_procdir6);
375         htable_selective_cleanup(hinfo, select_all);
376         vfree(hinfo);
377 }
378
379 static struct xt_hashlimit_htable *htable_find_get(const char *name,
380                                                    u_int8_t family)
381 {
382         struct xt_hashlimit_htable *hinfo;
383         struct hlist_node *pos;
384
385         spin_lock_bh(&hashlimit_lock);
386         hlist_for_each_entry(hinfo, pos, &hashlimit_htables, node) {
387                 if (!strcmp(name, hinfo->pde->name) &&
388                     hinfo->family == family) {
389                         atomic_inc(&hinfo->use);
390                         spin_unlock_bh(&hashlimit_lock);
391                         return hinfo;
392                 }
393         }
394         spin_unlock_bh(&hashlimit_lock);
395         return NULL;
396 }
397
398 static void htable_put(struct xt_hashlimit_htable *hinfo)
399 {
400         if (atomic_dec_and_test(&hinfo->use)) {
401                 spin_lock_bh(&hashlimit_lock);
402                 hlist_del(&hinfo->node);
403                 spin_unlock_bh(&hashlimit_lock);
404                 htable_destroy(hinfo);
405         }
406 }
407
408 /* The algorithm used is the Simple Token Bucket Filter (TBF)
409  * see net/sched/sch_tbf.c in the linux source tree
410  */
411
412 /* Rusty: This is my (non-mathematically-inclined) understanding of
413    this algorithm.  The `average rate' in jiffies becomes your initial
414    amount of credit `credit' and the most credit you can ever have
415    `credit_cap'.  The `peak rate' becomes the cost of passing the
416    test, `cost'.
417
418    `prev' tracks the last packet hit: you gain one credit per jiffy.
419    If you get credit balance more than this, the extra credit is
420    discarded.  Every time the match passes, you lose `cost' credits;
421    if you don't have that many, the test fails.
422
423    See Alexey's formal explanation in net/sched/sch_tbf.c.
424
425    To get the maximum range, we multiply by this factor (ie. you get N
426    credits per jiffy).  We want to allow a rate as low as 1 per day
427    (slowest userspace tool allows), which means
428    CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
429 */
430 #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
431
432 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
433  * us the power of 2 below the theoretical max, so GCC simply does a
434  * shift. */
435 #define _POW2_BELOW2(x) ((x)|((x)>>1))
436 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
437 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
438 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
439 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
440 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
441
442 #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
443
444 /* Precision saver. */
445 static inline u_int32_t
446 user2credits(u_int32_t user)
447 {
448         /* If multiplying would overflow... */
449         if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY))
450                 /* Divide first. */
451                 return (user / XT_HASHLIMIT_SCALE) * HZ * CREDITS_PER_JIFFY;
452
453         return (user * HZ * CREDITS_PER_JIFFY) / XT_HASHLIMIT_SCALE;
454 }
455
456 static inline void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now)
457 {
458         dh->rateinfo.credit += (now - dh->rateinfo.prev) * CREDITS_PER_JIFFY;
459         if (dh->rateinfo.credit > dh->rateinfo.credit_cap)
460                 dh->rateinfo.credit = dh->rateinfo.credit_cap;
461         dh->rateinfo.prev = now;
462 }
463
464 static inline __be32 maskl(__be32 a, unsigned int l)
465 {
466         return l ? htonl(ntohl(a) & ~0 << (32 - l)) : 0;
467 }
468
469 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
470 static void hashlimit_ipv6_mask(__be32 *i, unsigned int p)
471 {
472         switch (p) {
473         case 0 ... 31:
474                 i[0] = maskl(i[0], p);
475                 i[1] = i[2] = i[3] = 0;
476                 break;
477         case 32 ... 63:
478                 i[1] = maskl(i[1], p - 32);
479                 i[2] = i[3] = 0;
480                 break;
481         case 64 ... 95:
482                 i[2] = maskl(i[2], p - 64);
483                 i[3] = 0;
484         case 96 ... 127:
485                 i[3] = maskl(i[3], p - 96);
486                 break;
487         case 128:
488                 break;
489         }
490 }
491 #endif
492
493 static int
494 hashlimit_init_dst(const struct xt_hashlimit_htable *hinfo,
495                    struct dsthash_dst *dst,
496                    const struct sk_buff *skb, unsigned int protoff)
497 {
498         __be16 _ports[2], *ports;
499         u8 nexthdr;
500
501         memset(dst, 0, sizeof(*dst));
502
503         switch (hinfo->family) {
504         case AF_INET:
505                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
506                         dst->ip.dst = maskl(ip_hdr(skb)->daddr,
507                                       hinfo->cfg.dstmask);
508                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
509                         dst->ip.src = maskl(ip_hdr(skb)->saddr,
510                                       hinfo->cfg.srcmask);
511
512                 if (!(hinfo->cfg.mode &
513                       (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
514                         return 0;
515                 nexthdr = ip_hdr(skb)->protocol;
516                 break;
517 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
518         case AF_INET6:
519                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP) {
520                         memcpy(&dst->ip6.dst, &ipv6_hdr(skb)->daddr,
521                                sizeof(dst->ip6.dst));
522                         hashlimit_ipv6_mask(dst->ip6.dst, hinfo->cfg.dstmask);
523                 }
524                 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP) {
525                         memcpy(&dst->ip6.src, &ipv6_hdr(skb)->saddr,
526                                sizeof(dst->ip6.src));
527                         hashlimit_ipv6_mask(dst->ip6.src, hinfo->cfg.srcmask);
528                 }
529
530                 if (!(hinfo->cfg.mode &
531                       (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
532                         return 0;
533                 nexthdr = ipv6_hdr(skb)->nexthdr;
534                 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr);
535                 if ((int)protoff < 0)
536                         return -1;
537                 break;
538 #endif
539         default:
540                 BUG();
541                 return 0;
542         }
543
544         switch (nexthdr) {
545         case IPPROTO_TCP:
546         case IPPROTO_UDP:
547         case IPPROTO_UDPLITE:
548         case IPPROTO_SCTP:
549         case IPPROTO_DCCP:
550                 ports = skb_header_pointer(skb, protoff, sizeof(_ports),
551                                            &_ports);
552                 break;
553         default:
554                 _ports[0] = _ports[1] = 0;
555                 ports = _ports;
556                 break;
557         }
558         if (!ports)
559                 return -1;
560         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SPT)
561                 dst->src_port = ports[0];
562         if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DPT)
563                 dst->dst_port = ports[1];
564         return 0;
565 }
566
567 static bool
568 hashlimit_mt_v0(const struct sk_buff *skb, const struct net_device *in,
569                 const struct net_device *out, const struct xt_match *match,
570                 const void *matchinfo, int offset, unsigned int protoff,
571                 bool *hotdrop)
572 {
573         const struct xt_hashlimit_info *r =
574                 ((const struct xt_hashlimit_info *)matchinfo)->u.master;
575         struct xt_hashlimit_htable *hinfo = r->hinfo;
576         unsigned long now = jiffies;
577         struct dsthash_ent *dh;
578         struct dsthash_dst dst;
579
580         if (hashlimit_init_dst(hinfo, &dst, skb, protoff) < 0)
581                 goto hotdrop;
582
583         spin_lock_bh(&hinfo->lock);
584         dh = dsthash_find(hinfo, &dst);
585         if (!dh) {
586                 dh = dsthash_alloc_init(hinfo, &dst);
587                 if (!dh) {
588                         spin_unlock_bh(&hinfo->lock);
589                         goto hotdrop;
590                 }
591
592                 dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
593                 dh->rateinfo.prev = jiffies;
594                 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
595                                                    hinfo->cfg.burst);
596                 dh->rateinfo.credit_cap = user2credits(hinfo->cfg.avg *
597                                                        hinfo->cfg.burst);
598                 dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
599         } else {
600                 /* update expiration timeout */
601                 dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
602                 rateinfo_recalc(dh, now);
603         }
604
605         if (dh->rateinfo.credit >= dh->rateinfo.cost) {
606                 /* We're underlimit. */
607                 dh->rateinfo.credit -= dh->rateinfo.cost;
608                 spin_unlock_bh(&hinfo->lock);
609                 return true;
610         }
611
612         spin_unlock_bh(&hinfo->lock);
613
614         /* default case: we're overlimit, thus don't match */
615         return false;
616
617 hotdrop:
618         *hotdrop = true;
619         return false;
620 }
621
622 static bool
623 hashlimit_mt(const struct sk_buff *skb, const struct net_device *in,
624              const struct net_device *out, const struct xt_match *match,
625              const void *matchinfo, int offset, unsigned int protoff,
626              bool *hotdrop)
627 {
628         const struct xt_hashlimit_mtinfo1 *info = matchinfo;
629         struct xt_hashlimit_htable *hinfo = info->hinfo;
630         unsigned long now = jiffies;
631         struct dsthash_ent *dh;
632         struct dsthash_dst dst;
633
634         if (hashlimit_init_dst(hinfo, &dst, skb, protoff) < 0)
635                 goto hotdrop;
636
637         spin_lock_bh(&hinfo->lock);
638         dh = dsthash_find(hinfo, &dst);
639         if (dh == NULL) {
640                 dh = dsthash_alloc_init(hinfo, &dst);
641                 if (dh == NULL) {
642                         spin_unlock_bh(&hinfo->lock);
643                         goto hotdrop;
644                 }
645
646                 dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
647                 dh->rateinfo.prev = jiffies;
648                 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
649                                       hinfo->cfg.burst);
650                 dh->rateinfo.credit_cap = user2credits(hinfo->cfg.avg *
651                                           hinfo->cfg.burst);
652                 dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
653         } else {
654                 /* update expiration timeout */
655                 dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
656                 rateinfo_recalc(dh, now);
657         }
658
659         if (dh->rateinfo.credit >= dh->rateinfo.cost) {
660                 /* below the limit */
661                 dh->rateinfo.credit -= dh->rateinfo.cost;
662                 spin_unlock_bh(&hinfo->lock);
663                 return !(info->cfg.mode & XT_HASHLIMIT_INVERT);
664         }
665
666         spin_unlock_bh(&hinfo->lock);
667         /* default match is underlimit - so over the limit, we need to invert */
668         return info->cfg.mode & XT_HASHLIMIT_INVERT;
669
670  hotdrop:
671         *hotdrop = true;
672         return false;
673 }
674
675 static bool
676 hashlimit_mt_check_v0(const char *tablename, const void *inf,
677                       const struct xt_match *match, void *matchinfo,
678                       unsigned int hook_mask)
679 {
680         struct xt_hashlimit_info *r = matchinfo;
681
682         /* Check for overflow. */
683         if (r->cfg.burst == 0 ||
684             user2credits(r->cfg.avg * r->cfg.burst) < user2credits(r->cfg.avg)) {
685                 printk(KERN_ERR "xt_hashlimit: overflow, try lower: %u/%u\n",
686                        r->cfg.avg, r->cfg.burst);
687                 return false;
688         }
689         if (r->cfg.mode == 0 ||
690             r->cfg.mode > (XT_HASHLIMIT_HASH_DPT |
691                            XT_HASHLIMIT_HASH_DIP |
692                            XT_HASHLIMIT_HASH_SIP |
693                            XT_HASHLIMIT_HASH_SPT))
694                 return false;
695         if (!r->cfg.gc_interval)
696                 return false;
697         if (!r->cfg.expire)
698                 return false;
699         if (r->name[sizeof(r->name) - 1] != '\0')
700                 return false;
701
702         /* This is the best we've got: We cannot release and re-grab lock,
703          * since checkentry() is called before x_tables.c grabs xt_mutex.
704          * We also cannot grab the hashtable spinlock, since htable_create will
705          * call vmalloc, and that can sleep.  And we cannot just re-search
706          * the list of htable's in htable_create(), since then we would
707          * create duplicate proc files. -HW */
708         mutex_lock(&hlimit_mutex);
709         r->hinfo = htable_find_get(r->name, match->family);
710         if (!r->hinfo && htable_create_v0(r, match->family) != 0) {
711                 mutex_unlock(&hlimit_mutex);
712                 return false;
713         }
714         mutex_unlock(&hlimit_mutex);
715
716         /* Ugly hack: For SMP, we only want to use one set */
717         r->u.master = r;
718         return true;
719 }
720
721 static bool
722 hashlimit_mt_check(const char *tablename, const void *inf,
723                    const struct xt_match *match, void *matchinfo,
724                    unsigned int hook_mask)
725 {
726         struct xt_hashlimit_mtinfo1 *info = matchinfo;
727
728         /* Check for overflow. */
729         if (info->cfg.burst == 0 ||
730             user2credits(info->cfg.avg * info->cfg.burst) <
731             user2credits(info->cfg.avg)) {
732                 printk(KERN_ERR "xt_hashlimit: overflow, try lower: %u/%u\n",
733                        info->cfg.avg, info->cfg.burst);
734                 return false;
735         }
736         if (info->cfg.gc_interval == 0 || info->cfg.expire == 0)
737                 return false;
738         if (info->name[sizeof(info->name)-1] != '\0')
739                 return false;
740         if (match->family == AF_INET) {
741                 if (info->cfg.srcmask > 32 || info->cfg.dstmask > 32)
742                         return false;
743         } else {
744                 if (info->cfg.srcmask > 128 || info->cfg.dstmask > 128)
745                         return false;
746         }
747
748         /* This is the best we've got: We cannot release and re-grab lock,
749          * since checkentry() is called before x_tables.c grabs xt_mutex.
750          * We also cannot grab the hashtable spinlock, since htable_create will
751          * call vmalloc, and that can sleep.  And we cannot just re-search
752          * the list of htable's in htable_create(), since then we would
753          * create duplicate proc files. -HW */
754         mutex_lock(&hlimit_mutex);
755         info->hinfo = htable_find_get(info->name, match->family);
756         if (!info->hinfo && htable_create(info, match->family) != 0) {
757                 mutex_unlock(&hlimit_mutex);
758                 return false;
759         }
760         mutex_unlock(&hlimit_mutex);
761         return true;
762 }
763
764 static void
765 hashlimit_mt_destroy_v0(const struct xt_match *match, void *matchinfo)
766 {
767         const struct xt_hashlimit_info *r = matchinfo;
768
769         htable_put(r->hinfo);
770 }
771
772 static void
773 hashlimit_mt_destroy(const struct xt_match *match, void *matchinfo)
774 {
775         const struct xt_hashlimit_mtinfo1 *info = matchinfo;
776
777         htable_put(info->hinfo);
778 }
779
780 #ifdef CONFIG_COMPAT
781 struct compat_xt_hashlimit_info {
782         char name[IFNAMSIZ];
783         struct hashlimit_cfg cfg;
784         compat_uptr_t hinfo;
785         compat_uptr_t master;
786 };
787
788 static void hashlimit_mt_compat_from_user(void *dst, void *src)
789 {
790         int off = offsetof(struct compat_xt_hashlimit_info, hinfo);
791
792         memcpy(dst, src, off);
793         memset(dst + off, 0, sizeof(struct compat_xt_hashlimit_info) - off);
794 }
795
796 static int hashlimit_mt_compat_to_user(void __user *dst, void *src)
797 {
798         int off = offsetof(struct compat_xt_hashlimit_info, hinfo);
799
800         return copy_to_user(dst, src, off) ? -EFAULT : 0;
801 }
802 #endif
803
804 static struct xt_match hashlimit_mt_reg[] __read_mostly = {
805         {
806                 .name           = "hashlimit",
807                 .revision       = 0,
808                 .family         = AF_INET,
809                 .match          = hashlimit_mt_v0,
810                 .matchsize      = sizeof(struct xt_hashlimit_info),
811 #ifdef CONFIG_COMPAT
812                 .compatsize     = sizeof(struct compat_xt_hashlimit_info),
813                 .compat_from_user = hashlimit_mt_compat_from_user,
814                 .compat_to_user = hashlimit_mt_compat_to_user,
815 #endif
816                 .checkentry     = hashlimit_mt_check_v0,
817                 .destroy        = hashlimit_mt_destroy_v0,
818                 .me             = THIS_MODULE
819         },
820         {
821                 .name           = "hashlimit",
822                 .revision       = 1,
823                 .family         = AF_INET,
824                 .match          = hashlimit_mt,
825                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
826                 .checkentry     = hashlimit_mt_check,
827                 .destroy        = hashlimit_mt_destroy,
828                 .me             = THIS_MODULE,
829         },
830 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
831         {
832                 .name           = "hashlimit",
833                 .family         = AF_INET6,
834                 .match          = hashlimit_mt_v0,
835                 .matchsize      = sizeof(struct xt_hashlimit_info),
836 #ifdef CONFIG_COMPAT
837                 .compatsize     = sizeof(struct compat_xt_hashlimit_info),
838                 .compat_from_user = hashlimit_mt_compat_from_user,
839                 .compat_to_user = hashlimit_mt_compat_to_user,
840 #endif
841                 .checkentry     = hashlimit_mt_check_v0,
842                 .destroy        = hashlimit_mt_destroy_v0,
843                 .me             = THIS_MODULE
844         },
845         {
846                 .name           = "hashlimit",
847                 .revision       = 1,
848                 .family         = AF_INET6,
849                 .match          = hashlimit_mt,
850                 .matchsize      = sizeof(struct xt_hashlimit_mtinfo1),
851                 .checkentry     = hashlimit_mt_check,
852                 .destroy        = hashlimit_mt_destroy,
853                 .me             = THIS_MODULE,
854         },
855 #endif
856 };
857
858 /* PROC stuff */
859 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
860         __acquires(htable->lock)
861 {
862         struct proc_dir_entry *pde = s->private;
863         struct xt_hashlimit_htable *htable = pde->data;
864         unsigned int *bucket;
865
866         spin_lock_bh(&htable->lock);
867         if (*pos >= htable->cfg.size)
868                 return NULL;
869
870         bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
871         if (!bucket)
872                 return ERR_PTR(-ENOMEM);
873
874         *bucket = *pos;
875         return bucket;
876 }
877
878 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
879 {
880         struct proc_dir_entry *pde = s->private;
881         struct xt_hashlimit_htable *htable = pde->data;
882         unsigned int *bucket = (unsigned int *)v;
883
884         *pos = ++(*bucket);
885         if (*pos >= htable->cfg.size) {
886                 kfree(v);
887                 return NULL;
888         }
889         return bucket;
890 }
891
892 static void dl_seq_stop(struct seq_file *s, void *v)
893         __releases(htable->lock)
894 {
895         struct proc_dir_entry *pde = s->private;
896         struct xt_hashlimit_htable *htable = pde->data;
897         unsigned int *bucket = (unsigned int *)v;
898
899         kfree(bucket);
900         spin_unlock_bh(&htable->lock);
901 }
902
903 static int dl_seq_real_show(struct dsthash_ent *ent, u_int8_t family,
904                                    struct seq_file *s)
905 {
906         /* recalculate to show accurate numbers */
907         rateinfo_recalc(ent, jiffies);
908
909         switch (family) {
910         case AF_INET:
911                 return seq_printf(s, "%ld %u.%u.%u.%u:%u->"
912                                      "%u.%u.%u.%u:%u %u %u %u\n",
913                                  (long)(ent->expires - jiffies)/HZ,
914                                  NIPQUAD(ent->dst.ip.src),
915                                  ntohs(ent->dst.src_port),
916                                  NIPQUAD(ent->dst.ip.dst),
917                                  ntohs(ent->dst.dst_port),
918                                  ent->rateinfo.credit, ent->rateinfo.credit_cap,
919                                  ent->rateinfo.cost);
920 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
921         case AF_INET6:
922                 return seq_printf(s, "%ld " NIP6_FMT ":%u->"
923                                      NIP6_FMT ":%u %u %u %u\n",
924                                  (long)(ent->expires - jiffies)/HZ,
925                                  NIP6(*(struct in6_addr *)&ent->dst.ip6.src),
926                                  ntohs(ent->dst.src_port),
927                                  NIP6(*(struct in6_addr *)&ent->dst.ip6.dst),
928                                  ntohs(ent->dst.dst_port),
929                                  ent->rateinfo.credit, ent->rateinfo.credit_cap,
930                                  ent->rateinfo.cost);
931 #endif
932         default:
933                 BUG();
934                 return 0;
935         }
936 }
937
938 static int dl_seq_show(struct seq_file *s, void *v)
939 {
940         struct proc_dir_entry *pde = s->private;
941         struct xt_hashlimit_htable *htable = pde->data;
942         unsigned int *bucket = (unsigned int *)v;
943         struct dsthash_ent *ent;
944         struct hlist_node *pos;
945
946         if (!hlist_empty(&htable->hash[*bucket])) {
947                 hlist_for_each_entry(ent, pos, &htable->hash[*bucket], node)
948                         if (dl_seq_real_show(ent, htable->family, s))
949                                 return 1;
950         }
951         return 0;
952 }
953
954 static const struct seq_operations dl_seq_ops = {
955         .start = dl_seq_start,
956         .next  = dl_seq_next,
957         .stop  = dl_seq_stop,
958         .show  = dl_seq_show
959 };
960
961 static int dl_proc_open(struct inode *inode, struct file *file)
962 {
963         int ret = seq_open(file, &dl_seq_ops);
964
965         if (!ret) {
966                 struct seq_file *sf = file->private_data;
967                 sf->private = PDE(inode);
968         }
969         return ret;
970 }
971
972 static const struct file_operations dl_file_ops = {
973         .owner   = THIS_MODULE,
974         .open    = dl_proc_open,
975         .read    = seq_read,
976         .llseek  = seq_lseek,
977         .release = seq_release
978 };
979
980 static int __init hashlimit_mt_init(void)
981 {
982         int err;
983
984         err = xt_register_matches(hashlimit_mt_reg,
985               ARRAY_SIZE(hashlimit_mt_reg));
986         if (err < 0)
987                 goto err1;
988
989         err = -ENOMEM;
990         hashlimit_cachep = kmem_cache_create("xt_hashlimit",
991                                             sizeof(struct dsthash_ent), 0, 0,
992                                             NULL);
993         if (!hashlimit_cachep) {
994                 printk(KERN_ERR "xt_hashlimit: unable to create slab cache\n");
995                 goto err2;
996         }
997         hashlimit_procdir4 = proc_mkdir("ipt_hashlimit", init_net.proc_net);
998         if (!hashlimit_procdir4) {
999                 printk(KERN_ERR "xt_hashlimit: unable to create proc dir "
1000                                 "entry\n");
1001                 goto err3;
1002         }
1003         err = 0;
1004 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
1005         hashlimit_procdir6 = proc_mkdir("ip6t_hashlimit", init_net.proc_net);
1006         if (!hashlimit_procdir6) {
1007                 printk(KERN_ERR "xt_hashlimit: unable to create proc dir "
1008                                 "entry\n");
1009                 err = -ENOMEM;
1010         }
1011 #endif
1012         if (!err)
1013                 return 0;
1014         remove_proc_entry("ipt_hashlimit", init_net.proc_net);
1015 err3:
1016         kmem_cache_destroy(hashlimit_cachep);
1017 err2:
1018         xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1019 err1:
1020         return err;
1021
1022 }
1023
1024 static void __exit hashlimit_mt_exit(void)
1025 {
1026         remove_proc_entry("ipt_hashlimit", init_net.proc_net);
1027 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
1028         remove_proc_entry("ip6t_hashlimit", init_net.proc_net);
1029 #endif
1030         kmem_cache_destroy(hashlimit_cachep);
1031         xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
1032 }
1033
1034 module_init(hashlimit_mt_init);
1035 module_exit(hashlimit_mt_exit);