resolve domains directly against dyn nameserver (instead of system resolver)
[dyn-nsupdate.git] / client-scripts / dyn-ns-client
1 #!/usr/bin/env python3
2 # Copyright (c) 2014, Ralf Jung <post@ralfj.de>
3 # All rights reserved.
4
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are met:
7
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.
13
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 #==============================================================================
25
26 import urllib.request, socket, sys, argparse, os, configparser, itertools, subprocess, re, ssl
27 import dns, dns.resolver
28
29 VERBOSE_CHANGE = 1
30 VERBOSE_FULL   = 2
31
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)
35         return context
36     else:
37         return None
38
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)
44     return config
45
46 def getConfigDir():
47     try:
48         from xdg import BaseDirectory
49         return os.path.join(BaseDirectory.xdg_config_home, "dyn-nsupdate")
50     except ImportError:
51         return os.path.expanduser("~/.config/dyn-nsupdate")
52
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')
56     else:
57         return urllib.request.urlopen(url).read().decode('utf-8').strip('\n')
58
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']
63     if method == 'none':
64         return None
65     elif method == 'remove':
66         return ""
67     elif method == 'web':
68         server = config[family].get('server', config['DEFAULT']['server'])
69         url = 'https://'+server+'/checkip'
70         try:
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)
76         return ip
77     elif method in methods:
78         return methods[method]()
79     else:
80         raise Exception("Unsupported "+family+" detection method: "+method)
81
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)
85
86 def getMyIPv6(config, verbose = 0):
87     '''Returns our current IPv6 address, detected as given by the configuration'''
88     def local():
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)
93             if m is not None:
94                 ip = m.group(1)
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)
99                     return ip
100         raise Exception("Unable to detect correct local IPv6 address")
101     return getMyIP("IPv6", config, methods={'local': local}, verbose=verbose)
102
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)
106     addr = addr[0][4][0]
107     res = dns.resolver.Resolver()
108     res.nameservers = [addr]
109     return res
110
111 def getCurIP(domain, rtype, res):
112     '''Return the current IP of the given <domain>. <rtype> can be A or AAAA.'''
113     try:
114         return res.query(domain, rtype)[0].address
115     except dns.exception.DNSException: # domain not found
116         return ""
117
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
123     
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))
132     
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)
135     if not needUpdate:
136         if verbose >= VERBOSE_FULL:
137             print("Everything already up-to-date, nothing to do")
138         return True
139
140     # we need to update the IP
141     url = 'https://'+server+'/update?password='+urllib.parse.quote(password)+'&domain='+urllib.parse.quote(domain)
142     expected = "good"
143     if ipv4 is not None:
144         url += '&ip='+urllib.parse.quote(ipv4)
145         expected += " "+ipv4
146     if ipv6 is not None:
147         url += '&ipv6='+urllib.parse.quote(ipv6)
148         expected += " "+ipv6
149     if verbose >= VERBOSE_FULL:
150         print("Request:",url)
151     result = urlopen(url, config)
152     
153     # did everything go as planned?
154     if result == expected:
155         if verbose >= VERBOSE_CHANGE:
156             msg = "Successfully updated domain {} on {}:".format(domain, server)
157             if ipv4 is not None:
158                 if curIPv4 == ipv4:
159                     msg += " IPv4={} (unchanged)".format(curIPv4)
160                 else:
161                     msg += " IPv4={} -> {}".format(curIPv4, ipv4)
162             if ipv4 is not None and ipv6 is not None:
163                 msg += ","
164             if ipv6 is not None:
165                 if curIPv6 == ipv6:
166                     msg += " IPv6={} (unchanged)".format(curIPv6)
167                 else:
168                     msg += " IPv6={} -> {}".format(curIPv6, ipv6)
169             print(msg)
170         # all went all right
171         return True
172     else:
173         # Something went wrong
174         print("Unexpected answer from server",server,"while updating",domain)
175         print("Got '{}', expected '{}'".format(result, expected))
176         return False
177
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()
188     
189     # read config
190     if not os.path.isfile(args.config):
191         raise Exception("The config file does not exist: "+args.config)
192     config = readConfig(args.config)
193
194     # get our own addresses
195     myIPv4 = getMyIPv4(config, args.verbose)
196     myIPv6 = getMyIPv6(config, args.verbose)
197
198     # update all the domains
199     exitcode = 0
200     domains = map(str.strip, config['DEFAULT']['domains'].split(','))
201     if not domains:
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):
205             exitcode = 1
206     sys.exit(exitcode)