ca605dfbe1d0823daac3fb23d6344f1198253e63
[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 not supported
725 [ $force_ipversion -eq 1 ] && \
726 write_log 14 "uclient-fetch: Force connecting to IPv4 or IPv6 addresses not supported"
727 # https possibly not supported
728 [ $use_https -eq 1 -a ! -f /lib/libustream-ssl.so ] && \
729 write_log 14 "uclient-fetch: no HTTPS support! Additional install one of ustream-ssl packages"
730 # proxy support
731 [ -z "$proxy" ] && __PROG="$__PROG -Y off" || __PROG="$__PROG -Y on"
732 # https & certificates
733 if [ $use_https -eq 1 ]; then
734 if [ "$cacert" = "IGNORE" ]; then
735 __PROG="$__PROG --no-check-certificate"
736 elif [ -f "$cacert" ]; then
737 __PROG="$__PROG --ca-certificate=$cacert"
738 elif [ -n "$cacert" ]; then # it's not a file; nothing else supported
739 write_log 14 "No valid certificate file '$cacert' for HTTPS communication"
740 fi
741 fi
742 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
743 __PROG="uclient-fetch" # reuse for error logging
744
745 # Busybox Wget or any other wget in search $PATH (did not support neither IPv6 nor HTTPS)
746 elif [ -n "$(which wget)" ]; then
747 __PROG="$(which wget) -q -O $DATFILE"
748 # force network/ip not supported
749 [ -n "$__BINDIP" ] && \
750 write_log 14 "BusyBox Wget: FORCE binding to specific address not supported"
751 # force ip version not supported
752 [ $force_ipversion -eq 1 ] && \
753 write_log 14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
754 # https not supported
755 [ $use_https -eq 1 ] && \
756 write_log 14 "BusyBox Wget: no HTTPS support"
757 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
758 [ -z "$proxy" ] && __PROG="$__PROG -Y off"
759
760 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
761 __PROG="Busybox Wget" # reuse for error logging
762
763 else
764 write_log 13 "Neither 'Wget' nor 'cURL' nor 'uclient-fetch' installed or executable"
765 fi
766
767 while : ; do
768 write_log 7 "#> $__RUNPROG"
769 eval $__RUNPROG # DO transfer
770 __ERR=$? # save error code
771 [ $__ERR -eq 0 ] && return 0 # no error leave
772 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
773
774 write_log 3 "$__PROG Error: '$__ERR'"
775 write_log 7 "$(cat $ERRFILE)" # report error
776
777 [ $VERBOSE_MODE -gt 1 ] && {
778 # VERBOSE_MODE > 1 then NO retry
779 write_log 4 "Transfer failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
780 return 1
781 }
782
783 __CNT=$(( $__CNT + 1 )) # increment error counter
784 # if error count > retry_count leave here
785 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
786 write_log 14 "Transfer failed after $retry_count retries"
787
788 write_log 4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
789 sleep $RETRY_SECONDS &
790 PID_SLEEP=$!
791 wait $PID_SLEEP # enable trap-handler
792 PID_SLEEP=0
793 done
794 # we should never come here there must be a programming error
795 write_log 12 "Error in 'do_transfer()' - program coding error"
796 }
797
798 send_update() {
799 # $1 # IP to set at DDNS service provider
800 local __IP
801
802 [ $# -ne 1 ] && write_log 12 "Error calling 'send_update()' - wrong number of parameters"
803
804 if [ $ALLOW_LOCAL_IP -eq 0 ]; then
805 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
806 [ $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)")
807 [ $use_ipv6 -eq 1 ] && __IP=$(echo $1 | grep "^[0-9a-eA-E]")
808 [ -z "$__IP" ] && write_log 14 "Private or invalid or no IP '$1' given! Please check your configuration"
809 else
810 __IP="$1"
811 fi
812
813 if [ -n "$update_script" ]; then
814 write_log 7 "parsing script '$update_script'"
815 . $update_script
816 else
817 local __URL __ERR
818
819 # do replaces in URL
820 __URL=$(echo $update_url | sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
821 -e "s#\[PARAMENC\]#$URL_PENC#g" -e "s#\[PARAMOPT\]#$param_opt#g" \
822 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
823 [ $use_https -ne 0 ] && __URL=$(echo $__URL | sed -e 's#^http:#https:#')
824
825 do_transfer "$__URL" || return 1
826
827 write_log 7 "DDNS Provider answered:\n$(cat $DATFILE)"
828
829 [ -z "$SRV_ANSWER" ] && return 0 # not set then ignore
830
831 grep -i -E "$SRV_ANSWER" $DATFILE >/dev/null 2>&1
832 return $? # "0" if found
833 fi
834 }
835
836 get_local_ip () {
837 # $1 Name of Variable to store local IP (LOCAL_IP)
838 local __CNT=0 # error counter
839 local __RUNPROG __DATA __URL __ERR
840
841 [ $# -ne 1 ] && write_log 12 "Error calling 'get_local_ip()' - wrong number of parameters"
842 write_log 7 "Detect local IP on '$ip_source'"
843
844 while : ; do
845 case $ip_source in
846 network)
847 # set correct program
848 [ $use_ipv6 -eq 0 ] && __RUNPROG="network_get_ipaddr" \
849 || __RUNPROG="network_get_ipaddr6"
850 eval "$__RUNPROG __DATA $ip_network" || \
851 write_log 13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
852 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on network '$ip_network'"
853 ;;
854 interface)
855 write_log 7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
856 ifconfig $ip_interface >$DATFILE 2>$ERRFILE
857 __ERR=$?
858 if [ $__ERR -eq 0 ]; then
859 if [ $use_ipv6 -eq 0 ]; then
860 __DATA=$(awk '
861 /inet addr:/ { # Filter IPv4
862 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
863 $1=""; # remove inet
864 $3=""; # remove Bcast: ...
865 $4=""; # remove Mask: ...
866 FS=":"; # separator ":"
867 $0=$0; # reread to activate separator
868 $1=""; # remove addr
869 FS=" "; # set back separator to default " "
870 $0=$0; # reread to activate separator (remove whitespaces)
871 print $1; # print IPv4 addr
872 }' $DATFILE
873 )
874 else
875 __DATA=$(awk '
876 /inet6/ && /: [0-9a-eA-E]/ { # Filter IPv6 exclude fxxx
877 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
878 FS="/"; # separator "/"
879 $0=$0; # reread to activate separator
880 $2=""; # remove everything behind "/"
881 FS=" "; # set back separator to default " "
882 $0=$0; # reread to activate separator
883 print $3; # print IPv6 addr
884 }' $DATFILE
885 )
886 fi
887 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on interface '$ip_interface'"
888 else
889 write_log 3 "ifconfig Error: '$__ERR'"
890 write_log 7 "$(cat $ERRFILE)" # report error
891 fi
892 ;;
893 script)
894 write_log 7 "#> $ip_script >$DATFILE 2>$ERRFILE"
895 eval $ip_script >$DATFILE 2>$ERRFILE
896 __ERR=$?
897 if [ $__ERR -eq 0 ]; then
898 __DATA=$(cat $DATFILE)
899 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected via script '$ip_script'"
900 else
901 write_log 3 "$ip_script Error: '$__ERR'"
902 write_log 7 "$(cat $ERRFILE)" # report error
903 fi
904 ;;
905 web)
906 do_transfer "$ip_url"
907 # use correct regular expression
908 [ $use_ipv6 -eq 0 ] \
909 && __DATA=$(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
910 || __DATA=$(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
911 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on web at '$ip_url'"
912 ;;
913 *)
914 write_log 12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
915 ;;
916 esac
917 # valid data found return here
918 [ -n "$__DATA" ] && {
919 eval "$1=\"$__DATA\""
920 return 0
921 }
922
923 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
924
925 write_log 7 "Data detected:\n$(cat $DATFILE)"
926
927 [ $VERBOSE_MODE -gt 1 ] && {
928 # VERBOSE_MODE > 1 then NO retry
929 write_log 4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
930 return 1
931 }
932
933 __CNT=$(( $__CNT + 1 )) # increment error counter
934 # if error count > retry_count leave here
935 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
936 write_log 14 "Get local IP via '$ip_source' failed after $retry_count retries"
937 write_log 4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
938 sleep $RETRY_SECONDS &
939 PID_SLEEP=$!
940 wait $PID_SLEEP # enable trap-handler
941 PID_SLEEP=0
942 done
943 # we should never come here there must be a programming error
944 write_log 12 "Error in 'get_local_ip()' - program coding error"
945 }
946
947 get_registered_ip() {
948 # $1 Name of Variable to store public IP (REGISTERED_IP)
949 # $2 (optional) if set, do not retry on error
950 local __CNT=0 # error counter
951 local __ERR=255
952 local __REGEX __PROG __RUNPROG __DATA __IP
953 local __MUSL=$(nslookup localhost 2>&1 | grep -qF "(null)"; echo $?) # 0 == busybox compiled with musl "(null)" found
954 # return codes
955 # 1 no IP detected
956
957 [ $# -lt 1 -o $# -gt 2 ] && write_log 12 "Error calling 'get_registered_ip()' - wrong number of parameters"
958 write_log 7 "Detect registered/public IP"
959
960 # set correct regular expression
961 [ $use_ipv6 -eq 0 ] && __REGEX="$IPV4_REGEX" || __REGEX="$IPV6_REGEX"
962
963 if [ -n "$(which host)" ]; then
964 __PROG="$(which host)"
965 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -t A" || __PROG="$__PROG -t AAAA"
966 if [ $force_ipversion -eq 1 ]; then # force IP version
967 [ $use_ipv6 -eq 0 ] && __PROG="$__PROG -4" || __PROG="$__PROG -6"
968 fi
969 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
970
971 __RUNPROG="$__PROG $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
972 __PROG="BIND host"
973 elif [ -n "$(which hostip)" ]; then # hostip package installed
974 __PROG="$(which hostip)"
975 [ $force_dnstcp -ne 0 ] && \
976 write_log 14 "hostip - no support for 'DNS over TCP'"
977
978 # is IP given as dns_server ?
979 __IP=$(echo $dns_server | grep -m 1 -o "$IPV4_REGEX")
980 [ -z "$__IP" ] && __IP=$(echo $dns_server | grep -m 1 -o "$IPV6_REGEX")
981
982 # we got NO ip for dns_server, so build command
983 [ -z "$__IP" -a -n "$dns_server" ] && {
984 __IP="\`/usr/bin/hostip"
985 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] && __IP="$__IP -6"
986 __IP="$__IP $dns_server | grep -m 1 -o"
987 [ $use_ipv6 -eq 1 -a $force_ipversion -eq 1 ] \
988 && __IP="$__IP '$IPV6_REGEX'" \
989 || __IP="$__IP '$IPV4_REGEX'"
990 __IP="$__IP \`"
991 }
992
993 [ $use_ipv6 -eq 1 ] && __PROG="$__PROG -6"
994 [ -n "$dns_server" ] && __PROG="$__PROG -r $__IP"
995 __RUNPROG="$__PROG $lookup_host >$DATFILE 2>$ERRFILE"
996 __PROG="hostip"
997 elif [ -n "$(which nslookup)" ]; then # last use BusyBox nslookup
998 [ $force_ipversion -ne 0 -o $force_dnstcp -ne 0 ] && \
999 write_log 14 "Busybox nslookup - no support to 'force IP Version' or 'DNS over TCP'"
1000 [ $__MUSL -eq 0 -a -n "$dns_server" ] && \
1001 write_log 14 "Busybox compiled with musl - nslookup - no support to set/use DNS Server"
1002
1003 __RUNPROG="$(which nslookup) $lookup_host $dns_server >$DATFILE 2>$ERRFILE"
1004 __PROG="BusyBox nslookup"
1005 else # there must be an error
1006 write_log 12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
1007 fi
1008
1009 while : ; do
1010 write_log 7 "#> $__RUNPROG"
1011 eval $__RUNPROG
1012 __ERR=$?
1013 if [ $__ERR -ne 0 ]; then
1014 write_log 3 "$__PROG error: '$__ERR'"
1015 write_log 7 "$(cat $ERRFILE)"
1016 else
1017 if [ "$__PROG" = "BIND host" ]; then
1018 __DATA=$(cat $DATFILE | awk -F "address " '/has/ {print $2; exit}' )
1019 elif [ "$__PROG" = "hostip" ]; then
1020 __DATA=$(cat $DATFILE | grep -m 1 -o "$__REGEX")
1021 else
1022 __DATA=$(cat $DATFILE | sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
1023 fi
1024 [ -n "$__DATA" ] && {
1025 write_log 7 "Registered IP '$__DATA' detected"
1026 eval "$1=\"$__DATA\"" # valid data found
1027 return 0 # leave here
1028 }
1029 write_log 4 "NO valid IP found"
1030 __ERR=127
1031 fi
1032
1033 [ $LUCI_HELPER ] && return $__ERR # no retry if called by LuCI helper script
1034 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
1035 [ $VERBOSE_MODE -gt 1 ] && {
1036 # VERBOSE_MODE > 1 then NO retry
1037 write_log 4 "Get registered/public IP for '$lookup_host' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
1038 return $__ERR
1039 }
1040
1041 __CNT=$(( $__CNT + 1 )) # increment error counter
1042 # if error count > retry_count leave here
1043 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
1044 write_log 14 "Get registered/public IP for '$lookup_host' failed after $retry_count retries"
1045
1046 write_log 4 "Get registered/public IP for '$lookup_host' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
1047 sleep $RETRY_SECONDS &
1048 PID_SLEEP=$!
1049 wait $PID_SLEEP # enable trap-handler
1050 PID_SLEEP=0
1051 done
1052 # we should never come here there must be a programming error
1053 write_log 12 "Error in 'get_registered_ip()' - program coding error"
1054 }
1055
1056 get_uptime() {
1057 # $1 Variable to store result in
1058 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
1059 local __UPTIME=$(cat /proc/uptime)
1060 eval "$1=\"${__UPTIME%%.*}\""
1061 }
1062
1063 trap_handler() {
1064 # $1 trap signal
1065 # $2 optional (exit status)
1066 local __PIDS __PID
1067 local __ERR=${2:-0}
1068 local __OLD_IFS=$IFS
1069 local __NEWLINE_IFS='
1070 ' # __NEWLINE_IFS
1071
1072 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev/null # kill pending sleep if exist
1073
1074 case $1 in
1075 0) if [ $__ERR -eq 0 ]; then
1076 write_log 5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
1077 else
1078 write_log 4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1079 fi ;;
1080 1) write_log 6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1081 # reload config via starting the script again
1082 eval "/usr/lib/ddns/dynamic_dns_updater.sh $SECTION_ID $VERBOSE_MODE &"
1083 exit 0 ;; # and leave this one
1084 2) write_log 5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)\n";;
1085 3) write_log 5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)\n";;
1086 15) write_log 5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)\n";;
1087 *) write_log 13 "Unhandled signal '$1' in 'trap_handler()'";;
1088 esac
1089
1090 __PIDS=$(pgrep -P $$) # get my childs (pgrep prints with "newline")
1091 IFS=$__NEWLINE_IFS
1092 for __PID in $__PIDS; do
1093 kill -$1 $__PID # terminate it
1094 done
1095 IFS=$__OLD_IFS
1096
1097 # remove out and err file
1098 [ -f $DATFILE ] && rm -f $DATFILE
1099 [ -f $ERRFILE ] && rm -f $ERRFILE
1100
1101 # exit with correct handling:
1102 # remove trap handling settings and send kill to myself
1103 trap - 0 1 2 3 15
1104 [ $1 -gt 0 ] && kill -$1 $$
1105 }
1106
1107 split_FQDN() {
1108 # $1 FQDN to split
1109 # $2 name of variable to store TLD
1110 # $3 name of variable to store (reg)Domain
1111 # $4 name of variable to store Host/Subdomain
1112
1113 [ $# -ne 4 ] && write_log 12 "Error calling 'split_FQDN()' - wrong number of parameters"
1114 [ -z "$1" ] && write_log 12 "Error calling 'split_FQDN()' - missing FQDN to split"
1115 [ -f $TLDFILE ] || write_log 12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1116
1117 local _HOST _FDOM _CTLD _FTLD
1118 local _SET="$@" # save given function parameters
1119
1120 local _PAR=$(echo "$1" | tr [A-Z] [a-z] | tr "." " ") # to lower and replace DOT with SPACE
1121 set -- $_PAR # set new as function parameters
1122 _PAR="" # clear variable for later reuse
1123 while [ -n "$1" ] ; do # as long we have parameters
1124 _PAR="$1 $_PAR" # invert order of parameters
1125 shift
1126 done
1127 set -- $_PAR # use new as function parameters
1128 _PAR="" # clear variable
1129
1130 while [ -n "$1" ] ; do # as long we have parameters
1131 if [ -z "$_CTLD" ]; then # first loop
1132 _CTLD="$1" # CURRENT TLD to look at
1133 shift
1134 else
1135 _CTLD="$1.$_CTLD" # Next TLD to look at
1136 shift
1137 fi
1138 # check if TLD exact match in tld_names.dat, save TLD
1139 zcat $TLDFILE | grep -E "^$_CTLD$" >/dev/null 2>&1 && {
1140 _FTLD="$_CTLD" # save found
1141 _FDOM="$1" # save domain next step might be invalid
1142 continue
1143 }
1144 # check if match any "*" in tld_names.dat,
1145 zcat $TLDFILE | grep -E "^\*.$_CTLD$" >/dev/null 2>&1 && {
1146 [ -z "$1" ] && break # no more data break
1147 # check if next level TLD match excludes "!" in tld_names.dat
1148 if zcat $TLDFILE | grep -E "^!$1.$_CTLD$" >/dev/null 2>&1 ; then
1149 _FTLD="$_CTLD" # Yes
1150 else
1151 _FTLD="$1.$_CTLD"
1152 shift
1153 fi
1154 _FDOM="$1"; shift
1155 }
1156 [ -n "$_FTLD" ] && break # we have something valid, break
1157 done
1158
1159 # the leftover parameters are the HOST/SUBDOMAIN
1160 while [ -n "$1" ]; do
1161 _HOST="$1 $_HOST" # remember we need to invert
1162 shift
1163 done
1164 _HOST=$(echo $_HOST | tr " " ".") # insert DOT
1165
1166 set -- $_SET # set back parameters from function call
1167 [ -n "$_FTLD" ] && {
1168 eval "$2=$_FTLD" # set TLD
1169 eval "$3=$_FDOM" # set registrable domain
1170 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1171 return 0
1172 }
1173 eval "$2=''" # clear TLD
1174 eval "$3=''" # clear registrable domain
1175 eval "$4=''" # clear HOST/SUBDOMAIN
1176 return 1
1177 }
1178
1179 expand_ipv6() {
1180 # Original written for bash by
1181 # Author: Florian Streibelt <florian@f-streibelt.de>
1182 # Date: 08.04.2012
1183 # License: Public Domain, but please be fair and
1184 # attribute the original author(s) and provide
1185 # a link to the original source for corrections:
1186 #. https://github.com/mutax/IPv6-Address-checks
1187
1188 # $1 IPv6 t0 expand
1189 # $2 name of variable to store expanded IPv6
1190 [ $# -ne 2 ] && write_log 12 "Error calling 'expand_ipv6()' - wrong number of parameters"
1191
1192 INPUT="$(echo "$1" | tr 'A-F' 'a-f')"
1193 [ "$INPUT" = "::" ] && INPUT="::0" # special case ::
1194
1195 O=""
1196
1197 while [ "$O" != "$INPUT" ]; do
1198 O="$INPUT"
1199
1200 # fill all words with zeroes
1201 INPUT=$( echo "$INPUT" | sed -e 's|:\([0-9a-f]\{3\}\):|:0\1:|g' \
1202 -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]\{2\}\):|:00\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]\):|:000\1:|g' \
1208 -e 's|:\([0-9a-f]\)$|:000\1|g' \
1209 -e 's|^\([0-9a-f]\):|000\1:|g' )
1210
1211 done
1212
1213 # now expand the ::
1214 ZEROES=""
1215
1216 echo "$INPUT" | grep -qs "::"
1217 if [ "$?" -eq 0 ]; then
1218 GRPS="$( echo "$INPUT" | sed 's|[0-9a-f]||g' | wc -m )"
1219 GRPS=$(( GRPS-1 )) # remove carriage return
1220 MISSING=$(( 8-GRPS ))
1221 while [ $MISSING -gt 0 ]; do
1222 ZEROES="$ZEROES:0000"
1223 MISSING=$(( MISSING-1 ))
1224 done
1225
1226 # be careful where to place the :
1227 INPUT=$( echo "$INPUT" | sed -e 's|\(.\)::\(.\)|\1'$ZEROES':\2|g' \
1228 -e 's|\(.\)::$|\1'$ZEROES':0000|g' \
1229 -e 's|^::\(.\)|'$ZEROES':0000:\1|g;s|^:||g' )
1230 fi
1231
1232 # an expanded address has 39 chars + CR
1233 if [ $(echo $INPUT | wc -m) != 40 ]; then
1234 write_log 4 "Error in 'expand_ipv6()' - invalid IPv6 found: '$1' expanded: '$INPUT'"
1235 eval "$2='invalid'"
1236 return 1
1237 fi
1238
1239 # echo the fully expanded version of the address
1240 eval "$2=$INPUT"
1241 return 0
1242 }