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
33 SECTION_ID
="" # hold config's section name
34 VERBOSE_MODE
=1 # default mode is log to console, but easily changed with parameter
36 LOGFILE
="" # logfile - all files are set in dynamic_dns_updater.sh
38 UPDFILE
="" # store UPTIME of last update
39 DATFILE
="" # save stdout data of WGet and other external programs called
40 ERRFILE
="" # save stderr output of WGet and other external programs called
41 TLDFILE
=/usr
/lib
/ddns
/tld_names.dat.gz
# TLD file used by split_FQDN
43 CHECK_SECONDS
=0 # calculated seconds out of given
44 FORCE_SECONDS
=0 # interval and unit
45 RETRY_SECONDS
=0 # in configuration
47 LAST_TIME
=0 # holds the uptime of last successful update
48 CURR_TIME
=0 # holds the current uptime
49 NEXT_TIME
=0 # calculated time for next FORCED update
50 EPOCH_TIME
=0 # seconds since 1.1.1970 00:00:00
52 REGISTERED_IP
="" # holds the IP read from DNS
53 LOCAL_IP
="" # holds the local IP read from the box
55 URL_USER
="" # url encoded $username from config file
56 URL_PASS
="" # url encoded $password from config file
57 URL_PENC
="" # url encoded $param_enc from config file
59 SRV_ANSWER
="" # Answer given by service on success
61 ERR_LAST
=0 # used to save $? return code of program and function calls
62 ERR_UPDATE
=0 # error counter on different local and registered ip
64 PID_SLEEP
=0 # ProcessID of current background "sleep"
66 # allow NON-public IP's
67 ALLOW_LOCAL_IP
=$
(uci
-q get ddns.global.allow_local_ip
) || ALLOW_LOCAL_IP
=0
69 # directory to store run information to.
70 RUNDIR
=$
(uci
-q get ddns.global.run_dir
) || RUNDIR
="/var/run/ddns"
71 [ -d $RUNDIR ] || mkdir
-p -m755 $RUNDIR
73 # directory to store log files
74 LOGDIR
=$
(uci
-q get ddns.global.log_dir
) || LOGDIR
="/var/log/ddns"
75 [ -d $LOGDIR ] || mkdir
-p -m755 $LOGDIR
77 # number of lines to before rotate logfile
78 LOGLINES
=$
(uci
-q get ddns.global.log_lines
) || LOGLINES
=250
79 LOGLINES
=$
((LOGLINES
+ 1)) # correct sed handling
81 # format to show date information in log and luci-app-ddns default ISO 8601 format
82 DATE_FORMAT
=$
(uci
-q get ddns.global.date_format
) || DATE_FORMAT
="%F %R"
83 DATE_PROG
="date +'$DATE_FORMAT'"
85 # regular expression to detect IPv4 / IPv6
86 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
87 IPV4_REGEX
="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
88 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
89 IPV6_REGEX
="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
91 # detect if called by dynamic_dns_lucihelper.sh script, disable retrys (empty variable == false)
92 [ "$(basename $0)" = "dynamic_dns_lucihelper.sh" ] && LUCI_HELPER
="TRUE" || LUCI_HELPER
=""
94 # USE_CURL if GNU Wget and cURL installed normally Wget is used by do_transfer()
95 # to change this use global option use_curl '1'
96 USE_CURL
=$
(uci
-q get ddns.global.use_curl
) || USE_CURL
=0 # read config
97 [ -x /usr
/bin
/curl
] || USE_CURL
=0 # check for cURL
99 # loads all options for a given package and section
100 # also, sets all_option_variables to a list of the variable names
101 # $1 = ddns, $2 = SECTION_ID
102 load_all_config_options
()
105 local __SECTIONID
="$2"
107 local __ALL_OPTION_VARIABLES
=""
109 # this callback loads all the variables in the __SECTIONID section when we do
110 # config_load. We need to redefine the option_cb for different sections
111 # so that the active one isn't still active after we're done with it. For reference
112 # the $1 variable is the name of the option and $2 is the name of the section
115 if [ .
"$2" = .
"$__SECTIONID" ]; then
118 __ALL_OPTION_VARIABLES
="$__ALL_OPTION_VARIABLES $1"
121 option_cb
() { return 0; }
125 config_load
"$__PKGNAME"
127 # Given SECTION_ID not found so no data, so return 1
128 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
130 for __VAR
in $__ALL_OPTION_VARIABLES
132 config_get
"$__VAR" "$__SECTIONID" "$__VAR"
137 # read's all service sections from ddns config
138 # $1 = Name of variable to store
139 load_all_service_sections
() {
143 # only look for section type "service", ignore everything else
144 [ "$1" = "service" ] && __DATA
="$__DATA $2"
148 eval "$1=\"$__DATA\""
152 # starts updater script for all given sections or only for the one given
153 # $1 = interface (Optional: when given only scripts are started
154 # configured for that interface)
155 # used by /etc/hotplug.d/iface/25-ddns on IFUP
156 # and by /etc/init.d/ddns start
157 start_daemon_for_all_ddns_sections
()
164 load_all_service_sections __SECTIONS
165 for __SECTIONID
in $__SECTIONS; do
166 config_get __IFACE
"$__SECTIONID" interface
"wan"
167 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
168 /usr
/lib
/ddns
/dynamic_dns_updater.sh
$__SECTIONID 0 >/dev
/null
2>&1 &
172 # stop sections process incl. childs (sleeps)
174 stop_section_processes
() {
176 local __PIDFILE
="$RUNDIR/$1.pid"
177 [ $# -ne 1 ] && write_log
12 "Error calling 'stop_section_processes()' - wrong number of parameters"
179 [ -e "$__PIDFILE" ] && {
180 __PID
=$
(cat $__PIDFILE)
181 ps |
grep "^[\t ]*$__PID" >/dev
/null
2>&1 && kill $__PID || __PID
=0 # terminate it
183 [ $__PID -eq 0 ] # report if process was running
186 # stop updater script for all defines sections or only for one given
187 # $1 = interface (optional)
188 # used by /etc/hotplug.d/iface/25-ddns on 'ifdown'
189 # and by /etc/init.d/ddns stop
190 # needed because we also need to kill "sleep" child processes
191 stop_daemon_for_all_ddns_sections
() {
197 load_all_service_sections __SECTIONS
198 for __SECTIONID
in $__SECTIONS; do
199 config_get __IFACE
"$__SECTIONID" interface
"wan"
200 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
201 stop_section_processes
"$__SECTIONID"
205 # reports to console, logfile, syslog
206 # $1 loglevel 7 == Debug to 0 == EMERG
207 # value +10 will exit the scripts
208 # $2..n text to report
210 local __LEVEL __EXIT __CMD __MSG
211 local __TIME
=$
(date +%H
%M
%S
)
219 shift # remove loglevel
220 [ $__EXIT -eq 0 ] && __MSG
="$*" || __MSG
="$* - TERMINATE"
221 case $__LEVEL in # create log message and command depending on loglevel
222 0) __CMD
="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
223 __MSG
=" $__TIME EMERG : $__MSG" ;;
224 1) __CMD
="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
225 __MSG
=" $__TIME ALERT : $__MSG" ;;
226 2) __CMD
="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
227 __MSG
=" $__TIME CRIT : $__MSG" ;;
228 3) __CMD
="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
229 __MSG
=" $__TIME ERROR : $__MSG" ;;
230 4) __CMD
="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
231 __MSG
=" $__TIME WARN : $__MSG" ;;
232 5) __CMD
="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
233 __MSG
=" $__TIME note : $__MSG" ;;
234 6) __CMD
="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
235 __MSG
=" $__TIME info : $__MSG" ;;
236 7) __MSG
=" $__TIME : $__MSG";;
241 [ $VERBOSE_MODE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
243 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE_MODE -gt 1 ]; then
244 echo -e "$__MSG" >> $LOGFILE
245 # VERBOSE_MODE > 1 then NO loop so NO truncate log to $LOGLINES lines
246 [ $VERBOSE_MODE -gt 1 ] ||
sed -i -e :a
-e '$q;N;'$LOGLINES',$D;ba' $LOGFILE
248 [ $LUCI_HELPER ] && return # nothing else todo when running LuCI helper script
249 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
250 __CMD
=$
(echo -e "$__CMD" |
tr -d '\n' |
tr '\t' ' ') # remove \n \t chars
251 [ $__EXIT -eq 1 ] && {
252 $__CMD # force syslog before exit
255 [ $use_syslog -eq 0 ] && return
256 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && $__CMD
260 # replace all special chars to their %hex value
261 # used for USERNAME and PASSWORD in update_url
262 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
263 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
264 # "$"(Dollar) # because used as variable output
265 # tested with the following string stored via Luci Application as password / username
266 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
268 # $1 Name of Variable to store encoded string to
269 # $2 string to encode
270 local __STR __LEN __CHAR __OUT
274 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
276 __STR
="$2" # read string to encode
277 __LEN
=${#__STR} # get string length
279 while [ $__POS -le $__LEN ]; do
280 # read one chat of the string
281 __CHAR
=$
(expr substr
"$__STR" $__POS 1)
289 # special char get %hex code
290 __OUT
=$
(printf '%%%02x' "'$__CHAR" )
293 __ENC
="${__ENC}${__OUT}" # append to encoded string
294 __POS
=$
(( $__POS + 1 )) # increment position
297 eval "$1=\"$__ENC\"" # transfer back to variable
301 # extract url or script for given DDNS Provider from
302 # file /usr/lib/ddns/services for IPv4 or from
303 # file /usr/lib/ddns/services_ipv6 for IPv6
304 # $1 Name of Variable to store url to
305 # $2 Name of Variable to store script to
306 # $3 Name of Variable to store service answer to
308 [ $# -ne 3 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
310 __FILE
="/usr/lib/ddns/services" # IPv4
311 [ $use_ipv6 -ne 0 ] && __FILE
="/usr/lib/ddns/services_ipv6" # IPv6
313 # workaround with variables; pipe create subshell with no give back of variable content
315 # only grep without # or whitespace at linestart | remove "
316 # grep -v -E "(^#|^[[:space:]]*$)" $__FILE | sed -e s/\"//g > pipe_$$ &
317 sed '/^#/d/^[ \t]*$/ds/\"//g' $__FILE > pipe_$$
&
319 while read __SERVICE __DATA __ANSWER
; do
320 if [ "$__SERVICE" = "$service_name" ]; then
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\""
327 eval "$3=\"$__ANSWER\""
334 eval "$1=\"\"" # no service match clear variables
340 # Calculate seconds from interval and unit
341 # $1 Name of Variable to store result in
343 # $3 Unit of time interval
345 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
347 "days" ) eval "$1=$(( $2 * 86400 ))";;
348 "hours" ) eval "$1=$(( $2 * 3600 ))";;
349 "minutes" ) eval "$1=$(( $2 * 60 ))";;
356 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
357 # only did the following changes
358 # - commented out "#!/bin/bash" and usage section
359 # - replace exit by return for usage as function
360 # - some reformatting
362 # timeout [-SIG] time [--] command args...
364 # Run the given command until completion, but kill it if it runs too long.
365 # Specifically designed to exit immediately (no sleep interval) and clean up
366 # nicely without messages or leaving any extra processes when finished.
369 # timeout 5 countdown
371 # Based on notes in my "Shell Script Hints", section "Command Timeout"
372 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
374 # This script uses a lot of tricks to terminate both the background command,
375 # the timeout script, and even the sleep process. It also includes trap
376 # commands to prevent sub-shells reporting expected "Termination Errors".
378 # It took years of occasional trials, errors and testing to get a pure bash
379 # timeout command working as well as this does.
381 #.Anthony Thyssen 6 April 2011
383 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
384 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
385 # PROGNAME=$(basename $PROGNAME) # base name of program
387 # output the script comments as docs
389 # echo >&2 "$PROGNAME:" "$@"
390 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
396 while [ $# -gt 0 ]; do
399 # forced end of user options
409 # unforced end of user options
415 # run main command in backgrounds and get its pid
419 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
422 # cleanup sleep process
423 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
424 # sleep timeout period in background
429 kill $SIG $command_pid >/dev
/null
2>&1
434 # Wait for main command to finished or be timed out
438 # Clean up timeout sub-shell - if it is still running!
439 kill $timeout_pid 2>/dev
/null
440 wait $timeout_pid 2>/dev
/null
442 # Uncomment to check if a LONG sleep still running (no sleep should be)
445 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
450 # verify given host and port is connectable
451 # $1 Host/IP to verify
456 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
458 # 1 system specific error
459 # 2 nslookup/host error
460 # 3 nc (netcat) error
461 # 4 unmatched IP version
463 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
465 # check if ip or FQDN was given
466 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
467 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
468 # if FQDN given get IP address
469 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
470 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
472 __RUNPROG
="/usr/bin/host -t ANY $__HOST >$DATFILE 2>$ERRFILE"
473 else # use BusyBox nslookup
474 __PROG
="BusyBox nslookup"
475 __RUNPROG
="/usr/bin/nslookup $__HOST >$DATFILE 2>$ERRFILE"
477 write_log
7 "#> $__RUNPROG"
481 [ $__ERR -gt 0 ] && {
482 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
483 write_log
7 "$(cat $ERRFILE)"
487 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
488 __IPV4
=$
(cat $DATFILE |
awk -F "address " '/has address/ {print $2; exit}' )
489 __IPV6
=$
(cat $DATFILE |
awk -F "address " '/has IPv6/ {print $2; exit}' )
490 else # use BusyBox nslookup
491 __IPV4
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }")
492 __IPV6
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }")
496 # check IP version if forced
497 if [ $force_ipversion -ne 0 ]; then
499 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
500 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
501 [ $__ERR -gt 0 ] && {
502 [ $LUCI_HELPER ] && return 4
503 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
508 # busybox nc compiled without -l option "NO OPT l!" -> critical error
509 /usr
/bin
/nc
--help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
510 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
511 # busybox nc compiled with extensions
512 /usr
/bin
/nc
--help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
515 # run busybox nc to HOST PORT
516 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
517 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
518 # not worrying, if there is an IPv6 wan address
519 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
520 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
522 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
523 __RUNPROG
="/usr/bin/nc -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
524 write_log
7 "#> $__RUNPROG"
527 [ $__ERR -eq 0 ] && return 0
528 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
529 write_log
7 "$(cat $ERRFILE)"
531 else # nc compiled without extensions (no timeout support)
532 __RUNPROG
="timeout 2 -- /usr/bin/nc $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
533 write_log
7 "#> $__RUNPROG"
536 [ $__ERR -eq 0 ] && return 0
537 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
542 # verify given DNS server if connectable
543 # $1 DNS server to verify
545 local __ERR
=255 # last error buffer
546 local __CNT
=0 # error counter
548 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
549 write_log
7 "Verify DNS server '$1'"
551 while [ $__ERR -ne 0 ]; do
553 verify_host_port
"$1" "53"
555 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
557 elif [ $__ERR -ne 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
558 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
560 elif [ $__ERR -ne 0 ]; then
561 __CNT
=$
(( $__CNT + 1 )) # increment error counter
562 # if error count > retry_count leave here
563 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
564 write_log
14 "Verify DNS server '$1' failed after $retry_count retries"
566 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
567 sleep $RETRY_SECONDS &
569 wait $PID_SLEEP # enable trap-handler
576 # analyze and verify given proxy string
577 # $1 Proxy-String to verify
579 # complete entry user:password@host:port
580 # inside user and password NO '@' of ":" allowed
581 # host and port only host:port
582 # host only host ERROR unsupported
583 # IPv4 address instead of host 123.234.234.123
584 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
585 local __TMP __HOST __PORT
586 local __ERR
=255 # last error buffer
587 local __CNT
=0 # error counter
589 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
590 write_log
7 "Verify Proxy server 'http://$1'"
592 # try to split user:password "@" host:port
593 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
594 # no "@" found - only host:port is given
595 [ -z "$__TMP" ] && __TMP
="$1"
596 # now lets check for IPv6 address
597 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
598 # IPv6 host address found read port
599 if [ -n "$__HOST" ]; then
601 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
603 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
604 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
606 # No Port detected - EXITING
607 [ -z "$__PORT" ] && {
608 [ $LUCI_HELPER ] && return 5
609 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
612 while [ $__ERR -gt 0 ]; do
613 verify_host_port
"$__HOST" "$__PORT"
615 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
617 elif [ $__ERR -gt 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
618 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
620 elif [ $__ERR -gt 0 ]; then
621 __CNT
=$
(( $__CNT + 1 )) # increment error counter
622 # if error count > retry_count leave here
623 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
624 write_log
14 "Verify Proxy server '$1' failed after $retry_count retries"
626 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
627 sleep $RETRY_SECONDS &
629 wait $PID_SLEEP # enable trap-handler
640 local __CNT
=0 # error counter
641 local __PROG __RUNPROG
643 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
645 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
646 grep -i "\+ssl" /usr
/bin
/wget
>/dev
/null
2>&1 # check for Wget with SSL support
647 if [ $?
-eq 0 -a $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
648 __PROG
="/usr/bin/wget -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
649 # force network/ip to use for communication
650 if [ -n "$bind_network" ]; then
652 # set correct program to detect IP
653 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" || __RUNPROG
="network_get_ipaddr6"
654 eval "$__RUNPROG __BINDIP $bind_network" || \
655 write_log
13 "Can not detect local IP using '$__RUNPROG $bind_network' - Error: '$?'"
656 write_log
7 "Force communication via IP '$__BINDIP'"
657 __PROG
="$__PROG --bind-address=$__BINDIP"
659 # force ip version to use
660 if [ $force_ipversion -eq 1 ]; then
661 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
663 # set certificate parameters
664 if [ $use_https -eq 1 ]; then
665 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
666 __PROG
="$__PROG --no-check-certificate"
667 elif [ -f "$cacert" ]; then
668 __PROG
="$__PROG --ca-certificate=${cacert}"
669 elif [ -d "$cacert" ]; then
670 __PROG
="$__PROG --ca-directory=${cacert}"
671 else # exit here because it makes no sense to start loop
672 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
675 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
676 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
678 __RUNPROG
="$__PROG '$__URL'" # build final command
679 __PROG
="GNU Wget" # reuse for error logging
681 # 2nd choice is cURL IPv4/IPv6/HTTPS
682 # libcurl might be compiled without Proxy Support (default in trunk)
683 elif [ -x /usr
/bin
/curl
]; then
684 __PROG
="/usr/bin/curl -RsS -o $DATFILE --stderr $ERRFILE"
685 # force network/interface-device to use for communication
686 if [ -n "$bind_network" ]; then
688 network_get_physdev __DEVICE
$bind_network || \
689 write_log
13 "Can not detect local device using 'network_get_physdev $bind_network' - Error: '$?'"
690 write_log
7 "Force communication via device '$__DEVICE'"
691 __PROG
="$__PROG --interface $__DEVICE"
693 # force ip version to use
694 if [ $force_ipversion -eq 1 ]; then
695 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
697 # set certificate parameters
698 if [ $use_https -eq 1 ]; then
699 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
700 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
701 elif [ -f "$cacert" ]; then
702 __PROG
="$__PROG --cacert $cacert"
703 elif [ -d "$cacert" ]; then
704 __PROG
="$__PROG --capath $cacert"
705 else # exit here because it makes no sense to start loop
706 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
709 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
710 # or check if libcurl compiled with proxy support
711 if [ -z "$proxy" ]; then
712 __PROG
="$__PROG --noproxy '*'"
714 # if libcurl has no proxy support and proxy should be used then force ERROR
715 # libcurl currently no proxy support by default
716 grep -i "all_proxy" /usr
/lib
/libcurl.so
* >/dev
/null
2>&1 || \
717 write_log
13 "cURL: libcurl compiled without Proxy support"
720 __RUNPROG
="$__PROG '$__URL'" # build final command
721 __PROG
="cURL" # reuse for error logging
723 # busybox Wget (did not support neither IPv6 nor HTTPS)
724 elif [ -x /usr
/bin
/wget
]; then
725 __PROG
="/usr/bin/wget -q -O $DATFILE"
726 # force network/ip not supported
727 [ -n "$__BINDIP" ] && \
728 write_log
14 "BusyBox Wget: FORCE binding to specific address not supported"
729 # force ip version not supported
730 [ $force_ipversion -eq 1 ] && \
731 write_log
14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
732 # https not supported
733 [ $use_https -eq 1 ] && \
734 write_log
14 "BusyBox Wget: no HTTPS support"
735 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
736 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
738 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
739 __PROG
="Busybox Wget" # reuse for error logging
742 write_log
13 "Neither 'Wget' nor 'cURL' installed or executable"
746 write_log
7 "#> $__RUNPROG"
747 eval $__RUNPROG # DO transfer
748 __ERR
=$?
# save error code
749 [ $__ERR -eq 0 ] && return 0 # no error leave
750 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
752 write_log
3 "$__PROG Error: '$__ERR'"
753 write_log
7 "$(cat $ERRFILE)" # report error
755 [ $VERBOSE_MODE -gt 1 ] && {
756 # VERBOSE_MODE > 1 then NO retry
757 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
761 __CNT
=$
(( $__CNT + 1 )) # increment error counter
762 # if error count > retry_count leave here
763 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
764 write_log
14 "Transfer failed after $retry_count retries"
766 write_log
4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
767 sleep $RETRY_SECONDS &
769 wait $PID_SLEEP # enable trap-handler
772 # we should never come here there must be a programming error
773 write_log
12 "Error in 'do_transfer()' - program coding error"
777 # $1 # IP to set at DDNS service provider
780 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
782 if [ $ALLOW_LOCAL_IP -eq 0 ]; then
783 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
784 [ $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)")
785 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
786 [ -z "$__IP" ] && write_log
14 "Private or invalid or no IP '$1' given! Please check your configuration"
791 if [ -n "$update_script" ]; then
792 write_log
7 "parsing script '$update_script'"
798 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
799 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
800 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
801 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
803 do_transfer
"$__URL" ||
return 1
805 write_log
7 "DDNS Provider answered:\n$(cat $DATFILE)"
807 [ -z "$SRV_ANSWER" ] && return 0 # not set then ignore
809 grep -i -E "$SRV_ANSWER" $DATFILE >/dev
/null
2>&1
810 return $?
# "0" if found
815 # $1 Name of Variable to store local IP (LOCAL_IP)
816 local __CNT
=0 # error counter
817 local __RUNPROG __DATA __URL __ERR
819 [ $# -ne 1 ] && write_log
12 "Error calling 'get_local_ip()' - wrong number of parameters"
820 write_log
7 "Detect local IP on '$ip_source'"
825 # set correct program
826 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
827 || __RUNPROG
="network_get_ipaddr6"
828 eval "$__RUNPROG __DATA $ip_network" || \
829 write_log
13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
830 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on network '$ip_network'"
833 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
834 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
836 if [ $__ERR -eq 0 ]; then
837 if [ $use_ipv6 -eq 0 ]; then
839 /inet addr:/ { # Filter IPv4
840 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
842 $3=""; # remove Bcast: ...
843 $4=""; # remove Mask: ...
844 FS=":"; # separator ":"
845 $0=$0; # reread to activate separator
847 FS=" "; # set back separator to default " "
848 $0=$0; # reread to activate separator (remove whitespaces)
849 print $1; # print IPv4 addr
854 /inet6/ && /: [0-9a-eA-E]/ && !/\/128/ { # Filter IPv6 exclude fxxx and /128 prefix
855 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
856 FS="/"; # separator "/"
857 $0=$0; # reread to activate separator
858 $2=""; # remove everything behind "/"
859 FS=" "; # set back separator to default " "
860 $0=$0; # reread to activate separator
861 print $3; # print IPv6 addr
865 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on interface '$ip_interface'"
867 write_log
3 "ifconfig Error: '$__ERR'"
868 write_log
7 "$(cat $ERRFILE)" # report error
872 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
873 eval $ip_script >$DATFILE 2>$ERRFILE
875 if [ $__ERR -eq 0 ]; then
876 __DATA
=$
(cat $DATFILE)
877 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected via script '$ip_script'"
879 write_log
3 "$ip_script Error: '$__ERR'"
880 write_log
7 "$(cat $ERRFILE)" # report error
884 do_transfer
"$ip_url"
885 # use correct regular expression
886 [ $use_ipv6 -eq 0 ] \
887 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
888 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
889 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on web at '$ip_url'"
892 write_log
12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
895 # valid data found return here
896 [ -n "$__DATA" ] && {
897 eval "$1=\"$__DATA\""
901 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
903 write_log
7 "Data detected:\n$(cat $DATFILE)"
905 [ $VERBOSE_MODE -gt 1 ] && {
906 # VERBOSE_MODE > 1 then NO retry
907 write_log
4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
911 __CNT
=$
(( $__CNT + 1 )) # increment error counter
912 # if error count > retry_count leave here
913 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
914 write_log
14 "Get local IP via '$ip_source' failed after $retry_count retries"
915 write_log
4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
916 sleep $RETRY_SECONDS &
918 wait $PID_SLEEP # enable trap-handler
921 # we should never come here there must be a programming error
922 write_log
12 "Error in 'get_local_ip()' - program coding error"
925 get_registered_ip
() {
926 # $1 Name of Variable to store public IP (REGISTERED_IP)
927 # $2 (optional) if set, do not retry on error
928 local __CNT
=0 # error counter
930 local __REGEX __PROG __RUNPROG __DATA
934 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
935 write_log
7 "Detect registered/public IP"
937 # set correct regular expression
938 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
940 if [ -x /usr
/bin
/host ]; then
941 __PROG
="/usr/bin/host"
942 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
943 if [ $force_ipversion -eq 1 ]; then # force IP version
944 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
946 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
948 __RUNPROG
="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
950 elif [ -x /usr
/bin
/nslookup ]; then # last use BusyBox nslookup
951 [ $force_ipversion -ne 0 -o $force_dnstcp -ne 0 ] && \
952 write_log
14 "Busybox nslookup - no support to 'force IP Version' or 'DNS over TCP'"
954 __RUNPROG
="/usr/bin/nslookup $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
955 __PROG
="BusyBox nslookup"
956 else # there must be an error
957 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
961 write_log
7 "#> $__RUNPROG"
964 if [ $__ERR -ne 0 ]; then
965 write_log
3 "$__PROG error: '$__ERR'"
966 write_log
7 "$(cat $ERRFILE)"
968 if [ "$__PROG" = "BIND host" ]; then
969 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
971 __DATA
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
973 [ -n "$__DATA" ] && {
974 write_log
7 "Registered IP '$__DATA' detected"
975 eval "$1=\"$__DATA\"" # valid data found
976 return 0 # leave here
978 write_log
4 "NO valid IP found"
982 [ $LUCI_HELPER ] && return $__ERR # no retry if called by LuCI helper script
983 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
984 [ $VERBOSE_MODE -gt 1 ] && {
985 # VERBOSE_MODE > 1 then NO retry
986 write_log
4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
990 __CNT
=$
(( $__CNT + 1 )) # increment error counter
991 # if error count > retry_count leave here
992 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
993 write_log
14 "Get registered/public IP for '$lookup_host' failed after $retry_count retries"
995 write_log
4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
996 sleep $RETRY_SECONDS &
998 wait $PID_SLEEP # enable trap-handler
1001 # we should never come here there must be a programming error
1002 write_log
12 "Error in 'get_registered_ip()' - program coding error"
1006 # $1 Variable to store result in
1007 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
1008 local __UPTIME
=$
(cat /proc
/uptime
)
1009 eval "$1=\"${__UPTIME%%.*}\""
1014 # $2 optional (exit status)
1017 local __OLD_IFS
=$IFS
1018 local __NEWLINE_IFS
='
1021 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
1024 0) if [ $__ERR -eq 0 ]; then
1025 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
1027 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1029 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1030 # reload config via starting the script again
1031 eval "/usr/lib/ddns/dynamic_dns_updater.sh $SECTION_ID $VERBOSE_MODE &"
1032 exit 0 ;; # and leave this one
1033 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)\n";;
1034 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)\n";;
1035 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)\n";;
1036 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1039 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1041 for __PID
in $__PIDS; do
1042 kill -$1 $__PID # terminate it
1046 # remove out and err file
1047 [ -f $DATFILE ] && rm -f $DATFILE
1048 [ -f $ERRFILE ] && rm -f $ERRFILE
1050 # exit with correct handling:
1051 # remove trap handling settings and send kill to myself
1053 [ $1 -gt 0 ] && kill -$1 $$
1058 # $2 name of variable to store TLD
1059 # $3 name of variable to store (reg)Domain
1060 # $4 name of variable to store Host/Subdomain
1062 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1063 [ -z "$1" ] && write_log
12 "Error calling 'split_FQDN()' - missing FQDN to split"
1064 [ -f $TLDFILE ] || write_log
12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1066 local _HOST _FDOM _CTLD _FTLD
1067 local _SET
="$@" # save given function parameters
1069 local _PAR
=$
(echo "$1" |
tr [A-Z
] [a-z
] |
tr "." " ") # to lower and replace DOT with SPACE
1070 set -- $_PAR # set new as function parameters
1071 _PAR
="" # clear variable for later reuse
1072 while [ -n "$1" ] ; do # as long we have parameters
1073 _PAR
="$1 $_PAR" # invert order of parameters
1076 set -- $_PAR # use new as function parameters
1077 _PAR
="" # clear variable
1079 while [ -n "$1" ] ; do # as long we have parameters
1080 if [ -z "$_CTLD" ]; then # first loop
1081 _CTLD
="$1" # CURRENT TLD to look at
1084 _CTLD
="$1.$_CTLD" # Next TLD to look at
1087 # check if TLD exact match in tld_names.dat, save TLD
1088 zcat
$TLDFILE |
grep -E "^$_CTLD$" >/dev
/null
2>&1 && {
1089 _FTLD
="$_CTLD" # save found
1090 _FDOM
="$1" # save domain next step might be invalid
1093 # check if match any "*" in tld_names.dat,
1094 zcat
$TLDFILE |
grep -E "^\*.$_CTLD$" >/dev
/null
2>&1 && {
1095 [ -z "$1" ] && break # no more data break
1096 # check if next level TLD match excludes "!" in tld_names.dat
1097 if zcat
$TLDFILE |
grep -E "^!$1.$_CTLD$" >/dev
/null
2>&1 ; then
1098 _FTLD
="$_CTLD" # Yes
1105 [ -n "$_FTLD" ] && break # we have something valid, break
1108 # the leftover parameters are the HOST/SUBDOMAIN
1109 while [ -n "$1" ]; do
1110 _HOST
="$1 $HOST" # remember we need to invert
1113 _HOST
=$
(echo $_HOST |
tr " " ".") # insert DOT
1115 set -- $_SET # set back parameters from function call
1116 [ -n "$_FTLD" ] && {
1117 eval "$2=$_FTLD" # set TLD
1118 eval "$3=$_FDOM" # set registrable domain
1119 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1122 eval "$2=''" # clear TLD
1123 eval "$3=''" # clear registrable domain
1124 eval "$4=''" # clear HOST/SUBDOMAIN