dynamic_dns_updater.sh 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #!/bin/sh
  2. # /usr/lib/ddns/dynamic_dns_updater.sh
  3. #
  4. #.Distributed under the terms of the GNU General Public License (GPL) version 2.0
  5. # Original written by Eric Paul Bishop, January 2008
  6. # (Loosely) based on the script on the one posted by exobyte in the forums here:
  7. # http://forum.openwrt.org/viewtopic.php?id=14040
  8. # extended and partial rewritten
  9. #.2014-2017 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
  10. #
  11. # variables in small chars are read from /etc/config/ddns
  12. # variables in big chars are defined inside these scripts as global vars
  13. # variables in big chars beginning with "__" are local defined inside functions only
  14. # set -vx #script debugger
  15. . $(dirname $0)/dynamic_dns_functions.sh # global vars are also defined here
  16. usage() {
  17. cat << EOF
  18. Usage:
  19. $MYPROG [options] -- command
  20. Commands:
  21. start Start SECTION or NETWORK or all
  22. stop Stop NETWORK or all
  23. Parameters:
  24. -n NETWORK Start/Stop sections in background monitoring NETWORK, force VERBOSE=0
  25. -S SECTION SECTION to start
  26. use either -N NETWORK or -S SECTION
  27. -h show this help and exit
  28. -V show version and exit
  29. -v LEVEL VERBOSE=LEVEL (default 1)
  30. '0' NO output to console
  31. '1' output to console
  32. '2' output to console AND logfile
  33. + run once WITHOUT retry on error
  34. '3' output to console AND logfile
  35. + run once WITHOUT retry on error
  36. + NOT sending update to DDNS service
  37. EOF
  38. }
  39. usage_err() {
  40. printf %s\\n "$MYPROG: $@" >&2
  41. usage >&2
  42. exit 1
  43. }
  44. while getopts ":hv:n:S:V" OPT; do
  45. case "$OPT" in
  46. h) usage; exit 0;;
  47. v) VERBOSE=$OPTARG;;
  48. n) NETWORK=$OPTARG;;
  49. S) SECTION_ID=$OPTARG;;
  50. V) printf %s\\n "ddns-scripts $VERSION"; exit 0;;
  51. :) usage_err "option -$OPTARG missing argument";;
  52. \?) usage_err "invalid option -$OPTARG";;
  53. *) usage_err "unhandled option -$OPT $OPTARG";;
  54. esac
  55. done
  56. shift $((OPTIND - 1 )) # OPTIND is 1 based
  57. [ -n "$NETWORK" -a -n "$SECTION_ID" ] && usage_err "use either option '-N' or '-S' not both"
  58. [ $# -eq 0 ] && usage_err "missing command"
  59. [ $# -gt 1 ] && usage_err "to much commands"
  60. case "$1" in
  61. start)
  62. if [ -n "$NETWORK" ]; then
  63. start_daemon_for_all_ddns_sections "$NETWORK"
  64. exit 0
  65. fi
  66. if [ -z "$SECTION_ID" ]; then
  67. start_daemon_for_all_ddns_sections
  68. exit 0
  69. fi
  70. ;;
  71. stop)
  72. if [ -n "$INTERFACE" ]; then
  73. stop_daemon_for_all_ddns_sections "$NETWORK"
  74. exit 0
  75. else
  76. stop_daemon_for_all_ddns_sections
  77. exit 0
  78. fi
  79. exit 1
  80. ;;
  81. reload)
  82. killall -1 dynamic_dns_updater.sh 2>/dev/null
  83. exit $?
  84. ;;
  85. *) usage_err "unknown command - $1";;
  86. esac
  87. # set file names
  88. PIDFILE="$ddns_rundir/$SECTION_ID.pid" # Process ID file
  89. UPDFILE="$ddns_rundir/$SECTION_ID.update" # last update successful send (system uptime)
  90. DATFILE="$ddns_rundir/$SECTION_ID.dat" # save stdout data of WGet and other extern programs called
  91. ERRFILE="$ddns_rundir/$SECTION_ID.err" # save stderr output of WGet and other extern programs called
  92. LOGFILE="$ddns_logdir/$SECTION_ID.log" # log file
  93. # VERBOSE > 1 delete logfile if exist to create an empty one
  94. # only with this data of this run for easier diagnostic
  95. # new one created by write_log function
  96. [ $VERBOSE -gt 1 -a -f $LOGFILE ] && rm -f $LOGFILE
  97. # TRAP handler
  98. trap "trap_handler 0 \$?" 0 # handle script exit with exit status
  99. trap "trap_handler 1" 1 # SIGHUP Hangup / reload config
  100. trap "trap_handler 2" 2 # SIGINT Terminal interrupt
  101. trap "trap_handler 3" 3 # SIGQUIT Terminal quit
  102. # trap "trap_handler 9" 9 # SIGKILL no chance to trap
  103. trap "trap_handler 15" 15 # SIGTERM Termination
  104. ################################################################################
  105. # Leave this comment here, to clearly document variable names that are expected/possible
  106. # Use load_all_config_options to load config options, which is a much more flexible solution.
  107. #
  108. # config_load "ddns"
  109. # config_get <variable> $SECTION_ID <option>
  110. #
  111. # defined options (also used as variable):
  112. #
  113. # enabled self-explanatory
  114. # interface network interface used by hotplug.d i.e. 'wan' or 'wan6'
  115. #
  116. # service_name Which DDNS service do you use or "custom"
  117. # update_url URL to use to update your "custom" DDNS service
  118. # update_script SCRIPT to use to update your "custom" DDNS service
  119. #
  120. # lookup_host FQDN of ONE of your at DDNS service defined host / required to validate if IP update happen/necessary
  121. # domain Nomally your DDNS hostname / replace [DOMAIN] in update_url
  122. # username Username of your DDNS service account / urlenceded and replace [USERNAME] in update_url
  123. # password Password of your DDNS service account / urlencoded and replace [PASSWORD] in update_url
  124. # param_enc Optional parameter for (later) usage / urlencoded and replace [PARAMENC] in update_url
  125. # param_opt Optional parameter for (later) usage / replace [PARAMOPT] in update_url
  126. #
  127. # use_https use HTTPS to update DDNS service
  128. # cacert file or directory where HTTPS can find certificates to verify server; 'IGNORE' ignore check of server certificate
  129. #
  130. # use_syslog log activity to syslog
  131. #
  132. # ip_source source to detect current local IP ('network' or 'web' or 'script' or 'interface')
  133. # ip_network local defined network to read IP from i.e. 'wan' or 'wan6'
  134. # ip_url URL to read local address from i.e. http://checkip.dyndns.com/ or http://checkipv6.dyndns.com/
  135. # ip_script full path and name of your script to detect local IP
  136. # ip_interface physical interface to use for detecting
  137. #
  138. # check_interval check for changes every !!! checks below 10 minutes make no sense because the Internet
  139. # check_unit 'days' 'hours' 'minutes' !!! needs about 5-10 minutes to sync an IP-change for an DNS entry
  140. #
  141. # force_interval force to send an update to your service if no change was detected
  142. # force_unit 'days' 'hours' 'minutes' !!! force_interval="0" runs this script once for use i.e. with cron
  143. #
  144. # retry_interval if error was detected retry in
  145. # retry_unit 'days' 'hours' 'minutes' 'seconds'
  146. # retry_count number of retries before scripts stops
  147. #
  148. # use_ipv6 detecting/sending IPv6 address
  149. # force_ipversion force usage of IPv4 or IPv6 for the whole detection and update communication
  150. # dns_server using a non default dns server to get Registered IP from Internet
  151. # force_dnstcp force communication with DNS server via TCP instead of default UDP
  152. # proxy using a proxy for communication !!! ALSO used to detect local IP via web => return proxy's IP !!!
  153. # use_logfile self-explanatory "/var/log/ddns/$SECTION_ID.log"
  154. # is_glue the record that should be updated is a glue record
  155. #
  156. # some functionality needs
  157. # - GNU Wget or cURL installed for sending updates to DDNS service
  158. # - BIND host installed to detect Registered IP
  159. #
  160. ################################################################################
  161. load_all_config_options "ddns" "$SECTION_ID"
  162. ERR_LAST=$? # save return code - equal 0 if SECTION_ID found
  163. # set defaults if not defined
  164. [ -z "$enabled" ] && enabled=0
  165. [ -z "$retry_count" ] && retry_count=0 # endless retry
  166. [ -z "$use_syslog" ] && use_syslog=2 # syslog "Notice"
  167. [ -z "$use_https" ] && use_https=0 # not use https
  168. [ -z "$use_logfile" ] && use_logfile=1 # use logfile by default
  169. [ -z "$use_ipv6" ] && use_ipv6=0 # use IPv4 by default
  170. [ -z "$force_ipversion" ] && force_ipversion=0 # default let system decide
  171. [ -z "$force_dnstcp" ] && force_dnstcp=0 # default UDP
  172. [ -z "$ip_source" ] && ip_source="network"
  173. [ -z "$is_glue" ] && is_glue=0 # default the ddns record is not a glue record
  174. [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 0 ] && ip_network="wan" # IPv4: default wan
  175. [ "$ip_source" = "network" -a -z "$ip_network" -a $use_ipv6 -eq 1 ] && ip_network="wan6" # IPv6: default wan6
  176. [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 0 ] && ip_url="http://checkip.dyndns.com"
  177. [ "$ip_source" = "web" -a -z "$ip_url" -a $use_ipv6 -eq 1 ] && ip_url="http://checkipv6.dyndns.com"
  178. [ "$ip_source" = "interface" -a -z "$ip_interface" ] && ip_interface="eth1"
  179. # SECTION_ID does not exists
  180. [ $ERR_LAST -ne 0 ] && {
  181. [ $VERBOSE -le 1 ] && VERBOSE=2 # force console out and logfile output
  182. [ -f $LOGFILE ] && rm -f $LOGFILE # clear logfile before first entry
  183. write_log 7 "************ ************** ************** **************"
  184. write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
  185. write_log 7 "ddns version : $VERSION"
  186. write_log 7 "uci configuration:\n$(uci -q show ddns | grep '=service' | sort)"
  187. write_log 14 "Service section '$SECTION_ID' not defined"
  188. }
  189. write_log 7 "************ ************** ************** **************"
  190. write_log 5 "PID '$$' started at $(eval $DATE_PROG)"
  191. write_log 7 "ddns version : $VERSION"
  192. write_log 7 "uci configuration:\n$(uci -q show ddns.$SECTION_ID | sort)"
  193. # write_log 7 "ddns version : $(opkg list-installed ddns-scripts | cut -d ' ' -f 3)"
  194. case $VERBOSE in
  195. 0) write_log 7 "verbose mode : 0 - run normal, NO console output";;
  196. 1) write_log 7 "verbose mode : 1 - run normal, console mode";;
  197. 2) write_log 7 "verbose mode : 2 - run once, NO retry on error";;
  198. 3) write_log 7 "verbose mode : 3 - run once, NO retry on error, NOT sending update";;
  199. *) write_log 14 "error detecting VERBOSE '$VERBOSE'";;
  200. esac
  201. # check enabled state otherwise we don't need to continue
  202. [ $enabled -eq 0 ] && write_log 14 "Service section disabled!"
  203. # determine what update url we're using if a service_name is supplied
  204. # otherwise update_url is set inside configuration (custom update url)
  205. # or update_script is set inside configuration (custom update script)
  206. [ -n "$service_name" ] && get_service_data update_url update_script UPD_ANSWER
  207. [ -z "$update_url" -a -z "$update_script" ] && write_log 14 "No update_url found/defined or no update_script found/defined!"
  208. [ -n "$update_script" -a ! -f "$update_script" ] && write_log 14 "Custom update_script not found!"
  209. # temporary needed to convert existing uci settings
  210. [ -z "$lookup_host" ] && {
  211. uci -q set ddns.$SECTION_ID.lookup_host="$domain"
  212. uci -q commit ddns
  213. lookup_host="$domain"
  214. }
  215. # later versions only check if configured correctly
  216. # without lookup host and possibly other required options we can do nothing for you
  217. [ -z "$lookup_host" ] && write_log 14 "Service section not configured correctly! Missing 'lookup_host'"
  218. [ -n "$update_url" ] && {
  219. # only check if update_url is given, update_scripts have to check themselves
  220. [ -z "$domain" ] && $(echo "$update_url" | grep "\[DOMAIN\]" >/dev/null 2>&1) && \
  221. write_log 14 "Service section not configured correctly! Missing 'domain'"
  222. [ -z "$username" ] && $(echo "$update_url" | grep "\[USERNAME\]" >/dev/null 2>&1) && \
  223. write_log 14 "Service section not configured correctly! Missing 'username'"
  224. [ -z "$password" ] && $(echo "$update_url" | grep "\[PASSWORD\]" >/dev/null 2>&1) && \
  225. write_log 14 "Service section not configured correctly! Missing 'password'"
  226. [ -z "$param_enc" ] && $(echo "$update_url" | grep "\[PARAMENC\]" >/dev/null 2>&1) && \
  227. write_log 14 "Service section not configured correctly! Missing 'param_enc'"
  228. [ -z "$param_opt" ] && $(echo "$update_url" | grep "\[PARAMOPT\]" >/dev/null 2>&1) && \
  229. write_log 14 "Service section not configured correctly! Missing 'param_opt'"
  230. }
  231. # url encode username (might be email or something like this)
  232. # and password (might have special chars for security reason)
  233. # and optional parameter "param_enc"
  234. [ -n "$username" ] && urlencode URL_USER "$username"
  235. [ -n "$password" ] && urlencode URL_PASS "$password"
  236. [ -n "$param_enc" ] && urlencode URL_PENC "$param_enc"
  237. # verify ip_source 'script' if script is configured and executable
  238. if [ "$ip_source" = "script" ]; then
  239. set -- $ip_script #handling script with parameters, we need a trick
  240. [ -z "$1" ] && write_log 14 "No script defined to detect local IP!"
  241. [ -x "$1" ] || write_log 14 "Script to detect local IP not executable!"
  242. fi
  243. # compute update interval in seconds
  244. get_seconds CHECK_SECONDS ${check_interval:-10} ${check_unit:-"minutes"} # default 10 min
  245. get_seconds FORCE_SECONDS ${force_interval:-72} ${force_unit:-"hours"} # default 3 days
  246. get_seconds RETRY_SECONDS ${retry_interval:-60} ${retry_unit:-"seconds"} # default 60 sec
  247. [ $CHECK_SECONDS -lt 300 ] && CHECK_SECONDS=300 # minimum 5 minutes
  248. [ $FORCE_SECONDS -gt 0 -a $FORCE_SECONDS -lt $CHECK_SECONDS ] && FORCE_SECONDS=$CHECK_SECONDS # FORCE_SECONDS >= CHECK_SECONDS or 0
  249. write_log 7 "check interval: $CHECK_SECONDS seconds"
  250. write_log 7 "force interval: $FORCE_SECONDS seconds"
  251. write_log 7 "retry interval: $RETRY_SECONDS seconds"
  252. write_log 7 "retry counter : $retry_count times"
  253. # kill old process if it exists & set new pid file
  254. stop_section_processes "$SECTION_ID"
  255. [ $? -gt 0 ] && write_log 7 "'SIGTERM' was send to old process" || write_log 7 "No old process"
  256. echo $$ > $PIDFILE
  257. # determine when the last update was
  258. # the following lines should prevent multiple updates if hotplug fires multiple startups
  259. # as described in Ticket #7820, but did not function if never an update take place
  260. # i.e. after a reboot (/var is linked to /tmp)
  261. # using uptime as reference because date might not be updated via NTP client
  262. get_uptime CURR_TIME
  263. [ -e "$UPDFILE" ] && {
  264. LAST_TIME=$(cat $UPDFILE)
  265. # check also LAST > CURR because link of /var/run to /tmp might be removed
  266. # i.e. boxes with larger filesystems
  267. [ -z "$LAST_TIME" ] && LAST_TIME=0
  268. [ $LAST_TIME -gt $CURR_TIME ] && LAST_TIME=0
  269. }
  270. if [ $LAST_TIME -eq 0 ]; then
  271. write_log 7 "last update: never"
  272. else
  273. EPOCH_TIME=$(( $(date +%s) - $CURR_TIME + $LAST_TIME ))
  274. EPOCH_TIME="date -d @$EPOCH_TIME +'$ddns_dateformat'"
  275. write_log 7 "last update: $(eval $EPOCH_TIME)"
  276. fi
  277. # verify DNS server
  278. [ -n "$dns_server" ] && verify_dns "$dns_server"
  279. # verify Proxy server and set environment
  280. [ -n "$proxy" ] && {
  281. verify_proxy "$proxy" && {
  282. # everything ok set proxy
  283. export HTTP_PROXY="http://$proxy"
  284. export HTTPS_PROXY="http://$proxy"
  285. export http_proxy="http://$proxy"
  286. export https_proxy="http://$proxy"
  287. }
  288. }
  289. # let's check if there is already an IP registered on the web
  290. get_registered_ip REGISTERED_IP "NO_RETRY"
  291. ERR_LAST=$?
  292. # No error or No IP set otherwise retry
  293. [ $ERR_LAST -eq 0 -o $ERR_LAST -eq 127 ] || get_registered_ip REGISTERED_IP
  294. # on IPv6 we use expanded version to be shure when comparing
  295. [ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP
  296. # loop endlessly, checking ip every check_interval and forcing an updating once every force_interval
  297. write_log 6 "Starting main loop at $(eval $DATE_PROG)"
  298. while : ; do
  299. get_local_ip LOCAL_IP # read local IP
  300. [ $use_ipv6 -eq 1 ] && expand_ipv6 "$LOCAL_IP" LOCAL_IP # on IPv6 we use expanded version
  301. # prepare update
  302. # never updated or forced immediate then NEXT_TIME = 0
  303. [ $FORCE_SECONDS -eq 0 -o $LAST_TIME -eq 0 ] \
  304. && NEXT_TIME=0 \
  305. || NEXT_TIME=$(( $LAST_TIME + $FORCE_SECONDS ))
  306. get_uptime CURR_TIME # get current uptime
  307. # send update when current time > next time or local ip different from registered ip
  308. if [ $CURR_TIME -ge $NEXT_TIME -o "$LOCAL_IP" != "$REGISTERED_IP" ]; then
  309. if [ $VERBOSE -gt 2 ]; then
  310. write_log 7 "Verbose Mode: $VERBOSE - NO UPDATE send"
  311. elif [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
  312. write_log 7 "Update needed - L: '$LOCAL_IP' <> R: '$REGISTERED_IP'"
  313. else
  314. write_log 7 "Forced Update - L: '$LOCAL_IP' == R: '$REGISTERED_IP'"
  315. fi
  316. ERR_LAST=0
  317. [ $VERBOSE -lt 3 ] && {
  318. # only send if VERBOSE < 3
  319. send_update "$LOCAL_IP"
  320. ERR_LAST=$? # save return value
  321. }
  322. # error sending local IP to provider
  323. # we have no communication error (handled inside send_update/do_transfer)
  324. # but update was not recognized
  325. # do NOT retry after RETRY_SECONDS, do retry after CHECK_SECONDS
  326. # to early retrys will block most DDNS provider
  327. # providers answer is checked inside send_update() function
  328. if [ $ERR_LAST -eq 0 ]; then
  329. get_uptime LAST_TIME # we send update, so
  330. echo $LAST_TIME > $UPDFILE # save LASTTIME to file
  331. [ "$LOCAL_IP" != "$REGISTERED_IP" ] \
  332. && write_log 6 "Update successful - IP '$LOCAL_IP' send" \
  333. || write_log 6 "Forced update successful - IP: '$LOCAL_IP' send"
  334. elif [ $ERR_LAST -eq 127 ]; then
  335. write_log 3 "No update send to DDNS Provider"
  336. else
  337. write_log 3 "IP update not accepted by DDNS Provider"
  338. fi
  339. fi
  340. # now we wait for check interval before testing if update was recognized
  341. # only sleep if VERBOSE <= 2 because otherwise nothing was send
  342. [ $VERBOSE -le 2 ] && {
  343. write_log 7 "Waiting $CHECK_SECONDS seconds (Check Interval)"
  344. sleep $CHECK_SECONDS &
  345. PID_SLEEP=$!
  346. wait $PID_SLEEP # enable trap-handler
  347. PID_SLEEP=0
  348. } || write_log 7 "Verbose Mode: $VERBOSE - NO Check Interval waiting"
  349. REGISTERED_IP="" # clear variable
  350. get_registered_ip REGISTERED_IP # get registered/public IP
  351. [ $use_ipv6 -eq 1 ] && expand_ipv6 "$REGISTERED_IP" REGISTERED_IP # on IPv6 we use expanded version
  352. # IP's are still different
  353. if [ "$LOCAL_IP" != "$REGISTERED_IP" ]; then
  354. if [ $VERBOSE -le 1 ]; then # VERBOSE <=1 then retry
  355. ERR_UPDATE=$(( $ERR_UPDATE + 1 ))
  356. [ $retry_count -gt 0 -a $ERR_UPDATE -gt $retry_count ] && \
  357. write_log 14 "Updating IP at DDNS provider failed after $retry_count retries"
  358. write_log 4 "Updating IP at DDNS provider failed - starting retry $ERR_UPDATE/$retry_count"
  359. continue # loop to beginning
  360. else
  361. write_log 4 "Updating IP at DDNS provider failed"
  362. write_log 7 "Verbose Mode: $VERBOSE - NO retry"; exit 1
  363. fi
  364. else
  365. # we checked successful the last update
  366. ERR_UPDATE=0 # reset error counter
  367. fi
  368. # force_update=0 or VERBOSE > 1 - leave here
  369. [ $VERBOSE -gt 1 ] && write_log 7 "Verbose Mode: $VERBOSE - NO reloop"
  370. [ $FORCE_SECONDS -eq 0 ] && write_log 6 "Configured to run once"
  371. [ $VERBOSE -gt 1 -o $FORCE_SECONDS -eq 0 ] && exit 0
  372. write_log 6 "Rerun IP check at $(eval $DATE_PROG)"
  373. done
  374. # we should never come here there must be a programming error
  375. write_log 12 "Error in 'dynamic_dns_updater.sh - program coding error"