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