17475448b38accce4f7c320eca99c1a303c2fa90
[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" -o -n "$KNOT_HOST" ]; then # use BIND host or Knot 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 "$DRILL" ]; then # use drill if installed
554 __IPV4="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV4_REGEX")"
555 __IPV6="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV6_REGEX")"
556 elif [ -n "$HOSTIP" ]; then # use hostip if installed
557 __IPV4="$(grep -m 1 -o "$IPV4_REGEX" "$DATFILE")"
558 __IPV6="$(grep -m 1 -o "$IPV6_REGEX" "$DATFILE")"
559 else # use BusyBox nslookup
560 __IPV4="$(sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }" "$DATFILE")"
561 __IPV6="$(sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }" "$DATFILE")"
562 fi
563 }
564
565 # check IP version if forced
566 if [ $force_ipversion -ne 0 ]; then
567 __ERR=0
568 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR=4
569 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR=6
570 [ $__ERR -gt 0 ] && {
571 [ -n "$LUCI_HELPER" ] && return 4
572 write_log 14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
573 }
574 fi
575
576 # verify nc command
577 # busybox nc compiled without -l option "NO OPT l!" -> critical error
578 $__NC --help 2>&1 | grep -i "NO OPT l!" >/dev/null 2>&1 && \
579 write_log 12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
580 # busybox nc compiled with extensions
581 $__NC --help 2>&1 | grep "\-w" >/dev/null 2>&1 && __NCEXT="TRUE"
582
583 # connectivity test
584 # run busybox nc to HOST PORT
585 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
586 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
587 # not worrying, if there is an IPv6 wan address
588 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
589 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP=$__IPV6 || __IP=$__IPV4
590
591 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
592 __RUNPROG="$__NC -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
593 write_log 7 "#> $__RUNPROG"
594 eval $__RUNPROG
595 __ERR=$?
596 [ $__ERR -eq 0 ] && return 0
597 write_log 3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
598 write_log 7 "$(cat $ERRFILE)"
599 return 3
600 else # nc compiled without extensions (no timeout support)
601 __RUNPROG="timeout 2 -- $__NC $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
602 write_log 7 "#> $__RUNPROG"
603 eval $__RUNPROG
604 __ERR=$?
605 [ $__ERR -eq 0 ] && return 0
606 write_log 3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
607 return 3
608 fi
609 }
610
611 # verify given DNS server if connectable
612 # $1 DNS server to verify
613 verify_dns() {
614 local __ERR=255 # last error buffer
615 local __CNT=0 # error counter
616
617 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_dns()' - wrong number of parameters"
618 write_log 7 "Verify DNS server '$1'"
619
620 while [ $__ERR -ne 0 ]; do
621 # DNS uses port 53
622 verify_host_port "$1" "53"
623 __ERR=$?
624 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
625 return $__ERR
626 elif [ $__ERR -ne 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
627 write_log 4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
628 return $__ERR
629 elif [ $__ERR -ne 0 ]; then
630 __CNT=$(( $__CNT + 1 )) # increment error counter
631 # if error count > retry_max_count leave here
632 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
633 write_log 14 "Verify DNS server '$1' failed after $retry_max_count retries"
634
635 write_log 4 "Verify DNS server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
636 sleep $RETRY_SECONDS &
637 PID_SLEEP=$!
638 wait $PID_SLEEP # enable trap-handler
639 PID_SLEEP=0
640 fi
641 done
642 return 0
643 }
644
645 # analyze and verify given proxy string
646 # $1 Proxy-String to verify
647 verify_proxy() {
648 # complete entry user:password@host:port
649 # inside user and password NO '@' of ":" allowed
650 # host and port only host:port
651 # host only host ERROR unsupported
652 # IPv4 address instead of host 123.234.234.123
653 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
654 local __TMP __HOST __PORT
655 local __ERR=255 # last error buffer
656 local __CNT=0 # error counter
657
658 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_proxy()' - wrong number of parameters"
659 write_log 7 "Verify Proxy server 'http://$1'"
660
661 # try to split user:password "@" host:port
662 __TMP=$(echo $1 | awk -F "@" '{print $2}')
663 # no "@" found - only host:port is given
664 [ -z "$__TMP" ] && __TMP="$1"
665 # now lets check for IPv6 address
666 __HOST=$(echo $__TMP | grep -m 1 -o "$IPV6_REGEX")
667 # IPv6 host address found read port
668 if [ -n "$__HOST" ]; then
669 # IPv6 split at "]:"
670 __PORT=$(echo $__TMP | awk -F "]:" '{print $2}')
671 else
672 __HOST=$(echo $__TMP | awk -F ":" '{print $1}')
673 __PORT=$(echo $__TMP | awk -F ":" '{print $2}')
674 fi
675 # No Port detected - EXITING
676 [ -z "$__PORT" ] && {
677 [ -n "$LUCI_HELPER" ] && return 5
678 write_log 14 "Invalid Proxy server Error '5' - proxy port missing"
679 }
680
681 while [ $__ERR -gt 0 ]; do
682 verify_host_port "$__HOST" "$__PORT"
683 __ERR=$?
684 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
685 return $__ERR
686 elif [ $__ERR -gt 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
687 write_log 4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
688 return $__ERR
689 elif [ $__ERR -gt 0 ]; then
690 __CNT=$(( $__CNT + 1 )) # increment error counter
691 # if error count > retry_max_count leave here
692 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
693 write_log 14 "Verify Proxy server '$1' failed after $retry_max_count retries"
694
695 write_log 4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
696 sleep $RETRY_SECONDS &
697 PID_SLEEP=$!
698 wait $PID_SLEEP # enable trap-handler
699 PID_SLEEP=0
700 fi
701 done
702 return 0
703 }
704
705 do_transfer() {
706 # $1 # URL to use
707 local __URL="$1"
708 local __ERR=0
709 local __CNT=0 # error counter
710 local __PROG __RUNPROG
711
712 [ $# -ne 1 ] && write_log 12 "Error in 'do_transfer()' - wrong number of parameters"
713
714 # Use ip_network as default for bind_network if not separately specified
715 [ -z "$bind_network" ] && [ "$ip_source" = "network" ] && [ "$ip_network" ] && bind_network="$ip_network"
716
717 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
718 if [ -n "$WGET_SSL" ] && [ $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
719 __PROG="$WGET --hsts-file=/tmp/.wget-hsts -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
720 # force network/ip to use for communication
721 if [ -n "$bind_network" ]; then
722 local __BINDIP
723 # set correct program to detect IP
724 [ $use_ipv6 -eq 0 ] && __RUNPROG="network_get_ipaddr" || __RUNPROG="network_get_ipaddr6"
725 eval "$__RUNPROG __BINDIP $bind_network" || \
726 write_log 13 "Can not detect current IP using '$__RUNPROG $bind_network' - Error: '$?'"
727 write_log 7 "Force communication via IP '$__BINDIP'"
728 __PROG="$__PROG --bind-address=$__BINDIP"
729 fi
730 # force ip version to use
731 if [ $force_ipversion -eq 1 ]; then
732 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
733 fi
734 # set certificate parameters
735 if [ $use_https -eq 1 ]; then
736 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
737 __PROG="$__PROG --no-check-certificate"
738 elif [ -f "$cacert" ]; then
739 __PROG="$__PROG --ca-certificate=${cacert}"
740 elif [ -d "$cacert" ]; then
741 __PROG="$__PROG --ca-directory=${cacert}"
742 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
743 write_log 14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
744 fi
745 fi
746 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
747 [ -z "$proxy" ] && __PROG="$__PROG --no-proxy"
748
749 # user agent string if provided
750 if [ -n "$user_agent" ]; then
751 # replace single and double quotes
752 user_agent=$(echo $user_agent | sed "s/'/ /g" | sed 's/"/ /g')
753 __PROG="$__PROG --user-agent='$user_agent'"
754 fi
755
756 __RUNPROG="$__PROG '$__URL'" # build final command
757 __PROG="GNU Wget" # reuse for error logging
758
759 # 2nd choice is cURL IPv4/IPv6/HTTPS
760 # libcurl might be compiled without Proxy or HTTPS Support
761 elif [ -n "$CURL" ]; then
762 __PROG="$CURL -RsS -o $DATFILE --stderr $ERRFILE"
763 # check HTTPS support
764 [ -z "$CURL_SSL" -a $use_https -eq 1 ] && \
765 write_log 13 "cURL: libcurl compiled without https support"
766 # force network/interface-device to use for communication
767 if [ -n "$bind_network" ]; then
768 local __DEVICE
769 network_get_device __DEVICE $bind_network || \
770 write_log 13 "Can not detect local device using 'network_get_device $bind_network' - Error: '$?'"
771 write_log 7 "Force communication via device '$__DEVICE'"
772 __PROG="$__PROG --interface $__DEVICE"
773 fi
774 # force ip version to use
775 if [ $force_ipversion -eq 1 ]; then
776 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
777 fi
778 # set certificate parameters
779 if [ $use_https -eq 1 ]; then
780 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
781 __PROG="$__PROG --insecure" # but not empty better to use "IGNORE"
782 elif [ -f "$cacert" ]; then
783 __PROG="$__PROG --cacert $cacert"
784 elif [ -d "$cacert" ]; then
785 __PROG="$__PROG --capath $cacert"
786 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
787 write_log 14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
788 fi
789 fi
790 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
791 # or check if libcurl compiled with proxy support
792 if [ -z "$proxy" ]; then
793 __PROG="$__PROG --noproxy '*'"
794 elif [ -z "$CURL_PROXY" ]; then
795 # if libcurl has no proxy support and proxy should be used then force ERROR
796 write_log 13 "cURL: libcurl compiled without Proxy support"
797 fi
798
799 __RUNPROG="$__PROG '$__URL'" # build final command
800 __PROG="cURL" # reuse for error logging
801
802 # uclient-fetch possibly with ssl support if /lib/libustream-ssl.so installed
803 elif [ -n "$UCLIENT_FETCH" ]; then
804 # UCLIENT_FETCH_SSL not empty then SSL support available
805 UCLIENT_FETCH_SSL=$(find /lib /usr/lib -name libustream-ssl.so* 2>/dev/null)
806 __PROG="$UCLIENT_FETCH -q -O $DATFILE"
807 # force network/ip not supported
808 [ -n "$__BINDIP" ] && \
809 write_log 14 "uclient-fetch: FORCE binding to specific address not supported"
810 # force ip version to use
811 if [ $force_ipversion -eq 1 ]; then
812 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
813 fi
814 # https possibly not supported
815 [ $use_https -eq 1 -a -z "$UCLIENT_FETCH_SSL" ] && \
816 write_log 14 "uclient-fetch: no HTTPS support! Additional install one of ustream-ssl packages"
817 # proxy support
818 [ -z "$proxy" ] && __PROG="$__PROG -Y off" || __PROG="$__PROG -Y on"
819 # https & certificates
820 if [ $use_https -eq 1 ]; then
821 if [ "$cacert" = "IGNORE" ]; then
822 __PROG="$__PROG --no-check-certificate"
823 elif [ -f "$cacert" ]; then
824 __PROG="$__PROG --ca-certificate=$cacert"
825 elif [ -n "$cacert" ]; then # it's not a file; nothing else supported
826 write_log 14 "No valid certificate file '$cacert' for HTTPS communication"
827 fi
828 fi
829 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
830 __PROG="uclient-fetch" # reuse for error logging
831
832 # Busybox Wget or any other wget in search $PATH (did not support neither IPv6 nor HTTPS)
833 elif [ -n "$WGET" ]; then
834 __PROG="$WGET -q -O $DATFILE"
835 # force network/ip not supported
836 [ -n "$__BINDIP" ] && \
837 write_log 14 "BusyBox Wget: FORCE binding to specific address not supported"
838 # force ip version not supported
839 [ $force_ipversion -eq 1 ] && \
840 write_log 14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
841 # https not supported
842 [ $use_https -eq 1 ] && \
843 write_log 14 "BusyBox Wget: no HTTPS support"
844 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
845 [ -z "$proxy" ] && __PROG="$__PROG -Y off"
846
847 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
848 __PROG="Busybox Wget" # reuse for error logging
849
850 else
851 write_log 13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
852 fi
853
854 while : ; do
855 write_log 7 "#> $__RUNPROG"
856 eval $__RUNPROG # DO transfer
857 __ERR=$? # save error code
858 [ $__ERR -eq 0 ] && return 0 # no error leave
859 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
860
861 write_log 3 "$__PROG Error: '$__ERR'"
862 write_log 7 "$(cat $ERRFILE)" # report error
863
864 [ $VERBOSE -gt 1 ] && {
865 # VERBOSE > 1 then NO retry
866 write_log 4 "Transfer failed - Verbose Mode: $VERBOSE - NO retry on error"
867 return 1
868 }
869
870 __CNT=$(( $__CNT + 1 )) # increment error counter
871 # if error count > retry_max_count leave here
872 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
873 write_log 14 "Transfer failed after $retry_max_count retries"
874
875 write_log 4 "Transfer failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
876 sleep $RETRY_SECONDS &
877 PID_SLEEP=$!
878 wait $PID_SLEEP # enable trap-handler
879 PID_SLEEP=0
880 done
881 # we should never come here there must be a programming error
882 write_log 12 "Error in 'do_transfer()' - program coding error"
883 }
884
885 send_update() {
886 # $1 # IP to set at DDNS service provider
887 local __IP
888
889 [ $# -ne 1 ] && write_log 12 "Error calling 'send_update()' - wrong number of parameters"
890
891 if [ $upd_privateip -eq 0 ]; then
892 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
893 [ $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)")
894 [ $use_ipv6 -eq 1 ] && __IP=$(echo $1 | grep "^[0-9a-eA-E]")
895 else
896 __IP=$(echo $1 | grep -m 1 -o "$IPV4_REGEX") # valid IPv4 or
897 [ -z "$__IP" ] && __IP=$(echo $1 | grep -m 1 -o "$IPV6_REGEX") # IPv6
898 fi
899 [ -z "$__IP" ] && {
900 write_log 3 "No or private or invalid IP '$1' given! Please check your configuration"
901 return 127
902 }
903
904 if [ -n "$update_script" ]; then
905 write_log 7 "parsing script '$update_script'"
906 . $update_script
907 else
908 local __URL __ERR
909
910 # do replaces in URL
911 __URL=$(echo $update_url | sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
912 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
913 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
914 [ $use_https -ne 0 ] && __URL=$(echo $__URL | sed -e 's#^http:#https:#')
915
916 do_transfer "$__URL" || return 1
917
918 write_log 7 "DDNS Provider answered:${N}$(cat $DATFILE)"
919
920 [ -z "$UPD_ANSWER" ] && return 0 # not set then ignore
921
922 grep -i -E "$UPD_ANSWER" $DATFILE >/dev/null 2>&1
923 return $? # "0" if found
924 fi
925 }
926
927 get_current_ip () {
928 # $1 Name of Variable to store current IP
929 local __CNT=0 # error counter
930 local __RUNPROG __DATA __URL __ERR
931
932 [ $# -ne 1 ] && write_log 12 "Error calling 'get_current_ip()' - wrong number of parameters"
933 write_log 7 "Detect current IP on '$ip_source'"
934
935 while : ; do
936 if [ -n "$ip_network" -a "$ip_source" = "network" ]; then
937 # set correct program
938 network_flush_cache # force re-read data from ubus
939 [ $use_ipv6 -eq 0 ] && __RUNPROG="network_get_ipaddr" \
940 || __RUNPROG="network_get_ipaddr6"
941 eval "$__RUNPROG __DATA $ip_network" || \
942 write_log 13 "Can not detect current IP using $__RUNPROG '$ip_network' - Error: '$?'"
943 [ -n "$__DATA" ] && write_log 7 "Current IP '$__DATA' detected on network '$ip_network'"
944 elif [ -n "$ip_interface" -a "$ip_source" = "interface" ]; then
945 local __DATA4=""; local __DATA6=""
946 if [ -n "$(command -v ip)" ]; then # ip program installed
947 write_log 7 "#> ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE"
948 ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE
949 __ERR=$?
950 if [ $__ERR -eq 0 ]; then
951 # DATFILE (sample)
952 # 10: l2tp-inet: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1456 qdisc fq_codel state UNKNOWN qlen 3\ link/ppp
953 # 10: l2tp-inet inet 95.30.176.51 peer 95.30.176.1/32 scope global l2tp-inet\ valid_lft forever preferred_lft forever
954 # 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
955 # 5: eth1 inet 172.27.10.128/24 brd 172.27.10.255 scope global eth1\ valid_lft forever preferred_lft forever
956 # 5: eth1 inet 172.55.55.155/24 brd 172.27.10.255 scope global eth1\ valid_lft 12345sec preferred_lft 12345sec
957 # 5: eth1 inet6 2002:b0c7:f326::806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
958 # 5: eth1 inet6 fd43:5368:6f6d:6500:806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
959 # 5: eth1 inet6 fd43:5368:6f6d:6500:a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
960 # 5: eth1 inet6 2002:b0c7:f326::a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
961
962 # remove remove remove replace replace
963 # link inet6 fxxx sec forever=>-1 / => ' ' to separate subnet from ip
964 sed "/link/d; /inet6 f/d; s/sec//g; s/forever/-1/g; s/\// /g" $DATFILE | \
965 awk '{ print $3" "$4" "$NF }' > $ERRFILE # temp reuse ERRFILE
966 # we only need inet? IP prefered time
967
968 local __TIME4=0; local __TIME6=0
969 local __TYP __ADR __TIME
970 while read __TYP __ADR __TIME; do
971 __TIME=${__TIME:-0} # supress shell errors on last (empty) line of DATFILE
972 # IPversion no "-1" record stored - now "-1" record or new time > oldtime
973 [ "$__TYP" = "inet6" -a $__TIME6 -ge 0 -a \( $__TIME -lt 0 -o $__TIME -gt $__TIME6 \) ] && {
974 __DATA6="$__ADR"
975 __TIME6="$__TIME"
976 }
977 [ "$__TYP" = "inet" -a $__TIME4 -ge 0 -a \( $__TIME -lt 0 -o $__TIME -gt $__TIME4 \) ] && {
978 __DATA4="$__ADR"
979 __TIME4="$__TIME"
980 }
981 done < $ERRFILE
982 else
983 write_log 3 "ip Error: '$__ERR'"
984 write_log 7 "$(cat $ERRFILE)" # report error
985 fi
986 else # use deprecated ifconfig
987 write_log 7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
988 ifconfig $ip_interface >$DATFILE 2>$ERRFILE
989 __ERR=$?
990 if [ $__ERR -eq 0 ]; then
991 __DATA4=$(awk '
992 /inet addr:/ { # Filter IPv4
993 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
994 $1=""; # remove inet
995 $3=""; # remove Bcast: ...
996 $4=""; # remove Mask: ...
997 FS=":"; # separator ":"
998 $0=$0; # reread to activate separator
999 $1=""; # remove addr
1000 FS=" "; # set back separator to default " "
1001 $0=$0; # reread to activate separator (remove whitespaces)
1002 print $1; # print IPv4 addr
1003 }' $DATFILE
1004 )
1005 __DATA6=$(awk '
1006 /inet6/ && /: [0-9a-eA-E]/ { # Filter IPv6 exclude fxxx
1007 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
1008 FS="/"; # separator "/"
1009 $0=$0; # reread to activate separator
1010 $2=""; # remove everything behind "/"
1011 FS=" "; # set back separator to default " "
1012 $0=$0; # reread to activate separator
1013 print $3; # print IPv6 addr
1014 }' $DATFILE
1015 )
1016 else
1017 write_log 3 "ifconfig Error: '$__ERR'"
1018 write_log 7 "$(cat $ERRFILE)" # report error
1019 fi
1020 fi
1021 [ $use_ipv6 -eq 0 ] && __DATA="$__DATA4" || __DATA="$__DATA6"
1022 [ -n "$__DATA" ] && write_log 7 "Current IP '$__DATA' detected on interface '$ip_interface'"
1023 elif [ -n "$ip_script" -a "$ip_source" = "script" ]; then
1024 write_log 7 "#> $ip_script >$DATFILE 2>$ERRFILE"
1025 eval $ip_script >$DATFILE 2>$ERRFILE
1026 __ERR=$?
1027 if [ $__ERR -eq 0 ]; then
1028 __DATA=$(cat $DATFILE)
1029 [ -n "$__DATA" ] && write_log 7 "Current IP '$__DATA' detected via script '$ip_script'"
1030 else
1031 write_log 3 "$ip_script Error: '$__ERR'"
1032 write_log 7 "$(cat $ERRFILE)" # report error
1033 fi
1034 elif [ -n "$ip_url" -a "$ip_source" = "web" ]; then
1035 do_transfer "$ip_url"
1036 # use correct regular expression
1037 [ $use_ipv6 -eq 0 ] \
1038 && __DATA=$(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
1039 || __DATA=$(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
1040 [ -n "$__DATA" ] && write_log 7 "Current IP '$__DATA' detected on web at '$ip_url'"
1041 else
1042 write_log 12 "Error in 'get_current_ip()' - unhandled ip_source '$ip_source'"
1043 fi
1044 # valid data found return here
1045 [ -n "$__DATA" ] && {
1046 eval "$1=\"$__DATA\""
1047 return 0
1048 }
1049
1050 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
1051
1052 write_log 7 "Data detected:"
1053 write_log 7 "$(cat $DATFILE)"
1054
1055 [ $VERBOSE -gt 1 ] && {
1056 # VERBOSE > 1 then NO retry
1057 write_log 4 "Get current IP via '$ip_source' failed - Verbose Mode: $VERBOSE - NO retry on error"
1058 return 1
1059 }
1060
1061 __CNT=$(( $__CNT + 1 )) # increment error counter
1062 # if error count > retry_max_count leave here
1063 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
1064 write_log 14 "Get current IP via '$ip_source' failed after $retry_max_count retries"
1065 write_log 4 "Get current IP via '$ip_source' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
1066 sleep $RETRY_SECONDS &
1067 PID_SLEEP=$!
1068 wait $PID_SLEEP # enable trap-handler
1069 PID_SLEEP=0
1070 done
1071 # we should never come here there must be a programming error
1072 write_log 12 "Error in 'get_current_ip()' - program coding error"
1073 }
1074
1075 get_registered_ip() {
1076 # $1 Name of Variable to store public IP (REGISTERED_IP)
1077 # $2 (optional) if set, do not retry on error
1078 local __CNT=0 # error counter
1079 local __ERR=255
1080 local __REGEX __PROG __RUNPROG __DATA __IP
1081 # return codes
1082 # 1 no IP detected
1083
1084 [ $# -lt 1 -o $# -gt 2 ] && write_log 12 "Error calling 'get_registered_ip()' - wrong number of parameters"
1085 [ $is_glue -eq 1 -a -z "$BIND_HOST" ] && write_log 14 "Lookup of glue records is only supported using BIND host"
1086 write_log 7 "Detect registered/public IP"
1087
1088 # set correct regular expression
1089 [ $use_ipv6 -eq 0 ] && __REGEX="$IPV4_REGEX" || __REGEX="$IPV6_REGEX"
1090
1091 if [ -n "$BIND_HOST" ]; then
1092 __PROG="$BIND_HOST"
1093 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -t A" || __PROG="$__PROG -t AAAA"
1094 if [ $force_ipversion -eq 1 ]; then # force IP version
1095 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1096 fi
1097 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
1098 [ $is_glue -eq 1 ] && __PROG="$__PROG -v" # use verbose output to get additional section
1099
1100 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1101 __PROG="BIND host"
1102 elif [ -n "$KNOT_HOST" ]; then
1103 __PROG="$KNOT_HOST"
1104 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -t A" || __PROG="$__PROG -t AAAA"
1105 if [ $force_ipversion -eq 1 ]; then # force IP version
1106 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1107 fi
1108 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
1109
1110 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1111 __PROG="Knot host"
1112 elif [ -n "$DRILL" ]; then
1113 __PROG="$DRILL -V0" # drill options name @server type
1114 if [ $force_ipversion -eq 1 ]; then # force IP version
1115 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1116 fi
1117 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -t" || __PROG="$__PROG -u" # force TCP
1118 __PROG="$__PROG $lookup_host"
1119 [ -n "$dns_server" ] && __PROG="$__PROG @$dns_server"
1120 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG A" || __PROG="$__PROG AAAA"
1121
1122 __RUNPROG="$__PROG >$DATFILE 2>$ERRFILE"
1123 __PROG="drill"
1124 elif [ -n "$HOSTIP" ]; then # hostip package installed
1125 __PROG="$HOSTIP"
1126 [ $force_dnstcp -ne 0 ] && \
1127 write_log 14 "hostip - no support for 'DNS over TCP'"
1128
1129 # is IP given as dns_server ?
1130 __IP=$(echo $dns_server | grep -m 1 -o "$IPV4_REGEX")
1131 [ -z "$__IP" ] && __IP=$(echo $dns_server | grep -m 1 -o "$IPV6_REGEX")
1132
1133 # we got NO ip for dns_server, so build command
1134 [ -z "$__IP" -a -n "$dns_server" ] && {
1135 __IP="\`$HOSTIP"
1136 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] && __IP="$__IP -6"
1137 __IP="$__IP $dns_server | grep -m 1 -o"
1138 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] \
1139 && __IP="$__IP '$IPV6_REGEX'" \
1140 || __IP="$__IP '$IPV4_REGEX'"
1141 __IP="$__IP \`"
1142 }
1143
1144 [ $use_ipv6 -eq 1 ] && __PROG="$__PROG -6"
1145 [ -n "$dns_server" ] && __PROG="$__PROG -r $__IP"
1146 __RUNPROG="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
1147 __PROG="hostip"
1148 elif [ -n "$NSLOOKUP" ]; then # last use BusyBox nslookup
1149 NSLOOKUP_MUSL=$($(command -v nslookup) localhost 2>&1 | grep -F "(null)") # not empty busybox compiled with musl
1150 [ $force_dnstcp -ne 0 ] && \
1151 write_log 14 "Busybox nslookup - no support for 'DNS over TCP'"
1152 [ -n "$NSLOOKUP_MUSL" -a -n "$dns_server" ] && \
1153 write_log 14 "Busybox compiled with musl - nslookup don't support the use of DNS Server"
1154 [ $force_ipversion -ne 0 ] && \
1155 write_log 5 "Busybox nslookup - no support to 'force IP Version' (ignored)"
1156
1157 __RUNPROG="$NSLOOKUP $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1158 __PROG="BusyBox nslookup"
1159 else # there must be an error
1160 write_log 12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
1161 fi
1162
1163 while : ; do
1164 write_log 7 "#> $__RUNPROG"
1165 eval $__RUNPROG
1166 __ERR=$?
1167 if [ $__ERR -ne 0 ]; then
1168 write_log 3 "$__PROG error: '$__ERR'"
1169 write_log 7 "$(cat $ERRFILE)"
1170 else
1171 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then
1172 if [ $is_glue -eq 1 ]; then
1173 __DATA=$(cat $DATFILE | grep "^$lookup_host" | grep -om1 "$__REGEX" )
1174 else
1175 __DATA=$(cat $DATFILE | awk -F "address " '/has/ {print $2; exit}' )
1176 fi
1177 elif [ -n "$DRILL" ]; then
1178 __DATA=$(cat $DATFILE | awk '/^'"$lookup_host"'/ {print $5; exit}' )
1179 elif [ -n "$HOSTIP" ]; then
1180 __DATA=$(cat $DATFILE | grep -om1 "$__REGEX")
1181 elif [ -n "$NSLOOKUP" ]; then
1182 __DATA=$(cat $DATFILE | sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
1183 fi
1184 [ -n "$__DATA" ] && {
1185 write_log 7 "Registered IP '$__DATA' detected"
1186 [ -z "$IPFILE" ] || echo "$__DATA" > $IPFILE
1187 eval "$1=\"$__DATA\"" # valid data found
1188 return 0 # leave here
1189 }
1190 write_log 4 "NO valid IP found"
1191 __ERR=127
1192 fi
1193 [ -z "$IPFILE" ] || echo "" > $IPFILE
1194
1195 [ -n "$LUCI_HELPER" ] && return $__ERR # no retry if called by LuCI helper script
1196 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
1197 [ $VERBOSE -gt 1 ] && {
1198 # VERBOSE > 1 then NO retry
1199 write_log 4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE - NO retry on error"
1200 return $__ERR
1201 }
1202
1203 __CNT=$(( $__CNT + 1 )) # increment error counter
1204 # if error count > retry_max_count leave here
1205 [ $retry_max_count -gt 0 -a $__CNT -gt $retry_max_count ] && \
1206 write_log 14 "Get registered/public IP for '$lookup_host' failed after $retry_max_count retries"
1207
1208 write_log 4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_max_count in $RETRY_SECONDS seconds"
1209 sleep $RETRY_SECONDS &
1210 PID_SLEEP=$!
1211 wait $PID_SLEEP # enable trap-handler
1212 PID_SLEEP=0
1213 done
1214 # we should never come here there must be a programming error
1215 write_log 12 "Error in 'get_registered_ip()' - program coding error"
1216 }
1217
1218 get_uptime() {
1219 # $1 Variable to store result in
1220 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
1221 local __UPTIME=$(cat /proc/uptime)
1222 eval "$1=\"${__UPTIME%%.*}\""
1223 }
1224
1225 trap_handler() {
1226 # $1 trap signal
1227 # $2 optional (exit status)
1228 local __PIDS __PID
1229 local __ERR=${2:-0}
1230 local __OLD_IFS=$IFS
1231 local __NEWLINE_IFS='
1232 ' # __NEWLINE_IFS
1233
1234 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev/null # kill pending sleep if exist
1235
1236 case $1 in
1237 0) if [ $__ERR -eq 0 ]; then
1238 write_log 5 "PID '$$' exit normal at $(eval $DATE_PROG)${N}"
1239 else
1240 write_log 4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)${N}"
1241 fi ;;
1242 1) write_log 6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1243 # reload config via starting the script again
1244 /usr/lib/ddns/dynamic_dns_updater.sh -v "0" -S "$__SECTIONID" -- start || true
1245 exit 0 ;; # and leave this one
1246 2) write_log 5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)${N}";;
1247 3) write_log 5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)${N}";;
1248 15) write_log 5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)${N}";;
1249 *) write_log 13 "Unhandled signal '$1' in 'trap_handler()'";;
1250 esac
1251
1252 __PIDS=$(pgrep -P $$) # get my childs (pgrep prints with "newline")
1253 IFS=$__NEWLINE_IFS
1254 for __PID in $__PIDS; do
1255 kill -$1 $__PID # terminate it
1256 done
1257 IFS=$__OLD_IFS
1258
1259 # remove out and err file
1260 [ -f $DATFILE ] && rm -f $DATFILE
1261 [ -f $ERRFILE ] && rm -f $ERRFILE
1262
1263 # exit with correct handling:
1264 # remove trap handling settings and send kill to myself
1265 trap - 0 1 2 3 15
1266 [ $1 -gt 0 ] && kill -$1 $$
1267 }
1268
1269 split_FQDN() {
1270 # $1 FQDN to split
1271 # $2 name of variable to store TLD
1272 # $3 name of variable to store (reg)Domain
1273 # $4 name of variable to store Host/Subdomain
1274
1275 [ $# -ne 4 ] && write_log 12 "Error calling 'split_FQDN()' - wrong number of parameters"
1276 [ -z "$1" ] && write_log 12 "Error calling 'split_FQDN()' - missing FQDN to split"
1277 [ -f $TLDFILE ] || write_log 12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1278
1279 local _HOST _FDOM _CTLD _FTLD
1280 local _SET="$@" # save given function parameters
1281
1282 local _PAR=$(echo "$1" | tr [A-Z] [a-z] | tr "." " ") # to lower and replace DOT with SPACE
1283 set -- $_PAR # set new as function parameters
1284 _PAR="" # clear variable for later reuse
1285 while [ -n "$1" ] ; do # as long we have parameters
1286 _PAR="$1 $_PAR" # invert order of parameters
1287 shift
1288 done
1289 set -- $_PAR # use new as function parameters
1290 _PAR="" # clear variable
1291
1292 while [ -n "$1" ] ; do # as long we have parameters
1293 if [ -z "$_CTLD" ]; then # first loop
1294 _CTLD="$1" # CURRENT TLD to look at
1295 shift
1296 else
1297 _CTLD="$1.$_CTLD" # Next TLD to look at
1298 shift
1299 fi
1300 # check if TLD exact match in tld_names.dat, save TLD
1301 zcat $TLDFILE | grep -E "^$_CTLD$" >/dev/null 2>&1 && {
1302 _FTLD="$_CTLD" # save found
1303 _FDOM="$1" # save domain next step might be invalid
1304 continue
1305 }
1306 # check if match any "*" in tld_names.dat,
1307 zcat $TLDFILE | grep -E "^\*.$_CTLD$" >/dev/null 2>&1 && {
1308 [ -z "$1" ] && break # no more data break
1309 # check if next level TLD match excludes "!" in tld_names.dat
1310 if zcat $TLDFILE | grep -E "^!$1.$_CTLD$" >/dev/null 2>&1 ; then
1311 _FTLD="$_CTLD" # Yes
1312 else
1313 _FTLD="$1.$_CTLD"
1314 shift
1315 fi
1316 _FDOM="$1"; shift
1317 }
1318 [ -n "$_FTLD" ] && break # we have something valid, break
1319 done
1320
1321 # the leftover parameters are the HOST/SUBDOMAIN
1322 while [ -n "$1" ]; do
1323 _HOST="$1 $_HOST" # remember we need to invert
1324 shift
1325 done
1326 _HOST=$(echo $_HOST | tr " " ".") # insert DOT
1327
1328 set -- $_SET # set back parameters from function call
1329 [ -n "$_FTLD" ] && {
1330 eval "$2=$_FTLD" # set TLD
1331 eval "$3=$_FDOM" # set registrable domain
1332 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1333 return 0
1334 }
1335 eval "$2=''" # clear TLD
1336 eval "$3=''" # clear registrable domain
1337 eval "$4=''" # clear HOST/SUBDOMAIN
1338 return 1
1339 }
1340
1341 expand_ipv6() {
1342 # Original written for bash by
1343 #.Author: Florian Streibelt <florian@f-streibelt.de>
1344 # Date: 08.04.2012
1345 # License: Public Domain, but please be fair and
1346 # attribute the original author(s) and provide
1347 # a link to the original source for corrections:
1348 #. https://github.com/mutax/IPv6-Address-checks
1349
1350 # $1 IPv6 to expand
1351 # $2 name of variable to store expanded IPv6
1352 [ $# -ne 2 ] && write_log 12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1353
1354 INPUT="$(echo "$1" | tr 'A-F' 'a-f')"
1355 [ "$INPUT" = "::" ] && INPUT="::0" # special case ::
1356
1357 O=""
1358
1359 while [ "$O" != "$INPUT" ]; do
1360 O="$INPUT"
1361
1362 # fill all words with zeroes
1363 INPUT=$( echo "$INPUT" | sed -e 's|:\([0-9a-f]\{3\}\):|:0\1:|g' \
1364 -e 's|:\([0-9a-f]\{3\}\)$|:0\1|g' \
1365 -e 's|^\([0-9a-f]\{3\}\):|0\1:|g' \
1366 -e 's|:\([0-9a-f]\{2\}\):|:00\1:|g' \
1367 -e 's|:\([0-9a-f]\{2\}\)$|:00\1|g' \
1368 -e 's|^\([0-9a-f]\{2\}\):|00\1:|g' \
1369 -e 's|:\([0-9a-f]\):|:000\1:|g' \
1370 -e 's|:\([0-9a-f]\)$|:000\1|g' \
1371 -e 's|^\([0-9a-f]\):|000\1:|g' )
1372
1373 done
1374
1375 # now expand the ::
1376 ZEROES=""
1377
1378 echo "$INPUT" | grep -qs "::"
1379 if [ "$?" -eq 0 ]; then
1380 GRPS="$( echo "$INPUT" | sed 's|[0-9a-f]||g' | wc -m )"
1381 GRPS=$(( GRPS-1 )) # remove carriage return
1382 MISSING=$(( 8-GRPS ))
1383 while [ $MISSING -gt 0 ]; do
1384 ZEROES="$ZEROES:0000"
1385 MISSING=$(( MISSING-1 ))
1386 done
1387
1388 # be careful where to place the :
1389 INPUT=$( echo "$INPUT" | sed -e 's|\(.\)::\(.\)|\1'$ZEROES':\2|g' \
1390 -e 's|\(.\)::$|\1'$ZEROES':0000|g' \
1391 -e 's|^::\(.\)|'$ZEROES':0000:\1|g;s|^:||g' )
1392 fi
1393
1394 # an expanded address has 39 chars + CR
1395 if [ $(echo $INPUT | wc -m) != 40 ]; then
1396 write_log 4 "Error in 'expand_ipv6()' - invalid IPv6 found: '$1' expanded: '$INPUT'"
1397 eval "$2='invalid'"
1398 return 1
1399 fi
1400
1401 # echo the fully expanded version of the address
1402 eval "$2=$INPUT"
1403 return 0
1404 }