Merge pull request #475 from antonlacon/minidlna-1.1.x
[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 # Original written by Eric Paul Bishop, January 2008
5 # Distributed under the terms of the GNU General Public License (GPL) version 2.0
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 #
9 # extended and partial rewritten in August 2014
10 # by Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
11 # to support:
12 # - IPv6 DDNS services
13 # - DNS Server to retrieve registered IP including TCP transport (Ticket 7820)
14 # - Proxy Server to send out updates
15 # - force_interval=0 to run once (Luci Ticket 538)
16 # - the usage of BIND's host command instead of BusyBox's nslookup if installed
17 # - extended Verbose Mode and log file support for better error detection
18 # - wait for interface to fully come up, before the first update is done
19 #
20 # variables in small chars are read from /etc/config/ddns
21 # variables in big chars are defined inside these scripts as global vars
22 # variables in big chars beginning with "__" are local defined inside functions only
23 #set -vx #script debugger
24
25 [ $# -lt 1 -o -n "${2//[0-3]/}" -o ${#2} -gt 1 ] && {
26 echo -e "\n USAGE:"
27 echo -e " $0 [SECTION] [VERBOSE_MODE]\n"
28 echo " [SECTION] - service section as defined in /etc/config/ddns"
29 echo " [VERBOSE_MODE] - '0' NO output to console"
30 echo " '1' output to console"
31 echo " '2' output to console AND logfile"
32 echo " + run once WITHOUT retry on error"
33 echo " '3' output to console AND logfile"
34 echo " + run once WITHOUT retry on error"
35 echo -e " + NOT sending update to DDNS service\n"
36 exit 1
37 }
38
39 . /usr/lib/ddns/dynamic_dns_functions.sh # global vars are also defined here
40
41 SECTION_ID="$1"
42 VERBOSE_MODE=${2:-1} # default mode is log to console
43
44 # set file names
45 PIDFILE="$RUNDIR/$SECTION_ID.pid" # Process ID file
46 UPDFILE="$RUNDIR/$SECTION_ID.update" # last update successful send (system uptime)
47 LOGFILE="$LOGDIR/$SECTION_ID.log" # log file
48
49 # VERBOSE_MODE > 1 delete logfile if exist to create an empty one
50 # only with this data of this run for easier diagnostic
51 # new one created by write_log function
52 [ $VERBOSE_MODE -gt 1 -a -f $LOGFILE ] && rm -f $LOGFILE
53
54 # TRAP handler
55 trap "trap_handler 0 \$?" 0 # handle script exit with exit status
56 trap "trap_handler 1" 1 # SIGHUP Hangup / reload config
57 trap "trap_handler 2" 2 # SIGINT Terminal interrupt
58 trap "trap_handler 3" 3 # SIGQUIT Terminal quit
59 #trap "trap_handler 9" 9 # SIGKILL no chance to trap
60 trap "trap_handler 15" 15 # SIGTERM Termination
61
62 ################################################################################
63 # Leave this comment here, to clearly document variable names that are expected/possible
64 # Use load_all_config_options to load config options, which is a much more flexible solution.
65 #
66 # config_load "ddns"
67 # config_get <variable> $SECTION_ID <option>
68 #
69 # defined options (also used as variable):
70 #
71 # enable self-explanatory
72 # interface network interface used by hotplug.d i.e. 'wan' or 'wan6'
73 #
74 # service_name Which DDNS service do you use or "custom"
75 # update_url URL to use to update your "custom" DDNS service
76 # update_script SCRIPT to use to update your "custom" DDNS service
77 #
78 # domain Your DNS name / replace [DOMAIN] in update_url
79 # username Username of your DDNS service account / replace [USERNAME] in update_url
80 # password Password of your DDNS service account / replace [PASSWORD] in update_url
81 #
82 # use_https use HTTPS to update DDNS service
83 # cacert file or directory where HTTPS can find certificates to verify server; 'IGNORE' ignore check of server certificate
84 #
85 # use_syslog log activity to syslog
86 #
87 # ip_source source to detect current local IP ('network' or 'web' or 'script' or 'interface')
88 # ip_network local defined network to read IP from i.e. 'wan' or 'wan6'
89 # ip_url URL to read local address from i.e. http://checkip.dyndns.com/ or http://checkipv6.dyndns.com/
90 # ip_script full path and name of your script to detect local IP
91 # ip_interface physical interface to use for detecting
92 #
93 # check_interval check for changes every !!! checks below 10 minutes make no sense because the Internet
94 # check_unit 'days' 'hours' 'minutes' !!! needs about 5-10 minutes to sync an IP-change for an DNS entry
95 #
96 # force_interval force to send an update to your service if no change was detected
97 # force_unit 'days' 'hours' 'minutes' !!! force_interval="0" runs this script once for use i.e. with cron
98 #
99 # retry_interval if error was detected retry in
100 # retry_unit 'days' 'hours' 'minutes' 'seconds'
101 # retry_count #NEW# number of retries before scripts stops
102 #
103 # use_ipv6 #NEW# detecting/sending IPv6 address
104 # force_ipversion #NEW# force usage of IPv4 or IPv6 for the whole detection and update communication
105 # dns_server #NEW# using a non default dns server to get Registered IP from Internet
106 # force_dnstcp #NEW# force communication with DNS server via TCP instead of default UDP
107 # proxy #NEW# using a proxy for communication !!! ALSO used to detect local IP via web => return proxy's IP !!!
108 # use_logfile #NEW# self-explanatory "/var/log/ddns/$SECTION_ID.log"
109 #
110 # some functionality needs
111 # - GNU Wget or cURL installed for sending updates to DDNS service
112 # - BIND host installed to detect Registered IP
113 #
114 ################################################################################
115
116 # verify and load SECTION_ID is exists
117 [ "$(uci_get ddns $SECTION_ID)" != "service" ] && {
118 [ $VERBOSE_MODE -le 1 ] && VERBOSE_MODE=2 # force console out and logfile output
119 [ -f $LOGFILE ] && rm -f $LOGFILE # clear logfile before first entry
120 write_log 7 "************ ************** ************** **************"
121 write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
122 write_log 7 "uci configuration:\n$(uci -q show ddns | grep '=service' | sort)"
123 write_log 14 "Service section '$SECTION_ID' not defined"
124 }
125 load_all_config_options "ddns" "$SECTION_ID"
126
127 write_log 7 "************ ************** ************** **************"
128 write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
129 write_log 7 "uci configuraion:\n$(uci -q show ddns.$SECTION_ID | sort)"
130 case $VERBOSE_MODE in
131 0) write_log 7 "verbose mode : 0 - run normal, NO console output";;
132 1) write_log 7 "verbose mode : 1 - run normal, console mode";;
133 2) write_log 7 "verbose mode : 2 - run once, NO retry on error";;
134 3) write_log 7 "verbose mode : 3 - run once, NO retry on error, NOT sending update";;
135 *) write_log 14 "error detecting VERBOSE_MODE '$VERBOSE_MODE'";;
136 esac
137
138 # set defaults if not defined
139 [ -z "$enabled" ] && enabled=0
140 [ -z "$retry_count" ] && retry_count=5
141 [ -z "$use_syslog" ] && use_syslog=0 # not use syslog
142 [ -z "$use_https" ] && use_https=0 # not use https
143 [ -z "$use_logfile" ] && use_logfile=1 # NEW - use logfile by default
144 [ -z "$use_ipv6" ] && use_ipv6=0 # NEW - use IPv4 by default
145 [ -z "$force_ipversion" ] && force_ipversion=0 # NEW - default let system decide
146 [ -z "$force_dnstcp" ] && force_dnstcp=0 # NEW - default UDP
147 [ -z "$ip_source" ] && ip_source="network"
148 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 0 ] && ip_network="wan" # IPv4: default wan
149 [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 1 ] && ip_network="wan6" # IPv6: default wan6
150 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 0 ] && ip_url="http://checkip.dyndns.com"
151 [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 1 ] && ip_url="http://checkipv6.dyndns.com"
152 [ "$ip_source" = "interface" -a -z "$ip_interface" ] && ip_interface="eth1"
153
154 # check enabled state otherwise we don't need to continue
155 [ $enabled -eq 0 ] && write_log 14 "Service section disabled!"
156
157 # without domain or username or password we can do nothing for you
158 [ -z "$domain" -o -z "$username" -o -z "$password" ] && write_log 14 "Service section not correctly configured!"
159 urlencode URL_USER "$username" # encode username, might be email or something like this
160 urlencode URL_PASS "$password" # encode password, might have special chars for security reason
161
162 # verify ip_source script if configured and executable
163 if [ "$ip_source" = "script" ]; then
164 set -- $ip_script #handling script with parameters, we need a trick
165 [ -z "$1" ] && write_log 14 "No script defined to detect local IP!"
166 [ -x "$1" ] || write_log 14 "Script to detect local IP not executable!"
167 fi
168
169 # compute update interval in seconds
170 get_seconds CHECK_SECONDS ${check_interval:-10} ${check_unit:-"minutes"} # default 10 min
171 get_seconds FORCE_SECONDS ${force_interval:-72} ${force_unit:-"hours"} # default 3 days
172 get_seconds RETRY_SECONDS ${retry_interval:-60} ${retry_unit:-"seconds"} # default 60 sec
173 [ $CHECK_SECONDS -lt 300 ] && CHECK_SECONDS=300 # minimum 5 minutes
174 [ $FORCE_SECONDS -gt 0 -a $FORCE_SECONDS -lt $CHECK_SECONDS ] && FORCE_SECONDS=$CHECK_SECONDS # FORCE_SECONDS >= CHECK_SECONDS or 0
175 write_log 7 "check interval: $CHECK_SECONDS seconds"
176 write_log 7 "force interval: $FORCE_SECONDS seconds"
177 write_log 7 "retry interval: $RETRY_SECONDS seconds"
178 write_log 7 "retry counter : $retry_count times"
179
180 # determine what update url we're using if a service_name is supplied
181 # otherwise update_url is set inside configuration (custom update url)
182 # or update_script is set inside configuration (custom update script)
183 [ -n "$service_name" ] && get_service_data update_url update_script
184 [ -z "$update_url" -a -z "$update_script" ] && write_log 14 "No update_url found/defined or no update_script found/defined!"
185 [ -n "$update_script" -a ! -f "$update_script" ] && write_log 14 "Custom update_script not found!"
186
187 #kill old process if it exists & set new pid file
188 if [ -d $RUNDIR ]; then
189 #if process for section is already running, stop it
190 stop_section_processes "$SECTION_ID"
191 [ $? -gt 0 ] && write_log 7 "Send 'SIGTERM' to old process" || write_log 7 "No old process"
192 else
193 #make dir since it doesn't exist
194 mkdir -p $RUNDIR
195 write_log 7 "No old process"
196 fi
197 echo $$ > $PIDFILE
198
199 # determine when the last update was
200 # the following lines should prevent multiple updates if hotplug fires multiple startups
201 # as described in Ticket #7820, but did not function if never an update take place
202 # i.e. after a reboot (/var is linked to /tmp)
203 # using uptime as reference because date might not be updated via NTP client
204 get_uptime CURR_TIME
205 [ -e "$UPDFILE" ] && {
206 LAST_TIME=$(cat $UPDFILE)
207 # check also LAST > CURR because link of /var/run to /tmp might be removed
208 # i.e. boxes with larger filesystems
209 [ -z "$LAST_TIME" ] && LAST_TIME=0
210 [ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME=0
211 }
212 if [ $LAST_TIME -eq 0 ]; then
213 write_log 7 "last update: never"
214 else
215 EPOCH_TIME=$(( $(date +%s) - CURR_TIME + LAST_TIME ))
216 EPOCH_TIME="date -d @$EPOCH_TIME +'$DATE_FORMAT'"
217 write_log 7 "last update: $(eval $EPOCH_TIME)"
218 fi
219
220 # we need time here because hotplug.d is fired by netifd
221 # but IP addresses are not set by DHCP/DHCPv6 etc.
222 write_log 7 "Waiting 10 seconds for interfaces to fully come up"
223 sleep 10 &
224 PID_SLEEP=$!
225 wait $PID_SLEEP # enable trap-handler
226 PID_SLEEP=0
227
228 # verify DNS server
229 [ -n "$dns_server" ] && verify_dns "$dns_server"
230
231 # verify Proxy server and set environment
232 [ -n "$proxy" ] && {
233 verify_proxy "$proxy" && {
234 # everything ok set proxy
235 export HTTP_PROXY="http://$proxy"
236 export HTTPS_PROXY="http://$proxy"
237 export http_proxy="http://$proxy"
238 export https_proxy="http://$proxy"
239 }
240 }
241
242 # let's check if there is already an IP registered at the web
243 # but ignore errors if not
244 get_registered_ip REGISTERED_IP "NO_RETRY"
245
246 # loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
247 write_log 6 "Starting main loop at $(eval $DATE_PROG)"
248 while : ; do
249
250 get_local_ip LOCAL_IP # read local IP
251
252 # prepare update
253 # never updated or forced immediate then NEXT_TIME = 0
254 [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
255 && NEXT_TIME=0 \
256 || NEXT_TIME=$(( $LAST_TIME + $FORCE_SECONDS ))
257
258 get_uptime CURR_TIME # get current uptime
259
260 # send update when current time > next time or local ip different from registered ip
261 if [ $CURR_TIME -ge $NEXT_TIME -o "$LOCAL_IP" != "$REGISTERED_IP" ]; then
262 if [ $VERBOSE_MODE -gt 2 ]; then
263 write_log 7 "Verbose Mode: $VERBOSE_MODE - NO UPDATE send"
264 elif [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
265 write_log 7 "Update needed - L: '$LOCAL_IP' <> R: '$REGISTERED_IP'"
266 else
267 write_log 7 "Forced Update - L: '$LOCAL_IP' == R: '$REGISTERED_IP'"
268 fi
269
270 ERR_LAST=0
271 [ $VERBOSE_MODE -lt 3 ] && {
272 # only send if VERBOSE_MODE < 3
273 send_update "$LOCAL_IP"
274 ERR_LAST=$? # save return value
275 }
276
277 # error sending local IP to provider
278 # we have no communication error (handled inside send_update/do_transfer)
279 # but update was not recognized
280 # do NOT retry after RETRY_SECONDS, do retry after CHECK_SECONDS
281 # to early retrys will block most DDNS provider
282 # providers answer is checked inside send_update() function
283 if [ $ERR_LAST -eq 0 ]; then
284 get_uptime LAST_TIME # we send update, so
285 echo $LAST_TIME > $UPDFILE # save LASTTIME to file
286 [ "$LOCAL_IP" != "$REGISTERED_IP" ] && write_log 6 "Update successful - IP '$LOCAL_IP' send"
287 [ "$LOCAL_IP" = "$REGISTERED_IP" ] || write_log 6 "Forced update successful - IP: '$LOCAL_IP' send"
288 else
289 write_log 3 "Can not update IP at DDNS Provider"
290 fi
291 fi
292
293 # now we wait for check interval before testing if update was recognized
294 # only sleep if VERBOSE_MODE <= 2 because otherwise nothing was send
295 [ $VERBOSE_MODE -le 2 ] && {
296 write_log 7 "Waiting $CHECK_SECONDS seconds (Check Interval)"
297 sleep $CHECK_SECONDS &
298 PID_SLEEP=$!
299 wait $PID_SLEEP # enable trap-handler
300 PID_SLEEP=0
301 } || write_log 7 "Verbose Mode: $VERBOSE_MODE - NO Check Interval waiting"
302
303 REGISTERED_IP="" # clear variable
304 get_registered_ip REGISTERED_IP # get registered/public IP
305
306 # IP's are still different
307 if [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
308 if [ $VERBOSE_MODE -le 1 ]; then # VERBOSE_MODE <=1 then retry
309 ERR_UPDATE=$(( $ERR_UPDATE + 1 ))
310 [ $ERR_UPDATE -gt $retry_count ] && write_log 14 "Updating IP at DDNS provider failed after $retry_count retries"
311 write_log 4 "Updating IP at DDNS provider failed - starting retry $ERR_UPDATE/$retry_count"
312 continue # loop to beginning
313 else
314 write_log 4 "Updating IP at DDNS provider failed"
315 write_log 7 "Verbose Mode: $VERBOSE_MODE - NO retry"; exit 1
316 fi
317 else
318 # we checked successful the last update
319 ERR_UPDATE=0 # reset error counter
320 fi
321
322 # force_update=0 or VERBOSE_MODE > 1 - leave here
323 [ $VERBOSE_MODE -gt 1 ] && write_log 7 "Verbose Mode: $VERBOSE_MODE - NO reloop"
324 [ $FORCE_SECONDS -eq 0 ] && write_log 6 "Configured to run once"
325 [ $VERBOSE_MODE -gt 1 -o $FORCE_SECONDS -eq 0 ] && exit 0
326
327 write_log 6 "Rerun IP check at $(eval $DATE_PROG)"
328 done
329 # we should never come here there must be a programming error
330 write_log 12 "Error in 'dynamic_dns_updater.sh - program coding error"