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 by
10 #.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 __CMD
=$
(echo -e "$__CMD" |
tr -d '\n' |
tr '\t' ' ') # remove \n \t chars
239 [ $__EXIT -eq 1 ] && {
240 $__CMD # force syslog before exit
243 [ $use_syslog -eq 0 ] && return
244 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && $__CMD
248 # replace all special chars to their %hex value
249 # used for USERNAME and PASSWORD in update_url
250 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
251 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
252 # "$"(Dollar) # because used as variable output
253 # tested with the following string stored via Luci Application as password / username
254 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
256 # $1 Name of Variable to store encoded string to
257 # $2 string to encode
258 local __STR __LEN __CHAR __OUT
262 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
264 __STR
="$2" # read string to encode
265 __LEN
=${#__STR} # get string length
267 while [ $__POS -le $__LEN ]; do
268 # read one chat of the string
269 __CHAR
=$
(expr substr
"$__STR" $__POS 1)
277 # special char get %hex code
278 __OUT
=$
(printf '%%%02x' "'$__CHAR" )
281 __ENC
="${__ENC}${__OUT}" # append to encoded string
282 __POS
=$
(( $__POS + 1 )) # increment position
285 eval "$1=\"$__ENC\"" # transfer back to variable
289 # extract url or script for given DDNS Provider from
290 # file /usr/lib/ddns/services for IPv4 or from
291 # file /usr/lib/ddns/services_ipv6 for IPv6
292 # $1 Name of Variable to store url to
293 # $2 Name of Variable to store script to
295 local __LINE __FILE __NAME __URL __SERVICES __DATA
298 local __NEWLINE_IFS
='
300 [ $# -ne 2 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
302 __FILE
="/usr/lib/ddns/services" # IPv4
303 [ $use_ipv6 -ne 0 ] && __FILE
="/usr/lib/ddns/services_ipv6" # IPv6
305 # remove any lines not containing data, and then make sure fields are enclosed in double quotes
306 __SERVICES
=$
(cat $__FILE |
grep "^[\t ]*[^#]" | \
307 awk ' gsub("\x27", "\"") { if ($1~/^[^\"]*$/) $1="\""$1"\"" }; { if ( $NF~/^[^\"]*$/) $NF="\""$NF"\"" }; { print $0 }')
310 for __LINE
in $__SERVICES; do
311 # grep out proper parts of data and use echo to remove quotes
312 __NAME
=$
(echo $__LINE |
grep -o "^[\t ]*\"[^\"]*\"" |
xargs -r -n1 echo)
313 __DATA
=$
(echo $__LINE |
grep -o "\"[^\"]*\"[\t ]*$" |
xargs -r -n1 echo)
315 if [ "$__NAME" = "$service_name" ]; then
316 break # found so leave for loop
321 # check if URL or SCRIPT is given
322 __URL
=$
(echo "$__DATA" |
grep "^http")
323 [ -z "$__URL" ] && __SCRIPT
="/usr/lib/ddns/$__DATA"
326 eval "$2=\"$__SCRIPT\""
330 # Calculate seconds from interval and unit
331 # $1 Name of Variable to store result in
333 # $3 Unit of time interval
335 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
337 "days" ) eval "$1=$(( $2 * 86400 ))";;
338 "hours" ) eval "$1=$(( $2 * 3600 ))";;
339 "minutes" ) eval "$1=$(( $2 * 60 ))";;
346 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
347 # only did the following changes
348 # - commented out "#!/bin/bash" and usage section
349 # - replace exit by return for usage as function
350 # - some reformatting
352 # timeout [-SIG] time [--] command args...
354 # Run the given command until completion, but kill it if it runs too long.
355 # Specifically designed to exit immediately (no sleep interval) and clean up
356 # nicely without messages or leaving any extra processes when finished.
359 # timeout 5 countdown
361 # Based on notes in my "Shell Script Hints", section "Command Timeout"
362 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
364 # This script uses a lot of tricks to terminate both the background command,
365 # the timeout script, and even the sleep process. It also includes trap
366 # commands to prevent sub-shells reporting expected "Termination Errors".
368 # It took years of occasional trials, errors and testing to get a pure bash
369 # timeout command working as well as this does.
371 #.Anthony Thyssen 6 April 2011
373 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
374 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
375 # PROGNAME=$(basename $PROGNAME) # base name of program
377 # output the script comments as docs
379 # echo >&2 "$PROGNAME:" "$@"
380 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
386 while [ $# -gt 0 ]; do
389 # forced end of user options
399 # unforced end of user options
405 # run main command in backgrounds and get its pid
409 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
412 # cleanup sleep process
413 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
414 # sleep timeout period in background
419 kill $SIG $command_pid >/dev
/null
2>&1
424 # Wait for main command to finished or be timed out
428 # Clean up timeout sub-shell - if it is still running!
429 kill $timeout_pid 2>/dev
/null
430 wait $timeout_pid 2>/dev
/null
432 # Uncomment to check if a LONG sleep still running (no sleep should be)
435 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
440 # verify given host and port is connectable
441 # $1 Host/IP to verify
446 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
448 # 1 system specific error
449 # 2 nslookup/host error
450 # 3 nc (netcat) error
451 # 4 unmatched IP version
453 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
455 # check if ip or FQDN was given
456 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
457 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
458 # if FQDN given get IP address
459 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
460 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
462 __RUNPROG
="/usr/bin/host -t ANY $__HOST >$DATFILE 2>$ERRFILE"
463 else # use BusyBox nslookup
464 __PROG
="BusyBox nslookup"
465 __RUNPROG
="/usr/bin/nslookup $__HOST >$DATFILE 2>$ERRFILE"
467 write_log
7 "#> $__RUNPROG"
471 [ $__ERR -gt 0 ] && {
472 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
473 write_log
7 "$(cat $ERRFILE)"
477 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
478 __IPV4
=$
(cat $DATFILE |
awk -F "address " '/has address/ {print $2; exit}' )
479 __IPV6
=$
(cat $DATFILE |
awk -F "address " '/has IPv6/ {print $2; exit}' )
480 else # use BusyBox nslookup
481 __IPV4
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }")
482 __IPV6
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }")
486 # check IP version if forced
487 if [ $force_ipversion -ne 0 ]; then
489 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
490 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
491 [ $__ERR -gt 0 ] && {
492 [ $LUCI_HELPER ] && return 4
493 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
498 # busybox nc compiled without -l option "NO OPT l!" -> critical error
499 /usr
/bin
/nc
--help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
500 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
501 # busybox nc compiled with extensions
502 /usr
/bin
/nc
--help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
505 # run busybox nc to HOST PORT
506 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
507 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
508 # not worrying, if there is an IPv6 wan address
509 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
510 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
512 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
513 __RUNPROG
="/usr/bin/nc -vw 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
514 write_log
7 "#> $__RUNPROG"
517 [ $__ERR -eq 0 ] && return 0
518 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
519 write_log
7 "$(cat $ERRFILE)"
521 else # nc compiled without extensions (no timeout support)
522 __RUNPROG
="timeout 2 -- /usr/bin/nc $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
523 write_log
7 "#> $__RUNPROG"
526 [ $__ERR -eq 0 ] && return 0
527 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
532 # verify given DNS server if connectable
533 # $1 DNS server to verify
535 local __ERR
=255 # last error buffer
536 local __CNT
=0 # error counter
538 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
539 write_log
7 "Verify DNS server '$1'"
541 while [ $__ERR -ne 0 ]; do
543 verify_host_port
"$1" "53"
545 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
547 elif [ $__ERR -ne 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
548 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
550 elif [ $__ERR -ne 0 ]; then
551 __CNT
=$
(( $__CNT + 1 )) # increment error counter
552 # if error count > retry_count leave here
553 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
554 write_log
14 "Verify DNS server '$1' failed after $retry_count retries"
556 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
557 sleep $RETRY_SECONDS &
559 wait $PID_SLEEP # enable trap-handler
566 # analyze and verify given proxy string
567 # $1 Proxy-String to verify
569 # complete entry user:password@host:port
570 # inside user and password NO '@' of ":" allowed
571 # host and port only host:port
572 # host only host ERROR unsupported
573 # IPv4 address instead of host 123.234.234.123
574 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
575 local __TMP __HOST __PORT
576 local __ERR
=255 # last error buffer
577 local __CNT
=0 # error counter
579 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
580 write_log
7 "Verify Proxy server 'http://$1'"
582 # try to split user:password "@" host:port
583 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
584 # no "@" found - only host:port is given
585 [ -z "$__TMP" ] && __TMP
="$1"
586 # now lets check for IPv6 address
587 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
588 # IPv6 host address found read port
589 if [ -n "$__HOST" ]; then
591 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
593 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
594 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
596 # No Port detected - EXITING
597 [ -z "$__PORT" ] && {
598 [ $LUCI_HELPER ] && return 5
599 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
602 while [ $__ERR -gt 0 ]; do
603 verify_host_port
"$__HOST" "$__PORT"
605 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
607 elif [ $__ERR -gt 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
608 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
610 elif [ $__ERR -gt 0 ]; then
611 __CNT
=$
(( $__CNT + 1 )) # increment error counter
612 # if error count > retry_count leave here
613 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
614 write_log
14 "Verify Proxy server '$1' failed after $retry_count retries"
616 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
617 sleep $RETRY_SECONDS &
619 wait $PID_SLEEP # enable trap-handler
630 local __CNT
=0 # error counter
631 local __PROG __RUNPROG
633 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
635 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
636 if /usr
/bin
/wget
--version 2>&1 |
grep "\+ssl" >/dev
/null
2>&1 ; then
637 __PROG
="/usr/bin/wget -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
638 # force network/ip to use for communication
639 if [ -n "$bind_network" ]; then
641 # set correct program to detect IP
642 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" || __RUNPROG
="network_get_ipaddr6"
643 eval "$__RUNPROG __BINDIP $bind_network" || \
644 write_log
13 "Can not detect local IP using '$__RUNPROG $bind_network' - Error: '$?'"
645 write_log
7 "Force communication via IP '$__BINDIP'"
646 __PROG
="$__PROG --bind-address=$__BINDIP"
648 # force ip version to use
649 if [ $force_ipversion -eq 1 ]; then
650 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
652 # set certificate parameters
653 if [ $use_https -eq 1 ]; then
654 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
655 __PROG
="$__PROG --no-check-certificate"
656 elif [ -f "$cacert" ]; then
657 __PROG
="$__PROG --ca-certificate=${cacert}"
658 elif [ -d "$cacert" ]; then
659 __PROG
="$__PROG --ca-directory=${cacert}"
660 else # exit here because it makes no sense to start loop
661 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
664 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
665 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
667 __RUNPROG
="$__PROG '$__URL'" # build final command
668 __PROG
="GNU Wget" # reuse for error logging
670 # 2nd choice is cURL IPv4/IPv6/HTTPS
671 # libcurl might be compiled without Proxy Support (default in trunk)
672 elif [ -x /usr
/bin
/curl
]; then
673 __PROG
="/usr/bin/curl -RsS -o $DATFILE --stderr $ERRFILE"
674 # force network/interface-device to use for communication
675 if [ -n "$bind_network" ]; then
677 network_get_physdev __DEVICE
$bind_network || \
678 write_log
13 "Can not detect local device using 'network_get_physdev $bind_network' - Error: '$?'"
679 write_log
7 "Force communication via device '$__DEVICE'"
680 __PROG
="$__PROG --interface $__DEVICE"
682 # force ip version to use
683 if [ $force_ipversion -eq 1 ]; then
684 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
686 # set certificate parameters
687 if [ $use_https -eq 1 ]; then
688 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
689 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
690 elif [ -f "$cacert" ]; then
691 __PROG
="$__PROG --cacert $cacert"
692 elif [ -d "$cacert" ]; then
693 __PROG
="$__PROG --capath $cacert"
694 else # exit here because it makes no sense to start loop
695 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
698 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
699 # or check if libcurl compiled with proxy support
700 if [ -z "$proxy" ]; then
701 __PROG
="$__PROG --noproxy '*'"
703 # if libcurl has no proxy support and proxy should be used then force ERROR
704 # libcurl currently no proxy support by default
705 grep -i "all_proxy" /usr
/lib
/libcurl.so
* >/dev
/null
2>&1 || \
706 write_log
13 "cURL: libcurl compiled without Proxy support"
709 __RUNPROG
="$__PROG '$__URL'" # build final command
710 __PROG
="cURL" # reuse for error logging
712 # busybox Wget (did not support neither IPv6 nor HTTPS)
713 elif [ -x /usr
/bin
/wget
]; then
714 __PROG
="/usr/bin/wget -q -O $DATFILE"
715 # force network/ip not supported
716 [ -n "$__BINDIP" ] && \
717 write_log
14 "BusyBox Wget: FORCE binding to specific address not supported"
718 # force ip version not supported
719 [ $force_ipversion -eq 1 ] && \
720 write_log
14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
721 # https not supported
722 [ $use_https -eq 1 ] && \
723 write_log
14 "BusyBox Wget: no HTTPS support"
724 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
725 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
727 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
728 __PROG
="Busybox Wget" # reuse for error logging
731 write_log
13 "Neither 'Wget' nor 'cURL' installed or executable"
735 write_log
7 "#> $__RUNPROG"
736 eval $__RUNPROG # DO transfer
737 __ERR
=$?
# save error code
738 [ $__ERR -eq 0 ] && return 0 # no error leave
739 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
741 write_log
3 "$__PROG Error: '$__ERR'"
742 write_log
7 "$(cat $ERRFILE)" # report error
744 [ $VERBOSE_MODE -gt 1 ] && {
745 # VERBOSE_MODE > 1 then NO retry
746 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
750 __CNT
=$
(( $__CNT + 1 )) # increment error counter
751 # if error count > retry_count leave here
752 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
753 write_log
14 "Transfer failed after $retry_count retries"
755 write_log
4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
756 sleep $RETRY_SECONDS &
758 wait $PID_SLEEP # enable trap-handler
761 # we should never come here there must be a programming error
762 write_log
12 "Error in 'do_transfer()' - program coding error"
766 # $1 # IP to set at DDNS service provider
769 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
771 if [ $ALLOW_LOCAL_IP -eq 0 ]; then
772 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
773 [ $use_ipv6 -eq 0 ] && __IP
=$
(echo $1 |
grep -v -E "(^0|^10\.|^100\.6[4-9]\.|^100\.[7-9][0-9]\.|^100\.1[0-1][0-9]\.|^100\.12[0-7]\.|^127|^169\.254|^172\.1[6-9]\.|^172\.2[0-9]\.|^172\.3[0-1]\.|^192\.168)")
774 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
775 [ -z "$__IP" ] && write_log
14 "Private or invalid or no IP '$1' given! Please check your configuration"
780 if [ -n "$update_script" ]; then
781 write_log
7 "parsing script '$update_script'"
787 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
788 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
789 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
791 do_transfer
"$__URL" ||
return 1
793 write_log
7 "DDNS Provider answered:\n$(cat $DATFILE)"
796 # TODO analyze providers answer
797 # "good" or "nochg" = dyndns.com compatible API
798 # grep -i -E "good|nochg" $DATFILE >/dev/null 2>&1
799 # return $? # "0" if found
804 # $1 Name of Variable to store local IP (LOCAL_IP)
805 local __CNT
=0 # error counter
806 local __RUNPROG __DATA __URL __ERR
808 [ $# -ne 1 ] && write_log
12 "Error calling 'get_local_ip()' - wrong number of parameters"
809 write_log
7 "Detect local IP on '$ip_source'"
814 # set correct program
815 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
816 || __RUNPROG
="network_get_ipaddr6"
817 eval "$__RUNPROG __DATA $ip_network" || \
818 write_log
13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
819 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on network '$ip_network'"
822 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
823 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
825 if [ $__ERR -eq 0 ]; then
826 if [ $use_ipv6 -eq 0 ]; then
828 /inet addr:/ { # Filter IPv4
829 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
831 $3=""; # remove Bcast: ...
832 $4=""; # remove Mask: ...
833 FS=":"; # separator ":"
834 $0=$0; # reread to activate separator
836 FS=" "; # set back separator to default " "
837 $0=$0; # reread to activate separator (remove whitespaces)
838 print $1; # print IPv4 addr
843 /inet6/ && /: [0-9a-eA-E]/ && !/\/128/ { # Filter IPv6 exclude fxxx and /128 prefix
844 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
845 FS="/"; # separator "/"
846 $0=$0; # reread to activate separator
847 $2=""; # remove everything behind "/"
848 FS=" "; # set back separator to default " "
849 $0=$0; # reread to activate separator
850 print $3; # print IPv6 addr
854 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on interface '$ip_interface'"
856 write_log
3 "ifconfig Error: '$__ERR'"
857 write_log
7 "$(cat $ERRFILE)" # report error
861 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
862 eval $ip_script >$DATFILE 2>$ERRFILE
864 if [ $__ERR -eq 0 ]; then
865 __DATA
=$
(cat $DATFILE)
866 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected via script '$ip_script'"
868 write_log
3 "$ip_script Error: '$__ERR'"
869 write_log
7 "$(cat $ERRFILE)" # report error
873 do_transfer
"$ip_url"
874 # use correct regular expression
875 [ $use_ipv6 -eq 0 ] \
876 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
877 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
878 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on web at '$ip_url'"
881 write_log
12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
884 # valid data found return here
885 [ -n "$__DATA" ] && {
886 eval "$1=\"$__DATA\""
890 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
892 write_log
7 "Data detected:\n$(cat $DATFILE)"
894 [ $VERBOSE_MODE -gt 1 ] && {
895 # VERBOSE_MODE > 1 then NO retry
896 write_log
4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
900 __CNT
=$
(( $__CNT + 1 )) # increment error counter
901 # if error count > retry_count leave here
902 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
903 write_log
14 "Get local IP via '$ip_source' failed after $retry_count retries"
904 write_log
4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
905 sleep $RETRY_SECONDS &
907 wait $PID_SLEEP # enable trap-handler
910 # we should never come here there must be a programming error
911 write_log
12 "Error in 'get_local_ip()' - program coding error"
914 get_registered_ip
() {
915 # $1 Name of Variable to store public IP (REGISTERED_IP)
916 # $2 (optional) if set, do not retry on error
917 local __CNT
=0 # error counter
919 local __REGEX __PROG __RUNPROG __DATA
923 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
924 write_log
7 "Detect registered/public IP"
926 # set correct regular expression
927 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
929 if [ -x /usr
/bin
/host ]; then
930 __PROG
="/usr/bin/host"
931 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
932 if [ $force_ipversion -eq 1 ]; then # force IP version
933 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
935 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
937 __RUNPROG
="$__PROG $domain $dns_server >$DATFILE 2>$ERRFILE"
939 elif [ -x /usr
/bin
/nslookup ]; then # last use BusyBox nslookup
940 [ $force_ipversion -ne 0 -o $force_dnstcp -ne 0 ] && \
941 write_log
14 "Busybox nslookup - no support to 'force IP Version' or 'DNS over TCP'"
943 __RUNPROG
="/usr/bin/nslookup $domain $dns_server >$DATFILE 2>$ERRFILE"
944 __PROG
="BusyBox nslookup"
945 else # there must be an error
946 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
950 write_log
7 "#> $__RUNPROG"
953 if [ $__ERR -ne 0 ]; then
954 write_log
3 "$__PROG error: '$__ERR'"
955 write_log
7 "$(cat $ERRFILE)"
957 if [ "$__PROG" = "BIND host" ]; then
958 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
960 __DATA
=$
(cat $DATFILE |
sed -ne "3,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
962 [ -n "$__DATA" ] && {
963 write_log
7 "Registered IP '$__DATA' detected"
964 eval "$1=\"$__DATA\"" # valid data found
965 return 0 # leave here
967 write_log
4 "NO valid IP found"
971 [ $LUCI_HELPER ] && return $__ERR # no retry if called by LuCI helper script
972 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
973 [ $VERBOSE_MODE -gt 1 ] && {
974 # VERBOSE_MODE > 1 then NO retry
975 write_log
4 "Get registered/public IP for '$domain' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
979 __CNT
=$
(( $__CNT + 1 )) # increment error counter
980 # if error count > retry_count leave here
981 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
982 write_log
14 "Get registered/public IP for '$domain' failed after $retry_count retries"
984 write_log
4 "Get registered/public IP for '$domain' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
985 sleep $RETRY_SECONDS &
987 wait $PID_SLEEP # enable trap-handler
990 # we should never come here there must be a programming error
991 write_log
12 "Error in 'get_registered_ip()' - program coding error"
995 # $1 Variable to store result in
996 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
997 local __UPTIME
=$
(cat /proc
/uptime
)
998 eval "$1=\"${__UPTIME%%.*}\""
1003 # $2 optional (exit status)
1006 local __OLD_IFS
=$IFS
1007 local __NEWLINE_IFS
='
1010 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
1013 0) if [ $__ERR -eq 0 ]; then
1014 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
1016 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1018 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1019 # reload config via starting the script again
1020 eval "/usr/lib/ddns/dynamic_dns_updater.sh $SECTION_ID $VERBOSE_MODE &"
1021 exit 0 ;; # and leave this one
1022 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)\n";;
1023 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)\n";;
1024 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)\n";;
1025 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1028 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1030 for __PID
in $__PIDS; do
1031 kill -$1 $__PID # terminate it
1035 # remove out and err file
1036 [ -f $DATFILE ] && rm -f $DATFILE
1037 [ -f $ERRFILE ] && rm -f $ERRFILE
1039 # exit with correct handling:
1040 # remove trap handling settings and send kill to myself
1042 [ $1 -gt 0 ] && kill -$1 $$
1047 # $2 name of variable to store TLD
1048 # $3 name of variable to store (reg)Domain
1049 # $4 name of variable to store Host/Subdomain
1051 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1053 _SET
="$@" # save given parameters
1054 local _FHOST _FTLD _FOUND
1055 local _FDOM
=$
(echo "$1" |
tr [A-Z
] [a-z
]) # to lower
1057 set -- $
(echo "$_FDOM" |
tr "." " ") # replace DOT with SPACE and set as script parameters
1058 _FDOM
="" # clear variable for later reuse
1060 while [ -n "$1" ] ; do # as long we have parameters
1061 _FTLD
=$
(echo $@ |
tr " " ".") # build back dot separated as TLD
1062 # look if match excludes "!" in tld_names.dat
1063 grep -E "^!$_FTLD$" $TLDFILE >/dev
/null
2>&1 ||
{
1064 # Don't match excludes
1065 # check if match any "*" in tld_names.dat
1066 grep -E "^*.$_FTLD$" $TLDFILE >/dev
/null
2>&1 && {
1068 break # found leave while
1070 # check if exact match in tld_names.dat
1071 grep -E "^$_FTLD$" $TLDFILE >/dev
/null
2>&1 && {
1073 break # found leave while
1077 _FHOST
="$_FHOST $_FDOM" # append DOMAIN to last found HOST
1078 _FDOM
="$1" # set 1st parameter as DOMAIN
1079 _FTLD
="" # clear TLD
1080 shift # delete 1st parameter and retry with the rest
1083 set -- $_SET # set back parameters from function call
1084 [ -n "$_FHOST" ] && _FHOST
=$
(echo $_FHOST |
tr " " ".") # put dots back into HOST
1085 [ -n "$_FOUND" ] && {
1086 eval "$2=$_FTLD" # set found TLD
1087 eval "$3=$_FDOM" # set found registrable domain
1088 eval "$4=$_FHOST" # set found HOST/SUBDOMAIN
1091 eval "$2=''" # clear TLD
1092 eval "$3=''" # clear registrable domain
1093 eval "$4=''" # clear HOST/SUBDOMAIN