finally fully use gnu license recommendations
[distro-setup] / dynamic-ip-update
1 #!/bin/bash
2 # I, Ian Kelling, follow the GNU license recommendations at
3 # https://www.gnu.org/licenses/license-recommendations.en.html. They
4 # recommend that small programs, < 300 lines, be licensed under the
5 # Apache License 2.0. This file contains or is part of one or more small
6 # programs. If a small program grows beyond 300 lines, I plan to switch
7 # its license to GPL.
8
9 # Copyright 2024 Ian Kelling
10
11 # Licensed under the Apache License, Version 2.0 (the "License");
12 # you may not use this file except in compliance with the License.
13 # You may obtain a copy of the License at
14
15 # http://www.apache.org/licenses/LICENSE-2.0
16
17 # Unless required by applicable law or agreed to in writing, software
18 # distributed under the License is distributed on an "AS IS" BASIS,
19 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 # See the License for the specific language governing permissions and
21 # limitations under the License.
22
23
24 set -e; . /usr/local/lib/bash-bear; set +e
25 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
26
27 this_file="$(readlink -f -- "${BASH_SOURCE[0]}")"
28 readonly this_file
29 this_dir="${this_file%/*}"
30 readonly this_dir
31 cd "$this_dir"
32
33 usage() {
34 cat <<EOF
35 Usage: ${0##*/} [-f]
36 Update ip in remote nameserver.
37
38 -f Force update even if ip hasn't changed.
39 -h|--help Print help and exit.
40
41 Note: Uses util-linux getopt option parsing: spaces between args and
42 options, short options can be combined, options before args.
43 EOF
44 exit $1
45 }
46
47 ##### begin command line parsing ########
48
49 # ensure we can handle args with spaces or empty.
50 ret=0; getopt -T || ret=$?
51 [[ $ret == 4 ]] || { echo "Install util-linux for enhanced getopt" >&2; exit 1; }
52
53 force=false # default
54 temp=$(getopt -l help hf "$@") || usage 1
55 eval set -- "$temp"
56 while true; do
57 case $1 in
58 -f) force=true ;;
59 --) shift; break ;;
60 *) echo "$0: unexpected args: $*" >&2 ; usage 1 ;;
61 esac
62 shift
63 done
64
65 ##### end command line parsing ########
66
67 main() {
68
69 fqdn=$(hostname -f)
70 domaintmp=${fqdn#*.}
71 hostnametmp=${fqdn%%.*}
72 # i for internet
73 fqdn=${hostnametmp}i.${domaintmp}
74
75 up4=false
76
77 if ! tmp=$(ip -4 route get 85.119.83.50 2>/dev/null); then
78 # our internet is down
79 if [[ $INVOCATION_ID ]]; then
80 return 0
81 else
82 echo $0: failed to get route, giving up
83 exit 0
84 fi
85 fi
86 read -r _ _ gateway _ ifdev _ <<<"$tmp"
87
88 case $gateway in
89 10.2.0.1)
90 dyndomain=b8.nz
91 dynhost=i.b8.nz
92 ;;
93 *)
94 return 0
95 ;;
96 esac
97
98 # We check if we are at home by testing gateway ssh
99 # fingerprint. However, if we found in the past that we are, I dont
100 # like to spam its logs with ssh login attempts, so just check if our
101 # gateway interface has an increasing amount of packets sent +
102 # received from last time.
103 athome=false
104 if [[ -s /dev/shm/dynamic-ip-update-state ]]; then
105 oldbytes=$(cat /dev/shm/dynamic-ip-update-state)
106 newbytes=$(awk '$1 == "'$ifdev':" {print $2 + $10}' /proc/net/dev)
107 if [[ $oldbytes == [1-9]* ]] && (( newbytes >= oldbytes )); then
108 athome=true
109 printf "%s\n" "$newbytes" >/dev/shm/dynamic-ip-update-state
110 fi
111 fi
112 if ! $athome && timeout -s 9 5 ssh-keyscan -p 2220 -t rsa $gateway 2>/dev/null | grep -qFx "[$gateway]:2220 ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCH+/h1dGEfKEusBblndU2e6QT4wLCm5+yqr/sqh/0X9YfjR7BfWWm8nNmuP55cYc+Wuf5ljB1H1acXEcsl1y8e0j3agHfF0V74FE1N1zz5nn2Ep8NHnmqgEhza38ZxMPh+4p3X7zklEKU7+3SzybKBi8sg0wLzlS2LM0JaUN80zR2sK11Kye3dURUXPk78u5wodOkgcEYRwSYaDMJlUzWP+poRXIDJwFaMQnwmxbl/c84yOyaU0x/d6hFwoRscWecihX+vvBNeSyxR4xr2HDOyUWwJkctyAgt2p7w3tfkXOKcCRzTAjGVIMQLTvo0sG/yJbcyHoEFdFybCsgDvfyYn"; then
113 athome=true
114 awk '$1 == "'$ifdev':" {print $2 + $10}' /proc/net/dev > /dev/shm/dynamic-ip-update-state
115 fi
116
117
118 if $athome; then
119 if ! cur4="$(dig +short $dynhost @iankelling.org | tail -1)"; then
120 if [[ ! $INVOCATION_ID ]]; then
121 echo "$0: dig failed. internet looks down. giving up"
122 fi
123 return 0
124 fi
125 if ip4=$(curl --connect-timeout 10 -s4 https://iankelling.org/cgi/pubip); then
126 if $force || [[ $cur4 && $ip4 && $cur4 != "$ip4" ]]; then
127 up4=true # update ipv4
128 fi
129 fi
130 fi
131
132 # may not be set yet so allow fail
133 cur6="$(host -4 -t aaaa $fqdn iankelling.org | sed -rn 's/.*has IPv6 address (.*)/\1/p;T;q')" ||:
134
135 up6=false
136
137 out6=$(curl --connect-timeout 10 -s6 https://iankelling.org/cgi/pubip) ||: # failure allowed if we have no ipv6
138
139 if [[ $out6 ]]; then
140 dev=$(ip -o a show to $out6 | awk '{print $2}')
141 # we use slaac with privacy extension, so get our less private more permanent address
142 mac=$(cat /sys/class/net/$dev/address)
143
144 IFS=: read -ra f <<<$mac; set -- ${f[@]}
145 ip6=${out6%:*:*:*:*}:$(printf %x $((0x$1 + 2)))$2:$3'ff:fe'$4:$5$6
146 # in case we aren't using slaac
147 if ! ip a | grep "^ *inet6 $ip6/" &>/dev/null; then
148 ip6=$out6
149 fi
150 fi
151
152 if $force || [[ $cur6 != "$ip6" ]]; then
153 up6=true
154 fi
155
156 # if we failed to get our ipv6 addr, we probably have ipv6
157 # connectivity problem.
158 if [[ ! $ip6 ]]; then
159 ip_arg=-4
160 fi
161
162 if ! $up4 && ! $up6; then
163 return 0
164 fi
165
166 # note, a simpler way to do this would be to ssh and use
167 # "${SSH_CLIENT%% *}
168 # to update bind if needed.
169
170 tmpf=$(mktemp)
171 cat >>$tmpf <<EOF
172 server iankelling.org
173 zone b8.nz
174 EOF
175
176 if $up4; then
177 cat >>$tmpf <<EOF
178 update delete $dynhost. A
179 update add $dynhost. 300 A $ip4
180 update delete $dyndomain. A
181 update add $dyndomain. 300 A $ip4
182 EOF
183 fi
184
185 if $up6; then
186 if [[ $ip6 ]]; then
187 cat >>$tmpf <<EOF
188 update delete $fqdn. AAAA
189 update add $fqdn. 60 AAAA $ip6
190 EOF
191 else
192 cat >>$tmpf <<EOF
193 update delete $fqdn. AAAA
194 EOF
195 fi
196 fi
197
198 cat >>$tmpf <<EOF
199 show
200 send
201 answer
202 quit
203 EOF
204
205 chronic nsupdate $ip_arg -k /p/c/machine_specific/vps/filesystem/etc/bind/Kb8.nz.*.private <$tmpf || nsupdate_fails=$((nsupdate_fails + 1))
206 sed -i 's/^server .*/server bk.b8.nz/' $tmpf
207 chronic nsupdate $ip_arg -k /p/c/machine_specific/vps/filesystem/etc/bind/Kb8.nz.*.private <$tmpf || nsupdate_fails=$((nsupdate_fails + 1))
208 if (( nsupdate_fails > nsupdate_fail_limit )); then
209 echo error: nsupdate is persistently failing >&2
210 exit 1
211 fi
212 rm -f $tmpf
213 }
214
215 loop-main() {
216 while true; do
217 main
218 sleep 30
219 done
220 }
221
222 nsupdate_fails=0
223 if [[ $INVOCATION_ID ]]; then
224 nsupdate_fail_limit=10
225 loop-main
226 else
227 nsupdate_fail_limit=0
228 main
229 fi
230
231 exit 0
232
233
234 # # # persistent initial setup for this:
235 # # # create files in /a/c/machine_specific/vps/filesystem/etc/bind
236 # # # note, conflink also does some group ownership stuff.
237 # mkc /p/c/machine_specific/vps/filesystem/etc/bind
238 # sudo dnssec-keygen -a HMAC-SHA512 -b 512 -n HOST b8.nz
239 # user=$(id -un)
240 # sudo chown $user:$user *
241
242
243 # f=key.b8.nz
244 # cat >$tmpf <<EOF
245 # key b8.nz. {
246 # algorithm HMAC-SHA512;
247 # secret "$(awk '$1 == "Key:" {print $2}' Kb8.nz.*.private)";
248 # };
249 # EOF
250
251 # chmod 640 [kK]*
252
253 # # push here?
254 # #myunison -ob li
255 # #ssh li conflink
256 # ssh li.b8.nz systemctl reload named
257
258
259 # # b8.nz has address 65.96.178.16
260 # # b8.nz has IPv6 address 2601:197:600:6efb:82fa:5bff:fe1c:6ecf