You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.1 KiB

  1. #!/bin/sh
  2. #
  3. # Copyright (C) 2018 rosysong@rosinson.com
  4. #
  5. . /lib/nft-qos/core.sh
  6. # return average rate for dhcp leases
  7. qosdef_dynamic_rate() { # <bandwidth>
  8. local c=0 c6=0
  9. [ ! -e /tmp/dhcp.leases -a \
  10. ! -e /var/dhcp6.leases ] && return
  11. [ -e /tmp/dhcp.leases ] && \
  12. c=$(wc -l < /tmp/dhcp.leases 2>/dev/null)
  13. [ -e /var/dhcp6.leases ] && \
  14. c6=$(wc -l < /var/dhcp6.leases 2>/dev/null)
  15. [ $c -eq 0 -a $c6 -eq 0 ] && \
  16. { echo 12500; return; }
  17. echo $(($1 / ($c + $c6)))
  18. }
  19. qosdef_append_chain_dym() { # <hook> <name> <bandwidth>
  20. local cidr cidr6
  21. local operator rate
  22. local hook=$1 name=$2 bandwidth=$3
  23. config_get cidr default 'dynamic_cidr'
  24. config_get cidr6 default 'dynamic_cidr6'
  25. [ -z "$cidr" -a -z "$cidr6" ] && return
  26. case "$2" in
  27. download) operator=daddr;;
  28. upload) operator=saddr;;
  29. esac
  30. rate=$(qosdef_dynamic_rate $bandwidth)
  31. qosdef_appendx "\tchain $name {\n"
  32. qosdef_append_chain_def filter $hook 0 accept
  33. qosdef_append_rule_limit_whitelist $name
  34. [ -n "$cidr" ] && \
  35. qosdef_append_rule_ip_limit $cidr $operator kbytes $rate
  36. [ -n "$cidr6" ] && \
  37. qosdef_append_rule_ip_limit $cidr6 $operator kbytes $rate
  38. qosdef_appendx "\t}\n"
  39. }
  40. qosdef_flush_dynamic() {
  41. qosdef_flush_table "$NFT_QOS_INET_FAMILY" nft-qos-dynamic
  42. }
  43. # init dynamic qos
  44. qosdef_init_dynamic() {
  45. local dynamic_bw_up dynamic_bw_down limit_enable limit_type
  46. local hook_ul="prerouting" hook_dl="postrouting"
  47. uci_validate_section nft-qos default default \
  48. 'limit_enable:bool:0' \
  49. 'limit_type:maxlength(8)' \
  50. 'dynamic_bw_up:uinteger:100' \
  51. 'dynamic_bw_down:uinteger:100'
  52. [ $? -ne 0 ] && {
  53. logger -t nft-qos-dynamic "validation failed"
  54. return 1
  55. }
  56. [ $limit_enable -eq 0 -o \
  57. "$limit_type" = "static" ] && return 1
  58. # Transfer mbits/s to mbytes/s
  59. # e.g. 100,000 kbits == 12,500 kbytes
  60. dynamic_bw_up=$(($dynamic_bw_up * 1000 / 8))
  61. dynamic_bw_down=$(($dynamic_bw_down * 1000 / 8))
  62. [ -z "$NFT_QOS_HAS_BRIDGE" ] && {
  63. hook_ul="postrouting"
  64. hook_dl="prerouting"
  65. }
  66. qosdef_appendx "table $NFT_QOS_INET_FAMILY nft-qos-dynamic {\n"
  67. qosdef_append_chain_dym $hook_ul upload $dynamic_bw_up
  68. qosdef_append_chain_dym $hook_dl download $dynamic_bw_down
  69. qosdef_appendx "}\n"
  70. }