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