-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnetshare.sh
More file actions
executable file
·1289 lines (1117 loc) · 52.3 KB
/
netshare.sh
File metadata and controls
executable file
·1289 lines (1117 loc) · 52.3 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
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
#!/usr/bin/env bash
# netshare — Dynamic Network Sharing Manager
# Manages internet sharing (NAT + DHCP) between network interfaces.
# Profiles saved to ~/.config/netshare/profiles/
# Active state tracked in /var/run/netshare/
set -euo pipefail
# ── Paths ──────────────────────────────────────────────────────────────────────
PROFILE_DIR="${HOME}/.config/netshare/profiles"
STATE_DIR="/var/run/netshare"
DNSMASQ_DIR="/etc/dnsmasq.d"
DNSMASQ_PREFIX="netshare-"
NM_CONF_DIR="/etc/NetworkManager/conf.d"
# ── Colours ────────────────────────────────────────────────────────────────────
if [[ -t 1 ]]; then
RED=$'\033[0;31m'; GREEN=$'\033[0;32m'; YELLOW=$'\033[1;33m'
CYAN=$'\033[0;36m'; BOLD=$'\033[1m'; DIM=$'\033[2m'; RESET=$'\033[0m'
TICK="${GREEN}✓${RESET}"; CROSS="${RED}✗${RESET}"
ARROW="${CYAN}→${RESET}"; DOT="${DIM}·${RESET}"
else
RED=''; GREEN=''; YELLOW=''; CYAN=''; BOLD=''; DIM=''; RESET=''
TICK='[OK]'; CROSS='[ERR]'; ARROW='-->'; DOT=' -'
fi
ok() { echo -e "${TICK} $*"; }
err() { echo -e "${CROSS} $*" >&2; }
info() { echo -e "${ARROW} $*"; }
warn() { echo -e "${YELLOW}!${RESET} $*"; }
step() { echo -e "${DOT} $*"; }
die() { err "$*"; exit 1; }
hr() { printf "${DIM}%s${RESET}\n" "$(printf '─%.0s' {1..60})"; }
hdr() { echo; echo -e "${BOLD}${CYAN}$*${RESET}"; hr; }
# ── Root handling ──────────────────────────────────────────────────────────────
# Call as: ensure_root <original args...>
# Re-execs the whole script with sudo, preserving the command and args.
ensure_root() {
[[ $EUID -eq 0 ]] && return
info "Re-running with sudo..."
exec sudo -E bash "$0" "$@"
}
# ── Orphan cleanup ─────────────────────────────────────────────────────────────
# /var/run is tmpfs — wiped on reboot. NM conf.d and dnsmasq configs persist.
# On any invocation, clean up leftover files that have no matching state file.
cleanup_orphans() {
[[ $EUID -ne 0 ]] && return # only when root
# Orphaned dnsmasq configs
for f in "${DNSMASQ_DIR}/${DNSMASQ_PREFIX}"*.conf; do
[[ -f "$f" ]] || continue
local pname; pname=$(basename "${f%.conf}")
pname="${pname#${DNSMASQ_PREFIX}}"
if [[ ! -f "$(state_file "$pname")" ]]; then
warn "Removing orphaned dnsmasq config: ${f} (no active state — likely left from reboot)"
rm -f "$f"
if systemctl list-unit-files dnsmasq.service 2>/dev/null | grep -q dnsmasq; then
systemctl restart dnsmasq &>/dev/null || true
else
pkill -x dnsmasq 2>/dev/null || true
fi
fi
done
# Orphaned NetworkManager unmanaged configs
for f in "${NM_CONF_DIR}"/netshare-*-unmanaged.conf; do
[[ -f "$f" ]] || continue
# Extract interface name from filename: netshare-<iface>-unmanaged.conf
local bname; bname=$(basename "$f")
local iface; iface="${bname#netshare-}"; iface="${iface%-unmanaged.conf}"
# Check if any active state references this interface as downstream
local found=false
for sf in "${STATE_DIR}"/*.conf; do
[[ -f "$sf" ]] || continue
grep -q "^DOWNSTREAM=${iface}$" "$sf" 2>/dev/null && found=true && break
done
if ! "$found"; then
warn "Removing orphaned NM unmanaged config: ${f} (restoring ${iface} to NetworkManager)"
rm -f "$f"
nm_running && nmcli general reload &>/dev/null || true
fi
done
}
# ── Prompting helpers ──────────────────────────────────────────────────────────
# ask_input <var_name> <prompt> [default]
ask_input() {
local _var="$1" _prompt="$2" _default="${3-}"
local _display_prompt
if [[ -n "$_default" ]]; then
_display_prompt="${BOLD}${_prompt}${RESET} [${DIM}${_default}${RESET}]: "
else
_display_prompt="${BOLD}${_prompt}${RESET}: "
fi
while true; do
printf "%b" "$_display_prompt"
local _val=""
IFS= read -r _val || true
_val="${_val:-$_default}"
if [[ -z "$_val" && -z "$_default" ]]; then
warn "Value required."
continue
fi
printf -v "$_var" '%s' "$_val"
return
done
}
# ask_input_optional <var_name> <prompt> — empty answer is fine
ask_input_optional() {
local _var="$1" _prompt="$2"
printf "%b" "${BOLD}${_prompt}${RESET} ${DIM}(press Enter to skip)${RESET}: "
local _val=""
IFS= read -r _val || true
printf -v "$_var" '%s' "$_val"
}
# ask_yn <prompt> [y|n] → returns 0 for yes, 1 for no
ask_yn() {
local _prompt="$1" _default="${2:-y}"
local _hint
[[ "$_default" == "y" ]] && _hint="Y/n" || _hint="y/N"
while true; do
printf "%b" "${BOLD}${_prompt}${RESET} [${_hint}]: "
local _ans; IFS= read -r _ans
_ans="${_ans:-$_default}"
case "${_ans,,}" in
y|yes) return 0 ;;
n|no) return 1 ;;
*) warn "Please enter y or n." ;;
esac
done
}
# ask_menu <var_name> <title> item1 item2 ...
# Displays numbered menu, puts chosen value into var_name
ask_menu() {
local _var="$1"; shift
local _title="$1"; shift
local _items=("$@")
local _n=${#_items[@]}
echo
echo -e "${BOLD}${_title}${RESET}"
hr
local i
for (( i=0; i<_n; i++ )); do
printf " ${CYAN}%2d)${RESET} %s\n" $(( i+1 )) "${_items[$i]}"
done
hr
while true; do
printf "%b" "${BOLD}Choose [1-${_n}]${RESET}: "
local _choice; IFS= read -r _choice
if [[ "$_choice" =~ ^[0-9]+$ ]] && (( _choice >= 1 && _choice <= _n )); then
printf -v "$_var" '%s' "${_items[$(( _choice-1 ))]}"
return
fi
warn "Enter a number between 1 and ${_n}."
done
}
# ── Validation ─────────────────────────────────────────────────────────────────
is_valid_cidr() {
# Basic CIDR check: x.x.x.x/y
[[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]{1,2}$ ]] || return 1
local _ip _pfx
_ip="${1%/*}"; _pfx="${1#*/}"
(( _pfx >= 0 && _pfx <= 32 )) || return 1
local _o
IFS='.' read -ra _o <<< "$_ip"
for _b in "${_o[@]}"; do (( _b >= 0 && _b <= 255 )) || return 1; done
return 0
}
is_valid_ip() {
[[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || return 1
local _o; IFS='.' read -ra _o <<< "$1"
for _b in "${_o[@]}"; do (( _b >= 0 && _b <= 255 )) || return 1; done
return 0
}
ask_cidr() {
local _var="$1" _prompt="$2" _default="${3-}"
while true; do
ask_input "$_var" "$_prompt" "$_default"
local _chk="${!_var}"
if is_valid_cidr "$_chk"; then
return
fi
warn "Not a valid CIDR (e.g. 10.11.11.0/24)"
done
}
ask_ip() {
local _var="$1" _prompt="$2" _default="${3-}"
while true; do
ask_input "$_var" "$_prompt" "$_default"
local _chk="${!_var}"
if is_valid_ip "$_chk"; then
return
fi
warn "Not a valid IP address."
done
}
# ── Interface detection ────────────────────────────────────────────────────────
get_interfaces() {
# Print: name|state|addresses|type
ip -o link show | awk -F': ' '{print $2}' | while read -r iface; do
[[ "$iface" == "lo" ]] && continue
[[ "$iface" =~ @ ]] && iface="${iface%%@*}" # strip @ifname suffix
local state addrs type
state=$(ip -o link show "$iface" 2>/dev/null | grep -oP 'state \K\S+' || echo "UNKNOWN")
addrs=$(ip -o -4 addr show "$iface" 2>/dev/null | awk '{print $4}' | paste -sd,)
[[ -z "$addrs" ]] && addrs="-"
# Guess type
case "$iface" in
wl*|wifi*|ath*|wlan*) type="wifi" ;;
eth*|en*|em*|eno*|enp*|enx*|ens*) type="ethernet" ;;
tun*|tap*) type="tunnel" ;;
br*) type="bridge" ;;
docker*|veth*) type="virtual" ;;
*) type="other" ;;
esac
echo "${iface}|${state}|${addrs}|${type}"
done
}
get_iface_names() {
get_interfaces | cut -d'|' -f1
}
get_default_route_iface() {
ip route show default 2>/dev/null | awk '/^default/ {print $5; exit}'
}
# strip_ansi <string> — returns string with ANSI escape codes removed
strip_ansi() { printf '%s' "$1" | sed 's/\[[0-9;]*m//g'; }
# pad <string> <width> — pad string to width, ignoring ANSI codes in length calc
pad() {
local str="$1" width="$2"
local visible; visible=$(strip_ansi "$str")
local pad=$(( width - ${#visible} ))
(( pad < 0 )) && pad=0
printf '%s%*s' "$str" "$pad" ''
}
print_iface_table() {
hdr "Network Interfaces"
local default_iface; default_iface=$(get_default_route_iface)
# Collect rows first so we can calculate column widths
local -a col_name col_type col_state col_addr
while IFS='|' read -r name state addrs type; do
local suffix=""
[[ "$name" == "$default_iface" ]] && suffix=" (default route)"
local state_col
if [[ "$state" == "UP" ]]; then state_col="${GREEN}UP${RESET}"
elif [[ "$state" == "DOWN" ]]; then state_col="${RED}DOWN${RESET}"
else state_col="${DIM}${state}${RESET}"; fi
col_name+=("${BOLD}${name}${RESET}${DIM}${suffix}${RESET}")
col_type+=("$type")
col_state+=("$state_col")
col_addr+=("${DIM}${addrs}${RESET}")
done < <(get_interfaces)
# Calculate max visible widths
local w_name=9 w_type=4 w_state=5 # minimums = header widths
for (( i=0; i<${#col_name[@]}; i++ )); do
local v; v=$(strip_ansi "${col_name[$i]}"); (( ${#v} > w_name )) && w_name=${#v}
v="${col_type[$i]}"; (( ${#v} > w_type )) && w_type=${#v}
v=$(strip_ansi "${col_state[$i]}"); (( ${#v} > w_state )) && w_state=${#v}
done
# Header
printf " ${BOLD}%-*s %-*s %-*s %s${RESET}\n" "$w_name" "INTERFACE" "$w_type" "TYPE" "$w_state" "STATE" "ADDRESSES"
hr
for (( i=0; i<${#col_name[@]}; i++ )); do
printf " %s %s %s %s\n" "$(pad "${col_name[$i]}" $w_name)" "$(pad "${col_type[$i]}" $w_type)" "$(pad "${col_state[$i]}" $w_state)" "${col_addr[$i]}"
done
hr
}
# ── Subnet helpers ─────────────────────────────────────────────────────────────
suggest_subnet() {
local candidates=("10.11.11.0/24" "10.42.0.0/24" "192.168.100.0/24" "172.20.0.0/24")
local existing; existing=$(ip route 2>/dev/null)
for c in "${candidates[@]}"; do
local net="${c%.*}" # e.g. 10.11.11
if ! echo "$existing" | grep -q "$net"; then
echo "$c"; return
fi
done
echo "10.11.11.0/24"
}
# Given x.x.x.0/24 → x.x.x.1
subnet_to_server_ip() {
local net="${1%/*}" # strip /prefix
echo "${net%.*}.1"
}
# Given x.x.x.0/24 → start=x.x.x.30 end=x.x.x.254
subnet_to_dhcp_range() {
local base="${1%.*}"
echo "${base}.30 ${base}.254"
}
# ── Package management ─────────────────────────────────────────────────────────
detect_pkg_manager() {
for pm in apt-get dnf yum pacman zypper; do
command -v "$pm" &>/dev/null && echo "$pm" && return
done
echo ""
}
install_packages() {
local pm; pm=$(detect_pkg_manager)
[[ -z "$pm" ]] && { err "No supported package manager found. Install manually: $*"; return 1; }
info "Installing packages via ${pm}: $*"
case "$pm" in
apt-get) apt-get install -y -qq "$@" ;;
dnf|yum) "$pm" install -y -q "$@" ;;
pacman) pacman -S --noconfirm --quiet "$@" ;;
zypper) zypper install -y "$@" ;;
esac
}
ensure_dnsmasq() {
command -v dnsmasq &>/dev/null && return 0
warn "dnsmasq not found."
ask_yn "Install dnsmasq now?" y || die "dnsmasq is required."
install_packages dnsmasq
}
ensure_iptables() {
command -v iptables &>/dev/null && return 0
warn "iptables not found."
install_packages iptables
}
# ── Firewall detection & handling ──────────────────────────────────────────────
detect_firewalls() {
# Sets globals: FW_UFW, FW_FIREWALLD
FW_UFW=false; FW_FIREWALLD=false
if command -v ufw &>/dev/null; then
ufw status 2>/dev/null | grep -qi "active" && FW_UFW=true
fi
if command -v firewall-cmd &>/dev/null; then
firewall-cmd --state &>/dev/null && FW_FIREWALLD=true
fi
}
configure_ufw() {
local downstream="$1" subnet="$2"
step "Configuring UFW..."
# Allow traffic from LAN
ufw allow in on "$downstream" from "$subnet" &>/dev/null || true
# Set DEFAULT_FORWARD_POLICY=ACCEPT
local ufw_default="/etc/default/ufw"
if [[ -f "$ufw_default" ]] && grep -q 'DEFAULT_FORWARD_POLICY="DROP"' "$ufw_default"; then
sed -i 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/' "$ufw_default"
ufw reload &>/dev/null || true
ok "UFW forward policy set to ACCEPT"
fi
}
teardown_ufw() {
local downstream="$1" subnet="$2"
ufw delete allow in on "$downstream" from "$subnet" &>/dev/null || true
}
configure_firewalld() {
local upstream="$1" downstream="$2"
step "Configuring firewalld..."
firewall-cmd --permanent --zone=external --add-interface="$upstream" &>/dev/null || true
firewall-cmd --permanent --zone=internal --add-interface="$downstream" &>/dev/null || true
firewall-cmd --permanent --zone=external --add-masquerade &>/dev/null || true
firewall-cmd --reload &>/dev/null || true
ok "firewalld zones configured"
}
teardown_firewalld() {
local upstream="$1" downstream="$2"
firewall-cmd --permanent --zone=external --remove-interface="$upstream" &>/dev/null || true
firewall-cmd --permanent --zone=internal --remove-interface="$downstream" &>/dev/null || true
firewall-cmd --permanent --zone=external --remove-masquerade &>/dev/null || true
firewall-cmd --reload &>/dev/null || true
}
# ── NetworkManager ─────────────────────────────────────────────────────────────
nm_running() {
systemctl is-active NetworkManager &>/dev/null
}
nm_set_unmanaged() {
local iface="$1"
nm_running || return 0
local conf="${NM_CONF_DIR}/netshare-${iface}-unmanaged.conf"
step "Setting ${iface} as unmanaged in NetworkManager..."
sudo mkdir -p "$NM_CONF_DIR"
printf '[keyfile]\nunmanaged-devices=interface-name:%s\n' "$iface" | sudo tee "$conf" > /dev/null
nmcli general reload &>/dev/null || true
sleep 1
ok "NetworkManager told to ignore ${iface}"
}
nm_restore() {
local iface="$1"
local conf="${NM_CONF_DIR}/netshare-${iface}-unmanaged.conf"
rm -f "$conf"
nm_running && nmcli general reload &>/dev/null || true
}
# ── State management ───────────────────────────────────────────────────────────
# State files are simple KEY=VALUE (bash-sourceable)
state_file() { echo "${STATE_DIR}/$1.conf"; }
save_state() {
local name="$1"; shift
mkdir -p "$STATE_DIR"
cat > "$(state_file "$name")" <<EOF
# netshare state — $name — $(date)
UPSTREAM=$1
DOWNSTREAM=$2
SUBNET=$3
SERVER_IP=$4
NM_UNMANAGED=$5
UFW_ACTIVE=$6
FIREWALLD_ACTIVE=$7
IP_FWD_WAS=$8
DNSMASQ_CONF=$9
STARTED_AT="$(date '+%Y-%m-%d %H:%M:%S')"
EOF
}
load_state() {
local sf; sf=$(state_file "$1")
[[ -f "$sf" ]] || return 1
# shellcheck source=/dev/null
source "$sf"
}
remove_state() {
rm -f "$(state_file "$1")"
}
get_active_profiles() {
[[ -d "$STATE_DIR" ]] || return
for f in "${STATE_DIR}"/*.conf; do
[[ -f "$f" ]] && basename "${f%.conf}"
done
}
# ── Profile management ─────────────────────────────────────────────────────────
# Profiles are also bash-sourceable KEY=VALUE files
profile_file() { echo "${PROFILE_DIR}/$1.conf"; }
save_profile() {
local name="$1"
mkdir -p "$PROFILE_DIR"
cat > "$(profile_file "$name")" <<EOF
# netshare profile — $name
# Created: $(date '+%Y-%m-%d %H:%M:%S')
UPSTREAM=${NS_UPSTREAM}
DOWNSTREAM=${NS_DOWNSTREAM}
SUBNET=${NS_SUBNET}
SERVER_IP=${NS_SERVER_IP}
DHCP_START=${NS_DHCP_START}
DHCP_END=${NS_DHCP_END}
LEASE_TIME=${NS_LEASE_TIME}
DNS_SERVERS=${NS_DNS_SERVERS}
EXTRA_OPTS=${NS_EXTRA_OPTS}
UPDATED_AT="$(date '+%Y-%m-%d %H:%M:%S')"
EOF
ok "Profile '${name}' saved → $(profile_file "$name")"
}
load_profile() {
local pf; pf=$(profile_file "$1")
[[ -f "$pf" ]] || { err "Profile '$1' not found."; return 1; }
source "$pf"
# Map to NS_ vars (profiles store without prefix for readability)
NS_UPSTREAM="$UPSTREAM"
NS_DOWNSTREAM="$DOWNSTREAM"
NS_SUBNET="$SUBNET"
NS_SERVER_IP="$SERVER_IP"
NS_DHCP_START="$DHCP_START"
NS_DHCP_END="$DHCP_END"
NS_LEASE_TIME="$LEASE_TIME"
NS_DNS_SERVERS="$DNS_SERVERS"
NS_EXTRA_OPTS="${EXTRA_OPTS:-}"
}
list_profiles() {
[[ -d "$PROFILE_DIR" ]] || return
for f in "${PROFILE_DIR}"/*.conf; do
[[ -f "$f" ]] && basename "${f%.conf}"
done
}
delete_profile() {
rm -f "$(profile_file "$1")"
}
# ── Setup wizard ───────────────────────────────────────────────────────────────
cmd_setup() {
local edit_name="${1-}" # if editing an existing profile
hdr "netshare — Setup Wizard"
# Load existing profile values as defaults if editing
if [[ -n "$edit_name" ]] && [[ -f "$(profile_file "$edit_name")" ]]; then
info "Editing existing profile: ${edit_name}"
load_profile "$edit_name"
fi
# Gather interfaces
local iface_list
mapfile -t iface_list < <(get_iface_names)
(( ${#iface_list[@]} >= 2 )) || die "Need at least 2 network interfaces (found ${#iface_list[@]})."
print_iface_table
echo
# Build menu display strings (name + type)
local iface_menu=()
local default_iface; default_iface=$(get_default_route_iface)
while IFS='|' read -r name state addrs type; do
local suffix=""
[[ "$name" == "$default_iface" ]] && suffix=" (default route)"
iface_menu+=("${name} [${type}${suffix}]")
done < <(get_interfaces)
# ── Upstream ──────────────────────────────────────────────────────────
info "Select the UPSTREAM interface (internet / WAN)"
local up_choice
ask_menu up_choice "Upstream (internet-facing) interface:" "${iface_menu[@]}"
NS_UPSTREAM="${up_choice%% *}" # strip display suffix
# ── Downstream ────────────────────────────────────────────────────────
# Build list excluding upstream
local down_menu=()
while IFS='|' read -r name state addrs type; do
[[ "$name" == "$NS_UPSTREAM" ]] && continue
down_menu+=("${name} [${type}]")
done < <(get_interfaces)
echo
info "Select the DOWNSTREAM interface (LAN / clients connect here)"
local down_choice
ask_menu down_choice "Downstream (LAN-facing) interface:" "${down_menu[@]}"
NS_DOWNSTREAM="${down_choice%% *}"
# ── Subnet ────────────────────────────────────────────────────────────
echo
local _default_subnet; _default_subnet=$(suggest_subnet)
[[ -n "${NS_SUBNET:-}" ]] || NS_SUBNET="$_default_subnet"
ask_cidr NS_SUBNET "Subnet for LAN (CIDR)" "${NS_SUBNET}"
# ── Server IP ─────────────────────────────────────────────────────────
local _default_sip; _default_sip=$(subnet_to_server_ip "$NS_SUBNET")
[[ -n "${NS_SERVER_IP:-}" ]] || NS_SERVER_IP="$_default_sip"
ask_ip NS_SERVER_IP "Server IP on downstream interface" "${NS_SERVER_IP}"
# ── DHCP range ────────────────────────────────────────────────────────
local _dhcp_range; _dhcp_range=$(subnet_to_dhcp_range "$NS_SUBNET")
local _def_start; _def_start="${_dhcp_range%% *}"
local _def_end; _def_end="${_dhcp_range##* }"
[[ -n "${NS_DHCP_START:-}" ]] || NS_DHCP_START="$_def_start"
[[ -n "${NS_DHCP_END:-}" ]] || NS_DHCP_END="$_def_end"
ask_ip NS_DHCP_START "DHCP range start" "${NS_DHCP_START}"
ask_ip NS_DHCP_END "DHCP range end" "${NS_DHCP_END}"
# ── Lease time ────────────────────────────────────────────────────────
[[ -n "${NS_LEASE_TIME:-}" ]] || NS_LEASE_TIME="12h"
ask_input NS_LEASE_TIME "DHCP lease time" "${NS_LEASE_TIME}"
# ── DNS servers ───────────────────────────────────────────────────────
[[ -n "${NS_DNS_SERVERS:-}" ]] || NS_DNS_SERVERS="8.8.8.8,1.1.1.1"
ask_input NS_DNS_SERVERS "DNS servers (comma-separated)" "${NS_DNS_SERVERS}"
# ── Extra dnsmasq options ─────────────────────────────────────────────
[[ -n "${NS_EXTRA_OPTS:-}" ]] || NS_EXTRA_OPTS=""
ask_input_optional NS_EXTRA_OPTS "Extra dnsmasq options"
# ── Summary ───────────────────────────────────────────────────────────
echo
hdr "Configuration Summary"
printf " ${BOLD}%-20s${RESET} %s\n" "Upstream (WAN):" "$NS_UPSTREAM"
printf " ${BOLD}%-20s${RESET} %s\n" "Downstream (LAN):" "$NS_DOWNSTREAM"
printf " ${BOLD}%-20s${RESET} %s\n" "Server IP:" "${NS_SERVER_IP}/${NS_SUBNET#*/}"
printf " ${BOLD}%-20s${RESET} %s – %s\n" "DHCP range:" "$NS_DHCP_START" "$NS_DHCP_END"
printf " ${BOLD}%-20s${RESET} %s\n" "Lease time:" "$NS_LEASE_TIME"
printf " ${BOLD}%-20s${RESET} %s\n" "DNS:" "$NS_DNS_SERVERS"
[[ -n "$NS_EXTRA_OPTS" ]] && \
printf " ${BOLD}%-20s${RESET} %s\n" "Extra opts:" "$NS_EXTRA_OPTS"
hr
# ── Profile name ──────────────────────────────────────────────────────
local profile_name="${edit_name:-default}"
ask_input profile_name "Save as profile name" "$profile_name"
profile_name="${profile_name,,}" # lowercase
profile_name="${profile_name// /-}" # spaces → dashes
if [[ -f "$(profile_file "$profile_name")" && "$profile_name" != "$edit_name" ]]; then
ask_yn "Profile '${profile_name}' already exists. Overwrite?" n || { info "Aborted."; return 1; }
fi
save_profile "$profile_name"
echo
if ask_yn "Apply this configuration now?" y; then
exec sudo -E bash "$0" up "$profile_name"
fi
}
# ── Bring up ───────────────────────────────────────────────────────────────────
cmd_up() {
local name="${1:-}"
if [[ -z "$name" ]]; then
local profiles=(); mapfile -t profiles < <(list_profiles)
(( ${#profiles[@]} > 0 )) || die "No profiles found. Run 'netshare setup' first."
if (( ${#profiles[@]} == 1 )); then
name="${profiles[0]}"
else
ask_menu name "Select profile to bring up:" "${profiles[@]}"
fi
fi
load_profile "$name" || exit 1
# Check if this exact profile is already active
if [[ -f "$(state_file "$name")" ]]; then
warn "Profile '${name}' is already active."
ask_yn "Bring it down and re-apply?" n || return 1
cmd_down "$name"
sleep 1
fi
# Check for interface conflicts with other active profiles
local -a conflicts=()
for _sf in "${STATE_DIR}"/*.conf; do
[[ -f "$_sf" ]] || continue
local _aname; _aname=$(basename "${_sf%.conf}")
[[ "$_aname" == "$name" ]] && continue
# Source just enough to get the interfaces
local _aup _adown
_aup=$(grep '^UPSTREAM=' "$_sf" | cut -d= -f2)
_adown=$(grep '^DOWNSTREAM=' "$_sf" | cut -d= -f2)
if [[ "$_adown" == "$NS_DOWNSTREAM" || "$_adown" == "$NS_UPSTREAM" || "$_aup" == "$NS_DOWNSTREAM" || "$_aup" == "$NS_UPSTREAM" ]]; then
conflicts+=("$_aname (downstream: ${_adown}, upstream: ${_aup})")
fi
done
if (( ${#conflicts[@]} > 0 )); then
err "Interface conflict with active profile(s):"
for _c in "${conflicts[@]}"; do
echo -e " ${DIM}•${RESET} ${_c}"
done
echo
warn "Sharing the same interface across two profiles will cause conflicts."
ask_yn "Tear down conflicting profile(s) and continue?" n || return 1
for _sf in "${STATE_DIR}"/*.conf; do
[[ -f "$_sf" ]] || continue
local _aname; _aname=$(basename "${_sf%.conf}")
[[ "$_aname" == "$name" ]] && continue
local _adown
_adown=$(grep '^DOWNSTREAM=' "$_sf" | cut -d= -f2)
local _aup
_aup=$(grep '^UPSTREAM=' "$_sf" | cut -d= -f2)
if [[ "$_adown" == "$NS_DOWNSTREAM" || "$_adown" == "$NS_UPSTREAM" || "$_aup" == "$NS_DOWNSTREAM" || "$_aup" == "$NS_UPSTREAM" ]]; then
info "Tearing down: ${_aname}"
cmd_down "$_aname"
sleep 1
fi
done
fi
hdr "Bringing up: ${name}"
local upstream="$NS_UPSTREAM"
local downstream="$NS_DOWNSTREAM"
local subnet="$NS_SUBNET"
local server_ip="$NS_SERVER_IP"
local prefix="${subnet#*/}"
local nm_unmanaged=false
local ufw_active=false
local firewalld_active=false
local ip_fwd_was
# Save current ip_forward state
ip_fwd_was=$(cat /proc/sys/net/ipv4/ip_forward 2>/dev/null || echo "0")
# Trap for cleanup on error
local _cleanup_needed=true
cleanup_on_err() {
"$_cleanup_needed" || return
warn "Error during setup. Attempting cleanup..."
iptables -t nat -D POSTROUTING -o "$upstream" -j MASQUERADE &>/dev/null || true
iptables -D FORWARD -i "$upstream" -o "$downstream" -m state --state RELATED,ESTABLISHED -j ACCEPT &>/dev/null || true
iptables -D FORWARD -i "$downstream" -o "$upstream" -j ACCEPT &>/dev/null || true
iptables -D INPUT -i "$downstream" -s "$subnet" -j ACCEPT &>/dev/null || true
ip addr flush dev "$downstream" &>/dev/null || true
local conf="${DNSMASQ_DIR}/${DNSMASQ_PREFIX}${name}.conf"
rm -f "$conf"
systemctl restart dnsmasq &>/dev/null || pkill -x dnsmasq 2>/dev/null || true
"$nm_unmanaged" && nm_restore "$downstream"
remove_state "$name"
}
trap cleanup_on_err ERR
# ── 0. Validate interfaces exist ──────────────────────────────────────
local missing_ifaces=()
for _iface in "$upstream" "$downstream"; do
if ! ip link show "$_iface" &>/dev/null; then
missing_ifaces+=("$_iface")
fi
done
if (( ${#missing_ifaces[@]} > 0 )); then
err "Interface(s) not found: ${missing_ifaces[*]}"
err "Check that all adapters are plugged in and try again."
return 1
fi
# Warn if downstream is DOWN but continue (it will be brought up)
local ds_state
ds_state=$(ip -o link show "$downstream" 2>/dev/null | grep -oP 'state \K\S+' || echo "UNKNOWN")
if [[ "$ds_state" == "DOWN" ]]; then
warn "Interface ${downstream} is currently DOWN — it will be brought up by this script."
warn "If it is a USB adapter, make sure it is fully connected before continuing."
ask_yn "Continue?" y || return 1
fi
# Warn if upstream has no default route
if ! ip route show default dev "$upstream" &>/dev/null || [[ -z "$(ip route show default dev "$upstream" 2>/dev/null)" ]]; then
warn "No default route found on upstream interface ${upstream}."
warn "Internet sharing may not work until ${upstream} has a route to the internet."
ask_yn "Continue anyway?" y || return 1
fi
# ── 1. Warn if downstream is WiFi ─────────────────────────────────────
local ds_type
case "$downstream" in
wl*|wifi*|ath*|wlan*) ds_type="wifi" ;;
*) ds_type="other" ;;
esac
if [[ "$ds_type" == "wifi" ]]; then
echo
warn "Downstream interface '${downstream}' appears to be a WiFi adapter."
warn "WiFi adapters in managed mode (connected to an AP) cannot accept"
warn "connections from other devices — clients will not be able to connect."
warn "To share over WiFi you need a separate adapter in AP mode (hostapd)."
warn "Ethernet adapters are recommended for the downstream interface."
echo
ask_yn "Continue anyway?" n || return 1
fi
# ── 2. Dependencies ────────────────────────────────────────────────────
ensure_dnsmasq
ensure_iptables
# ── 1. NetworkManager ──────────────────────────────────────────────────
if nm_running; then
nm_set_unmanaged "$downstream"
nm_unmanaged=true
fi
# ── 2. Configure IP ────────────────────────────────────────────────────
step "Assigning ${server_ip}/${prefix} to ${downstream}..."
ip addr flush dev "$downstream"
ip addr add "${server_ip}/${prefix}" dev "$downstream"
ip link set "$downstream" up
ok "IP configured on ${downstream}"
# ── 3. IP forwarding ───────────────────────────────────────────────────
step "Enabling IP forwarding..."
sysctl -w net.ipv4.ip_forward=1 &>/dev/null
ok "IP forwarding enabled"
# ── 4. iptables ────────────────────────────────────────────────────────
step "Configuring iptables NAT + forwarding rules..."
iptables -t nat -A POSTROUTING -o "$upstream" -j MASQUERADE
iptables -A FORWARD -i "$upstream" -o "$downstream" -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i "$downstream" -o "$upstream" -j ACCEPT
iptables -A INPUT -i "$downstream" -s "$subnet" -j ACCEPT
ok "iptables rules applied"
# ── 5. Firewall managers ───────────────────────────────────────────────
detect_firewalls
if "$FW_UFW"; then
configure_ufw "$downstream" "$subnet"
ufw_active=true
fi
if "$FW_FIREWALLD"; then
configure_firewalld "$upstream" "$downstream"
firewalld_active=true
fi
# ── 6. dnsmasq config ─────────────────────────────────────────────────
step "Writing dnsmasq config..."
local conf="${DNSMASQ_DIR}/${DNSMASQ_PREFIX}${name}.conf"
mkdir -p "$DNSMASQ_DIR"
cat > "$conf" <<EOF
# netshare — profile: ${name}
interface=${downstream}
bind-interfaces
dhcp-range=${NS_DHCP_START},${NS_DHCP_END},${NS_LEASE_TIME}
dhcp-option=6,${NS_DNS_SERVERS}
${NS_EXTRA_OPTS}
EOF
ok "dnsmasq config written → ${conf}"
# ── 7. Start dnsmasq ───────────────────────────────────────────────────
step "Restarting dnsmasq..."
if systemctl list-unit-files dnsmasq.service &>/dev/null && systemctl list-unit-files dnsmasq.service | grep -q dnsmasq; then
systemctl restart dnsmasq
systemctl enable dnsmasq &>/dev/null || true
ok "dnsmasq running (systemd)"
else
# No systemd unit — kill any existing instance and start directly
pkill -x dnsmasq 2>/dev/null || true
sleep 0.5
dnsmasq --conf-file="${conf}"
ok "dnsmasq running (direct)"
fi
# ── 8. Save state ──────────────────────────────────────────────────────
save_state "$name" \
"$upstream" "$downstream" "$subnet" "$server_ip" \
"$nm_unmanaged" "$ufw_active" "$firewalld_active" \
"$ip_fwd_was" "$conf"
_cleanup_needed=false
trap - ERR
echo
hdr "Active: ${name}"
printf " ${GREEN}✓${RESET} Internet sharing is ${BOLD}active${RESET}\n\n"
printf " ${BOLD}%-18s${RESET} %b%s${RESET}\n" "WAN interface:" "${CYAN}" "$upstream"
printf " ${BOLD}%-18s${RESET} %b%s${RESET} → %s\n" "LAN interface:" "${CYAN}" "$downstream" "$server_ip"
printf " ${BOLD}%-18s${RESET} %s – %s\n" "DHCP range:" "$NS_DHCP_START" "$NS_DHCP_END"
echo
echo -e " Run ${BOLD}netshare down ${name}${RESET} to stop."
echo -e " Run ${BOLD}netshare restart ${name}${RESET} if you re-plug the downstream adapter."
hr
}
# ── Bring down ─────────────────────────────────────────────────────────────────
cmd_down() {
local name="${1:-}"
local force=false
[[ "${1:-}" == "--force" ]] && { force=true; shift; }
[[ -z "$name" ]] && name="${1:-}"
if [[ -z "$name" ]]; then
local active=(); mapfile -t active < <(get_active_profiles)
if (( ${#active[@]} == 0 )); then
err "No active sessions found."
echo
echo -e " If you believe a profile is stuck (e.g. after a crashed run), use:"
echo -e " ${BOLD}netshare down --force <profile>${RESET}"
echo
echo -e " Note: a system reboot automatically cleans up any orphaned configs."
return 1
elif (( ${#active[@]} == 1 )); then
name="${active[0]}"
else
ask_menu name "Select session to bring down:" "${active[@]}"
fi
fi
# If a name was given directly but has no active state, catch it here
if ! [[ -f "$(state_file "$name")" ]]; then
if ! "$force"; then
err "Profile '${name}' is not currently active."
echo
echo -e " To force-clean a stuck profile's system configs, use:"
echo -e " ${BOLD}netshare down --force ${name}${RESET}"
return 1
fi
fi
hdr "Tearing down: ${name}"
# Try to load saved state; fall back to profile
if load_state "$name" 2>/dev/null; then
local upstream="$UPSTREAM"
local downstream="$DOWNSTREAM"
local subnet="$SUBNET"
local nm_unmanaged="${NM_UNMANAGED:-false}"
local ufw_active="${UFW_ACTIVE:-false}"
local firewalld_active="${FIREWALLD_ACTIVE:-false}"
local ip_fwd_was="${IP_FWD_WAS:-0}"
local dnsmasq_conf="${DNSMASQ_CONF:-${DNSMASQ_DIR}/${DNSMASQ_PREFIX}${name}.conf}"
elif load_profile "$name" 2>/dev/null; then
warn "No active state found — running forced cleanup using profile config."
warn "Only netshare-managed configs will be removed; system state is not modified."
local upstream="$NS_UPSTREAM"
local downstream="$NS_DOWNSTREAM"
local subnet="$NS_SUBNET"
local nm_unmanaged=false
local ufw_active=false
local firewalld_active=false
local ip_fwd_was=1 # don't touch ip_forward — we don't know the prior state
local dnsmasq_conf="${DNSMASQ_DIR}/${DNSMASQ_PREFIX}${name}.conf"
else
die "No state or profile found for '${name}'."
fi
# ── 1. Remove dnsmasq config ───────────────────────────────────────────
step "Removing dnsmasq config..."
rm -f "$dnsmasq_conf"
if systemctl list-unit-files dnsmasq.service 2>/dev/null | grep -q dnsmasq; then
systemctl restart dnsmasq 2>/dev/null || true
else
pkill -x dnsmasq 2>/dev/null || true
fi
ok "dnsmasq config removed"
# ── 2. Remove iptables rules ───────────────────────────────────────────
step "Removing iptables rules..."
iptables -t nat -D POSTROUTING -o "$upstream" -j MASQUERADE &>/dev/null || true
iptables -D FORWARD -i "$upstream" -o "$downstream" -m state --state RELATED,ESTABLISHED -j ACCEPT &>/dev/null || true
iptables -D FORWARD -i "$downstream" -o "$upstream" -j ACCEPT &>/dev/null || true
iptables -D INPUT -i "$downstream" -s "$subnet" -j ACCEPT &>/dev/null || true
ok "iptables rules removed"
# ── 3. Firewall cleanup ────────────────────────────────────────────────
"$ufw_active" && teardown_ufw "$downstream" "$subnet"
"$firewalld_active" && teardown_firewalld "$upstream" "$downstream"
# ── 4. Flush IP ────────────────────────────────────────────────────────
step "Flushing IP from ${downstream}..."
ip addr flush dev "$downstream" 2>/dev/null || true
ok "IP flushed from ${downstream}"
# ── 5. IP forwarding ───────────────────────────────────────────────────
if [[ "$ip_fwd_was" == "0" ]]; then
step "Disabling IP forwarding..."
sysctl -w net.ipv4.ip_forward=0 &>/dev/null
ok "IP forwarding disabled"
else
info "IP forwarding left enabled (was active before netshare)."
fi
# ── 6. NetworkManager ──────────────────────────────────────────────────
if "$nm_unmanaged"; then
step "Restoring ${downstream} to NetworkManager..."
nm_restore "$downstream"
ok "NetworkManager restored"
fi
# ── 7. Cleanup state ───────────────────────────────────────────────────
remove_state "$name"
echo
hdr "Stopped: ${name}"
printf " ${RED}✓${RESET} Internet sharing for ${BOLD}${name}${RESET} has been stopped.\n"
hr
}
# ── Status ─────────────────────────────────────────────────────────────────────
cmd_status() {
hdr "netshare — Status"
print_iface_table
local active=(); mapfile -t active < <(get_active_profiles)
if (( ${#active[@]} > 0 )); then
echo
echo -e "${BOLD}Active Sessions${RESET}"
hr
for name in "${active[@]}"; do
load_state "$name" 2>/dev/null || continue
printf " ${GREEN}●${RESET} ${BOLD}%-16s${RESET} WAN: ${CYAN}%-14s${RESET} LAN: ${CYAN}%-14s${RESET} %s [since %s]\n" \
"$name" "$UPSTREAM" "$DOWNSTREAM" "$SERVER_IP" "${STARTED_AT:-?}"
done