-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathflexqos.sh
1924 lines (1777 loc) · 74.3 KB
/
flexqos.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
###########################################################
# ______ _ ____ _____ #
# | ____|| | / __ \ / ____| #
# | |__ | | ___ __ __| | | | ___ | (___ #
# | __| | | / _ \\ \/ /| | | | / _ \ \___ \ #
# | | | || __/ > < | |__| || (_) |____) | #
# |_| |_| \___|/_/\_\ \___\_\ \___/|_____/ #
# #
###########################################################
# FlexQoS maintained by dave14305
# Contributors: @maghuro
# shellcheck disable=SC1090,SC1091,SC2039,SC2154,SC3043
# amtm NoMD5check
version=1.4.4
release=2024-11-26
# Forked from FreshJR_QOS v8.8, written by FreshJR07 https://github.com/FreshJR07/FreshJR_QOS
# License
# FlexQoS is free to use under the GNU General Public License, version 3 (GPL-3.0).
# https://opensource.org/licenses/GPL-3.0
# initialize Merlin Addon API helper functions
. /usr/sbin/helper.sh
# -x is a flag to show verbose script output for debugging purposes only
if [ "${1}" = "-x" ]; then
shift
set -x
fi
# Global variables
readonly SCRIPTNAME_DISPLAY="FlexQoS"
readonly SCRIPTNAME="flexqos"
readonly GIT_URL="https://raw.githubusercontent.com/dave14305/${SCRIPTNAME_DISPLAY}/master"
readonly ADDON_DIR="/jffs/addons/${SCRIPTNAME}"
readonly WEBUIPATH="${ADDON_DIR}/${SCRIPTNAME}.asp"
readonly SCRIPTPATH="${ADDON_DIR}/${SCRIPTNAME}.sh"
readonly LOCKFILE="/tmp/addonwebui.lock"
IPv6_enabled="$(nvram get ipv6_service)"
# Update version number in custom_settings.txt for reading in WebUI
if [ "$(am_settings_get "${SCRIPTNAME}"_ver)" != "${version}" ]; then
am_settings_set "${SCRIPTNAME}"_ver "${version}"
fi
# If Merlin fq_codel patch is active, use original tc binary for passing commands
# Will be obsolete in 386.1 and higher.
if [ -e "/usr/sbin/realtc" ]; then
TC="/usr/sbin/realtc"
else
TC="/usr/sbin/tc"
fi
# Detect if script is run from an SSH shell interactively or being invoked via cron or from the WebUI (unattended)
if tty >/dev/null 2>&1; then
mode="interactive"
else
mode="unattended"
fi
# marks for iptables rules
# We use the ffff value to avoid conflicts with predefined apps in AppDB so there would be no conflict
# with any user-defined AppDB rules.
Net_mark="09"
Work_mark="06"
Gaming_mark="08"
Others_mark="0a"
Web_mark="18"
Streaming_mark="04"
Downloads_mark="03"
Learn_mark="3f"
logmsg() {
if [ "$#" = "0" ]; then
return
fi
logger -t "${SCRIPTNAME_DISPLAY}" "$*"
} # logmsg
Red() {
printf -- '\033[1;31m%s\033[0m\n' "${1}"
}
Green() {
printf -- '\033[1;32m%s\033[0m\n' "${1}"
}
Blue() {
printf -- '\033[1;36m%s\033[0m\n' "${1}"
}
Yellow() {
printf -- '\033[1;33m%s\033[0m\n' "${1}"
}
get_class_mark() {
case "${1}" in
0) printf "%s\n" "${Net_mark}" ;;
1) printf "%s\n" "${Gaming_mark}" ;;
2) printf "%s\n" "${Streaming_mark}" ;;
3) printf "%s\n" "${Work_mark}" ;;
4) printf "%s\n" "${Web_mark}" ;;
5) printf "%s\n" "${Downloads_mark}" ;;
6) printf "%s\n" "${Others_mark}" ;;
7) printf "%s\n" "${Learn_mark}" ;;
*) printf "%s\n" "" ;;
esac
}
iptables_static_rules() {
local OUTPUTCLS
OUTPUTCLS="$(am_settings_get "${SCRIPTNAME}"_outputcls)"
OUTPUTCLS="$(get_class_mark "${OUTPUTCLS:-5}")" # If setting not found, use default value of 5 (File Transfers)
printf "Applying iptables static rules\n"
# Reference for VPN Fix origin: https://www.snbforums.com/threads/36836/page-78#post-412034
# Partially fixed in https://github.com/RMerl/asuswrt-merlin.ng/commit/f7d6478df7b934c9540fa9740ad71d49d84a1756
iptables -t mangle -D OUTPUT -o "${wan}" -p udp -m multiport --dports 53,123 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff > /dev/null 2>&1 # Outbound DNS & NTP
iptables -t mangle -A OUTPUT -o "${wan}" -p udp -m multiport --dports 53,123 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff
iptables -t mangle -D OUTPUT -o "${wan}" -p tcp -m multiport --dports 53,853 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff > /dev/null 2>&1 # Outbound DNS and DoT
iptables -t mangle -A OUTPUT -o "${wan}" -p tcp -m multiport --dports 53,853 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff
iptables -t mangle -D OUTPUT -o "${wan}" -p udp -m multiport ! --dports 53,123 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff > /dev/null 2>&1 #VPN Fix - (Fixes upload traffic not detected when the router is acting as a VPN Client)
iptables -t mangle -A OUTPUT -o "${wan}" -p udp -m multiport ! --dports 53,123 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff
iptables -t mangle -D OUTPUT -o "${wan}" -p tcp -m multiport ! --dports 53,853 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff > /dev/null 2>&1 #VPN Fix - (Fixes upload traffic not detected when the router is acting as a VPN Client)
iptables -t mangle -A OUTPUT -o "${wan}" -p tcp -m multiport ! --dports 53,853 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff
iptables -t mangle -N "${SCRIPTNAME_DISPLAY}_down" 2>/dev/null
iptables -t mangle -N "${SCRIPTNAME_DISPLAY}_up" 2>/dev/null
iptables -t mangle -A POSTROUTING -o "${lan}" -m mark --mark 0x80000000/0xc0000000 -j "${SCRIPTNAME_DISPLAY}_down"
iptables -t mangle -A POSTROUTING -o "${wan}" -m mark --mark 0x40000000/0xc0000000 -j "${SCRIPTNAME_DISPLAY}_up"
if [ "${IPv6_enabled}" != "disabled" ]; then
ip6tables -t mangle -D OUTPUT -o "${wan}" -p udp -m multiport --dports 53,123 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff > /dev/null 2>&1 # Outbound DNS & NTP
ip6tables -t mangle -A OUTPUT -o "${wan}" -p udp -m multiport --dports 53,123 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff
ip6tables -t mangle -D OUTPUT -o "${wan}" -p tcp -m multiport --dports 53,853 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff > /dev/null 2>&1 # Outbound DNS and DoT
ip6tables -t mangle -A OUTPUT -o "${wan}" -p tcp -m multiport --dports 53,853 -j MARK --set-mark 0x40"${Net_mark}"0fff/0xc03f0fff
ip6tables -t mangle -D OUTPUT -o "${wan}" -p udp -m multiport ! --dports 53,123 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff > /dev/null 2>&1 #VPN Fix - (Fixes upload traffic not detected when the router is acting as a VPN Client)
ip6tables -t mangle -A OUTPUT -o "${wan}" -p udp -m multiport ! --dports 53,123 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff
ip6tables -t mangle -D OUTPUT -o "${wan}" -p tcp -m multiport ! --dports 53,853 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff > /dev/null 2>&1 #VPN Fix - (Fixes upload traffic not detected when the router is acting as a VPN Client)
ip6tables -t mangle -A OUTPUT -o "${wan}" -p tcp -m multiport ! --dports 53,853 -j MARK --set-mark 0x40"${OUTPUTCLS}"ffff/0xc03fffff
ip6tables -t mangle -N "${SCRIPTNAME_DISPLAY}_down" 2>/dev/null
ip6tables -t mangle -N "${SCRIPTNAME_DISPLAY}_up" 2>/dev/null
ip6tables -t mangle -A POSTROUTING -o "${lan}" -m mark --mark 0x80000000/0xc0000000 -j "${SCRIPTNAME_DISPLAY}_down"
ip6tables -t mangle -A POSTROUTING -o "${wan}" -m mark --mark 0x40000000/0xc0000000 -j "${SCRIPTNAME_DISPLAY}_up"
fi
}
get_static_filter() {
local MARK
local FLOWID
MARK="${1}"
FLOWID="${2}"
printf "filter add dev %s protocol all prio 5 u32 match mark 0x80%sffff 0xc03fffff flowid %s\n" "${tclan}" "${MARK}" "${FLOWID}"
printf "filter add dev %s protocol all prio 5 u32 match mark 0x40%sffff 0xc03fffff flowid %s\n" "${tcwan}" "${MARK}" "${FLOWID}"
} # get_static_filter
write_appdb_static_rules() {
# These rules define the flowid (priority level) of the Class destinations selected by users in iptables rules.
# Previous versions of the script were susceptible to the chosen Class being overridden by the users AppDB rules.
# Adding these filters ensures the Class you select in iptables rules is strictly observed.
# prio 5 is used because the first default filter rule (mark 0x80030000 0xc03f0000) is found at prio 6 as of this writing,
# so we want these filters to always take precedence over the built-in filters.
# File is overwritten (>) if it exists and later appended by write_appdb_rules() and write_custom_rates().
{
if [ -n "${iptables_rules}" ]; then
get_static_filter "${Net_mark}" "${Net_flow}"
get_static_filter "${Work_mark}" "${Work_flow}"
get_static_filter "${Gaming_mark}" "${Gaming_flow}"
get_static_filter "${Others_mark}" "${Others_flow}"
get_static_filter "${Web_mark}" "${Web_flow}"
get_static_filter "${Streaming_mark}" "${Streaming_flow}"
get_static_filter "${Downloads_mark}" "${Downloads_flow}"
get_static_filter "${Learn_mark}" "${Learn_flow}"
fi
} > "/tmp/${SCRIPTNAME}_tcrules"
} # write_appdb_static_rules
get_burst() {
local RATE
local DURATION
local BURST
local MIN_BURST
RATE="${1}"
DURATION="${2}" # acceptable added latency in microseconds (1ms)
# https://github.com/tohojo/sqm-scripts/blob/master/src/functions.sh
# let's assume ATM/AAL5 to be the worst case encapsulation
# and 48 Bytes a reasonable worst case per packet overhead
MIN_BURST=$(( WANMTU + 48 )) # add 48 bytes to MTU for the ovehead
MIN_BURST=$(( MIN_BURST + 47 )) # now do ceil(Min_BURST / 48) * 53 in shell integer arithmic
MIN_BURST=$(( MIN_BURST / 48 ))
MIN_BURST=$(( MIN_BURST * 53 )) # for MTU 1489 to 1536 this will result in MIN_BURST = 1749 Bytes
BURST=$((DURATION*RATE/8000))
# If the calculated burst is less than ASUS' minimum value of 3200, use 3200
# to avoid problems with child and leaf classes outside of FlexQoS scope that use 3200.
# If using fq_codel option, use 1600 as a minimum burst.
if [ "$(am_settings_get "${SCRIPTNAME}"_qdisc)" = "0" ]; then
if [ "${BURST}" -lt 3200 ]; then
BURST=3200
fi
elif [ "${BURST}" -lt "${MIN_BURST}" ]; then
BURST="${MIN_BURST}"
fi
printf "%s" "${BURST}"
} # get_burst
get_cburst() {
local RATE
local BURST
local MIN_BURST
RATE="${1}"
# https://github.com/tohojo/sqm-scripts/blob/master/src/functions.sh
# let's assume ATM/AAL5 to be the worst case encapsulation
# and 48 Bytes a reasonable worst case per packet overhead
MIN_BURST=$(( WANMTU + 48 )) # add 48 bytes to MTU for the ovehead
MIN_BURST=$(( MIN_BURST + 47 )) # now do ceil(Min_BURST / 48) * 53 in shell integer arithmic
MIN_BURST=$(( MIN_BURST / 48 ))
MIN_BURST=$(( MIN_BURST * 53 )) # for MTU 1489 to 1536 this will result in MIN_BURST = 1749 Bytes
BURST=$((RATE*1000/1280000))
BURST=$((BURST*1600))
# If the calculated burst is less than ASUS' minimum value of 3200, use 3200
# to avoid problems with child and leaf classes outside of FlexQoS scope that use 3200.
if [ "${BURST}" -lt 3200 ]; then
if [ "$(am_settings_get "${SCRIPTNAME}"_qdisc)" = "0" ]; then
BURST=3200
else
BURST="${MIN_BURST}"
fi
fi
printf "%s" "${BURST}"
} # get_cburst
get_quantum() {
local RATE
local QUANTUM
local MIN_QUANTUM
RATE="${1}"
# https://github.com/tohojo/sqm-scripts/blob/master/src/functions.sh
# let's assume ATM/AAL5 to be the worst case encapsulation
# and 48 Bytes a reasonable worst case per packet overhead
MIN_QUANTUM=$(( WANMTU + 48 )) # add 48 bytes to MTU for the ovehead
MIN_QUANTUM=$(( MIN_QUANTUM + 47 )) # now do ceil(Min_BURST / 48) * 53 in shell integer arithmic
MIN_QUANTUM=$(( MIN_QUANTUM / 48 ))
MIN_QUANTUM=$(( MIN_QUANTUM * 53 )) # for MTU 1489 to 1536 this will result in MIN_BURST = 1749 Bytes
QUANTUM=$((RATE*1000/8/10))
# If the calculated quantum is less than the MTU, use MTU+14 as the quantum
if [ "${QUANTUM}" -lt "${MIN_QUANTUM}" ]; then
QUANTUM="${MIN_QUANTUM}"
fi
printf "%s" "${QUANTUM}"
} # get_quantum
get_overhead() {
local NVRAM_OVERHEAD
local NVRAM_ATM
local OVERHEAD
NVRAM_OVERHEAD="$(nvram get qos_overhead)"
if [ -n "${NVRAM_OVERHEAD}" ] && [ "${NVRAM_OVERHEAD}" -gt "0" ]; then
OVERHEAD="overhead ${NVRAM_OVERHEAD}"
NVRAM_ATM="$(nvram get qos_atm)"
if [ "${NVRAM_ATM}" = "1" ]; then
OVERHEAD="${OVERHEAD} linklayer atm"
else
OVERHEAD="${OVERHEAD} linklayer ethernet"
fi
fi
printf "%s" "${OVERHEAD}"
} # get_overhead
get_custom_rate_rule() {
local IFACE
local PRIO
local RATE
local CEIL
local DURATION
IFACE="${1}"
PRIO="${2}"
RATE="${3}"
CEIL="${4}"
DURATION=1000 # 1000 microseconds = 1 ms
printf "class change dev %s parent 1:1 classid 1:1%s htb %s prio %s rate %sKbit ceil %sKbit burst %sb cburst %sb quantum %s\n" \
"${IFACE}" "${PRIO}" "$(get_overhead)" "${PRIO}" "${RATE}" "${CEIL}" "$(get_burst "${CEIL}" "${DURATION}")" "$(get_cburst "${CEIL}")" "$(get_quantum "${RATE}")"
} # get_custom_rate_rule
write_custom_rates() {
local i
if [ "${DownCeil}" -gt "0" ] && [ "${UpCeil}" -gt "0" ]; then
# For all 8 classes (0-7), write the tc commands needed to modify the bandwidth rates and related parameters
# that get assigned in set_tc_variables().
# File is appended (>>) because it is initially created in write_appdb_static_rules().
{
for i in 0 1 2 3 4 5 6 7
do
eval get_custom_rate_rule "${tclan}" "${i}" \$DownRate${i} \$DownCeil${i}
eval get_custom_rate_rule "${tcwan}" "${i}" \$UpRate${i} \$UpCeil${i}
done
} >> "/tmp/${SCRIPTNAME}_tcrules"
fi
} # write_custom_rates
set_tc_variables() {
# Read various settings from the router and construct the variables needed to implement the custom rules.
local drp0 drp1 drp2 drp3 drp4 drp5 drp6 drp7
local dcp0 dcp1 dcp2 dcp3 dcp4 dcp5 dcp6 dcp7
local urp0 urp1 urp2 urp3 urp4 urp5 urp6 urp7
local ucp0 ucp1 ucp2 ucp3 ucp4 ucp5 ucp6 ucp7
# shellcheck disable=SC2034
local Cat0DownBandPercent Cat1DownBandPercent Cat2DownBandPercent Cat3DownBandPercent Cat4DownBandPercent Cat5DownBandPercent Cat6DownBandPercent Cat7DownBandPercent
# shellcheck disable=SC2034
local Cat0DownCeilPercent Cat1DownCeilPercent Cat2DownCeilPercent Cat3DownCeilPercent Cat4DownCeilPercent Cat5DownCeilPercent Cat6DownCeilPercent Cat7DownCeilPercent
# shellcheck disable=SC2034
local Cat0UpBandPercent Cat1UpBandPercent Cat2UpBandPercent Cat3UpBandPercent Cat4UpBandPercent Cat5UpBandPercent Cat6UpBandPercent Cat7UpBandPercent
# shellcheck disable=SC2034
local Cat0UpCeilPercent Cat1UpCeilPercent Cat2UpCeilPercent Cat3UpCeilPercent Cat4UpCeilPercent Cat5UpCeilPercent Cat6UpCeilPercent Cat7UpCeilPercent
local flowid
local line
local i
tclan="br0"
if [ -f /sys/module/tdts_udb/parameters/qos_wan ]; then
tcwan="$(cat /sys/module/tdts_udb/parameters/qos_wan)"
else
tcwan="$(nvram get wan_ifname)"
fi
# Detect the default filter rule for Untracked traffic (Mark 000000) if it exists.
# Newer 384 stock firmware dropped this rule, so Untracked traffic flows into the Work-From-Home priority by default.
# First check for older ASUS default rule (0x80000000 0xc000ffff).
# If not found, get the prio for the Work-From-Home Instant messengers category 00 (0x80000000 0xc03f0000) and subtract 1.
undf_prio="$("${TC}" filter show dev br0 | /bin/grep -i -m1 -B1 "0x80000000 0xc000ffff" | sed -nE 's/.* pref ([0-9]+) .*/\1/p')"
if [ -z "${undf_prio}" ]; then
undf_prio="$("${TC}" filter show dev br0 | /bin/grep -i -m1 -B1 "0x80000000 0xc03f0000" | sed -nE 's/.* pref ([0-9]+) .*/\1/p')"
undf_prio="$((undf_prio-1))"
fi
read -r \
drp0 drp1 drp2 drp3 drp4 drp5 drp6 drp7 \
dcp0 dcp1 dcp2 dcp3 dcp4 dcp5 dcp6 dcp7 \
urp0 urp1 urp2 urp3 urp4 urp5 urp6 urp7 \
ucp0 ucp1 ucp2 ucp3 ucp4 ucp5 ucp6 ucp7 \
<<EOF
$(echo "${bwrates}" | sed 's/^<//g;s/[<>]/ /g')
EOF
# read priority order of QoS categories as set by user on the QoS page of the GUI
flowid=0
while read -r line;
do
if [ "$(echo "${line}" | cut -c 1)" = '[' ]; then
flowid="$(echo "${line}" | cut -c 2)"
fi
case "${line}" in
'0')
Work_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp3}"
eval "Cat${flowid}DownCeilPercent=${dcp3}"
eval "Cat${flowid}UpBandPercent=${urp3}"
eval "Cat${flowid}UpCeilPercent=${ucp3}"
;;
'1')
Downloads_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp5}"
eval "Cat${flowid}DownCeilPercent=${dcp5}"
eval "Cat${flowid}UpBandPercent=${urp5}"
eval "Cat${flowid}UpCeilPercent=${ucp5}"
;;
'4')
# Special handling for category 4 since it is duplicated between Streaming and Learn-From-Home.
# We have to find the priority placement of Learn-From-Home versus Streaming in the QoS GUI to know
# if the first time we encounter a 4 in the file if it is meant to be Streaming or Learn-From-Home.
# The second time we encounter a 4, we know it is meant for the remaining option.
if nvram get bwdpi_app_rulelist | /bin/grep -qE "<4,13(<.*)?<4<"; then
# Learn-From-Home is higher priority than Streaming
if [ -z "${Learn_flow}" ]; then
Learn_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp7}"
eval "Cat${flowid}DownCeilPercent=${dcp7}"
eval "Cat${flowid}UpBandPercent=${urp7}"
eval "Cat${flowid}UpCeilPercent=${ucp7}"
else
Streaming_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp2}"
eval "Cat${flowid}DownCeilPercent=${dcp2}"
eval "Cat${flowid}UpBandPercent=${urp2}"
eval "Cat${flowid}UpCeilPercent=${ucp2}"
fi
else
# Streaming is higher priority than Learn-From-Home
if [ -z "${Streaming_flow}" ]; then
Streaming_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp2}"
eval "Cat${flowid}DownCeilPercent=${dcp2}"
eval "Cat${flowid}UpBandPercent=${urp2}"
eval "Cat${flowid}UpCeilPercent=${ucp2}"
else
Learn_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp7}"
eval "Cat${flowid}DownCeilPercent=${dcp7}"
eval "Cat${flowid}UpBandPercent=${urp7}"
eval "Cat${flowid}UpCeilPercent=${ucp7}"
fi
fi # Check Learn-From-Home and Streaming priority order
;;
'7')
Others_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp6}"
eval "Cat${flowid}DownCeilPercent=${dcp6}"
eval "Cat${flowid}UpBandPercent=${urp6}"
eval "Cat${flowid}UpCeilPercent=${ucp6}"
;;
'8')
Gaming_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp1}"
eval "Cat${flowid}DownCeilPercent=${dcp1}"
eval "Cat${flowid}UpBandPercent=${urp1}"
eval "Cat${flowid}UpCeilPercent=${ucp1}"
;;
'9')
Net_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp0}"
eval "Cat${flowid}DownCeilPercent=${dcp0}"
eval "Cat${flowid}UpBandPercent=${urp0}"
eval "Cat${flowid}UpCeilPercent=${ucp0}"
;;
'24')
Web_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp4}"
eval "Cat${flowid}DownCeilPercent=${dcp4}"
eval "Cat${flowid}UpBandPercent=${urp4}"
eval "Cat${flowid}UpCeilPercent=${ucp4}"
;;
'na')
# This is how the old ASUS default category would appear, but this option will soon be deprecated
# when all supported models are using the new QoS Categories.
Learn_flow="1:1${flowid}"
eval "Cat${flowid}DownBandPercent=${drp7}"
eval "Cat${flowid}DownCeilPercent=${dcp7}"
eval "Cat${flowid}UpBandPercent=${urp7}"
eval "Cat${flowid}UpCeilPercent=${ucp7}"
;;
esac
done <<EOF
$(sed -E '/^ceil_/d;s/rule=//g;/\{/q' /tmp/bwdpi/qosd.conf | head -n -1)
EOF
#calculate up/down rates based on user-provided bandwidth from GUI
#GUI shows in Mb/s; nvram stores in Kb/s
DownCeil="$(printf "%.0f" "$(nvram get qos_ibw)")"
UpCeil="$(printf "%.0f" "$(nvram get qos_obw)")"
# Only apply custom rates if Manual Bandwidth mode set in QoS page
if [ "${DownCeil}" -gt "0" ] && [ "${UpCeil}" -gt "0" ]; then
# Automatic bandwidth mode incompatible with custom rates
i=0
while [ "${i}" -lt "8" ]
do
eval "DownRate${i}=\$((DownCeil\*Cat${i}DownBandPercent/100))"
eval "UpRate${i}=\$((UpCeil\*Cat${i}UpBandPercent/100))"
eval "DownCeil${i}=\$((DownCeil\*Cat${i}DownCeilPercent/100))"
eval "UpCeil${i}=\$((UpCeil\*Cat${i}UpCeilPercent/100))"
i="$((i+1))"
done
fi # Auto Bandwidth check
} # set_tc_variables
appdb() {
# Search TrendMicro appdb file for matches to user-specified string. Return up to 25 matches
local line cat_decimal
/bin/grep -m 25 -i "${1}" /tmp/bwdpi/bwdpi.app.db | while read -r line; do
echo "${line}" | awk -F "," '{printf " Application: %s\n Mark: %02X%04X\nDefault Class: ", $4, $1, $2}'
cat_decimal=$(echo "${line}" | cut -f 1 -d "," )
case "${cat_decimal}" in
'9'|'18'|'19'|'20')
printf "Net Control Packets"
;;
'0'|'5'|'6'|'15'|'17')
printf "Work-From-Home"
;;
'8')
printf "Gaming"
;;
'7'|'10'|'11'|'21'|'23')
printf "Others"
;;
'13'|'24')
printf "Web Surfing"
;;
'4')
printf "Video and Audio Streaming"
;;
'1'|'3'|'14')
printf "File Transferring"
;;
*)
printf "Unknown"
;;
esac
printf "\n\n"
done
} # appdb
webconfigpage() {
local urlpage urlproto urldomain urlport
# Eye candy function that will construct a URL to display after install or upgrade so a user knows where to
# find the webUI page. In most cases though, they will go to the Adaptive QoS tab and find the FlexQoS sub-tab anyway.
urlpage="$(sed -nE "/${SCRIPTNAME_DISPLAY}/ s/.*url\: \"(user[0-9]+\.asp)\".*/\1/p" /tmp/menuTree.js)"
if [ "$(nvram get http_enable)" = "1" ]; then
urlproto="https"
else
urlproto="http"
fi
if [ -n "$(nvram get lan_domain)" ]; then
urldomain="$(nvram get lan_hostname).$(nvram get lan_domain)"
else
urldomain="$(nvram get lan_ipaddr)"
fi
if [ "$(nvram get ${urlproto}_lanport)" = "80" ] || [ "$(nvram get ${urlproto}_lanport)" = "443" ]; then
urlport=""
else
urlport=":$(nvram get ${urlproto}_lanport)"
fi
if echo "${urlpage}" | grep -qE "user[0-9]+\.asp"; then
printf "Advanced configuration available via:\n"
Blue " ${urlproto}://${urldomain}${urlport}/${urlpage}"
fi
} # webconfigpage
scriptinfo() {
# Version header used in interactive sessions
[ "${mode}" = "interactive" ] || return
printf "\n"
Green "${SCRIPTNAME_DISPLAY} v${version} released ${release}"
printf "\n"
} # scriptinfo
debug() {
local RMODEL ipt_debug appdb_debug
[ -z "$(nvram get odmpid)" ] && RMODEL="$(nvram get productid)" || RMODEL="$(nvram get odmpid)"
Green "[SPOILER=\"${SCRIPTNAME_DISPLAY} Debug\"][CODE]"
scriptinfo
printf "Debug date : %s\n" "$(date +'%Y-%m-%d %H:%M:%S%z')"
printf "Router Model : %s\n" "${RMODEL}"
printf "Firmware Ver : %s_%s\n" "$(nvram get buildno)" "$(nvram get extendno)"
printf "DPI/Sig Ver : %s / %s\n" "$(nvram get bwdpi_dpi_ver)" "$(nvram get bwdpi_sig_ver)"
get_config
set_tc_variables
printf "WAN iface : %s\n" "${wan}"
printf "tc WAN iface : %s\n" "${tcwan}"
printf "IPv6 : %s\n" "${IPv6_enabled}"
printf "Undf Prio : %s\n" "${undf_prio}"
printf "Down Band : %s\n" "${DownCeil}"
printf "Up Band : %s\n" "${UpCeil}"
printf "*****************\n"
printf "Net Control : %s\n" "${Net_flow}"
printf "Work-From-Home : %s\n" "${Work_flow}"
printf "Gaming : %s\n" "${Gaming_flow}"
printf "Others : %s\n" "${Others_flow}"
printf "Web Surfing : %s\n" "${Web_flow}"
printf "Streaming : %s\n" "${Streaming_flow}"
printf "File Transfers : %s\n" "${Downloads_flow}"
printf "Learn-From-Home : %s\n" "${Learn_flow}"
printf "*****************\n"
# Only print custom rates if Manual Bandwidth setting is enabled on QoS page
if [ "${DownCeil}" -gt "0" ] && [ "${UpCeil}" -gt "0" ]; then
printf "Downrates : %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s\n" "${DownRate0}" "${DownRate1}" "${DownRate2}" "${DownRate3}" "${DownRate4}" "${DownRate5}" "${DownRate6}" "${DownRate7}"
printf "Downceils : %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s\n" "${DownCeil0}" "${DownCeil1}" "${DownCeil2}" "${DownCeil3}" "${DownCeil4}" "${DownCeil5}" "${DownCeil6}" "${DownCeil7}"
printf "Uprates : %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s\n" "${UpRate0}" "${UpRate1}" "${UpRate2}" "${UpRate3}" "${UpRate4}" "${UpRate5}" "${UpRate6}" "${UpRate7}"
printf "Upceils : %7s, %7s, %7s, %7s, %7s, %7s, %7s, %7s\n" "${UpCeil0}" "${UpCeil1}" "${UpCeil2}" "${UpCeil3}" "${UpCeil4}" "${UpCeil5}" "${UpCeil6}" "${UpCeil7}"
printf "*****************\n"
else
printf "Custom rates disabled with Automatic Bandwidth mode!\n"
printf "*****************\n"
fi
ipt_debug="$(am_settings_get "${SCRIPTNAME}"_iptables)"
printf "iptables settings: %s\n" "${ipt_debug:-Defaults}"
write_iptables_rules
# Remove superfluous commands from the output in order to focus on the parsed details
/bin/sed -E "/^ip[6]?tables -t mangle -[FD] /d; s/ip[6]?tables -t mangle //g; s/[[:space:]]{2,}/ /g" "/tmp/${SCRIPTNAME}_iprules"
printf "*****************\n"
appdb_debug="$(am_settings_get "${SCRIPTNAME}"_appdb)"
printf "appdb rules: %s\n" "${appdb_debug:-Defaults}"
true > "/tmp/${SCRIPTNAME}_tcrules"
write_appdb_rules
write_custom_rates
cat "/tmp/${SCRIPTNAME}_tcrules"
Green "[/CODE][/SPOILER]"
# Since these tmp files aren't being used to apply rules, we delete them to avoid confusion about the last known ruleset
rm "/tmp/${SCRIPTNAME}_iprules" "/tmp/${SCRIPTNAME}_tcrules"
printf "\n"
Yellow "Copy the text from [SPOILER] to [/SPOILER] and paste into a forum post at snbforums.com"
} # debug
get_flowid() {
# Map class destination field from webui settings to the established class/flowid based on user priorities
# flowid will be one of 1:10 - 1:17, depending on the user priority sequencing in the QoS GUI
# Input: numeric class destination from iptables rule
local flowid
case "${1}" in
0) flowid="${Net_flow}" ;;
1) flowid="${Gaming_flow}" ;;
2) flowid="${Streaming_flow}" ;;
3) flowid="${Work_flow}" ;;
4) flowid="${Web_flow}" ;;
5) flowid="${Downloads_flow}" ;;
6) flowid="${Others_flow}" ;;
7) flowid="${Learn_flow}" ;;
# return empty if destination missing
*) flowid="" ;;
esac
printf "%s\n" "${flowid}"
} # get_flowid
Is_Valid_CIDR() {
/bin/grep -qE '^[!]?([0-9]{1,3}\.){3}[0-9]{1,3}(/[0-9]{1,2})?$'
} # Is_Valid_CIDR
Is_Valid_Port() {
/bin/grep -qE '^[!]?([0-9]{1,5})((:[0-9]{1,5})?|(,[0-9]{1,5})*)$'
} # Is_Valid_Port
Is_Valid_Mark() {
/bin/grep -qE '^[!]?[A-Fa-f0-9]{2}([A-Fa-f0-9]{4}|[\*]{4})$'
} # Is_Valid_Mark
parse_appdb_rule() {
# Process an appdb custom rule into the appropriate tc filter syntax
# Input: $1 = Mark from appdb rule XXYYYY XX=Category(hex) YYYY=ID(hex or ****)
# $2 = Class destination
# Output: stdout is written directly to the /tmp/flexqos_appdb_rules file via redirect in write_appdb_rules(),
# so don't add unnecessary output in this function.
local cat id
local DOWN_mark UP_mark
local flowid
local currmask
local prio currprio
local currhandledown currhandleup
# Only process if Mark is a valid format
if echo "${1}" | Is_Valid_Mark; then
# Extract category and appid from mark
cat="$(echo "${1}" | cut -c 1-2)"
id="$(echo "${1}" | cut -c 3-6)"
# check if wildcard mark
if [ "${id}" = "****" ]; then
# Replace asterisks with zeros and use category mask
# This mark and mask
DOWN_mark="0x80${cat}0000 0xc03f0000"
UP_mark="0x40${cat}0000 0xc03f0000"
elif [ "${1}" = "000000" ]; then
# unidentified traffic needs a special mask
DOWN_mark="0x80${1} 0xc000ffff"
UP_mark="0x40${1} 0xc000ffff"
else
# specific application mark
DOWN_mark="0x80${1} 0xc03fffff"
UP_mark="0x40${1} 0xc03fffff"
fi
# get destination class
flowid="$(get_flowid "${2}")"
# To override the default tc filters with our custom filter rules, we need to insert our rules
# at a higher priority (lower number) than the built-in filter for each category.
if [ "${1}" = "000000" ]; then
# special mask for unidentified traffic
currmask="0xc000ffff"
else
currmask="0xc03f0000"
fi
# search the tc filter temp file we made in write_appdb_rules() for the existing priority of the
# category we are going to override with a custom appdb filter rule.
# e.g. If we are going to make a rule for appdb mark 1400C5, we need to find the current priority of category 14.
prio="$(/bin/grep -i -m 1 -B1 "0x80${cat}0000 ${currmask}" "/tmp/${SCRIPTNAME}_tmp_tcfilterdown" | sed -nE 's/.* pref ([0-9]+) .*/\1/p')"
currprio="${prio}"
# If there is no existing filter for the category, use the undf_prio defined in set_tc_variables().
# This is usually only necessary for Untracked traffic (mark 000000).
# Otherwise, take the current priority and subtract 1 so that our rule will be processed earlier than the default rule.
if [ -z "${prio}" ]; then
prio="${undf_prio}"
else
prio="$((prio-1))"
fi
# Build and echo the tc filter commands based on the possible actions required:
# 1. Change an existing filter to point to a new flowid (mostly relevant for wildcard appdb rules).
# 2. Insert a new filter at a higher priority than the existing filter that would otherwise match this mark.
if { [ "${id}" = "****" ] || [ "${1}" = "000000" ]; } && [ -n "${currprio}" ]; then
# change existing rule for wildcard marks and Untracked mark only if current priority already determined.
# Need to get handle of existing filter for proper tc filter change syntax.
currhandledown="$(/bin/grep -i -m 1 -B1 "0x80${cat}0000 ${currmask}" "/tmp/${SCRIPTNAME}_tmp_tcfilterdown" | sed -nE 's/.* fh ([0-9a-f:]+) .*/\1/p')"
currhandleup="$(/bin/grep -i -m 1 -B1 "0x40${cat}0000 ${currmask}" "/tmp/${SCRIPTNAME}_tmp_tcfilterup" | sed -nE 's/.* fh ([0-9a-f:]+) .*/\1/p')"
printf "filter change dev %s prio %s protocol all handle %s u32 flowid %s\n" "${tclan}" "${currprio}" "${currhandledown}" "${flowid}"
printf "filter change dev %s prio %s protocol all handle %s u32 flowid %s\n" "${tcwan}" "${currprio}" "${currhandleup}" "${flowid}"
else
# add new rule for individual app one priority level higher (-1)
printf "filter add dev %s protocol all prio %s u32 match mark %s flowid %s\n" "${tclan}" "${prio}" "${DOWN_mark}" "${flowid}"
printf "filter add dev %s protocol all prio %s u32 match mark %s flowid %s\n" "${tcwan}" "${prio}" "${UP_mark}" "${flowid}"
fi
fi # Is_Valid_Mark
} # parse_appdb_rule
create_ipset() {
# To translate IPv4 iptables rules using local IPv4 addresses, create 2 ipsets and 2 iptables rules to track
# corresponding IPv6 addresses for a given IPv4 local address
# Input: $1 = local IP/CIDR (minus optional negation)
# Output: stdout ipset and iptables commands
local LOCALIP IPV6LIFETIME IPV6RASTATE
# If IPv6 is disabled, return early
[ "${IPv6_enabled}" = "disabled" ] && return
# Strip optional negation if present
LOCALIP="${1}"
IPV6RASTATE="$(nvram get ipv6_autoconf_type)" # 0=Stateless, 1=Stateful
ipset -! create "${LOCALIP}-mac" hash:mac timeout "$(nvram get dhcp_lease)" 2>/dev/null
ipset -! flush "${LOCALIP}-mac" 2>/dev/null
case "${IPv6_enabled}" in
dhcp6|other) #Native or Static
if [ "${IPV6RASTATE}" = "1" ]; then
# Stateful, get DHCP Lifetime
IPV6LIFETIME="$(nvram get ipv6_dhcp_lifetime)"
else
# Stateless, use hard-coded value from firmware
IPV6LIFETIME=600
fi
;;
*)
IPV6LIFETIME=600
;;
esac
ipset -! create "${LOCALIP}" hash:ip family inet6 timeout "${IPV6LIFETIME}" 2>/dev/null
ipset -! flush "${LOCALIP}" 2>/dev/null
printf "iptables -t mangle -D PREROUTING -i %s -m conntrack --ctstate NEW -s %s -j SET --add-set %s-mac src --exist 2>/dev/null\n" "${lan}" "${LOCALIP}" "${LOCALIP}"
printf "ip6tables -t mangle -D PREROUTING -i %s -m conntrack --ctstate NEW -m set --match-set %s-mac src -j SET --add-set %s src --exist 2>/dev/null\n" "${lan}" "${LOCALIP}" "${LOCALIP}"
printf "iptables -t mangle -I PREROUTING -i %s -m conntrack --ctstate NEW -s %s -j SET --add-set %s-mac src --exist\n" "${lan}" "${LOCALIP}" "${LOCALIP}"
printf "ip6tables -t mangle -I PREROUTING -i %s -m conntrack --ctstate NEW -m set --match-set %s-mac src -j SET --add-set %s src --exist\n" "${lan}" "${LOCALIP}" "${LOCALIP}"
}
parse_iptablerule() {
# Process an iptables custom rule into the appropriate iptables syntax
# Input: $1 = local IP (e.g. 192.168.1.100 !192.168.1.100 192.168.1.100/31 !192.168.1.100/31)
# $2 = remote IP (e.g. 9.9.9.9 !9.9.9.9 9.9.9.0/24 !9.9.9.0/24)
# $3 = protocol (e.g. both, tcp, or udp)
# $4 = local port (e.g. 443 !443 1234:5678 !1234:5678 53,123,853 !53,123,853)
# $5 = remote port (e.g. 443 !443 1234:5678 !1234:5678 53,123,853 !53,123,853)
# $6 = mark (e.g. XXYYYY !XXYYYY XX=Category(hex) YYYY=ID(hex or ****))
# $7 = class destination (e.g. 0-7)
# Output: stdout is written directly to the /tmp/flexqos_iprules file via redirect in write_iptables_rules(),
# so don't add unnecessary output in this function.
local DOWN_Lip UP_Lip CIDR
local DOWN_Lip6 UP_Lip6
local DOWN_Rip UP_Rip
local PROTOS proto
local DOWN_Lport UP_Lport
local DOWN_Rport UP_Rport
local tmpMark DOWN_mark UP_mark
local DOWN_dst UP_dst Dst_mark
# local IP
# Check for acceptable IP format
if echo "${1}" | Is_Valid_CIDR; then
# print ! (if present) and remaining CIDR
DOWN_Lip="$(echo "${1}" | sed -E 's/^([!])?/\1 -d /')"
UP_Lip="$(echo "${1}" | sed -E 's/^([!])?/\1 -s /')"
# Only create ipset if there is no remote IP/CIDR defined, since the IPv6 rule would not work with remote IPv4 CIDR
if ! echo "${2}" | Is_Valid_CIDR; then
# Alternate syntax for IPv6 ipset matching
CIDR="$(echo "${1}" | sed -E 's/^!//')"
create_ipset "${CIDR}" # 2>/dev/null
DOWN_Lip6="$(echo "${1}" | sed -E 's/^([!])?(([0-9]{1,3}\.){3}[0-9]{1,3}(\/[0-9]{1,2})?)/-m set \1 --match-set \2 dst/')"
UP_Lip6="$(echo "${1}" | sed -E 's/^([!])?(([0-9]{1,3}\.){3}[0-9]{1,3}(\/[0-9]{1,2})?)/-m set \1 --match-set \2 src/')"
fi
else
DOWN_Lip=""
UP_Lip=""
DOWN_Lip6=""
UP_Lip6=""
fi
# remote IP
# Check for acceptable IP format
if echo "${2}" | Is_Valid_CIDR; then
# print ! (if present) and remaining CIDR
DOWN_Rip="$(echo "${2}" | sed -E 's/^([!])?/\1 -s /')"
UP_Rip="$(echo "${2}" | sed -E 's/^([!])?/\1 -d /')"
else
DOWN_Rip=""
UP_Rip=""
fi
# protocol (required when port specified)
if [ "${3}" = "tcp" ] || [ "${3}" = "udp" ]; then
# print protocol directly
PROTOS="${3}"
elif [ "${#4}" -gt "1" ] || [ "${#5}" -gt "1" ]; then
# proto=both & ports are defined
PROTOS="tcp>udp" # separated by > because IFS will be temporarily set to '>' by calling function. TODO Fix Me
else
# neither proto nor ports defined
PROTOS="all"
fi
# local port
if echo "${4}" | Is_Valid_Port; then
# Use multiport to specify any port specification:
# single port, multiple ports, port range
DOWN_Lport="-m multiport $(echo "${4}" | sed -E 's/^([!])?/\1 --dports /')"
UP_Lport="-m multiport $(echo "${4}" | sed -E 's/^([!])?/\1 --sports /')"
else
DOWN_Lport=""
UP_Lport=""
fi
# remote port
if echo "${5}" | Is_Valid_Port; then
# Use multiport to specify any port specification:
# single port, multiple ports, port range
DOWN_Rport="-m multiport $(echo "${5}" | sed -E 's/^([!])?/\1 --sports /')"
UP_Rport="-m multiport $(echo "${5}" | sed -E 's/^([!])?/\1 --dports /')"
else
DOWN_Rport=""
UP_Rport=""
fi
# mark
if echo "${6}" | Is_Valid_Mark; then
tmpMark="${6}" # Use a tmp variable since we have to manipulate the contents for ! and ****
DOWN_mark="-m mark"
UP_mark="-m mark"
if [ "$(echo "${tmpMark}" | cut -c 1)" = "!" ]; then # first char is !
DOWN_mark="${DOWN_mark} !"
UP_mark="${UP_mark} !"
tmpMark="$(echo "${tmpMark}" | sed -E 's/^!//')" # strip the !
fi
# Extract category and appid from mark
cat="$(echo "${tmpMark}" | cut -c 1-2)"
id="$(echo "${tmpMark}" | cut -c 3-6)"
# check if wildcard mark
if [ "${id}" = "****" ]; then
# replace **** with 0000 and use category mask
DOWN_mark="${DOWN_mark} --mark 0x80${cat}0000/0xc03f0000"
UP_mark="${UP_mark} --mark 0x40${cat}0000/0xc03f0000"
else
DOWN_mark="${DOWN_mark} --mark 0x80${tmpMark}/0xc03fffff"
UP_mark="${UP_mark} --mark 0x40${tmpMark}/0xc03fffff"
fi
else
DOWN_mark=""
UP_mark=""
fi
# if all parameters are empty stop processing the rule
if [ -z "${DOWN_Lip}${DOWN_Rip}${DOWN_Lport}${DOWN_Rport}${DOWN_mark}" ]; then
return
fi
# destination mark
# numbers come from webui select options for class field
Dst_mark="$(get_class_mark "${7}")"
if [ -z "${Dst_mark}" ]; then
return
fi
DOWN_dst="-j MARK --set-mark 0x80${Dst_mark}ffff/0xc03fffff"
UP_dst="-j MARK --set-mark 0x40${Dst_mark}ffff/0xc03fffff"
# This block is redirected to the /tmp/flexqos_iprules file, so no extraneous output, please
# If proto=both we have to create 2 statements, one for tcp and one for udp.
for proto in ${PROTOS}; do
# download ipv4
printf "iptables -t mangle -A %s %s %s -p %s %s %s %s %s\n" "${SCRIPTNAME_DISPLAY}_down" "${DOWN_Lip}" "${DOWN_Rip}" "${proto}" "${DOWN_Lport}" "${DOWN_Rport}" "${DOWN_mark}" "${DOWN_dst}"
# upload ipv4
printf "iptables -t mangle -A %s %s %s -p %s %s %s %s %s\n" "${SCRIPTNAME_DISPLAY}_up" "${UP_Lip}" "${UP_Rip}" "${proto}" "${UP_Lport}" "${UP_Rport}" "${UP_mark}" "${UP_dst}"
# If rule contains no IPv4 remote addresses, and IPv6 is enabled, add a corresponding rule for IPv6
if [ "${IPv6_enabled}" != "disabled" ] && [ -z "${DOWN_Rip}" ]; then
# download ipv6
printf "ip6tables -t mangle -A %s %s -p %s %s %s %s %s\n" "${SCRIPTNAME_DISPLAY}_down" "${DOWN_Lip6}" "${proto}" "${DOWN_Lport}" "${DOWN_Rport}" "${DOWN_mark}" "${DOWN_dst}"
# upload ipv6
printf "ip6tables -t mangle -A %s %s -p %s %s %s %s %s\n" "${SCRIPTNAME_DISPLAY}_up" "${UP_Lip6}" "${proto}" "${UP_Lport}" "${UP_Rport}" "${UP_mark}" "${UP_dst}"
fi
done
} # parse_iptablerule
about() {
scriptinfo
cat <<EOF
License
${SCRIPTNAME_DISPLAY} is free to use under the GNU General Public License, version 3 (GPL-3.0).
https://opensource.org/licenses/GPL-3.0
For discussion visit this thread:
https://www.snbforums.com/forums/asuswrt-merlin-addons.60/?prefix_id=8
https://github.com/dave14305/FlexQoS (Source Code)
About
Script Changes Unidentified traffic destination away from Work-From-Home into Others
Script Changes HTTPS traffic destination away from Net Control into Web Surfing
Script Changes Guaranteed Bandwidth per QoS category into logical percentages of upload and download.
Script includes misc default rules
(Wifi Calling) - UDP traffic on remote ports 500 & 4500 moved into Work-From-Home
(Facetime) - UDP traffic on local ports 16384 - 16415 moved into Work-From-Home
(Usenet) - TCP traffic on remote ports 119 & 563 moved into File Transfers
(Gaming) - Gaming TCP traffic from remote ports 80 & 443 moved into File Transfers.
(Snapchat) - Moved into Others
(Speedtest.net) - Moved into File Transfers
(Google Play) - Moved into File Transfers
(Apple AppStore)- Moved into File Transfers
(VPN Fix) - Router VPN Client upload traffic moved into File Transfers instead of whitelisted
(Gaming Manual) - Unidentified traffic for specified devices, not originating from ports 80/443, moved into Gaming
Gaming Rule Note
Gaming traffic originating from ports 80 & 443 is primarily downloads & patches (some lobby/login protocols mixed within)
Manually configurable rule will take untracked traffic for specified devices, not originating from server ports 80/443, and place it into Gaming
Use of this gaming rule REQUIRES devices to have a continuous static ip assignment & this range needs to be passed into the script
EOF
}
backup() {
# Backup existing user rules in /jffs/addons/custom_settings.txt
# Input: create [force]|restore|remove
case "${1}" in
'create')
if [ "${2}" != "force" ] && [ -f "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh" ]; then
grep "# Backup date" "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
printf "A backup already exists. Do you want to overwrite this backup? [1=Yes 2=No]: "
read -r yn
if [ "${yn}" != "1" ]; then
Yellow "Backup cancelled."
return
fi
fi
printf "Running backup...\n"
{
printf "#!/bin/sh\n"
printf "# Backup date: %s\n" "$(date +'%Y-%m-%d %H:%M:%S%z')"
printf ". /usr/sbin/helper.sh\n"
[ -n "$(am_settings_get "${SCRIPTNAME}"_iptables)" ] && printf "am_settings_set %s_iptables \"%s\"\n" "${SCRIPTNAME}" "$(am_settings_get "${SCRIPTNAME}"_iptables)"
[ -n "$(am_settings_get "${SCRIPTNAME}"_iptables_names)" ] && printf "am_settings_set %s_iptables_names \"%s\"\n" "${SCRIPTNAME}" "$(am_settings_get "${SCRIPTNAME}"_iptables_names)"
[ -n "$(am_settings_get "${SCRIPTNAME}"_appdb)" ] && printf "am_settings_set %s_appdb \"%s\"\n" "${SCRIPTNAME}" "$(am_settings_get "${SCRIPTNAME}"_appdb)"
[ -n "$(am_settings_get "${SCRIPTNAME}"_bwrates)" ] && printf "am_settings_set %s_bwrates \"%s\"\n" "${SCRIPTNAME}" "$(am_settings_get "${SCRIPTNAME}"_bwrates)"
[ -n "$(am_settings_get "${SCRIPTNAME}"_qdisc)" ] && printf "am_settings_set %s_qdisc \"%s\"\n" "${SCRIPTNAME}" "$(am_settings_get "${SCRIPTNAME}"_qdisc)"
} > "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
if /bin/grep -q "${SCRIPTNAME}_" "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"; then
Green "Backup done to ${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
else
rm "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
Yellow "Backup cancelled. All settings using default values."
fi
;;
'restore')
if [ -f "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh" ]; then
Yellow "$(grep "# Backup date" "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh")"
printf "Do you want to restore this backup? [1=Yes 2=No]: "
read -r yn
if [ "${yn}" = "1" ]; then
sh "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
Green "Backup restored!"
needrestart=1
else
Yellow "Restore cancelled."
fi
else
Red "No backup file exists!"
fi
;;
'remove')
[ -f "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh" ] && rm "${ADDON_DIR}/restore_${SCRIPTNAME}_settings.sh"
Green "Backup deleted."
;;
esac
} # backup
download_file() {
# Download file from Github once to a temp location. If the same as the destination file, don't replace.
# Otherwise move it from the temp location to the destination.
if curl -fsL --retry 3 --connect-timeout 3 "${GIT_URL}/${1}" -o "/tmp/${1}"; then
if [ "$(md5sum "/tmp/${1}" | awk '{print $1}')" != "$(md5sum "${2}" 2>/dev/null | awk '{print $1}')" ]; then