Repository navigation
Expand file tree
/
Copy pathcharon.sh
More file actions
executable file
·509 lines (456 loc) · 15.9 KB
/
Copy pathcharon.sh
File metadata and controls
executable file
·509 lines (456 loc) · 15.9 KB
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
#!/usr/bin/env bash
#
# charon.sh - Charon temporary bandwidth control for Linux.
#
# Uses Linux Traffic Control (tc) to limit both egress and ingress bandwidth.
# It stays in the foreground and removes only the rules it created when it
# exits or is interrupted.
#
# Usage: sudo ./charon.sh <interface> <limit>
# Example: sudo ./charon.sh enp5s0 1mbit
#
set -u
# Root runs should not inherit command lookup or locale behavior from the
# invoking shell. The listed paths cover the standard locations on Linux.
PATH='/usr/sbin:/usr/bin:/sbin:/bin'
LC_ALL=C
export PATH LC_ALL
INTERFACE=""
LIMIT=""
ROOT_MAY_EXIST=false
INGRESS_MAY_EXIST=false
INGRESS_FILTER_MAY_EXIST=false
RULES_APPLIED=false
RULE_REMOVED=false
LOCK_OWNED=false
STARTUP_LOCK_OWNED=false
CLEANED_UP=false
SETUP_STATE="initial"
TC=""
IP=""
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'
print_banner() {
printf '%b\n' "${BLUE}====================================================${NC}"
printf '%b\n' "${BLUE} Charon for Linux ${NC}"
printf '%b\n' "${BLUE}====================================================${NC}"
}
print_available_interfaces() {
printf '%b\n' "${CYAN}Available network interfaces on this machine:${NC}"
if [ -n "$IP" ] && [ -x "$IP" ]; then
"$IP" -br link show 2>/dev/null | awk '{ sub(/@.*/, "", $1); print " - " $1 }'
elif command -v ip >/dev/null 2>&1; then
ip -br link show 2>/dev/null | awk '{ sub(/@.*/, "", $1); print " - " $1 }'
elif [ -d /sys/class/net ]; then
find /sys/class/net -mindepth 1 -maxdepth 1 -printf ' - %f\n' 2>/dev/null | sort
else
printf ' (unable to list interfaces)\n'
fi
}
usage() {
print_banner
printf 'Usage: sudo %s <interface> <limit>\n' "$0"
printf 'Example: sudo %s enp5s0 1mbit\n\n' "$0"
print_available_interfaces
}
process_start_time() {
local pid stat
pid="$1"
if [[ "$pid" =~ ^[0-9]+$ ]] && [ -r "/proc/$pid/stat" ]; then
IFS= read -r stat < "/proc/$pid/stat" || return
stat="${stat##*) }"
awk 'NF >= 20 { print $20 }' <<< "$stat"
fi
}
lock_field() {
sed -n "${2}p" "$1" 2>/dev/null || true
}
write_lock() {
local tmp
tmp="${LOCKFILE}.tmp.$$"
if ! {
printf '%s\n' "$$"
printf '%s\n' "$PROCESS_START"
printf '%s\n' "$ROOT_MAJOR"
printf '%s\n' "$SETUP_STATE"
} > "$tmp" || ! mv -f "$tmp" "$LOCKFILE"; then
rm -f "$tmp"
return 1
fi
}
release_startup_lock() {
local owner start
rm -f "$STARTUP_CANDIDATE"
if [ "$STARTUP_LOCK_OWNED" != true ]; then
return
fi
if [ -f "$STARTUP_LOCK" ]; then
owner=$(lock_field "$STARTUP_LOCK" 1)
start=$(lock_field "$STARTUP_LOCK" 2)
if [ "$owner" = "$$" ] && [ "$start" = "$PROCESS_START" ]; then
rm -f "$STARTUP_LOCK"
fi
fi
STARTUP_LOCK_OWNED=false
}
acquire_startup_lock() {
local attempts current owner start
attempts=0
if ! printf '%s\n%s\n' "$$" "$PROCESS_START" > "$STARTUP_CANDIDATE"; then
return 1
fi
while ! ln "$STARTUP_CANDIDATE" "$STARTUP_LOCK" 2>/dev/null; do
owner=$(lock_field "$STARTUP_LOCK" 1)
start=$(lock_field "$STARTUP_LOCK" 2)
current=$(process_start_time "$owner")
if [ -z "$start" ] || [ "$start" != "$current" ]; then
rm -f "$STARTUP_LOCK"
else
sleep 0.05
fi
attempts=$((attempts + 1))
if [ "$attempts" -ge 200 ]; then
rm -f "$STARTUP_CANDIDATE"
return 1
fi
done
STARTUP_LOCK_OWNED=true
rm -f "$STARTUP_CANDIDATE"
return 0
}
remove_own_lock() {
local owner start
if [ "$LOCK_OWNED" != true ] || [ ! -f "$LOCKFILE" ]; then
return
fi
owner=$(lock_field "$LOCKFILE" 1)
start=$(lock_field "$LOCKFILE" 2)
if [ "$owner" = "$$" ] && [ "$start" = "$PROCESS_START" ]; then
rm -f "$LOCKFILE"
fi
}
root_is_ours() {
local qdiscs
if ! qdiscs=$("$TC" qdisc show dev "$INTERFACE" 2>/dev/null); then
return 2
fi
awk -v handle="${ROOT_MAJOR}:" '
$1 == "qdisc" && $2 == "tbf" && $3 == handle && $0 ~ / root([[:space:]]|$)/ { found = 1 }
END { exit !found }
' <<< "$qdiscs"
}
ingress_is_ours() {
local qdiscs
if ! qdiscs=$("$TC" qdisc show dev "$INTERFACE" 2>/dev/null); then
return 2
fi
awk '
$1 == "qdisc" && $2 == "ingress" && $3 == "ffff:" { found = 1 }
END { exit !found }
' <<< "$qdiscs"
}
ingress_filter_is_ours() {
local filters
if ! filters=$("$TC" filter show dev "$INTERFACE" parent ffff: 2>/dev/null); then
return 2
fi
awk -v pref="$FILTER_PREF" '
$0 ~ (" pref " pref " ") { found = 1 }
END { exit !found }
' <<< "$filters"
}
remove_owned_rules() {
local filters status
RULE_REMOVED=false
if [ "$INGRESS_MAY_EXIST" = true ]; then
ingress_is_ours
status=$?
if [ "$status" -eq 2 ]; then
return 1
fi
if [ "$status" -eq 0 ]; then
if [ "$INGRESS_FILTER_MAY_EXIST" = true ]; then
ingress_filter_is_ours
status=$?
if [ "$status" -eq 2 ]; then
return 1
fi
if [ "$status" -eq 0 ]; then
if ! "$TC" filter del dev "$INTERFACE" parent ffff: protocol all pref "$FILTER_PREF" 2>/dev/null; then
return 1
fi
RULE_REMOVED=true
fi
fi
# Keep a shared ingress qdisc if another tool has attached filters.
if ! filters=$("$TC" filter show dev "$INTERFACE" parent ffff: 2>/dev/null); then
return 1
fi
if [ -z "$filters" ]; then
if ! "$TC" qdisc del dev "$INTERFACE" ingress 2>/dev/null; then
return 1
fi
RULE_REMOVED=true
fi
fi
fi
if [ "$ROOT_MAY_EXIST" = true ]; then
root_is_ours
status=$?
if [ "$status" -eq 2 ]; then
return 1
fi
if [ "$status" -eq 0 ]; then
if ! "$TC" qdisc del dev "$INTERFACE" root 2>/dev/null; then
return 1
fi
RULE_REMOVED=true
fi
fi
return 0
}
cleanup_stale_instance() {
local configured_major old_major old_state
configured_major="$ROOT_MAJOR"
old_major=$(lock_field "$LOCKFILE" 3)
old_state=$(lock_field "$LOCKFILE" 4)
if [[ "$old_major" =~ ^[0-9a-fA-F]+$ ]]; then
ROOT_MAJOR="$old_major"
case "$old_state" in
root_pending|ingress_pending|filter_pending|active)
ROOT_MAY_EXIST=true
;;
esac
case "$old_state" in
ingress_pending|filter_pending|active)
INGRESS_MAY_EXIST=true
;;
esac
if [ "$old_state" = filter_pending ] || [ "$old_state" = active ]; then
INGRESS_FILTER_MAY_EXIST=true
fi
if ! remove_owned_rules; then
return 1
fi
fi
rm -f "$LOCKFILE"
ROOT_MAJOR="$configured_major"
ROOT_MAY_EXIST=false
INGRESS_MAY_EXIST=false
INGRESS_FILTER_MAY_EXIST=false
}
cleanup() {
local exit_code="$?"
local cleanup_ok
if [ "$CLEANED_UP" = true ]; then
return
fi
CLEANED_UP=true
trap - EXIT HUP INT TERM
if [ "$RULES_APPLIED" = true ]; then
printf '\n%b[*] Cleanup triggered. Restoring normal bandwidth on %s...%b\n' "$YELLOW" "$INTERFACE" "$NC"
fi
cleanup_ok=false
if remove_owned_rules; then
cleanup_ok=true
fi
rm -f "${LOCKFILE}.tmp.$$"
release_startup_lock
if [ "$cleanup_ok" = true ]; then
remove_own_lock
else
printf '%b[!] Error: Cleanup could not confirm that all Charon rules were removed.%b\n' "$RED" "$NC" >&2
printf 'Recovery state was kept in %s for the next run.\n' "$LOCKFILE" >&2
if [ "$exit_code" -eq 0 ]; then
exit_code=1
fi
fi
if [ "$RULES_APPLIED" = true ]; then
if [ "$cleanup_ok" = true ]; then
if [ "$RULE_REMOVED" = true ]; then
printf '%b[+] Successfully removed Charon bandwidth rules from '\''%s'\''.%b\n' "$GREEN" "$INTERFACE" "$NC"
else
printf '%b[+] Interface '\''%s'\'' is already clear or was changed externally.%b\n' "$GREEN" "$INTERFACE" "$NC"
fi
printf '%b[+] System bandwidth returned to its normal state.%b\n' "$GREEN" "$NC"
fi
fi
exit "$exit_code"
}
if [ "$#" -eq 1 ] && { [ "$1" = "-h" ] || [ "$1" = "--help" ]; }; then
usage
exit 0
fi
if [ "$#" -ne 2 ]; then
usage >&2
exit 2
fi
if [ "$(uname -s)" != "Linux" ]; then
print_banner
printf '%b\n' "${RED}[!] Error: This version is for Linux only.${NC}" >&2
exit 1
fi
if [ "$EUID" -ne 0 ]; then
print_banner
printf '%b\n' "${RED}[!] Error: This script must be run with root privileges (sudo).${NC}" >&2
printf 'Usage: sudo %s <interface> <limit>\n' "$0" >&2
printf 'Example: sudo %s enp5s0 1mbit\n\n' "$0" >&2
exit 1
fi
TC=$(command -v tc 2>/dev/null || true)
IP=$(command -v ip 2>/dev/null || true)
if [ -z "$TC" ] || [ -z "$IP" ]; then
print_banner
printf '%b\n' "${RED}[!] Error: Linux traffic-control utilities 'tc' and 'ip' were not found.${NC}" >&2
printf '%s\n' "Install the iproute2 package for your distribution." >&2
exit 1
fi
INTERFACE="$1"
LIMIT="$2"
if [[ "$INTERFACE" == *$'\n'* ]] || ! "$IP" link show dev "$INTERFACE" >/dev/null 2>&1; then
print_banner
printf '%b[!] Error: Network interface '\''%s'\'' does not exist.%b\n' "$RED" "$INTERFACE" "$NC" >&2
print_available_interfaces >&2
exit 1
fi
# Accept tc's common rate spellings and the cross-platform /s suffix while
# rejecting empty, zero, negative, or malformed values before touching state.
LOWER_LIMIT=$(printf '%s' "$LIMIT" | tr '[:upper:]' '[:lower:]')
if [[ ! "$LOWER_LIMIT" =~ ^([0-9]+([.][0-9]+)?)([kmgt]?)(bit(/s)?|bps)$ ]] || \
! awk -v n="${BASH_REMATCH[1]:-0}" 'BEGIN { exit !(n > 0) }'; then
print_banner
printf '%b[!] Error: Invalid bandwidth limit '\''%s'\''.%b\n' "$RED" "$LIMIT" "$NC" >&2
printf '%s\n' "Use a positive value such as 1mbit, 500kbit, or 10gbit." >&2
exit 1
fi
TC_LIMIT="${LOWER_LIMIT%/s}"
INTERFACE_HASH=$(printf '%s' "$INTERFACE" | cksum | awk '{ print $1 }')
SAFE_INTERFACE=$(printf '%s' "$INTERFACE" | tr -c 'A-Za-z0-9_' '_')
ROOT_MAJOR=$(printf '%x' $((0x1000 + (INTERFACE_HASH % 0xd000))))
FILTER_PREF=$((1000 + (INTERFACE_HASH % 30000)))
LOCKFILE="/run/charon_${SAFE_INTERFACE}_${INTERFACE_HASH}.lock"
STARTUP_LOCK="${LOCKFILE}.startup"
STARTUP_CANDIDATE="${STARTUP_LOCK}.$$.candidate"
PROCESS_START=$(process_start_time "$$")
if [ -z "$PROCESS_START" ]; then
print_banner
printf '%b\n' "${RED}[!] Error: Could not read this process's Linux start-time identity.${NC}" >&2
exit 1
fi
umask 077
trap cleanup EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
if ! acquire_startup_lock; then
print_banner
printf '%b[!] Error: Timed out waiting for another Charon startup on %s.%b\n' "$RED" "$INTERFACE" "$NC" >&2
exit 1
fi
# Recover only state positively identified as ours after an ungraceful exit.
if [ -f "$LOCKFILE" ]; then
LOCK_PID=$(lock_field "$LOCKFILE" 1)
LOCK_START=$(lock_field "$LOCKFILE" 2)
CURRENT_START=$(process_start_time "$LOCK_PID")
if [ -n "$LOCK_START" ] && [ "$LOCK_START" = "$CURRENT_START" ]; then
print_banner
printf '%b[!] Error: Another limiter instance (PID %s) is already managing %s.%b\n' "$RED" "$LOCK_PID" "$INTERFACE" "$NC" >&2
printf '%s\n' "Stop it before applying a new limit." >&2
exit 1
fi
if ! cleanup_stale_instance; then
print_banner
printf '%b[!] Error: Charon could not safely recover stale state for '\''%s'\''.%b\n' "$RED" "$INTERFACE" "$NC" >&2
printf 'The recovery journal was kept at %s.\n' "$LOCKFILE" >&2
exit 1
fi
fi
# The startup lock protects this atomic creation and the complete record write.
if ! (set -o noclobber; printf '%s\n%s\n%s\n%s\n' \
"$$" "$PROCESS_START" "$ROOT_MAJOR" "$SETUP_STATE" > "$LOCKFILE") 2>/dev/null; then
print_banner
printf '%b[!] Error: Another limiter started managing %s at the same time.%b\n' "$RED" "$INTERFACE" "$NC" >&2
exit 1
fi
LOCK_OWNED=true
release_startup_lock
# Qdiscs with handle 0: are implicit kernel/driver state. Removing our TBF
# causes Linux to recreate that default hierarchy. Any nonzero egress handle
# may carry user-managed parameters that cannot be reconstructed exactly.
# Ingress and clsact qdiscs are never implicit defaults.
if ! QDISC_STATE=$("$TC" qdisc show dev "$INTERFACE" 2>/dev/null); then
print_banner
printf '%b[!] Error: Could not inspect existing traffic-control state on '\''%s'\''.%b\n' "$RED" "$INTERFACE" "$NC" >&2
exit 1
fi
ROOT_CONFLICT=$(awk '
$1 == "qdisc" && $2 != "ingress" && $2 != "clsact" && $3 != "0:" { print; exit }
' <<< "$QDISC_STATE")
INGRESS_CONFLICT=$(awk '
$1 == "qdisc" && ($2 == "ingress" || $2 == "clsact") { print; exit }
' <<< "$QDISC_STATE")
if [ -n "$ROOT_CONFLICT" ] || [ -n "$INGRESS_CONFLICT" ]; then
print_banner
printf '%b[!] Error: '\''%s'\'' already has custom traffic-control state.%b\n' "$RED" "$INTERFACE" "$NC" >&2
[ -n "$ROOT_CONFLICT" ] && printf ' Egress: %s\n' "$ROOT_CONFLICT" >&2
[ -n "$INGRESS_CONFLICT" ] && printf ' Ingress: %s\n' "$INGRESS_CONFLICT" >&2
printf '%s\n' "Refusing to overwrite rules that this script would be unable to restore exactly." >&2
exit 1
fi
printf '%b[*] Configuring traffic control on interface '\''%s'\''...%b\n' "$YELLOW" "$INTERFACE" "$NC"
# Mark each object as potentially present before creating it, closing the small
# signal window between a successful tc command and its corresponding state flag.
SETUP_STATE="root_pending"
if ! write_lock; then
printf '%b\n' "${RED}[!] Error: Could not journal egress setup state.${NC}" >&2
exit 1
fi
ROOT_MAY_EXIST=true
if ! "$TC" qdisc add dev "$INTERFACE" root handle "${ROOT_MAJOR}:" \
tbf rate "$TC_LIMIT" burst 32kb latency 400ms; then
printf '%b\n' "${RED}[!] Error: Failed to apply egress traffic-control rules.${NC}" >&2
printf "Verify that bandwidth limit '%s' is valid for tc.\n" "$LIMIT" >&2
exit 1
fi
SETUP_STATE="ingress_pending"
if ! write_lock; then
printf '%b\n' "${RED}[!] Error: Could not journal ingress setup state.${NC}" >&2
exit 1
fi
INGRESS_MAY_EXIST=true
if ! "$TC" qdisc add dev "$INTERFACE" handle ffff: ingress; then
printf '%b\n' "${RED}[!] Error: Failed to create the ingress qdisc.${NC}" >&2
exit 1
fi
SETUP_STATE="filter_pending"
if ! write_lock; then
printf '%b\n' "${RED}[!] Error: Could not journal ingress-filter setup state.${NC}" >&2
exit 1
fi
INGRESS_FILTER_MAY_EXIST=true
if ! "$TC" filter add dev "$INTERFACE" parent ffff: protocol all pref "$FILTER_PREF" \
u32 match u32 0 0 police rate "$TC_LIMIT" burst 100k drop flowid :1; then
printf '%b\n' "${RED}[!] Error: Failed to apply ingress policing rules.${NC}" >&2
exit 1
fi
SETUP_STATE="active"
if ! write_lock; then
printf '%b\n' "${RED}[!] Error: Could not record limiter state for safe cleanup.${NC}" >&2
exit 1
fi
RULES_APPLIED=true
print_banner
printf '%b\n' "${GREEN}[+] CHARON IS NOW ACTIVE${NC}"
printf '%b %s\n' "${GREEN}[+] Target Interface :${NC}" "$INTERFACE"
printf '%b %s\n' "${GREEN}[+] Ingress Limit :${NC}" "$LIMIT"
printf '%b %s\n' "${GREEN}[+] Egress Limit :${NC}" "$LIMIT"
printf '%b\n' "\n${CYAN}[i] This script is running in the foreground to maintain the limit.${NC}"
printf '%b\n' "${YELLOW}[!] PRESS [Ctrl+C] or terminate this process to restore normal speed.${NC}"
printf '%b\n' "${BLUE}====================================================${NC}"
while true; do
sleep 1
done