// SPDX-License-Identifier: GPL-2.0-only /* (C) 1999 Jérôme de Vivie <[email protected]> * (C) 1999 Hervé Eychenne <[email protected]> * (C) 2006-2012 Patrick McHardy <[email protected]> */ #define pr_fmt(fmt) … #include <linux/slab.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/interrupt.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter/xt_limit.h> struct xt_limit_priv { … }; MODULE_LICENSE(…) …; MODULE_AUTHOR(…) …; MODULE_DESCRIPTION(…) …; MODULE_ALIAS(…) …; MODULE_ALIAS(…) …; /* The algorithm used is the Simple Token Bucket Filter (TBF) * see net/sched/sch_tbf.c in the linux source tree */ /* Rusty: This is my (non-mathematically-inclined) understanding of this algorithm. The `average rate' in jiffies becomes your initial amount of credit `credit' and the most credit you can ever have `credit_cap'. The `peak rate' becomes the cost of passing the test, `cost'. `prev' tracks the last packet hit: you gain one credit per jiffy. If you get credit balance more than this, the extra credit is discarded. Every time the match passes, you lose `cost' credits; if you don't have that many, the test fails. See Alexey's formal explanation in net/sched/sch_tbf.c. To get the maximum range, we multiply by this factor (ie. you get N credits per jiffy). We want to allow a rate as low as 1 per day (slowest userspace tool allows), which means CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32. ie. */ #define MAX_CPJ … /* Repeated shift and or gives us all 1s, final shift and add 1 gives * us the power of 2 below the theoretical max, so GCC simply does a * shift. */ #define _POW2_BELOW2(x) … #define _POW2_BELOW4(x) … #define _POW2_BELOW8(x) … #define _POW2_BELOW16(x) … #define _POW2_BELOW32(x) … #define POW2_BELOW32(x) … #define CREDITS_PER_JIFFY … static bool limit_mt(const struct sk_buff *skb, struct xt_action_param *par) { … } /* Precision saver. */ static u32 user2credits(u32 user) { … } static int limit_mt_check(const struct xt_mtchk_param *par) { … } static void limit_mt_destroy(const struct xt_mtdtor_param *par) { … } #ifdef CONFIG_NETFILTER_XTABLES_COMPAT struct compat_xt_rateinfo { … }; /* To keep the full "prev" timestamp, the upper 32 bits are stored in the * master pointer, which does not need to be preserved. */ static void limit_mt_compat_from_user(void *dst, const void *src) { … } static int limit_mt_compat_to_user(void __user *dst, const void *src) { … } #endif /* CONFIG_NETFILTER_XTABLES_COMPAT */ static struct xt_match limit_mt_reg __read_mostly = …; static int __init limit_mt_init(void) { … } static void __exit limit_mt_exit(void) { … } module_init(…) …; module_exit(limit_mt_exit);