Merge pull request #1475 from ejurgensen/master
[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 LOGFILE="" # logfile - all files are set in dynamic_dns_updater.sh
36 PIDFILE="" # pid file
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
41
42 CHECK_SECONDS=0 # calculated seconds out of given
43 FORCE_SECONDS=0 # interval and unit
44 RETRY_SECONDS=0 # in configuration
45
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
50
51 REGISTERED_IP="" # holds the IP read from DNS
52 LOCAL_IP="" # holds the local IP read from the box
53
54 URL_USER="" # url encoded $username from config file
55 URL_PASS="" # url encoded $password from config file
56
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
59
60 PID_SLEEP=0 # ProcessID of current background "sleep"
61
62 # allow NON-public IP's
63 ALLOW_LOCAL_IP=$(uci -q get ddns.global.allow_local_ip) || ALLOW_LOCAL_IP=0
64
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
68
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
72
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
76
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'"
80
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,\}\)"
86
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=""
89
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
94
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()
99 {
100 local __PKGNAME="$1"
101 local __SECTIONID="$2"
102 local __VAR
103 local __ALL_OPTION_VARIABLES=""
104
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
109 config_cb()
110 {
111 if [ ."$2" = ."$__SECTIONID" ]; then
112 option_cb()
113 {
114 __ALL_OPTION_VARIABLES="$__ALL_OPTION_VARIABLES $1"
115 }
116 else
117 option_cb() { return 0; }
118 fi
119 }
120
121 config_load "$__PKGNAME"
122
123 # Given SECTION_ID not found so no data, so return 1
124 [ -z "$__ALL_OPTION_VARIABLES" ] && return 1
125
126 for __VAR in $__ALL_OPTION_VARIABLES
127 do
128 config_get "$__VAR" "$__SECTIONID" "$__VAR"
129 done
130 return 0
131 }
132
133 # read's all service sections from ddns config
134 # $1 = Name of variable to store
135 load_all_service_sections() {
136 local __DATA=""
137 config_cb()
138 {
139 # only look for section type "service", ignore everything else
140 [ "$1" = "service" ] && __DATA="$__DATA $2"
141 }
142 config_load "ddns"
143
144 eval "$1=\"$__DATA\""
145 return
146 }
147
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()
154 {
155 local __EVENTIF="$1"
156 local __SECTIONS=""
157 local __SECTIONID=""
158 local __IFACE=""
159
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 &
165 done
166 }
167
168 # stop sections process incl. childs (sleeps)
169 # $1 = section
170 stop_section_processes() {
171 local __PID=0
172 local __PIDFILE="$RUNDIR/$1.pid"
173 [ $# -ne 1 ] && write_log 12 "Error calling 'stop_section_processes()' - wrong number of parameters"
174
175 [ -e "$__PIDFILE" ] && {
176 __PID=$(cat $__PIDFILE)
177 ps | grep "^[\t ]*$__PID" >/dev/null 2>&1 && kill $__PID || __PID=0 # terminate it
178 }
179 [ $__PID -eq 0 ] # report if process was running
180 }
181
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() {
188 local __EVENTIF="$1"
189 local __SECTIONS=""
190 local __SECTIONID=""
191 local __IFACE=""
192
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"
198 done
199 }
200
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
205 write_log() {
206 local __LEVEL __EXIT __CMD __MSG
207 local __TIME=$(date +%H%M%S)
208 [ $1 -ge 10 ] && {
209 __LEVEL=$(($1-10))
210 __EXIT=1
211 } || {
212 __LEVEL=$1
213 __EXIT=0
214 }
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";;
233 *) return;;
234 esac
235
236 # verbose echo
237 [ $VERBOSE_MODE -gt 0 -o $__EXIT -gt 0 ] && echo -e "$__MSG"
238 # write to logfile
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
243 fi
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
249 exit 1
250 }
251 [ $use_syslog -eq 0 ] && return
252 [ $((use_syslog + __LEVEL)) -le 7 ] && $__CMD
253 return
254 }
255
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
263 urlencode() {
264 # $1 Name of Variable to store encoded string to
265 # $2 string to encode
266 local __STR __LEN __CHAR __OUT
267 local __ENC=""
268 local __POS=1
269
270 [ $# -ne 2 ] && write_log 12 "Error calling 'urlencode()' - wrong number of parameters"
271
272 __STR="$2" # read string to encode
273 __LEN=${#__STR} # get string length
274
275 while [ $__POS -le $__LEN ]; do
276 # read one chat of the string
277 __CHAR=$(expr substr "$__STR" $__POS 1)
278
279 case "$__CHAR" in
280 [-_.~a-zA-Z0-9] )
281 # standard char
282 __OUT="${__CHAR}"
283 ;;
284 * )
285 # special char get %hex code
286 __OUT=$(printf '%%%02x' "'$__CHAR" )
287 ;;
288 esac
289 __ENC="${__ENC}${__OUT}" # append to encoded string
290 __POS=$(( $__POS + 1 )) # increment position
291 done
292
293 eval "$1=\"$__ENC\"" # transfer back to variable
294 return 0
295 }
296
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
302 get_service_data() {
303 local __LINE __FILE __NAME __URL __SERVICES __DATA
304 local __SCRIPT=""
305 local __OLD_IFS=$IFS
306 local __NEWLINE_IFS='
307 ' # __NEWLINE_IFS
308 [ $# -ne 2 ] && 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 # 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 }')
316
317 IFS=$__NEWLINE_IFS
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)
322
323 if [ "$__NAME" = "$service_name" ]; then
324 break # found so leave for loop
325 fi
326 done
327 IFS=$__OLD_IFS
328
329 # check if URL or SCRIPT is given
330 __URL=$(echo "$__DATA" | grep "^http")
331 [ -z "$__URL" ] && __SCRIPT="/usr/lib/ddns/$__DATA"
332
333 eval "$1=\"$__URL\""
334 eval "$2=\"$__SCRIPT\""
335 return 0
336 }
337
338 # Calculate seconds from interval and unit
339 # $1 Name of Variable to store result in
340 # $2 Number and
341 # $3 Unit of time interval
342 get_seconds() {
343 [ $# -ne 3 ] && write_log 12 "Error calling 'get_seconds()' - wrong number of parameters"
344 case "$3" in
345 "days" ) eval "$1=$(( $2 * 86400 ))";;
346 "hours" ) eval "$1=$(( $2 * 3600 ))";;
347 "minutes" ) eval "$1=$(( $2 * 60 ))";;
348 * ) eval "$1=$2";;
349 esac
350 return 0
351 }
352
353 timeout() {
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
359 #
360 # timeout [-SIG] time [--] command args...
361 #
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.
365 #
366 # Example use
367 # timeout 5 countdown
368 #
369 # Based on notes in my "Shell Script Hints", section "Command Timeout"
370 # http://www.ict.griffith.edu.au/~anthony/info/shell/script.hints
371 #
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".
375 #
376 # It took years of occasional trials, errors and testing to get a pure bash
377 # timeout command working as well as this does.
378 #
379 #.Anthony Thyssen 6 April 2011
380 #
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
384
385 # output the script comments as docs
386 # Usage() {
387 # echo >&2 "$PROGNAME:" "$@"
388 # sed >&2 -n '/^###/q; /^#/!q; s/^#//; s/^ //; 3s/^/Usage: /; 2,$ p' "$PROGDIR/$PROGNAME"
389 # exit 10;
390 # }
391
392 SIG=-TERM
393
394 while [ $# -gt 0 ]; do
395 case "$1" in
396 --)
397 # forced end of user options
398 shift;
399 break ;;
400 # -\?|--help|--doc*)
401 # Usage ;;
402 [0-9]*)
403 TIMEOUT="$1" ;;
404 -*)
405 SIG="$1" ;;
406 *)
407 # unforced end of user options
408 break ;;
409 esac
410 shift # next option
411 done
412
413 # run main command in backgrounds and get its pid
414 "$@" &
415 command_pid=$!
416
417 # timeout sub-process abort countdown after ABORT seconds! also backgrounded
418 sleep_pid=0
419 (
420 # cleanup sleep process
421 trap 'kill -TERM $sleep_pid; return 1' 1 2 3 15
422 # sleep timeout period in background
423 sleep $TIMEOUT &
424 sleep_pid=$!
425 wait $sleep_pid
426 # Abort the command
427 kill $SIG $command_pid >/dev/null 2>&1
428 return 1
429 ) &
430 timeout_pid=$!
431
432 # Wait for main command to finished or be timed out
433 wait $command_pid
434 status=$?
435
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
439
440 # Uncomment to check if a LONG sleep still running (no sleep should be)
441 # sleep 1
442 # echo "-----------"
443 # /bin/ps j # uncomment to show if abort "sleep" is still sleeping
444
445 return $status
446 }
447
448 # verify given host and port is connectable
449 # $1 Host/IP to verify
450 # $2 Port to verify
451 verify_host_port() {
452 local __HOST=$1
453 local __PORT=$2
454 local __IP __IPV4 __IPV6 __RUNPROG __PROG __ERR
455 # return codes
456 # 1 system specific error
457 # 2 nslookup/host error
458 # 3 nc (netcat) error
459 # 4 unmatched IP version
460
461 [ $# -ne 2 ] && write_log 12 "Error calling 'verify_host_port()' - wrong number of parameters"
462
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
469 __PROG="BIND host"
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"
474 fi
475 write_log 7 "#> $__RUNPROG"
476 eval $__RUNPROG
477 __ERR=$?
478 # command error
479 [ $__ERR -gt 0 ] && {
480 write_log 3 "DNS Resolver Error - $__PROG Error '$__ERR'"
481 write_log 7 "$(cat $ERRFILE)"
482 return 2
483 }
484 # extract IP address
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 }")
491 fi
492 }
493
494 # check IP version if forced
495 if [ $force_ipversion -ne 0 ]; then
496 __ERR=0
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"
502 }
503 fi
504
505 # verify nc command
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"
511
512 # connectivity test
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
519
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"
523 eval $__RUNPROG
524 __ERR=$?
525 [ $__ERR -eq 0 ] && return 0
526 write_log 3 "Connect error - BusyBox nc (netcat) Error '$__ERR'"
527 write_log 7 "$(cat $ERRFILE)"
528 return 3
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"
532 eval $__RUNPROG
533 __ERR=$?
534 [ $__ERR -eq 0 ] && return 0
535 write_log 3 "Connect error - BusyBox nc (netcat) timeout Error '$__ERR'"
536 return 3
537 fi
538 }
539
540 # verify given DNS server if connectable
541 # $1 DNS server to verify
542 verify_dns() {
543 local __ERR=255 # last error buffer
544 local __CNT=0 # error counter
545
546 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_dns()' - wrong number of parameters"
547 write_log 7 "Verify DNS server '$1'"
548
549 while [ $__ERR -ne 0 ]; do
550 # DNS uses port 53
551 verify_host_port "$1" "53"
552 __ERR=$?
553 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
554 return $__ERR
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"
557 return $__ERR
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"
563
564 write_log 4 "Verify DNS server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
565 sleep $RETRY_SECONDS &
566 PID_SLEEP=$!
567 wait $PID_SLEEP # enable trap-handler
568 PID_SLEEP=0
569 fi
570 done
571 return 0
572 }
573
574 # analyze and verify given proxy string
575 # $1 Proxy-String to verify
576 verify_proxy() {
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
586
587 [ $# -ne 1 ] && write_log 12 "Error calling 'verify_proxy()' - wrong number of parameters"
588 write_log 7 "Verify Proxy server 'http://$1'"
589
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
598 # IPv6 split at "]:"
599 __PORT=$(echo $__TMP | awk -F "]:" '{print $2}')
600 else
601 __HOST=$(echo $__TMP | awk -F ":" '{print $1}')
602 __PORT=$(echo $__TMP | awk -F ":" '{print $2}')
603 fi
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"
608 }
609
610 while [ $__ERR -gt 0 ]; do
611 verify_host_port "$__HOST" "$__PORT"
612 __ERR=$?
613 if [ $LUCI_HELPER ]; then # no retry if called by LuCI helper script
614 return $__ERR
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"
617 return $__ERR
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"
623
624 write_log 4 "Verify Proxy server '$1' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
625 sleep $RETRY_SECONDS &
626 PID_SLEEP=$!
627 wait $PID_SLEEP # enable trap-handler
628 PID_SLEEP=0
629 fi
630 done
631 return 0
632 }
633
634 do_transfer() {
635 # $1 # URL to use
636 local __URL="$1"
637 local __ERR=0
638 local __CNT=0 # error counter
639 local __PROG __RUNPROG
640
641 [ $# -ne 1 ] && write_log 12 "Error in 'do_transfer()' - wrong number of parameters"
642
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
649 local __BINDIP
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"
656 fi
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
660 fi
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"
671 fi
672 fi
673 # disable proxy if no set (there might be .wgetrc or .curlrc or wrong environment set)
674 [ -z "$proxy" ] && __PROG="$__PROG --no-proxy"
675
676 __RUNPROG="$__PROG '$__URL'" # build final command
677 __PROG="GNU Wget" # reuse for error logging
678
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
685 local __DEVICE
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"
690 fi
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
694 fi
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"
705 fi
706 fi
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 '*'"
711 else
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"
716 fi
717
718 __RUNPROG="$__PROG '$__URL'" # build final command
719 __PROG="cURL" # reuse for error logging
720
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"
735
736 __RUNPROG="$__PROG '$__URL' 2>$ERRFILE" # build final command
737 __PROG="Busybox Wget" # reuse for error logging
738
739 else
740 write_log 13 "Neither 'Wget' nor 'cURL' installed or executable"
741 fi
742
743 while : ; do
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
749
750 write_log 3 "$__PROG Error: '$__ERR'"
751 write_log 7 "$(cat $ERRFILE)" # report error
752
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"
756 return 1
757 }
758
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"
763
764 write_log 4 "Transfer failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
765 sleep $RETRY_SECONDS &
766 PID_SLEEP=$!
767 wait $PID_SLEEP # enable trap-handler
768 PID_SLEEP=0
769 done
770 # we should never come here there must be a programming error
771 write_log 12 "Error in 'do_transfer()' - program coding error"
772 }
773
774 send_update() {
775 # $1 # IP to set at DDNS service provider
776 local __IP
777
778 [ $# -ne 1 ] && write_log 12 "Error calling 'send_update()' - wrong number of parameters"
779
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"
785 else
786 __IP="$1"
787 fi
788
789 if [ -n "$update_script" ]; then
790 write_log 7 "parsing script '$update_script'"
791 . $update_script
792 else
793 local __URL __ERR
794
795 # do replaces in URL
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:#')
799
800 do_transfer "$__URL" || return 1
801
802 write_log 7 "DDNS Provider answered:\n$(cat $DATFILE)"
803
804 return 0
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
809 fi
810 }
811
812 get_local_ip () {
813 # $1 Name of Variable to store local IP (LOCAL_IP)
814 local __CNT=0 # error counter
815 local __RUNPROG __DATA __URL __ERR
816
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'"
819
820 while : ; do
821 case $ip_source in
822 network)
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'"
829 ;;
830 interface)
831 write_log 7 "#> ifconfig $ip_interface >$DATFILE 2>$ERRFILE"
832 ifconfig $ip_interface >$DATFILE 2>$ERRFILE
833 __ERR=$?
834 if [ $__ERR -eq 0 ]; then
835 if [ $use_ipv6 -eq 0 ]; then
836 __DATA=$(awk '
837 /inet addr:/ { # Filter IPv4
838 # inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
839 $1=""; # remove inet
840 $3=""; # remove Bcast: ...
841 $4=""; # remove Mask: ...
842 FS=":"; # separator ":"
843 $0=$0; # reread to activate separator
844 $1=""; # remove addr
845 FS=" "; # set back separator to default " "
846 $0=$0; # reread to activate separator (remove whitespaces)
847 print $1; # print IPv4 addr
848 }' $DATFILE
849 )
850 else
851 __DATA=$(awk '
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
860 }' $DATFILE
861 )
862 fi
863 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected on interface '$ip_interface'"
864 else
865 write_log 3 "ifconfig Error: '$__ERR'"
866 write_log 7 "$(cat $ERRFILE)" # report error
867 fi
868 ;;
869 script)
870 write_log 7 "#> $ip_script >$DATFILE 2>$ERRFILE"
871 eval $ip_script >$DATFILE 2>$ERRFILE
872 __ERR=$?
873 if [ $__ERR -eq 0 ]; then
874 __DATA=$(cat $DATFILE)
875 [ -n "$__DATA" ] && write_log 7 "Local IP '$__DATA' detected via script '$ip_script'"
876 else
877 write_log 3 "$ip_script Error: '$__ERR'"
878 write_log 7 "$(cat $ERRFILE)" # report error
879 fi
880 ;;
881 web)
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'"
888 ;;
889 *)
890 write_log 12 "Error in 'get_local_ip()' - unhandled ip_source '$ip_source'"
891 ;;
892 esac
893 # valid data found return here
894 [ -n "$__DATA" ] && {
895 eval "$1=\"$__DATA\""
896 return 0
897 }
898
899 [ $LUCI_HELPER ] && return 1 # no retry if called by LuCI helper script
900
901 write_log 7 "Data detected:\n$(cat $DATFILE)"
902
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"
906 return 1
907 }
908
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 &
915 PID_SLEEP=$!
916 wait $PID_SLEEP # enable trap-handler
917 PID_SLEEP=0
918 done
919 # we should never come here there must be a programming error
920 write_log 12 "Error in 'get_local_ip()' - program coding error"
921 }
922
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
927 local __ERR=255
928 local __REGEX __PROG __RUNPROG __DATA
929 # return codes
930 # 1 no IP detected
931
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"
934
935 # set correct regular expression
936 [ $use_ipv6 -eq 0 ] && __REGEX="$IPV4_REGEX" || __REGEX="$IPV6_REGEX"
937
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"
943 fi
944 [ $force_dnstcp -eq 1 ] && __PROG="$__PROG -T" # force TCP
945
946 __RUNPROG="$__PROG $domain $dns_server >$DATFILE 2>$ERRFILE"
947 __PROG="BIND host"
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'"
951
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"
956 fi
957
958 while : ; do
959 write_log 7 "#> $__RUNPROG"
960 eval $__RUNPROG
961 __ERR=$?
962 if [ $__ERR -ne 0 ]; then
963 write_log 3 "$__PROG error: '$__ERR'"
964 write_log 7 "$(cat $ERRFILE)"
965 else
966 if [ "$__PROG" = "BIND host" ]; then
967 __DATA=$(cat $DATFILE | awk -F "address " '/has/ {print $2; exit}' )
968 else
969 __DATA=$(cat $DATFILE | sed -ne "/^Name:/,\$ { s/^Address[0-9 ]\{0,\}: \($__REGEX\).*$/\\1/p }" )
970 fi
971 [ -n "$__DATA" ] && {
972 write_log 7 "Registered IP '$__DATA' detected"
973 eval "$1=\"$__DATA\"" # valid data found
974 return 0 # leave here
975 }
976 write_log 4 "NO valid IP found"
977 __ERR=127
978 fi
979
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"
985 return $__ERR
986 }
987
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"
992
993 write_log 4 "Get registered/public IP for '$domain' failed - retry $__CNT/$retry_count in $RETRY_SECONDS seconds"
994 sleep $RETRY_SECONDS &
995 PID_SLEEP=$!
996 wait $PID_SLEEP # enable trap-handler
997 PID_SLEEP=0
998 done
999 # we should never come here there must be a programming error
1000 write_log 12 "Error in 'get_registered_ip()' - program coding error"
1001 }
1002
1003 get_uptime() {
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%%.*}\""
1008 }
1009
1010 trap_handler() {
1011 # $1 trap signal
1012 # $2 optional (exit status)
1013 local __PIDS __PID
1014 local __ERR=${2:-0}
1015 local __OLD_IFS=$IFS
1016 local __NEWLINE_IFS='
1017 ' # __NEWLINE_IFS
1018
1019 [ $PID_SLEEP -ne 0 ] && kill -$1 $PID_SLEEP 2>/dev/null # kill pending sleep if exist
1020
1021 case $1 in
1022 0) if [ $__ERR -eq 0 ]; then
1023 write_log 5 "PID '$$' exit normal at $(eval $DATE_PROG)\n"
1024 else
1025 write_log 4 "PID '$$' exit WITH ERROR '$__ERR' at $(eval $DATE_PROG)\n"
1026 fi ;;
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()'";;
1035 esac
1036
1037 __PIDS=$(pgrep -P $$) # get my childs (pgrep prints with "newline")
1038 IFS=$__NEWLINE_IFS
1039 for __PID in $__PIDS; do
1040 kill -$1 $__PID # terminate it
1041 done
1042 IFS=$__OLD_IFS
1043
1044 # remove out and err file
1045 [ -f $DATFILE ] && rm -f $DATFILE
1046 [ -f $ERRFILE ] && rm -f $ERRFILE
1047
1048 # exit with correct handling:
1049 # remove trap handling settings and send kill to myself
1050 trap - 0 1 2 3 15
1051 [ $1 -gt 0 ] && kill -$1 $$
1052 }
1053
1054 split_FQDN() {
1055 # $1 FQDN to split
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
1059
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'"
1063
1064 local _HOST _FDOM _CTLD _FTLD
1065 local _SET="$@" # save given function parameters
1066
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
1072 shift
1073 done
1074 set -- $_PAR # use new as function parameters
1075 _PAR="" # clear variable
1076
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
1080 shift
1081 else
1082 _CTLD="$1.$_CTLD" # Next TLD to look at
1083 shift
1084 fi
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
1089 continue
1090 }
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
1097 else
1098 _FTLD="$1.$_CTLD"
1099 shift
1100 fi
1101 _FDOM="$1"; shift
1102 }
1103 [ -n "$_FTLD" ] && break # we have something valid, break
1104 done
1105
1106 # the leftover parameters are the HOST/SUBDOMAIN
1107 while [ -n "$1" ]; do
1108 _HOST="$1 $HOST" # remember we need to invert
1109 shift
1110 done
1111 _HOST=$(echo $_HOST | tr " " ".") # insert DOT
1112
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
1118 return 0
1119 }
1120 eval "$2=''" # clear TLD
1121 eval "$3=''" # clear registrable domain
1122 eval "$4=''" # clear HOST/SUBDOMAIN
1123 return 1
1124 }