-#!/usr/bin/python
+#!/usr/bin/python3
###############################################################################
# #
# ddns - A dynamic DNS client for IPFire #
import logging
import logging.handlers
-import ConfigParser
+import configparser
-from i18n import _
+from .i18n import _
logger = logging.getLogger("ddns.core")
logger.propagate = 1
-import database
-import providers
+from . import database
+from . import providers
from .errors import *
from .system import DDNSSystem
def load_configuration(self, filename):
logger.debug(_("Loading configuration file %s") % filename)
- configs = ConfigParser.RawConfigParser()
+ configs = configparser.RawConfigParser()
configs.read([filename,])
# First apply all global configuration settings.
self.settings[k] = v
# Allow missing config section
- except ConfigParser.NoSectionError:
+ except configparser.NoSectionError:
pass
for entry in configs.sections():
# Check if the provider is actually supported and if there are
# some dependencies missing on this system.
if not provider.supported():
- logger.warning("Provider '%s' is known, but not supported on this machine" % (provider.name))
+ logger.warning("Provider '%s' is known, but not supported on this machine" % provider.name)
continue
# Create an instance of the provider object with settings from the
try:
entry(force=force)
- except DDNSError, e:
- logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) failed:") % \
- { "hostname" : entry.hostname, "provider" : entry.name })
+ except DDNSError as e:
+ logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) failed:") %
+ {"hostname": entry.hostname, "provider": entry.name})
logger.error(" %s: %s" % (e.__class__.__name__, e.reason))
if e.message:
logger.error(" %s" % e.message)
- except Exception, e:
- logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) throwed an unhandled exception:") % \
- { "hostname" : entry.hostname, "provider" : entry.name }, exc_info=True)
+ except Exception:
+ logger.error(_("Dynamic DNS update for %(hostname)s (%(provider)s) threw an unhandled exception:") %
+ {"hostname": entry.hostname, "provider": entry.name}, exc_info=True)
-#!/usr/bin/python
+#!/usr/bin/python3
###############################################################################
# #
# ddns - A dynamic DNS client for IPFire #
import logging
import os
import subprocess
-import urllib2
+import urllib.request
+import urllib.error
+import urllib.parse
import xml.dom.minidom
-from i18n import _
+from .i18n import _
# Import all possible exception types.
from .errors import *
if not all((provider.handle, provider.name, provider.website)):
raise DDNSError(_("Provider is not properly configured"))
- assert not _providers.has_key(provider.handle), \
+ assert provider.handle not in _providers, \
"Provider '%s' has already been registered" % provider.handle
_providers[provider.handle] = provider
return "<DDNS Provider %s (%s)>" % (self.name, self.handle)
def __cmp__(self, other):
- return cmp(self.hostname, other.hostname)
+ return (lambda a, b: (a > b)-(a < b))(self.hostname, other.hostname)
@property
def db(self):
self.core.db.log_failure(self.hostname, e)
raise
- logger.info(_("Dynamic DNS update for %(hostname)s (%(provider)s) successful") % \
- { "hostname" : self.hostname, "provider" : self.name })
+ logger.info(_("Dynamic DNS update for %(hostname)s (%(provider)s) successful") %
+ {"hostname": self.hostname, "provider": self.name})
self.core.db.log_success(self.hostname)
def update(self):
def remove_protocol(self, proto):
if not self.can_remove_records:
- raise RuntimeError, "can_remove_records is enabled, but remove_protocol() not implemented"
+ raise RuntimeError("can_remove_records is enabled, but remove_protocol() not implemented")
raise NotImplementedError
def requires_update(self):
# If the IP addresses have changed, an update is required
if self.ip_address_changed(self.protocols):
- logger.debug(_("An update for %(hostname)s (%(provider)s)"
- " is performed because of an IP address change") % \
- { "hostname" : self.hostname, "provider" : self.name })
+ logger.debug(_("An update for %(hostname)s (%(provider)s) is performed because of an IP address change") %
+ {"hostname": self.hostname, "provider": self.name})
return True
# If the holdoff time has expired, an update is required, too
if self.holdoff_time_expired():
- logger.debug(_("An update for %(hostname)s (%(provider)s)"
- " is performed because the holdoff time has expired") % \
- { "hostname" : self.hostname, "provider" : self.name })
+ logger.debug(_("An update for %(hostname)s (%(provider)s) is performed because the holdoff time has expired") %
+ {"hostname": self.hostname, "provider": self.name})
return True
# Otherwise, we don't need to perform an update
- logger.debug(_("No update required for %(hostname)s (%(provider)s)") % \
- { "hostname" : self.hostname, "provider" : self.name })
+ logger.debug(_("No update required for %(hostname)s (%(provider)s)") %
+ {"hostname": self.hostname, "provider": self.name})
return False
# If there is no holdoff time, we won't update ever again.
if self.holdoff_failure_days is None:
- logger.warning(_("An update has not been performed because earlier updates failed for %s") \
- % self.hostname)
+ logger.warning(_("An update has not been performed because earlier updates failed for %s") % self.hostname)
logger.warning(_("There will be no retries"))
return True
if now < holdoff_end:
failure_message = self.db.last_update_failure_message(self.hostname)
- logger.warning(_("An update has not been performed because earlier updates failed for %s") \
- % self.hostname)
+ logger.warning(_("An update has not been performed because earlier updates failed for %s") % self.hostname)
if failure_message:
logger.warning(_("Last failure message:"))
logger.debug("The holdoff time has expired for %s" % self.hostname)
return True
else:
- logger.debug("Updates for %s are held off until %s" % \
- (self.hostname, holdoff_end))
+ logger.debug("Updates for %s are held off until %s" %
+ (self.hostname, holdoff_end))
return False
def send_request(self, *args, **kwargs):
def send_request(self, data):
# Send update to the server.
- response = DDNSProvider.send_request(self, self.url, data=data,
- username=self.username, password=self.password)
+ response = DDNSProvider.send_request(self, self.url, data=data, username=self.username, password=self.password)
# Get the full response message.
output = response.read()
will be sent by various providers. This class uses the python
shipped XML minidom module to walk through the XML tree and return
a requested element.
- """
+ """
def get_xml_tag_value(self, document, content):
# Send input to the parser.
# -t sets the timeout
command = ["nsupdate", "-v", "-t", "60"]
- p = subprocess.Popen(command, shell=True,
- stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- )
+ p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate(scriptlet)
if p.returncode == 0:
# Send update to the server.
try:
- response = self.send_request(self.url, username=self.username, password=self.password,
- data=data)
+ response = self.send_request(self.url, username=self.username, password=self.password, data=data)
# Handle error codes.
- except urllib2.HTTPError, e:
+ except urllib.error.HTTPError as e:
if e.code == 422:
raise DDNSRequestError(_("Domain not found."))
}
# Send update to the server.
- response = self.send_request(self.url, username=self.username, password=self.password,
- data=data)
+ response = self.send_request(self.url, username=self.username, password=self.password, data=data)
# Handle success messages.
if response.code == 200:
}
# Send update to the server.
- response = self.send_request(self.url, username=self.username, password=self.password,
- data=data)
+ response = self.send_request(self.url, username=self.username, password=self.password, data=data)
# Get the full response message.
output = response.read()
output = output.strip()
# Handle success messages.
- if output.startswith("I:OK") :
+ if output.startswith("I:OK"):
return
# If we got here, some other update error happened.
raise DDNSUpdateError
-
class DDNSProviderDynU(DDNSProtocolDynDNS2, DDNSProvider):
handle = "dynu.com"
name = "Dynu"
}
# Send update to the server.
- response = self.send_request(self.url, data=data,
- username=self.username, password=self.password)
+ response = self.send_request(self.url, data=data, username=self.username, password=self.password)
# Get the full response message.
output = response.read()
response = self.send_request(url, data=data)
# Handle error codes
- except urllib2.HTTPError, e:
+ except urllib.error.HTTPError as e:
if e.code == 404:
raise DDNSAuthenticationError
data["ipv4"] = address4
# Raise an error if none address is given.
- if not data.has_key("ipv6") and not data.has_key("ipv4"):
+ if "ipv6" not in data and "ipv4" not in data:
raise DDNSConfigurationError
# Check if a token has been set.
response = self.send_request(self.url, data=data)
else:
# Send update to the server.
- response = self.send_request(self.url, username=self.username, password=self.password,
- data=data)
+ response = self.send_request(self.url, username=self.username, password=self.password, data=data)
# Get the full response message.
output = response.read()
}
# Send update to the server.
- response = self.send_request(self.url, username=self.username, password=self.password,
- data=data)
+ response = self.send_request(self.url, username=self.username, password=self.password, data=data)
# Get the full response message.
output = response.read()
-#!/usr/bin/python
+#!/usr/bin/python3
###############################################################################
# #
# ddns - A dynamic DNS client for IPFire #
import re
import ssl
import socket
-import urllib
-import urllib2
+import urllib.request
+import urllib.parse
+import urllib.error
-from __version__ import CLIENT_VERSION
+from .__version__ import CLIENT_VERSION
from .errors import *
-from i18n import _
+from .i18n import _
# Initialize the logger.
import logging
with open("/var/ipfire/red/local-ipaddress") as f:
return f.readline()
- except IOError, e:
+ except IOError as e:
# File not found
if e.errno == 2:
return
if data:
logger.debug(" data: %s" % data)
- req = urllib2.Request(url, data=data)
+ req = urllib.request.Request(url, data=data)
if username and password:
basic_auth_header = self._make_basic_auth_header(username, password)
logger.debug(" %s: %s" % (k, v))
try:
- resp = urllib2.urlopen(req, timeout=timeout)
+ resp = urllib.request.urlopen(req, timeout=timeout)
# Log response header.
logger.debug(_("Response header (Status Code %s):") % resp.code)
# Return the entire response object.
return resp
- except urllib2.HTTPError, e:
+ except urllib.error.HTTPError as e:
# Log response header.
logger.debug(_("Response header (Status Code %s):") % e.code)
for k, v in e.hdrs.items():
# Raise all other unhandled exceptions.
raise
- except urllib2.URLError, e:
+ except urllib.error.URLError as e:
if e.reason:
# Handle SSL errors
if isinstance(e.reason, ssl.SSLError):
# Raise all other unhandled exceptions.
raise
- except socket.timeout, e:
+ except socket.timeout as e:
logger.debug(_("Connection timeout"))
raise DDNSConnectionTimeoutError
args = []
for k, v in data.items():
- arg = "%s=%s" % (k, urllib.quote(v))
+ arg = "%s=%s" % (k, urllib.parse.quote(v))
args.append(arg)
return "&".join(args)
authstring = "%s:%s" % (username, password)
# Encode authorization data in base64.
- authstring = base64.encodestring(authstring)
+ authstring = base64.encodebytes(authstring)
# Remove any newline characters.
authstring = authstring.replace("\n", "")
# Resolve the host address.
try:
response = socket.getaddrinfo(hostname, None, family)
- except socket.gaierror, e:
+ except socket.gaierror as e:
# Name or service not known
if e.errno == -2:
return []
continue
# Add to repsonse list if not already in there.
- if not address in addresses:
+ if address not in addresses:
addresses.append(address)
return addresses
"""
try:
f = open("/etc/os-release", "r")
- except IOError, e:
+ except IOError as e:
# File not found
if e.errno == 2:
return
"""
try:
f = open("/etc/system-release", "r")
- except IOError, e:
+ except IOError as e:
# File not found
if e.errno == 2:
return