2 # Copyright (c) 2014, Ralf Jung <post@ralfj.de>
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are met:
8 # 1. Redistributions of source code must retain the above copyright notice, this
9 # list of conditions and the following disclaimer.
10 # 2. Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation
12 # and/or other materials provided with the distribution.
14 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
18 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
21 # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 #==============================================================================
26 import urllib.request, socket, sys, argparse, os, configparser, itertools, subprocess, re, ssl
27 import dns, dns.resolver
32 def sslContext(config):
33 if config['DEFAULT'].get('ssl_check_cert', 'yes').lower() in ('0', 'false', 'no'):
34 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
39 def readConfig(fname, defSection = 'DEFAULT'):
40 config = configparser.ConfigParser()
41 with open(fname) as file:
42 stream = itertools.chain(("["+defSection+"]\n",), file)
43 config.read_file(stream)
48 from xdg import BaseDirectory
49 return os.path.join(BaseDirectory.xdg_config_home, "dyn-nsupdate")
51 return os.path.expanduser("~/.config/dyn-nsupdate")
53 def urlopen(url, config):
54 if sys.version_info >= (3, 4, 3):
55 return urllib.request.urlopen(url, context=sslContext(config)).read().decode('utf-8').strip('\n')
57 return urllib.request.urlopen(url).read().decode('utf-8').strip('\n')
59 def getMyIP(family, config, methods = {}, verbose = 0):
60 '''Returns our current IP address (<family> can be "IPv4" or "IPv6"), detected as given by the configuration.
61 Additional detection methods can be supplied via <methods>.'''
62 method = config[family]['method']
65 elif method == 'remove':
68 server = config[family].get('server', config['DEFAULT']['server'])
69 url = 'https://'+server+'/checkip'
71 ip = urlopen(url, config)
72 except urllib.error.URLError:
73 raise Exception("Error fetching {}, make sure the URL is correct and the internet connection actually works.".format(url))
74 if verbose >= VERBOSE_FULL:
75 print("Server",server,"says my",family,"is",ip)
77 elif method in methods:
78 return methods[method]()
80 raise Exception("Unsupported "+family+" detection method: "+method)
82 def getMyIPv4(config, verbose = 0):
83 '''Returns our current IPv4 address, detected as given by the configuration'''
84 return getMyIP("IPv4", config, verbose=verbose)
86 def getMyIPv6(config, verbose = 0):
87 '''Returns our current IPv6 address, detected as given by the configuration'''
89 device = config["IPv6"].get("device")
90 out = subprocess.check_output(["ip", "addr", "show"] + ([] if device is None else ["dev", device]))
91 for line in out.decode('utf-8').split('\n'):
92 m = re.search('inet6 ([a-fA-F0-9:]+)/64 ([a-zA-Z0-9 ]*)', line)
95 flags = m.group(2).split()
96 if not 'temporary' in flags and not 'deprecated' in flags and not "link" in flags:
97 if verbose >= VERBOSE_FULL:
98 print("Local IPv6 detected to be",ip)
100 raise Exception("Unable to detect correct local IPv6 address")
101 return getMyIP("IPv6", config, methods={'local': local}, verbose=verbose)
103 def getResolver(server):
104 '''Return a resovler with the given server (defined by DNS name)'''
105 addr = socket.getaddrinfo(server, None, family=socket.AF_INET)
107 res = dns.resolver.Resolver()
108 res.nameservers = [addr]
111 def getCurIP(domain, rtype, res):
112 '''Return the current IP of the given <domain>. <rtype> can be A or AAAA.'''
114 return res.query(domain, rtype)[0].address
115 except dns.exception.DNSException: # domain not found
118 def updateDomain(server, domain, ipv4, ipv6, password, config, verbose):
119 '''Update the given domain, using the server, password. ipv4 or ipv6 can be None to not update that record, or strings with the respective addresses.
120 Updates ae only performed if necessary.
121 Returns True on success, False on failure.'''
122 assert ipv4 is not None or ipv6 is not None
124 # check what the domain is currently mapped to
125 res = getResolver(server)
126 if verbose >= VERBOSE_FULL:
127 print("Resolving names using {}".format(res.nameservers))
128 curIPv4 = getCurIP(domain, 'A', res)
129 curIPv6 = getCurIP(domain, 'AAAA', res)
130 if verbose >= VERBOSE_FULL:
131 print("Current status of domain {} is: IPv4 address '{}', IPv6 address '{}'".format(domain, curIPv4, curIPv6))
133 # check if there's something to do
134 needUpdate = (ipv4 is not None and curIPv4 != ipv4) or (ipv6 is not None and curIPv6 != ipv6)
136 if verbose >= VERBOSE_FULL:
137 print("Everything already up-to-date, nothing to do")
140 # we need to update the IP
141 url = 'https://'+server+'/update?password='+urllib.parse.quote(password)+'&domain='+urllib.parse.quote(domain)
144 url += '&ip='+urllib.parse.quote(ipv4)
147 url += '&ipv6='+urllib.parse.quote(ipv6)
149 if verbose >= VERBOSE_FULL:
150 print("Request:",url)
151 result = urlopen(url, config)
153 # did everything go as planned?
154 if result == expected:
155 if verbose >= VERBOSE_CHANGE:
156 msg = "Successfully updated domain {} on {}:".format(domain, server)
159 msg += " IPv4={} (unchanged)".format(curIPv4)
161 msg += " IPv4={} -> {}".format(curIPv4, ipv4)
162 if ipv4 is not None and ipv6 is not None:
166 msg += " IPv6={} (unchanged)".format(curIPv6)
168 msg += " IPv6={} -> {}".format(curIPv6, ipv6)
173 # Something went wrong
174 print("Unexpected answer from server",server,"while updating",domain)
175 print("Got '{}', expected '{}'".format(result, expected))
178 if __name__ == "__main__":
179 # allow overwriting some values on the command-line
180 parser = argparse.ArgumentParser(description='Update a domain managed by a dyn-nsupdate server')
181 parser.add_argument("-c", "--config",
182 dest="config", default=os.path.join(getConfigDir(), "dyn-ns-client.conf"),
183 help="The configuration file")
184 parser.add_argument("-v", "--verbose",
185 action="count", dest="verbose", default=0,
186 help="Be more verbose")
187 args = parser.parse_args()
190 if not os.path.isfile(args.config):
191 raise Exception("The config file does not exist: "+args.config)
192 config = readConfig(args.config)
194 # get our own addresses
195 myIPv4 = getMyIPv4(config, args.verbose)
196 myIPv6 = getMyIPv6(config, args.verbose)
198 # update all the domains
200 domains = map(str.strip, config['DEFAULT']['domains'].split(','))
202 raise Exception("No domain given to update!")
203 for domain in domains:
204 if not updateDomain(config['DEFAULT']['server'], domain, myIPv4, myIPv6, config['DEFAULT']['password'], config, verbose=args.verbose):