add a verbosity level that only prints on changes; allow to ignore SSL cert errors
[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
28 VERBOSE_CHANGE = 1
29 VERBOSE_FULL   = 2
30
31 def sslContext(config):
32     if config['DEFAULT']['ssl_check_cert'].lower() in ('0', 'false', 'no'):
33         context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
34         return context
35     else:
36         return None
37
38 def readConfig(fname, defSection = 'DEFAULT'):
39     config = configparser.ConfigParser()
40     with open(fname) as file:
41         stream = itertools.chain(("["+defSection+"]\n",), file)
42         config.read_file(stream)
43     return config
44
45 def getConfigDir():
46     try:
47         from xdg import BaseDirectory
48         return os.path.join(BaseDirectory.xdg_config_home, "dyn-nsupdate")
49     except ImportError:
50         return os.path.expanduser("~/.config/dyn-nsupdate")
51
52 def urlopen(url, config):
53     return urllib.request.urlopen(url, context=sslContext(config)).read().decode('utf-8').strip()
54
55 def getMyIP(family, config, methods = {}, verbose = 0):
56     '''Returns our current IP address (<family> can be "IPv4" or "IPv6"), detected as given by the configuration.
57        Additional detection methods can be supplied via <methods>.'''
58     method = config[family]['method']
59     if method == 'none':
60         return None
61     elif method == 'web':
62         server = config[family].get('server', config['DEFAULT']['server'])
63         ip = urlopen('https://'+server+'/checkip', config)
64         if verbose >= VERBOSE_FULL:
65             print("Server",server,"says my",family,"is",ip)
66         return ip
67     elif method in methods:
68         return methods[method]()
69     else:
70         raise Exception("Unsupported "+family+" detection method: "+method)
71
72 def getMyIPv4(config, verbose = 0):
73     '''Returns our current IPv4 address, detected as given by the configuration'''
74     return getMyIP("IPv4", config, verbose=verbose)
75
76 def getMyIPv6(config, verbose = 0):
77     '''Returns our current IPv6 address, detected as given by the configuration'''
78     def local():
79         out = subprocess.check_output(["ip", "addr"])
80         for line in out.decode('utf-8').split('\n'):
81             m = re.search('inet6 ([a-fA-F0-9:]+)/64 ([a-zA-Z0-9 ]*)', line)
82             if m is not None:
83                 ip = m.group(1)
84                 flags = m.group(2).split()
85                 if not 'temporary' in flags and not 'deprecated' in flags and not "link" in flags:
86                     if verbose >= VERBOSE_FULL:
87                         print("Local IPv6 detected to be",ip)
88                     return ip
89         raise Exception("Unable to detect correct local IPv6 address")
90     return getMyIP("IPv6", config, methods={'local': local}, verbose=verbose)
91
92 def getCurIP(domain, family):
93     '''Return the current IP of the given <domain>. <family> can be socket.AF_INET or socket.AF_INET6.'''
94     try:
95         addr = socket.getaddrinfo(domain, None, family=family)
96         return addr[0][4][0]
97     except socket.gaierror: # domain not found
98         return ""
99
100 def getCurIPv4(domain):
101     '''Returns the current IPv4 address of the given domain'''
102     return getCurIP(domain, socket.AF_INET)
103
104 def getCurIPv6(domain):
105     '''Returns the current IPv6 address of the given domain'''
106     return getCurIP(domain, socket.AF_INET6)
107
108 def updateDomain(server, domain, ipv4, ipv6, password, config, verbose):
109     '''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.
110        Updates ae only performed if necessary.
111        Returns True on success, False on failure.'''
112     assert ipv4 is not None or ipv6 is not None
113     
114     # check what the domain is currently mapped to
115     curIPv4 = getCurIPv4(domain)
116     curIPv6 = getCurIPv6(domain)
117     if verbose >= VERBOSE_FULL:
118         print("Current status of domain {} is: IPv4 address '{}', IPv6 address '{}'".format(domain, curIPv4, curIPv6))
119     
120     # check if there's something to do
121     needUpdate = (ipv4 is not None and curIPv4 != ipv4) or (ipv6 is not None and curIPv6 != ipv6)
122     if not needUpdate:
123         if verbose >= VERBOSE_FULL:
124             print("Everything already up-to-date, nothing to do")
125         return True
126
127     # we need to update the IP
128     url = 'https://'+server+'/update?password='+urllib.parse.quote(password)+'&domain='+urllib.parse.quote(domain)
129     expected = "good"
130     if ipv4 is not None:
131         url += '&ip='+urllib.parse.quote(ipv4)
132         expected += " "+ipv4
133     if ipv6 is not None:
134         url += '&ipv6='+urllib.parse.quote(ipv6)
135         expected += " "+ipv6
136     result = urlopen(url, config)
137     
138     # did everything go as planned?
139     if result == expected:
140         if verbose >= VERBOSE_CHANGE:
141             msg = "Successfully updated domain {} on {}:".format(domain, server)
142             if ipv4 is not None:
143                 msg += " IPv4={}".format(ipv4)
144             if ipv6 is not None:
145                 msg += " IPv6={}".format(ipv6)
146             print(msg)
147         # all went all right
148         return True
149     else:
150         # Something went wrong
151         print("Unexpected answer from server",server,"while updating",domain)
152         print(result)
153         return False
154
155 if __name__ == "__main__":
156     # allow overwriting some values on the command-line
157     parser = argparse.ArgumentParser(description='Update a domain managed by a dyn-nsupdate server')
158     parser.add_argument("-c", "--config",
159                         dest="config", default=os.path.join(getConfigDir(), "dyn-ns-client.conf"),
160                         help="The configuration file")
161     parser.add_argument("-v", "--verbose",
162                         action="count", dest="verbose",
163                         help="Be more verbose")
164     args = parser.parse_args()
165     
166     # read config
167     if not os.path.isfile(args.config):
168         raise Exception("The config file does not exist: "+args.config)
169     config = readConfig(args.config)
170
171     # get our own addresses
172     myIPv4 = getMyIPv4(config, args.verbose)
173     myIPv6 = getMyIPv6(config, args.verbose)
174
175     # update all the domains
176     exitcode = 0
177     domains = map(str.strip, config['DEFAULT']['domains'].split(','))
178     if not domains:
179         raise Exception("No domain given to update!")
180     for domain in domains:
181         if not updateDomain(config['DEFAULT']['server'], domain, myIPv4, myIPv6, config['DEFAULT']['password'], config, verbose=args.verbose):
182             exitcode = 1
183     sys.exit(exitcode)