xt_quota.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * netfilter module to enforce network quotas
  3. *
  4. * Sam Johnston <samj@samj.net>
  5. */
  6. #include <linux/skbuff.h>
  7. #include <linux/slab.h>
  8. #include <linux/spinlock.h>
  9. #include <linux/netfilter/x_tables.h>
  10. #include <linux/netfilter/xt_quota.h>
  11. struct xt_quota_priv {
  12. spinlock_t lock;
  13. uint64_t quota;
  14. };
  15. MODULE_LICENSE("GPL");
  16. MODULE_AUTHOR("Sam Johnston <samj@samj.net>");
  17. MODULE_DESCRIPTION("Xtables: countdown quota match");
  18. MODULE_ALIAS("ipt_quota");
  19. MODULE_ALIAS("ip6t_quota");
  20. static bool
  21. quota_mt(const struct sk_buff *skb, struct xt_action_param *par)
  22. {
  23. struct xt_quota_info *q = (void *)par->matchinfo;
  24. struct xt_quota_priv *priv = q->master;
  25. bool ret = q->flags & XT_QUOTA_INVERT;
  26. spin_lock_bh(&priv->lock);
  27. if (priv->quota >= skb->len) {
  28. priv->quota -= skb->len;
  29. ret = !ret;
  30. } else {
  31. /* we do not allow even small packets from now on */
  32. priv->quota = 0;
  33. }
  34. spin_unlock_bh(&priv->lock);
  35. return ret;
  36. }
  37. static int quota_mt_check(const struct xt_mtchk_param *par)
  38. {
  39. struct xt_quota_info *q = par->matchinfo;
  40. if (q->flags & ~XT_QUOTA_MASK)
  41. return -EINVAL;
  42. q->master = kmalloc(sizeof(*q->master), GFP_KERNEL);
  43. if (q->master == NULL)
  44. return -ENOMEM;
  45. spin_lock_init(&q->master->lock);
  46. q->master->quota = q->quota;
  47. return 0;
  48. }
  49. static void quota_mt_destroy(const struct xt_mtdtor_param *par)
  50. {
  51. const struct xt_quota_info *q = par->matchinfo;
  52. kfree(q->master);
  53. }
  54. static struct xt_match quota_mt_reg __read_mostly = {
  55. .name = "quota",
  56. .revision = 0,
  57. .family = NFPROTO_UNSPEC,
  58. .match = quota_mt,
  59. .checkentry = quota_mt_check,
  60. .destroy = quota_mt_destroy,
  61. .matchsize = sizeof(struct xt_quota_info),
  62. .me = THIS_MODULE,
  63. };
  64. static int __init quota_mt_init(void)
  65. {
  66. return xt_register_match(&quota_mt_reg);
  67. }
  68. static void __exit quota_mt_exit(void)
  69. {
  70. xt_unregister_match(&quota_mt_reg);
  71. }
  72. module_init(quota_mt_init);
  73. module_exit(quota_mt_exit);