diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index bf301dedb..005b4260f 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -2,6 +2,7 @@ # Switch to black formatting 1f93b2355a2816918e11a55e61b42010d15a6720 +5f2a95d154650366078b0d387e5b01427c4340c0 # Switch to prettier formatting 6b44909f21ee39237b7504cd31ffa6cf28275c33 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e751a43e4..34f420128 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -38,7 +38,7 @@ repos: - id: flake8 additional_dependencies: - flake8-bugbear - - repo: https://github.com/prettier/prettier + - repo: https://github.com/pre-commit/mirrors-prettier rev: master hooks: - id: prettier diff --git a/README.md b/README.md index c23ee8ef4..8f9cc1b84 100644 --- a/README.md +++ b/README.md @@ -63,7 +63,7 @@ For information about how to go about submitting bug reports or pull requests, p Installation instructions for installing from source for different operating systems can be found [on the forum](https://community.octoprint.org/tags/c/support/guides/15/setup). -If you want to run OctoPrint on a Raspberry Pi, you might want to take a look at [OctoPi](https://github.com/guysoft/OctoPi) +If you want to run OctoPrint on a Raspberry Pi, you really should take a look at [OctoPi](https://github.com/guysoft/OctoPi) which is a custom SD card image that includes OctoPrint plus dependencies. The generic steps that should basically be done regardless of operating system @@ -76,13 +76,6 @@ you already have Python 2.7, 3.6 or 3.7, pip and virtualenv and their dependenci parameter, e.g. `virtualenv --python=python3 venv`. 2. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install OctoPrint` -Or alternatively, for an install from source: - -1. Checkout OctoPrint: `git clone https://github.com/OctoPrint/OctoPrint.git` -2. Change into the OctoPrint folder: `cd OctoPrint` -3. Create a user-owned virtual environment therein: `virtualenv venv` -4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .` - You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage) for details. diff --git a/docs/api/datamodel.rst b/docs/api/datamodel.rst index 346225081..bbca4519f 100644 --- a/docs/api/datamodel.rst +++ b/docs/api/datamodel.rst @@ -162,6 +162,10 @@ Resend stats - 1 - int - Number of resend requests received since connecting. + * - ``transmitted`` + - 1 + - int + - Number of transmitted lines since connecting. * - ``ratio`` - 1 - int diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 8a001dc05..7b8a949eb 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -24,9 +24,6 @@ Use the following settings to enable access control: .. code-block:: yaml accessControl: - # whether to enable access control or not. Defaults to true - enabled: true - # The user manager implementation to use for accessing user information. Currently only a filebased # user manager is implemented which stores configured accounts in a YAML file (Default: users.yaml # in the default configuration folder, see below) @@ -75,6 +72,10 @@ Use the following settings to enable access control: # If a remote user is not found, add them. Use this only if all users from the remote system can use OctoPrint. addRemoteUsers: false + # Secret salt used for password hashing, DO NOT TOUCH. If changed you will no longer be able to log in with your + # existing accounts. + salt: someSecretSalt + .. _sec-configuration-config_yaml-api: API diff --git a/setup.py b/setup.py index a29295e89..31efb1135 100644 --- a/setup.py +++ b/setup.py @@ -75,7 +75,7 @@ INSTALL_REQUIRES_PYTHON2 = [ "scandir>=1.10,<2", "chainmap>=1.0.3,<2", "typing>=3.7.4.1,<4", - "enum34>=1.1.10", + "enum34>=1.1.10,<1.2", ] # Python 3 specific requirements diff --git a/src/octoprint/access/users.py b/src/octoprint/access/users.py index 5e3115d15..a7340bfed 100644 --- a/src/octoprint/access/users.py +++ b/src/octoprint/access/users.py @@ -502,6 +502,8 @@ class FilebasedUserManager(UserManager): def __init__(self, group_manager, path=None, settings=None): UserManager.__init__(self, group_manager, settings=settings) + self._logger = logging.getLogger(__name__) + if path is None: path = self._settings.get(["accessControl", "userfile"]) if path is None: @@ -517,10 +519,19 @@ class FilebasedUserManager(UserManager): def _load(self): if os.path.exists(self._userfile) and os.path.isfile(self._userfile): - self._customized = True + # noinspection PyBroadException with io.open(self._userfile, "rt", encoding="utf-8") as f: data = yaml.safe_load(f) + if not data or not isinstance(data, dict): + self._logger.fatal( + "{} does not contain a valid map of users. Fix " + "the file, or remove it, then restart OctoPrint.".format( + self._userfile + ) + ) + raise CorruptUserStorage() + for name, attributes in data.items(): if not isinstance(attributes, dict): continue @@ -570,6 +581,7 @@ class FilebasedUserManager(UserManager): if self._dirty: self._save() + self._customized = True else: self._customized = False @@ -1008,10 +1020,14 @@ class UnknownUser(Exception): class UnknownRole(Exception): - def _init_(self, role): + def __init__(self, role): Exception.__init__(self, "Unknown role: %s" % role) +class CorruptUserStorage(Exception): + pass + + ##~~ Refactoring helpers diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 9e9a24f67..548fd88bb 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -11,7 +11,12 @@ import click from octoprint import init_settings from octoprint.access.groups import FilebasedGroupManager -from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists +from octoprint.access.users import ( + CorruptUserStorage, + FilebasedUserManager, + UnknownUser, + UserAlreadyExists, +) from octoprint.cli import get_ctx_obj_option from octoprint.util import get_class, sv @@ -63,6 +68,8 @@ def user(ctx): try: clazz = get_class(name) user_manager = clazz(group_manager=group_manager, settings=settings) + except CorruptUserStorage: + raise except Exception: click.echo( "Could not instantiate user manager {}, falling back to FilebasedUserManager!".format( @@ -76,7 +83,7 @@ def user(ctx): except Exception: click.echo("Could not instantiate user manager", err=True) - return + ctx.exit(-1) @user.command(name="list") diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index bf0a33c34..6428d8893 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -643,7 +643,7 @@ class LocalFileStorage(StorageInterface): for key, node in nodes.items(): if node["type"] == "folder": node = copy.copy(node) - node["children"] = [] + node["children"] = {} result[key] = node return result diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 2b2b3bf94..066d20799 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -501,7 +501,6 @@ class BackupPlugin( backup_file, exclude=exclude, settings=settings, - logger=self._logger, plugin_manager=cli_group.plugin_manager, datafolder=datafolder, ) @@ -839,6 +838,9 @@ class BackupPlugin( on_backup_done=None, on_backup_error=None, ): + if logger is None: + logger = logging.getLogger(__name__) + exclude_by_default = ( "generated", "logs", diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index 715c579f4..dac3d0a38 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -1149,9 +1149,10 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): def _updateResendDataCallback(self): if not self._comm: - return self._dict(count=0, ratio=0) + return self._dict(count=0, transmitted=0, ratio=0) return self._dict( count=self._comm.received_resends, + transmitted=self._comm.transmitted_lines, ratio=int(self._comm.resend_ratio * 100.0), ) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 6f908f24f..1cfb0a578 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -547,6 +547,8 @@ class Server(object): try: clazz = octoprint.util.get_class(user_manager_name) userManager = clazz(groupManager) + except octoprint.access.users.CorruptUserStorage: + raise except Exception: self._logger.exception( "Could not instantiate user manager {}, " diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 68b80b5f7..8ba9a05cf 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -140,8 +140,10 @@ def uploadLanguagePack(): upload_name = request.values[input_upload_name] upload_path = request.values[input_upload_path] - exts = filter( - lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar") + exts = list( + filter( + lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar") + ) ) if not len(exts): return make_response( diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py index 753da331e..2466f655f 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -243,6 +243,7 @@ def getSettings(): ["serial", "capabilities", "emergency_parser"] ), "resendRatioThreshold": s.getInt(["serial", "resendRatioThreshold"]), + "resendRatioStart": s.getInt(["serial", "resendRatioStart"]), }, "folder": { "uploads": s.getBaseFolder("uploads"), @@ -871,6 +872,8 @@ def _saveSettings(data): s.setInt( ["serial", "resendRatioThreshold"], data["serial"]["resendRatioThreshold"] ) + if "resendRatioStart" in data["serial"]: + s.setInt(["serial", "resendRatioStart"], data["serial"]["resendRatioStart"]) oldLog = s.getBoolean(["serial", "log"]) if "log" in data["serial"]: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index a09916eb3..fb097d4a9 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -170,6 +170,7 @@ default_settings = { "emergency_parser": True, }, "resendRatioThreshold": 10, + "resendRatioStart": 100, # command specific flags "triggerOkForM29": True, }, diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js index d5e19c1b4..911018fa9 100644 --- a/src/octoprint/static/js/app/viewmodels/printerstate.js +++ b/src/octoprint/static/js/app/viewmodels/printerstate.js @@ -12,7 +12,10 @@ $(function () { self.resendTotalTransmitted = ko.observable(0); self.resendRatio = ko.observable(0); self.resendRatioCritical = ko.pureComputed(function () { - return self.resendRatio() >= self.settings.serial_resendRatioThreshold(); + return ( + self.resendRatio() >= self.settings.serial_resendRatioThreshold() && + self.resendTotalTransmitted() >= self.settings.serial_resendRatioStart() + ); }); self.resendRatioNotification = undefined; @@ -387,6 +390,7 @@ $(function () { self._processResends = function (data) { self.resendCount(data.count); + self.resendTotalTransmitted(data.transmitted); self.resendRatio(data.ratio); }; diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js index a58bee66c..8a4c341bc 100644 --- a/src/octoprint/static/js/app/viewmodels/settings.js +++ b/src/octoprint/static/js/app/viewmodels/settings.js @@ -235,6 +235,7 @@ $(function () { self.serial_disableSdPrintingDetection = ko.observable(undefined); self.serial_ackMax = ko.observable(undefined); self.serial_resendRatioThreshold = ko.observable(100); + self.serial_resendRatioStart = ko.observable(100); self.folder_uploads = ko.observable(undefined); self.folder_timelapse = ko.observable(undefined); diff --git a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 index a88f490c1..254f671a6 100644 --- a/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 +++ b/src/octoprint/templates/dialogs/settings/serialconnection.jinja2 @@ -526,6 +526,15 @@ +
+ +
+
+ + lines +
+
+
diff --git a/src/octoprint/templates/sidebar/state.jinja2 b/src/octoprint/templates/sidebar/state.jinja2 index 53038507d..3746d4162 100644 --- a/src/octoprint/templates/sidebar/state.jinja2 +++ b/src/octoprint/templates/sidebar/state.jinja2 @@ -1,5 +1,5 @@ {{ _('State') }}:
-{{ _('Resend requests') }}: (%)
+{{ _('Resend ratio') }}: / (%)

{{ _('File') }}:  (SD)
{{ _('Uploaded') }}:
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index a491d9c17..a18df4866 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -665,6 +665,7 @@ class MachineCom(object): self._transmitted_lines = 0 self._received_resend_requests = 0 + self._resend_ratio_start = settings().getInt(["serial", "resendRatioStart"]) self._resend_ratio_threshold = ( settings().getInt(["serial", "resendRatioThreshold"]) / 100.0 ) @@ -826,13 +827,14 @@ class MachineCom(object): resend_ratio = self.resend_ratio if ( resend_ratio >= self._resend_ratio_threshold + and self._transmitted_lines > self._resend_ratio_start and not self._resend_ratio_reported ): message = ( - "Over {}% of transmitted lines have triggered resend requests " - "({:.2f}%). The communication with the printers is unreliable. " + "Over {:.0f}% of transmitted lines have triggered resend requests " + "({:.2f}%). The communication with the printer is unreliable. " "Please see https://faq.octoprint.org/communication-errors.".format( - self._resend_ratio_threshold, resend_ratio + self._resend_ratio_threshold * 100, resend_ratio * 100 ) ) self._log(message) diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py index aa20778cb..647d1852a 100644 --- a/src/octoprint/vendor/zeroconf.py +++ b/src/octoprint/vendor/zeroconf.py @@ -1,5 +1,4 @@ -from __future__ import ( - absolute_import, division, print_function, unicode_literals) +from __future__ import absolute_import, division, print_function, unicode_literals """ Multicast DNS Service Discovery for Python, v0.14-wmcbrine Copyright 2003 Paul Scott-Murphy, 2014 William McBrine @@ -39,16 +38,20 @@ import netifaces from six import binary_type, indexbytes, int2byte, iteritems, text_type from six.moves import xrange -__author__ = 'Paul Scott-Murphy, William McBrine' -__maintainer__ = 'Jakub Stasiak ' -__version__ = '0.19.1' -__license__ = 'LGPL' +__author__ = "Paul Scott-Murphy, William McBrine" +__maintainer__ = "Jakub Stasiak " +__version__ = "0.19.1" +__license__ = "LGPL" __all__ = [ "__version__", - "Zeroconf", "ServiceInfo", "ServiceBrowser", - "Error", "InterfaceChoice", "ServiceStateChange", + "Zeroconf", + "ServiceInfo", + "ServiceBrowser", + "Error", + "InterfaceChoice", + "ServiceStateChange", ] @@ -68,10 +71,11 @@ _BROWSER_TIME = 500 # Some DNS constants -_MDNS_ADDR = '224.0.0.251' +_MDNS_ADDR = "224.0.0.251" _MDNS_PORT = 5353 _DNS_PORT = 53 -_DNS_TTL = 60 * 60 # one hour default TTL +_DNS_HOST_TTL = 120 # two minute for host records (A, SRV etc) as-per RFC6762 +_DNS_OTHER_TTL = 4500 # 75 minutes for non-host records (PTR, TXT etc) as-per RFC6762 _MAX_MSG_TYPICAL = 1460 # unused _MAX_MSG_ABSOLUTE = 8966 @@ -120,36 +124,40 @@ _TYPE_ANY = 255 # Mapping constants to names -_CLASSES = {_CLASS_IN: "in", - _CLASS_CS: "cs", - _CLASS_CH: "ch", - _CLASS_HS: "hs", - _CLASS_NONE: "none", - _CLASS_ANY: "any"} +_CLASSES = { + _CLASS_IN: "in", + _CLASS_CS: "cs", + _CLASS_CH: "ch", + _CLASS_HS: "hs", + _CLASS_NONE: "none", + _CLASS_ANY: "any", +} -_TYPES = {_TYPE_A: "a", - _TYPE_NS: "ns", - _TYPE_MD: "md", - _TYPE_MF: "mf", - _TYPE_CNAME: "cname", - _TYPE_SOA: "soa", - _TYPE_MB: "mb", - _TYPE_MG: "mg", - _TYPE_MR: "mr", - _TYPE_NULL: "null", - _TYPE_WKS: "wks", - _TYPE_PTR: "ptr", - _TYPE_HINFO: "hinfo", - _TYPE_MINFO: "minfo", - _TYPE_MX: "mx", - _TYPE_TXT: "txt", - _TYPE_AAAA: "quada", - _TYPE_SRV: "srv", - _TYPE_ANY: "any"} +_TYPES = { + _TYPE_A: "a", + _TYPE_NS: "ns", + _TYPE_MD: "md", + _TYPE_MF: "mf", + _TYPE_CNAME: "cname", + _TYPE_SOA: "soa", + _TYPE_MB: "mb", + _TYPE_MG: "mg", + _TYPE_MR: "mr", + _TYPE_NULL: "null", + _TYPE_WKS: "wks", + _TYPE_PTR: "ptr", + _TYPE_HINFO: "hinfo", + _TYPE_MINFO: "minfo", + _TYPE_MX: "mx", + _TYPE_TXT: "txt", + _TYPE_AAAA: "quada", + _TYPE_SRV: "srv", + _TYPE_ANY: "any", +} -_HAS_A_TO_Z = re.compile(r'[A-Za-z]') -_HAS_ONLY_A_TO_Z_NUM_HYPHEN = re.compile(r'^[A-Za-z0-9\-]+$') -_HAS_ASCII_CONTROL_CHARS = re.compile(r'[\x00-\x1f\x7f]') +_HAS_A_TO_Z = re.compile(r"[A-Za-z]") +_HAS_ONLY_A_TO_Z_NUM_HYPHEN = re.compile(r"^[A-Za-z0-9\-]+$") +_HAS_ASCII_CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f]") @enum.unique @@ -164,7 +172,7 @@ class ServiceStateChange(enum.Enum): Removed = 2 -HOST_ONLY_NETWORK_MASK = '255.255.255.255' +HOST_ONLY_NETWORK_MASK = "255.255.255.255" # utility functions @@ -215,69 +223,67 @@ def service_type_name(type_): :param type_: Type, SubType or service name to validate :return: fully qualified service name (eg: _http._tcp.local.) """ - if not (type_.endswith('._tcp.local.') or type_.endswith('._udp.local.')): + if not (type_.endswith("._tcp.local.") or type_.endswith("._udp.local.")): raise BadTypeInNameException( - "Type '%s' must end with '._tcp.local.' or '._udp.local.'" % - type_) + "Type '%s' must end with '._tcp.local.' or '._udp.local.'" % type_ + ) - remaining = type_[:-len('._tcp.local.')].split('.') + remaining = type_[: -len("._tcp.local.")].split(".") name = remaining.pop() if not name: raise BadTypeInNameException("No Service name found") if len(remaining) == 1 and len(remaining[0]) == 0: - raise BadTypeInNameException( - "Type '%s' must not start with '.'" % type_) + raise BadTypeInNameException("Type '%s' must not start with '.'" % type_) - if name[0] != '_': - raise BadTypeInNameException( - "Service name (%s) must start with '_'" % name) + if name[0] != "_": + raise BadTypeInNameException("Service name (%s) must start with '_'" % name) # remove leading underscore name = name[1:] if len(name) > 15: - raise BadTypeInNameException( - "Service name (%s) must be <= 15 bytes" % name) + raise BadTypeInNameException("Service name (%s) must be <= 15 bytes" % name) - if '--' in name: - raise BadTypeInNameException( - "Service name (%s) must not contain '--'" % name) + if "--" in name: + raise BadTypeInNameException("Service name (%s) must not contain '--'" % name) - if '-' in (name[0], name[-1]): + if "-" in (name[0], name[-1]): raise BadTypeInNameException( - "Service name (%s) may not start or end with '-'" % name) + "Service name (%s) may not start or end with '-'" % name + ) if not _HAS_A_TO_Z.search(name): raise BadTypeInNameException( - "Service name (%s) must contain at least one letter (eg: 'A-Z')" % - name) + "Service name (%s) must contain at least one letter (eg: 'A-Z')" % name + ) if not _HAS_ONLY_A_TO_Z_NUM_HYPHEN.search(name): raise BadTypeInNameException( "Service name (%s) must contain only these characters: " - "A-Z, a-z, 0-9, hyphen ('-')" % name) + "A-Z, a-z, 0-9, hyphen ('-')" % name + ) - if remaining and remaining[-1] == '_sub': + if remaining and remaining[-1] == "_sub": remaining.pop() if len(remaining) == 0 or len(remaining[0]) == 0: - raise BadTypeInNameException( - "_sub requires a subtype name") + raise BadTypeInNameException("_sub requires a subtype name") if len(remaining) > 1: - remaining = ['.'.join(remaining)] + remaining = [".".join(remaining)] if remaining: - length = len(remaining[0].encode('utf-8')) + length = len(remaining[0].encode("utf-8")) if length > 63: raise BadTypeInNameException("Too long: '%s'" % remaining[0]) if _HAS_ASCII_CONTROL_CHARS.search(remaining[0]): raise BadTypeInNameException( - "Ascii control character 0x00-0x1F and 0x7F illegal in '%s'" % - remaining[0]) + "Ascii control character 0x00-0x1F and 0x7F illegal in '%s'" + % remaining[0] + ) - return '_' + name + type_[-len('._tcp.local.'):] + return "_" + name + type_[-len("._tcp.local.") :] # Exceptions @@ -306,6 +312,7 @@ class AbstractMethodException(Error): class BadTypeInNameException(Error): pass + # implementation classes @@ -324,7 +331,7 @@ class QuietLogger(object): logger = log.debug if logger_data is not None: logger(*logger_data) - logger('Exception occurred:', exc_info=exc_info) + logger("Exception occurred:", exc_info=exc_info) @classmethod def log_warning_once(cls, *args): @@ -351,10 +358,12 @@ class DNSEntry(object): def __eq__(self, other): """Equality test on name, type, and class""" - return (self.name == other.name and - self.type == other.type and - self.class_ == other.class_ and - isinstance(other, DNSEntry)) + return ( + self.name == other.name + and self.type == other.type + and self.class_ == other.class_ + and isinstance(other, DNSEntry) + ) def __ne__(self, other): """Non-equality test""" @@ -372,8 +381,11 @@ class DNSEntry(object): def to_string(self, hdr, other): """String representation with additional information""" - result = "%s[%s,%s" % (hdr, self.get_type(self.type), - self.get_class_(self.class_)) + result = "%s[%s,%s" % ( + hdr, + self.get_type(self.type), + self.get_class_(self.class_), + ) if self.unique: result += "-unique," else: @@ -395,9 +407,11 @@ class DNSQuestion(DNSEntry): def answered_by(self, rec): """Returns true if the question is answered by the record""" - return (self.class_ == rec.class_ and - (self.type == rec.type or self.type == _TYPE_ANY) and - self.name == rec.name) + return ( + self.class_ == rec.class_ + and (self.type == rec.type or self.type == _TYPE_ANY) + and self.name == rec.name + ) def __repr__(self): """String representation""" @@ -462,7 +476,10 @@ class DNSRecord(DNSEntry): def to_string(self, other): """String representation with additional information""" arg = "%s/%s,%s" % ( - self.ttl, self.get_remaining_ttl(current_time_millis()), other) + self.ttl, + self.get_remaining_ttl(current_time_millis()), + other, + ) return DNSEntry.to_string(self, "record", arg) @@ -480,7 +497,11 @@ class DNSAddress(DNSRecord): def __eq__(self, other): """Tests equality on address""" - return isinstance(other, DNSAddress) and self.address == other.address and DNSEntry.__eq__(self, other) + return ( + isinstance(other, DNSAddress) + and self.address == other.address + and DNSEntry.__eq__(self, other) + ) def __repr__(self): """String representation""" @@ -497,25 +518,27 @@ class DNSHinfo(DNSRecord): def __init__(self, name, type_, class_, ttl, cpu, os): DNSRecord.__init__(self, name, type_, class_, ttl) try: - self.cpu = cpu.decode('utf-8') + self.cpu = cpu.decode("utf-8") except AttributeError: self.cpu = cpu try: - self.os = os.decode('utf-8') + self.os = os.decode("utf-8") except AttributeError: self.os = os def write(self, out): """Used in constructing an outgoing packet""" - out.write_character_string(self.cpu.encode('utf-8')) - out.write_character_string(self.os.encode('utf-8')) + out.write_character_string(self.cpu.encode("utf-8")) + out.write_character_string(self.os.encode("utf-8")) def __eq__(self, other): """Tests equality on cpu and os""" - return (isinstance(other, DNSHinfo) and - self.cpu == other.cpu and - self.os == other.os and - DNSEntry.__eq__(self, other)) + return ( + isinstance(other, DNSHinfo) + and self.cpu == other.cpu + and self.os == other.os + and DNSEntry.__eq__(self, other) + ) def __repr__(self): """String representation""" @@ -536,7 +559,11 @@ class DNSPointer(DNSRecord): def __eq__(self, other): """Tests equality on alias""" - return isinstance(other, DNSPointer) and self.alias == other.alias and DNSEntry.__eq__(self, other) + return ( + isinstance(other, DNSPointer) + and self.alias == other.alias + and DNSEntry.__eq__(self, other) + ) def __repr__(self): """String representation""" @@ -558,7 +585,11 @@ class DNSText(DNSRecord): def __eq__(self, other): """Tests equality on text""" - return isinstance(other, DNSText) and self.text == other.text and DNSEntry.__eq__(self, other) + return ( + isinstance(other, DNSText) + and self.text == other.text + and DNSEntry.__eq__(self, other) + ) def __repr__(self): """String representation""" @@ -572,8 +603,7 @@ class DNSService(DNSRecord): """A DNS service record""" - def __init__(self, name, type_, class_, ttl, - priority, weight, port, server): + def __init__(self, name, type_, class_, ttl, priority, weight, port, server): DNSRecord.__init__(self, name, type_, class_, ttl) self.priority = priority self.weight = weight @@ -589,12 +619,14 @@ class DNSService(DNSRecord): def __eq__(self, other): """Tests equality on priority, weight, port and server""" - return (isinstance(other, DNSService) and - self.priority == other.priority and - self.weight == other.weight and - self.port == other.port and - self.server == other.server and - DNSEntry.__eq__(self, other)) + return ( + isinstance(other, DNSService) + and self.priority == other.priority + and self.weight == other.weight + and self.port == other.port + and self.server == other.server + and DNSEntry.__eq__(self, other) + ) def __repr__(self): """String representation""" @@ -626,26 +658,32 @@ class DNSIncoming(QuietLogger): self.valid = True except (IndexError, struct.error, IncomingDecodeError): - self.log_exception_warning(( - 'Choked at offset %d while unpacking %r', self.offset, data)) + self.log_exception_warning( + ("Choked at offset %d while unpacking %r", self.offset, data) + ) def unpack(self, format_): length = struct.calcsize(format_) - info = struct.unpack( - format_, self.data[self.offset:self.offset + length]) + info = struct.unpack(format_, self.data[self.offset : self.offset + length]) self.offset += length return info def read_header(self): """Reads header portion of packet""" - (self.id, self.flags, self.num_questions, self.num_answers, - self.num_authorities, self.num_additionals) = self.unpack(b'!6H') + ( + self.id, + self.flags, + self.num_questions, + self.num_answers, + self.num_authorities, + self.num_additionals, + ) = self.unpack(b"!6H") def read_questions(self): """Reads questions section of packet""" for i in xrange(self.num_questions): name = self.read_name() - type_, class_ = self.unpack(b'!HH') + type_, class_ = self.unpack(b"!HH") question = DNSQuestion(name, type_, class_) self.questions.append(question) @@ -662,13 +700,13 @@ class DNSIncoming(QuietLogger): def read_string(self, length): """Reads a string of a given length from the packet""" - info = self.data[self.offset:self.offset + length] + info = self.data[self.offset : self.offset + length] self.offset += length return info def read_unsigned_short(self): """Reads an unsigned short from the packet""" - return self.unpack(b'!H')[0] + return self.unpack(b"!H")[0] def read_others(self): """Reads the answers, authorities and additionals section of the @@ -676,30 +714,37 @@ class DNSIncoming(QuietLogger): n = self.num_answers + self.num_authorities + self.num_additionals for i in xrange(n): domain = self.read_name() - type_, class_, ttl, length = self.unpack(b'!HHiH') + type_, class_, ttl, length = self.unpack(b"!HHiH") rec = None if type_ == _TYPE_A: - rec = DNSAddress( - domain, type_, class_, ttl, self.read_string(4)) + rec = DNSAddress(domain, type_, class_, ttl, self.read_string(4)) elif type_ == _TYPE_CNAME or type_ == _TYPE_PTR: - rec = DNSPointer( - domain, type_, class_, ttl, self.read_name()) + rec = DNSPointer(domain, type_, class_, ttl, self.read_name()) elif type_ == _TYPE_TXT: - rec = DNSText( - domain, type_, class_, ttl, self.read_string(length)) + rec = DNSText(domain, type_, class_, ttl, self.read_string(length)) elif type_ == _TYPE_SRV: rec = DNSService( - domain, type_, class_, ttl, - self.read_unsigned_short(), self.read_unsigned_short(), - self.read_unsigned_short(), self.read_name()) + domain, + type_, + class_, + ttl, + self.read_unsigned_short(), + self.read_unsigned_short(), + self.read_unsigned_short(), + self.read_name(), + ) elif type_ == _TYPE_HINFO: rec = DNSHinfo( - domain, type_, class_, ttl, - self.read_character_string(), self.read_character_string()) + domain, + type_, + class_, + ttl, + self.read_character_string(), + self.read_character_string(), + ) elif type_ == _TYPE_AAAA: - rec = DNSAddress( - domain, type_, class_, ttl, self.read_string(16)) + rec = DNSAddress(domain, type_, class_, ttl, self.read_string(16)) else: # Try to ignore types we don't know about # Skip the payload for the resource record so the next @@ -719,11 +764,11 @@ class DNSIncoming(QuietLogger): def read_utf(self, offset, length): """Reads a UTF-8 string of a given length from the packet""" - return text_type(self.data[offset:offset + length], 'utf-8', 'replace') + return text_type(self.data[offset : offset + length], "utf-8", "replace") def read_name(self): """Reads a domain name from the packet""" - result = '' + result = "" off = self.offset next_ = -1 first = off @@ -735,15 +780,14 @@ class DNSIncoming(QuietLogger): break t = length & 0xC0 if t == 0x00: - result = ''.join((result, self.read_utf(off, length) + '.')) + result = "".join((result, self.read_utf(off, length) + ".")) off += length elif t == 0xC0: if next_ < 0: next_ = off + 1 off = ((length & 0x3F) << 8) | indexbytes(self.data, off) if off >= first: - raise IncomingDecodeError( - "Bad domain name (circular) at %s" % (off,)) + raise IncomingDecodeError("Bad domain name (circular) at %s" % (off,)) first = off else: raise IncomingDecodeError("Bad domain name at %s" % (off,)) @@ -776,14 +820,16 @@ class DNSOutgoing(object): self.additionals = [] def __repr__(self): - return '' % ', '.join([ - 'multicast=%s' % self.multicast, - 'flags=%s' % self.flags, - 'questions=%s' % self.questions, - 'answers=%s' % self.answers, - 'authorities=%s' % self.authorities, - 'additionals=%s' % self.additionals, - ]) + return "" % ", ".join( + [ + "multicast=%s" % self.multicast, + "flags=%s" % self.flags, + "questions=%s" % self.questions, + "answers=%s" % self.answers, + "authorities=%s" % self.authorities, + "additionals=%s" % self.additionals, + ] + ) class State(enum.Enum): init = 0 @@ -809,7 +855,7 @@ class DNSOutgoing(object): self.authorities.append(record) def add_additional_answer(self, record): - """ Adds an additional answer + """Adds an additional answer From: RFC 6763, DNS-Based Service Discovery, February 2013 @@ -852,20 +898,20 @@ class DNSOutgoing(object): def write_byte(self, value): """Writes a single byte to the packet""" - self.pack(b'!c', int2byte(value)) + self.pack(b"!c", int2byte(value)) def insert_short(self, index, value): """Inserts an unsigned short in a certain position in the packet""" - self.data.insert(index, struct.pack(b'!H', value)) + self.data.insert(index, struct.pack(b"!H", value)) self.size += 2 def write_short(self, value): """Writes an unsigned short to the packet""" - self.pack(b'!H', value) + self.pack(b"!H", value) def write_int(self, value): """Writes an unsigned integer to the packet""" - self.pack(b'!I', int(value)) + self.pack(b"!I", int(value)) def write_string(self, value): """Writes a string to the packet""" @@ -875,7 +921,7 @@ class DNSOutgoing(object): def write_utf(self, s): """Writes a UTF-8 string of a given length to the packet""" - utfstr = s.encode('utf-8') + utfstr = s.encode("utf-8") length = len(utfstr) if length > 64: raise NamePartTooLongException @@ -904,12 +950,12 @@ class DNSOutgoing(object): """ # split name into each label - parts = name.split('.') + parts = name.split(".") if not parts[-1]: parts.pop() # construct each suffix - name_suffices = ['.'.join(parts[i:]) for i in range(len(parts))] + name_suffices = [".".join(parts[i:]) for i in range(len(parts))] # look for an existing name or suffix for count, sub_name in enumerate(name_suffices): @@ -1007,7 +1053,7 @@ class DNSOutgoing(object): self.insert_short(0, 0) else: self.insert_short(0, self.id) - return b''.join(self.data) + return b"".join(self.data) class DNSCache(object): @@ -1056,9 +1102,11 @@ class DNSCache(object): def current_entry_with_name_and_alias(self, name, alias): now = current_time_millis() for record in self.entries_with_name(name): - if (record.type == _TYPE_PTR and - not record.is_expired(now) and - record.alias == alias): + if ( + record.type == _TYPE_PTR + and not record.is_expired(now) + and record.alias == alias + ): return record def entries(self): @@ -1085,7 +1133,7 @@ class Engine(threading.Thread): """ def __init__(self, zc): - threading.Thread.__init__(self, name='zeroconf-Engine') + threading.Thread.__init__(self, name="zeroconf-Engine") self.daemon = True self.zc = zc self.readers = {} # maps socket to reader @@ -1148,7 +1196,7 @@ class Listener(QuietLogger): self.log_exception_warning() return - log.debug('Received from %r:%r: %r ', addr, port, data) + log.debug("Received from %r:%r: %r ", addr, port, data) self.data = data msg = DNSIncoming(data) @@ -1176,7 +1224,7 @@ class Reaper(threading.Thread): have expired.""" def __init__(self, zc): - threading.Thread.__init__(self, name='zeroconf-Reaper') + threading.Thread.__init__(self, name="zeroconf-Reaper") self.daemon = True self.zc = zc self.start() @@ -1207,7 +1255,6 @@ class Signal(object): class SignalRegistrationInterface(object): - def __init__(self, handlers): self._handlers = handlers @@ -1230,11 +1277,10 @@ class ServiceBrowser(threading.Thread): def __init__(self, zc, type_, handlers=None, listener=None): """Creates a browser for a specific type""" - assert handlers or listener, 'You need to specify at least one handler' + assert handlers or listener, "You need to specify at least one handler" if not type_.endswith(service_type_name(type_)): raise BadTypeInNameException - threading.Thread.__init__( - self, name='zeroconf-ServiceBrowser_' + type_) + threading.Thread.__init__(self, name="zeroconf-ServiceBrowser_" + type_) self.daemon = True self.zc = zc self.type = type_ @@ -1247,13 +1293,14 @@ class ServiceBrowser(threading.Thread): self.done = False - if hasattr(handlers, 'add_service'): + if hasattr(handlers, "add_service"): listener = handlers handlers = None handlers = handlers or [] if listener: + def on_change(zeroconf, service_type, name, state_change): args = (zeroconf, service_type, name) if state_change is ServiceStateChange.Added: @@ -1262,6 +1309,7 @@ class ServiceBrowser(threading.Thread): listener.remove_service(*args) else: raise NotImplementedError(state_change) + handlers.append(on_change) for h in handlers: @@ -1285,7 +1333,8 @@ class ServiceBrowser(threading.Thread): service_type=self.type, name=name, state_change=state_change, - )) + ) + ) if record.type == _TYPE_PTR and record.name == self.type: expired = record.is_expired(now) @@ -1343,8 +1392,19 @@ class ServiceInfo(object): """Service information""" - def __init__(self, type_, name, addresses=None, port=None, weight=0, - priority=0, properties=None, server=None): + def __init__( + self, + type_, + name, + addresses=None, + port=None, + weight=0, + priority=0, + properties=None, + server=None, + host_ttl=_DNS_HOST_TTL, + other_ttl=_DNS_OTHER_TTL, + ): """Create a service description. type_: fully qualified service type name @@ -1356,7 +1416,10 @@ class ServiceInfo(object): priority: priority of the service properties: dictionary of properties (or a string holding the bytes for the text field) - server: fully qualified name for service host (defaults to name)""" + server: fully qualified name for service host (defaults to name) + host_ttl: ttl used for A/SRV records + other_ttl: ttl used for PTR/TXT records + """ if not type_.endswith(service_type_name(name)): raise BadTypeInNameException @@ -1367,11 +1430,12 @@ class ServiceInfo(object): else: self._addresses = [] # This results in an ugly error when registering, better check now - invalid = [a for a in self._addresses - if not isinstance(a, bytes) or len(a) != 4] + invalid = [a for a in self._addresses if not isinstance(a, bytes) or len(a) != 4] if invalid: - raise TypeError('Addresses must be bytes, got %s. Hint: convert string addresses ' - 'with socket.inet_pton' % invalid) + raise TypeError( + "Addresses must be bytes, got %s. Hint: convert string addresses " + "with socket.inet_pton" % invalid + ) self.port = port self.weight = weight self.priority = priority @@ -1381,6 +1445,8 @@ class ServiceInfo(object): self.server = name self._properties = {} self._set_properties(properties) + self.host_ttl = host_ttl + self.other_ttl = other_ttl @property def addresses(self): @@ -1404,27 +1470,27 @@ class ServiceInfo(object): if isinstance(properties, dict): self._properties = properties list_ = [] - result = b'' + result = b"" for key, value in iteritems(properties): if isinstance(key, text_type): - key = key.encode('utf-8') + key = key.encode("utf-8") if value is None: - suffix = b'' + suffix = b"" elif isinstance(value, text_type): - suffix = value.encode('utf-8') + suffix = value.encode("utf-8") elif isinstance(value, binary_type): suffix = value elif isinstance(value, int): if value: - suffix = b'true' + suffix = b"true" else: - suffix = b'false' + suffix = b"false" else: - suffix = b'' - list_.append(b'='.join((key, suffix))) + suffix = b"" + list_.append(b"=".join((key, suffix))) for item in list_: - result = b''.join((result, int2byte(len(item)), item)) + result = b"".join((result, int2byte(len(item)), item)) self.text = result else: self.text = properties @@ -1439,11 +1505,11 @@ class ServiceInfo(object): while index < end: length = indexbytes(text, index) index += 1 - strs.append(text[index:index + length]) + strs.append(text[index : index + length]) index += length for s in strs: - parts = s.split(b'=', 1) + parts = s.split(b"=", 1) try: key, value = parts except ValueError: @@ -1451,9 +1517,9 @@ class ServiceInfo(object): key = s value = False else: - if value == b'true': + if value == b"true": value = True - elif value == b'false' or not value: + elif value == b"false" or not value: value = False # Only update non-existent properties @@ -1465,7 +1531,7 @@ class ServiceInfo(object): def get_name(self): """Name accessor""" if self.type is not None and self.name.endswith("." + self.type): - return self.name[:len(self.name) - len(self.type) - 1] + return self.name[: len(self.name) - len(self.type) - 1] return self.name def update_record(self, zc, now, record): @@ -1484,8 +1550,8 @@ class ServiceInfo(object): self.priority = record.priority # self.address = None self.update_record( - zc, now, zc.cache.get_by_details( - self.server, _TYPE_A, _CLASS_IN)) + zc, now, zc.cache.get_by_details(self.server, _TYPE_A, _CLASS_IN) + ) elif record.type == _TYPE_TXT: if record.name == self.name: self._set_text(record.text) @@ -1520,24 +1586,21 @@ class ServiceInfo(object): return False if next_ <= now: out = DNSOutgoing(_FLAGS_QR_QUERY) - out.add_question( - DNSQuestion(self.name, _TYPE_SRV, _CLASS_IN)) + out.add_question(DNSQuestion(self.name, _TYPE_SRV, _CLASS_IN)) out.add_answer_at_time( - zc.cache.get_by_details( - self.name, _TYPE_SRV, _CLASS_IN), now) + zc.cache.get_by_details(self.name, _TYPE_SRV, _CLASS_IN), now + ) - out.add_question( - DNSQuestion(self.name, _TYPE_TXT, _CLASS_IN)) + out.add_question(DNSQuestion(self.name, _TYPE_TXT, _CLASS_IN)) out.add_answer_at_time( - zc.cache.get_by_details( - self.name, _TYPE_TXT, _CLASS_IN), now) + zc.cache.get_by_details(self.name, _TYPE_TXT, _CLASS_IN), now + ) if self.server is not None: - out.add_question( - DNSQuestion(self.server, _TYPE_A, _CLASS_IN)) + out.add_question(DNSQuestion(self.server, _TYPE_A, _CLASS_IN)) out.add_answer_at_time( - zc.cache.get_by_details( - self.server, _TYPE_A, _CLASS_IN), now) + zc.cache.get_by_details(self.server, _TYPE_A, _CLASS_IN), now + ) zc.send(out) next_ = now + delay delay *= 2 @@ -1559,15 +1622,21 @@ class ServiceInfo(object): def __repr__(self): """String representation""" - return '%s(%s)' % ( + return "%s(%s)" % ( type(self).__name__, - ', '.join( - '%s=%r' % (name, getattr(self, name)) + ", ".join( + "%s=%r" % (name, getattr(self, name)) for name in ( - 'type', 'name', 'addresses', 'port', 'weight', 'priority', - 'server', 'properties', + "type", + "name", + "addresses", + "port", + "weight", + "priority", + "server", + "properties", ) - ) + ), ) @@ -1575,6 +1644,7 @@ class ZeroconfServiceTypes(object): """ Return all of the advertised services on any local networks """ + def __init__(self): self.found_services = set() @@ -1597,7 +1667,8 @@ class ZeroconfServiceTypes(object): local_zc = zc or Zeroconf(interfaces=interfaces) listener = cls() browser = ServiceBrowser( - local_zc, '_services._dns-sd._udp.local.', listener=listener) + local_zc, "_services._dns-sd._udp.local.", listener=listener + ) # wait for responses time.sleep(timeout) @@ -1612,15 +1683,19 @@ class ZeroconfServiceTypes(object): def get_all_addresses(address_family): - return list({addr['addr'] - for iface in netifaces.interfaces() - for addr in netifaces.ifaddresses(iface).get(address_family, []) - if addr.get('netmask') != HOST_ONLY_NETWORK_MASK}) + return list( + { + addr["addr"] + for iface in netifaces.interfaces() + for addr in netifaces.ifaddresses(iface).get(address_family, []) + if addr.get("netmask") != HOST_ONLY_NETWORK_MASK + } + ) def normalize_interface_choice(choice, address_family): if choice is InterfaceChoice.Default: - choice = ['0.0.0.0'] + choice = ["0.0.0.0"] elif choice is InterfaceChoice.All: choice = get_all_addresses(address_family) return choice @@ -1651,12 +1726,12 @@ def new_socket(): # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and # IP_MULTICAST_LOOP socket options as an unsigned char. - ttl = struct.pack(b'B', 255) + ttl = struct.pack(b"B", 255) s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) - loop = struct.pack(b'B', 1) + loop = struct.pack(b"B", 1) s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop) - s.bind(('', _MDNS_PORT)) + s.bind(("", _MDNS_PORT)) return s @@ -1690,21 +1765,25 @@ class Zeroconf(QuietLogger): self._respond_sockets = [] for i in interfaces: - log.debug('Adding %r to multicast group', i) + log.debug("Adding %r to multicast group", i) try: self._listen_socket.setsockopt( - socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, - socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i)) + socket.IPPROTO_IP, + socket.IP_ADD_MEMBERSHIP, + socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i), + ) except socket.error as e: if get_errno(e) == errno.EADDRINUSE: log.info( - 'Address in use when adding %s to multicast group, ' - 'it is expected to happen on some systems', i, + "Address in use when adding %s to multicast group, " + "it is expected to happen on some systems", + i, ) elif get_errno(e) == errno.EADDRNOTAVAIL: log.info( - 'Address not available when adding %s to multicast ' - 'group, it is expected to happen on some systems', i, + "Address not available when adding %s to multicast " + "group, it is expected to happen on some systems", + i, ) continue else: @@ -1712,7 +1791,8 @@ class Zeroconf(QuietLogger): respond_socket = new_socket() respond_socket.setsockopt( - socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i)) + socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i) + ) self._respond_sockets.append(respond_socket) @@ -1773,9 +1853,9 @@ class Zeroconf(QuietLogger): for listener in [k for k in self.browsers]: self.remove_service_listener(listener) - def register_service(self, info, ttl=_DNS_TTL, allow_name_change=False): + def register_service(self, info, ttl=_DNS_HOST_TTL, allow_name_change=False): """Registers service information to the network with a default TTL - of 60 seconds. Zeroconf will then respond to requests for + of 120 seconds. Zeroconf will then respond to requests for information for that service. The name of the service may be changed if needed to make it unique on the network.""" self.check_service(info, allow_name_change) @@ -1794,18 +1874,29 @@ class Zeroconf(QuietLogger): continue out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) out.add_answer_at_time( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0) + DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0 + ) out.add_answer_at_time( - DNSService(info.name, _TYPE_SRV, _CLASS_IN, - ttl, info.priority, info.weight, info.port, - info.server), 0) + DNSService( + info.name, + _TYPE_SRV, + _CLASS_IN, + ttl, + info.priority, + info.weight, + info.port, + info.server, + ), + 0, + ) out.add_answer_at_time( - DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0) + DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0 + ) for address in info.addresses: out.add_answer_at_time( - DNSAddress(info.server, _TYPE_A, _CLASS_IN, - ttl, address), 0) + DNSAddress(info.server, _TYPE_A, _CLASS_IN, ttl, address), 0 + ) self.send(out) i += 1 next_time += _REGISTER_TIME @@ -1819,7 +1910,7 @@ class Zeroconf(QuietLogger): else: del self.servicetypes[info.type] except Exception as e: # TODO stop catching all Exceptions - log.exception('Unknown error, possibly benign: %r', e) + log.exception("Unknown error, possibly benign: %r", e) now = current_time_millis() next_time = now i = 0 @@ -1830,17 +1921,29 @@ class Zeroconf(QuietLogger): continue out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) out.add_answer_at_time( - DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0) + DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0 + ) out.add_answer_at_time( - DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, - info.priority, info.weight, info.port, info.name), 0) + DNSService( + info.name, + _TYPE_SRV, + _CLASS_IN, + 0, + info.priority, + info.weight, + info.port, + info.name, + ), + 0, + ) out.add_answer_at_time( - DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0) + DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0 + ) for address in info.addresses: out.add_answer_at_time( - DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, - address), 0) + DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, address), 0 + ) self.send(out) i += 1 next_time += _UNREGISTER_TIME @@ -1858,17 +1961,29 @@ class Zeroconf(QuietLogger): continue out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) for info in self.services.values(): - out.add_answer_at_time(DNSPointer( - info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0) - out.add_answer_at_time(DNSService( - info.name, _TYPE_SRV, _CLASS_IN, 0, - info.priority, info.weight, info.port, info.server), 0) - out.add_answer_at_time(DNSText( - info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0) + out.add_answer_at_time( + DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0 + ) + out.add_answer_at_time( + DNSService( + info.name, + _TYPE_SRV, + _CLASS_IN, + 0, + info.priority, + info.weight, + info.port, + info.server, + ), + 0, + ) + out.add_answer_at_time( + DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0 + ) for address in info.addresses: - out.add_answer_at_time(DNSAddress( - info.server, _TYPE_A, _CLASS_IN, 0, - address), 0) + out.add_answer_at_time( + DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, address), 0 + ) self.send(out) i += 1 next_time += _UNREGISTER_TIME @@ -1883,7 +1998,7 @@ class Zeroconf(QuietLogger): if not info.type.endswith(service_name): raise BadTypeInNameException - instance_name = info.name[:-len(service_name) - 1] + instance_name = info.name[: -len(service_name) - 1] next_instance_number = 2 now = current_time_millis() @@ -1891,14 +2006,12 @@ class Zeroconf(QuietLogger): i = 0 while i < 3: # check for a name conflict - while self.cache.current_entry_with_name_and_alias( - info.type, info.name): + while self.cache.current_entry_with_name_and_alias(info.type, info.name): if not allow_name_change: raise NonUniqueNameException # change the name and look for a conflict - info.name = '%s-%s.%s' % ( - instance_name, next_instance_number, info.type) + info.name = "%s-%s.%s" % (instance_name, next_instance_number, info.type) next_instance_number += 1 service_type_name(info.name) next_time = now @@ -1912,8 +2025,9 @@ class Zeroconf(QuietLogger): out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA) self.debug = out out.add_question(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN)) - out.add_authorative_answer(DNSPointer( - info.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, info.name)) + out.add_authorative_answer( + DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, info.other_ttl, info.name) + ) self.send(out) i += 1 next_time += _CHECK_TIME @@ -1936,7 +2050,7 @@ class Zeroconf(QuietLogger): self.listeners.remove(listener) self.notify_all() except Exception as e: # TODO stop catching all Exceptions - log.exception('Unknown error, possibly benign: %r', e) + log.exception("Unknown error, possibly benign: %r", e) def update_record(self, now, rec): """Used to notify listeners of new information that has updated @@ -1981,16 +2095,64 @@ class Zeroconf(QuietLogger): for stype in self.servicetypes.keys(): if out is None: out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer(msg, DNSPointer( - "_services._dns-sd._udp.local.", _TYPE_PTR, - _CLASS_IN, _DNS_TTL, stype)) + out.add_answer( + msg, + DNSPointer( + "_services._dns-sd._udp.local.", + _TYPE_PTR, + _CLASS_IN, + _DNS_OTHER_TTL, + stype, + ), + ) for service in self.services.values(): if question.name == service.type: if out is None: out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) - out.add_answer(msg, DNSPointer( - service.type, _TYPE_PTR, - _CLASS_IN, _DNS_TTL, service.name)) + out.add_answer( + msg, + DNSPointer( + service.type, + _TYPE_PTR, + _CLASS_IN, + service.other_ttl, + service.name, + ), + ) + + # Add recommended additional answers according to + # https://tools.ietf.org/html/rfc6763#section-12.1. + out.add_additional_answer( + DNSService( + service.name, + _TYPE_SRV, + _CLASS_IN | _CLASS_UNIQUE, + service.host_ttl, + service.priority, + service.weight, + service.port, + service.server, + ) + ) + out.add_additional_answer( + DNSText( + service.name, + _TYPE_TXT, + _CLASS_IN | _CLASS_UNIQUE, + service.other_ttl, + service.text, + ) + ) + for address in service.addresses: + out.add_additional_answer( + DNSAddress( + service.server, + _TYPE_A, + _CLASS_IN | _CLASS_UNIQUE, + service.host_ttl, + address, + ) + ) else: try: if out is None: @@ -2001,29 +2163,57 @@ class Zeroconf(QuietLogger): for service in self.services.values(): if service.server == question.name.lower(): for address in service.addresses: - out.add_answer(msg, DNSAddress( - question.name, _TYPE_A, - _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, address)) + out.add_answer( + msg, + DNSAddress( + question.name, + _TYPE_A, + _CLASS_IN | _CLASS_UNIQUE, + service.host_ttl, + address, + ), + ) service = self.services.get(question.name.lower(), None) if not service: continue if question.type in (_TYPE_SRV, _TYPE_ANY): - out.add_answer(msg, DNSService( - question.name, _TYPE_SRV, _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, service.priority, service.weight, - service.port, service.server)) + out.add_answer( + msg, + DNSService( + question.name, + _TYPE_SRV, + _CLASS_IN | _CLASS_UNIQUE, + service.host_ttl, + service.priority, + service.weight, + service.port, + service.server, + ), + ) if question.type in (_TYPE_TXT, _TYPE_ANY): - out.add_answer(msg, DNSText( - question.name, _TYPE_TXT, _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, service.text)) + out.add_answer( + msg, + DNSText( + question.name, + _TYPE_TXT, + _CLASS_IN | _CLASS_UNIQUE, + service.other_ttl, + service.text, + ), + ) if question.type == _TYPE_SRV: for address in service.addresses: - out.add_additional_answer(DNSAddress( - service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, address)) + out.add_additional_answer( + DNSAddress( + service.server, + _TYPE_A, + _CLASS_IN | _CLASS_UNIQUE, + service.host_ttl, + address, + ) + ) except Exception: # TODO stop catching all Exceptions self.log_exception_warning() @@ -2035,23 +2225,24 @@ class Zeroconf(QuietLogger): """Sends an outgoing packet.""" packet = out.packet() if len(packet) > _MAX_MSG_ABSOLUTE: - self.log_warning_once("Dropping %r over-sized packet (%d bytes) %r", - out, len(packet), packet) + self.log_warning_once( + "Dropping %r over-sized packet (%d bytes) %r", out, len(packet), packet + ) return - log.debug('Sending %r (%d bytes) as %r...', out, len(packet), packet) + log.debug("Sending %r (%d bytes) as %r...", out, len(packet), packet) for s in self._respond_sockets: if self._GLOBAL_DONE: return try: bytes_sent = s.sendto(packet, 0, (addr, port)) - except Exception: # TODO stop catching all Exceptions + except Exception: # TODO stop catching all Exceptions # on send errors, log the exception and keep going self.log_exception_warning() else: if bytes_sent != len(packet): self.log_warning_once( - '!!! sent %d out of %d bytes to %r' % ( - bytes_sent, len(packet)), s) + "!!! sent %d out of %d bytes to %r" % (bytes_sent, len(packet)), s + ) def close(self): """Ends the background threads, and prevent this instance from