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