Merge pull request #537 from dibdot/master
[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 case $VERBOSE_MODE in
130 0) write_log 7 "verbose mode '0' - run normal, NO console output";;
131 1) write_log 7 "verbose mode '1' - run normal, console mode";;
132 2) write_log 7 "verbose mode '2' - run once, NO retry on error";;
133 3) write_log 7 "verbose mode '3' - run once, NO retry on error, NOT sending update";;
134 *) write_log 14 "error detecting VERBOSE_MODE '$VERBOSE_MODE'";;
135 esac
136 write_log 7 "uci configuraion:\n$(uci -q show ddns.$SECTION_ID | sort)"
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 [ -z "$ip_script" ] && write_log 14 "No script defined to detect local IP!"
165 [ -x "$ip_script" ] || write_log 14 "Script to detect local IP not found or not executable!"
166 fi
167
168 # compute update interval in seconds
169 get_seconds CHECK_SECONDS ${check_interval:-10} ${check_unit:-"minutes"} # default 10 min
170 get_seconds FORCE_SECONDS ${force_interval:-72} ${force_unit:-"hours"} # default 3 days
171 get_seconds RETRY_SECONDS ${retry_interval:-60} ${retry_unit:-"seconds"} # default 60 sec
172 [ $CHECK_SECONDS -lt 300 ] && CHECK_SECONDS=300 # minimum 5 minutes
173 [ $FORCE_SECONDS -gt 0 -a $FORCE_SECONDS -lt $CHECK_SECONDS ] && FORCE_SECONDS=$CHECK_SECONDS # FORCE_SECONDS >= CHECK_SECONDS or 0
174 write_log 7 "check interval: $CHECK_SECONDS seconds"
175 write_log 7 "force interval: $FORCE_SECONDS seconds"
176 write_log 7 "retry interval: $RETRY_SECONDS seconds"
177 write_log 7 "retry counter : $retry_count times"
178
179 # determine what update url we're using if a service_name is supplied
180 # otherwise update_url is set inside configuration (custom update url)
181 # or update_script is set inside configuration (custom update script)
182 [ -n "$service_name" ] && get_service_data update_url update_script
183 [ -z "$update_url" -a -z "$update_script" ] && write_log 14 "No update_url found/defined or no update_script found/defined!"
184 [ -n "$update_script" -a ! -f "$update_script" ] && write_log 14 "Custom update_script not found!"
185
186 #kill old process if it exists & set new pid file
187 if [ -d $RUNDIR ]; then
188 #if process for section is already running, stop it
189 stop_section_processes "$SECTION_ID"
190 [ $? -gt 0 ] && write_log 7 "Send 'SIGTERM' to old process" || write_log 7 "No old process"
191 else
192 #make dir since it doesn't exist
193 mkdir -p $RUNDIR
194 write_log 7 "No old process"
195 fi
196 echo $$ > $PIDFILE
197
198 # determine when the last update was
199 # the following lines should prevent multiple updates if hotplug fires multiple startups
200 # as described in Ticket #7820, but did not function if never an update take place
201 # i.e. after a reboot (/var is linked to /tmp)
202 # using uptime as reference because date might not be updated via NTP client
203 get_uptime CURR_TIME
204 [ -e "$UPDFILE" ] && {
205 LAST_TIME=$(cat $UPDFILE)
206 # check also LAST > CURR because link of /var/run to /tmp might be removed
207 # i.e. boxes with larger filesystems
208 [ -z "$LAST_TIME" ] && LAST_TIME=0
209 [ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME=0
210 }
211 if [ $LAST_TIME -eq 0 ]; then
212 write_log 7 "last update: never"
213 else
214 EPOCH_TIME=$(( $(date +%s) - CURR_TIME + LAST_TIME ))
215 EPOCH_TIME="date -d @$EPOCH_TIME +'$DATE_FORMAT'"
216 write_log 7 "last update: $(eval $EPOCH_TIME)"
217 fi
218
219 # we need time here because hotplug.d is fired by netifd
220 # but IP addresses are not set by DHCP/DHCPv6 etc.
221 write_log 7 "Waiting 10 seconds for interfaces to fully come up"
222 sleep 10 &
223 PID_SLEEP=$!
224 wait $PID_SLEEP # enable trap-handler
225 PID_SLEEP=0
226
227 # verify DNS server
228 [ -n "$dns_server" ] && verify_dns "$dns_server"
229
230 # verify Proxy server and set environment
231 [ -n "$proxy" ] && {
232 verify_proxy "$proxy" && {
233 # everything ok set proxy
234 export HTTP_PROXY="http://$proxy"
235 export HTTPS_PROXY="http://$proxy"
236 export http_proxy="http://$proxy"
237 export https_proxy="http://$proxy"
238 }
239 }
240
241 # let's check if there is already an IP registered at the web
242 # but ignore errors if not
243 get_registered_ip REGISTERED_IP "NO_RETRY"
244
245 # loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
246 write_log 6 "Starting main loop at $(eval $DATE_PROG)"
247 while : ; do
248
249 get_local_ip LOCAL_IP # read local IP
250
251 # prepare update
252 # never updated or forced immediate then NEXT_TIME = 0
253 [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
254 && NEXT_TIME=0 \
255 || NEXT_TIME=$(( $LAST_TIME + $FORCE_SECONDS ))
256
257 get_uptime CURR_TIME # get current uptime
258
259 # send update when current time > next time or local ip different from registered ip
260 if [ $CURR_TIME -ge $NEXT_TIME -o "$LOCAL_IP" != "$REGISTERED_IP" ]; then
261 if [ $VERBOSE_MODE -gt 2 ]; then
262 write_log 7 "Verbose Mode: $VERBOSE_MODE - NO UPDATE send"
263 elif [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
264 write_log 7 "Update needed - L: '$LOCAL_IP' <> R: '$REGISTERED_IP'"
265 else
266 write_log 7 "Forced Update - L: '$LOCAL_IP' == R: '$REGISTERED_IP'"
267 fi
268
269 ERR_LAST=0
270 [ $VERBOSE_MODE -lt 3 ] && {
271 # only send if VERBOSE_MODE < 3
272 send_update "$LOCAL_IP"
273 ERR_LAST=$? # save return value
274 }
275
276 # error sending local IP to provider
277 # we have no communication error (handled inside send_update/do_transfer)
278 # but update was not recognized
279 # do NOT retry after RETRY_SECONDS, do retry after CHECK_SECONDS
280 # to early retrys will block most DDNS provider
281 # providers answer is checked inside send_update() function
282 [ $ERR_LAST -eq 0 ] && {
283 get_uptime LAST_TIME # we send update, so
284 echo $LAST_TIME > $UPDFILE # save LASTTIME to file
285 [ "$LOCAL_IP" != "$REGISTERED_IP" ] \
286 && write_log 6 "Update successful - IP '$LOCAL_IP' send" \
287 || write_log 6 "Forced update successful - IP: '$LOCAL_IP' send"
288 } || write_log 3 "Can not update IP at DDNS Provider"
289 fi
290
291 # now we wait for check interval before testing if update was recognized
292 # only sleep if VERBOSE_MODE <= 2 because otherwise nothing was send
293 [ $VERBOSE_MODE -le 2 ] && {
294 write_log 7 "Waiting $CHECK_SECONDS seconds (Check Interval)"
295 sleep $CHECK_SECONDS &
296 PID_SLEEP=$!
297 wait $PID_SLEEP # enable trap-handler
298 PID_SLEEP=0
299 } || write_log 7 "Verbose Mode: $VERBOSE_MODE - NO Check Interval waiting"
300
301 REGISTERED_IP="" # clear variable
302 get_registered_ip REGISTERED_IP # get registered/public IP
303
304 # IP's are still different
305 if [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
306 if [ $VERBOSE_MODE -le 1 ]; then # VERBOSE_MODE <=1 then retry
307 ERR_UPDATE=$(( $ERR_UPDATE + 1 ))
308 [ $ERR_UPDATE -gt $retry_count ] && write_log 14 "Updating IP at DDNS provider failed after $retry_count retries"
309 write_log 4 "Updating IP at DDNS provider failed - starting retry $ERR_UPDATE/$retry_count"
310 continue # loop to beginning
311 else
312 write_log 4 "Updating IP at DDNS provider failed"
313 write_log 7 "Verbose Mode: $VERBOSE_MODE - NO retry"; exit 1
314 fi
315 else
316 # we checked successful the last update
317 ERR_UPDATE=0 # reset error counter
318 fi
319
320 # force_update=0 or VERBOSE_MODE > 1 - leave here
321 [ $VERBOSE_MODE -gt 1 ] && write_log 7 "Verbose Mode: $VERBOSE_MODE - NO reloop"; exit 0
322 [ $FORCE_SECONDS -eq 0 ] && write_log 6 "Configured to run once"; exit 0
323 write_log 6 "Rerun IP check at $(eval $DATE_PROG)"
324 done
325 # we should never come here there must be a programming error
326 write_log 12 "Error in 'dynamic_dns_updater.sh - program coding error"