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.

90 lines
2.1 KiB

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