b66f5d72426e7e9718c5ef0111b21f4725eba1e2
[project/firewall4.git] / root / sbin / fw4
1 #!/bin/sh
2
3 set -o pipefail
4
5 MAIN=/usr/share/firewall4/main.uc
6 LOCK=/var/run/fw4.lock
7 STATE=/var/run/fw4.state
8 VERBOSE=
9
10 [ -t 2 ] && export TTY=1
11
12 die() {
13 [ -n "$QUIET" ] || echo "$@" >&2
14 exit 1
15 }
16
17 start() {
18 {
19 flock -x 1000
20
21 case "$1" in
22 start)
23 [ -f $STATE ] && die "The fw4 firewall appears to be already loaded."
24 ;;
25 reload)
26 [ ! -f $STATE ] && die "The fw4 firewall does not appear to be loaded."
27
28 # Delete state to force reloading ubus state
29 rm -f $STATE
30 ;;
31 esac
32
33 ACTION=start \
34 utpl -S $MAIN | nft $VERBOSE -f /proc/self/fd/0
35 } 1000>$LOCK
36 }
37
38 print() {
39 ACTION=print \
40 utpl -S $MAIN
41 }
42
43 stop() {
44 {
45 flock -x 1000
46
47 if nft list tables inet | grep -sq "table inet fw4"; then
48 nft delete table inet fw4
49 rm -f $STATE
50 else
51 return 1
52 fi
53 } 1000>$LOCK
54 }
55
56 flush() {
57 {
58 flock -x 1000
59
60 local dummy family table
61 nft list tables | while read dummy family table; do
62 nft delete table "$family" "$table"
63 done
64
65 rm -f $STATE
66 } 1000>$LOCK
67 }
68
69 reload_sets() {
70 ACTION=reload-sets \
71 flock -x $LOCK utpl -S $MAIN | nft $VERBOSE -f /proc/self/fd/0
72 }
73
74 lookup() {
75 ACTION=$1 OBJECT=$2 DEVICE=$3 \
76 flock -x $LOCK utpl -S $MAIN
77 }
78
79 while [ -n "$1" ]; do
80 case "$1" in
81 -q)
82 export QUIET=1
83 shift
84 ;;
85 -v)
86 export VERBOSE=-e
87 shift
88 ;;
89 *)
90 break
91 ;;
92 esac
93 done
94
95 case "$1" in
96 start|reload)
97 start "$1"
98 ;;
99 stop)
100 stop || die "The fw4 firewall does not appear to be loaded, try fw4 flush to delete all rules."
101 ;;
102 flush)
103 flush
104 ;;
105 restart)
106 stop || rm -f $STATE
107 start
108 ;;
109 print)
110 print
111 ;;
112 reload-sets)
113 reload_sets
114 ;;
115 network|device|zone)
116 lookup "$@"
117 ;;
118 *)
119 cat <<EOT
120 Usage:
121
122 $0 [-v] [-q] start|stop|flush|restart|reload
123
124 Start, stop, flush, restart or reload the firewall respectively.
125
126
127 $0 [-v] [-q] reload-sets
128
129 Reload the contents of all declared sets but do not touch the
130 ruleset.
131
132
133 $0 [-q] print
134
135 Print the rendered ruleset.
136
137
138 $0 [-q] network {net}
139
140 Print the name of the firewall zone covering the given network.
141
142 Exits with code 1 if the network is not found or if no zone is
143 covering it.
144
145
146 $0 [-q] device {dev}
147
148 Print the name of the firewall zone covering the given device.
149
150 Exits with code 1 if the device is not found or if no zone is
151 covering it.
152
153
154 $0 [-q] zone {zone} [dev]
155
156 Print all covered devices of the given zone, optionally restricted
157 to only the given device name.
158
159 Exits with code 1 if zone is not found or if a device is specified
160 and not covered by the given zone.
161
162 EOT
163 ;;
164 esac