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