2 # /usr/lib/ddns/dynamic_dns_functions.sh
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
9 # extended and partial rewritten in August 2014
10 # by Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
12 # - IPv6 DDNS services
13 # - setting DNS Server to retrieve current IP including TCP transport
14 # - Proxy Server to send out updates or retrieving WEB based IP detection
15 # - force_interval=0 to run once (useful for cron jobs etc.)
16 # - the usage of BIND's host instead of BusyBox's nslookup if installed (DNS via TCP)
17 # - extended Verbose Mode and log file support for better error detection
20 # copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
21 # @author Anthony Thyssen 6 April 2011
23 # variables in small chars are read from /etc/config/ddns
24 # variables in big chars are defined inside these scripts as global vars
25 # variables in big chars beginning with "__" are local defined inside functions only
26 # set -vx #script debugger
29 .
/lib
/functions
/network.sh
32 SECTION_ID
="" # hold config's section name
33 VERBOSE_MODE
=1 # default mode is log to console, but easily changed with parameter
35 # allow NON-public IP's
36 ALLOW_LOCAL_IP
=$
(uci
-q get ddns.global.allow_local_ip
) || ALLOW_LOCAL_IP
=0
37 # directory to store run information to.
38 RUNDIR
=$
(uci
-q get ddns.global.run_dir
) || RUNDIR
="/var/run/ddns"
39 [ -d $RUNDIR ] || mkdir
-p -m755 $RUNDIR
40 # directory to store log files
41 LOGDIR
=$
(uci
-q get ddns.global.log_dir
) || LOGDIR
="/var/log/ddns"
42 [ -d $LOGDIR ] || mkdir
-p -m755 $LOGDIR
43 LOGFILE
="" # logfile - all files are set in dynamic_dns_updater.sh
45 UPDFILE
="" # store UPTIME of last update
46 DATFILE
="" # save stdout data of WGet and other external programs called
47 ERRFILE
="" # save stderr output of WGet and other external programs called
48 TLDFILE
=/usr
/lib
/ddns
/tld_names.dat
# TLD file used by split_FQDN
50 # number of lines to before rotate logfile
51 LOGLINES
=$
(uci
-q get ddns.global.log_lines
) || LOGLINES
=250
52 LOGLINES
=$
((LOGLINES
+ 1)) # correct sed handling
54 CHECK_SECONDS
=0 # calculated seconds out of given
55 FORCE_SECONDS
=0 # interval and unit
56 RETRY_SECONDS
=0 # in configuration
58 LAST_TIME
=0 # holds the uptime of last successful update
59 CURR_TIME
=0 # holds the current uptime
60 NEXT_TIME
=0 # calculated time for next FORCED update
61 EPOCH_TIME
=0 # seconds since 1.1.1970 00:00:00
63 REGISTERED_IP
="" # holds the IP read from DNS
64 LOCAL_IP
="" # holds the local IP read from the box
66 URL_USER
="" # url encoded $username from config file
67 URL_PASS
="" # url encoded $password from config file
69 ERR_LAST
=0 # used to save $? return code of program and function calls
70 ERR_UPDATE
=0 # error counter on different local and registered ip
72 PID_SLEEP
=0 # ProcessID of current background "sleep"
74 # format to show date information in log and luci-app-ddns default ISO 8601 format
75 DATE_FORMAT
=$
(uci
-q get ddns.global.date_format
) || DATE_FORMAT
="%F %R"
76 DATE_PROG
="date +'$DATE_FORMAT'"
78 # regular expression to detect IPv4 / IPv6
79 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
80 IPV4_REGEX
="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
81 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
82 IPV6_REGEX
="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
84 # detect if called by dynamic_dns_lucihelper.sh script, disable retrys (empty variable == false)
85 [ "$(basename $0)" = "dynamic_dns_lucihelper.sh" ] && LUCI_HELPER
="TRUE" || LUCI_HELPER
=""
87 # loads all options for a given package and section
88 # also, sets all_option_variables to a list of the variable names
89 # $1 = ddns, $2 = SECTION_ID
90 load_all_config_options
()
93 local __SECTIONID
="$2"
95 local __ALL_OPTION_VARIABLES
=""
97 # this callback loads all the variables in the __SECTIONID section when we do
98 # config_load. We need to redefine the option_cb for different sections
99 # so that the active one isn't still active after we're done with it. For reference
100 # the $1 variable is the name of the option and $2 is the name of the section
103 if [ .
"$2" = .
"$__SECTIONID" ]; then
106 __ALL_OPTION_VARIABLES
="$__ALL_OPTION_VARIABLES $1"
109 option_cb
() { return 0; }
113 config_load
"$__PKGNAME"
115 # Given SECTION_ID not found so no data, so return 1
116 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
118 for __VAR
in $__ALL_OPTION_VARIABLES
120 config_get
"$__VAR" "$__SECTIONID" "$__VAR"
125 # read's all service sections from ddns config
126 # $1 = Name of variable to store
127 load_all_service_sections
() {
131 # only look for section type "service", ignore everything else
132 [ "$1" = "service" ] && __DATA
="$__DATA $2"
136 eval "$1=\"$__DATA\""
140 # starts updater script for all given sections or only for the one given
141 # $1 = interface (Optional: when given only scripts are started
142 # configured for that interface)
143 # used by /etc/hotplug.d/iface/25-ddns on IFUP
144 # and by /etc/init.d/ddns start
145 start_daemon_for_all_ddns_sections
()
152 load_all_service_sections __SECTIONS
153 for __SECTIONID
in $__SECTIONS; do
154 config_get __IFACE
"$__SECTIONID" interface
"wan"
155 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
156 /usr
/lib
/ddns
/dynamic_dns_updater.sh
$__SECTIONID 0 >/dev
/null
2>&1 &
160 # stop sections process incl. childs (sleeps)
162 stop_section_processes
() {
164 local __PIDFILE
="$RUNDIR/$1.pid"
165 [ $# -ne 1 ] && write_log
12 "Error calling 'stop_section_processes()' - wrong number of parameters"
167 [ -e "$__PIDFILE" ] && {
168 __PID
=$
(cat $__PIDFILE)
169 ps |
grep "^[\t ]*$__PID" >/dev
/null
2>&1 && kill $__PID || __PID
=0 # terminate it
171 [ $__PID -eq 0 ] # report if process was running
174 # stop updater script for all defines sections or only for one given
175 # $1 = interface (optional)
176 # used by /etc/hotplug.d/iface/25-ddns on 'ifdown'
177 # and by /etc/init.d/ddns stop
178 # needed because we also need to kill "sleep" child processes
179 stop_daemon_for_all_ddns_sections
() {
185 load_all_service_sections __SECTIONS
186 for __SECTIONID
in $__SECTIONS; do
187 config_get __IFACE
"$__SECTIONID" interface
"wan"
188 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
189 stop_section_processes
"$__SECTIONID"
193 # reports to console, logfile, syslog
194 # $1 loglevel 7 == Debug to 0 == EMERG
195 # value +10 will exit the scripts
196 # $2..n text to report
198 local __LEVEL __EXIT __CMD __MSG
199 local __TIME
=$
(date +%H
%M
%S
)
207 shift # remove loglevel
208 [ $__EXIT -eq 0 ] && __MSG
="$*" || __MSG
="$* - TERMINATE"
209 case $__LEVEL in # create log message and command depending on loglevel
210 0) __CMD
="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
211 __MSG
=" $__TIME EMERG : $__MSG" ;;
212 1) __CMD
="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
213 __MSG
=" $__TIME ALERT : $__MSG" ;;
214 2) __CMD
="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
215 __MSG
=" $__TIME CRIT : $__MSG" ;;
216 3) __CMD
="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
217 __MSG
=" $__TIME ERROR : $__MSG" ;;
218 4) __CMD
="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
219 __MSG
=" $__TIME WARN : $__MSG" ;;
220 5) __CMD
="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
221 __MSG
=" $__TIME note : $__MSG" ;;
222 6) __CMD
="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
223 __MSG
=" $__TIME info : $__MSG" ;;
224 7) __MSG
=" $__TIME : $__MSG";;
229 [ $VERBOSE_MODE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
231 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE_MODE -gt 1 ]; then
232 echo -e "$__MSG" >> $LOGFILE
233 # VERBOSE_MODE > 1 then NO loop so NO truncate log to $LOGLINES lines
234 [ $VERBOSE_MODE -gt 1 ] ||
sed -i -e :a
-e '$q;N;'$LOGLINES',$D;ba' $LOGFILE
236 [ $LUCI_HELPER ] && return # nothing else todo when running LuCI helper script
237 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
238 [ $__EXIT -eq 1 ] && {
239 $__CMD # force syslog before exit
242 [ $use_syslog -eq 0 ] && return
243 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && $__CMD
247 # replace all special chars to their %hex value
248 # used for USERNAME and PASSWORD in update_url
249 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
250 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
251 # "$"(Dollar) # because used as variable output
252 # tested with the following string stored via Luci Application as password / username
253 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
255 # $1 Name of Variable to store encoded string to
256 # $2 string to encode
257 local __STR __LEN __CHAR __OUT
261 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
263 __STR
="$2" # read string to encode
264 __LEN
=${#__STR} # get string length
266 while [ $__POS -le $__LEN ]; do
267 # read one chat of the string
268 __CHAR
=$
(expr substr
"$__STR" $__POS 1)
276 # special char get %hex code
277 __OUT
=$
(printf '%%%02x' "'$__CHAR" )
280 __ENC
="${__ENC}${__OUT}" # append to encoded string
281 __POS
=$
(( $__POS + 1 )) # increment position
284 eval "$1=\"$__ENC\"" # transfer back to variable
288 # extract url or script for given DDNS Provider from
289 # file /usr/lib/ddns/services for IPv4 or from
290 # file /usr/lib/ddns/services_ipv6 for IPv6
291 # $1 Name of Variable to store url to
292 # $2 Name of Variable to store script to
294 local __LINE __FILE __NAME __URL __SERVICES __DATA
297 local __NEWLINE_IFS
='
299 [ $# -ne 2 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
301 __FILE
="/usr/lib/ddns/services" # IPv4
302 [ $use_ipv6 -ne 0 ] && __FILE
="/usr/lib/ddns/services_ipv6" # IPv6
304 # remove any lines not containing data, and then make sure fields are enclosed in double quotes
305 __SERVICES
=$
(cat $__FILE |
grep "^[\t ]*[^#]" | \
306 awk ' gsub("\x27", "\"") { if ($1~/^[^\"]*$/) $1="\""$1"\"" }; { if ( $NF~/^[^\"]*$/) $NF="\""$NF"\"" }; { print $0 }')
309 for __LINE
in $__SERVICES; do
310 # grep out proper parts of data and use echo to remove quotes
311 __NAME
=$
(echo $__LINE |
grep -o "^[\t ]*\"[^\"]*\"" |
xargs -r -n1 echo)
312 __DATA
=$
(echo $__LINE |
grep -o "\"[^\"]*\"[\t ]*$" |
xargs -r -n1 echo)
314 if [ "$__NAME" = "$service_name" ]; then
315 break # found so leave for loop
320 # check if URL or SCRIPT is given
321 __URL
=$
(echo "$__DATA" |
grep "^http")
322 [ -z "$__URL" ] && __SCRIPT
="/usr/lib/ddns/$__DATA"
325 eval "$2=\"$__SCRIPT\""
329 # Calculate seconds from interval and unit
330 # $1 Name of Variable to store result in
332 # $3 Unit of time interval
334 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
336 "days" ) eval "$1=$(( $2 * 86400 ))";;
337 "hours" ) eval "$1=$(( $2 * 3600 ))";;
338 "minutes" ) eval "$1=$(( $2 * 60 ))";;
345 # copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
346 # only did the following changes
347 # - commented out "#!/bin/bash" and usage section
348 # - replace exit by return for usage as function
349 # - some reformatting
351 # timeout [-SIG] time [--] command args...
353 # Run the given command until completion, but kill it if it runs too long.
354 # Specifically designed to exit immediately (no sleep interval) and clean up
355 # nicely without messages or leaving any extra processes when finished.
358 # timeout 5 countdown
362 # Based on notes in my "Shell Script Hints", section "Command Timeout"
363 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
365 # This script uses a lot of tricks to terminate both the background command,
366 # the timeout script, and even the sleep process. It also includes trap
367 # commands to prevent sub-shells reporting expected "Termination Errors".
369 # It took years of occasional trials, errors and testing to get a pure bash
370 # timeout command working as well as this does.
374 # Anthony Thyssen 6 April 2011
376 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
377 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
378 # PROGNAME=$(basename $PROGNAME) # base name of program
380 # output the script comments as docs
382 # echo >&2 "$PROGNAME:" "$@"
383 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
389 while [ $# -gt 0 ]; do
392 # forced end of user options
402 # unforced end of user options
408 # run main command in backgrounds and get its pid
412 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
415 # cleanup sleep process
416 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
417 # sleep timeout period in background
422 kill $SIG $command_pid >/dev
/null
2>&1
427 # Wait for main command to finished or be timed out
431 # Clean up timeout sub-shell - if it is still running!
432 kill $timeout_pid 2>/dev
/null
433 wait $timeout_pid 2>/dev
/null
435 # Uncomment to check if a LONG sleep still running (no sleep should be)
438 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
443 # verify given host and port is connectable
444 # $1 Host/IP to verify
449 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
451 # 1 system specific error
452 # 2 nslookup/host error
453 # 3 nc (netcat) error
454 # 4 unmatched IP version
456 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
458 # check if ip or FQDN was given
459 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
460 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
461 # if FQDN given get IP address
462 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
463 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
465 __RUNPROG
="/usr/bin/host -t ANY $__HOST >$DATFILE 2>$ERRFILE"
466 else # use BusyBox nslookup
467 __PROG
="BusyBox nslookup"
468 __RUNPROG
="/usr/bin/nslookup $__HOST >$DATFILE 2>$ERRFILE"
470 write_log
7 "#> $__RUNPROG"
474 [ $__ERR -gt 0 ] && {
475 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
476 write_log
7 "$(cat $ERRFILE)"
480 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
481 __IPV4
=$
(cat $DATFILE |
awk -F "address " '/has address/ {print $2; exit}' )
482 __IPV6
=$
(cat $DATFILE |
awk -F "address " '/has IPv6/ {print $2; exit}' )
483 else # use BusyBox nslookup
484 __IPV4
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }")
485 __IPV6
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }")
489 # check IP version if forced
490 if [ $force_ipversion -ne 0 ]; then
492 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
493 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
494 [ $__ERR -gt 0 ] && {
495 [ $LUCI_HELPER ] && return 4
496 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
501 # busybox nc compiled without -l option "NO OPT l!" -> critical error
502 /usr
/bin
/nc
--help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
503 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
504 # busybox nc compiled with extensions
505 /usr
/bin
/nc
--help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
508 # run busybox nc to HOST PORT
509 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
510 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
511 # not worrying, if there is an IPv6 wan address
512 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
513 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
515 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
516 __RUNPROG
="/usr/bin/nc -vw 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
517 write_log
7 "#> $__RUNPROG"
520 [ $__ERR -eq 0 ] && return 0
521 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
522 write_log
7 "$(cat $ERRFILE)"
524 else # nc compiled without extensions (no timeout support)
525 __RUNPROG
="timeout 2 -- /usr/bin/nc $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
526 write_log
7 "#> $__RUNPROG"
529 [ $__ERR -eq 0 ] && return 0
530 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
535 # verify given DNS server if connectable
536 # $1 DNS server to verify
538 local __ERR
=255 # last error buffer
539 local __CNT
=0 # error counter
541 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
542 write_log
7 "Verify DNS server '$1'"
544 while [ $__ERR -ne 0 ]; do
546 verify_host_port
"$1" "53"
548 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
550 elif [ $__ERR -ne 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
551 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
553 elif [ $__ERR -ne 0 ]; then
554 __CNT
=$
(( $__CNT + 1 )) # increment error counter
555 # if error count > retry_count leave here
556 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
557 write_log
14 "Verify DNS server '$1' failed after $retry_count retries"
559 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
560 sleep $RETRY_SECONDS &
562 wait $PID_SLEEP # enable trap-handler
569 # analyze and verify given proxy string
570 # $1 Proxy-String to verify
572 # complete entry user:password@host:port
573 # inside user and password NO '@' of ":" allowed
574 # host and port only host:port
575 # host only host ERROR unsupported
576 # IPv4 address instead of host 123.234.234.123
577 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
578 local __TMP __HOST __PORT
579 local __ERR
=255 # last error buffer
580 local __CNT
=0 # error counter
582 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
583 write_log
7 "Verify Proxy server 'http://$1'"
585 # try to split user:password "@" host:port
586 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
587 # no "@" found - only host:port is given
588 [ -z "$__TMP" ] && __TMP
="$1"
589 # now lets check for IPv6 address
590 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
591 # IPv6 host address found read port
592 if [ -n "$__HOST" ]; then
594 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
596 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
597 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
599 # No Port detected - EXITING
600 [ -z "$__PORT" ] && {
601 [ $LUCI_HELPER ] && return 5
602 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
605 while [ $__ERR -gt 0 ]; do
606 verify_host_port
"$__HOST" "$__PORT"
608 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
610 elif [ $__ERR -gt 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
611 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
613 elif [ $__ERR -gt 0 ]; then
614 __CNT
=$
(( $__CNT + 1 )) # increment error counter
615 # if error count > retry_count leave here
616 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
617 write_log
14 "Verify Proxy server '$1' failed after $retry_count retries"
619 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
620 sleep $RETRY_SECONDS &
622 wait $PID_SLEEP # enable trap-handler
633 local __CNT
=0 # error counter
634 local __PROG __RUNPROG
636 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
638 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
639 if /usr
/bin
/wget
--version 2>&1 |
grep "\+ssl" >/dev
/null
2>&1 ; then
640 __PROG
="/usr/bin/wget -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
641 # force ip version to use
642 if [ $force_ipversion -eq 1 ]; then
643 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
645 # set certificate parameters
646 if [ $use_https -eq 1 ]; then
647 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
648 __PROG
="$__PROG --no-check-certificate"
649 elif [ -f "$cacert" ]; then
650 __PROG
="$__PROG --ca-certificate=${cacert}"
651 elif [ -d "$cacert" ]; then
652 __PROG
="$__PROG --ca-directory=${cacert}"
653 else # exit here because it makes no sense to start loop
654 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
657 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
658 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
660 __RUNPROG
="$__PROG '$__URL'" # build final command
661 __PROG
="GNU Wget" # reuse for error logging
663 # 2nd choice is cURL IPv4/IPv6/HTTPS
664 # libcurl might be compiled without Proxy Support (default in trunk)
665 elif [ -x /usr
/bin
/curl
]; then
666 __PROG
="/usr/bin/curl -RsS -o $DATFILE --stderr $ERRFILE"
667 # force ip version to use
668 if [ $force_ipversion -eq 1 ]; then
669 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
671 # set certificate parameters
672 if [ $use_https -eq 1 ]; then
673 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
674 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
675 elif [ -f "$cacert" ]; then
676 __PROG
="$__PROG --cacert $cacert"
677 elif [ -d "$cacert" ]; then
678 __PROG
="$__PROG --capath $cacert"
679 else # exit here because it makes no sense to start loop
680 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
683 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
684 # or check if libcurl compiled with proxy support
685 if [ -z "$proxy" ]; then
686 __PROG
="$__PROG --noproxy '*'"
688 # if libcurl has no proxy support and proxy should be used then force ERROR
689 # libcurl currently no proxy support by default
690 grep -i "all_proxy" /usr
/lib
/libcurl.so
* >/dev
/null
2>&1 || \
691 write_log
13 "cURL: libcurl compiled without Proxy support"
694 __RUNPROG
="$__PROG '$__URL'" # build final command
695 __PROG
="cURL" # reuse for error logging
697 # busybox Wget (did not support neither IPv6 nor HTTPS)
698 elif [ -x /usr
/bin
/wget
]; then
699 __PROG
="/usr/bin/wget -q -O $DATFILE"
700 # force ip version not supported
701 [ $force_ipversion -eq 1 ] && \
702 write_log
14 "BusyBox Wget: can not force IP version to use"
703 # https not supported
704 [ $use_https -eq 1 ] && \
705 write_log
14 "BusyBox Wget: no HTTPS support"
706 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
707 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
709 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
710 __PROG
="Busybox Wget" # reuse for error logging
713 write_log
13 "Neither 'Wget' nor 'cURL' installed or executable"
717 write_log
7 "#> $__RUNPROG"
718 eval $__RUNPROG # DO transfer
719 __ERR
=$?
# save error code
720 [ $__ERR -eq 0 ] && return 0 # no error leave
721 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
723 write_log
3 "$__PROG Error: '$__ERR'"
724 write_log
7 "$(cat $ERRFILE)" # report error
726 [ $VERBOSE_MODE -gt 1 ] && {
727 # VERBOSE_MODE > 1 then NO retry
728 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
732 __CNT
=$
(( $__CNT + 1 )) # increment error counter
733 # if error count > retry_count leave here
734 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
735 write_log
14 "Transfer failed after $retry_count retries"
737 write_log
4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
738 sleep $RETRY_SECONDS &
740 wait $PID_SLEEP # enable trap-handler
743 # we should never come here there must be a programming error
744 write_log
12 "Error in 'do_transfer()' - program coding error"
748 # $1 # IP to set at DDNS service provider
751 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
753 if [ $ALLOW_LOCAL_IP -eq 0 ]; then
754 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
755 [ $use_ipv6 -eq 0 ] && __IP
=$
(echo $1 |
grep -v -E "(^0|^10\.|^127|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168)")
756 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
757 [ -z "$__IP" ] && write_log
14 "Private or invalid or no IP '$1' given! Please check your configuration"
762 if [ -n "$update_script" ]; then
763 write_log
7 "parsing script '$update_script'"
769 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
770 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
771 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
773 do_transfer
"$__URL" ||
return 1
775 write_log
7 "DDNS Provider answered:\n$(cat $DATFILE)"
778 # TODO analyze providers answer
779 # "good" or "nochg" = dyndns.com compatible API
780 # grep -i -E "good|nochg" $DATFILE >/dev/null 2>&1
781 # return $? # "0" if found
786 # $1 Name of Variable to store local IP (LOCAL_IP)
787 local __CNT
=0 # error counter
788 local __RUNPROG __DATA __URL __ERR
790 [ $# -ne 1 ] && write_log
12 "Error calling 'get_local_ip()' - wrong number of parameters"
791 write_log
7 "Detect local IP"
796 # set correct program
797 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
798 || __RUNPROG
="network_get_ipaddr6"
799 write_log
7 "#> $__RUNPROG __DATA '$ip_network'"
800 eval "$__RUNPROG __DATA $ip_network" || write_log
3 "$__RUNPROG Error: '$?'"
801 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on network '$ip_network'"
804 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
805 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
807 if [ $__ERR -eq 0 ]; then
808 if [ $use_ipv6 -eq 0 ]; then
810 /inet addr:/ { # Filter IPv4
811 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
813 $3=""; # remove Bcast: ...
814 $4=""; # remove Mask: ...
815 FS=":"; # separator ":"
816 $0=$0; # reread to activate separator
818 FS=" "; # set back separator to default " "
819 $0=$0; # reread to activate separator (remove whitespaces)
820 print $1; # print IPv4 addr
825 /inet6/ && /: [0-9a-eA-E]/ && !/\/128/ { # Filter IPv6 exclude fxxx and /128 prefix
826 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
827 FS="/"; # separator "/"
828 $0=$0; # reread to activate separator
829 $2=""; # remove everything behind "/"
830 FS=" "; # set back separator to default " "
831 $0=$0; # reread to activate separator
832 print $3; # print IPv6 addr
836 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on interface '$ip_interface'"
838 write_log
3 "ifconfig Error: '$__ERR'"
839 write_log
7 "$(cat $ERRFILE)" # report error
843 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
844 eval $ip_script >$DATFILE 2>$ERRFILE
846 if [ $__ERR -eq 0 ]; then
847 __DATA
=$
(cat $DATFILE)
848 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected via script '$ip_script'"
850 write_log
3 "$ip_script Error: '$__ERR'"
851 write_log
7 "$(cat $ERRFILE)" # report error
855 do_transfer
"$ip_url"
856 # use correct regular expression
857 [ $use_ipv6 -eq 0 ] \
858 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
859 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
860 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on web at '$__URL'"
863 write_log
12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
866 # valid data found return here
867 [ -n "$__DATA" ] && {
868 eval "$1=\"$__DATA\""
872 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
874 write_log
7 "Data detected:\n$(cat $DATFILE)"
876 [ $VERBOSE_MODE -gt 1 ] && {
877 # VERBOSE_MODE > 1 then NO retry
878 write_log
4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
882 __CNT
=$
(( $__CNT + 1 )) # increment error counter
883 # if error count > retry_count leave here
884 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
885 write_log
14 "Get local IP via '$ip_source' failed after $retry_count retries"
886 write_log
4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
887 sleep $RETRY_SECONDS &
889 wait $PID_SLEEP # enable trap-handler
892 # we should never come here there must be a programming error
893 write_log
12 "Error in 'get_local_ip()' - program coding error"
896 get_registered_ip
() {
897 # $1 Name of Variable to store public IP (REGISTERED_IP)
898 # $2 (optional) if set, do not retry on error
899 local __CNT
=0 # error counter
901 local __REGEX __PROG __RUNPROG __DATA
905 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
906 write_log
7 "Detect registered/public IP"
908 # set correct regular expression
909 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
911 if [ -x /usr
/bin
/host ]; then
912 __PROG
="/usr/bin/host"
913 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
914 if [ $force_ipversion -eq 1 ]; then # force IP version
915 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
917 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
919 __RUNPROG
="$__PROG $domain $dns_server >$DATFILE 2>$ERRFILE"
921 elif [ -x /usr
/bin
/nslookup ]; then # last use BusyBox nslookup
922 [ $force_ipversion -ne 0 -o $force_dnstcp -ne 0 ] && \
923 write_log
14 "Busybox nslookup - no support to 'force IP Version' or 'DNS over TCP'"
925 __RUNPROG
="/usr/bin/nslookup $domain $dns_server >$DATFILE 2>$ERRFILE"
926 __PROG
="BusyBox nslookup"
927 else # there must be an error
928 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
932 write_log
7 "#> $__RUNPROG"
935 if [ $__ERR -ne 0 ]; then
936 write_log
3 "$__PROG error: '$__ERR'"
937 write_log
7 "$(cat $ERRFILE)"
939 if [ "$__PROG" = "BIND host" ]; then
940 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
942 __DATA
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
944 [ -n "$__DATA" ] && {
945 write_log
7 "Registered IP '$__DATA' detected"
946 eval "$1=\"$__DATA\"" # valid data found
947 return 0 # leave here
949 write_log
4 "NO valid IP found"
953 [ $LUCI_HELPER ] && return $__ERR # no retry if called by LuCI helper script
954 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
955 [ $VERBOSE_MODE -gt 1 ] && {
956 # VERBOSE_MODE > 1 then NO retry
957 write_log
4 "Get registered/public IP for '$domain' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
961 __CNT
=$
(( $__CNT + 1 )) # increment error counter
962 # if error count > retry_count leave here
963 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
964 write_log
14 "Get registered/public IP for '$domain' failed after $retry_count retries"
966 write_log
4 "Get registered/public IP for '$domain' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
967 sleep $RETRY_SECONDS &
969 wait $PID_SLEEP # enable trap-handler
972 # we should never come here there must be a programming error
973 write_log
12 "Error in 'get_registered_ip()' - program coding error"
977 # $1 Variable to store result in
978 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
979 local __UPTIME
=$
(cat /proc
/uptime
)
980 eval "$1=\"${__UPTIME%%.*}\""
985 # $2 optional (exit status)
989 local __NEWLINE_IFS
='
992 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
995 0) if [ $__ERR -eq 0 ]; then
996 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
998 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1000 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1001 # reload config via starting the script again
1002 eval "/usr/lib/ddns/dynamic_dns_updater.sh $SECTION_ID $VERBOSE_MODE &"
1003 exit 0 ;; # and leave this one
1004 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)\n";;
1005 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)\n";;
1006 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)\n";;
1007 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1010 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1012 for __PID
in $__PIDS; do
1013 kill -$1 $__PID # terminate it
1017 # remove out and err file
1018 [ -f $DATFILE ] && rm -f $DATFILE
1019 [ -f $ERRFILE ] && rm -f $ERRFILE
1021 # exit with correct handling:
1022 # remove trap handling settings and send kill to myself
1024 [ $1 -gt 0 ] && kill -$1 $$
1029 # $2 name of variable to store TLD
1030 # $3 name of variable to store (reg)Domain
1031 # $4 name of variable to store Host/Subdomain
1033 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1035 _SET
="$@" # save given parameters
1036 local _FHOST _FTLD _FOUND
1037 local _FDOM
=$
(echo "$1" |
tr [A-Z
] [a-z
]) # to lower
1039 set -- $
(echo "$_FDOM" |
tr "." " ") # replace DOT with SPACE and set as script parameters
1040 _FDOM
="" # clear variable for later reuse
1042 while [ -n "$1" ] ; do # as long we have parameters
1043 _FTLD
=$
(echo $@ |
tr " " ".") # build back dot separated as TLD
1044 # look if match excludes "!" in tld_names.dat
1045 grep -E "^!$_FTLD$" $TLDFILE >/dev
/null
2>&1 ||
{
1046 # Don't match excludes
1047 # check if match any "*" in tld_names.dat
1048 grep -E "^*.$_FTLD$" $TLDFILE >/dev
/null
2>&1 && {
1050 break # found leave while
1052 # check if exact match in tld_names.dat
1053 grep -E "^$_FTLD$" $TLDFILE >/dev
/null
2>&1 && {
1055 break # found leave while
1059 _FHOST
="$_FHOST $_FDOM" # append DOMAIN to last found HOST
1060 _FDOM
="$1" # set 1st parameter as DOMAIN
1061 _FTLD
="" # clear TLD
1062 shift # delete 1st parameter and retry with the rest
1065 set -- $_SET # set back parameters from function call
1066 [ -n "$_FHOST" ] && _FHOST
=$
(echo $_FHOST |
tr " " ".") # put dots back into HOST
1067 [ -n "$_FOUND" ] && {
1068 eval "$2=$_FTLD" # set found TLD
1069 eval "$3=$_FDOM" # set found registrable domain
1070 eval "$4=$_FHOST" # set found HOST/SUBDOMAIN
1073 eval "$2=''" # clear TLD
1074 eval "$3=''" # clear registrable domain
1075 eval "$4=''" # clear HOST/SUBDOMAIN