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