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