2 # /usr/lib/ddns/dynamic_dns_updater.sh
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>
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
16 . $
(dirname $0)/dynamic_dns_functions.sh
# global vars are also defined here
22 $MYPROG [options] -- command
25 start Start SECTION or NETWORK or all
26 stop Stop NETWORK or all
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
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
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
48 printf %s
\\n
"$MYPROG: $@" >&2
53 while getopts ":hv:n:S:V" OPT
; do
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";;
65 shift $
((OPTIND
- 1 )) # OPTIND is 1 based
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"
73 if [ -n "$NETWORK" ]; then
74 start_daemon_for_all_ddns_sections
"$NETWORK"
77 if [ -z "$SECTION_ID" ]; then
78 start_daemon_for_all_ddns_sections
83 if [ -n "$INTERFACE" ]; then
84 stop_daemon_for_all_ddns_sections
"$NETWORK"
87 stop_daemon_for_all_ddns_sections
93 killall
-1 dynamic_dns_updater.sh
2>/dev
/null
96 *) usage_err
"unknown command - $1";;
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
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
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
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.
125 # config_get <variable> $SECTION_ID <option>
127 # defined options (also used as variable):
129 # enabled self-explanatory
130 # interface network interface used by hotplug.d i.e. 'wan' or 'wan6'
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
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
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
146 # use_syslog log activity to syslog
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
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
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
160 # retry_interval if error was detected retry in
161 # retry_unit 'days' 'hours' 'minutes' 'seconds'
162 # retry_count number of retries before scripts stops
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
172 # some functionality needs
173 # - GNU Wget or cURL installed for sending updates to DDNS service
174 # - BIND host installed to detect Registered IP
176 ################################################################################
178 load_all_config_options
"ddns" "$SECTION_ID"
179 ERR_LAST
=$?
# save return code - equal 0 if SECTION_ID found
181 # set defaults if not defined
182 [ -z "$enabled" ] && enabled
=0
183 [ -z "$retry_count" ] && retry_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"
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"
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"
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)"
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'";;
229 # check enabled state otherwise we don't need to continue
230 [ $enabled -eq 0 ] && write_log
14 "Service section disabled!"
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
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!"
246 # temporary needed to convert existing uci settings
247 [ -z "$lookup_host" ] && {
248 uci
-q set ddns.
$SECTION_ID.lookup_host
="$domain"
250 lookup_host
="$domain"
252 # later versions only check if configured correctly
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'"
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" ""
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"
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'"
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!"
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 counter : $retry_count times"
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"
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
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
316 if [ $LAST_TIME -eq 0 ]; then
317 write_log
7 "last update: never"
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)"
325 [ -n "$dns_server" ] && verify_dns
"$dns_server"
327 # verify Proxy server and set environment
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"
338 # let's check if there is already an IP registered on the web
339 get_registered_ip REGISTERED_IP
"NO_RETRY"
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
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)"
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
354 # never updated or forced immediate then NEXT_TIME = 0
355 [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
357 || NEXT_TIME
=$
(( $LAST_TIME + $FORCE_SECONDS ))
359 get_uptime CURR_TIME
# get current uptime
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'"
368 write_log
7 "Forced Update - L: '$LOCAL_IP' == R: '$REGISTERED_IP'"
372 [ $VERBOSE -lt 3 ] && {
373 # only send if VERBOSE < 3
374 send_update
"$LOCAL_IP"
375 ERR_LAST
=$?
# save return value
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"
393 write_log
3 "IP update not accepted by DDNS Provider"
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 &
403 wait $PID_SLEEP # enable trap-handler
405 } || write_log
7 "Verbose Mode: $VERBOSE - NO Check Interval waiting"
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
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_count -gt 0 -a $ERR_UPDATE -gt $retry_count ] && \
416 write_log
14 "Updating IP at DDNS provider failed after $retry_count retries"
417 write_log
4 "Updating IP at DDNS provider failed - starting retry $ERR_UPDATE/$retry_count"
418 continue # loop to beginning
420 write_log
4 "Updating IP at DDNS provider failed"
421 write_log
7 "Verbose Mode: $VERBOSE - NO retry"; exit 1
424 # we checked successful the last update
425 ERR_UPDATE
=0 # reset error counter
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
433 write_log
6 "Rerun IP check at $(eval $DATE_PROG)"
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"