+import urllib.request, socket, sys, argparse, os, configparser, itertools, subprocess, re, ssl
+
+VERBOSE_CHANGE = 1
+VERBOSE_FULL = 2
+
+def sslContext(config):
+ if config['DEFAULT'].get('ssl_check_cert', 'yes').lower() in ('0', 'false', 'no'):
+ context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+ return context
+ else:
+ return None
+
+def readConfig(fname, defSection = 'DEFAULT'):
+ config = configparser.ConfigParser()
+ with open(fname) as file:
+ stream = itertools.chain(("["+defSection+"]\n",), file)
+ config.read_file(stream)
+ return config
+
+def getConfigDir():
+ try:
+ from xdg import BaseDirectory
+ return os.path.join(BaseDirectory.xdg_config_home, "dyn-nsupdate")
+ except ImportError:
+ return os.path.expanduser("~/.config/dyn-nsupdate")
+
+def urlopen(url, config):
+ if sys.version_info >= (3, 4, 3):
+ return urllib.request.urlopen(url, context=sslContext(config)).read().decode('utf-8').strip()
+ else:
+ return urllib.request.urlopen(url).read().decode('utf-8').strip()
+
+def getMyIP(family, config, methods = {}, verbose = 0):
+ '''Returns our current IP address (<family> can be "IPv4" or "IPv6"), detected as given by the configuration.
+ Additional detection methods can be supplied via <methods>.'''
+ method = config[family]['method']
+ if method == 'none':
+ return None
+ elif method == 'web':
+ server = config[family].get('server', config['DEFAULT']['server'])
+ ip = urlopen('https://'+server+'/checkip', config)
+ if verbose >= VERBOSE_FULL:
+ print("Server",server,"says my",family,"is",ip)
+ return ip
+ elif method in methods:
+ return methods[method]()
+ else:
+ raise Exception("Unsupported "+family+" detection method: "+method)