ddns-scripts: rename variable: s/retry_count/retry_max_count/
[feed/packages.git] / net / ddns-scripts / files / usr / lib / ddns / dynamic_dns_updater.sh
1 #!/bin/sh
2 # /usr/lib/ddns/dynamic_dns_updater.sh
3 #
4 #.Distributed under the terms of the GNU General Public License (GPL) version 2.0
5 # Original written by Eric Paul Bishop, January 2008
6 # (Loosely) based on the script on the one posted by exobyte in the forums here:
7 # http://forum.openwrt.org/viewtopic.php?id=14040
8 # extended and partial rewritten
9 #.2014-2018 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
10 #
11 # variables in small chars are read from /etc/config/ddns
12 # variables in big chars are defined inside these scripts as global vars
13 # variables in big chars beginning with "__" are local defined inside functions only
14 # set -vx #script debugger
15
16 . $(dirname $0)/dynamic_dns_functions.sh # global vars are also defined here
17
18 usage() {
19 cat << EOF
20
21 Usage:
22 $MYPROG [options] -- command
23
24 Commands:
25 start Start SECTION or NETWORK or all
26 stop Stop NETWORK or all
27
28 Parameters:
29 -n NETWORK Start/Stop sections in background monitoring NETWORK, force VERBOSE=0
30 -S SECTION SECTION to start
31 use either -N NETWORK or -S SECTION
32
33 -h show this help and exit
34 -V show version and exit
35 -v LEVEL VERBOSE=LEVEL (default 1)
36 '0' NO output to console
37 '1' output to console
38 '2' output to console AND logfile
39 + run once WITHOUT retry on error
40 '3' output to console AND logfile
41 + run once WITHOUT retry on error
42 + NOT sending update to DDNS service
43
44 EOF
45 }
46
47 usage_err() {
48 printf %s\\n "$MYPROG: $@" >&2
49 usage >&2
50 exit 1
51 }
52
53 while getopts ":hv:n:S:V" OPT; do
54 case "$OPT" in
55 h) usage; exit 0;;
56 v) VERBOSE=$OPTARG;;
57 n) NETWORK=$OPTARG;;
58 S) SECTION_ID=$OPTARG;;
59 V) printf %s\\n "ddns-scripts $VERSION"; exit 0;;
60 :) usage_err "option -$OPTARG missing argument";;
61 \?) usage_err "invalid option -$OPTARG";;
62 *) usage_err "unhandled option -$OPT $OPTARG";;
63 esac
64 done
65 shift $((OPTIND - 1 )) # OPTIND is 1 based
66
67 [ -n "$NETWORK" -a -n "$SECTION_ID" ] && usage_err "use either option '-N' or '-S' not both"
68 [ $# -eq 0 ] && usage_err "missing command"
69 [ $# -gt 1 ] && usage_err "to much commands"
70
71 case "$1" in
72 start)
73 if [ -n "$NETWORK" ]; then
74 start_daemon_for_all_ddns_sections "$NETWORK"
75 exit 0
76 fi
77 if [ -z "$SECTION_ID" ]; then
78 start_daemon_for_all_ddns_sections
79 exit 0
80 fi
81 ;;
82 stop)
83 if [ -n "$INTERFACE" ]; then
84 stop_daemon_for_all_ddns_sections "$NETWORK"
85 exit 0
86 else
87 stop_daemon_for_all_ddns_sections
88 exit 0
89 fi
90 exit 1
91 ;;
92 reload)
93 killall -1 dynamic_dns_updater.sh 2>/dev/null
94 exit $?
95 ;;
96 *) usage_err "unknown command - $1";;
97 esac
98
99 # set file names
100 PIDFILE="$ddns_rundir/$SECTION_ID.pid" # Process ID file
101 UPDFILE="$ddns_rundir/$SECTION_ID.update" # last update successful send (system uptime)
102 DATFILE="$ddns_rundir/$SECTION_ID.dat" # save stdout data of WGet and other extern programs called
103 ERRFILE="$ddns_rundir/$SECTION_ID.err" # save stderr output of WGet and other extern programs called
104 IPFILE="$ddns_rundir/$SECTION_ID.ip" #
105 LOGFILE="$ddns_logdir/$SECTION_ID.log" # log file
106
107 # VERBOSE > 1 delete logfile if exist to create an empty one
108 # only with this data of this run for easier diagnostic
109 # new one created by write_log function
110 [ $VERBOSE -gt 1 -a -f $LOGFILE ] && rm -f $LOGFILE
111
112 # TRAP handler
113 trap "trap_handler 0 \$?" 0 # handle script exit with exit status
114 trap "trap_handler 1" 1 # SIGHUP Hangup / reload config
115 trap "trap_handler 2" 2 # SIGINT Terminal interrupt
116 trap "trap_handler 3" 3 # SIGQUIT Terminal quit
117 # trap "trap_handler 9" 9 # SIGKILL no chance to trap
118 trap "trap_handler 15" 15 # SIGTERM Termination
119
120 ################################################################################
121 # Leave this comment here, to clearly document variable names that are expected/possible
122 # Use load_all_config_options to load config options, which is a much more flexible solution.
123 #
124 # config_load "ddns"
125 # config_get <variable> $SECTION_ID <option>
126 #
127 # defined options (also used as variable):
128 #
129 # enabled self-explanatory
130 # interface network interface used by hotplug.d i.e. 'wan' or 'wan6'
131 #
132 # service_name Which DDNS service do you use or "custom"
133 # update_url URL to use to update your "custom" DDNS service
134 # update_script SCRIPT to use to update your "custom" DDNS service
135 #
136 # lookup_host FQDN of ONE of your at DDNS service defined host / required to validate if IP update happen/necessary
137 # domain Nomally your DDNS hostname / replace [DOMAIN] in update_url
138 # username Username of your DDNS service account / urlenceded and replace [USERNAME] in update_url
139 # password Password of your DDNS service account / urlencoded and replace [PASSWORD] in update_url
140 # param_enc Optional parameter for (later) usage / urlencoded and replace [PARAMENC] in update_url
141 # param_opt Optional parameter for (later) usage / replace [PARAMOPT] in update_url
142 #
143 # use_https use HTTPS to update DDNS service
144 # cacert file or directory where HTTPS can find certificates to verify server; 'IGNORE' ignore check of server certificate
145 #
146 # use_syslog log activity to syslog
147 #
148 # ip_source source to detect current local IP ('network' or 'web' or 'script' or 'interface')
149 # ip_network local defined network to read IP from i.e. 'wan' or 'wan6'
150 # ip_url URL to read local address from i.e. http://checkip.dyndns.com/ or http://checkipv6.dyndns.com/
151 # ip_script full path and name of your script to detect local IP
152 # ip_interface physical interface to use for detecting
153 #
154 # check_interval check for changes every !!! checks below 10 minutes make no sense because the Internet
155 # check_unit 'days' 'hours' 'minutes' !!! needs about 5-10 minutes to sync an IP-change for an DNS entry
156 #
157 # force_interval force to send an update to your service if no change was detected
158 # force_unit 'days' 'hours' 'minutes' !!! force_interval="0" runs this script once for use i.e. with cron
159 #
160 # retry_interval if error was detected retry in
161 # retry_unit 'days' 'hours' 'minutes' 'seconds'
162 # retry_max_count number of retries before scripts stops
163 #
164 # use_ipv6 detecting/sending IPv6 address
165 # force_ipversion force usage of IPv4 or IPv6 for the whole detection and update communication
166 # dns_server using a non default dns server to get Registered IP from Internet
167 # force_dnstcp force communication with DNS server via TCP instead of default UDP
168 # proxy using a proxy for communication !!! ALSO used to detect local IP via web => return proxy's IP !!!
169 # use_logfile self-explanatory "/var/log/ddns/$SECTION_ID.log"
170 # is_glue the record that should be updated is a glue record
171 #
172 # some functionality needs
173 # - GNU Wget or cURL installed for sending updates to DDNS service
174 # - BIND host installed to detect Registered IP
175 #
176 ################################################################################
177
178 load_all_config_options "ddns" "$SECTION_ID"
179 ERR_LAST=$? # save return code - equal 0 if SECTION_ID found
180
181 # set defaults if not defined
182 [ -z "$enabled" ] && enabled=0
183 [ -z "$retry_max_count" ] && retry_max_count=0 # endless retry
184 [ -z "$use_syslog" ] && use_syslog=2 # syslog "Notice"
185 [ -z "$use_https" ] && use_https=0 # not use https
186 [ -z "$use_logfile" ] && use_logfile=1 # use logfile by default
187 [ -z "$use_ipv6" ] && use_ipv6=0 # use IPv4 by default
188 [ -z "$force_ipversion" ] && force_ipversion=0 # default let system decide
189 [ -z "$force_dnstcp" ] && force_dnstcp=0 # default UDP
190 [ -z "$ip_source" ] && ip_source="network"
191 [ -z "$is_glue" ] && is_glue=0 # default the ddns record is not a glue record
192 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 0 ] && ip_network="wan" # IPv4: default wan
193 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 1 ] && ip_network="wan6" # IPv6: default wan6
194 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 0 ] && ip_url="http://checkip.dyndns.com"
195 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 1 ] && ip_url="http://checkipv6.dyndns.com"
196 [ "$ip_source" = "interface" -a -z "$ip_interface" ] && ip_interface="eth1"
197
198 # url encode username (might be email or something like this)
199 # and password (might have special chars for security reason)
200 # and optional parameter "param_enc"
201 [ -n "$username" ] && urlencode URL_USER "$username"
202 [ -n "$password" ] && urlencode URL_PASS "$password"
203 [ -n "$param_enc" ] && urlencode URL_PENC "$param_enc"
204
205 # SECTION_ID does not exists
206 [ $ERR_LAST -ne 0 ] && {
207 [ $VERBOSE -le 1 ] && VERBOSE=2 # force console out and logfile output
208 [ -f $LOGFILE ] && rm -f $LOGFILE # clear logfile before first entry
209 write_log 7 "************ ************** ************** **************"
210 write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
211 write_log 7 "ddns version : $VERSION"
212 write_log 7 "uci configuration:${N}$(uci -q show ddns | grep '=service' | sort)"
213 write_log 14 "Service section '$SECTION_ID' not defined"
214 }
215
216 write_log 7 "************ ************** ************** **************"
217 write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
218 write_log 7 "ddns version : $VERSION"
219 write_log 7 "uci configuration:${N}$(uci -q show ddns.$SECTION_ID | sort)"
220 # write_log 7 "ddns version : $(opkg list-installed ddns-scripts | cut -d ' ' -f 3)"
221 case $VERBOSE in
222 0) write_log 7 "verbose mode : 0 - run normal, NO console output";;
223 1) write_log 7 "verbose mode : 1 - run normal, console mode";;
224 2) write_log 7 "verbose mode : 2 - run once, NO retry on error";;
225 3) write_log 7 "verbose mode : 3 - run once, NO retry on error, NOT sending update";;
226 *) write_log 14 "error detecting VERBOSE '$VERBOSE'";;
227 esac
228
229 # check enabled state otherwise we don't need to continue
230 [ $enabled -eq 0 ] && write_log 14 "Service section disabled!"
231
232 # determine what update url we're using if a service_name is supplied
233 # otherwise update_url is set inside configuration (custom update url)
234 # or update_script is set inside configuration (custom update script)
235 [ -n "$service_name" ] && {
236 # Check first if we have a custom service provider with this name
237 get_service_data "$service_name" "/usr/share/ddns/custom" update_url update_script UPD_ANSWER
238 if [ "$?" != "0" ]; then
239 get_service_data "$service_name" "/usr/share/ddns/default" update_url update_script UPD_ANSWER
240 fi
241 }
242
243 [ -z "$update_url" -a -z "$update_script" ] && write_log 14 "No update_url found/defined or no update_script found/defined!"
244 [ -n "$update_script" -a ! -f "$update_script" ] && write_log 14 "Custom update_script not found!"
245
246 # temporary needed to convert existing uci settings
247 [ -z "$lookup_host" ] && {
248 uci -q set ddns.$SECTION_ID.lookup_host="$domain"
249 uci -q commit ddns
250 lookup_host="$domain"
251 }
252 # later versions only check if configured correctly
253
254 # without lookup host and possibly other required options we can do nothing for you
255 [ -z "$lookup_host" ] && write_log 14 "Service section not configured correctly! Missing 'lookup_host'"
256
257 # verify validity of variables
258 [ -n "$lookup_host" ] && sanitize_variable lookup_host "$DNS_CHARSET" ""
259 [ -n "$dns_server" ] && sanitize_variable dns_server "$DNS_CHARSET" ""
260 [ -n "$domain" ] && sanitize_variable domain "$DNS_CHARSET_DOMAIN" ""
261
262 # Filter shell escape characters, if these are required in the URL, they
263 # can still be passed url encoded
264 [ -n "$param_opt" ] && sanitize_variable param_opt "" "$SHELL_ESCAPE"
265
266 [ -n "$update_url" ] && {
267 # only check if update_url is given, update_scripts have to check themselves
268 [ -z "$domain" ] && $(echo "$update_url" | grep "\[DOMAIN\]" >/dev/null 2>&1) && \
269 write_log 14 "Service section not configured correctly! Missing 'domain'"
270 [ -z "$username" ] && $(echo "$update_url" | grep "\[USERNAME\]" >/dev/null 2>&1) && \
271 write_log 14 "Service section not configured correctly! Missing 'username'"
272 [ -z "$password" ] && $(echo "$update_url" | grep "\[PASSWORD\]" >/dev/null 2>&1) && \
273 write_log 14 "Service section not configured correctly! Missing 'password'"
274 [ -z "$param_enc" ] && $(echo "$update_url" | grep "\[PARAMENC\]" >/dev/null 2>&1) && \
275 write_log 14 "Service section not configured correctly! Missing 'param_enc'"
276 [ -z "$param_opt" ] && $(echo "$update_url" | grep "\[PARAMOPT\]" >/dev/null 2>&1) && \
277 write_log 14 "Service section not configured correctly! Missing 'param_opt'"
278 }
279
280 # verify ip_source 'script' if script is configured and executable
281 if [ "$ip_source" = "script" ]; then
282 set -- $ip_script #handling script with parameters, we need a trick
283 [ -z "$1" ] && write_log 14 "No script defined to detect local IP!"
284 [ -x "$1" ] || write_log 14 "Script to detect local IP not executable!"
285 fi
286
287 # compute update interval in seconds
288 get_seconds CHECK_SECONDS ${check_interval:-10} ${check_unit:-"minutes"} # default 10 min
289 get_seconds FORCE_SECONDS ${force_interval:-72} ${force_unit:-"hours"} # default 3 days
290 get_seconds RETRY_SECONDS ${retry_interval:-60} ${retry_unit:-"seconds"} # default 60 sec
291 [ $CHECK_SECONDS -lt 300 ] && CHECK_SECONDS=300 # minimum 5 minutes
292 [ $FORCE_SECONDS -gt 0 -a $FORCE_SECONDS -lt $CHECK_SECONDS ] && FORCE_SECONDS=$CHECK_SECONDS # FORCE_SECONDS >= CHECK_SECONDS or 0
293 write_log 7 "check interval: $CHECK_SECONDS seconds"
294 write_log 7 "force interval: $FORCE_SECONDS seconds"
295 write_log 7 "retry interval: $RETRY_SECONDS seconds"
296 write_log 7 "retry max count : $retry_max_count times"
297
298 # kill old process if it exists & set new pid file
299 stop_section_processes "$SECTION_ID"
300 [ $? -gt 0 ] && write_log 7 "'SIGTERM' was send to old process" || write_log 7 "No old process"
301 echo $$ > $PIDFILE
302
303 # determine when the last update was
304 # the following lines should prevent multiple updates if hotplug fires multiple startups
305 # as described in Ticket #7820, but did not function if never an update take place
306 # i.e. after a reboot (/var is linked to /tmp)
307 # using uptime as reference because date might not be updated via NTP client
308 get_uptime CURR_TIME
309 [ -e "$UPDFILE" ] && {
310 LAST_TIME=$(cat $UPDFILE)
311 # check also LAST > CURR because link of /var/run to /tmp might be removed
312 # i.e. boxes with larger filesystems
313 [ -z "$LAST_TIME" ] && LAST_TIME=0
314 [ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME=0
315 }
316 if [ $LAST_TIME -eq 0 ]; then
317 write_log 7 "last update: never"
318 else
319 EPOCH_TIME=$(( $(date +%s) - $CURR_TIME + $LAST_TIME ))
320 EPOCH_TIME="date -d @$EPOCH_TIME +'$ddns_dateformat'"
321 write_log 7 "last update: $(eval $EPOCH_TIME)"
322 fi
323
324 # verify DNS server
325 [ -n "$dns_server" ] && verify_dns "$dns_server"
326
327 # verify Proxy server and set environment
328 [ -n "$proxy" ] && {
329 verify_proxy "$proxy" && {
330 # everything ok set proxy
331 export HTTP_PROXY="http://$proxy"
332 export HTTPS_PROXY="http://$proxy"
333 export http_proxy="http://$proxy"
334 export https_proxy="http://$proxy"
335 }
336 }
337
338 # let's check if there is already an IP registered on the web
339 get_registered_ip REGISTERED_IP "NO_RETRY"
340 ERR_LAST=$?
341 # No error or No IP set otherwise retry
342 [ $ERR_LAST -eq 0 -o $ERR_LAST -eq 127 ] || get_registered_ip REGISTERED_IP
343 # on IPv6 we use expanded version to be shure when comparing
344 [ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP
345
346 # loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
347 write_log 6 "Starting main loop at $(eval $DATE_PROG)"
348 while : ; do
349
350 get_local_ip LOCAL_IP # read local IP
351 [ $use_ipv6 -eq 1 ] && expand_ipv6 "$LOCAL_IP" LOCAL_IP # on IPv6 we use expanded version
352
353 # prepare update
354 # never updated or forced immediate then NEXT_TIME = 0
355 [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
356 && NEXT_TIME=0 \
357 || NEXT_TIME=$(( $LAST_TIME + $FORCE_SECONDS ))
358
359 get_uptime CURR_TIME # get current uptime
360
361 # send update when current time > next time or local ip different from registered ip
362 if [ $CURR_TIME -ge $NEXT_TIME -o "$LOCAL_IP" != "$REGISTERED_IP" ]; then
363 if [ $VERBOSE -gt 2 ]; then
364 write_log 7 "Verbose Mode: $VERBOSE - NO UPDATE send"
365 elif [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
366 write_log 7 "Update needed - L: '$LOCAL_IP' <> R: '$REGISTERED_IP'"
367 else
368 write_log 7 "Forced Update - L: '$LOCAL_IP' == R: '$REGISTERED_IP'"
369 fi
370
371 ERR_LAST=0
372 [ $VERBOSE -lt 3 ] && {
373 # only send if VERBOSE < 3
374 send_update "$LOCAL_IP"
375 ERR_LAST=$? # save return value
376 }
377
378 # error sending local IP to provider
379 # we have no communication error (handled inside send_update/do_transfer)
380 # but update was not recognized
381 # do NOT retry after RETRY_SECONDS, do retry after CHECK_SECONDS
382 # to early retrys will block most DDNS provider
383 # providers answer is checked inside send_update() function
384 if [ $ERR_LAST -eq 0 ]; then
385 get_uptime LAST_TIME # we send update, so
386 echo $LAST_TIME > $UPDFILE # save LASTTIME to file
387 [ "$LOCAL_IP" != "$REGISTERED_IP" ] \
388 && write_log 6 "Update successful - IP '$LOCAL_IP' send" \
389 || write_log 6 "Forced update successful - IP: '$LOCAL_IP' send"
390 elif [ $ERR_LAST -eq 127 ]; then
391 write_log 3 "No update send to DDNS Provider"
392 else
393 write_log 3 "IP update not accepted by DDNS Provider"
394 fi
395 fi
396
397 # now we wait for check interval before testing if update was recognized
398 # only sleep if VERBOSE <= 2 because otherwise nothing was send
399 [ $VERBOSE -le 2 ] && {
400 write_log 7 "Waiting $CHECK_SECONDS seconds (Check Interval)"
401 sleep $CHECK_SECONDS &
402 PID_SLEEP=$!
403 wait $PID_SLEEP # enable trap-handler
404 PID_SLEEP=0
405 } || write_log 7 "Verbose Mode: $VERBOSE - NO Check Interval waiting"
406
407 REGISTERED_IP="" # clear variable
408 get_registered_ip REGISTERED_IP # get registered/public IP
409 [ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP # on IPv6 we use expanded version
410
411 # IP's are still different
412 if [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
413 if [ $VERBOSE -le 1 ]; then # VERBOSE <=1 then retry
414 ERR_UPDATE=$(( $ERR_UPDATE + 1 ))
415 [ $retry_max_count -gt 0 -a $ERR_UPDATE -gt $retry_max_count ] && \
416 write_log 14 "Updating IP at DDNS provider failed after $retry_max_count retries"
417 write_log 4 "Updating IP at DDNS provider failed - starting retry $ERR_UPDATE/$retry_max_count"
418 continue # loop to beginning
419 else
420 write_log 4 "Updating IP at DDNS provider failed"
421 write_log 7 "Verbose Mode: $VERBOSE - NO retry"; exit 1
422 fi
423 else
424 # we checked successful the last update
425 ERR_UPDATE=0 # reset error counter
426 fi
427
428 # force_update=0 or VERBOSE > 1 - leave here
429 [ $VERBOSE -gt 1 ] && write_log 7 "Verbose Mode: $VERBOSE - NO reloop"
430 [ $FORCE_SECONDS -eq 0 ] && write_log 6 "Configured to run once"
431 [ $VERBOSE -gt 1 -o $FORCE_SECONDS -eq 0 ] && exit 0
432
433 write_log 6 "Rerun IP check at $(eval $DATE_PROG)"
434 done
435 # we should never come here there must be a programming error
436 write_log 12 "Error in 'dynamic_dns_updater.sh - program coding error"