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
31 def sslContext(config):
32 if config['DEFAULT'].get('ssl_check_cert', 'yes').lower() in ('0', 'false', 'no'):
33 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
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)
47 from xdg import BaseDirectory
48 return os.path.join(BaseDirectory.xdg_config_home, "dyn-nsupdate")
50 return os.path.expanduser("~/.config/dyn-nsupdate")
52 def urlopen(url, config):
53 if sys.version_info >= (3, 4, 3):
54 return urllib.request.urlopen(url, context=sslContext(config)).read().decode('utf-8').strip('\n')
56 return urllib.request.urlopen(url).read().decode('utf-8').strip('\n')
58 def getMyIP(family, config, methods = {}, verbose = 0):
59 '''Returns our current IP address (<family> can be "IPv4" or "IPv6"), detected as given by the configuration.
60 Additional detection methods can be supplied via <methods>.'''
61 method = config[family]['method']
64 elif method == 'remove':
67 server = config[family].get('server', config['DEFAULT']['server'])
68 url = 'https://'+server+'/checkip'
70 ip = urlopen(url, config)
71 except urllib.error.URLError:
72 raise Exception("Error fetching {}, make sure the URL is correct and the internet connection actually works.".format(url))
73 if verbose >= VERBOSE_FULL:
74 print("Server",server,"says my",family,"is",ip)
76 elif method in methods:
77 return methods[method]()
79 raise Exception("Unsupported "+family+" detection method: "+method)
81 def getMyIPv4(config, verbose = 0):
82 '''Returns our current IPv4 address, detected as given by the configuration'''
83 return getMyIP("IPv4", config, verbose=verbose)
85 def getMyIPv6(config, verbose = 0):
86 '''Returns our current IPv6 address, detected as given by the configuration'''
88 device = config["IPv6"].get("device")
89 out = subprocess.check_output(["ip", "addr", "show"] + ([] if device is None else ["dev", device]))
90 for line in out.decode('utf-8').split('\n'):
91 m = re.search('inet6 ([a-fA-F0-9:]+)/64 ([a-zA-Z0-9 ]*)', line)
94 flags = m.group(2).split()
95 if not 'temporary' in flags and not 'deprecated' in flags and not "link" in flags:
96 if verbose >= VERBOSE_FULL:
97 print("Local IPv6 detected to be",ip)
99 raise Exception("Unable to detect correct local IPv6 address")
100 return getMyIP("IPv6", config, methods={'local': local}, verbose=verbose)
102 def getCurIP(domain, family):
103 '''Return the current IP of the given <domain>. <family> can be socket.AF_INET or socket.AF_INET6.'''
105 addr = socket.getaddrinfo(domain, None, family=family)
107 except socket.gaierror: # domain not found
110 def getCurIPv4(domain):
111 '''Returns the current IPv4 address of the given domain'''
112 return getCurIP(domain, socket.AF_INET)
114 def getCurIPv6(domain):
115 '''Returns the current IPv6 address of the given domain'''
116 return getCurIP(domain, socket.AF_INET6)
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 curIPv4 = getCurIPv4(domain)
126 curIPv6 = getCurIPv6(domain)
127 if verbose >= VERBOSE_FULL:
128 print("Current status of domain {} is: IPv4 address '{}', IPv6 address '{}'".format(domain, curIPv4, curIPv6))
130 # check if there's something to do
131 needUpdate = (ipv4 is not None and curIPv4 != ipv4) or (ipv6 is not None and curIPv6 != ipv6)
133 if verbose >= VERBOSE_FULL:
134 print("Everything already up-to-date, nothing to do")
137 # we need to update the IP
138 url = 'https://'+server+'/update?password='+urllib.parse.quote(password)+'&domain='+urllib.parse.quote(domain)
141 url += '&ip='+urllib.parse.quote(ipv4)
144 url += '&ipv6='+urllib.parse.quote(ipv6)
146 if verbose >= VERBOSE_FULL:
147 print("Request:",url)
148 result = urlopen(url, config)
150 # did everything go as planned?
151 if result == expected:
152 if verbose >= VERBOSE_CHANGE:
153 msg = "Successfully updated domain {} on {}:".format(domain, server)
156 msg += " IPv4={} (unchanged)".format(curIPv4)
158 msg += " IPv4={} -> {}".format(curIPv4, ipv4)
159 if ipv4 is not None and ipv6 is not None:
163 msg += " IPv6={} (unchanged)".format(curIPv6)
165 msg += " IPv6={} -> {}".format(curIPv6, ipv6)
170 # Something went wrong
171 print("Unexpected answer from server",server,"while updating",domain)
172 print("Got '{}', expected '{}'".format(result, expected))
175 if __name__ == "__main__":
176 # allow overwriting some values on the command-line
177 parser = argparse.ArgumentParser(description='Update a domain managed by a dyn-nsupdate server')
178 parser.add_argument("-c", "--config",
179 dest="config", default=os.path.join(getConfigDir(), "dyn-ns-client.conf"),
180 help="The configuration file")
181 parser.add_argument("-v", "--verbose",
182 action="count", dest="verbose", default=0,
183 help="Be more verbose")
184 args = parser.parse_args()
187 if not os.path.isfile(args.config):
188 raise Exception("The config file does not exist: "+args.config)
189 config = readConfig(args.config)
191 # get our own addresses
192 myIPv4 = getMyIPv4(config, args.verbose)
193 myIPv6 = getMyIPv6(config, args.verbose)
195 # update all the domains
197 domains = map(str.strip, config['DEFAULT']['domains'].split(','))
199 raise Exception("No domain given to update!")
200 for domain in domains:
201 if not updateDomain(config['DEFAULT']['server'], domain, myIPv4, myIPv6, config['DEFAULT']['password'], config, verbose=args.verbose):