2 # /usr/lib/ddns/dynamic_dns_functions.sh
4 # Original written by Eric Paul Bishop, January 2008
5 #.Distributed under the terms of the GNU General Public License (GPL) version 2.0
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
9 # extended and partial rewritten in August 2014 by
10 #.Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
12 # - IPv6 DDNS services
13 # - setting DNS Server to retrieve current IP including TCP transport
14 # - Proxy Server to send out updates or retrieving WEB based IP detection
15 # - force_interval=0 to run once (useful for cron jobs etc.)
16 # - the usage of BIND's host instead of BusyBox's nslookup if installed (DNS via TCP)
17 # - extended Verbose Mode and log file support for better error detection
20 # copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
21 # @author Anthony Thyssen 6 April 2011
23 # variables in small chars are read from /etc/config/ddns
24 # variables in big chars are defined inside these scripts as global vars
25 # variables in big chars beginning with "__" are local defined inside functions only
26 # set -vx #script debugger
29 .
/lib
/functions
/network.sh
32 SECTION_ID
="" # hold config's section name
33 VERBOSE_MODE
=1 # default mode is log to console, but easily changed with parameter
35 LOGFILE
="" # logfile - all files are set in dynamic_dns_updater.sh
37 UPDFILE
="" # store UPTIME of last update
38 DATFILE
="" # save stdout data of WGet and other external programs called
39 ERRFILE
="" # save stderr output of WGet and other external programs called
40 TLDFILE
=/usr
/lib
/ddns
/tld_names.dat.gz
# TLD file used by split_FQDN
42 CHECK_SECONDS
=0 # calculated seconds out of given
43 FORCE_SECONDS
=0 # interval and unit
44 RETRY_SECONDS
=0 # in configuration
46 LAST_TIME
=0 # holds the uptime of last successful update
47 CURR_TIME
=0 # holds the current uptime
48 NEXT_TIME
=0 # calculated time for next FORCED update
49 EPOCH_TIME
=0 # seconds since 1.1.1970 00:00:00
51 REGISTERED_IP
="" # holds the IP read from DNS
52 LOCAL_IP
="" # holds the local IP read from the box
54 URL_USER
="" # url encoded $username from config file
55 URL_PASS
="" # url encoded $password from config file
57 ERR_LAST
=0 # used to save $? return code of program and function calls
58 ERR_UPDATE
=0 # error counter on different local and registered ip
60 PID_SLEEP
=0 # ProcessID of current background "sleep"
62 # allow NON-public IP's
63 ALLOW_LOCAL_IP
=$
(uci
-q get ddns.global.allow_local_ip
) || ALLOW_LOCAL_IP
=0
65 # directory to store run information to.
66 RUNDIR
=$
(uci
-q get ddns.global.run_dir
) || RUNDIR
="/var/run/ddns"
67 [ -d $RUNDIR ] || mkdir
-p -m755 $RUNDIR
69 # directory to store log files
70 LOGDIR
=$
(uci
-q get ddns.global.log_dir
) || LOGDIR
="/var/log/ddns"
71 [ -d $LOGDIR ] || mkdir
-p -m755 $LOGDIR
73 # number of lines to before rotate logfile
74 LOGLINES
=$
(uci
-q get ddns.global.log_lines
) || LOGLINES
=250
75 LOGLINES
=$
((LOGLINES
+ 1)) # correct sed handling
77 # format to show date information in log and luci-app-ddns default ISO 8601 format
78 DATE_FORMAT
=$
(uci
-q get ddns.global.date_format
) || DATE_FORMAT
="%F %R"
79 DATE_PROG
="date +'$DATE_FORMAT'"
81 # regular expression to detect IPv4 / IPv6
82 # IPv4 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x "." 0-9 1-3x
83 IPV4_REGEX
="[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}"
84 # IPv6 ( ( 0-9a-f 1-4char ":") min 1x) ( ( 0-9a-f 1-4char )optional) ( (":" 0-9a-f 1-4char ) min 1x)
85 IPV6_REGEX
="\(\([0-9A-Fa-f]\{1,4\}:\)\{1,\}\)\(\([0-9A-Fa-f]\{1,4\}\)\{0,1\}\)\(\(:[0-9A-Fa-f]\{1,4\}\)\{1,\}\)"
87 # detect if called by dynamic_dns_lucihelper.sh script, disable retrys (empty variable == false)
88 [ "$(basename $0)" = "dynamic_dns_lucihelper.sh" ] && LUCI_HELPER
="TRUE" || LUCI_HELPER
=""
90 # USE_CURL if GNU Wget and cURL installed normally Wget is used by do_transfer()
91 # to change this use global option use_curl '1'
92 USE_CURL
=$
(uci
-q get ddns.global.use_curl
) || USE_CURL
=0 # read config
93 [ -x /usr
/bin
/curl
] || USE_CURL
=0 # check for cURL
95 # loads all options for a given package and section
96 # also, sets all_option_variables to a list of the variable names
97 # $1 = ddns, $2 = SECTION_ID
98 load_all_config_options
()
101 local __SECTIONID
="$2"
103 local __ALL_OPTION_VARIABLES
=""
105 # this callback loads all the variables in the __SECTIONID section when we do
106 # config_load. We need to redefine the option_cb for different sections
107 # so that the active one isn't still active after we're done with it. For reference
108 # the $1 variable is the name of the option and $2 is the name of the section
111 if [ .
"$2" = .
"$__SECTIONID" ]; then
114 __ALL_OPTION_VARIABLES
="$__ALL_OPTION_VARIABLES $1"
117 option_cb
() { return 0; }
121 config_load
"$__PKGNAME"
123 # Given SECTION_ID not found so no data, so return 1
124 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
126 for __VAR
in $__ALL_OPTION_VARIABLES
128 config_get
"$__VAR" "$__SECTIONID" "$__VAR"
133 # read's all service sections from ddns config
134 # $1 = Name of variable to store
135 load_all_service_sections
() {
139 # only look for section type "service", ignore everything else
140 [ "$1" = "service" ] && __DATA
="$__DATA $2"
144 eval "$1=\"$__DATA\""
148 # starts updater script for all given sections or only for the one given
149 # $1 = interface (Optional: when given only scripts are started
150 # configured for that interface)
151 # used by /etc/hotplug.d/iface/25-ddns on IFUP
152 # and by /etc/init.d/ddns start
153 start_daemon_for_all_ddns_sections
()
160 load_all_service_sections __SECTIONS
161 for __SECTIONID
in $__SECTIONS; do
162 config_get __IFACE
"$__SECTIONID" interface
"wan"
163 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
164 /usr
/lib
/ddns
/dynamic_dns_updater.sh
$__SECTIONID 0 >/dev
/null
2>&1 &
168 # stop sections process incl. childs (sleeps)
170 stop_section_processes
() {
172 local __PIDFILE
="$RUNDIR/$1.pid"
173 [ $# -ne 1 ] && write_log
12 "Error calling 'stop_section_processes()' - wrong number of parameters"
175 [ -e "$__PIDFILE" ] && {
176 __PID
=$
(cat $__PIDFILE)
177 ps |
grep "^[\t ]*$__PID" >/dev
/null
2>&1 && kill $__PID || __PID
=0 # terminate it
179 [ $__PID -eq 0 ] # report if process was running
182 # stop updater script for all defines sections or only for one given
183 # $1 = interface (optional)
184 # used by /etc/hotplug.d/iface/25-ddns on 'ifdown'
185 # and by /etc/init.d/ddns stop
186 # needed because we also need to kill "sleep" child processes
187 stop_daemon_for_all_ddns_sections
() {
193 load_all_service_sections __SECTIONS
194 for __SECTIONID
in $__SECTIONS; do
195 config_get __IFACE
"$__SECTIONID" interface
"wan"
196 [ -z "$__EVENTIF" -o "$__IFACE" = "$__EVENTIF" ] ||
continue
197 stop_section_processes
"$__SECTIONID"
201 # reports to console, logfile, syslog
202 # $1 loglevel 7 == Debug to 0 == EMERG
203 # value +10 will exit the scripts
204 # $2..n text to report
206 local __LEVEL __EXIT __CMD __MSG
207 local __TIME
=$
(date +%H
%M
%S
)
215 shift # remove loglevel
216 [ $__EXIT -eq 0 ] && __MSG
="$*" || __MSG
="$* - TERMINATE"
217 case $__LEVEL in # create log message and command depending on loglevel
218 0) __CMD
="logger -p user.emerg -t ddns-scripts[$$] $SECTION_ID: $__MSG"
219 __MSG
=" $__TIME EMERG : $__MSG" ;;
220 1) __CMD
="logger -p user.alert -t ddns-scripts[$$] $SECTION_ID: $__MSG"
221 __MSG
=" $__TIME ALERT : $__MSG" ;;
222 2) __CMD
="logger -p user.crit -t ddns-scripts[$$] $SECTION_ID: $__MSG"
223 __MSG
=" $__TIME CRIT : $__MSG" ;;
224 3) __CMD
="logger -p user.err -t ddns-scripts[$$] $SECTION_ID: $__MSG"
225 __MSG
=" $__TIME ERROR : $__MSG" ;;
226 4) __CMD
="logger -p user.warn -t ddns-scripts[$$] $SECTION_ID: $__MSG"
227 __MSG
=" $__TIME WARN : $__MSG" ;;
228 5) __CMD
="logger -p user.notice -t ddns-scripts[$$] $SECTION_ID: $__MSG"
229 __MSG
=" $__TIME note : $__MSG" ;;
230 6) __CMD
="logger -p user.info -t ddns-scripts[$$] $SECTION_ID: $__MSG"
231 __MSG
=" $__TIME info : $__MSG" ;;
232 7) __MSG
=" $__TIME : $__MSG";;
237 [ $VERBOSE_MODE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
239 if [ ${use_logfile:-1} -eq 1 -o $VERBOSE_MODE -gt 1 ]; then
240 echo -e "$__MSG" >> $LOGFILE
241 # VERBOSE_MODE > 1 then NO loop so NO truncate log to $LOGLINES lines
242 [ $VERBOSE_MODE -gt 1 ] ||
sed -i -e :a
-e '$q;N;'$LOGLINES',$D;ba' $LOGFILE
244 [ $LUCI_HELPER ] && return # nothing else todo when running LuCI helper script
245 [ $__LEVEL -eq 7 ] && return # no syslog for debug messages
246 __CMD
=$
(echo -e "$__CMD" |
tr -d '\n' |
tr '\t' ' ') # remove \n \t chars
247 [ $__EXIT -eq 1 ] && {
248 $__CMD # force syslog before exit
251 [ $use_syslog -eq 0 ] && return
252 [ $
((use_syslog
+ __LEVEL
)) -le 7 ] && $__CMD
256 # replace all special chars to their %hex value
257 # used for USERNAME and PASSWORD in update_url
258 # unchanged: "-"(minus) "_"(underscore) "."(dot) "~"(tilde)
259 # to verify: "'"(single quote) '"'(double quote) # because shell delimiter
260 # "$"(Dollar) # because used as variable output
261 # tested with the following string stored via Luci Application as password / username
262 # A B!"#AA$1BB%&'()*+,-./:;<=>?@[\]^_`{|}~ without problems at Dollar or quotes
264 # $1 Name of Variable to store encoded string to
265 # $2 string to encode
266 local __STR __LEN __CHAR __OUT
270 [ $# -ne 2 ] && write_log
12 "Error calling 'urlencode()' - wrong number of parameters"
272 __STR
="$2" # read string to encode
273 __LEN
=${#__STR} # get string length
275 while [ $__POS -le $__LEN ]; do
276 # read one chat of the string
277 __CHAR
=$
(expr substr
"$__STR" $__POS 1)
285 # special char get %hex code
286 __OUT
=$
(printf '%%%02x' "'$__CHAR" )
289 __ENC
="${__ENC}${__OUT}" # append to encoded string
290 __POS
=$
(( $__POS + 1 )) # increment position
293 eval "$1=\"$__ENC\"" # transfer back to variable
297 # extract url or script for given DDNS Provider from
298 # file /usr/lib/ddns/services for IPv4 or from
299 # file /usr/lib/ddns/services_ipv6 for IPv6
300 # $1 Name of Variable to store url to
301 # $2 Name of Variable to store script to
303 local __LINE __FILE __NAME __URL __SERVICES __DATA
306 local __NEWLINE_IFS
='
308 [ $# -ne 2 ] && write_log
12 "Error calling 'get_service_data()' - wrong number of parameters"
310 __FILE
="/usr/lib/ddns/services" # IPv4
311 [ $use_ipv6 -ne 0 ] && __FILE
="/usr/lib/ddns/services_ipv6" # IPv6
313 # remove any lines not containing data, and then make sure fields are enclosed in double quotes
314 __SERVICES
=$
(cat $__FILE |
grep "^[\t ]*[^#]" | \
315 awk ' gsub("\x27", "\"") { if ($1~/^[^\"]*$/) $1="\""$1"\"" }; { if ( $NF~/^[^\"]*$/) $NF="\""$NF"\"" }; { print $0 }')
318 for __LINE
in $__SERVICES; do
319 # grep out proper parts of data and use echo to remove quotes
320 __NAME
=$
(echo $__LINE |
grep -o "^[\t ]*\"[^\"]*\"" |
xargs -r -n1 echo)
321 __DATA
=$
(echo $__LINE |
grep -o "\"[^\"]*\"[\t ]*$" |
xargs -r -n1 echo)
323 if [ "$__NAME" = "$service_name" ]; then
324 break # found so leave for loop
329 # check if URL or SCRIPT is given
330 __URL
=$
(echo "$__DATA" |
grep "^http")
331 [ -z "$__URL" ] && __SCRIPT
="/usr/lib/ddns/$__DATA"
334 eval "$2=\"$__SCRIPT\""
338 # Calculate seconds from interval and unit
339 # $1 Name of Variable to store result in
341 # $3 Unit of time interval
343 [ $# -ne 3 ] && write_log
12 "Error calling 'get_seconds()' - wrong number of parameters"
345 "days" ) eval "$1=$(( $2 * 86400 ))";;
346 "hours" ) eval "$1=$(( $2 * 3600 ))";;
347 "minutes" ) eval "$1=$(( $2 * 60 ))";;
354 #.copied from http://www.ict.griffith.edu.au/anthony/software/timeout.sh
355 # only did the following changes
356 # - commented out "#!/bin/bash" and usage section
357 # - replace exit by return for usage as function
358 # - some reformatting
360 # timeout [-SIG] time [--] command args...
362 # Run the given command until completion, but kill it if it runs too long.
363 # Specifically designed to exit immediately (no sleep interval) and clean up
364 # nicely without messages or leaving any extra processes when finished.
367 # timeout 5 countdown
369 # Based on notes in my "Shell Script Hints", section "Command Timeout"
370 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
372 # This script uses a lot of tricks to terminate both the background command,
373 # the timeout script, and even the sleep process. It also includes trap
374 # commands to prevent sub-shells reporting expected "Termination Errors".
376 # It took years of occasional trials, errors and testing to get a pure bash
377 # timeout command working as well as this does.
379 #.Anthony Thyssen 6 April 2011
381 # PROGNAME=$(type $0 | awk '{print $3}') # search for executable on path
382 # PROGDIR=$(dirname $PROGNAME) # extract directory of program
383 # PROGNAME=$(basename $PROGNAME) # base name of program
385 # output the script comments as docs
387 # echo >&2 "$PROGNAME:" "$@"
388 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
394 while [ $# -gt 0 ]; do
397 # forced end of user options
407 # unforced end of user options
413 # run main command in backgrounds and get its pid
417 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
420 # cleanup sleep process
421 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
422 # sleep timeout period in background
427 kill $SIG $command_pid >/dev
/null
2>&1
432 # Wait for main command to finished or be timed out
436 # Clean up timeout sub-shell - if it is still running!
437 kill $timeout_pid 2>/dev
/null
438 wait $timeout_pid 2>/dev
/null
440 # Uncomment to check if a LONG sleep still running (no sleep should be)
443 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
448 # verify given host and port is connectable
449 # $1 Host/IP to verify
454 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
456 # 1 system specific error
457 # 2 nslookup/host error
458 # 3 nc (netcat) error
459 # 4 unmatched IP version
461 [ $# -ne 2 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
463 # check if ip or FQDN was given
464 __IPV4
=$
(echo $__HOST |
grep -m 1 -o "$IPV4_REGEX$") # do not detect ip in 0.0.0.0.example.com
465 __IPV6
=$
(echo $__HOST |
grep -m 1 -o "$IPV6_REGEX")
466 # if FQDN given get IP address
467 [ -z "$__IPV4" -a -z "$__IPV6" ] && {
468 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
470 __RUNPROG
="/usr/bin/host -t ANY $__HOST >$DATFILE 2>$ERRFILE"
471 else # use BusyBox nslookup
472 __PROG
="BusyBox nslookup"
473 __RUNPROG
="/usr/bin/nslookup $__HOST >$DATFILE 2>$ERRFILE"
475 write_log
7 "#> $__RUNPROG"
479 [ $__ERR -gt 0 ] && {
480 write_log
3 "DNS Resolver Error - $__PROG Error '$__ERR'"
481 write_log
7 "$(cat $ERRFILE)"
485 if [ -x /usr
/bin
/host ]; then # use BIND host if installed
486 __IPV4
=$
(cat $DATFILE |
awk -F "address " '/has address/ {print $2; exit}' )
487 __IPV6
=$
(cat $DATFILE |
awk -F "address " '/has IPv6/ {print $2; exit}' )
488 else # use BusyBox nslookup
489 __IPV4
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV4_REGEX\).*$/\\1/p }")
490 __IPV6
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($IPV6_REGEX\).*$/\\1/p }")
494 # check IP version if forced
495 if [ $force_ipversion -ne 0 ]; then
497 [ $use_ipv6 -eq 0 -a -z "$__IPV4" ] && __ERR
=4
498 [ $use_ipv6 -eq 1 -a -z "$__IPV6" ] && __ERR
=6
499 [ $__ERR -gt 0 ] && {
500 [ $LUCI_HELPER ] && return 4
501 write_log
14 "Verify host Error '4' - Forced IP Version IPv$__ERR don't match"
506 # busybox nc compiled without -l option "NO OPT l!" -> critical error
507 /usr
/bin
/nc
--help 2>&1 |
grep -i "NO OPT l!" >/dev
/null
2>&1 && \
508 write_log
12 "Busybox nc (netcat) compiled without '-l' option, error 'NO OPT l!'"
509 # busybox nc compiled with extensions
510 /usr
/bin
/nc
--help 2>&1 |
grep "\-w" >/dev
/null
2>&1 && __NCEXT
="TRUE"
513 # run busybox nc to HOST PORT
514 # busybox might be compiled with "FEATURE_PREFER_IPV4_ADDRESS=n"
515 # then nc will try to connect via IPv6 if there is any IPv6 available on any host interface
516 # not worrying, if there is an IPv6 wan address
517 # so if not "force_ipversion" to use_ipv6 then connect test via ipv4, if available
518 [ $force_ipversion -ne 0 -a $use_ipv6 -ne 0 -o -z "$__IPV4" ] && __IP
=$__IPV6 || __IP
=$__IPV4
520 if [ -n "$__NCEXT" ]; then # BusyBox nc compiled with extensions (timeout support)
521 __RUNPROG
="/usr/bin/nc -w 1 $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
522 write_log
7 "#> $__RUNPROG"
525 [ $__ERR -eq 0 ] && return 0
526 write_log
3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
527 write_log
7 "$(cat $ERRFILE)"
529 else # nc compiled without extensions (no timeout support)
530 __RUNPROG
="timeout 2 -- /usr/bin/nc $__IP $__PORT </dev/null >$DATFILE 2>$ERRFILE"
531 write_log
7 "#> $__RUNPROG"
534 [ $__ERR -eq 0 ] && return 0
535 write_log
3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
540 # verify given DNS server if connectable
541 # $1 DNS server to verify
543 local __ERR
=255 # last error buffer
544 local __CNT
=0 # error counter
546 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_dns()' - wrong number of parameters"
547 write_log
7 "Verify DNS server '$1'"
549 while [ $__ERR -ne 0 ]; do
551 verify_host_port
"$1" "53"
553 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
555 elif [ $__ERR -ne 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
556 write_log
4 "Verify DNS server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
558 elif [ $__ERR -ne 0 ]; then
559 __CNT
=$
(( $__CNT + 1 )) # increment error counter
560 # if error count > retry_count leave here
561 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
562 write_log
14 "Verify DNS server '$1' failed after $retry_count retries"
564 write_log
4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
565 sleep $RETRY_SECONDS &
567 wait $PID_SLEEP # enable trap-handler
574 # analyze and verify given proxy string
575 # $1 Proxy-String to verify
577 # complete entry user:password@host:port
578 # inside user and password NO '@' of ":" allowed
579 # host and port only host:port
580 # host only host ERROR unsupported
581 # IPv4 address instead of host 123.234.234.123
582 # IPv6 address instead of host [xxxx:....:xxxx] in square bracket
583 local __TMP __HOST __PORT
584 local __ERR
=255 # last error buffer
585 local __CNT
=0 # error counter
587 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_proxy()' - wrong number of parameters"
588 write_log
7 "Verify Proxy server 'http://$1'"
590 # try to split user:password "@" host:port
591 __TMP
=$
(echo $1 |
awk -F "@" '{print $2}')
592 # no "@" found - only host:port is given
593 [ -z "$__TMP" ] && __TMP
="$1"
594 # now lets check for IPv6 address
595 __HOST
=$
(echo $__TMP |
grep -m 1 -o "$IPV6_REGEX")
596 # IPv6 host address found read port
597 if [ -n "$__HOST" ]; then
599 __PORT
=$
(echo $__TMP |
awk -F "]:" '{print $2}')
601 __HOST
=$
(echo $__TMP |
awk -F ":" '{print $1}')
602 __PORT
=$
(echo $__TMP |
awk -F ":" '{print $2}')
604 # No Port detected - EXITING
605 [ -z "$__PORT" ] && {
606 [ $LUCI_HELPER ] && return 5
607 write_log
14 "Invalid Proxy server Error '5' - proxy port missing"
610 while [ $__ERR -gt 0 ]; do
611 verify_host_port
"$__HOST" "$__PORT"
613 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
615 elif [ $__ERR -gt 0 -a $VERBOSE_MODE -gt 1 ]; then # VERBOSE_MODE > 1 then NO retry
616 write_log
4 "Verify Proxy server '$1' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
618 elif [ $__ERR -gt 0 ]; then
619 __CNT
=$
(( $__CNT + 1 )) # increment error counter
620 # if error count > retry_count leave here
621 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
622 write_log
14 "Verify Proxy server '$1' failed after $retry_count retries"
624 write_log
4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
625 sleep $RETRY_SECONDS &
627 wait $PID_SLEEP # enable trap-handler
638 local __CNT
=0 # error counter
639 local __PROG __RUNPROG
641 [ $# -ne 1 ] && write_log
12 "Error in 'do_transfer()' - wrong number of parameters"
643 # lets prefer GNU Wget because it does all for us - IPv4/IPv6/HTTPS/PROXY/force IP version
644 grep -i "\+ssl" /usr
/bin
/wget
>/dev
/null
2>&1 # check for Wget with SSL support
645 if [ $?
-eq 0 -a $USE_CURL -eq 0 ]; then # except global option use_curl is set to "1"
646 __PROG
="/usr/bin/wget -nv -t 1 -O $DATFILE -o $ERRFILE" # non_verbose no_retry outfile errfile
647 # force network/ip to use for communication
648 if [ -n "$bind_network" ]; then
650 # set correct program to detect IP
651 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" || __RUNPROG
="network_get_ipaddr6"
652 eval "$__RUNPROG __BINDIP $bind_network" || \
653 write_log
13 "Can not detect local IP using '$__RUNPROG $bind_network' - Error: '$?'"
654 write_log
7 "Force communication via IP '$__BINDIP'"
655 __PROG
="$__PROG --bind-address=$__BINDIP"
657 # force ip version to use
658 if [ $force_ipversion -eq 1 ]; then
659 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
661 # set certificate parameters
662 if [ $use_https -eq 1 ]; then
663 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
664 __PROG
="$__PROG --no-check-certificate"
665 elif [ -f "$cacert" ]; then
666 __PROG
="$__PROG --ca-certificate=${cacert}"
667 elif [ -d "$cacert" ]; then
668 __PROG
="$__PROG --ca-directory=${cacert}"
669 else # exit here because it makes no sense to start loop
670 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
673 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
674 [ -z "$proxy" ] && __PROG
="$__PROG --no-proxy"
676 __RUNPROG
="$__PROG '$__URL'" # build final command
677 __PROG
="GNU Wget" # reuse for error logging
679 # 2nd choice is cURL IPv4/IPv6/HTTPS
680 # libcurl might be compiled without Proxy Support (default in trunk)
681 elif [ -x /usr
/bin
/curl
]; then
682 __PROG
="/usr/bin/curl -RsS -o $DATFILE --stderr $ERRFILE"
683 # force network/interface-device to use for communication
684 if [ -n "$bind_network" ]; then
686 network_get_physdev __DEVICE
$bind_network || \
687 write_log
13 "Can not detect local device using 'network_get_physdev $bind_network' - Error: '$?'"
688 write_log
7 "Force communication via device '$__DEVICE'"
689 __PROG
="$__PROG --interface $__DEVICE"
691 # force ip version to use
692 if [ $force_ipversion -eq 1 ]; then
693 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6" # force IPv4/IPv6
695 # set certificate parameters
696 if [ $use_https -eq 1 ]; then
697 if [ "$cacert" = "IGNORE" ]; then # idea from Ticket #15327 to ignore server cert
698 __PROG
="$__PROG --insecure" # but not empty better to use "IGNORE"
699 elif [ -f "$cacert" ]; then
700 __PROG
="$__PROG --cacert $cacert"
701 elif [ -d "$cacert" ]; then
702 __PROG
="$__PROG --capath $cacert"
703 else # exit here because it makes no sense to start loop
704 write_log
14 "No valid certificate(s) found at '$cacert' for HTTPS communication"
707 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
708 # or check if libcurl compiled with proxy support
709 if [ -z "$proxy" ]; then
710 __PROG
="$__PROG --noproxy '*'"
712 # if libcurl has no proxy support and proxy should be used then force ERROR
713 # libcurl currently no proxy support by default
714 grep -i "all_proxy" /usr
/lib
/libcurl.so
* >/dev
/null
2>&1 || \
715 write_log
13 "cURL: libcurl compiled without Proxy support"
718 __RUNPROG
="$__PROG '$__URL'" # build final command
719 __PROG
="cURL" # reuse for error logging
721 # busybox Wget (did not support neither IPv6 nor HTTPS)
722 elif [ -x /usr
/bin
/wget
]; then
723 __PROG
="/usr/bin/wget -q -O $DATFILE"
724 # force network/ip not supported
725 [ -n "$__BINDIP" ] && \
726 write_log
14 "BusyBox Wget: FORCE binding to specific address not supported"
727 # force ip version not supported
728 [ $force_ipversion -eq 1 ] && \
729 write_log
14 "BusyBox Wget: Force connecting to IPv4 or IPv6 addresses not supported"
730 # https not supported
731 [ $use_https -eq 1 ] && \
732 write_log
14 "BusyBox Wget: no HTTPS support"
733 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
734 [ -z "$proxy" ] && __PROG
="$__PROG -Y off"
736 __RUNPROG
="$__PROG '$__URL' 2>$ERRFILE" # build final command
737 __PROG
="Busybox Wget" # reuse for error logging
740 write_log
13 "Neither 'Wget' nor 'cURL' installed or executable"
744 write_log
7 "#> $__RUNPROG"
745 eval $__RUNPROG # DO transfer
746 __ERR
=$?
# save error code
747 [ $__ERR -eq 0 ] && return 0 # no error leave
748 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
750 write_log
3 "$__PROG Error: '$__ERR'"
751 write_log
7 "$(cat $ERRFILE)" # report error
753 [ $VERBOSE_MODE -gt 1 ] && {
754 # VERBOSE_MODE > 1 then NO retry
755 write_log
4 "Transfer failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
759 __CNT
=$
(( $__CNT + 1 )) # increment error counter
760 # if error count > retry_count leave here
761 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
762 write_log
14 "Transfer failed after $retry_count retries"
764 write_log
4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
765 sleep $RETRY_SECONDS &
767 wait $PID_SLEEP # enable trap-handler
770 # we should never come here there must be a programming error
771 write_log
12 "Error in 'do_transfer()' - program coding error"
775 # $1 # IP to set at DDNS service provider
778 [ $# -ne 1 ] && write_log
12 "Error calling 'send_update()' - wrong number of parameters"
780 if [ $ALLOW_LOCAL_IP -eq 0 ]; then
781 # verify given IP / no private IPv4's / no IPv6 addr starting with fxxx of with ":"
782 [ $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)")
783 [ $use_ipv6 -eq 1 ] && __IP
=$
(echo $1 |
grep "^[0-9a-eA-E]")
784 [ -z "$__IP" ] && write_log
14 "Private or invalid or no IP '$1' given! Please check your configuration"
789 if [ -n "$update_script" ]; then
790 write_log
7 "parsing script '$update_script'"
796 __URL
=$
(echo $update_url |
sed -e "s#\[USERNAME\]#$URL_USER#g" -e "s#\[PASSWORD\]#$URL_PASS#g" \
797 -e "s#\[DOMAIN\]#$domain#g" -e "s#\[IP\]#$__IP#g")
798 [ $use_https -ne 0 ] && __URL
=$
(echo $__URL |
sed -e 's#^http:#https:#')
800 do_transfer
"$__URL" ||
return 1
802 write_log
7 "DDNS Provider answered:\n$(cat $DATFILE)"
805 # TODO analyze providers answer
806 # "good" or "nochg" = dyndns.com compatible API
807 # grep -i -E "good|nochg" $DATFILE >/dev/null 2>&1
808 # return $? # "0" if found
813 # $1 Name of Variable to store local IP (LOCAL_IP)
814 local __CNT
=0 # error counter
815 local __RUNPROG __DATA __URL __ERR
817 [ $# -ne 1 ] && write_log
12 "Error calling 'get_local_ip()' - wrong number of parameters"
818 write_log
7 "Detect local IP on '$ip_source'"
823 # set correct program
824 [ $use_ipv6 -eq 0 ] && __RUNPROG
="network_get_ipaddr" \
825 || __RUNPROG
="network_get_ipaddr6"
826 eval "$__RUNPROG __DATA $ip_network" || \
827 write_log
13 "Can not detect local IP using $__RUNPROG '$ip_network' - Error: '$?'"
828 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on network '$ip_network'"
831 write_log
7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
832 ifconfig
$ip_interface >$DATFILE 2>$ERRFILE
834 if [ $__ERR -eq 0 ]; then
835 if [ $use_ipv6 -eq 0 ]; then
837 /inet addr:/ { # Filter IPv4
838 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
840 $3=""; # remove Bcast: ...
841 $4=""; # remove Mask: ...
842 FS=":"; # separator ":"
843 $0=$0; # reread to activate separator
845 FS=" "; # set back separator to default " "
846 $0=$0; # reread to activate separator (remove whitespaces)
847 print $1; # print IPv4 addr
852 /inet6/ && /: [0-9a-eA-E]/ && !/\/128/ { # Filter IPv6 exclude fxxx and /128 prefix
853 # inet6 addr: 2001:db8::xxxx:xxxx/32 Scope:Global
854 FS="/"; # separator "/"
855 $0=$0; # reread to activate separator
856 $2=""; # remove everything behind "/"
857 FS=" "; # set back separator to default " "
858 $0=$0; # reread to activate separator
859 print $3; # print IPv6 addr
863 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on interface '$ip_interface'"
865 write_log
3 "ifconfig Error: '$__ERR'"
866 write_log
7 "$(cat $ERRFILE)" # report error
870 write_log
7 "#> $ip_script >$DATFILE 2>$ERRFILE"
871 eval $ip_script >$DATFILE 2>$ERRFILE
873 if [ $__ERR -eq 0 ]; then
874 __DATA
=$
(cat $DATFILE)
875 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected via script '$ip_script'"
877 write_log
3 "$ip_script Error: '$__ERR'"
878 write_log
7 "$(cat $ERRFILE)" # report error
882 do_transfer
"$ip_url"
883 # use correct regular expression
884 [ $use_ipv6 -eq 0 ] \
885 && __DATA
=$
(grep -m 1 -o "$IPV4_REGEX" $DATFILE) \
886 || __DATA
=$
(grep -m 1 -o "$IPV6_REGEX" $DATFILE)
887 [ -n "$__DATA" ] && write_log
7 "Local IP '$__DATA' detected on web at '$ip_url'"
890 write_log
12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
893 # valid data found return here
894 [ -n "$__DATA" ] && {
895 eval "$1=\"$__DATA\""
899 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
901 write_log
7 "Data detected:\n$(cat $DATFILE)"
903 [ $VERBOSE_MODE -gt 1 ] && {
904 # VERBOSE_MODE > 1 then NO retry
905 write_log
4 "Get local IP via '$ip_source' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
909 __CNT
=$
(( $__CNT + 1 )) # increment error counter
910 # if error count > retry_count leave here
911 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
912 write_log
14 "Get local IP via '$ip_source' failed after $retry_count retries"
913 write_log
4 "Get local IP via '$ip_source' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
914 sleep $RETRY_SECONDS &
916 wait $PID_SLEEP # enable trap-handler
919 # we should never come here there must be a programming error
920 write_log
12 "Error in 'get_local_ip()' - program coding error"
923 get_registered_ip
() {
924 # $1 Name of Variable to store public IP (REGISTERED_IP)
925 # $2 (optional) if set, do not retry on error
926 local __CNT
=0 # error counter
928 local __REGEX __PROG __RUNPROG __DATA
932 [ $# -lt 1 -o $# -gt 2 ] && write_log
12 "Error calling 'get_registered_ip()' - wrong number of parameters"
933 write_log
7 "Detect registered/public IP"
935 # set correct regular expression
936 [ $use_ipv6 -eq 0 ] && __REGEX
="$IPV4_REGEX" || __REGEX
="$IPV6_REGEX"
938 if [ -x /usr
/bin
/host ]; then
939 __PROG
="/usr/bin/host"
940 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -t A" || __PROG
="$__PROG -t AAAA"
941 if [ $force_ipversion -eq 1 ]; then # force IP version
942 [ $use_ipv6 -eq 0 ] && __PROG
="$__PROG -4" || __PROG
="$__PROG -6"
944 [ $force_dnstcp -eq 1 ] && __PROG
="$__PROG -T" # force TCP
946 __RUNPROG
="$__PROG $domain $dns_server >$DATFILE 2>$ERRFILE"
948 elif [ -x /usr
/bin
/nslookup ]; then # last use BusyBox nslookup
949 [ $force_ipversion -ne 0 -o $force_dnstcp -ne 0 ] && \
950 write_log
14 "Busybox nslookup - no support to 'force IP Version' or 'DNS over TCP'"
952 __RUNPROG
="/usr/bin/nslookup $domain $dns_server >$DATFILE 2>$ERRFILE"
953 __PROG
="BusyBox nslookup"
954 else # there must be an error
955 write_log
12 "Error in 'get_registered_ip()' - no supported Name Server lookup software accessible"
959 write_log
7 "#> $__RUNPROG"
962 if [ $__ERR -ne 0 ]; then
963 write_log
3 "$__PROG error: '$__ERR'"
964 write_log
7 "$(cat $ERRFILE)"
966 if [ "$__PROG" = "BIND host" ]; then
967 __DATA
=$
(cat $DATFILE |
awk -F "address " '/has/ {print $2; exit}' )
969 __DATA
=$
(cat $DATFILE |
sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
971 [ -n "$__DATA" ] && {
972 write_log
7 "Registered IP '$__DATA' detected"
973 eval "$1=\"$__DATA\"" # valid data found
974 return 0 # leave here
976 write_log
4 "NO valid IP found"
980 [ $LUCI_HELPER ] && return $__ERR # no retry if called by LuCI helper script
981 [ -n "$2" ] && return $__ERR # $2 is given -> no retry
982 [ $VERBOSE_MODE -gt 1 ] && {
983 # VERBOSE_MODE > 1 then NO retry
984 write_log
4 "Get registered/public IP for '$domain' failed - Verbose Mode: $VERBOSE_MODE - NO retry on error"
988 __CNT
=$
(( $__CNT + 1 )) # increment error counter
989 # if error count > retry_count leave here
990 [ $retry_count -gt 0 -a $__CNT -gt $retry_count ] && \
991 write_log
14 "Get registered/public IP for '$domain' failed after $retry_count retries"
993 write_log
4 "Get registered/public IP for '$domain' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
994 sleep $RETRY_SECONDS &
996 wait $PID_SLEEP # enable trap-handler
999 # we should never come here there must be a programming error
1000 write_log
12 "Error in 'get_registered_ip()' - program coding error"
1004 # $1 Variable to store result in
1005 [ $# -ne 1 ] && write_log
12 "Error calling 'verify_host_port()' - wrong number of parameters"
1006 local __UPTIME
=$
(cat /proc
/uptime
)
1007 eval "$1=\"${__UPTIME%%.*}\""
1012 # $2 optional (exit status)
1015 local __OLD_IFS
=$IFS
1016 local __NEWLINE_IFS
='
1019 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev
/null
# kill pending sleep if exist
1022 0) if [ $__ERR -eq 0 ]; then
1023 write_log
5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
1025 write_log
4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1027 1) write_log
6 "PID '$$' received 'SIGHUP' at $(eval $DATE_PROG)"
1028 # reload config via starting the script again
1029 eval "/usr/lib/ddns/dynamic_dns_updater.sh $SECTION_ID $VERBOSE_MODE &"
1030 exit 0 ;; # and leave this one
1031 2) write_log
5 "PID '$$' terminated by 'SIGINT' at $(eval $DATE_PROG)\n";;
1032 3) write_log
5 "PID '$$' terminated by 'SIGQUIT' at $(eval $DATE_PROG)\n";;
1033 15) write_log
5 "PID '$$' terminated by 'SIGTERM' at $(eval $DATE_PROG)\n";;
1034 *) write_log
13 "Unhandled signal '$1' in 'trap_handler()'";;
1037 __PIDS
=$
(pgrep
-P $$
) # get my childs (pgrep prints with "newline")
1039 for __PID
in $__PIDS; do
1040 kill -$1 $__PID # terminate it
1044 # remove out and err file
1045 [ -f $DATFILE ] && rm -f $DATFILE
1046 [ -f $ERRFILE ] && rm -f $ERRFILE
1048 # exit with correct handling:
1049 # remove trap handling settings and send kill to myself
1051 [ $1 -gt 0 ] && kill -$1 $$
1056 # $2 name of variable to store TLD
1057 # $3 name of variable to store (reg)Domain
1058 # $4 name of variable to store Host/Subdomain
1060 [ $# -ne 4 ] && write_log
12 "Error calling 'split_FQDN()' - wrong number of parameters"
1061 [ -z "$1" ] && write_log
12 "Error calling 'split_FQDN()' - missing FQDN to split"
1062 [ -f $TLDFILE ] || write_log
12 "Error calling 'split_FQDN()' - missing file '$TLDFILE'"
1064 local _HOST _FDOM _CTLD _FTLD
1065 local _SET
="$@" # save given function parameters
1067 local _PAR
=$
(echo "$1" |
tr [A-Z
] [a-z
] |
tr "." " ") # to lower and replace DOT with SPACE
1068 set -- $_PAR # set new as function parameters
1069 _PAR
="" # clear variable for later reuse
1070 while [ -n "$1" ] ; do # as long we have parameters
1071 _PAR
="$1 $_PAR" # invert order of parameters
1074 set -- $_PAR # use new as function parameters
1075 _PAR
="" # clear variable
1077 while [ -n "$1" ] ; do # as long we have parameters
1078 if [ -z "$_CTLD" ]; then # first loop
1079 _CTLD
="$1" # CURRENT TLD to look at
1082 _CTLD
="$1.$_CTLD" # Next TLD to look at
1085 # check if TLD exact match in tld_names.dat, save TLD
1086 zcat
$TLDFILE |
grep -E "^$_CTLD$" >/dev
/null
2>&1 && {
1087 _FTLD
="$_CTLD" # save found
1088 _FDOM
="$1" # save domain next step might be invalid
1091 # check if match any "*" in tld_names.dat,
1092 zcat
$TLDFILE |
grep -E "^\*.$_CTLD$" >/dev
/null
2>&1 && {
1093 [ -z "$1" ] && break # no more data break
1094 # check if next level TLD match excludes "!" in tld_names.dat
1095 if zcat
$TLDFILE |
grep -E "^!$1.$_CTLD$" >/dev
/null
2>&1 ; then
1096 _FTLD
="$_CTLD" # Yes
1103 [ -n "$_FTLD" ] && break # we have something valid, break
1106 # the leftover parameters are the HOST/SUBDOMAIN
1107 while [ -n "$1" ]; do
1108 _HOST
="$1 $HOST" # remember we need to invert
1111 _HOST
=$
(echo $_HOST |
tr " " ".") # insert DOT
1113 set -- $_SET # set back parameters from function call
1114 [ -n "$_FTLD" ] && {
1115 eval "$2=$_FTLD" # set TLD
1116 eval "$3=$_FDOM" # set registrable domain
1117 eval "$4=$_HOST" # set HOST/SUBDOMAIN
1120 eval "$2=''" # clear TLD
1121 eval "$3=''" # clear registrable domain
1122 eval "$4=''" # clear HOST/SUBDOMAIN