From b1509892862a09749f6800db5808a3eb554ddec0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 7 Jul 2020 11:35:58 +0200 Subject: [PATCH 01/14] =?UTF-8?q?=F0=9F=91=B7=E2=80=8D=EF=B8=8F=20Add=20wo?= =?UTF-8?q?rkflow=5Fdispatch=20trigger=20for=20install=20test?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/test_install.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/test_install.yml b/.github/workflows/test_install.yml index 68cf094b3..cbc5f6ad3 100644 --- a/.github/workflows/test_install.yml +++ b/.github/workflows/test_install.yml @@ -4,8 +4,7 @@ on: push: branches: - master - repository_dispatch: - types: [test_install] + workflow_dispatch: schedule: - cron: '0 */12 * * *' From e33b3b5883fd37ecb942da99237892ff0bbcbdce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 15 Jul 2020 11:25:31 +0200 Subject: [PATCH 02/14] =?UTF-8?q?=F0=9F=93=9D=20Update=20dev=20environment?= =?UTF-8?q?=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/development/environment.rst | 144 +++++++++++++++++-------------- 1 file changed, 81 insertions(+), 63 deletions(-) diff --git a/docs/development/environment.rst b/docs/development/environment.rst index 71c953de3..20a4ec2ac 100644 --- a/docs/development/environment.rst +++ b/docs/development/environment.rst @@ -19,12 +19,12 @@ below. * Checkout the OctoPrint sources from their Git repository: - * ``git clone -b devel https://github.com/foosel/OctoPrint.git`` + * ``git clone https://github.com/OctoPrint/OctoPrint.git`` * Enter the checked out source folder: ``cd OctoPrint`` - * Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for - installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies - with system wide installed instances): + * Create virtual environments in the checked out source folder for both Python 2 and Python 3 to use for + installing and running OctoPrint and its dependencies. Creating virtual environments avoids potential versioning + issues for the dependencies with system wide installed instances: * PY2: ``virtualenv --python=python2 venv2`` * PY3: ``virtualenv --python=python3 venv3`` @@ -46,47 +46,43 @@ below. When the virtual environment is activated you can then: * run the OctoPrint server via ``octoprint serve`` - * run the test suite from the checked out source folder via ``nosetests --with-doctest`` - * build the documentation from the ``docs`` sub folder of the checked out sources via ``sphinx-build -b html . _build`` + * run the test suite from the checked out source folder via ``pytest`` To switch the activated virtual environment, simply activate the new environment as described above. To deactivate the virtual environment and return to the system's default Python: ``deactivate``. +If you also want to be able to build the documentation that resides in the ``docs`` subfolder, you need to activate +the *Python 3* environment and install the docs dependencies as well: + + * ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below) + * ``pip install -e .[develop,plugins,docs]`` + +You can then build the documentation: + + * ``sphinx-build -b html . _build`` + .. _sec-development-environment-source-linux: Linux ..... -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. -First make sure you have python including its header files, pip, setuptools, virtualenv, git and some build requirements +First make sure you have python 2 and 3 including their header files, pip, setuptools, virtualenv, git and some build requirements installed: * On apt based distributions (e.g. Debian, Ubuntu, ...): .. code-block:: none - sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv git libyaml-dev build-essential - - * On zypper based distributions (example below for SLES 12 SP2): - - .. code-block:: none - - sudo zypper ar https://download.opensuse.org/repositories/devel:/languages:/python/SLE_12_SP2/ python_devel - sudo zypper ref - sudo zypper in python python-pip python-devel python-setuptools python-virtualenv git libyaml-devel - sudo zypper in -t pattern Basis-Devel + sudo apt-get install python python-pip python-dev python-setuptools python-virtualenv python3 python3-virtualenv python3-dev git libyaml-dev build-essential .. todo:: - Using a Linux distribution that doesn't use ``apt`` or ``zypper``? Please send a - `Pull Request `_ to get the necessary + Using a Linux distribution that doesn't use ``apt``? Please send a + `Pull Request `_ to get the necessary steps into this guide! Then: @@ -94,36 +90,42 @@ Then: .. code-block:: none cd ~/devel - git clone -b devel https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv venv - source ./venv/bin/activate + virtualenv --python=python2 venv2 + virtualenv --python=python3 venv3 + source ./venv2/bin/activate pip install --upgrade pip pip install -e .[develop,plugins] + source ./venv3/bin/activate + pip install --upgrade pip + pip install -e .[develop,plugins,docs] -You can then start OctoPrint via ``~/devel/OctoPrint/venv/bin/octoprint`` or just ``octoprint`` if you activated the virtual -environment. +You can then start OctoPrint via ``octoprint`` after activating one of the two virtual environments. .. _sec-development-environment-windows: Windows ....... -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - This assumes you'll host your OctoPrint development checkout at ``C:\Devel\OctoPrint``. If you want to use a different location, please substitute accordingly. First download & install: - * `Python 2.7.15 Windows x86 MSI installer `_ + * `Git for Windows `_ + * `Latest *stable* Python 2.7 and Python 3.8 releases from python.org `_ + (at the time of writing those are ``2.7.18`` and ``3.8.4``) * make sure to have the installer add Python to the ``PATH`` and have it install ``pip`` too + * it's recommended to install Python 2.7 into ``C:\Python27`` and Python 3 into ``C:\Python38`` - if you select + different install locations please substitute accordingly * `Microsoft Visual C++ Compiler for Python 2.7 `_ - * `Git for Windows `_ + * `Build Tools For Visual Studio 2019 `_ + + * install "C++ build tools" and ensure the latest versions of "MSVCv142 - VS 2019 C++ x64/x86 build tools" and + "Windows 10 SDK" are checked. Open the Git Bash you just installed and in that: @@ -131,12 +133,16 @@ Open the Git Bash you just installed and in that: pip install virtualenv cd /c/Devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint - virtualenv venv - source ./venv/Scripts/activate + virtualenv --python=C:\Python27\python.exe venv2 + virtualenv --python=C:\Python38\python.exe venv3 + source ./venv2/Scripts/activate pip install --upgrade pip pip install -e .[develop,plugins] + source ./venv3/Scripts/activate + pip install --upgrade pip + pip install -e .[develop,plugins,docs] .. _sec-development-environment-mac: @@ -145,12 +151,14 @@ Mac OS X .. note:: - This guide is based on the `Setup Guide for Mac OS X on OctoPrint's wiki `_. + This guide is based on the `Setup Guide for Mac OS X on OctoPrint's forum `_. Please report back if it works for you, due to lack of access to a Mac I cannot test it myself. Thanks. .. todo:: - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. + This guide is not yet adapted to the concurrent use of Python 2 and 3 environments during development. Please send a + `Pull Request `_ to get the necessary + steps into this guide! This assumes you'll host your OctoPrint development checkout at ``~/devel/OctoPrint``. If you want to use a different location, please substitute accordingly. @@ -178,7 +186,7 @@ You'll need a user account with administrator privileges. .. code-block:: none cd ~/devel - git clone https://github.com/foosel/OctoPrint.git + git clone https://github.com/OctoPrint/OctoPrint.git cd OctoPrint virtualenv venv source venv/bin/activate @@ -190,14 +198,10 @@ You'll need a user account with administrator privileges. IDE Setup --------- -.. todo:: - - This guide is not yet adapted to the concurrent use of Python 2.7 and 3.7 environments during development. - .. todo:: Using another IDE than the ones below? Please send a - `Pull Request `_ to get the necessary + `Pull Request `_ to get the necessary steps into this guide! .. _sec-development-environment-ides-pycharm: @@ -206,18 +210,23 @@ PyCharm ....... - "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) - - **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv - folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``) - - **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." > - "Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``) + - Register virtual environments: + + - **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", + select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2`` or ``C:\Devel\OctoPrint\venv2``). + - **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." > + "Virtualenv Environment > "Existing Environment", select OctoPrint ``venv2`` folder (e.g. ``~/devel/OctoPrint/venv2``). + + Repeat for the ``venv3`` folder. + - Right click "src" in project tree, mark as source folder - Add Run/Debug Configuration, select "Python": * Name: OctoPrint server - * Script: path to ``run`` in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/run`` or ``C:\Devel\OctoPrint\run``) - * Script parameters: ``serve --debug`` + * Module name: ``octoprint`` + * Parameters: ``serve --debug`` * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: Project Default * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * If you want dependencies to auto-update on run if necessary: "Before Launch" > "+" > "Run external tool" > "+" @@ -226,29 +235,38 @@ PyCharm * Parameters: ``install -e .[develop,plugins]`` * Working directory: ``$ProjectFileDir$`` - - Add Run/Debug Configuration, select "Python tests" and therein "Nosetests": + Note that sadly that seems to cause some hiccups on current PyCharm versions due to ``$PyInterpreterDirectory$`` + being empty sometimes, so if this fails to run on your installation, you should update your dependencies manually + for now. - * Name: OctoPrint nosetests - * Target: Path, ``.`` + - Add Run/Debug Configuration, select "Python tests" and therein "pytest": + + * Name: OctoPrint tests + * Target: Custom * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: Project Default * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * Just like with the run configuration for the server you can also have the dependencies auto-update on run of the tests, see above on how to set this up. - - Add Run/Debug Configuration, select "Python docs" and therein "Sphinx task" + - Add Run/Debug Configuration, select "Python": * Name: OctoPrint docs - * Command: ``html`` - * Input: the ``docs`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs`` or - ``C:\Devel\OctoPrint\docs``) - * Output: the ``docs/_build`` folder in the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint/docs/_build`` or - ``C:\Devel\OctoPrint\docs\_build``) + * Module name: ``sphinx.cmd.build`` + * Parameters: ``-v -T -E ./docs ./docs/_build -b html`` * Project: ``OctoPrint`` - * Python interpreter: the ``venv`` local virtual environment + * Python interpreter: ``venv3`` environment (the docs build requires Python 3) + * Working directory: the OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``) * Just like with the run configuration for the server you can also have the dependencies auto-update when building the documentation, see above on how to set this up. + Note that this requires you to also have installed the additional ``docs`` dependencies into the Python 3 venv as + described above via ``pip install -e .[develop,plugins,docs]``. + +To switch between Python 2 and 3, all you need to do now is change the Project Default Interpreter and restart +OctoPrint. On current PyCharm versions you can do that right from a small selection field in the footer of the IDE. +Otherwise go through Settings. + .. note:: Make sure you are running a PyCharm version of 2016.1 or later, or manually fix From e9b6d22932a9baa81668dab884fce4b2dbe384a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 28 Jul 2020 14:15:28 +0200 Subject: [PATCH 03/14] =?UTF-8?q?=F0=9F=91=B7=E2=80=8D=EF=B8=8F=20Trigger?= =?UTF-8?q?=20for=20docker=20builds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/trigger_docker.yml | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .github/workflows/trigger_docker.yml diff --git a/.github/workflows/trigger_docker.yml b/.github/workflows/trigger_docker.yml new file mode 100644 index 000000000..1d842b60c --- /dev/null +++ b/.github/workflows/trigger_docker.yml @@ -0,0 +1,18 @@ +name: Trigger docker build +on: + release: + types: + - released + - prereleased + +jobs: + trigger: + runs-on: ubuntu-latest + steps: + - name: 🚀 Repository Dispatch + uses: peter-evans/repository-dispatch@v1 + with: + token: ${{ secrets.DOCKER_ACCESS_TOKEN }} + repository: OctoPrint/docker + event-type: octoprint-release + client-payload: '{"ref": "${{ github.ref }}", "sha": "${{ github.sha }}", "event-name": "${{ github.event_name }}", "event-type": "${{ github.event.action }}"}' From 06637280e55660ac2680cb71a8c5d13c575b7403 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 12:45:23 +0200 Subject: [PATCH 04/14] =?UTF-8?q?=E2=99=BB=20Discovery:=20Switch=20to=20py?= =?UTF-8?q?thon-zeroconf?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pybonjour is no longer maintained and Python 2 only. Closes #3664 --- setup.py | 1 + src/octoprint/plugins/discovery/__init__.py | 198 ++++++++------------ 2 files changed, 81 insertions(+), 118 deletions(-) diff --git a/setup.py b/setup.py index 208fa2fca..44574eb24 100644 --- a/setup.py +++ b/setup.py @@ -34,6 +34,7 @@ INSTALL_REQUIRES = [ "tornado==5.1.1", # newer versions require Python 3 "markdown>=3.1,<3.2", # newer versions require Python 3 "rsa==4.0", # newer versions require Python 3 + "zeroconf==0.19.1", # newer versions require Python 3 "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 # anything below this should be checked on releases for new versions diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 3a12687e9..8de67a274 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -9,7 +9,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250 """ -import logging import flask from flask_babel import gettext @@ -19,18 +18,12 @@ from builtins import range import octoprint.plugin import octoprint.util -try: - # TODO: looks like pybonjour is py2 only - find alternatives or port? - import pybonjour -except ImportError: - pybonjour = False - +import zeroconf +import time +import collections +import socket def __plugin_load__(): - if not pybonjour: - # no pybonjour available, we can't use that - logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available") - plugin = DiscoveryPlugin() global __plugin_implementation__ @@ -38,14 +31,11 @@ def __plugin_load__(): global __plugin_helpers__ __plugin_helpers__ = dict( - ssdp_browse=plugin.ssdp_browse + ssdp_browse=plugin.ssdp_browse, + zeroconf_browse = plugin.zeroconf_browse, + zeroconf_register = plugin.zeroconf_register, + zeroconf_unregister = plugin.zeroconf_unregister ) - if pybonjour: - __plugin_helpers__.update(dict( - zeroconf_browse=plugin.zeroconf_browse, - zeroconf_register=plugin.zeroconf_register, - zeroconf_unregister=plugin.zeroconf_unregister - )) class DiscoveryPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.ShutdownPlugin, @@ -62,8 +52,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self.port = None # zeroconf - self._sd_refs = dict() - self._cnames = dict() + self._zeroconf = zeroconf.Zeroconf() + self._zeroconf_registrations = collections.defaultdict(list) # upnp/ssdp self._ssdp_monitor_active = False @@ -158,7 +148,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, ##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown def on_shutdown(self): - for key in self._sd_refs: + for key in self._zeroconf_registrations: reg_type, port = key self.zeroconf_unregister(reg_type, port) @@ -168,6 +158,27 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, # ZeroConf + def _format_zeroconf_service_type(self, service_type): + service_type = octoprint.util.to_native_str(service_type) + if not service_type.endswith(octoprint.util.to_native_str(".")): + service_type += octoprint.util.to_native_str(".") + if not service_type.endswith(octoprint.util.to_native_str("local.")): + service_type += octoprint.util.to_native_str("local.") + return service_type + + def _format_zeroconf_name(self, name, service_type): + service_type = self._format_zeroconf_service_type(service_type) + return octoprint.util.to_native_str(name) + octoprint.util.to_native_str(".") + service_type + + def _format_zeroconf_txt(self, record): + result = dict() + if not record: + return result + + for key, value in record.items(): + result[octoprint.util.to_bytes(key)] = octoprint.util.to_bytes(value) + return result + def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None): """ Registers a new service with Zeroconf/Bonjour/Avahi. @@ -178,37 +189,31 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, :param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs """ - if not pybonjour: - return - if not name: name = self.get_instance_name() if not port: port = self.port - params = dict( - name=name, - regtype=reg_type, - port=port - ) - if txt_record: - params["txtRecord"] = pybonjour.TXTRecord(txt_record) + reg_type = self._format_zeroconf_service_type(reg_type) + name = self._format_zeroconf_name(name, reg_type) + txt_record = self._format_zeroconf_txt(txt_record) key = (reg_type, port) + addresses = octoprint.util.net.interface_addresses() - counter = 1 - while True: - try: - self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) - self._logger.info("Registered '{name}' for {regtype}".format(**params)) - return True - except pybonjour.BonjourError as be: - if be.errorCode == pybonjour.kDNSServiceErr_NameConflict: - # Name already registered by different service, let's try a counter postfix. See #2852 - counter += 1 - params["name"] = "{} ({})".format(name, counter) - else: - raise + try: + for address in addresses: + info = zeroconf.ServiceInfo(reg_type, + name, + address=socket.inet_aton(address), + port=port, + properties=txt_record) + self._zeroconf.register_service(info, allow_name_change=True) + self._zeroconf_registrations[key].append(info) + + self._logger.info("Registered '{}' for {}".format(name, reg_type)) + except Exception: + self._logger.exception("Could not (fully) register {} for {} on port {}".format(name, reg_type, port)) def zeroconf_unregister(self, reg_type, port=None): """ @@ -219,22 +224,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, :return: """ - if not pybonjour: - return - if not port: port = self.port + reg_type = self._format_zeroconf_service_type(reg_type) key = (reg_type, port) - if not key in self._sd_refs: + if not key in self._zeroconf_registrations: return - sd_ref = self._sd_refs[key] + infos = self._zeroconf_registrations.pop(key) try: - sd_ref.close() - self._logger.debug("Unregistered {reg_type} on port {port}".format(reg_type=reg_type, port=port)) - except Exception: - self._logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) + for info in infos: + self._zeroconf.unregister_service(info) + self._logger.debug("Unregistered {} on port {}".format(reg_type, port)) + except: + self._logger.exception("Could not (fully) unregister {} on port {}".format(reg_type, port)) def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): """ @@ -271,79 +275,43 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, supplied to the callback instead) """ - if not pybonjour: - return None - import threading - import select if not block and not callback: raise ValueError("Non-blocking mode but no callback given") + service_type = self._format_zeroconf_service_type(service_type) + result = [] result_available = threading.Event() result_available.clear() - resolved = [] + class ZeroconfListener(object): + def __init__(self, logger): + self._logger = logger - def resolve_callback(sd_ref, flags, interface_index, error_code, fullname, hosttarget, port, txt_record): - if error_code == pybonjour.kDNSServiceErr_NoError: - txt_record_dict = None - if txt_record: - record = pybonjour.TXTRecord.parse(txt_record) - txt_record_dict = dict() - for key, value in record: - txt_record_dict[key] = value - - name = fullname[:fullname.find(service_type) - 1].replace("\\032", " ") - host = hosttarget[:-1] - - self._logger.debug("Resolved a result for Zeroconf resolution of {service_type}: {name} @ {host}".format(service_type=service_type, name=name, host=host)) - result.append(dict( - name=name, - host=host, - port=port, - txt_record=txt_record_dict - )) - resolved.append(True) - - def browse_callback(sd_ref, flags, interface_index, error_code, service_name, regtype, reply_domain): - if error_code != pybonjour.kDNSServiceErr_NoError: - return - - if not (flags & pybonjour.kDNSServiceFlagsAdd): - return - - self._logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type)) - resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback) - - try: - while not resolved: - ready = select.select([resolve_ref], [], [], resolve_timeout) - if resolve_ref not in ready[0]: - break - - pybonjour.DNSServiceProcessResult(resolve_ref) - else: - resolved.pop() - finally: - resolve_ref.close() + def add_service(self, zeroconf, type, name): + self._logger.debug("Got a browsing result for Zeroconf resolution of {}, resolving...".format(type)) + info = zeroconf.get_service_info(type, name, timeout=resolve_timeout * 1000) + if info: + address = socket.inet_ntoa(info.address) + self._logger.debug("Resolved a result for Zeroconf resolution of {}: {} @ {}".format(type, + name, + address)) + result.append(dict( + name=info.name[:-(len(type) + 1)], + host=address, + port=info.port, + txt_record=info.properties + )) self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) def browse(): - sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback) - try: - while True: - ready = select.select([sd_ref], [], [], browse_timeout) - - if not ready[0]: - break - - if sd_ref in ready[0]: - pybonjour.DNSServiceProcessResult(sd_ref) - finally: - sd_ref.close() + listener = ZeroconfListener(self._logger) + browser = zeroconf.ServiceBrowser(self._zeroconf, service_type, listener) + time.sleep(browse_timeout) + browser.cancel() if callback: callback(result) @@ -414,8 +382,6 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, result_available.clear() def browse(): - import socket - socket.setdefaulttimeout(timeout) search_message = "".join([ @@ -568,8 +534,6 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, :param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message """ - import socket - if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > octoprint.util.monotonic_time(): # we just sent an alive, no need to send another one now return @@ -627,7 +591,6 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, from BaseHTTPServer import BaseHTTPRequestHandler from io import BytesIO - import socket socket.setdefaulttimeout(timeout) @@ -703,7 +666,6 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if name: return "OctoPrint instance \"{}\"".format(name) else: - import socket return "OctoPrint instance on {}".format(socket.gethostname()) From 65937a9244d293e4d925cee679eeb43c065f8f72 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 12:50:02 +0200 Subject: [PATCH 05/14] =?UTF-8?q?=F0=9F=92=9A=20Make=20flake=208=20happy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/discovery/__init__.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index 8de67a274..a334d3042 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -133,14 +133,12 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, # Zeroconf self.zeroconf_register("_http._tcp", self.get_instance_name(), txt_record=self._create_http_txt_record_dict()) self.zeroconf_register("_octoprint._tcp", self.get_instance_name(), txt_record=self._create_octoprint_txt_record_dict()) - for zeroconf in self._settings.get(["zeroConf"]): - if "service" in zeroconf: - self.zeroconf_register( - zeroconf["service"], - zeroconf["name"] if "name" in zeroconf else self.get_instance_name(), - port=zeroconf["port"] if "port" in zeroconf else None, - txt_record=zeroconf["txtRecord"] if "txtRecord" in zeroconf else None - ) + for zc in self._settings.get(["zeroConf"]): + if "service" in zc: + self.zeroconf_register(zc["service"], + zc.get("name", self.get_instance_name()), + port=zc.get("port"), + txt_record=zc.get("txtRecord")) # SSDP self._ssdp_register() From cae900b1fb089ec99d79a0051ef974e4adc0208e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 13:04:27 +0200 Subject: [PATCH 06/14] =?UTF-8?q?=F0=9F=A5=85=20Try=20up=20to=20three=20ti?= =?UTF-8?q?mes=20to=20check=20for=20connectivity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Apparently some machines out there are a bit flaky after boot and it can take a bit for connectivity to work. As suggested by @fieldOfView in https://community.octoprint.org/t//177/9 we thus check connectivity three times in a row if negative before reporting it as negative. --- src/octoprint/util/connectivity.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/octoprint/util/connectivity.py b/src/octoprint/util/connectivity.py index 2cd90f964..93145f7d0 100644 --- a/src/octoprint/util/connectivity.py +++ b/src/octoprint/util/connectivity.py @@ -7,6 +7,7 @@ __copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms import threading import logging +import time from octoprint.util.net import server_reachable, resolve_host @@ -171,16 +172,26 @@ class ConnectivityChecker(object): self._logger.debug("Checking against {}:{} if we are online...".format(self._host, self._port)) old_value = self._online - self._connection_working = server_reachable(self._host, port=self._port) - if self._name: - if self._connection_working: - self._logger.debug("Checking if we can resolve {}...".format(self._name)) - self._resolution_working = len(resolve_host(self._name)) > 0 + for _ in range(3): + connection_working = server_reachable(self._host, port=self._port) + + if self._name: + if connection_working: + self._logger.debug("Checking if we can resolve {}...".format(self._name)) + resolution_working = len(resolve_host(self._name)) > 0 + else: + resolution_working = False else: - self._resolution_working = False - else: - self._resolution_working = True + resolution_working = True + + if not (connection_working and resolution_working): + # retry up to 3 times + time.sleep(1.0) + continue + + self._connection_working = connection_working + self._resolution_working = resolution_working if old_value != self._online: self._trigger_change(old_value, self._online) From fb8fcb068584827e2174566179761db99d65fbcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 13:13:41 +0200 Subject: [PATCH 07/14] =?UTF-8?q?=E2=99=BB=20Vendor=20bundle=20python-zero?= =?UTF-8?q?conf?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We need to use an older version for Python 2 compatibility reasons but need to fix some things on that. --- setup.py | 1 - src/octoprint/plugins/discovery/__init__.py | 2 +- src/octoprint/vendor/zeroconf.py | 2046 +++++++++++++++++++ 3 files changed, 2047 insertions(+), 2 deletions(-) create mode 100644 src/octoprint/vendor/zeroconf.py diff --git a/setup.py b/setup.py index 44574eb24..208fa2fca 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,6 @@ INSTALL_REQUIRES = [ "tornado==5.1.1", # newer versions require Python 3 "markdown>=3.1,<3.2", # newer versions require Python 3 "rsa==4.0", # newer versions require Python 3 - "zeroconf==0.19.1", # newer versions require Python 3 "regex!=2018.11.6", # avoid broken 2018.11.6. See #2874 # anything below this should be checked on releases for new versions diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index a334d3042..a22ff0d33 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -18,7 +18,7 @@ from builtins import range import octoprint.plugin import octoprint.util -import zeroconf +import octoprint.vendor.zeroconf as zeroconf import time import collections import socket diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py new file mode 100644 index 000000000..31416afa2 --- /dev/null +++ b/src/octoprint/vendor/zeroconf.py @@ -0,0 +1,2046 @@ +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 + + This module provides a framework for the use of DNS Service Discovery + using IP multicast. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 + USA +""" + +import enum +import errno +import logging +import re +import select +import socket +import struct +import sys +import threading +import time +from functools import reduce + +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' + + +__all__ = [ + "__version__", + "Zeroconf", "ServiceInfo", "ServiceBrowser", + "Error", "InterfaceChoice", "ServiceStateChange", +] + + +log = logging.getLogger(__name__) +log.addHandler(logging.NullHandler()) + +if log.level == logging.NOTSET: + log.setLevel(logging.WARN) + +# Some timing constants + +_UNREGISTER_TIME = 125 +_CHECK_TIME = 175 +_REGISTER_TIME = 225 +_LISTENER_TIME = 200 +_BROWSER_TIME = 500 + +# Some DNS constants + +_MDNS_ADDR = '224.0.0.251' +_MDNS_PORT = 5353 +_DNS_PORT = 53 +_DNS_TTL = 60 * 60 # one hour default TTL + +_MAX_MSG_TYPICAL = 1460 # unused +_MAX_MSG_ABSOLUTE = 8966 + +_FLAGS_QR_MASK = 0x8000 # query response mask +_FLAGS_QR_QUERY = 0x0000 # query +_FLAGS_QR_RESPONSE = 0x8000 # response + +_FLAGS_AA = 0x0400 # Authoritative answer +_FLAGS_TC = 0x0200 # Truncated +_FLAGS_RD = 0x0100 # Recursion desired +_FLAGS_RA = 0x8000 # Recursion available + +_FLAGS_Z = 0x0040 # Zero +_FLAGS_AD = 0x0020 # Authentic data +_FLAGS_CD = 0x0010 # Checking disabled + +_CLASS_IN = 1 +_CLASS_CS = 2 +_CLASS_CH = 3 +_CLASS_HS = 4 +_CLASS_NONE = 254 +_CLASS_ANY = 255 +_CLASS_MASK = 0x7FFF +_CLASS_UNIQUE = 0x8000 + +_TYPE_A = 1 +_TYPE_NS = 2 +_TYPE_MD = 3 +_TYPE_MF = 4 +_TYPE_CNAME = 5 +_TYPE_SOA = 6 +_TYPE_MB = 7 +_TYPE_MG = 8 +_TYPE_MR = 9 +_TYPE_NULL = 10 +_TYPE_WKS = 11 +_TYPE_PTR = 12 +_TYPE_HINFO = 13 +_TYPE_MINFO = 14 +_TYPE_MX = 15 +_TYPE_TXT = 16 +_TYPE_AAAA = 28 +_TYPE_SRV = 33 +_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"} + +_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]') + + +@enum.unique +class InterfaceChoice(enum.Enum): + Default = 1 + All = 2 + + +@enum.unique +class ServiceStateChange(enum.Enum): + Added = 1 + Removed = 2 + + +HOST_ONLY_NETWORK_MASK = '255.255.255.255' + + +# utility functions + + +def current_time_millis(): + """Current system time in milliseconds""" + return time.time() * 1000 + + +def service_type_name(type_): + """ + Validate a fully qualified service name, instance or subtype. [rfc6763] + + Returns fully qualified service name. + + Domain names used by mDNS-SD take the following forms: + + . <_tcp|_udp> . local. + . . <_tcp|_udp> . local. + ._sub . . <_tcp|_udp> . local. + + 1) must end with 'local.' + + This is true because we are implementing mDNS and since the 'm' means + multi-cast, the 'local.' domain is mandatory. + + 2) local is preceded with either '_udp.' or '_tcp.' + + 3) service name precedes <_tcp|_udp> + + The rules for Service Names [RFC6335] state that they may be no more + than fifteen characters long (not counting the mandatory underscore), + consisting of only letters, digits, and hyphens, must begin and end + with a letter or digit, must not contain consecutive hyphens, and + must contain at least one letter. + + The instance name and sub type may be up to 63 bytes. + + The portion of the Service Instance Name is a user- + friendly name consisting of arbitrary Net-Unicode text [RFC5198]. It + MUST NOT contain ASCII control characters (byte values 0x00-0x1F and + 0x7F) [RFC20] but otherwise is allowed to contain any characters, + without restriction, including spaces, uppercase, lowercase, + punctuation -- including dots -- accented characters, non-Roman text, + and anything else that may be represented using Net-Unicode. + + :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.')): + raise BadTypeInNameException( + "Type '%s' must end with '._tcp.local.' or '._udp.local.'" % + type_) + + 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_) + + 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) + + if '--' in name: + raise BadTypeInNameException( + "Service name (%s) must not contain '--'" % name) + + if '-' in (name[0], name[-1]): + raise BadTypeInNameException( + "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) + + 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) + + if remaining and remaining[-1] == '_sub': + remaining.pop() + if len(remaining) == 0 or len(remaining[0]) == 0: + raise BadTypeInNameException( + "_sub requires a subtype name") + + if len(remaining) > 1: + remaining = ['.'.join(remaining)] + + if remaining: + 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]) + + return '_' + name + type_[-len('._tcp.local.'):] + + +# Exceptions + + +class Error(Exception): + pass + + +class IncomingDecodeError(Error): + pass + + +class NonUniqueNameException(Error): + pass + + +class NamePartTooLongException(Error): + pass + + +class AbstractMethodException(Error): + pass + + +class BadTypeInNameException(Error): + pass + +# implementation classes + + +class QuietLogger(object): + _seen_logs = {} + + @classmethod + def log_exception_warning(cls, logger_data=None): + exc_info = sys.exc_info() + exc_str = str(exc_info[1]) + if exc_str not in cls._seen_logs: + # log at warning level the first time this is seen + cls._seen_logs[exc_str] = exc_info + logger = log.warning + else: + logger = log.debug + if logger_data is not None: + logger(*logger_data) + logger('Exception occurred:', exc_info=exc_info) + + @classmethod + def log_warning_once(cls, *args): + msg_str = args[0] + if msg_str not in cls._seen_logs: + cls._seen_logs[msg_str] = 0 + logger = log.warning + else: + logger = log.debug + cls._seen_logs[msg_str] += 1 + logger(*args) + + +class DNSEntry(object): + + """A DNS entry""" + + def __init__(self, name, type_, class_): + self.key = name.lower() + self.name = name + self.type = type_ + self.class_ = class_ & _CLASS_MASK + self.unique = (class_ & _CLASS_UNIQUE) != 0 + + def __eq__(self, other): + """Equality test on name, type, and class""" + return (isinstance(other, DNSEntry) and + self.name == other.name and + self.type == other.type and + self.class_ == other.class_) + + def __ne__(self, other): + """Non-equality test""" + return not self.__eq__(other) + + @staticmethod + def get_class_(class_): + """Class accessor""" + return _CLASSES.get(class_, "?(%s)" % class_) + + @staticmethod + def get_type(t): + """Type accessor""" + return _TYPES.get(t, "?(%s)" % t) + + 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_)) + if self.unique: + result += "-unique," + else: + result += "," + result += self.name + if other is not None: + result += ",%s]" % other + else: + result += "]" + return result + + +class DNSQuestion(DNSEntry): + + """A DNS question entry""" + + def __init__(self, name, type_, class_): + DNSEntry.__init__(self, name, type_, class_) + + 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) + + def __repr__(self): + """String representation""" + return DNSEntry.to_string(self, "question", None) + + +class DNSRecord(DNSEntry): + + """A DNS record - like a DNS entry, but has a TTL""" + + def __init__(self, name, type_, class_, ttl): + DNSEntry.__init__(self, name, type_, class_) + self.ttl = ttl + self.created = current_time_millis() + + def __eq__(self, other): + """Abstract method""" + raise AbstractMethodException + + def suppressed_by(self, msg): + """Returns true if any answer in a message can suffice for the + information held in this record.""" + for record in msg.answers: + if self.suppressed_by_answer(record): + return True + return False + + def suppressed_by_answer(self, other): + """Returns true if another record has same name, type and class, + and if its TTL is at least half of this record's.""" + return self == other and other.ttl > (self.ttl / 2) + + def get_expiration_time(self, percent): + """Returns the time at which this record will have expired + by a certain percentage.""" + return self.created + (percent * self.ttl * 10) + + def get_remaining_ttl(self, now): + """Returns the remaining TTL in seconds.""" + return max(0, (self.get_expiration_time(100) - now) / 1000.0) + + def is_expired(self, now): + """Returns true if this record has expired.""" + return self.get_expiration_time(100) <= now + + def is_stale(self, now): + """Returns true if this record is at least half way expired.""" + return self.get_expiration_time(50) <= now + + def reset_ttl(self, other): + """Sets this record's TTL and created time to that of + another record.""" + self.created = other.created + self.ttl = other.ttl + + def write(self, out): + """Abstract method""" + raise AbstractMethodException + + def to_string(self, other): + """String representation with additional information""" + arg = "%s/%s,%s" % ( + self.ttl, self.get_remaining_ttl(current_time_millis()), other) + return DNSEntry.to_string(self, "record", arg) + + +class DNSAddress(DNSRecord): + + """A DNS address record""" + + def __init__(self, name, type_, class_, ttl, address): + DNSRecord.__init__(self, name, type_, class_, ttl) + self.address = address + + def write(self, out): + """Used in constructing an outgoing packet""" + out.write_string(self.address) + + def __eq__(self, other): + """Tests equality on address""" + return isinstance(other, DNSAddress) and self.address == other.address + + def __repr__(self): + """String representation""" + try: + return str(socket.inet_ntoa(self.address)) + except Exception: # TODO stop catching all Exceptions + return str(self.address) + + +class DNSHinfo(DNSRecord): + + """A DNS host information record""" + + def __init__(self, name, type_, class_, ttl, cpu, os): + DNSRecord.__init__(self, name, type_, class_, ttl) + try: + self.cpu = cpu.decode('utf-8') + except AttributeError: + self.cpu = cpu + try: + 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')) + + def __eq__(self, other): + """Tests equality on cpu and os""" + return (isinstance(other, DNSHinfo) and + self.cpu == other.cpu and self.os == other.os) + + def __repr__(self): + """String representation""" + return self.cpu + " " + self.os + + +class DNSPointer(DNSRecord): + + """A DNS pointer record""" + + def __init__(self, name, type_, class_, ttl, alias): + DNSRecord.__init__(self, name, type_, class_, ttl) + self.alias = alias + + def write(self, out): + """Used in constructing an outgoing packet""" + out.write_name(self.alias) + + def __eq__(self, other): + """Tests equality on alias""" + return isinstance(other, DNSPointer) and self.alias == other.alias + + def __repr__(self): + """String representation""" + return self.to_string(self.alias) + + +class DNSText(DNSRecord): + + """A DNS text record""" + + def __init__(self, name, type_, class_, ttl, text): + assert isinstance(text, (bytes, type(None))) + DNSRecord.__init__(self, name, type_, class_, ttl) + self.text = text + + def write(self, out): + """Used in constructing an outgoing packet""" + out.write_string(self.text) + + def __eq__(self, other): + """Tests equality on text""" + return isinstance(other, DNSText) and self.text == other.text + + def __repr__(self): + """String representation""" + if len(self.text) > 10: + return self.to_string(self.text[:7]) + "..." + else: + return self.to_string(self.text) + + +class DNSService(DNSRecord): + + """A DNS service record""" + + def __init__(self, name, type_, class_, ttl, + priority, weight, port, server): + DNSRecord.__init__(self, name, type_, class_, ttl) + self.priority = priority + self.weight = weight + self.port = port + self.server = server + + def write(self, out): + """Used in constructing an outgoing packet""" + out.write_short(self.priority) + out.write_short(self.weight) + out.write_short(self.port) + out.write_name(self.server) + + 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) + + def __repr__(self): + """String representation""" + return self.to_string("%s:%s" % (self.server, self.port)) + + +class DNSIncoming(QuietLogger): + + """Object representation of an incoming DNS packet""" + + def __init__(self, data): + """Constructor from string holding bytes of packet""" + self.offset = 0 + self.data = data + self.questions = [] + self.answers = [] + self.id = 0 + self.flags = 0 + self.num_questions = 0 + self.num_answers = 0 + self.num_authorities = 0 + self.num_additionals = 0 + self.valid = False + + try: + self.read_header() + self.read_questions() + self.read_others() + self.valid = True + + except (IndexError, struct.error, IncomingDecodeError): + 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]) + 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') + + 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') + + question = DNSQuestion(name, type_, class_) + self.questions.append(question) + + # def read_int(self): + # """Reads an integer from the packet""" + # return self.unpack(b'!I')[0] + + def read_character_string(self): + """Reads a character string from the packet""" + length = indexbytes(self.data, self.offset) + self.offset += 1 + return self.read_string(length) + + def read_string(self, length): + """Reads a string of a given length from the packet""" + 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] + + def read_others(self): + """Reads the answers, authorities and additionals section of the + packet""" + 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') + + rec = None + if type_ == _TYPE_A: + 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()) + elif type_ == _TYPE_TXT: + 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()) + elif type_ == _TYPE_HINFO: + rec = DNSHinfo( + 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)) + else: + # Try to ignore types we don't know about + # Skip the payload for the resource record so the next + # records can be parsed correctly + self.offset += length + + if rec is not None: + self.answers.append(rec) + + def is_query(self): + """Returns true if this is a query""" + return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY + + def is_response(self): + """Returns true if this is a response""" + return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE + + 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') + + def read_name(self): + """Reads a domain name from the packet""" + result = '' + off = self.offset + next_ = -1 + first = off + + while True: + length = indexbytes(self.data, off) + off += 1 + if length == 0: + break + t = length & 0xC0 + if t == 0x00: + 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,)) + first = off + else: + raise IncomingDecodeError("Bad domain name at %s" % (off,)) + + if next_ >= 0: + self.offset = next_ + else: + self.offset = off + + return result + + +class DNSOutgoing(object): + + """Object representation of an outgoing packet""" + + def __init__(self, flags, multicast=True): + self.finished = False + self.id = 0 + self.multicast = multicast + self.flags = flags + self.names = {} + self.data = [] + self.size = 12 + self.state = self.State.init + + self.questions = [] + self.answers = [] + self.authorities = [] + 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, + ]) + + class State(enum.Enum): + init = 0 + finished = 1 + + def add_question(self, record): + """Adds a question""" + self.questions.append(record) + + def add_answer(self, inp, record): + """Adds an answer""" + if not record.suppressed_by(inp): + self.add_answer_at_time(record, 0) + + def add_answer_at_time(self, record, now): + """Adds an answer if it does not expire by a certain time""" + if record is not None: + if now == 0 or not record.is_expired(now): + self.answers.append((record, now)) + + def add_authorative_answer(self, record): + """Adds an authoritative answer""" + self.authorities.append(record) + + def add_additional_answer(self, record): + """ Adds an additional answer + + From: RFC 6763, DNS-Based Service Discovery, February 2013 + + 12. DNS Additional Record Generation + + DNS has an efficiency feature whereby a DNS server may place + additional records in the additional section of the DNS message. + These additional records are records that the client did not + explicitly request, but the server has reasonable grounds to expect + that the client might request them shortly, so including them can + save the client from having to issue additional queries. + + This section recommends which additional records SHOULD be generated + to improve network efficiency, for both Unicast and Multicast DNS-SD + responses. + + 12.1. PTR Records + + When including a DNS-SD Service Instance Enumeration or Selective + Instance Enumeration (subtype) PTR record in a response packet, the + server/responder SHOULD include the following additional records: + + o The SRV record(s) named in the PTR rdata. + o The TXT record(s) named in the PTR rdata. + o All address records (type "A" and "AAAA") named in the SRV rdata. + + 12.2. SRV Records + + When including an SRV record in a response packet, the + server/responder SHOULD include the following additional records: + + o All address records (type "A" and "AAAA") named in the SRV rdata. + + """ + self.additionals.append(record) + + def pack(self, format_, value): + self.data.append(struct.pack(format_, value)) + self.size += struct.calcsize(format_) + + def write_byte(self, value): + """Writes a single byte to the packet""" + 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.size += 2 + + def write_short(self, value): + """Writes an unsigned short to the packet""" + self.pack(b'!H', value) + + def write_int(self, value): + """Writes an unsigned integer to the packet""" + self.pack(b'!I', int(value)) + + def write_string(self, value): + """Writes a string to the packet""" + assert isinstance(value, bytes) + self.data.append(value) + self.size += len(value) + + def write_utf(self, s): + """Writes a UTF-8 string of a given length to the packet""" + utfstr = s.encode('utf-8') + length = len(utfstr) + if length > 64: + raise NamePartTooLongException + self.write_byte(length) + self.write_string(utfstr) + + def write_character_string(self, value): + assert isinstance(value, bytes) + length = len(value) + if length > 256: + raise NamePartTooLongException + self.write_byte(length) + self.write_string(value) + + def write_name(self, name): + """ + Write names to packet + + 18.14. Name Compression + + When generating Multicast DNS messages, implementations SHOULD use + name compression wherever possible to compress the names of resource + records, by replacing some or all of the resource record name with a + compact two-byte reference to an appearance of that data somewhere + earlier in the message [RFC1035]. + """ + + # split name into each label + parts = name.split('.') + if not parts[-1]: + parts.pop() + + # construct each suffix + 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): + if sub_name in self.names: + break + else: + count += 1 + + # note the new names we are saving into the packet + for suffix in name_suffices[:count]: + self.names[suffix] = self.size + len(name) - len(suffix) - 1 + + # write the new names out. + for part in parts[:count]: + self.write_utf(part) + + # if we wrote part of the name, create a pointer to the rest + if count != len(name_suffices): + # Found substring in packet, create pointer + index = self.names[name_suffices[count]] + self.write_byte((index >> 8) | 0xC0) + self.write_byte(index & 0xFF) + else: + # this is the end of a name + self.write_byte(0) + + def write_question(self, question): + """Writes a question to the packet""" + self.write_name(question.name) + self.write_short(question.type) + self.write_short(question.class_) + + def write_record(self, record, now): + """Writes a record (answer, authoritative answer, additional) to + the packet""" + if self.state == self.State.finished: + return 1 + + start_data_length, start_size = len(self.data), self.size + self.write_name(record.name) + self.write_short(record.type) + if record.unique and self.multicast: + self.write_short(record.class_ | _CLASS_UNIQUE) + else: + self.write_short(record.class_) + if now == 0: + self.write_int(record.ttl) + else: + self.write_int(record.get_remaining_ttl(now)) + index = len(self.data) + + # Adjust size for the short we will write before this record + self.size += 2 + record.write(self) + self.size -= 2 + + length = sum((len(d) for d in self.data[index:])) + # Here is the short we adjusted for + self.insert_short(index, length) + + # if we go over, then rollback and quit + if self.size > _MAX_MSG_ABSOLUTE: + while len(self.data) > start_data_length: + self.data.pop() + self.size = start_size + self.state = self.State.finished + return 1 + return 0 + + def packet(self): + """Returns a string containing the packet's bytes + + No further parts should be added to the packet once this + is done.""" + + overrun_answers, overrun_authorities, overrun_additionals = 0, 0, 0 + + if self.state != self.State.finished: + for question in self.questions: + self.write_question(question) + for answer, time_ in self.answers: + overrun_answers += self.write_record(answer, time_) + for authority in self.authorities: + overrun_authorities += self.write_record(authority, 0) + for additional in self.additionals: + overrun_additionals += self.write_record(additional, 0) + self.state = self.State.finished + + self.insert_short(0, len(self.additionals) - overrun_additionals) + self.insert_short(0, len(self.authorities) - overrun_authorities) + self.insert_short(0, len(self.answers) - overrun_answers) + self.insert_short(0, len(self.questions)) + self.insert_short(0, self.flags) + if self.multicast: + self.insert_short(0, 0) + else: + self.insert_short(0, self.id) + return b''.join(self.data) + + +class DNSCache(object): + + """A cache of DNS entries""" + + def __init__(self): + self.cache = {} + + def add(self, entry): + """Adds an entry""" + self.cache.setdefault(entry.key, []).append(entry) + + def remove(self, entry): + """Removes an entry""" + try: + list_ = self.cache[entry.key] + list_.remove(entry) + except (KeyError, ValueError): + pass + + def get(self, entry): + """Gets an entry by key. Will return None if there is no + matching entry.""" + try: + list_ = self.cache[entry.key] + for cached_entry in list_: + if entry.__eq__(cached_entry): + return cached_entry + except (KeyError, ValueError): + return None + + def get_by_details(self, name, type_, class_): + """Gets an entry by details. Will return None if there is + no matching entry.""" + entry = DNSEntry(name, type_, class_) + return self.get(entry) + + def entries_with_name(self, name): + """Returns a list of entries whose key matches the name.""" + try: + return self.cache[name.lower()] + except KeyError: + return [] + + 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): + return record + + def entries(self): + """Returns a list of all entries""" + if not self.cache: + return [] + else: + # avoid size change during iteration by copying the cache + values = list(self.cache.values()) + return reduce(lambda a, b: a + b, values) + + +class Engine(threading.Thread): + + """An engine wraps read access to sockets, allowing objects that + need to receive data from sockets to be called back when the + sockets are ready. + + A reader needs a handle_read() method, which is called when the socket + it is interested in is ready for reading. + + Writers are not implemented here, because we only send short + packets. + """ + + def __init__(self, zc): + threading.Thread.__init__(self, name='zeroconf-Engine') + self.daemon = True + self.zc = zc + self.readers = {} # maps socket to reader + self.timeout = 5 + self.condition = threading.Condition() + self.start() + + def run(self): + while not self.zc.done: + with self.condition: + rs = self.readers.keys() + if len(rs) == 0: + # No sockets to manage, but we wait for the timeout + # or addition of a socket + self.condition.wait(self.timeout) + + if len(rs) != 0: + try: + rr, wr, er = select.select(rs, [], [], self.timeout) + if not self.zc.done: + for socket_ in rr: + reader = self.readers.get(socket_) + if reader: + reader.handle_read(socket_) + + except (select.error, socket.error) as e: + # If the socket was closed by another thread, during + # shutdown, ignore it and exit + if e.args[0] != socket.EBADF or not self.zc.done: + raise + + def add_reader(self, reader, socket_): + with self.condition: + self.readers[socket_] = reader + self.condition.notify() + + def del_reader(self, socket_): + with self.condition: + del self.readers[socket_] + self.condition.notify() + + +class Listener(QuietLogger): + + """A Listener is used by this module to listen on the multicast + group to which DNS messages are sent, allowing the implementation + to cache information as it arrives. + + It requires registration with an Engine object in order to have + the read() method called when a socket is available for reading.""" + + def __init__(self, zc): + self.zc = zc + self.data = None + + def handle_read(self, socket_): + try: + data, (addr, port) = socket_.recvfrom(_MAX_MSG_ABSOLUTE) + except Exception: + self.log_exception_warning() + return + + log.debug('Received from %r:%r: %r ', addr, port, data) + + self.data = data + msg = DNSIncoming(data) + if not msg.valid: + pass + + elif msg.is_query(): + # Always multicast responses + if port == _MDNS_PORT: + self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT) + + # If it's not a multicast query, reply via unicast + # and multicast + elif port == _DNS_PORT: + self.zc.handle_query(msg, addr, port) + self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT) + + else: + self.zc.handle_response(msg) + + +class Reaper(threading.Thread): + + """A Reaper is used by this module to remove cache entries that + have expired.""" + + def __init__(self, zc): + threading.Thread.__init__(self, name='zeroconf-Reaper') + self.daemon = True + self.zc = zc + self.start() + + def run(self): + while True: + self.zc.wait(10 * 1000) + if self.zc.done: + return + now = current_time_millis() + for record in self.zc.cache.entries(): + if record.is_expired(now): + self.zc.update_record(now, record) + self.zc.cache.remove(record) + + +class Signal(object): + def __init__(self): + self._handlers = [] + + def fire(self, **kwargs): + for h in list(self._handlers): + h(**kwargs) + + @property + def registration_interface(self): + return SignalRegistrationInterface(self._handlers) + + +class SignalRegistrationInterface(object): + + def __init__(self, handlers): + self._handlers = handlers + + def register_handler(self, handler): + self._handlers.append(handler) + return self + + def unregister_handler(self, handler): + self._handlers.remove(handler) + return self + + +class ServiceBrowser(threading.Thread): + + """Used to browse for a service of a specific type. + + The listener object will have its add_service() and + remove_service() methods called when this browser + discovers changes in the services availability.""" + + 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' + if not type_.endswith(service_type_name(type_)): + raise BadTypeInNameException + threading.Thread.__init__( + self, name='zeroconf-ServiceBrowser_' + type_) + self.daemon = True + self.zc = zc + self.type = type_ + self.services = {} + self.next_time = current_time_millis() + self.delay = _BROWSER_TIME + self._handlers_to_call = [] + + self._service_state_changed = Signal() + + self.done = False + + 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: + listener.add_service(*args) + elif state_change is ServiceStateChange.Removed: + listener.remove_service(*args) + else: + raise NotImplementedError(state_change) + handlers.append(on_change) + + for h in handlers: + self.service_state_changed.register_handler(h) + + self.start() + + @property + def service_state_changed(self): + return self._service_state_changed.registration_interface + + def update_record(self, zc, now, record): + """Callback invoked by Zeroconf when new information arrives. + + Updates information required by browser in the Zeroconf cache.""" + + def enqueue_callback(state_change, name): + self._handlers_to_call.append( + lambda zeroconf: self._service_state_changed.fire( + zeroconf=zeroconf, + 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) + service_key = record.alias.lower() + try: + old_record = self.services[service_key] + except KeyError: + if not expired: + self.services[service_key] = record + enqueue_callback(ServiceStateChange.Added, record.alias) + else: + if not expired: + old_record.reset_ttl(record) + else: + del self.services[service_key] + enqueue_callback(ServiceStateChange.Removed, record.alias) + return + + expires = record.get_expiration_time(75) + if expires < self.next_time: + self.next_time = expires + + def cancel(self): + self.done = True + self.zc.remove_listener(self) + self.join() + + def run(self): + self.zc.add_listener(self, DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) + + while True: + now = current_time_millis() + if len(self._handlers_to_call) == 0 and self.next_time > now: + self.zc.wait(self.next_time - now) + if self.zc.done or self.done: + return + now = current_time_millis() + if self.next_time <= now: + out = DNSOutgoing(_FLAGS_QR_QUERY) + out.add_question(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) + for record in self.services.values(): + if not record.is_expired(now): + out.add_answer_at_time(record, now) + + self.zc.send(out) + self.next_time = now + self.delay + self.delay = min(20 * 1000, self.delay * 2) + + if len(self._handlers_to_call) > 0 and not self.zc.done: + handler = self._handlers_to_call.pop(0) + handler(self.zc) + + +class ServiceInfo(object): + + """Service information""" + + def __init__(self, type_, name, address=None, port=None, weight=0, + priority=0, properties=None, server=None): + """Create a service description. + + type_: fully qualified service type name + name: fully qualified service name + address: IP address as unsigned short, network byte order + port: port that the service runs on + weight: weight of the service + 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)""" + + if not type_.endswith(service_type_name(name)): + raise BadTypeInNameException + self.type = type_ + self.name = name + self.address = address + self.port = port + self.weight = weight + self.priority = priority + if server: + self.server = server + else: + self.server = name + self._properties = {} + self._set_properties(properties) + + @property + def properties(self): + return self._properties + + def _set_properties(self, properties): + """Sets properties and text of this info from a dictionary""" + if isinstance(properties, dict): + self._properties = properties + list_ = [] + result = b'' + for key, value in iteritems(properties): + if isinstance(key, text_type): + key = key.encode('utf-8') + + if value is None: + suffix = b'' + elif isinstance(value, text_type): + suffix = value.encode('utf-8') + elif isinstance(value, binary_type): + suffix = value + elif isinstance(value, int): + if value: + suffix = b'true' + else: + suffix = b'false' + else: + suffix = b'' + list_.append(b'='.join((key, suffix))) + for item in list_: + result = b''.join((result, int2byte(len(item)), item)) + self.text = result + else: + self.text = properties + + def _set_text(self, text): + """Sets properties and text given a text field""" + self.text = text + result = {} + end = len(text) + index = 0 + strs = [] + while index < end: + length = indexbytes(text, index) + index += 1 + strs.append(text[index:index + length]) + index += length + + for s in strs: + parts = s.split(b'=', 1) + try: + key, value = parts + except ValueError: + # No equals sign at all + key = s + value = False + else: + if value == b'true': + value = True + elif value == b'false' or not value: + value = False + + # Only update non-existent properties + if key and result.get(key) is None: + result[key] = value + + self._properties = result + + 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 + + def update_record(self, zc, now, record): + """Updates service information from a DNS record""" + if record is not None and not record.is_expired(now): + if record.type == _TYPE_A: + # if record.name == self.name: + if record.name == self.server: + self.address = record.address + elif record.type == _TYPE_SRV: + if record.name == self.name: + self.server = record.server + self.port = record.port + self.weight = record.weight + self.priority = record.priority + # self.address = None + self.update_record( + 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) + + def request(self, zc, timeout): + """Returns true if the service could be discovered on the + network, and updates this object with details discovered. + """ + now = current_time_millis() + delay = _LISTENER_TIME + next_ = now + delay + last = now + timeout + + record_types_for_check_cache = [ + (_TYPE_SRV, _CLASS_IN), + (_TYPE_TXT, _CLASS_IN), + ] + if self.server is not None: + record_types_for_check_cache.append((_TYPE_A, _CLASS_IN)) + for record_type in record_types_for_check_cache: + cached = zc.cache.get_by_details(self.name, *record_type) + if cached: + self.update_record(zc, now, cached) + + if None not in (self.server, self.address, self.text): + return True + + try: + zc.add_listener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN)) + while None in (self.server, self.address, self.text): + if last <= now: + return False + if next_ <= now: + out = DNSOutgoing(_FLAGS_QR_QUERY) + 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) + + 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) + + if self.server is not None: + 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.send(out) + next_ = now + delay + delay *= 2 + + zc.wait(min(next_, last) - now) + now = current_time_millis() + finally: + zc.remove_listener(self) + + return True + + def __eq__(self, other): + """Tests equality of service name""" + return isinstance(other, ServiceInfo) and other.name == self.name + + def __ne__(self, other): + """Non-equality test""" + return not self.__eq__(other) + + def __repr__(self): + """String representation""" + return '%s(%s)' % ( + type(self).__name__, + ', '.join( + '%s=%r' % (name, getattr(self, name)) + for name in ( + 'type', 'name', 'address', 'port', 'weight', 'priority', + 'server', 'properties', + ) + ) + ) + + +class ZeroconfServiceTypes(object): + """ + Return all of the advertised services on any local networks + """ + def __init__(self): + self.found_services = set() + + def add_service(self, zc, type_, name): + self.found_services.add(name) + + def remove_service(self, zc, type_, name): + pass + + @classmethod + def find(cls, zc=None, timeout=5, interfaces=InterfaceChoice.All): + """ + Return all of the advertised services on any local networks. + + :param zc: Zeroconf() instance. Pass in if already have an + instance running or if non-default interfaces are needed + :param timeout: seconds to wait for any responses + :return: tuple of service type strings + """ + local_zc = zc or Zeroconf(interfaces=interfaces) + listener = cls() + browser = ServiceBrowser( + local_zc, '_services._dns-sd._udp.local.', listener=listener) + + # wait for responses + time.sleep(timeout) + + # close down anything we opened + if zc is None: + local_zc.close() + else: + browser.cancel() + + return tuple(sorted(listener.found_services)) + + +def get_all_addresses(address_family): + return list(set( + 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'] + elif choice is InterfaceChoice.All: + choice = get_all_addresses(address_family) + return choice + + +def new_socket(): + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + # SO_REUSEADDR should be equivalent to SO_REUSEPORT for + # multicast UDP sockets (p 731, "TCP/IP Illustrated, + # Volume 2"), but some BSD-derived systems require + # SO_REUSEPORT to be specified explicity. Also, not all + # versions of Python have SO_REUSEPORT available. + # Catch OSError and socket.error for kernel versions <3.9 because lacking + # SO_REUSEPORT support. + try: + reuseport = socket.SO_REUSEPORT + except AttributeError: + pass + else: + try: + s.setsockopt(socket.SOL_SOCKET, reuseport, 1) + except (OSError, socket.error) as err: + # OSError on python 3, socket.error on python 2 + if not err.errno == errno.ENOPROTOOPT: + raise + + # 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) + s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) + loop = struct.pack(b'B', 1) + s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop) + + s.bind(('', _MDNS_PORT)) + return s + + +def get_errno(e): + assert isinstance(e, socket.error) + return e.args[0] + + +class Zeroconf(QuietLogger): + + """Implementation of Zeroconf Multicast DNS Service Discovery + + Supports registration, unregistration, queries and browsing. + """ + + def __init__( + self, + interfaces=InterfaceChoice.All, + ): + """Creates an instance of the Zeroconf class, establishing + multicast communications, listening and reaping threads. + + :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses + """ + # hook for threads + self._GLOBAL_DONE = False + + self._listen_socket = new_socket() + interfaces = normalize_interface_choice(interfaces, socket.AF_INET) + + self._respond_sockets = [] + + for i in interfaces: + 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)) + 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, + ) + 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, + ) + continue + else: + raise + + respond_socket = new_socket() + respond_socket.setsockopt( + socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i)) + + self._respond_sockets.append(respond_socket) + + self.listeners = [] + self.browsers = {} + self.services = {} + self.servicetypes = {} + + self.cache = DNSCache() + + self.condition = threading.Condition() + + self.engine = Engine(self) + self.listener = Listener(self) + self.engine.add_reader(self.listener, self._listen_socket) + self.reaper = Reaper(self) + + self.debug = None + + @property + def done(self): + return self._GLOBAL_DONE + + def wait(self, timeout): + """Calling thread waits for a given number of milliseconds or + until notified.""" + with self.condition: + self.condition.wait(timeout / 1000.0) + + def notify_all(self): + """Notifies all waiting threads""" + with self.condition: + self.condition.notify_all() + + def get_service_info(self, type_, name, timeout=3000): + """Returns network's service information for a particular + name and type, or None if no service matches by the timeout, + which defaults to 3 seconds.""" + info = ServiceInfo(type_, name) + if info.request(self, timeout): + return info + + def add_service_listener(self, type_, listener): + """Adds a listener for a particular service type. This object + will then have its update_record method called when information + arrives for that type.""" + self.remove_service_listener(listener) + self.browsers[listener] = ServiceBrowser(self, type_, listener) + + def remove_service_listener(self, listener): + """Removes a listener from the set that is currently listening.""" + if listener in self.browsers: + self.browsers[listener].cancel() + del self.browsers[listener] + + def remove_all_service_listeners(self): + """Removes a listener from the set that is currently listening.""" + 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): + """Registers service information to the network with a default TTL + of 60 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) + self.services[info.name.lower()] = info + if info.type in self.servicetypes: + self.servicetypes[info.type] += 1 + else: + self.servicetypes[info.type] = 1 + now = current_time_millis() + next_time = now + i = 0 + while i < 3: + if now < next_time: + self.wait(next_time - now) + now = current_time_millis() + continue + out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) + out.add_answer_at_time( + 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) + + out.add_answer_at_time( + DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0) + if info.address: + out.add_answer_at_time( + DNSAddress(info.server, _TYPE_A, _CLASS_IN, + ttl, info.address), 0) + self.send(out) + i += 1 + next_time += _REGISTER_TIME + + def unregister_service(self, info): + """Unregister a service.""" + try: + del self.services[info.name.lower()] + if self.servicetypes[info.type] > 1: + self.servicetypes[info.type] -= 1 + else: + del self.servicetypes[info.type] + except Exception as e: # TODO stop catching all Exceptions + log.exception('Unknown error, possibly benign: %r', e) + now = current_time_millis() + next_time = now + i = 0 + while i < 3: + if now < next_time: + self.wait(next_time - now) + now = current_time_millis() + continue + out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) + 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.name), 0) + out.add_answer_at_time( + DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0) + + if info.address: + out.add_answer_at_time( + DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, + info.address), 0) + self.send(out) + i += 1 + next_time += _UNREGISTER_TIME + + def unregister_all_services(self): + """Unregister all registered services.""" + if len(self.services) > 0: + now = current_time_millis() + next_time = now + i = 0 + while i < 3: + if now < next_time: + self.wait(next_time - now) + now = current_time_millis() + 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) + if info.address: + out.add_answer_at_time(DNSAddress( + info.server, _TYPE_A, _CLASS_IN, 0, + info.address), 0) + self.send(out) + i += 1 + next_time += _UNREGISTER_TIME + + def check_service(self, info, allow_name_change): + """Checks the network for a unique service name, modifying the + ServiceInfo passed in if it is not unique.""" + + # This is kind of funky because of the subtype based tests + # need to make subtypes a first class citizen + service_name = service_type_name(info.name) + if not info.type.endswith(service_name): + raise BadTypeInNameException + + instance_name = info.name[:-len(service_name) - 1] + next_instance_number = 2 + + now = current_time_millis() + next_time = now + i = 0 + while i < 3: + # check for a name conflict + 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) + next_instance_number += 1 + service_type_name(info.name) + next_time = now + i = 0 + + if now < next_time: + self.wait(next_time - now) + now = current_time_millis() + continue + + 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)) + self.send(out) + i += 1 + next_time += _CHECK_TIME + + def add_listener(self, listener, question): + """Adds a listener for a given question. The listener will have + its update_record method called when information is available to + answer the question.""" + now = current_time_millis() + self.listeners.append(listener) + if question is not None: + for record in self.cache.entries_with_name(question.name): + if question.answered_by(record) and not record.is_expired(now): + listener.update_record(self, now, record) + self.notify_all() + + def remove_listener(self, listener): + """Removes a listener.""" + try: + self.listeners.remove(listener) + self.notify_all() + except Exception as e: # TODO stop catching all Exceptions + log.exception('Unknown error, possibly benign: %r', e) + + def update_record(self, now, rec): + """Used to notify listeners of new information that has updated + a record.""" + for listener in self.listeners: + listener.update_record(self, now, rec) + self.notify_all() + + def handle_response(self, msg): + """Deal with incoming response packets. All answers + are held in the cache, and listeners are notified.""" + now = current_time_millis() + for record in msg.answers: + expired = record.is_expired(now) + if record in self.cache.entries(): + if expired: + self.cache.remove(record) + else: + entry = self.cache.get(record) + if entry is not None: + entry.reset_ttl(record) + else: + self.cache.add(record) + + for record in msg.answers: + self.update_record(now, record) + + def handle_query(self, msg, addr, port): + """Deal with incoming query packets. Provides a response if + possible.""" + out = None + + # Support unicast client responses + # + if port != _MDNS_PORT: + out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, multicast=False) + for question in msg.questions: + out.add_question(question) + + for question in msg.questions: + if question.type == _TYPE_PTR: + if question.name == "_services._dns-sd._udp.local.": + 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)) + 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)) + else: + try: + if out is None: + out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) + + # Answer A record queries for any service addresses we know + if question.type in (_TYPE_A, _TYPE_ANY): + for service in self.services.values(): + if service.server == question.name.lower(): + out.add_answer(msg, DNSAddress( + question.name, _TYPE_A, + _CLASS_IN | _CLASS_UNIQUE, + _DNS_TTL, service.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)) + 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)) + if question.type == _TYPE_SRV: + out.add_additional_answer(DNSAddress( + service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, + _DNS_TTL, service.address)) + except Exception: # TODO stop catching all Exceptions + self.log_exception_warning() + + if out is not None and out.answers: + out.id = msg.id + self.send(out, addr, port) + + def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): + """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) + return + 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 + # 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) + + def close(self): + """Ends the background threads, and prevent this instance from + servicing further queries.""" + if not self._GLOBAL_DONE: + self._GLOBAL_DONE = True + # remove service listeners + self.remove_all_service_listeners() + self.unregister_all_services() + + # shutdown recv socket and thread + self.engine.del_reader(self._listen_socket) + self._listen_socket.close() + self.engine.join() + + # shutdown the rest + self.notify_all() + self.reaper.join() + for s in self._respond_sockets: + s.close() From b0247597f9236b905eba6e0fa5f57f9560c4f302 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 13:25:35 +0200 Subject: [PATCH 08/14] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20improvements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Backported from jstasiak/python-zeroconf#205 by @nallath --- src/octoprint/vendor/zeroconf.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py index 31416afa2..8fabfb495 100644 --- a/src/octoprint/vendor/zeroconf.py +++ b/src/octoprint/vendor/zeroconf.py @@ -33,7 +33,7 @@ import struct import sys import threading import time -from functools import reduce +import itertools import netifaces from six import binary_type, indexbytes, int2byte, iteritems, text_type @@ -351,10 +351,10 @@ class DNSEntry(object): def __eq__(self, other): """Equality test on name, type, and class""" - return (isinstance(other, DNSEntry) and - self.name == other.name and + return (self.name == other.name and self.type == other.type and - self.class_ == other.class_) + self.class_ == other.class_ and + isinstance(other, DNSEntry)) def __ne__(self, other): """Non-equality test""" @@ -412,6 +412,8 @@ class DNSRecord(DNSEntry): DNSEntry.__init__(self, name, type_, class_) self.ttl = ttl self.created = current_time_millis() + self._expiration_time = self.get_expiration_time(100) + self._stale_time = self.get_expiration_time(50) def __eq__(self, other): """Abstract method""" @@ -437,15 +439,15 @@ class DNSRecord(DNSEntry): def get_remaining_ttl(self, now): """Returns the remaining TTL in seconds.""" - return max(0, (self.get_expiration_time(100) - now) / 1000.0) + return max(0, (self._expiration_time - now) / 1000.0) def is_expired(self, now): """Returns true if this record has expired.""" - return self.get_expiration_time(100) <= now + return self._expiration_time <= now def is_stale(self, now): """Returns true if this record is at least half way expired.""" - return self.get_expiration_time(50) <= now + return self._stale_time <= now def reset_ttl(self, other): """Sets this record's TTL and created time to that of @@ -532,7 +534,7 @@ class DNSPointer(DNSRecord): def __eq__(self, other): """Tests equality on alias""" - return isinstance(other, DNSPointer) and self.alias == other.alias + return isinstance(other, DNSPointer) and self.alias == other.alias and DNSEntry.__eq__(self, other) def __repr__(self): """String representation""" @@ -554,7 +556,7 @@ class DNSText(DNSRecord): def __eq__(self, other): """Tests equality on text""" - return isinstance(other, DNSText) and self.text == other.text + return isinstance(other, DNSText) and self.text == other.text and DNSEntry.__eq__(self, other) def __repr__(self): """String representation""" @@ -589,7 +591,8 @@ class DNSService(DNSRecord): self.priority == other.priority and self.weight == other.weight and self.port == other.port and - self.server == other.server) + self.server == other.server and + DNSEntry.__eq__(self, other)) def __repr__(self): """String representation""" @@ -1063,7 +1066,7 @@ class DNSCache(object): else: # avoid size change during iteration by copying the cache values = list(self.cache.values()) - return reduce(lambda a, b: a + b, values) + return list(itertools.chain.from_iterable(values)) class Engine(threading.Thread): @@ -1923,9 +1926,8 @@ class Zeroconf(QuietLogger): are held in the cache, and listeners are notified.""" now = current_time_millis() for record in msg.answers: - expired = record.is_expired(now) if record in self.cache.entries(): - if expired: + if record.is_expired(now): self.cache.remove(record) else: entry = self.cache.get(record) From 252b9b7e41316faf6f2d94d55d44ea0583f54beb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 13:34:31 +0200 Subject: [PATCH 09/14] =?UTF-8?q?=F0=9F=90=9B=20Fix=20two=20=5F=5Feq=5F=5F?= =?UTF-8?q?=20methods=20in=20vendored=20zeroconf=20lib?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/vendor/zeroconf.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py index 8fabfb495..0d7e388ea 100644 --- a/src/octoprint/vendor/zeroconf.py +++ b/src/octoprint/vendor/zeroconf.py @@ -480,7 +480,7 @@ class DNSAddress(DNSRecord): def __eq__(self, other): """Tests equality on address""" - return isinstance(other, DNSAddress) and self.address == other.address + return isinstance(other, DNSAddress) and self.address == other.address and DNSEntry.__eq__(self, other) def __repr__(self): """String representation""" @@ -513,7 +513,9 @@ class DNSHinfo(DNSRecord): def __eq__(self, other): """Tests equality on cpu and os""" return (isinstance(other, DNSHinfo) and - self.cpu == other.cpu and self.os == other.os) + self.cpu == other.cpu and + self.os == other.os and + DNSEntry.__eq__(self, other)) def __repr__(self): """String representation""" From ffde393c666af62d869c9bddb4608bb9c9043005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 15:05:40 +0200 Subject: [PATCH 10/14] =?UTF-8?q?=E2=99=BB=20Use=20vendored=20zeroconf=20o?= =?UTF-8?q?nly=20on=20Py2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adjusted vendored version to match (used) signatures of current py3 only versions. Use official builds under Py3 --- setup.py | 8 +++ src/octoprint/plugins/discovery/__init__.py | 57 +++++++++++------- src/octoprint/vendor/zeroconf.py | 66 ++++++++++++++------- 3 files changed, 89 insertions(+), 42 deletions(-) diff --git a/setup.py b/setup.py index 208fa2fca..f52aa8d7c 100644 --- a/setup.py +++ b/setup.py @@ -81,6 +81,11 @@ INSTALL_REQUIRES_PYTHON2 = [ "typing>=3.7.4.1,<4" ] +# Python 3 specific requirements +INSTALL_REQUIRES_PYTHON3 = [ + "zeroconf>=0.24,<0.25" +] + # OSX specific requirements INSTALL_REQUIRES_OSX = [ "appdirs>=1.4.4", @@ -130,12 +135,15 @@ if int(setuptools.__version__.split(".", 1)[0]) < 18: # add optional dependencies for setuptools versions < 18 that don't yet support environment markers if sys.version_info[0] < 3: INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2 + else: + INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3 if sys.platform == "darwin": INSTALL_REQUIRES += INSTALL_REQUIRES_OSX else: # environment markers supported EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2 + EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3 EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX #----------------------------------------------------------------------------------------------------------------------- diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index a22ff0d33..c787453f0 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -18,7 +18,14 @@ from builtins import range import octoprint.plugin import octoprint.util -import octoprint.vendor.zeroconf as zeroconf +try: + # python 3 + import zeroconf + +except ImportError: + # python 2: vendored version with some backported fixes + import octoprint.vendor.zeroconf as zeroconf + import time import collections import socket @@ -197,21 +204,19 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, txt_record = self._format_zeroconf_txt(txt_record) key = (reg_type, port) - addresses = octoprint.util.net.interface_addresses() + addresses = list(map(lambda x: socket.inet_aton(x), octoprint.util.net.interface_addresses())) try: - for address in addresses: - info = zeroconf.ServiceInfo(reg_type, - name, - address=socket.inet_aton(address), - port=port, - properties=txt_record) - self._zeroconf.register_service(info, allow_name_change=True) - self._zeroconf_registrations[key].append(info) - + info = zeroconf.ServiceInfo(reg_type, name, + addresses=addresses, + port=port, + server="{}.local.".format(socket.gethostname()), + properties=txt_record) + self._zeroconf.register_service(info, allow_name_change=True) + self._zeroconf_registrations[key].append(info) self._logger.info("Registered '{}' for {}".format(name, reg_type)) except Exception: - self._logger.exception("Could not (fully) register {} for {} on port {}".format(name, reg_type, port)) + self._logger.exception("Could not register {} for {} on port {}".format(name, reg_type, port)) def zeroconf_unregister(self, reg_type, port=None): """ @@ -292,16 +297,24 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._logger.debug("Got a browsing result for Zeroconf resolution of {}, resolving...".format(type)) info = zeroconf.get_service_info(type, name, timeout=resolve_timeout * 1000) if info: - address = socket.inet_ntoa(info.address) - self._logger.debug("Resolved a result for Zeroconf resolution of {}: {} @ {}".format(type, - name, - address)) - result.append(dict( - name=info.name[:-(len(type) + 1)], - host=address, - port=info.port, - txt_record=info.properties - )) + def to_result(info, address): + n = info.name[:-(len(type) + 1)] + p = info.port + + self._logger.debug("Resolved a result for Zeroconf resolution of {}: {} @ {}:{}".format(type, + n, + address, + p)) + + return dict(name=n, host=address, port=p, txt_record=info.properties) + + if hasattr(info, "addresses"): + # Python 3 + for address in map(lambda x: socket.inet_ntoa(x), info.addresses): + result.append(to_result(info, address)) + else: + # Python 2 + result.append(to_result(info, socket.inet_ntoa(info.address))) self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) diff --git a/src/octoprint/vendor/zeroconf.py b/src/octoprint/vendor/zeroconf.py index 0d7e388ea..4c912b44b 100644 --- a/src/octoprint/vendor/zeroconf.py +++ b/src/octoprint/vendor/zeroconf.py @@ -1343,13 +1343,14 @@ class ServiceInfo(object): """Service information""" - def __init__(self, type_, name, address=None, port=None, weight=0, + def __init__(self, type_, name, addresses=None, port=None, weight=0, priority=0, properties=None, server=None): """Create a service description. type_: fully qualified service type name name: fully qualified service name - address: IP address as unsigned short, network byte order + addresses: List of IP addresses as unsigned short (IPv4), + network byte order port: port that the service runs on weight: weight of the service priority: priority of the service @@ -1361,7 +1362,16 @@ class ServiceInfo(object): raise BadTypeInNameException self.type = type_ self.name = name - self.address = address + if addresses is not None: + self._addresses = addresses + 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] + if 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 @@ -1372,6 +1382,19 @@ class ServiceInfo(object): self._properties = {} self._set_properties(properties) + @property + def addresses(self): + """IPv4 addresses of this service.""" + return self._addresses + + @addresses.setter + def addresses(self, value): + """Replace the addresses list. + + This replaces all currently stored addresses. + """ + self._addresses = value + @property def properties(self): return self._properties @@ -1451,7 +1474,8 @@ class ServiceInfo(object): if record.type == _TYPE_A: # if record.name == self.name: if record.name == self.server: - self.address = record.address + if record.address not in self._addresses: + self._addresses.append(record.address) elif record.type == _TYPE_SRV: if record.name == self.name: self.server = record.server @@ -1486,12 +1510,12 @@ class ServiceInfo(object): if cached: self.update_record(zc, now, cached) - if None not in (self.server, self.address, self.text): + if self.server is not None and self.text is not None and self._addresses: return True try: zc.add_listener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN)) - while None in (self.server, self.address, self.text): + while self.server is None or self.text is None or not self._addresses: if last <= now: return False if next_ <= now: @@ -1540,7 +1564,7 @@ class ServiceInfo(object): ', '.join( '%s=%r' % (name, getattr(self, name)) for name in ( - 'type', 'name', 'address', 'port', 'weight', 'priority', + 'type', 'name', 'addresses', 'port', 'weight', 'priority', 'server', 'properties', ) ) @@ -1780,10 +1804,10 @@ class Zeroconf(QuietLogger): out.add_answer_at_time( DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0) - if info.address: + for address in info.addresses: out.add_answer_at_time( DNSAddress(info.server, _TYPE_A, _CLASS_IN, - ttl, info.address), 0) + ttl, address), 0) self.send(out) i += 1 next_time += _REGISTER_TIME @@ -1815,10 +1839,10 @@ class Zeroconf(QuietLogger): out.add_answer_at_time( DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0) - if info.address: + for address in info.addresses: out.add_answer_at_time( DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, - info.address), 0) + address), 0) self.send(out) i += 1 next_time += _UNREGISTER_TIME @@ -1843,10 +1867,10 @@ class Zeroconf(QuietLogger): 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) - if info.address: + for address in info.addresses: out.add_answer_at_time(DNSAddress( info.server, _TYPE_A, _CLASS_IN, 0, - info.address), 0) + address), 0) self.send(out) i += 1 next_time += _UNREGISTER_TIME @@ -1978,10 +2002,11 @@ class Zeroconf(QuietLogger): if question.type in (_TYPE_A, _TYPE_ANY): for service in self.services.values(): if service.server == question.name.lower(): - out.add_answer(msg, DNSAddress( - question.name, _TYPE_A, - _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, service.address)) + for address in service.addresses: + out.add_answer(msg, DNSAddress( + question.name, _TYPE_A, + _CLASS_IN | _CLASS_UNIQUE, + _DNS_TTL, address)) service = self.services.get(question.name.lower(), None) if not service: @@ -1997,9 +2022,10 @@ class Zeroconf(QuietLogger): question.name, _TYPE_TXT, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.text)) if question.type == _TYPE_SRV: - out.add_additional_answer(DNSAddress( - service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, - _DNS_TTL, service.address)) + for address in service.addresses: + out.add_additional_answer(DNSAddress( + service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, + _DNS_TTL, address)) except Exception: # TODO stop catching all Exceptions self.log_exception_warning() From 05cd9176938cac00f213701b5a7adb9f8e2f5285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 15:12:51 +0200 Subject: [PATCH 11/14] =?UTF-8?q?=E2=99=BB=20Remove=20no=20longer=20needed?= =?UTF-8?q?=20compatibility=20layer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugins/discovery/__init__.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index c787453f0..db9e03504 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -308,13 +308,8 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, return dict(name=n, host=address, port=p, txt_record=info.properties) - if hasattr(info, "addresses"): - # Python 3 - for address in map(lambda x: socket.inet_ntoa(x), info.addresses): - result.append(to_result(info, address)) - else: - # Python 2 - result.append(to_result(info, socket.inet_ntoa(info.address))) + for address in map(lambda x: socket.inet_ntoa(x), info.addresses): + result.append(to_result(info, address)) self._logger.debug("Browsing Zeroconf for {service_type}".format(service_type=service_type)) From 894178918b25e86aa3f37b66177c8e18776f7802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 31 Jul 2020 16:52:42 +0200 Subject: [PATCH 12/14] =?UTF-8?q?=F0=9F=90=9B=20Set=20sensible=20permissio?= =?UTF-8?q?ns=20on=20(uploaded)=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit chmod to 0o664 $ ~UMASK after moving to final destination. Should fix #3571 --- src/octoprint/__init__.py | 5 ++++- src/octoprint/filemanager/util.py | 18 +++++++++++++++--- src/octoprint/util/__init__.py | 5 ++++- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 18322aa29..0196952f7 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -5,6 +5,7 @@ from __future__ import absolute_import, division, print_function, unicode_litera import io import sys import logging as log +import os #~~ version @@ -19,7 +20,9 @@ __revision__ = versions.get('full-revisionid', versions.get('full', None)) del versions del get_versions -#~~ try to ensure a sound SSL environment +# figure out current umask - sadly only doable by setting a new one and resetting it, no query method +UMASK = os.umask(0) +os.umask(UMASK) urllib3_ssl = True """Whether requests/urllib3 and urllib3 (if installed) should be able to establish diff --git a/src/octoprint/filemanager/util.py b/src/octoprint/filemanager/util.py index 7074d508a..682d18e53 100644 --- a/src/octoprint/filemanager/util.py +++ b/src/octoprint/filemanager/util.py @@ -6,7 +6,9 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" import io +import os +from octoprint import UMASK from octoprint.util import atomic_write class AbstractFileWrapper(object): @@ -17,15 +19,18 @@ class AbstractFileWrapper(object): filename (str): The file's name """ + DEFAULT_PERMISSIONS = 0o664 + def __init__(self, filename): self.filename = filename - def save(self, path): + def save(self, path, permissions=None): """ Saves the file's content to the given absolute path. Arguments: path (str): The absolute path to where to save the file + permissions (int): The permissions to set on the file """ raise NotImplementedError() @@ -55,7 +60,7 @@ class DiskFileWrapper(AbstractFileWrapper): self.path = path self.move = move - def save(self, path): + def save(self, path, permissions=None): import shutil if self.move: @@ -63,6 +68,10 @@ class DiskFileWrapper(AbstractFileWrapper): else: shutil.copy2(self.path, path) + if permissions is None: + permissions = self.DEFAULT_PERMISSIONS & ~UMASK + os.chmod(path, permissions) + def stream(self): return io.open(self.path, 'rb') @@ -80,7 +89,7 @@ class StreamWrapper(AbstractFileWrapper): AbstractFileWrapper.__init__(self, filename) self.streams = streams - def save(self, path): + def save(self, path, permissions=None): """ Will dump the contents of all streams provided during construction into the target file, in the order they were provided. @@ -90,6 +99,9 @@ class StreamWrapper(AbstractFileWrapper): with atomic_write(path, mode='wb') as dest: for source in self.streams: shutil.copyfileobj(source, dest) + if permissions is None: + permissions = self.DEFAULT_PERMISSIONS & ~UMASK + os.chmod(path, permissions) def stream(self): """ diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 47029beed..a615ea0a3 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -37,6 +37,7 @@ except ImportError: from past.builtins import basestring, unicode +from octoprint import UMASK from octoprint.util.net import interface_addresses, address_for_client, server_reachable from octoprint.util.connectivity import ConnectivityChecker @@ -1060,7 +1061,9 @@ def mime_type_matches(mime, other): return type_matches and subtype_matches @contextlib.contextmanager -def atomic_write(filename, mode="w+b", encoding="utf-8", prefix="tmp", suffix="", permissions=0o644, max_permissions=0o777): +def atomic_write(filename, mode="w+b", encoding="utf-8", prefix="tmp", suffix="", permissions=None, max_permissions=0o777): + if permissions is None: + permissions = 0o664 & ~UMASK if os.path.exists(filename): permissions |= os.stat(filename).st_mode permissions &= max_permissions From e7e04271fdfa353fc85ebd3358b311483527fbf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 3 Aug 2020 09:59:56 +0200 Subject: [PATCH 13/14] =?UTF-8?q?=F0=9F=92=9A=20Fix=20tests=20broken=20by?= =?UTF-8?q?=20894178918?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/filemanager/test_filemanager.py | 3 ++- tests/util/test_file_helpers.py | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/filemanager/test_filemanager.py b/tests/filemanager/test_filemanager.py index 5bb985f3b..abf550ee6 100644 --- a/tests/filemanager/test_filemanager.py +++ b/tests/filemanager/test_filemanager.py @@ -398,7 +398,8 @@ class FileManagerTest(unittest.TestCase): @mock.patch("shutil.copyfileobj") @mock.patch("os.remove") @mock.patch("tempfile.NamedTemporaryFile") - def test_slice(self, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write): + @mock.patch("os.chmod") + def test_slice(self, mocked_chmod, mocked_tempfile, mocked_os, mocked_shutil, mocked_fileio, mocked_atomic_write): callback = mock.MagicMock() callback_args = ("one", "two", "three") diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py index 80c009434..196db58fb 100644 --- a/tests/util/test_file_helpers.py +++ b/tests/util/test_file_helpers.py @@ -126,7 +126,7 @@ class TestAtomicWrite(unittest.TestCase): mock_open.assert_called_once_with(path, mode="w+b") mock_file.write.assert_called_once_with("test") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with(path, 0o644) + mock_chmod.assert_called_once_with(path, 0o664) mock_move.assert_called_once_with(path, "somefile.yaml") @mock.patch("shutil.move") @@ -231,7 +231,7 @@ class TestAtomicWrite(unittest.TestCase): mock_close.assert_called_once_with(fd) mock_open.assert_called_once_with(path, mode="w", encoding="utf-8") mock_file.close.assert_called_once_with() - mock_chmod.assert_called_once_with(path, 0o644) + mock_chmod.assert_called_once_with(path, 0o664) mock_move.assert_called_once_with(path, "somefile.yaml") From a846fd8f83daead754eb4bfbfa483c01b63e90f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Mon, 3 Aug 2020 10:31:25 +0200 Subject: [PATCH 14/14] =?UTF-8?q?=E2=9C=85=20Add=20E2E=20for=20basic=20set?= =?UTF-8?q?tings=20dialog=20behaviour?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../templates/dialogs/settings.jinja2 | 8 +-- .../templates/navbar/settings.jinja2 | 2 +- tests/cypress/integration/settings.js | 57 +++++++++++++++++++ 3 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 tests/cypress/integration/settings.js diff --git a/src/octoprint/templates/dialogs/settings.jinja2 b/src/octoprint/templates/dialogs/settings.jinja2 index 1063b6809..87f37f0aa 100644 --- a/src/octoprint/templates/dialogs/settings.jinja2 +++ b/src/octoprint/templates/dialogs/settings.jinja2 @@ -1,6 +1,6 @@ -