cb345e846be538bbc6239d0f513e0f6b32c28784
[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 MYPROG=$(basename $0) # my program call name
32
33 LOGFILE="" # logfile - all files are set in dynamic_dns_updater.sh
34 PIDFILE="" # pid file
35 UPDFILE="" # store UPTIME of last update
36 DATFILE="" # save stdout data of WGet and other external programs called
37 ERRFILE="" # save stderr output of WGet and other external programs called
38 IPFILE="" # store registered IP for read by LuCI status
39 TLDFILE=/usr/share/public_suffix_list.dat.gz # TLD file used by split_FQDN
40
41 CHECK_SECONDS=0 # calculated seconds out of given
42 FORCE_SECONDS=0 # interval and unit
43 RETRY_SECONDS=0 # in configuration
44
45 LAST_TIME=0 # holds the uptime of last successful update
46 CURR_TIME=0 # holds the current uptime
47 NEXT_TIME=0 # calculated time for next FORCED update
48 EPOCH_TIME=0 # seconds since 1.1.1970 00:00:00
49
50 REGISTERED_IP="" # holds the IP read from DNS
51 LOCAL_IP="" # holds the local IP read from the box
52
53 URL_USER="" # url encoded $username from config file
54 URL_PASS="" # url encoded $password from config file
55 URL_PENC="" # url encoded $param_enc from config file
56
57 UPD_ANSWER="" # Answer given by service on success
58
59 ERR_LAST=0 # used to save $? return code of program and function calls
60 ERR_UPDATE=0 # error counter on different local and registered ip
61
62 PID_SLEEP=0 # ProcessID of current background "sleep"
63
64 # regular expression to detect IPv4 / IPv6
65 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
66 IPV4_REGEX="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
67 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
68 IPV6_REGEX="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
69
70 # characters that are dangerous to pass to a shell command line
71 SHELL_ESCAPE="[\"\'\`\$\!();><{}?|\[\]\*\\\\]"
72
73 # dns character set. "-" must be the last character
74 DNS_CHARSET="[@a-zA-Z0-9._-]"
75
76 # domains can have * for wildcard. "-" must be the last character
77 DNS_CHARSET_DOMAIN="[@a-zA-Z0-9._*-]"
78
79 # detect if called by ddns-lucihelper.sh script, disable retrys (empty variable == false)
80 LUCI_HELPER=$(printf %s "$MYPROG" | grep -i "luci")
81
82 # Name Server Lookup Programs
83 BIND_HOST=$(command -v host)
84 KNOT_HOST=$(command -v khost)
85 DRILL=$(command -v drill)
86 HOSTIP=$(command -v hostip)
87 NSLOOKUP=$(command -v nslookup)
88
89 # Transfer Programs
90 WGET=$(command -v wget)
91 $WGET -V 2>/dev/null | grep -F -q +https && WGET_SSL=$WGET
92
93 CURL=$(command -v curl)
94 # CURL_SSL not empty then SSL support available
95 CURL_SSL=$($CURL -V 2>/dev/null | grep -F "https")
96 # CURL_PROXY not empty then Proxy support available
97 CURL_PROXY=$(find /lib /usr/lib -name libcurl.so* -exec strings {} 2>/dev/null \; | grep -im1 "all_proxy")
98
99 UCLIENT_FETCH=$(command -v uclient-fetch)
100
101 # Global configuration settings
102 # allow NON-public IP's
103 upd_privateip=$(uci -q get ddns.global.upd_privateip) || upd_privateip=0
104
105 # directory to store run information to.
106 ddns_rundir=$(uci -q get ddns.global.ddns_rundir) || ddns_rundir="/var/run/ddns"
107 [ -d $ddns_rundir ] || mkdir -p -m755 $ddns_rundir
108
109 # directory to store log files
110 ddns_logdir=$(uci -q get ddns.global.ddns_logdir) || ddns_logdir="/var/log/ddns"
111 [ -d $ddns_logdir ] || mkdir -p -m755 $ddns_logdir
112
113 # number of lines to before rotate logfile
114 ddns_loglines=$(uci -q get ddns.global.ddns_loglines) || ddns_loglines=250
115 ddns_loglines=$((ddns_loglines + 1)) # correct sed handling
116
117 # format to show date information in log and luci-app-ddns default ISO 8601 format
118 ddns_dateformat=$(uci -q get ddns.global.ddns_dateformat) || ddns_dateformat="%F %R"
119 DATE_PROG="date +'$ddns_dateformat'"
120
121 # USE_CURL if GNU Wget and cURL installed normally Wget is used by do_transfer()
122 # to change this use global option use_curl '1'
123 USE_CURL=$(uci -q get ddns.global.use_curl) || USE_CURL=0 # read config
124 [ -n "$CURL" ] || USE_CURL=0 # check for cURL
125
126 # loads all options for a given package and section
127 # also, sets all_option_variables to a list of the variable names
128 # $1 = ddns, $2 = SECTION_ID
129 load_all_config_options()
130 {
131 local __PKGNAME="$1"
132 local __SECTIONID="$2"
133 local __VAR
134 local __ALL_OPTION_VARIABLES=""
135
136 # this callback loads all the variables in the __SECTIONID section when we do
137 # config_load. We need to redefine the option_cb for different sections
138 # so that the active one isn't still active after we're done with it. For reference
139 # the $1 variable is the name of the option and $2 is the name of the section
140 config_cb()
141 {
142 if [ ."$2" = ."$__SECTIONID" ]; then
143 option_cb()
144 {
145 __ALL_OPTION_VARIABLES="$__ALL_OPTION_VARIABLES $1"
146 }
147 else
148 option_cb() { return 0; }
149 fi
150 }
151
152 config_load "$__PKGNAME"
153
154 # Given SECTION_ID not found so no data, so return 1
155 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
156
157 for __VAR in $__ALL_OPTION_VARIABLES
158 do
159 config_get "$__VAR" "$__SECTIONID" "$__VAR"
160 done
161 return 0
162 }
163
164 # read's all service sections from ddns config
165 # $1 = Name of variable to store
166 load_all_service_sections() {
167 local __DATA=""
168 config_cb()
169 {
170 # only look for section type "service", ignore everything else
171 [ "$1" = "service" ] && __DATA="$__DATA $2"
172 }
173 config_load "ddns"
174
175 eval "$1=\"$__DATA\""
176 return
177 }
178
179 # starts updater script for all given sections or only for the one given
180 # $1 = interface (Optional: when given only scripts are started
181 # configured for that interface)
182 # used by /etc/hotplug.d/iface/95-ddns on IFUP
183 # and by /etc/init.d/ddns start
184 start_daemon_for_all_ddns_sections()
185 {
186 local __EVENTIF="$1"
187 local __SECTIONS=""
188 local __SECTIONID=""
189 local __IFACE=""
190
191 load_all_service_sections __SECTIONS
192 for __SECTIONID in $__SECTIONS; do
193 config_get __IFACE "$__SECTIONID" interface "wan"
194 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] || continue
195 if [ $VERBOSE -eq 0 ]; then # start in background
196 /usr/lib/ddns/dynamic_dns_updater.sh -v 0 -S "$__SECTIONID" -- start &
197 else
198 /usr/lib/ddns/dynamic_dns_updater.sh -v "$VERBOSE" -S "$__SECTIONID" -- start
199 fi
200 done
201 }
202
203 # stop sections process incl. childs (sleeps)
204 # $1 = section
205 stop_section_processes() {
206 local __PID=0
207 local __PIDFILE="$ddns_rundir/$1.pid"
208 [ $# -ne 1 ] && write_log 12 "Error calling 'stop_section_processes()' - wrong number of parameters"
209
210 [ -e "$__PIDFILE" ] && {
211 __PID=$(cat $__PIDFILE)
212 ps | grep "^[\t ]*$__PID" >/dev/null 2>&1 && kill $__PID || __PID=0 # terminate it
213 }
214 [ $__PID -eq 0 ] # report if process was running
215 }
216
217 # stop updater script for all defines sections or only for one given
218 # $1 = interface (optional)
219 # used by /etc/hotplug.d/iface/95-ddns on 'ifdown'
220 # and by /etc/init.d/ddns stop
221 # needed because we also need to kill "sleep" child processes
222 stop_daemon_for_all_ddns_sections() {
223 local __EVENTIF="$1"
224 local __SECTIONS=""
225 local __SECTIONID=""
226 local __IFACE=""
227
228 load_all_service_sections __SECTIONS
229 for __SECTIONID in $__SECTIONS; do
230 config_get __IFACE "$__SECTIONID" interface "wan"
231 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] || continue
232 stop_section_processes "$__SECTIONID"
233 done
234 }
235
236 # reports to console, logfile, syslog
237 # $1 loglevel 7 == Debug to 0 == EMERG
238 # value +10 will exit the scripts
239 # $2..n text to report
240 write_log() {
241 local __LEVEL __EXIT __CMD __MSG __MSE
242 local __TIME=$(date +%H%M%S)
243 [ $1 -ge 10 ] && {
244 __LEVEL=$(($1-10))
245 __EXIT=1
246 } || {
247 __LEVEL=$1
248 __EXIT=0
249 }
250 shift # remove loglevel
251 [ $__EXIT -eq 0 ] && __MSG="$*" || __MSG="$* - TERMINATE"
252 case $__LEVEL in # create log message and command depending on loglevel
253 0) __CMD="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
254 __MSG=" $__TIME EMERG : $__MSG" ;;
255 1) __CMD="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
256 __MSG=" $__TIME ALERT : $__MSG" ;;
257 2) __CMD="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
258 __MSG=" $__TIME CRIT : $__MSG" ;;
259 3) __CMD="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
260 __MSG=" $__TIME ERROR : $__MSG" ;;
261 4) __CMD="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
262 __MSG=" $__TIME WARN : $__MSG" ;;
263 5) __CMD="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
264 __MSG=" $__TIME note : $__MSG" ;;
265 6) __CMD="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
266 __MSG=" $__TIME info : $__MSG" ;;
267 7) __MSG=" $__TIME : $__MSG";;
268 *) return;;
269 esac
270
271 # verbose echo
272 [ $VERBOSE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
273 # write to logfile
274 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE -gt 1 ]; then
275 if [ -n "$password" ]; then
276 # url encode __MSG, password already done
277 urlencode __MSE "$__MSG"
278 # replace encoded password inside encoded message
279 # and url decode (newline was encoded as %00)
280 __MSG=$( echo -e "$__MSE" \
281 | sed -e "s/$URL_PASS/***PW***/g" \
282 | sed -e "s/+/ /g; s/%00/\n/g; s/%/\\\\x/g" | xargs -0 printf "%b" )
283 fi
284 printf "%s\n" "$__MSG" >> $LOGFILE
285 # VERBOSE > 1 then NO loop so NO truncate log to $ddns_loglines lines
286 [ $VERBOSE -gt 1 ] || sed -i -e :a -e '$q;N;'$ddns_loglines',$D;ba' $LOGFILE
287 fi
288 [ -n "$LUCI_HELPER" ] && return # nothing else todo when running LuCI helper script
289 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
290 __CMD=$(echo -e "$__CMD" | tr -d '\n' | tr '\t' ' ') # remove \n \t chars
291 [ $__EXIT -eq 1 ] && {
292 eval '$__CMD' # force syslog before exit
293 exit 1
294 }
295 [ $use_syslog -eq 0 ] && return
296 [ $((use_syslog + __LEVEL)) -le 7 ] && eval '$__CMD'
297
298 return
299 }
300
301 # replace all special chars to their %hex value
302 # used for USERNAME and PASSWORD in update_url
303 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
304 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
305 # "$"(Dollar) # because used as variable output
306 # tested with the following string stored via Luci Application as password / username
307 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
308 urlencode() {
309 # $1 Name of Variable to store encoded string to
310 # $2 string to encode
311 local __ENC
312
313 [ $# -ne 2 ] && write_log 12 "Error calling 'urlencode()' - wrong number of parameters"
314
315 __ENC="$(awk -v str="$2" 'BEGIN{ORS="";for(i=32;i<=127;i++)lookup[sprintf("%c",i)]=i
316 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}}')"
317
318 eval "$1=\"$__ENC\"" # transfer back to variable
319 return 0
320 }
321
322 # extract url or script for given DDNS Provider from
323 # $1 Name of the provider
324 # $2 Provider directory
325 # $3 Name of Variable to store url to
326 # $4 Name of Variable to store script to
327 # $5 Name of Variable to store service answer to
328 get_service_data() {
329 local provider="$1"
330 shift
331 local dir="$1"
332 shift
333
334 . /usr/share/libubox/jshn.sh
335 local name data url answer script
336
337 [ $# -ne 3 ] && write_log 12 "Error calling 'get_service_data()' - wrong number of parameters"
338
339 [ -f "${dir}/${provider}.json" ] || {
340 eval "$1=\"\""
341 eval "$2=\"\""
342 eval "$3=\"\""
343 return 1
344 }
345
346 json_load_file "${dir}/${provider}.json"
347 json_get_var name "name"
348 if [ "$use_ipv6" -eq "1" ]; then
349 json_select "ipv6"
350 else
351 json_select "ipv4"
352 fi
353 json_get_var data "url"
354 json_get_var answer "answer"
355 json_select ".."
356 json_cleanup
357
358 # check if URL or SCRIPT is given
359 url=$(echo "$data" | grep "^http")
360 [ -z "$url" ] && script="/usr/lib/ddns/${data}"
361
362 eval "$1=\"$url\""
363 eval "$2=\"$script\""
364 eval "$3=\"$answer\""
365 return 0
366 }
367
368 # Calculate seconds from interval and unit
369 # $1 Name of Variable to store result in
370 # $2 Number and
371 # $3 Unit of time interval
372 get_seconds() {
373 [ $# -ne 3 ] && write_log 12 "Error calling 'get_seconds()' - wrong number of parameters"
374 case "$3" in
375 "days" ) eval "$1=$(( $2 * 86400 ))";;
376 "hours" ) eval "$1=$(( $2 * 3600 ))";;
377 "minutes" ) eval "$1=$(( $2 * 60 ))";;
378 * ) eval "$1=$2";;
379 esac
380 return 0
381 }
382
383 timeout() {
384 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
385 # only did the following changes
386 # - commented out "#!/bin/bash" and usage section
387 # - replace exit by return for usage as function
388 # - some reformatting
389 #
390 # timeout [-SIG] time [--] command args...
391 #
392 # Run the given command until completion, but kill it if it runs too long.
393 # Specifically designed to exit immediately (no sleep interval) and clean up
394 # nicely without messages or leaving any extra processes when finished.
395 #
396 # Example use
397 # timeout 5 countdown
398 #
399 # Based on notes in my "Shell Script Hints", section "Command Timeout"
400 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
401 #
402 # This script uses a lot of tricks to terminate both the background command,
403 # the timeout script, and even the sleep process. It also includes trap
404 # commands to prevent sub-shells reporting expected "Termination Errors".
405 #
406 # It took years of occasional trials, errors and testing to get a pure bash
407 # timeout command working as well as this does.
408 #
409 #.Anthony Thyssen 6 April 2011
410 #
411 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
412 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
413 # PROGNAME=$(basename $PROGNAME) # base name of program
414
415 # output the script comments as docs
416 # Usage() {
417 # echo >&2 "$PROGNAME:" "$@"
418 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
419 # exit 10;
420 # }
421
422 SIG=-TERM
423
424 while [ $# -gt 0 ]; do
425 case "$1" in
426 --)
427 # forced end of user options
428 shift;
429 break ;;
430 # -\?|--help|--doc*)
431 # Usage ;;
432 [0-9]*)
433 TIMEOUT="$1" ;;
434 -*)
435 SIG="$1" ;;
436 *)
437 # unforced end of user options
438 break ;;
439 esac
440 shift # next option
441 done
442
443 # run main command in backgrounds and get its pid
444 "$@" &
445 command_pid=$!
446
447 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
448 sleep_pid=0
449 (
450 # cleanup sleep process
451 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
452 # sleep timeout period in background
453 sleep $TIMEOUT &
454 sleep_pid=$!
455 wait $sleep_pid
456 # Abort the command
457 kill $SIG $command_pid >/dev/null 2>&1
458 return 1
459 ) &
460 timeout_pid=$!
461
462 # Wait for main command to finished or be timed out
463 wait $command_pid
464 status=$?
465
466 # Clean up timeout sub-shell - if it is still running!
467 kill $timeout_pid 2>/dev/null
468 wait $timeout_pid 2>/dev/null
469
470 # Uncomment to check if a LONG sleep still running (no sleep should be)
471 # sleep 1
472 # echo "-----------"
473 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
474
475 return $status
476 }
477
478 # sanitize a variable
479 # $1 variable name
480 # $2 allowed shell pattern
481 # $3 disallowed shell pattern
482 sanitize_variable() {
483 local __VAR=$1
484 eval __VALUE=\$$__VAR
485 local __ALLOWED=$2
486 local __REJECT=$3
487
488 # removing all allowed should give empty string
489 if [ -n "$__ALLOWED" ]; then
490 [ -z "${__VALUE//$__ALLOWED}" ] || write_log 12 "sanitize on $__VAR found characters outside allowed subset"
491 fi
492
493 # removing rejected pattern should give the same string as the input
494 if [ -n "$__REJECT" ]; then
495 [ "$__VALUE" = "${__VALUE//$__REJECT}" ] || write_log 12 "sanitize on $__VAR found rejected characters"
496 fi
497 }
498
499 # verify given host and port is connectable
500 # $1 Host/IP to verify
501 # $2 Port to verify
502 verify_host_port() {
503 local __HOST=$1
504 local __PORT=$2
505 local __NC=$(command -v nc)
506 local __NCEXT=$($(command -v nc) --help 2>&1 | grep "\-w" 2>/dev/null) # busybox nc compiled with extensions
507 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
508 # return codes
509 # 1 system specific error
510 # 2 nslookup/host error
511 # 3 nc (netcat) error
512 # 4 unmatched IP version
513
514 [ $# -ne 2 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
515
516 # check if ip or FQDN was given
517 __IPV4=$(echo $__HOST | grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
518 __IPV6=$(echo $__HOST | grep -m 1 -o "$IPV6_REGEX")
519 # if FQDN given get IP address
520 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
521 if [ -n "$BIND_HOST" ]; then # use BIND host if installed
522 __PROG="BIND host"
523 __RUNPROG="$BIND_HOST $__HOST >$DATFILE 2>$ERRFILE"
524 elif [ -n "$KNOT_HOST" ]; then # use Knot host if installed
525 __PROG="Knot host"
526 __RUNPROG="$KNOT_HOST $__HOST >$DATFILE 2>$ERRFILE"
527 elif [ -n "$DRILL" ]; then # use drill if installed
528 __PROG="drill"
529 __RUNPROG="$DRILL -V0 $__HOST A >$DATFILE 2>$ERRFILE" # IPv4
530 __RUNPROG="$__RUNPROG; $DRILL -V0 $__HOST AAAA >>$DATFILE 2>>$ERRFILE" # IPv6
531 elif [ -n "$HOSTIP" ]; then # use hostip if installed
532 __PROG="hostip"
533 __RUNPROG="$HOSTIP $__HOST >$DATFILE 2>$ERRFILE" # IPv4
534 __RUNPROG="$__RUNPROG; $HOSTIP -6 $__HOST >>$DATFILE 2>>$ERRFILE" # IPv6
535 else # use BusyBox nslookup
536 __PROG="BusyBox nslookup"
537 __RUNPROG="$NSLOOKUP $__HOST >$DATFILE 2>$ERRFILE"
538 fi
539 write_log 7 "#> $__RUNPROG"
540 eval $__RUNPROG
541 __ERR=$?
542 # command error
543 [ $__ERR -gt 0 ] && {
544 write_log 3 "DNS Resolver Error - $__PROG Error '$__ERR'"
545 write_log 7 "$(cat $ERRFILE)"
546 return 2
547 }
548 # extract IP address
549 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then # use BIND host or Knot host if installed
550 __IPV4="$(awk -F "address " '/has address/ {print $2; exit}' "$DATFILE")"
551 __IPV6="$(awk -F "address " '/has IPv6/ {print $2; exit}' "$DATFILE")"
552 elif [ -n "$DRILL" ]; then # use drill if installed
553 __IPV4="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV4_REGEX")"
554 __IPV6="$(awk '/^'"$__HOST"'/ {print $5}' "$DATFILE" | grep -m 1 -o "$IPV6_REGEX")"
555 elif [ -n "$HOSTIP" ]; then # use hostip if installed
556 __IPV4="$(grep -m 1 -o "$IPV4_REGEX" "$DATFILE")"
557 __IPV6="$(grep -m 1 -o "$IPV6_REGEX" "$DATFILE")"
558 else # use BusyBox nslookup
559 __IPV4="$(sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }" "$DATFILE")"
560 __IPV6="$(sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }" "$DATFILE")"
561 fi
562 }
563
564 # check IP version if forced
565 if [ $force_ipversion -ne 0 ]; then
566 __ERR=0
567 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR=4
568 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR=6
569 [ $__ERR -gt 0 ] && {
570 [ -n "$LUCI_HELPER" ] && return 4
571 write_log 14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
572 }
573 fi
574
575 # verify nc command
576 # busybox nc compiled without -l option "NO OPT l!" -> critical error
577 $__NC --help 2>&1 | grep -i "NO OPT l!" >/dev/null 2>&1 && \
578 write_log 12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
579 # busybox nc compiled with extensions
580 $__NC --help 2>&1 | grep "\-w" >/dev/null 2>&1 && __NCEXT="TRUE"
581
582 # connectivity test
583 # run busybox nc to HOST PORT
584 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
585 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
586 # not worrying, if there is an IPv6 wan address
587 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
588 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP=$__IPV6 || __IP=$__IPV4
589
590 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
591 __RUNPROG="$__NC -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
592 write_log 7 "#> $__RUNPROG"
593 eval $__RUNPROG
594 __ERR=$?
595 [ $__ERR -eq 0 ] && return 0
596 write_log 3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
597 write_log 7 "$(cat $ERRFILE)"
598 return 3
599 else # nc compiled without extensions (no timeout support)
600 __RUNPROG="timeout 2 -- $__NC $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
601 write_log 7 "#> $__RUNPROG"
602 eval $__RUNPROG
603 __ERR=$?
604 [ $__ERR -eq 0 ] && return 0
605 write_log 3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
606 return 3
607 fi
608 }
609
610 # verify given DNS server if connectable
611 # $1 DNS server to verify
612 verify_dns() {
613 local __ERR=255 # last error buffer
614 local __CNT=0 # error counter
615
616 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_dns()' - wrong number of parameters"
617 write_log 7 "Verify DNS server '$1'"
618
619 while [ $__ERR -ne 0 ]; do
620 # DNS uses port 53
621 verify_host_port "$1" "53"
622 __ERR=$?
623 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
624 return $__ERR
625 elif [ $__ERR -ne 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
626 write_log 4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
627 return $__ERR
628 elif [ $__ERR -ne 0 ]; then
629 __CNT=$(( $__CNT + 1 )) # increment error counter
630 # if error count > retry_count leave here
631 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
632 write_log 14 "Verify DNS server '$1' failed after $retry_count retries"
633
634 write_log 4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
635 sleep $RETRY_SECONDS &
636 PID_SLEEP=$!
637 wait $PID_SLEEP # enable trap-handler
638 PID_SLEEP=0
639 fi
640 done
641 return 0
642 }
643
644 # analyze and verify given proxy string
645 # $1 Proxy-String to verify
646 verify_proxy() {
647 # complete entry user:password@host:port
648 # inside user and password NO '@' of ":" allowed
649 # host and port only host:port
650 # host only host ERROR unsupported
651 # IPv4 address instead of host 123.234.234.123
652 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
653 local __TMP __HOST __PORT
654 local __ERR=255 # last error buffer
655 local __CNT=0 # error counter
656
657 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_proxy()' - wrong number of parameters"
658 write_log 7 "Verify Proxy server 'http://$1'"
659
660 # try to split user:password "@" host:port
661 __TMP=$(echo $1 | awk -F "@" '{print $2}')
662 # no "@" found - only host:port is given
663 [ -z "$__TMP" ] && __TMP="$1"
664 # now lets check for IPv6 address
665 __HOST=$(echo $__TMP | grep -m 1 -o "$IPV6_REGEX")
666 # IPv6 host address found read port
667 if [ -n "$__HOST" ]; then
668 # IPv6 split at "]:"
669 __PORT=$(echo $__TMP | awk -F "]:" '{print $2}')
670 else
671 __HOST=$(echo $__TMP | awk -F ":" '{print $1}')
672 __PORT=$(echo $__TMP | awk -F ":" '{print $2}')
673 fi
674 # No Port detected - EXITING
675 [ -z "$__PORT" ] && {
676 [ -n "$LUCI_HELPER" ] && return 5
677 write_log 14 "Invalid Proxy server Error '5' - proxy port missing"
678 }
679
680 while [ $__ERR -gt 0 ]; do
681 verify_host_port "$__HOST" "$__PORT"
682 __ERR=$?
683 if [ -n "$LUCI_HELPER" ]; then # no retry if called by LuCI helper script
684 return $__ERR
685 elif [ $__ERR -gt 0 -a $VERBOSE -gt 1 ]; then # VERBOSE > 1 then NO retry
686 write_log 4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE - NO retry on error"
687 return $__ERR
688 elif [ $__ERR -gt 0 ]; then
689 __CNT=$(( $__CNT + 1 )) # increment error counter
690 # if error count > retry_count leave here
691 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
692 write_log 14 "Verify Proxy server '$1' failed after $retry_count retries"
693
694 write_log 4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
695 sleep $RETRY_SECONDS &
696 PID_SLEEP=$!
697 wait $PID_SLEEP # enable trap-handler
698 PID_SLEEP=0
699 fi
700 done
701 return 0
702 }
703
704 do_transfer() {
705 # $1 # URL to use
706 local __URL="$1"
707 local __ERR=0
708 local __CNT=0 # error counter
709 local __PROG __RUNPROG
710
711 [ $# -ne 1 ] && write_log 12 "Error in 'do_transfer()' - wrong number of parameters"
712
713 # Use ip_network as default for bind_network if not separately specified
714 [ -z "$bind_network" ] && [ "$ip_source" = "network" ] && [ "$ip_network" ] && bind_network="$ip_network"
715
716 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
717 if [ -n "$WGET_SSL" ] && [ $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
718 __PROG="$WGET --hsts-file=/tmp/.wget-hsts -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
719 # force network/ip to use for communication
720 if [ -n "$bind_network" ]; then
721 local __BINDIP
722 # set correct program to detect IP
723 [ $use_ipv6 -eq 0 ] && __RUNPROG="network_get_ipaddr" || __RUNPROG="network_get_ipaddr6"
724 eval "$__RUNPROG __BINDIP $bind_network" || \
725 write_log 13 "Can not detect local IP using '$__RUNPROG $bind_network' - Error: '$?'"
726 write_log 7 "Force communication via IP '$__BINDIP'"
727 __PROG="$__PROG --bind-address=$__BINDIP"
728 fi
729 # force ip version to use
730 if [ $force_ipversion -eq 1 ]; then
731 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
732 fi
733 # set certificate parameters
734 if [ $use_https -eq 1 ]; then
735 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
736 __PROG="$__PROG --no-check-certificate"
737 elif [ -f "$cacert" ]; then
738 __PROG="$__PROG --ca-certificate=${cacert}"
739 elif [ -d "$cacert" ]; then
740 __PROG="$__PROG --ca-directory=${cacert}"
741 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
742 write_log 14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
743 fi
744 fi
745 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
746 [ -z "$proxy" ] && __PROG="$__PROG --no-proxy"
747
748 # user agent string if provided
749 if [ -n "$user_agent" ]; then
750 # replace single and double quotes
751 user_agent=$(echo $user_agent | sed "s/'/ /g" | sed 's/"/ /g')
752 __PROG="$__PROG --user-agent='$user_agent'"
753 fi
754
755 __RUNPROG="$__PROG '$__URL'" # build final command
756 __PROG="GNU Wget" # reuse for error logging
757
758 # 2nd choice is cURL IPv4/IPv6/HTTPS
759 # libcurl might be compiled without Proxy or HTTPS Support
760 elif [ -n "$CURL" ]; then
761 __PROG="$CURL -RsS -o $DATFILE --stderr $ERRFILE"
762 # check HTTPS support
763 [ -z "$CURL_SSL" -a $use_https -eq 1 ] && \
764 write_log 13 "cURL: libcurl compiled without https support"
765 # force network/interface-device to use for communication
766 if [ -n "$bind_network" ]; then
767 local __DEVICE
768 network_get_device __DEVICE $bind_network || \
769 write_log 13 "Can not detect local device using 'network_get_device $bind_network' - Error: '$?'"
770 write_log 7 "Force communication via device '$__DEVICE'"
771 __PROG="$__PROG --interface $__DEVICE"
772 fi
773 # force ip version to use
774 if [ $force_ipversion -eq 1 ]; then
775 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
776 fi
777 # set certificate parameters
778 if [ $use_https -eq 1 ]; then
779 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
780 __PROG="$__PROG --insecure" # but not empty better to use "IGNORE"
781 elif [ -f "$cacert" ]; then
782 __PROG="$__PROG --cacert $cacert"
783 elif [ -d "$cacert" ]; then
784 __PROG="$__PROG --capath $cacert"
785 elif [ -n "$cacert" ]; then # it's not a file and not a directory but given
786 write_log 14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
787 fi
788 fi
789 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
790 # or check if libcurl compiled with proxy support
791 if [ -z "$proxy" ]; then
792 __PROG="$__PROG --noproxy '*'"
793 elif [ -z "$CURL_PROXY" ]; then
794 # if libcurl has no proxy support and proxy should be used then force ERROR
795 write_log 13 "cURL: libcurl compiled without Proxy support"
796 fi
797
798 __RUNPROG="$__PROG '$__URL'" # build final command
799 __PROG="cURL" # reuse for error logging
800
801 # uclient-fetch possibly with ssl support if /lib/libustream-ssl.so installed
802 elif [ -n "$UCLIENT_FETCH" ]; then
803 # UCLIENT_FETCH_SSL not empty then SSL support available
804 UCLIENT_FETCH_SSL=$(find /lib /usr/lib -name libustream-ssl.so* 2>/dev/null)
805 __PROG="$UCLIENT_FETCH -q -O $DATFILE"
806 # force network/ip not supported
807 [ -n "$__BINDIP" ] && \
808 write_log 14 "uclient-fetch: FORCE binding to specific address not supported"
809 # force ip version to use
810 if [ $force_ipversion -eq 1 ]; then
811 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6" # force IPv4/IPv6
812 fi
813 # https possibly not supported
814 [ $use_https -eq 1 -a -z "$UCLIENT_FETCH_SSL" ] && \
815 write_log 14 "uclient-fetch: no HTTPS support! Additional install one of ustream-ssl packages"
816 # proxy support
817 [ -z "$proxy" ] && __PROG="$__PROG -Y off" || __PROG="$__PROG -Y on"
818 # https & certificates
819 if [ $use_https -eq 1 ]; then
820 if [ "$cacert" = "IGNORE" ]; then
821 __PROG="$__PROG --no-check-certificate"
822 elif [ -f "$cacert" ]; then
823 __PROG="$__PROG --ca-certificate=$cacert"
824 elif [ -n "$cacert" ]; then # it's not a file; nothing else supported
825 write_log 14 "No valid certificate file '$cacert' for HTTPS communication"
826 fi
827 fi
828 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
829 __PROG="uclient-fetch" # reuse for error logging
830
831 # Busybox Wget or any other wget in search $PATH (did not support neither IPv6 nor HTTPS)
832 elif [ -n "$WGET" ]; then
833 __PROG="$WGET -q -O $DATFILE"
834 # force network/ip not supported
835 [ -n "$__BINDIP" ] && \
836 write_log 14 "BusyBox Wget: FORCE binding to specific address not supported"
837 # force ip version not supported
838 [ $force_ipversion -eq 1 ] && \
839 write_log 14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
840 # https not supported
841 [ $use_https -eq 1 ] && \
842 write_log 14 "BusyBox Wget: no HTTPS support"
843 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
844 [ -z "$proxy" ] && __PROG="$__PROG -Y off"
845
846 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
847 __PROG="Busybox Wget" # reuse for error logging
848
849 else
850 write_log 13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
851 fi
852
853 while : ; do
854 write_log 7 "#> $__RUNPROG"
855 eval $__RUNPROG # DO transfer
856 __ERR=$? # save error code
857 [ $__ERR -eq 0 ] && return 0 # no error leave
858 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
859
860 write_log 3 "$__PROG Error: '$__ERR'"
861 write_log 7 "$(cat $ERRFILE)" # report error
862
863 [ $VERBOSE -gt 1 ] && {
864 # VERBOSE > 1 then NO retry
865 write_log 4 "Transfer failed - Verbose Mode: $VERBOSE - NO retry on error"
866 return 1
867 }
868
869 __CNT=$(( $__CNT + 1 )) # increment error counter
870 # if error count > retry_count leave here
871 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
872 write_log 14 "Transfer failed after $retry_count retries"
873
874 write_log 4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
875 sleep $RETRY_SECONDS &
876 PID_SLEEP=$!
877 wait $PID_SLEEP # enable trap-handler
878 PID_SLEEP=0
879 done
880 # we should never come here there must be a programming error
881 write_log 12 "Error in 'do_transfer()' - program coding error"
882 }
883
884 send_update() {
885 # $1 # IP to set at DDNS service provider
886 local __IP
887
888 [ $# -ne 1 ] && write_log 12 "Error calling 'send_update()' - wrong number of parameters"
889
890 if [ $upd_privateip -eq 0 ]; then
891 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
892 [ $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)")
893 [ $use_ipv6 -eq 1 ] && __IP=$(echo $1 | grep "^[0-9a-eA-E]")
894 else
895 __IP=$(echo $1 | grep -m 1 -o "$IPV4_REGEX") # valid IPv4 or
896 [ -z "$__IP" ] && __IP=$(echo $1 | grep -m 1 -o "$IPV6_REGEX") # IPv6
897 fi
898 [ -z "$__IP" ] && {
899 write_log 3 "No or private or invalid IP '$1' given! Please check your configuration"
900 return 127
901 }
902
903 if [ -n "$update_script" ]; then
904 write_log 7 "parsing script '$update_script'"
905 . $update_script
906 else
907 local __URL __ERR
908
909 # do replaces in URL
910 __URL=$(echo $update_url | sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
911 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
912 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
913 [ $use_https -ne 0 ] && __URL=$(echo $__URL | sed -e 's#^http:#https:#')
914
915 do_transfer "$__URL" || return 1
916
917 write_log 7 "DDNS Provider answered:${N}$(cat $DATFILE)"
918
919 [ -z "$UPD_ANSWER" ] && return 0 # not set then ignore
920
921 grep -i -E "$UPD_ANSWER" $DATFILE >/dev/null 2>&1
922 return $? # "0" if found
923 fi
924 }
925
926 get_local_ip () {
927 # $1 Name of Variable to store local IP (LOCAL_IP)
928 local __CNT=0 # error counter
929 local __RUNPROG __DATA __URL __ERR
930
931 [ $# -ne 1 ] && write_log 12 "Error calling 'get_local_ip()' - wrong number of parameters"
932 write_log 7 "Detect local IP on '$ip_source'"
933
934 while : ; do
935 if [ -n "$ip_network" -a "$ip_source" = "network" ]; then
936 # set correct program
937 network_flush_cache # force re-read data from ubus
938 [ $use_ipv6 -eq 0 ] && __RUNPROG="network_get_ipaddr" \
939 || __RUNPROG="network_get_ipaddr6"
940 eval "$__RUNPROG __DATA $ip_network" || \
941 write_log 13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
942 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on network '$ip_network'"
943 elif [ -n "$ip_interface" -a "$ip_source" = "interface" ]; then
944 local __DATA4=""; local __DATA6=""
945 if [ -n "$(command -v ip)" ]; then # ip program installed
946 write_log 7 "#> ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE"
947 ip -o addr show dev $ip_interface scope global >$DATFILE 2>$ERRFILE
948 __ERR=$?
949 if [ $__ERR -eq 0 ]; then
950 # DATFILE (sample)
951 # 10: l2tp-inet: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1456 qdisc fq_codel state UNKNOWN qlen 3\ link/ppp
952 # 10: l2tp-inet inet 95.30.176.51 peer 95.30.176.1/32 scope global l2tp-inet\ valid_lft forever preferred_lft forever
953 # 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
954 # 5: eth1 inet 172.27.10.128/24 brd 172.27.10.255 scope global eth1\ valid_lft forever preferred_lft forever
955 # 5: eth1 inet 172.55.55.155/24 brd 172.27.10.255 scope global eth1\ valid_lft 12345sec preferred_lft 12345sec
956 # 5: eth1 inet6 2002:b0c7:f326::806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
957 # 5: eth1 inet6 fd43:5368:6f6d:6500:806b:c629:b8b9:433/128 scope global dynamic \ valid_lft 8026sec preferred_lft 8026sec
958 # 5: eth1 inet6 fd43:5368:6f6d:6500:a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
959 # 5: eth1 inet6 2002:b0c7:f326::a00:27ff:fed0:1032/64 scope global dynamic \ valid_lft 14352sec preferred_lft 14352sec
960
961 # remove remove remove replace replace
962 # link inet6 fxxx sec forever=>-1 / => ' ' to separate subnet from ip
963 sed "/link/d; /inet6 f/d; s/sec//g; s/forever/-1/g; s/\// /g" $DATFILE | \
964 awk '{ print $3" "$4" "$NF }' > $ERRFILE # temp reuse ERRFILE
965 # we only need inet? IP prefered time
966
967 local __TIME4=0; local __TIME6=0
968 local __TYP __ADR __TIME
969 while read __TYP __ADR __TIME; do
970 __TIME=${__TIME:-0} # supress shell errors on last (empty) line of DATFILE
971 # IPversion no "-1" record stored - now "-1" record or new time > oldtime
972 [ "$__TYP" = "inet6" -a $__TIME6 -ge 0 -a \( $__TIME -lt 0 -o $__TIME -gt $__TIME6 \) ] && {
973 __DATA6="$__ADR"
974 __TIME6="$__TIME"
975 }
976 [ "$__TYP" = "inet" -a $__TIME4 -ge 0 -a \( $__TIME -lt 0 -o $__TIME -gt $__TIME4 \) ] && {
977 __DATA4="$__ADR"
978 __TIME4="$__TIME"
979 }
980 done < $ERRFILE
981 else
982 write_log 3 "ip Error: '$__ERR'"
983 write_log 7 "$(cat $ERRFILE)" # report error
984 fi
985 else # use deprecated ifconfig
986 write_log 7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
987 ifconfig $ip_interface >$DATFILE 2>$ERRFILE
988 __ERR=$?
989 if [ $__ERR -eq 0 ]; then
990 __DATA4=$(awk '
991 /inet addr:/ { # Filter IPv4
992 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
993 $1=""; # remove inet
994 $3=""; # remove Bcast: ...
995 $4=""; # remove Mask: ...
996 FS=":"; # separator ":"
997 $0=$0; # reread to activate separator
998 $1=""; # remove addr
999 FS=" "; # set back separator to default " "
1000 $0=$0; # reread to activate separator (remove whitespaces)
1001 print $1; # print IPv4 addr
1002 }' $DATFILE
1003 )
1004 __DATA6=$(awk '
1005 /inet6/ && /: [0-9a-eA-E]/ { # Filter IPv6 exclude fxxx
1006 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
1007 FS="/"; # separator "/"
1008 $0=$0; # reread to activate separator
1009 $2=""; # remove everything behind "/"
1010 FS=" "; # set back separator to default " "
1011 $0=$0; # reread to activate separator
1012 print $3; # print IPv6 addr
1013 }' $DATFILE
1014 )
1015 else
1016 write_log 3 "ifconfig Error: '$__ERR'"
1017 write_log 7 "$(cat $ERRFILE)" # report error
1018 fi
1019 fi
1020 [ $use_ipv6 -eq 0 ] && __DATA="$__DATA4" || __DATA="$__DATA6"
1021 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on interface '$ip_interface'"
1022 elif [ -n "$ip_script" -a "$ip_source" = "script" ]; then
1023 write_log 7 "#> $ip_script >$DATFILE 2>$ERRFILE"
1024 eval $ip_script >$DATFILE 2>$ERRFILE
1025 __ERR=$?
1026 if [ $__ERR -eq 0 ]; then
1027 __DATA=$(cat $DATFILE)
1028 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected via script '$ip_script'"
1029 else
1030 write_log 3 "$ip_script Error: '$__ERR'"
1031 write_log 7 "$(cat $ERRFILE)" # report error
1032 fi
1033 elif [ -n "$ip_url" -a "$ip_source" = "web" ]; then
1034 do_transfer "$ip_url"
1035 # use correct regular expression
1036 [ $use_ipv6 -eq 0 ] \
1037 && __DATA=$(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
1038 || __DATA=$(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
1039 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on web at '$ip_url'"
1040 else
1041 write_log 12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
1042 fi
1043 # valid data found return here
1044 [ -n "$__DATA" ] && {
1045 eval "$1=\"$__DATA\""
1046 return 0
1047 }
1048
1049 [ -n "$LUCI_HELPER" ] && return 1 # no retry if called by LuCI helper script
1050
1051 write_log 7 "Data detected:"
1052 write_log 7 "$(cat $DATFILE)"
1053
1054 [ $VERBOSE -gt 1 ] && {
1055 # VERBOSE > 1 then NO retry
1056 write_log 4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE - NO retry on error"
1057 return 1
1058 }
1059
1060 __CNT=$(( $__CNT + 1 )) # increment error counter
1061 # if error count > retry_count leave here
1062 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
1063 write_log 14 "Get local IP via '$ip_source' failed after $retry_count retries"
1064 write_log 4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
1065 sleep $RETRY_SECONDS &
1066 PID_SLEEP=$!
1067 wait $PID_SLEEP # enable trap-handler
1068 PID_SLEEP=0
1069 done
1070 # we should never come here there must be a programming error
1071 write_log 12 "Error in 'get_local_ip()' - program coding error"
1072 }
1073
1074 get_registered_ip() {
1075 # $1 Name of Variable to store public IP (REGISTERED_IP)
1076 # $2 (optional) if set, do not retry on error
1077 local __CNT=0 # error counter
1078 local __ERR=255
1079 local __REGEX __PROG __RUNPROG __DATA __IP
1080 # return codes
1081 # 1 no IP detected
1082
1083 [ $# -lt 1 -o $# -gt 2 ] && write_log 12 "Error calling 'get_registered_ip()' - wrong number of parameters"
1084 [ $is_glue -eq 1 -a -z "$BIND_HOST" ] && write_log 14 "Lookup of glue records is only supported using BIND host"
1085 write_log 7 "Detect registered/public IP"
1086
1087 # set correct regular expression
1088 [ $use_ipv6 -eq 0 ] && __REGEX="$IPV4_REGEX" || __REGEX="$IPV6_REGEX"
1089
1090 if [ -n "$BIND_HOST" ]; then
1091 __PROG="$BIND_HOST"
1092 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -t A" || __PROG="$__PROG -t AAAA"
1093 if [ $force_ipversion -eq 1 ]; then # force IP version
1094 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1095 fi
1096 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
1097 [ $is_glue -eq 1 ] && __PROG="$__PROG -v" # use verbose output to get additional section
1098
1099 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1100 __PROG="BIND host"
1101 elif [ -n "$KNOT_HOST" ]; then
1102 __PROG="$KNOT_HOST"
1103 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -t A" || __PROG="$__PROG -t AAAA"
1104 if [ $force_ipversion -eq 1 ]; then # force IP version
1105 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1106 fi
1107 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
1108
1109 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1110 __PROG="Knot host"
1111 elif [ -n "$DRILL" ]; then
1112 __PROG="$DRILL -V0" # drill options name @server type
1113 if [ $force_ipversion -eq 1 ]; then # force IP version
1114 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
1115 fi
1116 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -t" || __PROG="$__PROG -u" # force TCP
1117 __PROG="$__PROG $lookup_host"
1118 [ -n "$dns_server" ] && __PROG="$__PROG @$dns_server"
1119 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG A" || __PROG="$__PROG AAAA"
1120
1121 __RUNPROG="$__PROG >$DATFILE 2>$ERRFILE"
1122 __PROG="drill"
1123 elif [ -n "$HOSTIP" ]; then # hostip package installed
1124 __PROG="$HOSTIP"
1125 [ $force_dnstcp -ne 0 ] && \
1126 write_log 14 "hostip - no support for 'DNS over TCP'"
1127
1128 # is IP given as dns_server ?
1129 __IP=$(echo $dns_server | grep -m 1 -o "$IPV4_REGEX")
1130 [ -z "$__IP" ] && __IP=$(echo $dns_server | grep -m 1 -o "$IPV6_REGEX")
1131
1132 # we got NO ip for dns_server, so build command
1133 [ -z "$__IP" -a -n "$dns_server" ] && {
1134 __IP="\`$HOSTIP"
1135 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] && __IP="$__IP -6"
1136 __IP="$__IP $dns_server | grep -m 1 -o"
1137 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] \
1138 && __IP="$__IP '$IPV6_REGEX'" \
1139 || __IP="$__IP '$IPV4_REGEX'"
1140 __IP="$__IP \`"
1141 }
1142
1143 [ $use_ipv6 -eq 1 ] && __PROG="$__PROG -6"
1144 [ -n "$dns_server" ] && __PROG="$__PROG -r $__IP"
1145 __RUNPROG="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
1146 __PROG="hostip"
1147 elif [ -n "$NSLOOKUP" ]; then # last use BusyBox nslookup
1148 NSLOOKUP_MUSL=$($(command -v nslookup) localhost 2>&1 | grep -F "(null)") # not empty busybox compiled with musl
1149 [ $force_dnstcp -ne 0 ] && \
1150 write_log 14 "Busybox nslookup - no support for 'DNS over TCP'"
1151 [ -n "$NSLOOKUP_MUSL" -a -n "$dns_server" ] && \
1152 write_log 14 "Busybox compiled with musl - nslookup don't support the use of DNS Server"
1153 [ $force_ipversion -ne 0 ] && \
1154 write_log 5 "Busybox nslookup - no support to 'force IP Version' (ignored)"
1155
1156 __RUNPROG="$NSLOOKUP $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1157 __PROG="BusyBox nslookup"
1158 else # there must be an error
1159 write_log 12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
1160 fi
1161
1162 while : ; do
1163 write_log 7 "#> $__RUNPROG"
1164 eval $__RUNPROG
1165 __ERR=$?
1166 if [ $__ERR -ne 0 ]; then
1167 write_log 3 "$__PROG error: '$__ERR'"
1168 write_log 7 "$(cat $ERRFILE)"
1169 else
1170 if [ -n "$BIND_HOST" -o -n "$KNOT_HOST" ]; then
1171 if [ $is_glue -eq 1 ]; then
1172 __DATA=$(cat $DATFILE | grep "^$lookup_host" | grep -om1 "$__REGEX" )
1173 else
1174 __DATA=$(cat $DATFILE | awk -F "address " '/has/ {print $2; exit}' )
1175 fi
1176 elif [ -n "$DRILL" ]; then
1177 __DATA=$(cat $DATFILE | awk '/^'"$lookup_host"'/ {print $5; exit}' )
1178 elif [ -n "$HOSTIP" ]; then
1179 __DATA=$(cat $DATFILE | grep -om1 "$__REGEX")
1180 elif [ -n "$NSLOOKUP" ]; then
1181 __DATA=$(cat $DATFILE | sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
1182 fi
1183 [ -n "$__DATA" ] && {
1184 write_log 7 "Registered IP '$__DATA' detected"
1185 [ -z "$IPFILE" ] || echo "$__DATA" > $IPFILE
1186 eval "$1=\"$__DATA\"" # valid data found
1187 return 0 # leave here
1188 }
1189 write_log 4 "NO valid IP found"
1190 __ERR=127
1191 fi
1192 [ -z "$IPFILE" ] || echo "" > $IPFILE
1193
1194 [ -n "$LUCI_HELPER" ] && return $__ERR # no retry if called by LuCI helper script
1195 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
1196 [ $VERBOSE -gt 1 ] && {
1197 # VERBOSE > 1 then NO retry
1198 write_log 4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE - NO retry on error"
1199 return $__ERR
1200 }
1201
1202 __CNT=$(( $__CNT + 1 )) # increment error counter
1203 # if error count > retry_count leave here
1204 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
1205 write_log 14 "Get registered/public IP for '$lookup_host' failed after $retry_count retries"
1206
1207 write_log 4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
1208 sleep $RETRY_SECONDS &
1209 PID_SLEEP=$!
1210 wait $PID_SLEEP # enable trap-handler
1211 PID_SLEEP=0
1212 done
1213 # we should never come here there must be a programming error
1214 write_log 12 "Error in 'get_registered_ip()' - program coding error"
1215 }
1216
1217 get_uptime() {
1218 # $1 Variable to store result in
1219 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
1220 local __UPTIME=$(cat /proc/uptime)
1221 eval "$1=\"${__UPTIME%%.*}\""
1222 }
1223
1224 trap_handler() {
1225 # $1 trap signal
1226 # $2 optional (exit status)
1227 local __PIDS __PID
1228 local __ERR=${2:-0}
1229 local __OLD_IFS=$IFS
1230 local __NEWLINE_IFS='
1231 ' # __NEWLINE_IFS
1232
1233 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev/null # kill pending sleep if exist
1234
1235 case $1 in
1236 0) if [ $__ERR -eq 0 ]; then
1237 write_log 5 "PID '$$' exit normal at $(eval $DATE_PROG)${N}"
1238 else
1239 write_log 4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)${N}"
1240 fi ;;
1241 1) write_log 6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1242 # reload config via starting the script again
1243 /usr/lib/ddns/dynamic_dns_updater.sh -v "0" -S "$__SECTIONID" -- start || true
1244 exit 0 ;; # and leave this one
1245 2) write_log 5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)${N}";;
1246 3) write_log 5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)${N}";;
1247 15) write_log 5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)${N}";;
1248 *) write_log 13 "Unhandled signal '$1' in 'trap_handler()'";;
1249 esac
1250
1251 __PIDS=$(pgrep -P $$) # get my childs (pgrep prints with "newline")
1252 IFS=$__NEWLINE_IFS
1253 for __PID in $__PIDS; do
1254 kill -$1 $__PID # terminate it
1255 done
1256 IFS=$__OLD_IFS
1257
1258 # remove out and err file
1259 [ -f $DATFILE ] && rm -f $DATFILE
1260 [ -f $ERRFILE ] && rm -f $ERRFILE
1261
1262 # exit with correct handling:
1263 # remove trap handling settings and send kill to myself
1264 trap - 0 1 2 3 15
1265 [ $1 -gt 0 ] && kill -$1 $$
1266 }
1267
1268 split_FQDN() {
1269 # $1 FQDN to split
1270 # $2 name of variable to store TLD
1271 # $3 name of variable to store (reg)Domain
1272 # $4 name of variable to store Host/Subdomain
1273
1274 [ $# -ne 4 ] && write_log 12 "Error calling 'split_FQDN()' - wrong number of parameters"
1275 [ -z "$1" ] && write_log 12 "Error calling 'split_FQDN()' - missing FQDN to split"
1276 [ -f $TLDFILE ] || write_log 12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1277
1278 local _HOST _FDOM _CTLD _FTLD
1279 local _SET="$@" # save given function parameters
1280
1281 local _PAR=$(echo "$1" | tr [A-Z] [a-z] | tr "." " ") # to lower and replace DOT with SPACE
1282 set -- $_PAR # set new as function parameters
1283 _PAR="" # clear variable for later reuse
1284 while [ -n "$1" ] ; do # as long we have parameters
1285 _PAR="$1 $_PAR" # invert order of parameters
1286 shift
1287 done
1288 set -- $_PAR # use new as function parameters
1289 _PAR="" # clear variable
1290
1291 while [ -n "$1" ] ; do # as long we have parameters
1292 if [ -z "$_CTLD" ]; then # first loop
1293 _CTLD="$1" # CURRENT TLD to look at
1294 shift
1295 else
1296 _CTLD="$1.$_CTLD" # Next TLD to look at
1297 shift
1298 fi
1299 # check if TLD exact match in tld_names.dat, save TLD
1300 zcat $TLDFILE | grep -E "^$_CTLD$" >/dev/null 2>&1 && {
1301 _FTLD="$_CTLD" # save found
1302 _FDOM="$1" # save domain next step might be invalid
1303 continue
1304 }
1305 # check if match any "*" in tld_names.dat,
1306 zcat $TLDFILE | grep -E "^\*.$_CTLD$" >/dev/null 2>&1 && {
1307 [ -z "$1" ] && break # no more data break
1308 # check if next level TLD match excludes "!" in tld_names.dat
1309 if zcat $TLDFILE | grep -E "^!$1.$_CTLD$" >/dev/null 2>&1 ; then
1310 _FTLD="$_CTLD" # Yes
1311 else
1312 _FTLD="$1.$_CTLD"
1313 shift
1314 fi
1315 _FDOM="$1"; shift
1316 }
1317 [ -n "$_FTLD" ] && break # we have something valid, break
1318 done
1319
1320 # the leftover parameters are the HOST/SUBDOMAIN
1321 while [ -n "$1" ]; do
1322 _HOST="$1 $_HOST" # remember we need to invert
1323 shift
1324 done
1325 _HOST=$(echo $_HOST | tr " " ".") # insert DOT
1326
1327 set -- $_SET # set back parameters from function call
1328 [ -n "$_FTLD" ] && {
1329 eval "$2=$_FTLD" # set TLD
1330 eval "$3=$_FDOM" # set registrable domain
1331 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1332 return 0
1333 }
1334 eval "$2=''" # clear TLD
1335 eval "$3=''" # clear registrable domain
1336 eval "$4=''" # clear HOST/SUBDOMAIN
1337 return 1
1338 }
1339
1340 expand_ipv6() {
1341 # Original written for bash by
1342 #.Author: Florian Streibelt <florian@f-streibelt.de>
1343 # Date: 08.04.2012
1344 # License: Public Domain, but please be fair and
1345 # attribute the original author(s) and provide
1346 # a link to the original source for corrections:
1347 #. https://github.com/mutax/IPv6-Address-checks
1348
1349 # $1 IPv6 to expand
1350 # $2 name of variable to store expanded IPv6
1351 [ $# -ne 2 ] && write_log 12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1352
1353 INPUT="$(echo "$1" | tr 'A-F' 'a-f')"
1354 [ "$INPUT" = "::" ] && INPUT="::0" # special case ::
1355
1356 O=""
1357
1358 while [ "$O" != "$INPUT" ]; do
1359 O="$INPUT"
1360
1361 # fill all words with zeroes
1362 INPUT=$( echo "$INPUT" | sed -e 's|:\([0-9a-f]\{3\}\):|:0\1:|g' \
1363 -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]\{2\}\):|:00\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]\):|:000\1:|g' \
1369 -e 's|:\([0-9a-f]\)$|:000\1|g' \
1370 -e 's|^\([0-9a-f]\):|000\1:|g' )
1371
1372 done
1373
1374 # now expand the ::
1375 ZEROES=""
1376
1377 echo "$INPUT" | grep -qs "::"
1378 if [ "$?" -eq 0 ]; then
1379 GRPS="$( echo "$INPUT" | sed 's|[0-9a-f]||g' | wc -m )"
1380 GRPS=$(( GRPS-1 )) # remove carriage return
1381 MISSING=$(( 8-GRPS ))
1382 while [ $MISSING -gt 0 ]; do
1383 ZEROES="$ZEROES:0000"
1384 MISSING=$(( MISSING-1 ))
1385 done
1386
1387 # be careful where to place the :
1388 INPUT=$( echo "$INPUT" | sed -e 's|\(.\)::\(.\)|\1'$ZEROES':\2|g' \
1389 -e 's|\(.\)::$|\1'$ZEROES':0000|g' \
1390 -e 's|^::\(.\)|'$ZEROES':0000:\1|g;s|^:||g' )
1391 fi
1392
1393 # an expanded address has 39 chars + CR
1394 if [ $(echo $INPUT | wc -m) != 40 ]; then
1395 write_log 4 "Error in 'expand_ipv6()' - invalid IPv6 found: '$1' expanded: '$INPUT'"
1396 eval "$2='invalid'"
1397 return 1
1398 fi
1399
1400 # echo the fully expanded version of the address
1401 eval "$2=$INPUT"
1402 return 0
1403 }