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
24 if [ -f "/usr/share/ddns/version" ]; then
25 VERSION
="$(cat "/usr
/share
/ddns
/version
")"
29 SECTION_ID
="" # hold config's section name
30 VERBOSE
=0 # default mode is log to console, but easily changed with parameter
31 DRY_RUN
=0 # run without actually doing (sending) any changes
32 MYPROG
=$
(basename $0) # my program call name
34 LOGFILE
="" # logfile - all files are set in dynamic_dns_updater.sh
36 UPDFILE
="" # store UPTIME of last update
37 DATFILE
="" # save stdout data of WGet and other external programs called
38 ERRFILE
="" # save stderr output of WGet and other external programs called
39 IPFILE
="" # store registered IP for read by LuCI status
40 TLDFILE
=/usr
/share
/public_suffix_list.dat.gz
# TLD file used by split_FQDN
42 CHECK_SECONDS
=0 # calculated seconds out of given
43 FORCE_SECONDS
=0 # interval and unit
44 RETRY_SECONDS
=0 # in configuration
46 LAST_TIME
=0 # holds the uptime of last successful update
47 CURR_TIME
=0 # holds the current uptime
48 NEXT_TIME
=0 # calculated time for next FORCED update
49 EPOCH_TIME
=0 # seconds since 1.1.1970 00:00:00
51 CURRENT_IP
="" # holds the current IP read from the box
52 REGISTERED_IP
="" # holds the IP read from DNS
54 URL_USER
="" # url encoded $username from config file
55 URL_PASS
="" # url encoded $password from config file
56 URL_PENC
="" # url encoded $param_enc from config file
58 UPD_ANSWER
="" # Answer given by service on success
60 ERR_LAST
=0 # used to save $? return code of program and function calls
61 RETRY_COUNT
=0 # error counter on different current and registered IPs
63 PID_SLEEP
=0 # ProcessID of current background "sleep"
65 # regular expression to detect IPv4 / IPv6
66 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
67 IPV4_REGEX
="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
68 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
69 IPV6_REGEX
="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
71 # characters that are dangerous to pass to a shell command line
72 SHELL_ESCAPE
="[\"\'\`\$\!();><{}?|\[\]\*\\\\]"
74 # dns character set. "-" must be the last character
75 DNS_CHARSET
="[@a-zA-Z0-9._-]"
77 # domains can have * for wildcard. "-" must be the last character
78 DNS_CHARSET_DOMAIN
="[@a-zA-Z0-9._*-]"
80 # detect if called by ddns-lucihelper.sh script, disable retrys (empty variable == false)
81 LUCI_HELPER
=$
(printf %s
"$MYPROG" |
grep -i "luci")
83 # Name Server Lookup Programs
84 BIND_HOST
=$
(command -v host)
85 KNOT_HOST
=$
(command -v khost
)
86 DRILL
=$
(command -v drill
)
87 HOSTIP
=$
(command -v hostip
)
88 NSLOOKUP
=$
(command -v nslookup)
91 WGET
=$
(command -v wget
)
92 $WGET -V 2>/dev
/null |
grep -F -q +https
&& WGET_SSL
=$WGET
94 CURL
=$
(command -v curl
)
95 # CURL_SSL not empty then SSL support available
96 CURL_SSL
=$
($CURL -V 2>/dev
/null |
grep -F "https")
97 # CURL_PROXY not empty then Proxy support available
98 CURL_PROXY
=$
(find /lib
/usr
/lib
-name libcurl.so
* -exec strings {} 2>/dev
/null \
; |
grep -im1 "all_proxy")
100 UCLIENT_FETCH
=$
(command -v uclient-fetch
)
102 # Global configuration settings
103 # allow NON-public IP's
104 upd_privateip
=$
(uci
-q get ddns.global.upd_privateip
) || upd_privateip
=0
106 # directory to store run information to.
107 ddns_rundir
=$
(uci
-q get ddns.global.ddns_rundir
) || ddns_rundir
="/var/run/ddns"
108 [ -d $ddns_rundir ] || mkdir
-p -m755 $ddns_rundir
110 # directory to store log files
111 ddns_logdir
=$
(uci
-q get ddns.global.ddns_logdir
) || ddns_logdir
="/var/log/ddns"
112 [ -d $ddns_logdir ] || mkdir
-p -m755 $ddns_logdir
114 # number of lines to before rotate logfile
115 ddns_loglines
=$
(uci
-q get ddns.global.ddns_loglines
) || ddns_loglines
=250
116 ddns_loglines
=$
((ddns_loglines
+ 1)) # correct sed handling
118 # format to show date information in log and luci-app-ddns default ISO 8601 format
119 ddns_dateformat
=$
(uci
-q get ddns.global.ddns_dateformat
) || ddns_dateformat
="%F %R"
120 DATE_PROG
="date +'$ddns_dateformat'"
122 # USE_CURL if GNU Wget and cURL installed normally Wget is used by do_transfer()
123 # to change this use global option use_curl '1'
124 USE_CURL
=$
(uci
-q get ddns.global.use_curl
) || USE_CURL
=0 # read config
125 [ -n "$CURL" ] || USE_CURL
=0 # check for cURL
127 # loads all options for a given package and section
128 # also, sets all_option_variables to a list of the variable names
129 # $1 = ddns, $2 = SECTION_ID
130 load_all_config_options
()
133 local __SECTIONID
="$2"
135 local __ALL_OPTION_VARIABLES
=""
137 # this callback loads all the variables in the __SECTIONID section when we do
138 # config_load. We need to redefine the option_cb for different sections
139 # so that the active one isn't still active after we're done with it. For reference
140 # the $1 variable is the name of the option and $2 is the name of the section
143 if [ .
"$2" = .
"$__SECTIONID" ]; then
146 __ALL_OPTION_VARIABLES
="$__ALL_OPTION_VARIABLES $1"
149 option_cb
() { return 0; }
153 config_load
"$__PKGNAME"
155 # Given SECTION_ID not found so no data, so return 1
156 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
158 for __VAR
in $__ALL_OPTION_VARIABLES
160 config_get
"$__VAR" "$__SECTIONID" "$__VAR"
165 # read's all service sections from ddns config
166 # $1 = Name of variable to store
167 load_all_service_sections
() {
171 # only look for section type "service", ignore everything else
172 [ "$1" = "service" ] && __DATA
="$__DATA $2"
176 eval "$1=\"$__DATA\""
180 # starts updater script for all given sections or only for the one given
181 # $1 = interface (Optional: when given only scripts are started
182 # configured for that interface)
183 # used by /etc/hotplug.d/iface/95-ddns on IFUP
184 # and by /etc/init.d/ddns start
185 start_daemon_for_all_ddns_sections
()
192 load_all_service_sections __SECTIONS
193 for __SECTIONID
in $__SECTIONS; do
194 config_get __IFACE
"$__SECTIONID" interface
"wan"
195 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
196 if [ $VERBOSE -eq 0 ]; then # start in background
197 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v 0 -S "$__SECTIONID" -- start
&
199 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v "$VERBOSE" -S "$__SECTIONID" -- start
204 # stop sections process incl. childs (sleeps)
206 stop_section_processes
() {
208 local __PIDFILE
="$ddns_rundir/$1.pid"
209 [ $# -ne 1 ] && write_log
12 "Error calling 'stop_section_processes()' - wrong number of parameters"
211 [ -e "$__PIDFILE" ] && {
212 __PID
=$
(cat $__PIDFILE)
213 ps |
grep "^[\t ]*$__PID" >/dev
/null
2>&1 && kill $__PID || __PID
=0 # terminate it
215 [ $__PID -eq 0 ] # report if process was running
218 # stop updater script for all defines sections or only for one given
219 # $1 = interface (optional)
220 # used by /etc/hotplug.d/iface/95-ddns on 'ifdown'
221 # and by /etc/init.d/ddns stop
222 # needed because we also need to kill "sleep" child processes
223 stop_daemon_for_all_ddns_sections
() {
229 load_all_service_sections __SECTIONS
230 for __SECTIONID
in $__SECTIONS; do
231 config_get __IFACE
"$__SECTIONID" interface
"wan"
232 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
233 stop_section_processes
"$__SECTIONID"
237 # reports to console, logfile, syslog
238 # $1 loglevel 7 == Debug to 0 == EMERG
239 # value +10 will exit the scripts
240 # $2..n text to report
242 local __LEVEL __EXIT __CMD __MSG __MSE
243 local __TIME
=$
(date +%H
%M
%S
)
251 shift # remove loglevel
252 [ $__EXIT -eq 0 ] && __MSG
="$*" || __MSG
="$* - TERMINATE"
253 case $__LEVEL in # create log message and command depending on loglevel
254 0) __CMD
="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
255 __MSG
=" $__TIME EMERG : $__MSG" ;;
256 1) __CMD
="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
257 __MSG
=" $__TIME ALERT : $__MSG" ;;
258 2) __CMD
="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
259 __MSG
=" $__TIME CRIT : $__MSG" ;;
260 3) __CMD
="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
261 __MSG
=" $__TIME ERROR : $__MSG" ;;
262 4) __CMD
="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
263 __MSG
=" $__TIME WARN : $__MSG" ;;
264 5) __CMD
="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
265 __MSG
=" $__TIME note : $__MSG" ;;
266 6) __CMD
="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
267 __MSG
=" $__TIME info : $__MSG" ;;
268 7) __MSG
=" $__TIME : $__MSG";;
273 [ $VERBOSE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
275 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE -gt 1 ]; then
276 if [ -n "$password" ]; then
277 # url encode __MSG, password already done
278 urlencode __MSE
"$__MSG"
279 # replace encoded password inside encoded message
280 # and url decode (newline was encoded as %00)
281 __MSG
=$
( echo -e "$__MSE" \
282 |
sed -e "s/$URL_PASS/***PW***/g" \
283 |
sed -e "s/+/ /g; s/%00/\n/g; s/%/\\\\x/g" |
xargs -0 printf "%b" )
285 printf "%s\n" "$__MSG" >> $LOGFILE
286 # VERBOSE > 1 then NO loop so NO truncate log to $ddns_loglines lines
287 [ $VERBOSE -gt 1 ] ||
sed -i -e :a
-e '$q;N;'$ddns_loglines',$D;ba' $LOGFILE
289 [ -n "$LUCI_HELPER" ] && return # nothing else todo when running LuCI helper script
290 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
291 __CMD
=$
(echo -e "$__CMD" |
tr -d '\n' |
tr '\t' ' ') # remove \n \t chars
292 [ $__EXIT -eq 1 ] && {
293 eval '$__CMD' # force syslog before exit
296 [ $use_syslog -eq 0 ] && return
297 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && eval '$__CMD'
302 # replace all special chars to their %hex value
303 # used for USERNAME and PASSWORD in update_url
304 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
305 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
306 # "$"(Dollar) # because used as variable output
307 # tested with the following string stored via Luci Application as password / username
308 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
310 # $1 Name of Variable to store encoded string to
311 # $2 string to encode
314 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
316 __ENC
="$(awk -v str="$2" 'BEGIN{ORS="";for(i=32;i<=127;i++)lookup[sprintf("%c
",i)]=i
317 for(k=1;k<=length(str);++k){enc=substr(str,k,1);if(enc!~"[-_.~a-zA-Z0-9
]")enc=sprintf("%%%02x
", lookup[enc]);print enc}}')"
319 eval "$1=\"$__ENC\"" # transfer back to variable
323 # extract url or script for given DDNS Provider from
324 # $1 Name of the provider
325 # $2 Provider directory
326 # $3 Name of Variable to store url to
327 # $4 Name of Variable to store script to
328 # $5 Name of Variable to store service answer to
335 .
/usr
/share
/libubox
/jshn.sh
336 local name data url answer
script
338 [ $# -ne 3 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
340 [ -f "${dir}/${provider}.json" ] ||
{
347 json_load_file
"${dir}/${provider}.json"
348 json_get_var name
"name"
349 if [ "$use_ipv6" -eq "1" ]; then
354 json_get_var data
"url"
355 json_get_var answer
"answer"
359 # check if URL or SCRIPT is given
360 url
=$
(echo "$data" |
grep "^http")
361 [ -z "$url" ] && script="/usr/lib/ddns/${data}"
364 eval "$2=\"$script\""
365 eval "$3=\"$answer\""
369 # Calculate seconds from interval and unit
370 # $1 Name of Variable to store result in
372 # $3 Unit of time interval
374 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
376 "days" ) eval "$1=$(( $2 * 86400 ))";;
377 "hours" ) eval "$1=$(( $2 * 3600 ))";;
378 "minutes" ) eval "$1=$(( $2 * 60 ))";;
385 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
386 # only did the following changes
387 # - commented out "#!/bin/bash" and usage section
388 # - replace exit by return for usage as function
389 # - some reformatting
391 # timeout [-SIG] time [--] command args...
393 # Run the given command until completion, but kill it if it runs too long.
394 # Specifically designed to exit immediately (no sleep interval) and clean up
395 # nicely without messages or leaving any extra processes when finished.
398 # timeout 5 countdown
400 # Based on notes in my "Shell Script Hints", section "Command Timeout"
401 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
403 # This script uses a lot of tricks to terminate both the background command,
404 # the timeout script, and even the sleep process. It also includes trap
405 # commands to prevent sub-shells reporting expected "Termination Errors".
407 # It took years of occasional trials, errors and testing to get a pure bash
408 # timeout command working as well as this does.
410 #.Anthony Thyssen 6 April 2011
412 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
413 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
414 # PROGNAME=$(basename $PROGNAME) # base name of program
416 # output the script comments as docs
418 # echo >&2 "$PROGNAME:" "$@"
419 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
425 while [ $# -gt 0 ]; do
428 # forced end of user options
438 # unforced end of user options
444 # run main command in backgrounds and get its pid
448 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
451 # cleanup sleep process
452 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
453 # sleep timeout period in background
458 kill $SIG $command_pid >/dev
/null
2>&1
463 # Wait for main command to finished or be timed out
467 # Clean up timeout sub-shell - if it is still running!
468 kill $timeout_pid 2>/dev
/null
469 wait $timeout_pid 2>/dev
/null
471 # Uncomment to check if a LONG sleep still running (no sleep should be)
474 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
479 # sanitize a variable
481 # $2 allowed shell pattern
482 # $3 disallowed shell pattern
483 sanitize_variable
() {
485 eval __VALUE
=\$
$__VAR
489 # removing all allowed should give empty string
490 if [ -n "$__ALLOWED" ]; then
491 [ -z "${__VALUE//$__ALLOWED}" ] || write_log
12 "sanitize on $__VAR found characters outside allowed subset"
494 # removing rejected pattern should give the same string as the input
495 if [ -n "$__REJECT" ]; then
496 [ "$__VALUE" = "${__VALUE//$__REJECT}" ] || write_log
12 "sanitize on $__VAR found rejected characters"
500 # verify given host and port is connectable
501 # $1 Host/IP to verify
506 local __NC
=$
(command -v nc
)
507 local __NCEXT
=$
($
(command -v nc
) --help 2>&1 |
grep "\-w" 2>/dev
/null
) # busybox nc compiled with extensions
508 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
510 # 1 system specific error
511 # 2 nslookup/host error
512 # 3 nc (netcat) error
513 # 4 unmatched IP version
515 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
517 # check if ip or FQDN was given
518 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
519 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
520 # if FQDN given get IP address
521 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
522 if [ -n "$BIND_HOST" ]; then # use BIND host if installed
524 __RUNPROG
="$BIND_HOST $__HOST >$DATFILE 2>$ERRFILE"
525 elif [ -n "$KNOT_HOST" ]; then # use Knot host if installed
527 __RUNPROG
="$KNOT_HOST $__HOST >$DATFILE 2>$ERRFILE"
528 elif [ -n "$DRILL" ]; then # use drill if installed
530 __RUNPROG
="$DRILL -V0 $__HOST A >$DATFILE 2>$ERRFILE" # IPv4
531 __RUNPROG
="$__RUNPROG; $DRILL -V0 $__HOST AAAA >>$DATFILE 2>>$ERRFILE" # IPv6
532 elif [ -n "$HOSTIP" ]; then # use hostip if installed
534 __RUNPROG
="$HOSTIP $__HOST >$DATFILE 2>$ERRFILE" # IPv4
535 __RUNPROG
="$__RUNPROG; $HOSTIP -6 $__HOST >>$DATFILE 2>>$ERRFILE" # IPv6
536 else # use BusyBox nslookup
537 __PROG
="BusyBox nslookup"
538 __RUNPROG
="$NSLOOKUP $__HOST >$DATFILE 2>$ERRFILE"
540 write_log
7 "#> $__RUNPROG"
544 [ $__ERR -gt 0 ] && {
545 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
546 write_log
7 "$(cat $ERRFILE)"
550 if [ -n "$BIND_HOST" ]; then # use BIND host if installed
551 __IPV4
="$(awk -F "address
" '/has address/ {print $2; exit}' "$DATFILE")"
552 __IPV6
="$(awk -F "address
" '/has IPv6/ {print $2; exit}' "$DATFILE")"
553 elif [ -n "$KNOT_HOST" ]; then # use Knot host if installed
554 __IPV4
="$(awk -F "address
" '/has IPv4/ {print $2; exit}' "$DATFILE")"
555 __IPV6
="$(awk -F "address
" '/has IPv6/ {print $2; exit}' "$DATFILE")"
556 elif [ -n "$DRILL" ]; then # use drill if installed
557 __IPV4
="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV4_REGEX")"
558 __IPV6
="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV6_REGEX")"
559 elif [ -n "$HOSTIP" ]; then # use hostip if installed
560 __IPV4
="$(grep -m 1 -o "$IPV4_REGEX" "$DATFILE")"
561 __IPV6
="$(grep -m 1 -o "$IPV6_REGEX" "$DATFILE")"
562 else # use BusyBox nslookup
563 __IPV4
="$(sed -ne "/^Name
:/,\$
{ s
/^Address
[0-9 ]\
{0,\
}: \
($IPV4_REGEX\
).
*$
/\\1/p
}" "$DATFILE")"
564 __IPV6
="$(sed -ne "/^Name
:/,\$
{ s
/^Address
[0-9 ]\
{0,\
}: \
($IPV6_REGEX\
).
*$
/\\1/p
}" "$DATFILE")"
568 # check IP version if forced
569 if [ $force_ipversion -ne 0 ]; then
571 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
572 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
573 [ $__ERR -gt 0 ] && {
574 [ -n "$LUCI_HELPER" ] && return 4
575 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
580 # busybox nc compiled without -l option "NO OPT l!" -> critical error
581 $__NC --help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
582 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
583 # busybox nc compiled with extensions
584 $__NC --help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
587 # run busybox nc to HOST PORT
588 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
589 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
590 # not worrying, if there is an IPv6 wan address
591 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
592 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
594 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
595 __RUNPROG
="$__NC -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
596 write_log
7 "#> $__RUNPROG"
599 [ $__ERR -eq 0 ] && return 0
600 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
601 write_log
7 "$(cat $ERRFILE)"
603 else # nc compiled without extensions (no timeout support)
604 __RUNPROG
="timeout 2 -- $__NC $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
605 write_log
7 "#> $__RUNPROG"
608 [ $__ERR -eq 0 ] && return 0
609 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
614 # verify given DNS server if connectable
615 # $1 DNS server to verify
617 local __ERR
=255 # last error buffer
618 local __CNT
=0 # error counter
620 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
621 write_log
7 "Verify DNS server '$1'"
623 while [ $__ERR -ne 0 ]; do
625 verify_host_port
"$1" "53"
627 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
629 elif [ $__ERR -ne 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
630 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
632 elif [ $__ERR -ne 0 ]; then
633 __CNT
=$
(( $__CNT + 1 )) # increment error counter
634 # if error count > retry_max_count leave here
635 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
636 write_log
14 "Verify DNS server '$1' failed after $retry_max_count retries"
638 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
639 sleep $RETRY_SECONDS &
641 wait $PID_SLEEP # enable trap-handler
648 # analyze and verify given proxy string
649 # $1 Proxy-String to verify
651 # complete entry user:password@host:port
652 # inside user and password NO '@' of ":" allowed
653 # host and port only host:port
654 # host only host ERROR unsupported
655 # IPv4 address instead of host 123.234.234.123
656 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
657 local __TMP __HOST __PORT
658 local __ERR
=255 # last error buffer
659 local __CNT
=0 # error counter
661 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
662 write_log
7 "Verify Proxy server 'http://$1'"
664 # try to split user:password "@" host:port
665 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
666 # no "@" found - only host:port is given
667 [ -z "$__TMP" ] && __TMP
="$1"
668 # now lets check for IPv6 address
669 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
670 # IPv6 host address found read port
671 if [ -n "$__HOST" ]; then
673 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
675 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
676 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
678 # No Port detected - EXITING
679 [ -z "$__PORT" ] && {
680 [ -n "$LUCI_HELPER" ] && return 5
681 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
684 while [ $__ERR -gt 0 ]; do
685 verify_host_port
"$__HOST" "$__PORT"
687 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
689 elif [ $__ERR -gt 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
690 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
692 elif [ $__ERR -gt 0 ]; then
693 __CNT
=$
(( $__CNT + 1 )) # increment error counter
694 # if error count > retry_max_count leave here
695 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
696 write_log
14 "Verify Proxy server '$1' failed after $retry_max_count retries"
698 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
699 sleep $RETRY_SECONDS &
701 wait $PID_SLEEP # enable trap-handler
712 local __CNT
=0 # error counter
713 local __PROG __RUNPROG
715 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
717 # Use ip_network as default for bind_network if not separately specified
718 [ -z "$bind_network" ] && [ "$ip_source" = "network" ] && [ "$ip_network" ] && bind_network
="$ip_network"
720 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
721 if [ -n "$WGET_SSL" ] && [ $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
722 __PROG
="$WGET --hsts-file=/tmp/.wget-hsts -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
723 # force network/ip to use for communication
724 if [ -n "$bind_network" ]; then
726 # set correct program to detect IP
727 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" || __RUNPROG
="network_get_ipaddr6"
728 eval "$__RUNPROG __BINDIP $bind_network" || \
729 write_log
13 "Can not detect current IP using '$__RUNPROG $bind_network' - Error: '$?'"
730 write_log
7 "Force communication via IP '$__BINDIP'"
731 __PROG
="$__PROG --bind-address=$__BINDIP"
733 # force ip version to use
734 if [ $force_ipversion -eq 1 ]; then
735 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
737 # set certificate parameters
738 if [ $use_https -eq 1 ]; then
739 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
740 __PROG
="$__PROG --no-check-certificate"
741 elif [ -f "$cacert" ]; then
742 __PROG
="$__PROG --ca-certificate=${cacert}"
743 elif [ -d "$cacert" ]; then
744 __PROG
="$__PROG --ca-directory=${cacert}"
745 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
746 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
749 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
750 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
752 # user agent string if provided
753 if [ -n "$user_agent" ]; then
754 # replace single and double quotes
755 user_agent
=$
(echo $user_agent |
sed "s/'/ /g" |
sed 's/"/ /g')
756 __PROG
="$__PROG --user-agent='$user_agent'"
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 __PROG
="$CURL -RsS -o $DATFILE --stderr $ERRFILE"
766 # check HTTPS support
767 [ -z "$CURL_SSL" -a $use_https -eq 1 ] && \
768 write_log
13 "cURL: libcurl compiled without https support"
769 # force network/interface-device to use for communication
770 if [ -n "$bind_network" ]; then
772 network_get_device __DEVICE
$bind_network || \
773 write_log
13 "Can not detect local device using 'network_get_device $bind_network' - Error: '$?'"
774 write_log
7 "Force communication via device '$__DEVICE'"
775 __PROG
="$__PROG --interface $__DEVICE"
777 # force ip version to use
778 if [ $force_ipversion -eq 1 ]; then
779 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
781 # set certificate parameters
782 if [ $use_https -eq 1 ]; then
783 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
784 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
785 elif [ -f "$cacert" ]; then
786 __PROG
="$__PROG --cacert $cacert"
787 elif [ -d "$cacert" ]; then
788 __PROG
="$__PROG --capath $cacert"
789 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
790 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
793 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
794 # or check if libcurl compiled with proxy support
795 if [ -z "$proxy" ]; then
796 __PROG
="$__PROG --noproxy '*'"
797 elif [ -z "$CURL_PROXY" ]; then
798 # if libcurl has no proxy support and proxy should be used then force ERROR
799 write_log
13 "cURL: libcurl compiled without Proxy support"
802 __RUNPROG
="$__PROG '$__URL'" # build final command
803 __PROG
="cURL" # reuse for error logging
805 # uclient-fetch possibly with ssl support if /lib/libustream-ssl.so installed
806 elif [ -n "$UCLIENT_FETCH" ]; then
807 # UCLIENT_FETCH_SSL not empty then SSL support available
808 UCLIENT_FETCH_SSL
=$
(find /lib
/usr
/lib
-name libustream-ssl.so
* 2>/dev
/null
)
809 __PROG
="$UCLIENT_FETCH -q -O $DATFILE"
810 # force network/ip not supported
811 [ -n "$__BINDIP" ] && \
812 write_log
14 "uclient-fetch: FORCE binding to specific address not supported"
813 # force ip version to use
814 if [ $force_ipversion -eq 1 ]; then
815 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
817 # https possibly not supported
818 [ $use_https -eq 1 -a -z "$UCLIENT_FETCH_SSL" ] && \
819 write_log
14 "uclient-fetch: no HTTPS support! Additional install one of ustream-ssl packages"
821 [ -z "$proxy" ] && __PROG
="$__PROG -Y off" || __PROG
="$__PROG -Y on"
822 # https & certificates
823 if [ $use_https -eq 1 ]; then
824 if [ "$cacert" = "IGNORE" ]; then
825 __PROG
="$__PROG --no-check-certificate"
826 elif [ -f "$cacert" ]; then
827 __PROG
="$__PROG --ca-certificate=$cacert"
828 elif [ -n "$cacert" ]; then # it's not a file; nothing else supported
829 write_log
14 "No valid certificate file '$cacert' for HTTPS communication"
832 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
833 __PROG
="uclient-fetch" # reuse for error logging
835 # Busybox Wget or any other wget in search $PATH (did not support neither IPv6 nor HTTPS)
836 elif [ -n "$WGET" ]; then
837 __PROG
="$WGET -q -O $DATFILE"
838 # force network/ip not supported
839 [ -n "$__BINDIP" ] && \
840 write_log
14 "BusyBox Wget: FORCE binding to specific address not supported"
841 # force ip version not supported
842 [ $force_ipversion -eq 1 ] && \
843 write_log
14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
844 # https not supported
845 [ $use_https -eq 1 ] && \
846 write_log
14 "BusyBox Wget: no HTTPS support"
847 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
848 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
850 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
851 __PROG
="Busybox Wget" # reuse for error logging
854 write_log
13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
858 write_log
7 "#> $__RUNPROG"
859 eval $__RUNPROG # DO transfer
860 __ERR
=$?
# save error code
861 [ $__ERR -eq 0 ] && return 0 # no error leave
862 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
864 write_log
3 "$__PROG Error: '$__ERR'"
865 write_log
7 "$(cat $ERRFILE)" # report error
867 [ $VERBOSE -gt 1 ] && {
868 # VERBOSE > 1 then NO retry
869 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE - NO retry on error"
873 __CNT
=$
(( $__CNT + 1 )) # increment error counter
874 # if error count > retry_max_count leave here
875 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
876 write_log
14 "Transfer failed after $retry_max_count retries"
878 write_log
4 "Transfer failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
879 sleep $RETRY_SECONDS &
881 wait $PID_SLEEP # enable trap-handler
884 # we should never come here there must be a programming error
885 write_log
12 "Error in 'do_transfer()' - program coding error"
889 # $1 # IP to set at DDNS service provider
892 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
894 if [ $upd_privateip -eq 0 ]; then
895 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
896 [ $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)")
897 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
899 __IP
=$
(echo $1 |
grep -m 1 -o "$IPV4_REGEX") # valid IPv4 or
900 [ -z "$__IP" ] && __IP
=$
(echo $1 |
grep -m 1 -o "$IPV6_REGEX") # IPv6
903 write_log
3 "No or private or invalid IP '$1' given! Please check your configuration"
907 if [ -n "$update_script" ]; then
908 write_log
7 "parsing script '$update_script'"
914 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
915 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
916 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
917 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
919 do_transfer
"$__URL" ||
return 1
921 write_log
7 "DDNS Provider answered:${N}$(cat $DATFILE)"
923 [ -z "$UPD_ANSWER" ] && return 0 # not set then ignore
925 grep -i -E "$UPD_ANSWER" $DATFILE >/dev
/null
2>&1
926 return $?
# "0" if found
931 # $1 Name of Variable to store current IP
932 local __CNT
=0 # error counter
933 local __RUNPROG __DATA __URL __ERR
935 [ $# -ne 1 ] && write_log
12 "Error calling 'get_current_ip()' - wrong number of parameters"
936 write_log
7 "Detect current IP on '$ip_source'"
939 if [ -n "$ip_network" -a "$ip_source" = "network" ]; then
940 # set correct program
941 network_flush_cache
# force re-read data from ubus
942 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
943 || __RUNPROG
="network_get_ipaddr6"
944 eval "$__RUNPROG __DATA $ip_network" || \
945 write_log
13 "Can not detect current IP using $__RUNPROG '$ip_network' - Error: '$?'"
946 [ -n "$__DATA" ] && write_log
7 "Current IP '$__DATA' detected on network '$ip_network'"
947 elif [ -n "$ip_interface" -a "$ip_source" = "interface" ]; then
948 local __DATA4
=""; local __DATA6
=""
949 if [ -n "$(command -v ip)" ]; then # ip program installed
950 write_log
7 "#> ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE"
951 ip
-o addr show dev
$ip_interface scope global
>$DATFILE 2>$ERRFILE
953 if [ $__ERR -eq 0 ]; then
955 # 10: l2tp-inet: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1456 qdisc fq_codel state UNKNOWN qlen 3\ link/ppp
956 # 10: l2tp-inet inet 95.30.176.51 peer 95.30.176.1/32 scope global l2tp-inet\ valid_lft forever preferred_lft forever
957 # 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
958 # 5: eth1 inet 172.27.10.128/24 brd 172.27.10.255 scope global eth1\ valid_lft forever preferred_lft forever
959 # 5: eth1 inet 172.55.55.155/24 brd 172.27.10.255 scope global eth1\ valid_lft 12345sec preferred_lft 12345sec
960 # 5: eth1 inet6 2002:b0c7:f326::806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
961 # 5: eth1 inet6 fd43:5368:6f6d:6500:806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
962 # 5: eth1 inet6 fd43:5368:6f6d:6500:a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
963 # 5: eth1 inet6 2002:b0c7:f326::a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
965 # remove remove remove replace replace
966 # link inet6 fxxx sec forever=>-1 / => ' ' to separate subnet from ip
967 sed "/link/d; /inet6 f/d; s/sec//g; s/forever/-1/g; s/\// /g" $DATFILE | \
968 awk '{ print $3" "$4" "$NF }' > $ERRFILE # temp reuse ERRFILE
969 # we only need inet? IP prefered time
971 local __TIME4
=0; local __TIME6
=0
972 local __TYP __ADR __TIME
973 while read __TYP __ADR __TIME
; do
974 __TIME
=${__TIME:-0} # supress shell errors on last (empty) line of DATFILE
975 # IPversion no "-1" record stored - now "-1" record or new time > oldtime
976 [ "$__TYP" = "inet6" -a $__TIME6 -ge 0 -a \
( $__TIME -lt 0 -o $__TIME -gt $__TIME6 \
) ] && {
980 [ "$__TYP" = "inet" -a $__TIME4 -ge 0 -a \
( $__TIME -lt 0 -o $__TIME -gt $__TIME4 \
) ] && {
986 write_log
3 "ip Error: '$__ERR'"
987 write_log
7 "$(cat $ERRFILE)" # report error
989 else # use deprecated ifconfig
990 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
991 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
993 if [ $__ERR -eq 0 ]; then
995 /inet addr:/ { # Filter IPv4
996 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
998 $3=""; # remove Bcast: ...
999 $4=""; # remove Mask: ...
1000 FS=":"; # separator ":"
1001 $0=$0; # reread to activate separator
1002 $1=""; # remove addr
1003 FS=" "; # set back separator to default " "
1004 $0=$0; # reread to activate separator (remove whitespaces)
1005 print $1; # print IPv4 addr
1009 /inet6/ && /: [0-9a-eA-E]/ { # Filter IPv6 exclude fxxx
1010 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
1011 FS="/"; # separator "/"
1012 $0=$0; # reread to activate separator
1013 $2=""; # remove everything behind "/"
1014 FS=" "; # set back separator to default " "
1015 $0=$0; # reread to activate separator
1016 print $3; # print IPv6 addr
1020 write_log
3 "ifconfig Error: '$__ERR'"
1021 write_log
7 "$(cat $ERRFILE)" # report error
1024 [ $use_ipv6 -eq 0 ] && __DATA
="$__DATA4" || __DATA
="$__DATA6"
1025 [ -n "$__DATA" ] && write_log
7 "Current IP '$__DATA' detected on interface '$ip_interface'"
1026 elif [ -n "$ip_script" -a "$ip_source" = "script" ]; then
1027 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
1028 eval $ip_script >$DATFILE 2>$ERRFILE
1030 if [ $__ERR -eq 0 ]; then
1031 __DATA
=$
(cat $DATFILE)
1032 [ -n "$__DATA" ] && write_log
7 "Current IP '$__DATA' detected via script '$ip_script'"
1034 write_log
3 "$ip_script Error: '$__ERR'"
1035 write_log
7 "$(cat $ERRFILE)" # report error
1037 elif [ -n "$ip_url" -a "$ip_source" = "web" ]; then
1038 do_transfer
"$ip_url"
1039 # use correct regular expression
1040 [ $use_ipv6 -eq 0 ] \
1041 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
1042 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
1043 [ -n "$__DATA" ] && write_log
7 "Current IP '$__DATA' detected on web at '$ip_url'"
1045 write_log
12 "Error in 'get_current_ip()' - unhandled ip_source '$ip_source'"
1047 # valid data found return here
1048 [ -n "$__DATA" ] && {
1049 eval "$1=\"$__DATA\""
1053 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
1055 write_log
7 "Data detected:"
1056 write_log
7 "$(cat $DATFILE)"
1058 [ $VERBOSE -gt 1 ] && {
1059 # VERBOSE > 1 then NO retry
1060 write_log
4 "Get current IP via '$ip_source' failed - Verbose Mode: $VERBOSE - NO retry on error"
1064 __CNT
=$
(( $__CNT + 1 )) # increment error counter
1065 # if error count > retry_max_count leave here
1066 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
1067 write_log
14 "Get current IP via '$ip_source' failed after $retry_max_count retries"
1068 write_log
4 "Get current IP via '$ip_source' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
1069 sleep $RETRY_SECONDS &
1071 wait $PID_SLEEP # enable trap-handler
1074 # we should never come here there must be a programming error
1075 write_log
12 "Error in 'get_current_ip()' - program coding error"
1078 get_registered_ip
() {
1079 # $1 Name of Variable to store public IP (REGISTERED_IP)
1080 # $2 (optional) if set, do not retry on error
1081 local __CNT
=0 # error counter
1083 local __REGEX __PROG __RUNPROG __DATA __IP
1087 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
1088 [ $is_glue -eq 1 -a -z "$BIND_HOST" ] && write_log
14 "Lookup of glue records is only supported using BIND host"
1089 write_log
7 "Detect registered/public IP"
1091 # set correct regular expression
1092 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
1094 if [ -n "$BIND_HOST" ]; then
1096 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
1097 if [ $force_ipversion -eq 1 ]; then # force IP version
1098 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1100 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
1101 [ $is_glue -eq 1 ] && __PROG
="$__PROG -v" # use verbose output to get additional section
1103 __RUNPROG
="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1105 elif [ -n "$KNOT_HOST" ]; then
1107 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
1108 if [ $force_ipversion -eq 1 ]; then # force IP version
1109 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1111 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
1113 __RUNPROG
="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1115 elif [ -n "$DRILL" ]; then
1116 __PROG
="$DRILL -V0" # drill options name @server type
1117 if [ $force_ipversion -eq 1 ]; then # force IP version
1118 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
1120 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -t" || __PROG
="$__PROG -u" # force TCP
1121 __PROG
="$__PROG $lookup_host"
1122 [ -n "$dns_server" ] && __PROG
="$__PROG @$dns_server"
1123 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG A" || __PROG
="$__PROG AAAA"
1125 __RUNPROG
="$__PROG >$DATFILE 2>$ERRFILE"
1127 elif [ -n "$HOSTIP" ]; then # hostip package installed
1129 [ $force_dnstcp -ne 0 ] && \
1130 write_log
14 "hostip - no support for 'DNS over TCP'"
1132 # is IP given as dns_server ?
1133 __IP
=$
(echo $dns_server |
grep -m 1 -o "$IPV4_REGEX")
1134 [ -z "$__IP" ] && __IP
=$
(echo $dns_server |
grep -m 1 -o "$IPV6_REGEX")
1136 # we got NO ip for dns_server, so build command
1137 [ -z "$__IP" -a -n "$dns_server" ] && {
1139 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] && __IP
="$__IP -6"
1140 __IP
="$__IP $dns_server | grep -m 1 -o"
1141 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] \
1142 && __IP
="$__IP '$IPV6_REGEX'" \
1143 || __IP
="$__IP '$IPV4_REGEX'"
1147 [ $use_ipv6 -eq 1 ] && __PROG
="$__PROG -6"
1148 [ -n "$dns_server" ] && __PROG
="$__PROG -r $__IP"
1149 __RUNPROG
="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
1151 elif [ -n "$NSLOOKUP" ]; then # last use BusyBox nslookup
1152 NSLOOKUP_MUSL
=$
($
(command -v nslookup) localhost
2>&1 |
grep -F "(null)") # not empty busybox compiled with musl
1153 [ $force_dnstcp -ne 0 ] && \
1154 write_log
14 "Busybox nslookup - no support for 'DNS over TCP'"
1155 [ -n "$NSLOOKUP_MUSL" -a -n "$dns_server" ] && \
1156 write_log
14 "Busybox compiled with musl - nslookup don't support the use of DNS Server"
1157 [ $force_ipversion -ne 0 ] && \
1158 write_log
5 "Busybox nslookup - no support to 'force IP Version' (ignored)"
1160 __RUNPROG
="$NSLOOKUP $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1161 __PROG
="BusyBox nslookup"
1162 else # there must be an error
1163 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
1167 write_log
7 "#> $__RUNPROG"
1170 if [ $__ERR -ne 0 ]; then
1171 write_log
3 "$__PROG error: '$__ERR'"
1172 write_log
7 "$(cat $ERRFILE)"
1174 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then
1175 if [ $is_glue -eq 1 ]; then
1176 __DATA
=$
(cat $DATFILE |
grep "^$lookup_host" |
grep -om1 "$__REGEX" )
1178 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
1180 elif [ -n "$DRILL" ]; then
1181 __DATA
=$
(cat $DATFILE |
awk '/^'"$lookup_host"'/ {print $5; exit}' )
1182 elif [ -n "$HOSTIP" ]; then
1183 __DATA
=$
(cat $DATFILE |
grep -om1 "$__REGEX")
1184 elif [ -n "$NSLOOKUP" ]; then
1185 __DATA
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
1187 [ -n "$__DATA" ] && {
1188 write_log
7 "Registered IP '$__DATA' detected"
1189 [ -z "$IPFILE" ] ||
echo "$__DATA" > $IPFILE
1190 eval "$1=\"$__DATA\"" # valid data found
1191 return 0 # leave here
1193 write_log
4 "NO valid IP found"
1196 [ -z "$IPFILE" ] ||
echo "" > $IPFILE
1198 [ -n "$LUCI_HELPER" ] && return $__ERR # no retry if called by LuCI helper script
1199 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
1200 [ $VERBOSE -gt 1 ] && {
1201 # VERBOSE > 1 then NO retry
1202 write_log
4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE - NO retry on error"
1206 __CNT
=$
(( $__CNT + 1 )) # increment error counter
1207 # if error count > retry_max_count leave here
1208 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
1209 write_log
14 "Get registered/public IP for '$lookup_host' failed after $retry_max_count retries"
1211 write_log
4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
1212 sleep $RETRY_SECONDS &
1214 wait $PID_SLEEP # enable trap-handler
1217 # we should never come here there must be a programming error
1218 write_log
12 "Error in 'get_registered_ip()' - program coding error"
1222 # $1 Variable to store result in
1223 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
1224 local __UPTIME
=$
(cat /proc
/uptime
)
1225 eval "$1=\"${__UPTIME%%.*}\""
1230 # $2 optional (exit status)
1233 local __OLD_IFS
=$IFS
1234 local __NEWLINE_IFS
='
1237 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
1240 0) if [ $__ERR -eq 0 ]; then
1241 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)${N}"
1243 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)${N}"
1245 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1246 # reload config via starting the script again
1247 /usr
/lib
/ddns
/dynamic_dns_updater.sh
-v "0" -S "$__SECTIONID" -- start || true
1248 exit 0 ;; # and leave this one
1249 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)${N}";;
1250 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)${N}";;
1251 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)${N}";;
1252 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1255 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1257 for __PID
in $__PIDS; do
1258 kill -$1 $__PID # terminate it
1262 # remove out and err file
1263 [ -f $DATFILE ] && rm -f $DATFILE
1264 [ -f $ERRFILE ] && rm -f $ERRFILE
1266 # exit with correct handling:
1267 # remove trap handling settings and send kill to myself
1269 [ $1 -gt 0 ] && kill -$1 $$
1274 # $2 name of variable to store TLD
1275 # $3 name of variable to store (reg)Domain
1276 # $4 name of variable to store Host/Subdomain
1278 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1279 [ -z "$1" ] && write_log
12 "Error calling 'split_FQDN()' - missing FQDN to split"
1280 [ -f $TLDFILE ] || write_log
12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1282 local _HOST _FDOM _CTLD _FTLD
1283 local _SET
="$@" # save given function parameters
1285 local _PAR
=$
(echo "$1" |
tr [A-Z
] [a-z
] |
tr "." " ") # to lower and replace DOT with SPACE
1286 set -- $_PAR # set new as function parameters
1287 _PAR
="" # clear variable for later reuse
1288 while [ -n "$1" ] ; do # as long we have parameters
1289 _PAR
="$1 $_PAR" # invert order of parameters
1292 set -- $_PAR # use new as function parameters
1293 _PAR
="" # clear variable
1295 while [ -n "$1" ] ; do # as long we have parameters
1296 if [ -z "$_CTLD" ]; then # first loop
1297 _CTLD
="$1" # CURRENT TLD to look at
1300 _CTLD
="$1.$_CTLD" # Next TLD to look at
1303 # check if TLD exact match in tld_names.dat, save TLD
1304 zcat
$TLDFILE |
grep -E "^$_CTLD$" >/dev
/null
2>&1 && {
1305 _FTLD
="$_CTLD" # save found
1306 _FDOM
="$1" # save domain next step might be invalid
1309 # check if match any "*" in tld_names.dat,
1310 zcat
$TLDFILE |
grep -E "^\*.$_CTLD$" >/dev
/null
2>&1 && {
1311 [ -z "$1" ] && break # no more data break
1312 # check if next level TLD match excludes "!" in tld_names.dat
1313 if zcat
$TLDFILE |
grep -E "^!$1.$_CTLD$" >/dev
/null
2>&1 ; then
1314 _FTLD
="$_CTLD" # Yes
1321 [ -n "$_FTLD" ] && break # we have something valid, break
1324 # the leftover parameters are the HOST/SUBDOMAIN
1325 while [ -n "$1" ]; do
1326 _HOST
="$1 $_HOST" # remember we need to invert
1329 _HOST
=$
(echo $_HOST |
tr " " ".") # insert DOT
1331 set -- $_SET # set back parameters from function call
1332 [ -n "$_FTLD" ] && {
1333 eval "$2=$_FTLD" # set TLD
1334 eval "$3=$_FDOM" # set registrable domain
1335 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1338 eval "$2=''" # clear TLD
1339 eval "$3=''" # clear registrable domain
1340 eval "$4=''" # clear HOST/SUBDOMAIN
1345 # Original written for bash by
1346 #.Author: Florian Streibelt <florian@f-streibelt.de>
1348 # License: Public Domain, but please be fair and
1349 # attribute the original author(s) and provide
1350 # a link to the original source for corrections:
1351 #. https://github.com/mutax/IPv6-Address-checks
1354 # $2 name of variable to store expanded IPv6
1355 [ $# -ne 2 ] && write_log
12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1357 INPUT
="$(echo "$1" | tr 'A-F' 'a-f')"
1358 [ "$INPUT" = "::" ] && INPUT
="::0" # special case ::
1362 while [ "$O" != "$INPUT" ]; do
1365 # fill all words with zeroes
1366 INPUT
=$
( echo "$INPUT" |
sed -e 's|:\([0-9a-f]\{3\}\):|:0\1:|g' \
1367 -e 's|:\([0-9a-f]\{3\}\)$|:0\1|g' \
1368 -e 's|^\([0-9a-f]\{3\}\):|0\1:|g' \
1369 -e 's|:\([0-9a-f]\{2\}\):|:00\1:|g' \
1370 -e 's|:\([0-9a-f]\{2\}\)$|:00\1|g' \
1371 -e 's|^\([0-9a-f]\{2\}\):|00\1:|g' \
1372 -e 's|:\([0-9a-f]\):|:000\1:|g' \
1373 -e 's|:\([0-9a-f]\)$|:000\1|g' \
1374 -e 's|^\([0-9a-f]\):|000\1:|g' )
1381 echo "$INPUT" |
grep -qs "::"
1382 if [ "$?" -eq 0 ]; then
1383 GRPS
="$( echo "$INPUT" | sed 's|[0-9a-f]||g' | wc -m )"
1384 GRPS
=$
(( GRPS-1
)) # remove carriage return
1385 MISSING
=$
(( 8-GRPS ))
1386 while [ $MISSING -gt 0 ]; do
1387 ZEROES
="$ZEROES:0000"
1388 MISSING
=$
(( MISSING-1
))
1391 # be careful where to place the :
1392 INPUT
=$
( echo "$INPUT" |
sed -e 's|\(.\)::\(.\)|\1'$ZEROES':\2|g' \
1393 -e 's|\(.\)::$|\1'$ZEROES':0000|g' \
1394 -e 's|^::\(.\)|'$ZEROES':0000:\1|g;s|^:||g' )
1397 # an expanded address has 39 chars + CR
1398 if [ $
(echo $INPUT |
wc -m) != 40 ]; then
1399 write_log
4 "Error in 'expand_ipv6()' - invalid IPv6 found: '$1' expanded: '$INPUT'"
1404 # echo the fully expanded version of the address