ddns-scripts: fix update_porkbun_v3 shell syntax
[feed/packages.git] / net / ddns-scripts / files / usr / lib / ddns / dynamic_dns_functions.sh
1 #!/bin/sh
2 # /usr/lib/ddns/dynamic_dns_functions.sh
3 #
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>
10 #
11 # function timeout
12 # copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
13 # @author Anthony Thyssen 6 April 2011
14 #
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
19
20 . /lib/functions.sh
21 . /lib/functions/network.sh
22
23 # GLOBAL VARIABLES #
24 if [ -f "/usr/share/ddns/version" ]; then
25 VERSION="$(cat "/usr/share/ddns/version")"
26 else
27 VERSION="unknown"
28 fi
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
33
34 LOGFILE="" # logfile - all files are set in dynamic_dns_updater.sh
35 PIDFILE="" # pid file
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
41
42 CHECK_SECONDS=0 # calculated seconds out of given
43 FORCE_SECONDS=0 # interval and unit
44 RETRY_SECONDS=0 # in configuration
45
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
50
51 CURRENT_IP="" # holds the current IP read from the box
52 REGISTERED_IP="" # holds the IP read from DNS
53
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
57
58 UPD_ANSWER="" # Answer given by service on success
59
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
62
63 PID_SLEEP=0 # ProcessID of current background "sleep"
64
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,\}\)"
70
71 # characters that are dangerous to pass to a shell command line
72 SHELL_ESCAPE="[\"\'\`\$\!();><{}?|\[\]\*\\\\]"
73
74 # dns character set. "-" must be the last character
75 DNS_CHARSET="[@a-zA-Z0-9._-]"
76
77 # domains can have * for wildcard. "-" must be the last character
78 DNS_CHARSET_DOMAIN="[@a-zA-Z0-9._*-]"
79
80 # detect if called by ddns-lucihelper.sh script, disable retrys (empty variable == false)
81 LUCI_HELPER=$(printf %s "$MYPROG" | grep -i "luci")
82
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)
89
90 # Transfer Programs
91 WGET=$(command -v wget)
92 $WGET -V 2>/dev/null | grep -F -q +https && WGET_SSL=$WGET
93
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")
99
100 UCLIENT_FETCH=$(command -v uclient-fetch)
101
102 # Global configuration settings
103 # allow NON-public IP's
104 upd_privateip=$(uci -q get ddns.global.upd_privateip) || upd_privateip=0
105
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
109
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
113
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
117
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'"
121
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
126
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()
131 {
132 local __PKGNAME="$1"
133 local __SECTIONID="$2"
134 local __VAR
135 local __ALL_OPTION_VARIABLES=""
136
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
141 config_cb()
142 {
143 if [ ."$2" = ."$__SECTIONID" ]; then
144 option_cb()
145 {
146 __ALL_OPTION_VARIABLES="$__ALL_OPTION_VARIABLES $1"
147 }
148 else
149 option_cb() { return 0; }
150 fi
151 }
152
153 config_load "$__PKGNAME"
154
155 # Given SECTION_ID not found so no data, so return 1
156 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
157
158 for __VAR in $__ALL_OPTION_VARIABLES
159 do
160 config_get "$__VAR" "$__SECTIONID" "$__VAR"
161 done
162 return 0
163 }
164
165 # read's all service sections from ddns config
166 # $1 = Name of variable to store
167 load_all_service_sections() {
168 local __DATA=""
169 config_cb()
170 {
171 # only look for section type "service", ignore everything else
172 [ "$1" = "service" ] && __DATA="$__DATA $2"
173 }
174 config_load "ddns"
175
176 eval "$1=\"$__DATA\""
177 return
178 }
179
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()
186 {
187 local __EVENTIF="$1"
188 local __SECTIONS=""
189 local __SECTIONID=""
190 local __IFACE=""
191
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 &
198 else
199 /usr/lib/ddns/dynamic_dns_updater.sh -v "$VERBOSE" -S "$__SECTIONID" -- start
200 fi
201 done
202 }
203
204 # stop sections process incl. childs (sleeps)
205 # $1 = section
206 stop_section_processes() {
207 local __PID=0
208 local __PIDFILE="$ddns_rundir/$1.pid"
209 [ $# -ne 1 ] && write_log 12 "Error calling 'stop_section_processes()' - wrong number of parameters"
210
211 [ -e "$__PIDFILE" ] && {
212 __PID=$(cat $__PIDFILE)
213 ps | grep "^[\t ]*$__PID" >/dev/null 2>&1 && kill $__PID || __PID=0 # terminate it
214 }
215 [ $__PID -eq 0 ] # report if process was running
216 }
217
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() {
224 local __EVENTIF="$1"
225 local __SECTIONS=""
226 local __SECTIONID=""
227 local __IFACE=""
228
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"
234 done
235 }
236
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
241 write_log() {
242 local __LEVEL __EXIT __CMD __MSG __MSE
243 local __TIME=$(date +%H%M%S)
244 [ $1 -ge 10 ] && {
245 __LEVEL=$(($1-10))
246 __EXIT=1
247 } || {
248 __LEVEL=$1
249 __EXIT=0
250 }
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";;
269 *) return;;
270 esac
271
272 # verbose echo
273 [ $VERBOSE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
274 # write to logfile
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" )
284 fi
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
288 fi
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
294 exit 1
295 }
296 [ $use_syslog -eq 0 ] && return
297 [ $((use_syslog + __LEVEL)) -le 7 ] && eval '$__CMD'
298
299 return
300 }
301
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
309 urlencode() {
310 # $1 Name of Variable to store encoded string to
311 # $2 string to encode
312 local __ENC
313
314 [ $# -ne 2 ] && write_log 12 "Error calling 'urlencode()' - wrong number of parameters"
315
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}}')"
318
319 eval "$1=\"$__ENC\"" # transfer back to variable
320 return 0
321 }
322
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
329 get_service_data() {
330 local provider="$1"
331 shift
332 local dir="$1"
333 shift
334
335 . /usr/share/libubox/jshn.sh
336 local name data url answer script
337
338 [ $# -ne 3 ] && write_log 12 "Error calling 'get_service_data()' - wrong number of parameters"
339
340 [ -f "${dir}/${provider}.json" ] || {
341 eval "$1=\"\""
342 eval "$2=\"\""
343 eval "$3=\"\""
344 return 1
345 }
346
347 json_load_file "${dir}/${provider}.json"
348 json_get_var name "name"
349 if [ "$use_ipv6" -eq "1" ]; then
350 json_select "ipv6"
351 else
352 json_select "ipv4"
353 fi
354 json_get_var data "url"
355 json_get_var answer "answer"
356 json_select ".."
357 json_cleanup
358
359 # check if URL or SCRIPT is given
360 url=$(echo "$data" | grep "^http")
361 [ -z "$url" ] && script="/usr/lib/ddns/${data}"
362
363 eval "$1=\"$url\""
364 eval "$2=\"$script\""
365 eval "$3=\"$answer\""
366 return 0
367 }
368
369 # Calculate seconds from interval and unit
370 # $1 Name of Variable to store result in
371 # $2 Number and
372 # $3 Unit of time interval
373 get_seconds() {
374 [ $# -ne 3 ] && write_log 12 "Error calling 'get_seconds()' - wrong number of parameters"
375 case "$3" in
376 "days" ) eval "$1=$(( $2 * 86400 ))";;
377 "hours" ) eval "$1=$(( $2 * 3600 ))";;
378 "minutes" ) eval "$1=$(( $2 * 60 ))";;
379 * ) eval "$1=$2";;
380 esac
381 return 0
382 }
383
384 timeout() {
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
390 #
391 # timeout [-SIG] time [--] command args...
392 #
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.
396 #
397 # Example use
398 # timeout 5 countdown
399 #
400 # Based on notes in my "Shell Script Hints", section "Command Timeout"
401 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
402 #
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".
406 #
407 # It took years of occasional trials, errors and testing to get a pure bash
408 # timeout command working as well as this does.
409 #
410 #.Anthony Thyssen 6 April 2011
411 #
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
415
416 # output the script comments as docs
417 # Usage() {
418 # echo >&2 "$PROGNAME:" "$@"
419 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
420 # exit 10;
421 # }
422
423 SIG=-TERM
424
425 while [ $# -gt 0 ]; do
426 case "$1" in
427 --)
428 # forced end of user options
429 shift;
430 break ;;
431 # -\?|--help|--doc*)
432 # Usage ;;
433 [0-9]*)
434 TIMEOUT="$1" ;;
435 -*)
436 SIG="$1" ;;
437 *)
438 # unforced end of user options
439 break ;;
440 esac
441 shift # next option
442 done
443
444 # run main command in backgrounds and get its pid
445 "$@" &
446 command_pid=$!
447
448 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
449 sleep_pid=0
450 (
451 # cleanup sleep process
452 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
453 # sleep timeout period in background
454 sleep $TIMEOUT &
455 sleep_pid=$!
456 wait $sleep_pid
457 # Abort the command
458 kill $SIG $command_pid >/dev/null 2>&1
459 return 1
460 ) &
461 timeout_pid=$!
462
463 # Wait for main command to finished or be timed out
464 wait $command_pid
465 status=$?
466
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
470
471 # Uncomment to check if a LONG sleep still running (no sleep should be)
472 # sleep 1
473 # echo "-----------"
474 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
475
476 return $status
477 }
478
479 # sanitize a variable
480 # $1 variable name
481 # $2 allowed shell pattern
482 # $3 disallowed shell pattern
483 sanitize_variable() {
484 local __VAR=$1
485 eval __VALUE=\$$__VAR
486 local __ALLOWED=$2
487 local __REJECT=$3
488
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"
492 fi
493
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"
497 fi
498 }
499
500 # verify given host and port is connectable
501 # $1 Host/IP to verify
502 # $2 Port to verify
503 verify_host_port() {
504 local __HOST=$1
505 local __PORT=$2
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
509 # return codes
510 # 1 system specific error
511 # 2 nslookup/host error
512 # 3 nc (netcat) error
513 # 4 unmatched IP version
514
515 [ $# -ne 2 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
516
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
523 __PROG="BIND host"
524 __RUNPROG="$BIND_HOST $__HOST >$DATFILE 2>$ERRFILE"
525 elif [ -n "$KNOT_HOST" ]; then # use Knot host if installed
526 __PROG="Knot host"
527 __RUNPROG="$KNOT_HOST $__HOST >$DATFILE 2>$ERRFILE"
528 elif [ -n "$DRILL" ]; then # use drill if installed
529 __PROG="drill"
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
533 __PROG="hostip"
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"
539 fi
540 write_log 7 "#> $__RUNPROG"
541 eval $__RUNPROG
542 __ERR=$?
543 # command error
544 [ $__ERR -gt 0 ] && {
545 write_log 3 "DNS Resolver Error - $__PROG Error '$__ERR'"
546 write_log 7 "$(cat $ERRFILE)"
547 return 2
548 }
549 # extract IP address
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")"
565 fi
566 }
567
568 # check IP version if forced
569 if [ $force_ipversion -ne 0 ]; then
570 __ERR=0
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"
576 }
577 fi
578
579 # verify nc command
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"
585
586 # connectivity test
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
593
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"
597 eval $__RUNPROG
598 __ERR=$?
599 [ $__ERR -eq 0 ] && return 0
600 write_log 3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
601 write_log 7 "$(cat $ERRFILE)"
602 return 3
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"
606 eval $__RUNPROG
607 __ERR=$?
608 [ $__ERR -eq 0 ] && return 0
609 write_log 3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
610 return 3
611 fi
612 }
613
614 # verify given DNS server if connectable
615 # $1 DNS server to verify
616 verify_dns() {
617 local __ERR=255 # last error buffer
618 local __CNT=0 # error counter
619
620 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_dns()' - wrong number of parameters"
621 write_log 7 "Verify DNS server '$1'"
622
623 while [ $__ERR -ne 0 ]; do
624 # DNS uses port 53
625 verify_host_port "$1" "53"
626 __ERR=$?
627 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
628 return $__ERR
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"
631 return $__ERR
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"
637
638 write_log 4 "Verify DNS server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
639 sleep $RETRY_SECONDS &
640 PID_SLEEP=$!
641 wait $PID_SLEEP # enable trap-handler
642 PID_SLEEP=0
643 fi
644 done
645 return 0
646 }
647
648 # analyze and verify given proxy string
649 # $1 Proxy-String to verify
650 verify_proxy() {
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
660
661 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_proxy()' - wrong number of parameters"
662 write_log 7 "Verify Proxy server 'http://$1'"
663
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
672 # IPv6 split at "]:"
673 __PORT=$(echo $__TMP | awk -F "]:" '{print $2}')
674 else
675 __HOST=$(echo $__TMP | awk -F ":" '{print $1}')
676 __PORT=$(echo $__TMP | awk -F ":" '{print $2}')
677 fi
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"
682 }
683
684 while [ $__ERR -gt 0 ]; do
685 verify_host_port "$__HOST" "$__PORT"
686 __ERR=$?
687 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
688 return $__ERR
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"
691 return $__ERR
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"
697
698 write_log 4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
699 sleep $RETRY_SECONDS &
700 PID_SLEEP=$!
701 wait $PID_SLEEP # enable trap-handler
702 PID_SLEEP=0
703 fi
704 done
705 return 0
706 }
707
708 do_transfer() {
709 # $1 # URL to use
710 local __URL="$1"
711 local __ERR=0
712 local __CNT=0 # error counter
713 local __PROG __RUNPROG
714
715 [ $# -ne 1 ] && write_log 12 "Error in 'do_transfer()' - wrong number of parameters"
716
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"
719
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
725 local __BINDIP
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"
732 fi
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
736 fi
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"
747 fi
748 fi
749 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
750 [ -z "$proxy" ] && __PROG="$__PROG --no-proxy"
751
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'"
757 fi
758
759 __RUNPROG="$__PROG '$__URL'" # build final command
760 __PROG="GNU Wget" # reuse for error logging
761
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
771 local __DEVICE
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"
776 fi
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
780 fi
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"
791 fi
792 fi
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"
800 fi
801
802 __RUNPROG="$__PROG '$__URL'" # build final command
803 __PROG="cURL" # reuse for error logging
804
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
816 fi
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"
820 # proxy support
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"
830 fi
831 fi
832 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
833 __PROG="uclient-fetch" # reuse for error logging
834
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"
849
850 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
851 __PROG="Busybox Wget" # reuse for error logging
852
853 else
854 write_log 13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
855 fi
856
857 while : ; do
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
863
864 write_log 3 "$__PROG Error: '$__ERR'"
865 write_log 7 "$(cat $ERRFILE)" # report error
866
867 [ $VERBOSE -gt 1 ] && {
868 # VERBOSE > 1 then NO retry
869 write_log 4 "Transfer failed - Verbose Mode: $VERBOSE - NO retry on error"
870 return 1
871 }
872
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"
877
878 write_log 4 "Transfer failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
879 sleep $RETRY_SECONDS &
880 PID_SLEEP=$!
881 wait $PID_SLEEP # enable trap-handler
882 PID_SLEEP=0
883 done
884 # we should never come here there must be a programming error
885 write_log 12 "Error in 'do_transfer()' - program coding error"
886 }
887
888 send_update() {
889 # $1 # IP to set at DDNS service provider
890 local __IP
891
892 [ $# -ne 1 ] && write_log 12 "Error calling 'send_update()' - wrong number of parameters"
893
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]")
898 else
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
901 fi
902 [ -z "$__IP" ] && {
903 write_log 3 "No or private or invalid IP '$1' given! Please check your configuration"
904 return 127
905 }
906
907 if [ -n "$update_script" ]; then
908 write_log 7 "parsing script '$update_script'"
909 . $update_script
910 else
911 local __URL __ERR
912
913 # do replaces in URL
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:#')
918
919 do_transfer "$__URL" || return 1
920
921 write_log 7 "DDNS Provider answered:${N}$(cat $DATFILE)"
922
923 [ -z "$UPD_ANSWER" ] && return 0 # not set then ignore
924
925 grep -i -E "$UPD_ANSWER" $DATFILE >/dev/null 2>&1
926 return $? # "0" if found
927 fi
928 }
929
930 get_current_ip () {
931 # $1 Name of Variable to store current IP
932 local __CNT=0 # error counter
933 local __RUNPROG __DATA __URL __ERR
934
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'"
937
938 while : ; do
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
952 __ERR=$?
953 if [ $__ERR -eq 0 ]; then
954 # DATFILE (sample)
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
964
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
970
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 \) ] && {
977 __DATA6="$__ADR"
978 __TIME6="$__TIME"
979 }
980 [ "$__TYP" = "inet" -a $__TIME4 -ge 0 -a \( $__TIME -lt 0 -o $__TIME -gt $__TIME4 \) ] && {
981 __DATA4="$__ADR"
982 __TIME4="$__TIME"
983 }
984 done < $ERRFILE
985 else
986 write_log 3 "ip Error: '$__ERR'"
987 write_log 7 "$(cat $ERRFILE)" # report error
988 fi
989 else # use deprecated ifconfig
990 write_log 7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
991 ifconfig $ip_interface >$DATFILE 2>$ERRFILE
992 __ERR=$?
993 if [ $__ERR -eq 0 ]; then
994 __DATA4=$(awk '
995 /inet addr:/ { # Filter IPv4
996 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
997 $1=""; # remove inet
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
1006 }' $DATFILE
1007 )
1008 __DATA6=$(awk '
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
1017 }' $DATFILE
1018 )
1019 else
1020 write_log 3 "ifconfig Error: '$__ERR'"
1021 write_log 7 "$(cat $ERRFILE)" # report error
1022 fi
1023 fi
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
1029 __ERR=$?
1030 if [ $__ERR -eq 0 ]; then
1031 __DATA=$(cat $DATFILE)
1032 [ -n "$__DATA" ] && write_log 7 "Current IP '$__DATA' detected via script '$ip_script'"
1033 else
1034 write_log 3 "$ip_script Error: '$__ERR'"
1035 write_log 7 "$(cat $ERRFILE)" # report error
1036 fi
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'"
1044 else
1045 write_log 12 "Error in 'get_current_ip()' - unhandled ip_source '$ip_source'"
1046 fi
1047 # valid data found return here
1048 [ -n "$__DATA" ] && {
1049 eval "$1=\"$__DATA\""
1050 return 0
1051 }
1052
1053 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
1054
1055 write_log 7 "Data detected:"
1056 write_log 7 "$(cat $DATFILE)"
1057
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"
1061 return 1
1062 }
1063
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 &
1070 PID_SLEEP=$!
1071 wait $PID_SLEEP # enable trap-handler
1072 PID_SLEEP=0
1073 done
1074 # we should never come here there must be a programming error
1075 write_log 12 "Error in 'get_current_ip()' - program coding error"
1076 }
1077
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
1082 local __ERR=255
1083 local __REGEX __PROG __RUNPROG __DATA __IP
1084 # return codes
1085 # 1 no IP detected
1086
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"
1090
1091 # set correct regular expression
1092 [ $use_ipv6 -eq 0 ] && __REGEX="$IPV4_REGEX" || __REGEX="$IPV6_REGEX"
1093
1094 if [ -n "$BIND_HOST" ]; then
1095 __PROG="$BIND_HOST"
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"
1099 fi
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
1102
1103 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1104 __PROG="BIND host"
1105 elif [ -n "$KNOT_HOST" ]; then
1106 __PROG="$KNOT_HOST"
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"
1110 fi
1111 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
1112
1113 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1114 __PROG="Knot host"
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"
1119 fi
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"
1124
1125 __RUNPROG="$__PROG >$DATFILE 2>$ERRFILE"
1126 __PROG="drill"
1127 elif [ -n "$HOSTIP" ]; then # hostip package installed
1128 __PROG="$HOSTIP"
1129 [ $force_dnstcp -ne 0 ] && \
1130 write_log 14 "hostip - no support for 'DNS over TCP'"
1131
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")
1135
1136 # we got NO ip for dns_server, so build command
1137 [ -z "$__IP" -a -n "$dns_server" ] && {
1138 __IP="\`$HOSTIP"
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'"
1144 __IP="$__IP \`"
1145 }
1146
1147 [ $use_ipv6 -eq 1 ] && __PROG="$__PROG -6"
1148 [ -n "$dns_server" ] && __PROG="$__PROG -r $__IP"
1149 __RUNPROG="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
1150 __PROG="hostip"
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)"
1159
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"
1164 fi
1165
1166 while : ; do
1167 write_log 7 "#> $__RUNPROG"
1168 eval $__RUNPROG
1169 __ERR=$?
1170 if [ $__ERR -ne 0 ]; then
1171 write_log 3 "$__PROG error: '$__ERR'"
1172 write_log 7 "$(cat $ERRFILE)"
1173 else
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" )
1177 else
1178 __DATA=$(cat $DATFILE | awk -F "address " '/has/ {print $2; exit}' )
1179 fi
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 }" )
1186 fi
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
1192 }
1193 write_log 4 "NO valid IP found"
1194 __ERR=127
1195 fi
1196 [ -z "$IPFILE" ] || echo "" > $IPFILE
1197
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"
1203 return $__ERR
1204 }
1205
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"
1210
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 &
1213 PID_SLEEP=$!
1214 wait $PID_SLEEP # enable trap-handler
1215 PID_SLEEP=0
1216 done
1217 # we should never come here there must be a programming error
1218 write_log 12 "Error in 'get_registered_ip()' - program coding error"
1219 }
1220
1221 get_uptime() {
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%%.*}\""
1226 }
1227
1228 trap_handler() {
1229 # $1 trap signal
1230 # $2 optional (exit status)
1231 local __PIDS __PID
1232 local __ERR=${2:-0}
1233 local __OLD_IFS=$IFS
1234 local __NEWLINE_IFS='
1235 ' # __NEWLINE_IFS
1236
1237 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev/null # kill pending sleep if exist
1238
1239 case $1 in
1240 0) if [ $__ERR -eq 0 ]; then
1241 write_log 5 "PID '$$' exit normal at $(eval $DATE_PROG)${N}"
1242 else
1243 write_log 4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)${N}"
1244 fi ;;
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()'";;
1253 esac
1254
1255 __PIDS=$(pgrep -P $$) # get my childs (pgrep prints with "newline")
1256 IFS=$__NEWLINE_IFS
1257 for __PID in $__PIDS; do
1258 kill -$1 $__PID # terminate it
1259 done
1260 IFS=$__OLD_IFS
1261
1262 # remove out and err file
1263 [ -f $DATFILE ] && rm -f $DATFILE
1264 [ -f $ERRFILE ] && rm -f $ERRFILE
1265
1266 # exit with correct handling:
1267 # remove trap handling settings and send kill to myself
1268 trap - 0 1 2 3 15
1269 [ $1 -gt 0 ] && kill -$1 $$
1270 }
1271
1272 split_FQDN() {
1273 # $1 FQDN to split
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
1277
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'"
1281
1282 local _HOST _FDOM _CTLD _FTLD
1283 local _SET="$@" # save given function parameters
1284
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
1290 shift
1291 done
1292 set -- $_PAR # use new as function parameters
1293 _PAR="" # clear variable
1294
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
1298 shift
1299 else
1300 _CTLD="$1.$_CTLD" # Next TLD to look at
1301 shift
1302 fi
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
1307 continue
1308 }
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
1315 else
1316 _FTLD="$1.$_CTLD"
1317 shift
1318 fi
1319 _FDOM="$1"; shift
1320 }
1321 [ -n "$_FTLD" ] && break # we have something valid, break
1322 done
1323
1324 # the leftover parameters are the HOST/SUBDOMAIN
1325 while [ -n "$1" ]; do
1326 _HOST="$1 $_HOST" # remember we need to invert
1327 shift
1328 done
1329 _HOST=$(echo $_HOST | tr " " ".") # insert DOT
1330
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
1336 return 0
1337 }
1338 eval "$2=''" # clear TLD
1339 eval "$3=''" # clear registrable domain
1340 eval "$4=''" # clear HOST/SUBDOMAIN
1341 return 1
1342 }
1343
1344 expand_ipv6() {
1345 # Original written for bash by
1346 #.Author: Florian Streibelt <florian@f-streibelt.de>
1347 # Date: 08.04.2012
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
1352
1353 # $1 IPv6 to expand
1354 # $2 name of variable to store expanded IPv6
1355 [ $# -ne 2 ] && write_log 12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1356
1357 INPUT="$(echo "$1" | tr 'A-F' 'a-f')"
1358 [ "$INPUT" = "::" ] && INPUT="::0" # special case ::
1359
1360 O=""
1361
1362 while [ "$O" != "$INPUT" ]; do
1363 O="$INPUT"
1364
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' )
1375
1376 done
1377
1378 # now expand the ::
1379 ZEROES=""
1380
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 ))
1389 done
1390
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' )
1395 fi
1396
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'"
1400 eval "$2='invalid'"
1401 return 1
1402 fi
1403
1404 # echo the fully expanded version of the address
1405 eval "$2=$INPUT"
1406 return 0
1407 }