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 -d dry run (don't send any changes)
46 printf %s
\\n
"$MYPROG: $@" >&2
51 while getopts ":hv:dn:S:V" OPT
; do
57 S
) SECTION_ID
=$OPTARG;;
58 V
) printf %s
\\n
"ddns-scripts $VERSION"; exit 0;;
59 :) usage_err
"option -$OPTARG missing argument";;
60 \?) usage_err
"invalid option -$OPTARG";;
61 *) usage_err
"unhandled option -$OPT $OPTARG";;
64 shift $
((OPTIND
- 1 )) # OPTIND is 1 based
66 [ -n "$NETWORK" -a -n "$SECTION_ID" ] && usage_err
"use either option '-N' or '-S' not both"
67 [ $# -eq 0 ] && usage_err
"missing command"
68 [ $# -gt 1 ] && usage_err
"to much commands"
72 if [ -n "$NETWORK" ]; then
73 start_daemon_for_all_ddns_sections
"$NETWORK"
76 if [ -z "$SECTION_ID" ]; then
77 start_daemon_for_all_ddns_sections
82 if [ -n "$INTERFACE" ]; then
83 stop_daemon_for_all_ddns_sections
"$NETWORK"
86 stop_daemon_for_all_ddns_sections
92 killall
-1 dynamic_dns_updater.sh
2>/dev
/null
95 *) usage_err
"unknown command - $1";;
99 PIDFILE
="$ddns_rundir/$SECTION_ID.pid" # Process ID file
100 UPDFILE
="$ddns_rundir/$SECTION_ID.update" # last update successful send (system uptime)
101 DATFILE
="$ddns_rundir/$SECTION_ID.dat" # save stdout data of WGet and other extern programs called
102 ERRFILE
="$ddns_rundir/$SECTION_ID.err" # save stderr output of WGet and other extern programs called
103 IPFILE
="$ddns_rundir/$SECTION_ID.ip" #
104 LOGFILE
="$ddns_logdir/$SECTION_ID.log" # log file
106 # VERBOSE > 1 delete logfile if exist to create an empty one
107 # only with this data of this run for easier diagnostic
108 # new one created by write_log function
109 [ $VERBOSE -gt 1 -a -f $LOGFILE ] && rm -f $LOGFILE
110 # Previously -v 3 could we used for dry run
111 [ $VERBOSE -ge 3 ] && DRY_RUN
=1
114 trap "trap_handler 0 \$?" 0 # handle script exit with exit status
115 trap "trap_handler 1" 1 # SIGHUP Hangup / reload config
116 trap "trap_handler 2" 2 # SIGINT Terminal interrupt
117 trap "trap_handler 3" 3 # SIGQUIT Terminal quit
118 # trap "trap_handler 9" 9 # SIGKILL no chance to trap
119 trap "trap_handler 15" 15 # SIGTERM Termination
121 ################################################################################
122 # Leave this comment here, to clearly document variable names that are expected/possible
123 # Use load_all_config_options to load config options, which is a much more flexible solution.
126 # config_get <variable> $SECTION_ID <option>
128 # defined options (also used as variable):
130 # enabled self-explanatory
131 # interface network interface used by hotplug.d i.e. 'wan' or 'wan6'
133 # service_name Which DDNS service do you use or "custom"
134 # update_url URL to use to update your "custom" DDNS service
135 # update_script SCRIPT to use to update your "custom" DDNS service
137 # lookup_host FQDN of ONE of your at DDNS service defined host / required to validate if IP update happen/necessary
138 # domain Nomally your DDNS hostname / replace [DOMAIN] in update_url
139 # username Username of your DDNS service account / urlenceded and replace [USERNAME] in update_url
140 # password Password of your DDNS service account / urlencoded and replace [PASSWORD] in update_url
141 # param_enc Optional parameter for (later) usage / urlencoded and replace [PARAMENC] in update_url
142 # param_opt Optional parameter for (later) usage / replace [PARAMOPT] in update_url
144 # use_https use HTTPS to update DDNS service
145 # cacert file or directory where HTTPS can find certificates to verify server; 'IGNORE' ignore check of server certificate
147 # use_syslog log activity to syslog
149 # ip_source source to detect current IP ('network' or 'web' or 'script' or 'interface')
150 # ip_network local defined network to read IP from i.e. 'wan' or 'wan6'
151 # ip_url URL to read current IP from i.e. http://checkip.dyndns.com/ or http://checkipv6.dyndns.com/
152 # ip_script full path and name of your script to detect current IP
153 # ip_interface physical interface to use for detecting
155 # check_interval check for changes every !!! checks below 10 minutes make no sense because the Internet
156 # check_unit 'days' 'hours' 'minutes' !!! needs about 5-10 minutes to sync an IP-change for an DNS entry
158 # force_interval force to send an update to your service if no change was detected
159 # force_unit 'days' 'hours' 'minutes' !!! force_interval="0" runs this script once for use i.e. with cron
161 # retry_interval if error was detected retry in
162 # retry_unit 'days' 'hours' 'minutes' 'seconds'
163 # retry_max_count number of retries before scripts stops
165 # use_ipv6 detecting/sending IPv6 address
166 # force_ipversion force usage of IPv4 or IPv6 for the whole detection and update communication
167 # dns_server using a non default dns server to get Registered IP from Internet
168 # force_dnstcp force communication with DNS server via TCP instead of default UDP
169 # proxy using a proxy for communication !!! ALSO used to detect current IP via web => return proxy's IP !!!
170 # use_logfile self-explanatory "/var/log/ddns/$SECTION_ID.log"
171 # is_glue the record that should be updated is a glue record
173 # some functionality needs
174 # - GNU Wget or cURL installed for sending updates to DDNS service
175 # - BIND host installed to detect Registered IP
177 ################################################################################
179 load_all_config_options
"ddns" "$SECTION_ID"
180 ERR_LAST
=$?
# save return code - equal 0 if SECTION_ID found
182 # set defaults if not defined
183 [ -z "$enabled" ] && enabled
=0
184 [ -z "$retry_max_count" ] && retry_max_count
=0 # endless retry
185 [ -z "$use_syslog" ] && use_syslog
=2 # syslog "Notice"
186 [ -z "$use_https" ] && use_https
=0 # not use https
187 [ -z "$use_logfile" ] && use_logfile
=1 # use logfile by default
188 [ -z "$use_ipv6" ] && use_ipv6
=0 # use IPv4 by default
189 [ -z "$force_ipversion" ] && force_ipversion
=0 # default let system decide
190 [ -z "$force_dnstcp" ] && force_dnstcp
=0 # default UDP
191 [ -z "$ip_source" ] && ip_source
="network"
192 [ -z "$is_glue" ] && is_glue
=0 # default the ddns record is not a glue record
193 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 0 ] && ip_network
="wan" # IPv4: default wan
194 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 1 ] && ip_network
="wan6" # IPv6: default wan6
195 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 0 ] && ip_url
="http://checkip.dyndns.com"
196 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 1 ] && ip_url
="http://checkipv6.dyndns.com"
197 [ "$ip_source" = "interface" -a -z "$ip_interface" ] && ip_interface
="eth1"
199 # url encode username (might be email or something like this)
200 # and password (might have special chars for security reason)
201 # and optional parameter "param_enc"
202 [ -n "$username" ] && urlencode URL_USER
"$username"
203 [ -n "$password" ] && urlencode URL_PASS
"$password"
204 [ -n "$param_enc" ] && urlencode URL_PENC
"$param_enc"
206 # SECTION_ID does not exists
207 [ $ERR_LAST -ne 0 ] && {
208 [ $VERBOSE -le 1 ] && VERBOSE
=2 # force console out and logfile output
209 [ -f $LOGFILE ] && rm -f $LOGFILE # clear logfile before first entry
210 write_log
7 "************ ************** ************** **************"
211 write_log
5 "PID '$$' started at $(eval $DATE_PROG)"
212 write_log
7 "ddns version : $VERSION"
213 write_log
7 "uci configuration:${N}$(uci -q show ddns | grep '=service' | sort)"
214 write_log
14 "Service section '$SECTION_ID' not defined"
217 write_log
7 "************ ************** ************** **************"
218 write_log
5 "PID '$$' started at $(eval $DATE_PROG)"
219 write_log
7 "ddns version : $VERSION"
220 write_log
7 "uci configuration:${N}$(uci -q show ddns.$SECTION_ID | sort)"
221 # write_log 7 "ddns version : $(opkg list-installed ddns-scripts | cut -d ' ' -f 3)"
223 0) write_log
7 "verbose mode : 0 - run normal, NO console output";;
224 1) write_log
7 "verbose mode : 1 - run normal, console mode";;
225 2) write_log
7 "verbose mode : 2 - run once, NO retry on error";;
226 *) write_log
14 "error detecting VERBOSE '$VERBOSE'";;
228 [ $DRY_RUN -ge 1 ] && write_log
7 "Dry Run: NOT sending update"
230 # check enabled state otherwise we don't need to continue
231 [ $enabled -eq 0 ] && write_log
14 "Service section disabled!"
233 # determine what update url we're using if a service_name is supplied
234 # otherwise update_url is set inside configuration (custom update url)
235 # or update_script is set inside configuration (custom update script)
236 [ -n "$service_name" ] && {
237 # Check first if we have a custom service provider with this name
238 get_service_data
"$service_name" "/usr/share/ddns/custom" update_url update_script UPD_ANSWER
239 if [ "$?" != "0" ]; then
240 get_service_data
"$service_name" "/usr/share/ddns/default" update_url update_script UPD_ANSWER
244 [ -z "$update_url" -a -z "$update_script" ] && write_log
14 "No update_url found/defined or no update_script found/defined!"
245 [ -n "$update_script" -a ! -f "$update_script" ] && write_log
14 "Custom update_script not found!"
247 # temporary needed to convert existing uci settings
248 [ -z "$lookup_host" ] && {
249 uci
-q set ddns.
$SECTION_ID.lookup_host
="$domain"
251 lookup_host
="$domain"
253 # later versions only check if configured correctly
255 # without lookup host and possibly other required options we can do nothing for you
256 [ -z "$lookup_host" ] && write_log
14 "Service section not configured correctly! Missing 'lookup_host'"
258 # verify validity of variables
259 [ -n "$lookup_host" ] && sanitize_variable lookup_host
"$DNS_CHARSET" ""
260 [ -n "$dns_server" ] && sanitize_variable dns_server
"$DNS_CHARSET" ""
261 [ -n "$domain" ] && sanitize_variable domain
"$DNS_CHARSET_DOMAIN" ""
263 # Filter shell escape characters, if these are required in the URL, they
264 # can still be passed url encoded
265 [ -n "$param_opt" ] && sanitize_variable param_opt
"" "$SHELL_ESCAPE"
267 [ -n "$update_url" ] && {
268 # only check if update_url is given, update_scripts have to check themselves
269 [ -z "$domain" ] && $
(echo "$update_url" |
grep "\[DOMAIN\]" >/dev
/null
2>&1) && \
270 write_log
14 "Service section not configured correctly! Missing 'domain'"
271 [ -z "$username" ] && $
(echo "$update_url" |
grep "\[USERNAME\]" >/dev
/null
2>&1) && \
272 write_log
14 "Service section not configured correctly! Missing 'username'"
273 [ -z "$password" ] && $
(echo "$update_url" |
grep "\[PASSWORD\]" >/dev
/null
2>&1) && \
274 write_log
14 "Service section not configured correctly! Missing 'password'"
275 [ -z "$param_enc" ] && $
(echo "$update_url" |
grep "\[PARAMENC\]" >/dev
/null
2>&1) && \
276 write_log
14 "Service section not configured correctly! Missing 'param_enc'"
277 [ -z "$param_opt" ] && $
(echo "$update_url" |
grep "\[PARAMOPT\]" >/dev
/null
2>&1) && \
278 write_log
14 "Service section not configured correctly! Missing 'param_opt'"
281 # verify ip_source 'script' if script is configured and executable
282 if [ "$ip_source" = "script" ]; then
283 set -- $ip_script #handling script with parameters, we need a trick
284 [ -z "$1" ] && write_log
14 "No script defined to detect current IP!"
285 [ -x "$1" ] || write_log
14 "Script to detect current IP not executable!"
288 # compute update interval in seconds
289 get_seconds CHECK_SECONDS
${check_interval:-10} ${check_unit:-"minutes"} # default 10 min
290 get_seconds FORCE_SECONDS
${force_interval:-72} ${force_unit:-"hours"} # default 3 days
291 get_seconds RETRY_SECONDS
${retry_interval:-60} ${retry_unit:-"seconds"} # default 60 sec
292 [ $CHECK_SECONDS -lt 300 ] && CHECK_SECONDS
=300 # minimum 5 minutes
293 [ $FORCE_SECONDS -gt 0 -a $FORCE_SECONDS -lt $CHECK_SECONDS ] && FORCE_SECONDS
=$CHECK_SECONDS # FORCE_SECONDS >= CHECK_SECONDS or 0
294 write_log
7 "check interval: $CHECK_SECONDS seconds"
295 write_log
7 "force interval: $FORCE_SECONDS seconds"
296 write_log
7 "retry interval: $RETRY_SECONDS seconds"
297 write_log
7 "retry max count : $retry_max_count times"
299 # kill old process if it exists & set new pid file
300 stop_section_processes
"$SECTION_ID"
301 [ $?
-gt 0 ] && write_log
7 "'SIGTERM' was send to old process" || write_log
7 "No old process"
304 # determine when the last update was
305 # the following lines should prevent multiple updates if hotplug fires multiple startups
306 # as described in Ticket #7820, but did not function if never an update take place
307 # i.e. after a reboot (/var is linked to /tmp)
308 # using uptime as reference because date might not be updated via NTP client
310 [ -e "$UPDFILE" ] && {
311 LAST_TIME
=$
(cat $UPDFILE)
312 # check also LAST > CURR because link of /var/run to /tmp might be removed
313 # i.e. boxes with larger filesystems
314 [ -z "$LAST_TIME" ] && LAST_TIME
=0
315 [ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME
=0
317 if [ $LAST_TIME -eq 0 ]; then
318 write_log
7 "last update: never"
320 EPOCH_TIME
=$
(( $
(date +%s
) - $CURR_TIME + $LAST_TIME ))
321 EPOCH_TIME
="date -d @$EPOCH_TIME +'$ddns_dateformat'"
322 write_log
7 "last update: $(eval $EPOCH_TIME)"
326 [ -n "$dns_server" ] && verify_dns
"$dns_server"
328 # verify Proxy server and set environment
330 verify_proxy
"$proxy" && {
331 # everything ok set proxy
332 export HTTP_PROXY
="http://$proxy"
333 export HTTPS_PROXY
="http://$proxy"
334 export http_proxy
="http://$proxy"
335 export https_proxy
="http://$proxy"
339 # let's check if there is already an IP registered on the web
340 get_registered_ip REGISTERED_IP
"NO_RETRY"
342 # No error or No IP set otherwise retry
343 [ $ERR_LAST -eq 0 -o $ERR_LAST -eq 127 ] || get_registered_ip REGISTERED_IP
344 # on IPv6 we use expanded version to be shure when comparing
345 [ $use_ipv6 -eq 1 ] && expand_ipv6
"$REGISTERED_IP" REGISTERED_IP
347 # loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
348 write_log
6 "Starting main loop at $(eval $DATE_PROG)"
351 get_current_ip CURRENT_IP
# read current IP
352 [ $use_ipv6 -eq 1 ] && expand_ipv6
"$CURRENT_IP" CURRENT_IP
# on IPv6 we use expanded version
355 # never updated or forced immediate then NEXT_TIME = 0
356 [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
358 || NEXT_TIME
=$
(( $LAST_TIME + $FORCE_SECONDS ))
360 get_uptime CURR_TIME
# get current uptime
362 # send update when current time > next time or current ip different from registered ip
363 if [ $CURR_TIME -ge $NEXT_TIME -o "$CURRENT_IP" != "$REGISTERED_IP" ]; then
364 if [ $DRY_RUN -ge 1 ]; then
365 write_log
7 "Dry Run: NO UPDATE send"
366 elif [ "$CURRENT_IP" != "$REGISTERED_IP" ]; then
367 write_log
7 "Update needed - L: '$CURRENT_IP' <> R: '$REGISTERED_IP'"
369 write_log
7 "Forced Update - L: '$CURRENT_IP' == R: '$REGISTERED_IP'"
373 [ $DRY_RUN -eq 0 ] && {
374 send_update
"$CURRENT_IP"
375 ERR_LAST
=$?
# save return value
378 # error sending current 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 [ "$CURRENT_IP" != "$REGISTERED_IP" ] \
388 && write_log
6 "Update successful - IP '$CURRENT_IP' send" \
389 || write_log
6 "Forced update successful - IP: '$CURRENT_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 [ $DRY_RUN -eq 0 ] && {
399 write_log
7 "Waiting $CHECK_SECONDS seconds (Check Interval)"
400 sleep $CHECK_SECONDS &
402 wait $PID_SLEEP # enable trap-handler
404 } || write_log
7 "Dry Run: NO Check Interval waiting"
406 REGISTERED_IP
="" # clear variable
407 get_registered_ip REGISTERED_IP
# get registered/public IP
408 [ $use_ipv6 -eq 1 ] && expand_ipv6
"$REGISTERED_IP" REGISTERED_IP
# on IPv6 we use expanded version
410 # IP's are still different
411 if [ "$CURRENT_IP" != "$REGISTERED_IP" ]; then
412 if [ $VERBOSE -le 1 ]; then # VERBOSE <=1 then retry
413 RETRY_COUNT
=$
(( $RETRY_COUNT + 1 ))
414 [ $retry_max_count -gt 0 -a $RETRY_COUNT -gt $retry_max_count ] && \
415 write_log
14 "Updating IP at DDNS provider failed after $retry_max_count retries"
416 write_log
4 "Updating IP at DDNS provider failed - starting retry $RETRY_COUNT/$retry_max_count"
417 continue # loop to beginning
419 write_log
4 "Updating IP at DDNS provider failed"
420 write_log
7 "Verbose Mode: $VERBOSE - NO retry"; exit 1
423 # we checked successful the last update
424 RETRY_COUNT
=0 # reset error counter
427 # force_update=0 or VERBOSE > 1 - leave here
428 [ $VERBOSE -gt 1 ] && write_log
7 "Verbose Mode: $VERBOSE - NO reloop"
429 [ $FORCE_SECONDS -eq 0 ] && write_log
6 "Configured to run once"
430 [ $VERBOSE -gt 1 -o $FORCE_SECONDS -eq 0 ] && exit 0
432 write_log
6 "Rerun IP check at $(eval $DATE_PROG)"
434 # we should never come here there must be a programming error
435 write_log
12 "Error in 'dynamic_dns_updater.sh - program coding error"