2 # /usr/lib/ddns/dynamic_dns_functions.sh
4 #.Distributed under the terms of the GNU General Public License (GPL) version 2.0
5 # Original written by Eric Paul Bishop, January 2008
6 # (Loosely) based on the script on the one posted by exobyte in the forums here:
7 # http://forum.openwrt.org/viewtopic.php?id=14040
8 # extended and partial rewritten
9 #.2014-2018 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
12 # copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
13 # @author Anthony Thyssen 6 April 2011
15 # variables in small chars are read from /etc/config/ddns
16 # variables in big chars are defined inside these scripts as global vars
17 # variables in big chars beginning with "__" are local defined inside functions only
18 # set -vx #script debugger
21 .
/lib
/functions
/network.sh
25 SECTION_ID
="" # hold config's section name
26 VERBOSE
=0 # default mode is log to console, but easily changed with parameter
27 MYPROG
=$
(basename $0) # my program call name
29 LOGFILE
="" # logfile - all files are set in dynamic_dns_updater.sh
31 UPDFILE
="" # store UPTIME of last update
32 DATFILE
="" # save stdout data of WGet and other external programs called
33 ERRFILE
="" # save stderr output of WGet and other external programs called
34 IPFILE
="" # store registered IP for read by LuCI status
35 TLDFILE
=/usr
/share
/public_suffix_list.dat.gz
# TLD file used by split_FQDN
37 CHECK_SECONDS
=0 # calculated seconds out of given
38 FORCE_SECONDS
=0 # interval and unit
39 RETRY_SECONDS
=0 # in configuration
41 LAST_TIME
=0 # holds the uptime of last successful update
42 CURR_TIME
=0 # holds the current uptime
43 NEXT_TIME
=0 # calculated time for next FORCED update
44 EPOCH_TIME
=0 # seconds since 1.1.1970 00:00:00
46 REGISTERED_IP
="" # holds the IP read from DNS
47 LOCAL_IP
="" # holds the local IP read from the box
49 URL_USER
="" # url encoded $username from config file
50 URL_PASS
="" # url encoded $password from config file
51 URL_PENC
="" # url encoded $param_enc from config file
53 UPD_ANSWER
="" # Answer given by service on success
55 ERR_LAST
=0 # used to save $? return code of program and function calls
56 ERR_UPDATE
=0 # error counter on different local and registered ip
58 PID_SLEEP
=0 # ProcessID of current background "sleep"
60 # regular expression to detect IPv4 / IPv6
61 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
62 IPV4_REGEX
="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
63 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
64 IPV6_REGEX
="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
66 # characters that are dangerous to pass to a shell command line
67 SHELL_ESCAPE
="[\"\'\`\$\!();><{}?|\[\]\*\\\\]"
70 DNS_CHARSET
="[@a-zA-Z0-9._-]"
72 # detect if called by ddns-lucihelper.sh script, disable retrys (empty variable == false)
73 LUCI_HELPER
=$
(printf %s
"$MYPROG" |
grep -i "luci")
75 # Name Server Lookup Programs
76 BIND_HOST
=$
(which host)
77 KNOT_HOST
=$
(which khost
)
79 HOSTIP
=$
(which hostip
)
80 NSLOOKUP
=$
(which nslookup)
84 WGET_SSL
=$
(which wget-ssl
)
88 # CURL_PROXY not empty then Proxy support available
89 CURL_PROXY
=$
(find /lib
/usr
/lib
-name libcurl.so
* -exec strings {} 2>/dev
/null \
; |
grep -im1 "all_proxy")
91 UCLIENT_FETCH
=$
(which uclient-fetch
)
93 # Global configuration settings
94 # allow NON-public IP's
95 upd_privateip
=$
(uci
-q get ddns.global.upd_privateip
) || upd_privateip
=0
97 # directory to store run information to.
98 ddns_rundir
=$
(uci
-q get ddns.global.ddns_rundir
) || ddns_rundir
="/var/run/ddns"
99 [ -d $ddns_rundir ] || mkdir
-p -m755 $ddns_rundir
101 # directory to store log files
102 ddns_logdir
=$
(uci
-q get ddns.global.ddns_logdir
) || ddns_logdir
="/var/log/ddns"
103 [ -d $ddns_logdir ] || mkdir
-p -m755 $ddns_logdir
105 # number of lines to before rotate logfile
106 ddns_loglines
=$
(uci
-q get ddns.global.ddns_loglines
) || ddns_loglines
=250
107 ddns_loglines
=$
((ddns_loglines
+ 1)) # correct sed handling
109 # format to show date information in log and luci-app-ddns default ISO 8601 format
110 ddns_dateformat
=$
(uci
-q get ddns.global.ddns_dateformat
) || ddns_dateformat
="%F %R"
111 DATE_PROG
="date +'$ddns_dateformat'"
113 # USE_CURL if GNU Wget and cURL installed normally Wget is used by do_transfer()
114 # to change this use global option use_curl '1'
115 USE_CURL
=$
(uci
-q get ddns.global.use_curl
) || USE_CURL
=0 # read config
116 [ -n "$CURL" ] || USE_CURL
=0 # check for cURL
118 # loads all options for a given package and section
119 # also, sets all_option_variables to a list of the variable names
120 # $1 = ddns, $2 = SECTION_ID
121 load_all_config_options
()
124 local __SECTIONID
="$2"
126 local __ALL_OPTION_VARIABLES
=""
128 # this callback loads all the variables in the __SECTIONID section when we do
129 # config_load. We need to redefine the option_cb for different sections
130 # so that the active one isn't still active after we're done with it. For reference
131 # the $1 variable is the name of the option and $2 is the name of the section
134 if [ .
"$2" = .
"$__SECTIONID" ]; then
137 __ALL_OPTION_VARIABLES
="$__ALL_OPTION_VARIABLES $1"
140 option_cb
() { return 0; }
144 config_load
"$__PKGNAME"
146 # Given SECTION_ID not found so no data, so return 1
147 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
149 for __VAR
in $__ALL_OPTION_VARIABLES
151 config_get
"$__VAR" "$__SECTIONID" "$__VAR"
156 # read's all service sections from ddns config
157 # $1 = Name of variable to store
158 load_all_service_sections
() {
162 # only look for section type "service", ignore everything else
163 [ "$1" = "service" ] && __DATA
="$__DATA $2"
167 eval "$1=\"$__DATA\""
171 # starts updater script for all given sections or only for the one given
172 # $1 = interface (Optional: when given only scripts are started
173 # configured for that interface)
174 # used by /etc/hotplug.d/iface/95-ddns on IFUP
175 # and by /etc/init.d/ddns start
176 start_daemon_for_all_ddns_sections
()
183 load_all_service_sections __SECTIONS
184 for __SECTIONID
in $__SECTIONS; do
185 config_get __IFACE
"$__SECTIONID" interface
"wan"
186 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
187 if [ $VERBOSE -eq 0 ]; then # start in background
188 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v 0 -S "$__SECTIONID" -- start
&
190 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v "$VERBOSE" -S "$__SECTIONID" -- start
195 # stop sections process incl. childs (sleeps)
197 stop_section_processes
() {
199 local __PIDFILE
="$ddns_rundir/$1.pid"
200 [ $# -ne 1 ] && write_log
12 "Error calling 'stop_section_processes()' - wrong number of parameters"
202 [ -e "$__PIDFILE" ] && {
203 __PID
=$
(cat $__PIDFILE)
204 ps |
grep "^[\t ]*$__PID" >/dev
/null
2>&1 && kill $__PID || __PID
=0 # terminate it
206 [ $__PID -eq 0 ] # report if process was running
209 # stop updater script for all defines sections or only for one given
210 # $1 = interface (optional)
211 # used by /etc/hotplug.d/iface/95-ddns on 'ifdown'
212 # and by /etc/init.d/ddns stop
213 # needed because we also need to kill "sleep" child processes
214 stop_daemon_for_all_ddns_sections
() {
220 load_all_service_sections __SECTIONS
221 for __SECTIONID
in $__SECTIONS; do
222 config_get __IFACE
"$__SECTIONID" interface
"wan"
223 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
224 stop_section_processes
"$__SECTIONID"
228 # reports to console, logfile, syslog
229 # $1 loglevel 7 == Debug to 0 == EMERG
230 # value +10 will exit the scripts
231 # $2..n text to report
233 local __LEVEL __EXIT __CMD __MSG __MSE
234 local __TIME
=$
(date +%H
%M
%S
)
242 shift # remove loglevel
243 [ $__EXIT -eq 0 ] && __MSG
="$*" || __MSG
="$* - TERMINATE"
244 case $__LEVEL in # create log message and command depending on loglevel
245 0) __CMD
="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
246 __MSG
=" $__TIME EMERG : $__MSG" ;;
247 1) __CMD
="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
248 __MSG
=" $__TIME ALERT : $__MSG" ;;
249 2) __CMD
="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
250 __MSG
=" $__TIME CRIT : $__MSG" ;;
251 3) __CMD
="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
252 __MSG
=" $__TIME ERROR : $__MSG" ;;
253 4) __CMD
="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
254 __MSG
=" $__TIME WARN : $__MSG" ;;
255 5) __CMD
="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
256 __MSG
=" $__TIME note : $__MSG" ;;
257 6) __CMD
="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
258 __MSG
=" $__TIME info : $__MSG" ;;
259 7) __MSG
=" $__TIME : $__MSG";;
264 [ $VERBOSE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
266 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE -gt 1 ]; then
267 if [ -n "$password" ]; then
268 # url encode __MSG, password already done
269 urlencode __MSE
"$__MSG"
270 # replace encoded password inside encoded message
271 # and url decode (newline was encoded as %00)
272 __MSG
=$
( echo -e "$__MSE" \
273 |
sed -e "s/$URL_PASS/***PW***/g" \
274 |
sed -e "s/+/ /g; s/%00/\n/g; s/%/\\\\x/g" |
xargs -0 printf "%b" )
276 printf "%s\n" "$__MSG" >> $LOGFILE
277 # VERBOSE > 1 then NO loop so NO truncate log to $ddns_loglines lines
278 [ $VERBOSE -gt 1 ] ||
sed -i -e :a
-e '$q;N;'$ddns_loglines',$D;ba' $LOGFILE
280 [ -n "$LUCI_HELPER" ] && return # nothing else todo when running LuCI helper script
281 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
282 __CMD
=$
(echo -e "$__CMD" |
tr -d '\n' |
tr '\t' ' ') # remove \n \t chars
283 [ $__EXIT -eq 1 ] && {
284 $__CMD # force syslog before exit
287 [ $use_syslog -eq 0 ] && return
288 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && $__CMD
293 # replace all special chars to their %hex value
294 # used for USERNAME and PASSWORD in update_url
295 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
296 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
297 # "$"(Dollar) # because used as variable output
298 # tested with the following string stored via Luci Application as password / username
299 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
301 # $1 Name of Variable to store encoded string to
302 # $2 string to encode
303 local __STR __LEN __CHAR __OUT
307 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
309 __STR
="$2" # read string to encode
310 __LEN
=${#__STR} # get string length
312 while [ $__POS -le $__LEN ]; do
313 # read one chat of the string
314 __CHAR
=$
(expr substr
"$__STR" $__POS 1)
322 # special char get %hex code
323 __OUT
=$
(printf '%%%02x' "'$__CHAR" )
326 __ENC
="${__ENC}${__OUT}" # append to encoded string
327 __POS
=$
(( $__POS + 1 )) # increment position
330 eval "$1=\"$__ENC\"" # transfer back to variable
334 # extract url or script for given DDNS Provider from
335 # file /etc/ddns/services for IPv4 or from
336 # file /etc/ddns/services_ipv6 for IPv6
337 # $1 Name of Variable to store url to
338 # $2 Name of Variable to store script to
339 # $3 Name of Variable to store service answer to
341 [ $# -ne 3 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
343 __FILE
="/etc/ddns/services" # IPv4
344 [ $use_ipv6 -ne 0 ] && __FILE
="/etc/ddns/services_ipv6" # IPv6
346 # workaround with variables; pipe create subshell with no give back of variable content
348 # only grep without # or whitespace at linestart | remove "
349 # grep -v -E "(^#|^[[:space:]]*$)" $__FILE | sed -e s/\"//g > pipe_$$ &
350 sed '/^#/d; /^[ \t]*$/d; s/\"//g' $__FILE > pipe_$$
&
352 while read __SERVICE __DATA __ANSWER
; do
353 if [ "$__SERVICE" = "$service_name" ]; then
354 # check if URL or SCRIPT is given
355 __URL
=$
(echo "$__DATA" |
grep "^http")
356 [ -z "$__URL" ] && __SCRIPT
="/usr/lib/ddns/$__DATA"
359 eval "$2=\"$__SCRIPT\""
360 eval "$3=\"$__ANSWER\""
367 eval "$1=\"\"" # no service match clear variables
373 # Calculate seconds from interval and unit
374 # $1 Name of Variable to store result in
376 # $3 Unit of time interval
378 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
380 "days" ) eval "$1=$(( $2 * 86400 ))";;
381 "hours" ) eval "$1=$(( $2 * 3600 ))";;
382 "minutes" ) eval "$1=$(( $2 * 60 ))";;
389 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
390 # only did the following changes
391 # - commented out "#!/bin/bash" and usage section
392 # - replace exit by return for usage as function
393 # - some reformatting
395 # timeout [-SIG] time [--] command args...
397 # Run the given command until completion, but kill it if it runs too long.
398 # Specifically designed to exit immediately (no sleep interval) and clean up
399 # nicely without messages or leaving any extra processes when finished.
402 # timeout 5 countdown
404 # Based on notes in my "Shell Script Hints", section "Command Timeout"
405 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
407 # This script uses a lot of tricks to terminate both the background command,
408 # the timeout script, and even the sleep process. It also includes trap
409 # commands to prevent sub-shells reporting expected "Termination Errors".
411 # It took years of occasional trials, errors and testing to get a pure bash
412 # timeout command working as well as this does.
414 #.Anthony Thyssen 6 April 2011
416 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
417 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
418 # PROGNAME=$(basename $PROGNAME) # base name of program
420 # output the script comments as docs
422 # echo >&2 "$PROGNAME:" "$@"
423 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
429 while [ $# -gt 0 ]; do
432 # forced end of user options
442 # unforced end of user options
448 # run main command in backgrounds and get its pid
452 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
455 # cleanup sleep process
456 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
457 # sleep timeout period in background
462 kill $SIG $command_pid >/dev
/null
2>&1
467 # Wait for main command to finished or be timed out
471 # Clean up timeout sub-shell - if it is still running!
472 kill $timeout_pid 2>/dev
/null
473 wait $timeout_pid 2>/dev
/null
475 # Uncomment to check if a LONG sleep still running (no sleep should be)
478 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
483 # sanitize a variable
485 # $2 allowed shell pattern
486 # $3 disallowed shell pattern
487 sanitize_variable
() {
489 eval __VALUE
=\$
$__VAR
493 # removing all allowed should give empty string
494 if [ -n "$__ALLOWED" ]; then
495 [ -z "${__VALUE//$__ALLOWED}" ] || write_log
12 "sanitize on $__VAR found characters outside allowed subset"
498 # removing rejected pattern should give the same string as the input
499 if [ -n "$__REJECT" ]; then
500 [ "$__VALUE" = "${__VALUE//$__REJECT}" ] || write_log
12 "sanitize on $__VAR found rejected characters"
504 # verify given host and port is connectable
505 # $1 Host/IP to verify
510 local __NC
=$
(which nc
)
511 local __NCEXT
=$
($
(which nc
) --help 2>&1 |
grep "\-w" 2>/dev
/null
) # busybox nc compiled with extensions
512 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
514 # 1 system specific error
515 # 2 nslookup/host error
516 # 3 nc (netcat) error
517 # 4 unmatched IP version
519 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
521 # check if ip or FQDN was given
522 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
523 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
524 # if FQDN given get IP address
525 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
526 if [ -n "$BIND_HOST" ]; then # use BIND host if installed
528 __RUNPROG
="$BIND_HOST $__HOST >$DATFILE 2>$ERRFILE"
529 elif [ -n "$KNOT_HOST" ]; then # use Knot host if installed
531 __RUNPROG
="$KNOT_HOST $__HOST >$DATFILE 2>$ERRFILE"
532 elif [ -n "$DRILL" ]; then # use drill if installed
534 __RUNPROG
="$DRILL -V0 $__HOST A >$DATFILE 2>$ERRFILE" # IPv4
535 __RUNPROG
="$__RUNPROG; $DRILL -V0 $__HOST AAAA >>$DATFILE 2>>$ERRFILE" # IPv6
536 elif [ -n "$HOSTIP" ]; then # use hostip if installed
538 __RUNPROG
="$HOSTIP $__HOST >$DATFILE 2>$ERRFILE" # IPv4
539 __RUNPROG
="$__RUNPROG; $HOSTIP -6 $__HOST >>$DATFILE 2>>$ERRFILE" # IPv6
540 else # use BusyBox nslookup
541 __PROG
="BusyBox nslookup"
542 __RUNPROG
="$NSLOOKUP $__HOST >$DATFILE 2>$ERRFILE"
544 write_log
7 "#> $__RUNPROG"
551 [ $__ERR -gt 0 ] && {
552 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
553 write_log
7 "$(cat $ERRFILE)"
557 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then # use BIND host or Knot host if installed
558 __IPV4
=$
(cat $DATFILE |
awk -F "address " '/has address/ {print $2; exit}' )
559 __IPV6
=$
(cat $DATFILE |
awk -F "address " '/has IPv6/ {print $2; exit}' )
560 elif [ -n "$DRILL" ]; then # use drill if installed
561 __IPV4
=$
(cat $DATFILE |
awk '/^'"$lookup_host"'/ {print $5}' |
grep -m 1 -o "$IPV4_REGEX")
562 __IPV6
=$
(cat $DATFILE |
awk '/^'"$lookup_host"'/ {print $5}' |
grep -m 1 -o "$IPV6_REGEX")
563 elif [ -n "$HOSTIP" ]; then # use hostip if installed
564 __IPV4
=$
(cat $DATFILE |
grep -m 1 -o "$IPV4_REGEX")
565 __IPV6
=$
(cat $DATFILE |
grep -m 1 -o "$IPV6_REGEX")
566 else # use BusyBox nslookup
567 __IPV4
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }")
568 __IPV6
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }")
572 # check IP version if forced
573 if [ $force_ipversion -ne 0 ]; then
575 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
576 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
577 [ $__ERR -gt 0 ] && {
578 [ -n "$LUCI_HELPER" ] && return 4
579 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
584 # busybox nc compiled without -l option "NO OPT l!" -> critical error
585 $__NC --help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
586 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
587 # busybox nc compiled with extensions
588 $__NC --help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
591 # run busybox nc to HOST PORT
592 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
593 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
594 # not worrying, if there is an IPv6 wan address
595 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
596 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
598 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
599 __RUNPROG
="$__NC -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
600 write_log
7 "#> $__RUNPROG"
606 [ $__ERR -eq 0 ] && return 0
607 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
608 write_log
7 "$(cat $ERRFILE)"
610 else # nc compiled without extensions (no timeout support)
611 __RUNPROG
="timeout 2 -- $__NC $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
612 write_log
7 "#> $__RUNPROG"
618 [ $__ERR -eq 0 ] && return 0
619 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
624 # verify given DNS server if connectable
625 # $1 DNS server to verify
627 local __ERR
=255 # last error buffer
628 local __CNT
=0 # error counter
630 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
631 write_log
7 "Verify DNS server '$1'"
633 while [ $__ERR -ne 0 ]; do
635 verify_host_port
"$1" "53"
637 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
639 elif [ $__ERR -ne 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
640 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
642 elif [ $__ERR -ne 0 ]; then
643 __CNT
=$
(( $__CNT + 1 )) # increment error counter
644 # if error count > retry_count leave here
645 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
646 write_log
14 "Verify DNS server '$1' failed after $retry_count retries"
648 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
649 sleep $RETRY_SECONDS &
651 wait $PID_SLEEP # enable trap-handler
658 # analyze and verify given proxy string
659 # $1 Proxy-String to verify
661 # complete entry user:password@host:port
662 # inside user and password NO '@' of ":" allowed
663 # host and port only host:port
664 # host only host ERROR unsupported
665 # IPv4 address instead of host 123.234.234.123
666 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
667 local __TMP __HOST __PORT
668 local __ERR
=255 # last error buffer
669 local __CNT
=0 # error counter
671 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
672 write_log
7 "Verify Proxy server 'http://$1'"
674 # try to split user:password "@" host:port
675 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
676 # no "@" found - only host:port is given
677 [ -z "$__TMP" ] && __TMP
="$1"
678 # now lets check for IPv6 address
679 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
680 # IPv6 host address found read port
681 if [ -n "$__HOST" ]; then
683 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
685 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
686 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
688 # No Port detected - EXITING
689 [ -z "$__PORT" ] && {
690 [ -n "$LUCI_HELPER" ] && return 5
691 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
694 while [ $__ERR -gt 0 ]; do
695 verify_host_port
"$__HOST" "$__PORT"
697 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
699 elif [ $__ERR -gt 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
700 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
702 elif [ $__ERR -gt 0 ]; then
703 __CNT
=$
(( $__CNT + 1 )) # increment error counter
704 # if error count > retry_count leave here
705 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
706 write_log
14 "Verify Proxy server '$1' failed after $retry_count retries"
708 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
709 sleep $RETRY_SECONDS &
711 wait $PID_SLEEP # enable trap-handler
722 local __CNT
=0 # error counter
723 local __PROG __RUNPROG
725 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
727 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
728 if [ -n "$WGET_SSL" -a $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
729 __PROG
="$WGET_SSL -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
730 # force network/ip to use for communication
731 if [ -n "$bind_network" ]; then
733 # set correct program to detect IP
734 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" || __RUNPROG
="network_get_ipaddr6"
735 ( set -o noglob
; eval "$__RUNPROG __BINDIP $bind_network" ) || \
736 write_log
13 "Can not detect local IP using '$__RUNPROG $bind_network' - Error: '$?'"
737 write_log
7 "Force communication via IP '$__BINDIP'"
738 __PROG
="$__PROG --bind-address=$__BINDIP"
740 # force ip version to use
741 if [ $force_ipversion -eq 1 ]; then
742 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
744 # set certificate parameters
745 if [ $use_https -eq 1 ]; then
746 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
747 __PROG
="$__PROG --no-check-certificate"
748 elif [ -f "$cacert" ]; then
749 __PROG
="$__PROG --ca-certificate=${cacert}"
750 elif [ -d "$cacert" ]; then
751 __PROG
="$__PROG --ca-directory=${cacert}"
752 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
753 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
756 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
757 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
759 __RUNPROG
="$__PROG '$__URL'" # build final command
760 __PROG
="GNU Wget" # reuse for error logging
762 # 2nd choice is cURL IPv4/IPv6/HTTPS
763 # libcurl might be compiled without Proxy or HTTPS Support
764 elif [ -n "$CURL" ]; then
765 # CURL_SSL not empty then SSL support available
766 CURL_SSL
=$
($
(which curl
) -V 2>/dev
/null |
grep "Protocols:" |
grep -F "https")
767 __PROG
="$CURL -RsS -o $DATFILE --stderr $ERRFILE"
768 # check HTTPS support
769 [ -z "$CURL_SSL" -a $use_https -eq 1 ] && \
770 write_log
13 "cURL: libcurl compiled without https support"
771 # force network/interface-device to use for communication
772 if [ -n "$bind_network" ]; then
774 network_get_physdev __DEVICE
$bind_network || \
775 write_log
13 "Can not detect local device using 'network_get_physdev $bind_network' - Error: '$?'"
776 write_log
7 "Force communication via device '$__DEVICE'"
777 __PROG
="$__PROG --interface $__DEVICE"
779 # force ip version to use
780 if [ $force_ipversion -eq 1 ]; then
781 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
783 # set certificate parameters
784 if [ $use_https -eq 1 ]; then
785 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
786 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
787 elif [ -f "$cacert" ]; then
788 __PROG
="$__PROG --cacert $cacert"
789 elif [ -d "$cacert" ]; then
790 __PROG
="$__PROG --capath $cacert"
791 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
792 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
795 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
796 # or check if libcurl compiled with proxy support
797 if [ -z "$proxy" ]; then
798 __PROG
="$__PROG --noproxy '*'"
799 elif [ -z "$CURL_PROXY" ]; then
800 # if libcurl has no proxy support and proxy should be used then force ERROR
801 write_log
13 "cURL: libcurl compiled without Proxy support"
804 __RUNPROG
="$__PROG '$__URL'" # build final command
805 __PROG
="cURL" # reuse for error logging
807 # uclient-fetch possibly with ssl support if /lib/libustream-ssl.so installed
808 elif [ -n "$UCLIENT_FETCH" ]; then
809 # UCLIENT_FETCH_SSL not empty then SSL support available
810 UCLIENT_FETCH_SSL
=$
(find /lib
/usr
/lib
-name libustream-ssl.so
* 2>/dev
/null
)
811 __PROG
="$UCLIENT_FETCH -q -O $DATFILE"
812 # force network/ip not supported
813 [ -n "$__BINDIP" ] && \
814 write_log
14 "uclient-fetch: FORCE binding to specific address not supported"
815 # force ip version to use
816 if [ $force_ipversion -eq 1 ]; then
817 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
819 # https possibly not supported
820 [ $use_https -eq 1 -a -z "$UCLIENT_FETCH_SSL" ] && \
821 write_log
14 "uclient-fetch: no HTTPS support! Additional install one of ustream-ssl packages"
823 [ -z "$proxy" ] && __PROG
="$__PROG -Y off" || __PROG
="$__PROG -Y on"
824 # https & certificates
825 if [ $use_https -eq 1 ]; then
826 if [ "$cacert" = "IGNORE" ]; then
827 __PROG
="$__PROG --no-check-certificate"
828 elif [ -f "$cacert" ]; then
829 __PROG
="$__PROG --ca-certificate=$cacert"
830 elif [ -n "$cacert" ]; then # it's not a file; nothing else supported
831 write_log
14 "No valid certificate file '$cacert' for HTTPS communication"
834 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
835 __PROG
="uclient-fetch" # reuse for error logging
837 # Busybox Wget or any other wget in search $PATH (did not support neither IPv6 nor HTTPS)
838 elif [ -n "$WGET" ]; then
839 __PROG
="$WGET -q -O $DATFILE"
840 # force network/ip not supported
841 [ -n "$__BINDIP" ] && \
842 write_log
14 "BusyBox Wget: FORCE binding to specific address not supported"
843 # force ip version not supported
844 [ $force_ipversion -eq 1 ] && \
845 write_log
14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
846 # https not supported
847 [ $use_https -eq 1 ] && \
848 write_log
14 "BusyBox Wget: no HTTPS support"
849 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
850 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
852 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
853 __PROG
="Busybox Wget" # reuse for error logging
856 write_log
13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
860 write_log
7 "#> $__RUNPROG"
863 eval $__RUNPROG # DO transfer
865 __ERR
=$?
# save error code
866 [ $__ERR -eq 0 ] && return 0 # no error leave
867 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
869 write_log
3 "$__PROG Error: '$__ERR'"
870 write_log
7 "$(cat $ERRFILE)" # report error
872 [ $VERBOSE -gt 1 ] && {
873 # VERBOSE > 1 then NO retry
874 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE - NO retry on error"
878 __CNT
=$
(( $__CNT + 1 )) # increment error counter
879 # if error count > retry_count leave here
880 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
881 write_log
14 "Transfer failed after $retry_count retries"
883 write_log
4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
884 sleep $RETRY_SECONDS &
886 wait $PID_SLEEP # enable trap-handler
889 # we should never come here there must be a programming error
890 write_log
12 "Error in 'do_transfer()' - program coding error"
894 # $1 # IP to set at DDNS service provider
897 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
899 if [ $upd_privateip -eq 0 ]; then
900 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
901 [ $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)")
902 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
904 __IP
=$
(echo $1 |
grep -m 1 -o "$IPV4_REGEX") # valid IPv4 or
905 [ -z "$__IP" ] && __IP
=$
(echo $1 |
grep -m 1 -o "$IPV6_REGEX") # IPv6
908 write_log
3 "No or private or invalid IP '$1' given! Please check your configuration"
912 if [ -n "$update_script" ]; then
913 write_log
7 "parsing script '$update_script'"
919 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
920 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
921 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
922 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
924 do_transfer
"$__URL" ||
return 1
926 write_log
7 "DDNS Provider answered:${N}$(cat $DATFILE)"
928 [ -z "$UPD_ANSWER" ] && return 0 # not set then ignore
930 grep -i -E "$UPD_ANSWER" $DATFILE >/dev
/null
2>&1
931 return $?
# "0" if found
936 # $1 Name of Variable to store local IP (LOCAL_IP)
937 local __CNT
=0 # error counter
938 local __RUNPROG __DATA __URL __ERR
940 [ $# -ne 1 ] && write_log
12 "Error calling 'get_local_ip()' - wrong number of parameters"
941 write_log
7 "Detect local IP on '$ip_source'"
944 if [ -n "$ip_network" ]; then
945 # set correct program
946 network_flush_cache
# force re-read data from ubus
947 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
948 || __RUNPROG
="network_get_ipaddr6"
949 ( set -o noglob
; eval "$__RUNPROG __DATA $ip_network" ) || \
950 write_log
13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
951 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on network '$ip_network'"
952 elif [ -n "$ip_interface" ]; then
953 local __DATA4
=""; local __DATA6
=""
954 if [ -n "$(which ip)" ]; then # ip program installed
955 write_log
7 "#> ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE"
956 ip
-o addr show dev
$ip_interface scope global
>$DATFILE 2>$ERRFILE
958 if [ $__ERR -eq 0 ]; then
960 # 10: l2tp-inet: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1456 qdisc fq_codel state UNKNOWN qlen 3\ link/ppp
961 # 10: l2tp-inet inet 95.30.176.51 peer 95.30.176.1/32 scope global l2tp-inet\ valid_lft forever preferred_lft forever
962 # 5: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP qlen 1000\ link/ether 08:00:27:d0:10:32 brd ff:ff:ff:ff:ff:ff
963 # 5: eth1 inet 172.27.10.128/24 brd 172.27.10.255 scope global eth1\ valid_lft forever preferred_lft forever
964 # 5: eth1 inet 172.55.55.155/24 brd 172.27.10.255 scope global eth1\ valid_lft 12345sec preferred_lft 12345sec
965 # 5: eth1 inet6 2002:b0c7:f326::806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
966 # 5: eth1 inet6 fd43:5368:6f6d:6500:806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
967 # 5: eth1 inet6 fd43:5368:6f6d:6500:a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
968 # 5: eth1 inet6 2002:b0c7:f326::a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
970 # remove remove remove replace replace
971 # link inet6 fxxx sec forever=>-1 / => ' ' to separate subnet from ip
972 sed "/link/d; /inet6 f/d; s/sec//g; s/forever/-1/g; s/\// /g" $DATFILE | \
973 awk '{ print $3" "$4" "$NF }' > $ERRFILE # temp reuse ERRFILE
974 # we only need inet? IP prefered time
976 local __TIME4
=0; local __TIME6
=0
977 local __TYP __ADR __TIME
978 while read __TYP __ADR __TIME
; do
979 __TIME
=${__TIME:-0} # supress shell errors on last (empty) line of DATFILE
980 # IPversion no "-1" record stored - now "-1" record or new time > oldtime
981 [ "$__TYP" = "inet6" -a $__TIME6 -ge 0 -a \
( $__TIME -lt 0 -o $__TIME -gt $__TIME6 \
) ] && {
985 [ "$__TYP" = "inet" -a $__TIME4 -ge 0 -a \
( $__TIME -lt 0 -o $__TIME -gt $__TIME4 \
) ] && {
991 write_log
3 "ip Error: '$__ERR'"
992 write_log
7 "$(cat $ERRFILE)" # report error
994 else # use deprecated ifconfig
995 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
996 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
998 if [ $__ERR -eq 0 ]; then
1000 /inet addr:/ { # Filter IPv4
1001 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
1002 $1=""; # remove inet
1003 $3=""; # remove Bcast: ...
1004 $4=""; # remove Mask: ...
1005 FS=":"; # separator ":"
1006 $0=$0; # reread to activate separator
1007 $1=""; # remove addr
1008 FS=" "; # set back separator to default " "
1009 $0=$0; # reread to activate separator (remove whitespaces)
1010 print $1; # print IPv4 addr
1014 /inet6/ && /: [0-9a-eA-E]/ { # Filter IPv6 exclude fxxx
1015 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
1016 FS="/"; # separator "/"
1017 $0=$0; # reread to activate separator
1018 $2=""; # remove everything behind "/"
1019 FS=" "; # set back separator to default " "
1020 $0=$0; # reread to activate separator
1021 print $3; # print IPv6 addr
1025 write_log
3 "ifconfig Error: '$__ERR'"
1026 write_log
7 "$(cat $ERRFILE)" # report error
1029 [ $use_ipv6 -eq 0 ] && __DATA
="$__DATA4" || __DATA
="$__DATA6"
1030 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on interface '$ip_interface'"
1031 elif [ -n "$ip_script" ]; then
1032 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
1035 eval $ip_script >$DATFILE 2>$ERRFILE
1038 if [ $__ERR -eq 0 ]; then
1039 __DATA
=$
(cat $DATFILE)
1040 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected via script '$ip_script'"
1042 write_log
3 "$ip_script Error: '$__ERR'"
1043 write_log
7 "$(cat $ERRFILE)" # report error
1045 elif [ -n "$ip_url" ]; then
1046 do_transfer
"$ip_url"
1047 # use correct regular expression
1048 [ $use_ipv6 -eq 0 ] \
1049 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
1050 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
1051 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on web at '$ip_url'"
1053 write_log
12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
1055 # valid data found return here
1056 [ -n "$__DATA" ] && {
1057 eval "$1=\"$__DATA\""
1061 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
1063 write_log
7 "Data detected:"
1064 write_log
7 "$(cat $DATFILE)"
1066 [ $VERBOSE -gt 1 ] && {
1067 # VERBOSE > 1 then NO retry
1068 write_log
4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE - NO retry on error"
1072 __CNT
=$
(( $__CNT + 1 )) # increment error counter
1073 # if error count > retry_count leave here
1074 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
1075 write_log
14 "Get local IP via '$ip_source' failed after $retry_count retries"
1076 write_log
4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
1077 sleep $RETRY_SECONDS &
1079 wait $PID_SLEEP # enable trap-handler
1082 # we should never come here there must be a programming error
1083 write_log
12 "Error in 'get_local_ip()' - program coding error"
1086 get_registered_ip
() {
1087 # $1 Name of Variable to store public IP (REGISTERED_IP)
1088 # $2 (optional) if set, do not retry on error
1089 local __CNT
=0 # error counter
1091 local __REGEX __PROG __RUNPROG __DATA __IP
1095 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
1096 [ $is_glue -eq 1 -a -z "$BIND_HOST" ] && write_log
14 "Lookup of glue records is only supported using BIND host"
1097 write_log
7 "Detect registered/public IP"
1099 # set correct regular expression
1100 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
1102 if [ -n "$BIND_HOST" ]; then
1104 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
1105 if [ $force_ipversion -eq 1 ]; then # force IP version
1106 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1108 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
1109 [ $is_glue -eq 1 ] && __PROG
="$__PROG -v" # use verbose output to get additional section
1111 __RUNPROG
="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1113 elif [ -n "$KNOT_HOST" ]; then
1115 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
1116 if [ $force_ipversion -eq 1 ]; then # force IP version
1117 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1119 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
1121 __RUNPROG
="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1123 elif [ -n "$DRILL" ]; then
1124 __PROG
="$DRILL -V0" # drill options name @server type
1125 if [ $force_ipversion -eq 1 ]; then # force IP version
1126 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1128 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -t" || __PROG
="$__PROG -u" # force TCP
1129 __PROG
="$__PROG $lookup_host"
1130 [ -n "$dns_server" ] && __PROG
="$__PROG @$dns_server"
1131 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG A" || __PROG
="$__PROG AAAA"
1133 __RUNPROG
="$__PROG >$DATFILE 2>$ERRFILE"
1135 elif [ -n "$HOSTIP" ]; then # hostip package installed
1137 [ $force_dnstcp -ne 0 ] && \
1138 write_log
14 "hostip - no support for 'DNS over TCP'"
1140 # is IP given as dns_server ?
1141 __IP
=$
(echo $dns_server |
grep -m 1 -o "$IPV4_REGEX")
1142 [ -z "$__IP" ] && __IP
=$
(echo $dns_server |
grep -m 1 -o "$IPV6_REGEX")
1144 # we got NO ip for dns_server, so build command
1145 [ -z "$__IP" -a -n "$dns_server" ] && {
1147 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] && __IP
="$__IP -6"
1148 __IP
="$__IP $dns_server | grep -m 1 -o"
1149 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] \
1150 && __IP
="$__IP '$IPV6_REGEX'" \
1151 || __IP
="$__IP '$IPV4_REGEX'"
1155 [ $use_ipv6 -eq 1 ] && __PROG
="$__PROG -6"
1156 [ -n "$dns_server" ] && __PROG
="$__PROG -r $__IP"
1157 __RUNPROG
="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
1159 elif [ -n "$NSLOOKUP" ]; then # last use BusyBox nslookup
1160 NSLOOKUP_MUSL
=$
($
(which nslookup) localhost
2>&1 |
grep -F "(null)") # not empty busybox compiled with musl
1161 [ $force_dnstcp -ne 0 ] && \
1162 write_log
14 "Busybox nslookup - no support for 'DNS over TCP'"
1163 [ -n "$NSLOOKUP_MUSL" -a -n "$dns_server" ] && \
1164 write_log
14 "Busybox compiled with musl - nslookup don't support the use of DNS Server"
1165 [ $force_ipversion -ne 0 ] && \
1166 write_log
5 "Busybox nslookup - no support to 'force IP Version' (ignored)"
1168 __RUNPROG
="$NSLOOKUP $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1169 __PROG
="BusyBox nslookup"
1170 else # there must be an error
1171 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
1175 write_log
7 "#> $__RUNPROG"
1181 if [ $__ERR -ne 0 ]; then
1182 write_log
3 "$__PROG error: '$__ERR'"
1183 write_log
7 "$(cat $ERRFILE)"
1185 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then
1186 if [ $is_glue -eq 1 ]; then
1187 __DATA
=$
(cat $DATFILE |
grep "^$lookup_host" |
grep -om1 "$__REGEX" )
1189 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
1191 elif [ -n "$DRILL" ]; then
1192 __DATA
=$
(cat $DATFILE |
awk '/^'"$lookup_host"'/ {print $5; exit}' )
1193 elif [ -n "$HOSTIP" ]; then
1194 __DATA
=$
(cat $DATFILE |
grep -om1 "$__REGEX")
1195 elif [ -n "$NSLOOKUP" ]; then
1196 __DATA
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
1198 [ -n "$__DATA" ] && {
1199 write_log
7 "Registered IP '$__DATA' detected"
1200 [ -z "$IPFILE" ] ||
echo "$__DATA" > $IPFILE
1201 eval "$1=\"$__DATA\"" # valid data found
1202 return 0 # leave here
1204 write_log
4 "NO valid IP found"
1207 [ -z "$IPFILE" ] ||
echo "" > $IPFILE
1209 [ -n "$LUCI_HELPER" ] && return $__ERR # no retry if called by LuCI helper script
1210 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
1211 [ $VERBOSE -gt 1 ] && {
1212 # VERBOSE > 1 then NO retry
1213 write_log
4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE - NO retry on error"
1217 __CNT
=$
(( $__CNT + 1 )) # increment error counter
1218 # if error count > retry_count leave here
1219 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
1220 write_log
14 "Get registered/public IP for '$lookup_host' failed after $retry_count retries"
1222 write_log
4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
1223 sleep $RETRY_SECONDS &
1225 wait $PID_SLEEP # enable trap-handler
1228 # we should never come here there must be a programming error
1229 write_log
12 "Error in 'get_registered_ip()' - program coding error"
1233 # $1 Variable to store result in
1234 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
1235 local __UPTIME
=$
(cat /proc
/uptime
)
1236 eval "$1=\"${__UPTIME%%.*}\""
1241 # $2 optional (exit status)
1244 local __OLD_IFS
=$IFS
1245 local __NEWLINE_IFS
='
1248 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
1251 0) if [ $__ERR -eq 0 ]; then
1252 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)${N}"
1254 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)${N}"
1256 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1257 # reload config via starting the script again
1258 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v "0" -S "$__SECTIONID" -- start || true
1259 exit 0 ;; # and leave this one
1260 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)${N}";;
1261 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)${N}";;
1262 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)${N}";;
1263 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1266 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1268 for __PID
in $__PIDS; do
1269 kill -$1 $__PID # terminate it
1273 # remove out and err file
1274 [ -f $DATFILE ] && rm -f $DATFILE
1275 [ -f $ERRFILE ] && rm -f $ERRFILE
1277 # exit with correct handling:
1278 # remove trap handling settings and send kill to myself
1280 [ $1 -gt 0 ] && kill -$1 $$
1285 # $2 name of variable to store TLD
1286 # $3 name of variable to store (reg)Domain
1287 # $4 name of variable to store Host/Subdomain
1289 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1290 [ -z "$1" ] && write_log
12 "Error calling 'split_FQDN()' - missing FQDN to split"
1291 [ -f $TLDFILE ] || write_log
12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1293 local _HOST _FDOM _CTLD _FTLD
1294 local _SET
="$@" # save given function parameters
1296 local _PAR
=$
(echo "$1" |
tr [A-Z
] [a-z
] |
tr "." " ") # to lower and replace DOT with SPACE
1297 set -- $_PAR # set new as function parameters
1298 _PAR
="" # clear variable for later reuse
1299 while [ -n "$1" ] ; do # as long we have parameters
1300 _PAR
="$1 $_PAR" # invert order of parameters
1303 set -- $_PAR # use new as function parameters
1304 _PAR
="" # clear variable
1306 while [ -n "$1" ] ; do # as long we have parameters
1307 if [ -z "$_CTLD" ]; then # first loop
1308 _CTLD
="$1" # CURRENT TLD to look at
1311 _CTLD
="$1.$_CTLD" # Next TLD to look at
1314 # check if TLD exact match in tld_names.dat, save TLD
1315 zcat
$TLDFILE |
grep -E "^$_CTLD$" >/dev
/null
2>&1 && {
1316 _FTLD
="$_CTLD" # save found
1317 _FDOM
="$1" # save domain next step might be invalid
1320 # check if match any "*" in tld_names.dat,
1321 zcat
$TLDFILE |
grep -E "^\*.$_CTLD$" >/dev
/null
2>&1 && {
1322 [ -z "$1" ] && break # no more data break
1323 # check if next level TLD match excludes "!" in tld_names.dat
1324 if zcat
$TLDFILE |
grep -E "^!$1.$_CTLD$" >/dev
/null
2>&1 ; then
1325 _FTLD
="$_CTLD" # Yes
1332 [ -n "$_FTLD" ] && break # we have something valid, break
1335 # the leftover parameters are the HOST/SUBDOMAIN
1336 while [ -n "$1" ]; do
1337 _HOST
="$1 $_HOST" # remember we need to invert
1340 _HOST
=$
(echo $_HOST |
tr " " ".") # insert DOT
1342 set -- $_SET # set back parameters from function call
1343 [ -n "$_FTLD" ] && {
1344 eval "$2=$_FTLD" # set TLD
1345 eval "$3=$_FDOM" # set registrable domain
1346 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1349 eval "$2=''" # clear TLD
1350 eval "$3=''" # clear registrable domain
1351 eval "$4=''" # clear HOST/SUBDOMAIN
1356 # Original written for bash by
1357 #.Author: Florian Streibelt <florian@f-streibelt.de>
1359 # License: Public Domain, but please be fair and
1360 # attribute the original author(s) and provide
1361 # a link to the original source for corrections:
1362 #. https://github.com/mutax/IPv6-Address-checks
1365 # $2 name of variable to store expanded IPv6
1366 [ $# -ne 2 ] && write_log
12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1368 INPUT
="$(echo "$1" | tr 'A-F' 'a-f')"
1369 [ "$INPUT" = "::" ] && INPUT
="::0" # special case ::
1373 while [ "$O" != "$INPUT" ]; do
1376 # fill all words with zeroes
1377 INPUT
=$
( echo "$INPUT" |
sed -e 's|:\([0-9a-f]\{3\}\):|:0\1:|g' \
1378 -e 's|:\([0-9a-f]\{3\}\)$|:0\1|g' \
1379 -e 's|^\([0-9a-f]\{3\}\):|0\1:|g' \
1380 -e 's|:\([0-9a-f]\{2\}\):|:00\1:|g' \
1381 -e 's|:\([0-9a-f]\{2\}\)$|:00\1|g' \
1382 -e 's|^\([0-9a-f]\{2\}\):|00\1:|g' \
1383 -e 's|:\([0-9a-f]\):|:000\1:|g' \
1384 -e 's|:\([0-9a-f]\)$|:000\1|g' \
1385 -e 's|^\([0-9a-f]\):|000\1:|g' )
1392 echo "$INPUT" |
grep -qs "::"
1393 if [ "$?" -eq 0 ]; then
1394 GRPS
="$( echo "$INPUT" | sed 's|[0-9a-f]||g' | wc -m )"
1395 GRPS
=$
(( GRPS-1
)) # remove carriage return
1396 MISSING
=$
(( 8-GRPS ))
1397 while [ $MISSING -gt 0 ]; do
1398 ZEROES
="$ZEROES:0000"
1399 MISSING
=$
(( MISSING-1
))
1402 # be careful where to place the :
1403 INPUT
=$
( echo "$INPUT" |
sed -e 's|\(.\)::\(.\)|\1'$ZEROES':\2|g' \
1404 -e 's|\(.\)::$|\1'$ZEROES':0000|g' \
1405 -e 's|^::\(.\)|'$ZEROES':0000:\1|g;s|^:||g' )
1408 # an expanded address has 39 chars + CR
1409 if [ $
(echo $INPUT |
wc -m) != 40 ]; then
1410 write_log
4 "Error in 'expand_ipv6()' - invalid IPv6 found: '$1' expanded: '$INPUT'"
1415 # echo the fully expanded version of the address