pax_global_header 0000666 0000000 0000000 00000000064 13602475314 0014517 g ustar 00root root 0000000 0000000 52 comment=29432bfffd057cf4da7636ba0c28c9d8a7ad4357
python-zeroconf-0.24.4/ 0000775 0000000 0000000 00000000000 13602475314 0014752 5 ustar 00root root 0000000 0000000 python-zeroconf-0.24.4/.gitignore 0000664 0000000 0000000 00000000167 13602475314 0016746 0 ustar 00root root 0000000 0000000 build/
*.pyc
*.pyo
Thumbs.db
.DS_Store
.project
.pydevproject
.settings
.idea
.vslick
.cache
.mypy_cache/
docs/_build/
python-zeroconf-0.24.4/.travis.yml 0000664 0000000 0000000 00000001005 13602475314 0017057 0 ustar 00root root 0000000 0000000 language: python
python:
- "3.5"
- "3.6"
- "3.7"
- "3.8"
- "pypy3.5"
- "pypy3"
install:
- pip install -r requirements-dev.txt
# mypy can't be installed on pypy
- if [[ "${TRAVIS_PYTHON_VERSION}" != "pypy"* ]] ; then pip install mypy ; fi
- if [[ "${TRAVIS_PYTHON_VERSION}" != *"3.5"* && "${TRAVIS_PYTHON_VERSION}" != "pypy"* ]] ; then
pip install black ; fi
script:
# no IPv6 support in Travis :(
- make TEST_ARGS='-a "!IPv6"' ci
after_success:
- coveralls
python-zeroconf-0.24.4/COPYING 0000664 0000000 0000000 00000057506 13602475314 0016022 0 ustar 00root root 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
python-zeroconf-0.24.4/MANIFEST.in 0000664 0000000 0000000 00000000043 13602475314 0016505 0 ustar 00root root 0000000 0000000 include README.rst
include COPYING
python-zeroconf-0.24.4/Makefile 0000664 0000000 0000000 00000002307 13602475314 0016414 0 ustar 00root root 0000000 0000000 .PHONY: all virtualenv
MAX_LINE_LENGTH=110
PYTHON_IMPLEMENTATION:=$(shell python -c "import sys;import platform;sys.stdout.write(platform.python_implementation())")
PYTHON_VERSION:=$(shell python -c "import sys;sys.stdout.write('%d.%d' % sys.version_info[:2])")
TEST_ARGS=
LINT_TARGETS:=flake8
ifneq ($(findstring PyPy,$(PYTHON_IMPLEMENTATION)),PyPy)
LINT_TARGETS:=$(LINT_TARGETS) mypy
endif
ifeq ($(or $(findstring 3.5,$(PYTHON_VERSION)),$(findstring PyPy,$(PYTHON_IMPLEMENTATION))),)
LINT_TARGETS:=$(LINT_TARGETS) black_check
endif
virtualenv: ./env/requirements.built
env:
virtualenv env
./env/requirements.built: env requirements-dev.txt
./env/bin/pip install -r requirements-dev.txt
cp requirements-dev.txt ./env/requirements.built
.PHONY: ci
ci: test_coverage lint
.PHONY: lint
lint: $(LINT_TARGETS)
flake8:
flake8 --max-line-length=$(MAX_LINE_LENGTH) setup.py examples zeroconf
.PHONY: black_check
black_check:
black --check setup.py examples zeroconf
mypy:
mypy examples/*.py zeroconf/*.py
test:
nosetests -v $(TEST_ARGS)
test_coverage:
nosetests -v --with-coverage --cover-package=zeroconf $(TEST_ARGS)
autopep8:
autopep8 --max-line-length=$(MAX_LINE_LENGTH) -i setup.py examples zeroconf
python-zeroconf-0.24.4/README.rst 0000664 0000000 0000000 00000030645 13602475314 0016451 0 ustar 00root root 0000000 0000000 python-zeroconf
===============
.. image:: https://travis-ci.org/jstasiak/python-zeroconf.svg?branch=master
:target: https://travis-ci.org/jstasiak/python-zeroconf
.. image:: https://img.shields.io/pypi/v/zeroconf.svg
:target: https://pypi.python.org/pypi/zeroconf
.. image:: https://img.shields.io/coveralls/jstasiak/python-zeroconf.svg
:target: https://coveralls.io/r/jstasiak/python-zeroconf
`Documentation `_.
This is fork of pyzeroconf, Multicast DNS Service Discovery for Python,
originally by Paul Scott-Murphy (https://github.com/paulsm/pyzeroconf),
modified by William McBrine (https://github.com/wmcbrine/pyzeroconf).
The original William McBrine's fork note::
This fork is used in all of my TiVo-related projects: HME for Python
(and therefore HME/VLC), Network Remote, Remote Proxy, and pyTivo.
Before this, I was tracking the changes for zeroconf.py in three
separate repos. I figured I should have an authoritative source.
Although I make changes based on my experience with TiVos, I expect that
they're generally applicable. This version also includes patches found
on the now-defunct (?) Launchpad repo of pyzeroconf, and elsewhere
around the net -- not always well-documented, sorry.
Compatible with:
* Bonjour
* Avahi
Compared to some other Zeroconf/Bonjour/Avahi Python packages, python-zeroconf:
* isn't tied to Bonjour or Avahi
* doesn't use D-Bus
* doesn't force you to use particular event loop or Twisted
* is pip-installable
* has PyPI distribution
Python compatibility
--------------------
* CPython 3.5+
* PyPy3 5.8+
Versioning
----------
This project's versions follow the following pattern: MAJOR.MINOR.PATCH.
* MAJOR version has been 0 so far
* MINOR version is incremented on backward incompatible changes
* PATCH version is incremented on backward compatible changes
Status
------
There are some people using this package. I don't actively use it and as such
any help I can offer with regard to any issues is very limited.
IPv6 support
------------
IPv6 support is relatively new and currently limited, specifically:
* `InterfaceChoice.All` is an alias for `InterfaceChoice.Default` on non-POSIX
systems.
* On Windows specific interfaces can only be requested as interface indexes,
not as IP addresses.
* Dual-stack IPv6 sockets are used, which may not be supported everywhere (some
BSD variants do not have them).
* Listening on localhost (`::1`) does not work. Help with understanding why is
appreciated.
How to get python-zeroconf?
===========================
* PyPI page https://pypi.python.org/pypi/zeroconf
* GitHub project https://github.com/jstasiak/python-zeroconf
The easiest way to install python-zeroconf is using pip::
pip install zeroconf
How do I use it?
================
Here's an example of browsing for a service:
.. code-block:: python
from zeroconf import ServiceBrowser, Zeroconf
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service %s removed" % (name,))
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
print("Service %s added, service info: %s" % (name, info))
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
.. note::
Discovery and service registration use *all* available network interfaces by default.
If you want to customize that you need to specify ``interfaces`` argument when
constructing ``Zeroconf`` object (see the code for details).
If you don't know the name of the service you need to browse for, try:
.. code-block:: python
from zeroconf import ZeroconfServiceTypes
print('\n'.join(ZeroconfServiceTypes.find()))
See examples directory for more.
Changelog
=========
0.24.4
------
* Fixed resetting TTL in DNSRecord.reset_ttl(), thanks to Matt Saxon
* Improved various DNS class' string representations, thanks to Jay Hogg
0.24.3
------
* Fixed import-time "TypeError: 'ellipsis' object is not iterable." on CPython 3.5.2
0.24.2
------
* Added support for AWDL interface on macOS (needed and used by the opendrop project but should be
useful in general), thanks to Milan Stute
* Added missing type hints
0.24.1
------
* Applied some significant performance optimizations, thanks to Jaime van Kessel for the patch and
to Ghostkeeper for performance measurements
* Fixed flushing outdated cache entries when incoming record is unique, thanks to Michael Hu
* Fixed handling updates of TXT records (they'd not get recorded previously), thanks to Michael Hu
0.24.0
------
* Added IPv6 support, thanks to Dmitry Tantsur
* Added additional recommended records to PTR responses, thanks to Scott Mertz
* Added handling of ENOTCONN being raised during shutdown when using Eventlet, thanks to Tamás Nepusz
* Included the py.typed marker in the package so that type checkers know to use type hints from the
source code, thanks to Dmitry Tantsur
0.23.0
------
* Added support for MyListener call getting updates to service TXT records, thanks to Matt Saxon
* Added support for multiple addresses when publishing a service, getting/setting single address
has become deprecated. Change thanks to Dmitry Tantsur
Backwards incompatible:
* Dropped Python 3.4 support
0.22.0
------
* A lot of maintenance work (tooling, typing coverage and improvements, spelling) done, thanks to Ville Skyttä
* Provided saner defaults in ServiceInfo's constructor, thanks to Jorge Miranda
* Fixed service removal packets not being sent on shutdown, thanks to Andrew Bonney
* Added a way to define TTL-s through ServiceInfo contructor parameters, thanks to Andrew Bonney
Technically backwards incompatible:
* Adjusted query intervals to match RFC 6762, thanks to Andrew Bonney
* Made default TTL-s match RFC 6762, thanks to Andrew Bonney
0.21.3
------
* This time really allowed incoming service names to contain underscores (patch released
as part of 0.21.0 was defective)
0.21.2
------
* Fixed import-time typing-related TypeError when older typing version is used
0.21.1
------
* Fixed installation on Python 3.4 (we use typing now but there was no explicit dependency on it)
0.21.0
------
* Added an error message when importing the package using unsupported Python version
* Fixed TTL handling for published service
* Implemented unicast support
* Fixed WSL (Windows Subsystem for Linux) compatibility
* Fixed occasional UnboundLocalError issue
* Fixed UTF-8 multibyte name compression
* Switched from netifaces to ifaddr (pure Python)
* Allowed incoming service names to contain underscores
0.20.0
------
* Dropped support for Python 2 (this includes PyPy) and 3.3
* Fixed some class' equality operators
* ServiceBrowser entries are being refreshed when 'stale' now
* Cache returns new records first now instead of last
0.19.1
------
* Allowed installation with netifaces >= 0.10.6 (a bug that was concerning us
got fixed)
0.19.0
------
* Technically backwards incompatible - restricted netifaces dependency version to
work around a bug, see https://github.com/jstasiak/python-zeroconf/issues/84 for
details
0.18.0
------
* Dropped Python 2.6 support
* Improved error handling inside code executed when Zeroconf object is being closed
0.17.7
------
* Better Handling of DNS Incoming Packets parsing exceptions
* Many exceptions will now log a warning the first time they are seen
* Catch and log sendto() errors
* Fix/Implement duplicate name change
* Fix overly strict name validation introduced in 0.17.6
* Greatly improve handling of oversized packets including:
- Implement name compression per RFC1035
- Limit size of generated packets to 9000 bytes as per RFC6762
- Better handle over sized incoming packets
* Increased test coverage to 95%
0.17.6
------
* Many improvements to address race conditions and exceptions during ZC()
startup and shutdown, thanks to: morpav, veawor, justingiorgi, herczy,
stephenrauch
* Added more test coverage: strahlex, stephenrauch
* Stephen Rauch contributed:
- Speed up browser startup
- Add ZeroconfServiceTypes() query class to discover all advertised service types
- Add full validation for service names, types and subtypes
- Fix for subtype browsing
- Fix DNSHInfo support
0.17.5
------
* Fixed OpenBSD compatibility, thanks to Alessio Sergi
* Fixed race condition on ServiceBrowser startup, thanks to gbiddison
* Fixed installation on some Python 3 systems, thanks to Per Sandström
* Fixed "size change during iteration" bug on Python 3, thanks to gbiddison
0.17.4
------
* Fixed support for Linux kernel versions < 3.9 (thanks to Giovanni Harting
and Luckydonald, GitHub pull request #26)
0.17.3
------
* Fixed DNSText repr on Python 3 (it'd crash when the text was longer than
10 bytes), thanks to Paulus Schoutsen for the patch, GitHub pull request #24
0.17.2
------
* Fixed installation on Python 3.4.3+ (was failing because of enum34 dependency
which fails to install on 3.4.3+, changed to depend on enum-compat instead;
thanks to Michael Brennan for the original patch, GitHub pull request #22)
0.17.1
------
* Fixed EADDRNOTAVAIL when attempting to use dummy network interfaces on Windows,
thanks to daid
0.17.0
------
* Added some Python dependencies so it's not zero-dependencies anymore
* Improved exception handling (it'll be quieter now)
* Messages are listened to and sent using all available network interfaces
by default (configurable); thanks to Marcus Müller
* Started using logging more freely
* Fixed a bug with binary strings as property values being converted to False
(https://github.com/jstasiak/python-zeroconf/pull/10); thanks to Dr. Seuss
* Added new ``ServiceBrowser`` event handler interface (see the examples)
* PyPy3 now officially supported
* Fixed ServiceInfo repr on Python 3, thanks to Yordan Miladinov
0.16.0
------
* Set up Python logging and started using it
* Cleaned up code style (includes migrating from camel case to snake case)
0.15.1
------
* Fixed handling closed socket (GitHub #4)
0.15
----
* Forked by Jakub Stasiak
* Made Python 3 compatible
* Added setup script, made installable by pip and uploaded to PyPI
* Set up Travis build
* Reformatted the code and moved files around
* Stopped catching BaseException in several places, that could hide errors
* Marked threads as daemonic, they won't keep application alive now
0.14
----
* Fix for SOL_IP undefined on some systems - thanks Mike Erdely.
* Cleaned up examples.
* Lowercased module name.
0.13
----
* Various minor changes; see git for details.
* No longer compatible with Python 2.2. Only tested with 2.5-2.7.
* Fork by William McBrine.
0.12
----
* allow selection of binding interface
* typo fix - Thanks A. M. Kuchlingi
* removed all use of word 'Rendezvous' - this is an API change
0.11
----
* correction to comments for addListener method
* support for new record types seen from OS X
- IPv6 address
- hostinfo
* ignore unknown DNS record types
* fixes to name decoding
* works alongside other processes using port 5353 (e.g. on Mac OS X)
* tested against Mac OS X 10.3.2's mDNSResponder
* corrections to removal of list entries for service browser
0.10
----
* Jonathon Paisley contributed these corrections:
- always multicast replies, even when query is unicast
- correct a pointer encoding problem
- can now write records in any order
- traceback shown on failure
- better TXT record parsing
- server is now separate from name
- can cancel a service browser
* modified some unit tests to accommodate these changes
0.09
----
* remove all records on service unregistration
* fix DOS security problem with readName
0.08
----
* changed licensing to LGPL
0.07
----
* faster shutdown on engine
* pointer encoding of outgoing names
* ServiceBrowser now works
* new unit tests
0.06
----
* small improvements with unit tests
* added defined exception types
* new style objects
* fixed hostname/interface problem
* fixed socket timeout problem
* fixed add_service_listener() typo bug
* using select() for socket reads
* tested on Debian unstable with Python 2.2.2
0.05
----
* ensure case insensitivty on domain names
* support for unicast DNS queries
0.04
----
* added some unit tests
* added __ne__ adjuncts where required
* ensure names end in '.local.'
* timeout on receiving socket for clean shutdown
License
=======
LGPL, see COPYING file for details.
python-zeroconf-0.24.4/docs/ 0000775 0000000 0000000 00000000000 13602475314 0015702 5 ustar 00root root 0000000 0000000 python-zeroconf-0.24.4/docs/Makefile 0000664 0000000 0000000 00000015162 13602475314 0017347 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/zeroconf.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/zeroconf.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/zeroconf"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/zeroconf"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
python-zeroconf-0.24.4/docs/api.rst 0000664 0000000 0000000 00000000217 13602475314 0017205 0 ustar 00root root 0000000 0000000 python-zeroconf API reference
=============================
.. automodule:: zeroconf
:members:
:undoc-members:
:show-inheritance:
python-zeroconf-0.24.4/docs/conf.py 0000664 0000000 0000000 00000020136 13602475314 0017203 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import zeroconf
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'python-zeroconf'
copyright = 'python-zeroconf authors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = zeroconf.__version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
'index': ('sidebar.html', 'sourcelink.html', 'searchbox.html'),
'**': ('localtoc.html', 'relations.html', 'sourcelink.html', 'searchbox.html'),
}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_domain_indices = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'zeroconfdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
# latex_documents = []
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# If true, show page references after internal links.
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
# man_pages = []
# If true, show URL addresses after external links.
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
# texinfo_documents = []
# Documents to append as an appendix to all manuals.
# texinfo_appendices = []
# If false, no module index is generated.
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'http://docs.python.org/': None}
def setup(app):
app.connect('autodoc-skip-member', skip_member)
def skip_member(app, what, name, obj, skip, options):
return (
skip
or getattr(obj, '__doc__', None) is None
or getattr(obj, '__private__', False) is True
or getattr(getattr(obj, '__func__', None), '__private__', False) is True
)
python-zeroconf-0.24.4/docs/index.rst 0000664 0000000 0000000 00000002010 13602475314 0017534 0 ustar 00root root 0000000 0000000 Welcome to python-zeroconf documentation!
=========================================
.. image:: https://travis-ci.org/jstasiak/python-zeroconf.svg?branch=master
:alt: Build status
:target: https://travis-ci.org/jstasiak/python-zeroconf
.. image:: https://img.shields.io/pypi/v/zeroconf.svg
:target: https://pypi.python.org/pypi/zeroconf
.. image:: https://coveralls.io/repos/github/jstasiak/python-zeroconf/badge.svg?branch=master
:alt: Covergage status
:target: https://coveralls.io/github/jstasiak/python-zeroconf?branch=master
GitHub (code repository, issues): https://github.com/jstasiak/python-zeroconf
PyPI (installable, stable distributions): https://pypi.org/project/zeroconf. You can install python-zeroconf using pip::
pip install zeroconf
python-zeroconf works with CPython 3.5+ and PyPy 3 implementing Python 3.5+.
Contents
--------
.. toctree::
:maxdepth: 1
api
See `the project's README `_ for more information.
python-zeroconf-0.24.4/examples/ 0000775 0000000 0000000 00000000000 13602475314 0016570 5 ustar 00root root 0000000 0000000 python-zeroconf-0.24.4/examples/browser.py 0000775 0000000 0000000 00000004206 13602475314 0020632 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
""" Example of browsing for a service (in this case, HTTP) """
import argparse
import logging
import socket
from time import sleep
from typing import cast
from zeroconf import IPVersion, ServiceBrowser, ServiceStateChange, Zeroconf
def on_service_state_change(
zeroconf: Zeroconf, service_type: str, name: str, state_change: ServiceStateChange
) -> None:
print("Service %s of type %s state changed: %s" % (name, service_type, state_change))
if state_change is ServiceStateChange.Added:
info = zeroconf.get_service_info(service_type, name)
if info:
addresses = ["%s:%d" % (socket.inet_ntoa(addr), cast(int, info.port)) for addr in info.addresses]
print(" Addresses: %s" % ", ".join(addresses))
print(" Weight: %d, priority: %d" % (info.weight, info.priority))
print(" Server: %s" % (info.server,))
if info.properties:
print(" Properties are:")
for key, value in info.properties.items():
print(" %s: %s" % (key, value))
else:
print(" No properties")
else:
print(" No info")
print('\n')
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true')
version_group = parser.add_mutually_exclusive_group()
version_group.add_argument('--v6', action='store_true')
version_group.add_argument('--v6-only', action='store_true')
args = parser.parse_args()
if args.debug:
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
if args.v6:
ip_version = IPVersion.All
elif args.v6_only:
ip_version = IPVersion.V6Only
else:
ip_version = IPVersion.V4Only
zeroconf = Zeroconf(ip_version=ip_version)
print("\nBrowsing services, press Ctrl-C to exit...\n")
browser = ServiceBrowser(zeroconf, "_http._tcp.local.", handlers=[on_service_state_change])
try:
while True:
sleep(0.1)
except KeyboardInterrupt:
pass
finally:
zeroconf.close()
python-zeroconf-0.24.4/examples/registration.py 0000775 0000000 0000000 00000002701 13602475314 0021657 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
""" Example of announcing a service (in this case, a fake HTTP server) """
import argparse
import logging
import socket
from time import sleep
from zeroconf import IPVersion, ServiceInfo, Zeroconf
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--debug', action='store_true')
version_group = parser.add_mutually_exclusive_group()
version_group.add_argument('--v6', action='store_true')
version_group.add_argument('--v6-only', action='store_true')
args = parser.parse_args()
if args.debug:
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
if args.v6:
ip_version = IPVersion.All
elif args.v6_only:
ip_version = IPVersion.V6Only
else:
ip_version = IPVersion.V4Only
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
"_http._tcp.local.",
"Paul's Test Web Site._http._tcp.local.",
addresses=[socket.inet_aton("127.0.0.1")],
port=80,
properties=desc,
server="ash-2.local.",
)
zeroconf = Zeroconf(ip_version=ip_version)
print("Registration of a service, press Ctrl-C to exit...")
zeroconf.register_service(info)
try:
while True:
sleep(0.1)
except KeyboardInterrupt:
pass
finally:
print("Unregistering...")
zeroconf.unregister_service(info)
zeroconf.close()
python-zeroconf-0.24.4/examples/resolver.py 0000775 0000000 0000000 00000001031 13602475314 0021001 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
""" Example of resolving a service with a known name """
import logging
import sys
from zeroconf import Zeroconf
TYPE = '_test._tcp.local.'
NAME = 'My Service Name'
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
if len(sys.argv) > 1:
assert sys.argv[1:] == ['--debug']
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
zeroconf = Zeroconf()
try:
print(zeroconf.get_service_info(TYPE, NAME + '.' + TYPE))
finally:
zeroconf.close()
python-zeroconf-0.24.4/examples/self_test.py 0000775 0000000 0000000 00000003403 13602475314 0021135 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
import logging
import socket
import sys
from zeroconf import ServiceInfo, Zeroconf, __version__
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
if len(sys.argv) > 1:
assert sys.argv[1:] == ['--debug']
logging.getLogger('zeroconf').setLevel(logging.DEBUG)
# Test a few module features, including service registration, service
# query (for Zoe), and service unregistration.
print("Multicast DNS Service Discovery for Python, version %s" % (__version__,))
r = Zeroconf()
print("1. Testing registration of a service...")
desc = {'version': '0.10', 'a': 'test value', 'b': 'another value'}
addresses = [socket.inet_aton("127.0.0.1")]
expected = {'127.0.0.1'}
if socket.has_ipv6:
addresses.append(socket.inet_pton(socket.AF_INET6, '::1'))
expected.add('::1')
info = ServiceInfo(
"_http._tcp.local.",
"My Service Name._http._tcp.local.",
addresses=addresses,
port=1234,
properties=desc,
)
print(" Registering service...")
r.register_service(info)
print(" Registration done.")
print("2. Testing query of service information...")
print(" Getting ZOE service: %s" % (r.get_service_info("_http._tcp.local.", "ZOE._http._tcp.local.")))
print(" Query done.")
print("3. Testing query of own service...")
queried_info = r.get_service_info("_http._tcp.local.", "My Service Name._http._tcp.local.")
assert queried_info
assert set(queried_info.parsed_addresses()) == expected
print(" Getting self: %s" % (queried_info,))
print(" Query done.")
print("4. Testing unregister of service information...")
r.unregister_service(info)
print(" Unregister done.")
r.close()
python-zeroconf-0.24.4/pyproject.toml 0000664 0000000 0000000 00000000152 13602475314 0017664 0 ustar 00root root 0000000 0000000 [tool.black]
line-length = 110
target_version = ['py35', 'py36', 'py37']
skip_string_normalization = true
python-zeroconf-0.24.4/requirements-dev.txt 0000664 0000000 0000000 00000000255 13602475314 0021014 0 ustar 00root root 0000000 0000000 autopep8
coveralls
coverage
# Version restricted because of https://github.com/PyCQA/pycodestyle/issues/741
flake8>=3.6.0
flake8-import-order
ifaddr
nose
pep8-naming!=0.6.0
python-zeroconf-0.24.4/setup.cfg 0000664 0000000 0000000 00000001053 13602475314 0016572 0 ustar 00root root 0000000 0000000 [flake8]
show-source = 1
application-import-names=zeroconf
max-line-length=110
ignore=E203,W503
[mypy]
ignore_missing_imports = true
follow_imports = error
check_untyped_defs = true
no_implicit_optional = true
warn_incomplete_stub = true
warn_no_return = true
warn_redundant_casts = true
warn_unused_configs = true
warn_unused_ignores = true
warn_return_any = true
# TODO: disallow untyped calls and defs once we have full type hint coverage
disallow_untyped_calls = false
disallow_untyped_defs = true
[mypy-zeroconf.test]
disallow_untyped_defs = false
python-zeroconf-0.24.4/setup.py 0000775 0000000 0000000 00000003313 13602475314 0016467 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python3
from io import open
from os.path import abspath, dirname, join
from setuptools import setup
PROJECT_ROOT = abspath(dirname(__file__))
with open(join(PROJECT_ROOT, 'README.rst'), encoding='utf-8') as f:
readme = f.read()
version = (
[l for l in open(join(PROJECT_ROOT, 'zeroconf', '__init__.py')) if '__version__' in l][0]
.split('=')[-1]
.strip()
.strip('\'"')
)
setup(
name='zeroconf',
version=version,
description='Pure Python Multicast DNS Service Discovery Library ' '(Bonjour/Avahi compatible)',
long_description=readme,
author='Paul Scott-Murphy, William McBrine, Jakub Stasiak',
url='https://github.com/jstasiak/python-zeroconf',
package_data={"zeroconf": ["py.typed"]},
packages=["zeroconf"],
platforms=['unix', 'linux', 'osx'],
license='LGPL',
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)',
'Operating System :: POSIX',
'Operating System :: POSIX :: Linux',
'Operating System :: MacOS :: MacOS X',
'Topic :: Software Development :: Libraries',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
keywords=['Bonjour', 'Avahi', 'Zeroconf', 'Multicast DNS', 'Service Discovery', 'mDNS'],
install_requires=['ifaddr', 'typing;python_version<"3.5"'],
)
python-zeroconf-0.24.4/zeroconf/ 0000775 0000000 0000000 00000000000 13602475314 0016577 5 ustar 00root root 0000000 0000000 python-zeroconf-0.24.4/zeroconf/__init__.py 0000664 0000000 0000000 00000272151 13602475314 0020720 0 ustar 00root root 0000000 0000000 """ 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 ipaddress
import itertools
import logging
import os
import platform
import re
import select
import socket
import struct
import sys
import threading
import time
import warnings
from typing import Dict, List, Optional, Sequence, Union, cast
from typing import Any, Callable, Set, Tuple # noqa # used in type hints
import ifaddr
__author__ = 'Paul Scott-Murphy, William McBrine'
__maintainer__ = 'Jakub Stasiak '
__version__ = '0.24.4'
__license__ = 'LGPL'
__all__ = [
"__version__",
"Zeroconf",
"ServiceInfo",
"ServiceBrowser",
"Error",
"InterfaceChoice",
"ServiceStateChange",
"IPVersion",
]
if sys.version_info <= (3, 3):
raise ImportError(
'''
Python version > 3.3 required for python-zeroconf.
If you need support for Python 2 or Python 3.3 please use version 19.1
'''
)
log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())
if log.level == logging.NOTSET:
log.setLevel(logging.WARN)
# Some timing constants
_UNREGISTER_TIME = 125 # ms
_CHECK_TIME = 175 # ms
_REGISTER_TIME = 225 # ms
_LISTENER_TIME = 200 # ms
_BROWSER_TIME = 1000 # ms
_BROWSER_BACKOFF_LIMIT = 3600 # s
# Some DNS constants
_MDNS_ADDR = '224.0.0.251'
_MDNS_ADDR_BYTES = socket.inet_aton(_MDNS_ADDR)
_MDNS_ADDR6 = 'ff02::fb'
_MDNS_ADDR6_BYTES = socket.inet_pton(socket.AF_INET6, _MDNS_ADDR6)
_MDNS_PORT = 5353
_DNS_PORT = 53
_DNS_HOST_TTL = 120 # two minute for host records (A, SRV etc) as-per RFC6762
_DNS_OTHER_TTL = 4500 # 75 minutes for non-host records (PTR, TXT etc) as-per RFC6762
_MAX_MSG_TYPICAL = 1460 # unused
_MAX_MSG_ABSOLUTE = 8966
_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_ONLY_A_TO_Z_NUM_HYPHEN_UNDERSCORE = re.compile(r'^[A-Za-z0-9\-\_]+$')
_HAS_ASCII_CONTROL_CHARS = re.compile(r'[\x00-\x1f\x7f]')
try:
_IPPROTO_IPV6 = socket.IPPROTO_IPV6
except AttributeError:
# Sigh: https://bugs.python.org/issue29515
_IPPROTO_IPV6 = 41
int2byte = struct.Struct(">B").pack
@enum.unique
class InterfaceChoice(enum.Enum):
Default = 1
All = 2
InterfacesType = Union[List[Union[str, int]], InterfaceChoice]
@enum.unique
class ServiceStateChange(enum.Enum):
Added = 1
Removed = 2
Updated = 3
@enum.unique
class IPVersion(enum.Enum):
V4Only = 1
V6Only = 2
All = 3
# utility functions
def current_time_millis() -> float:
"""Current system time in milliseconds"""
return time.time() * 1000
def _is_v6_address(addr: bytes) -> bool:
return len(addr) == 16
def service_type_name(type_: str, *, allow_underscores: bool = False) -> str:
"""
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)
allowed_characters_re = (
_HAS_ONLY_A_TO_Z_NUM_HYPHEN_UNDERSCORE if allow_underscores else _HAS_ONLY_A_TO_Z_NUM_HYPHEN
)
if not allowed_characters_re.search(name):
raise BadTypeInNameException(
"Service name (%s) must contain only these characters: "
"A-Z, a-z, 0-9, hyphen ('-')%s" % (name, ", underscore ('_')" if allow_underscores else "")
)
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:
_seen_logs = {} # type: Dict[str, Union[int, tuple]]
@classmethod
def log_exception_warning(cls, logger_data: Optional[Tuple] = None) -> 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=True)
@classmethod
def log_warning_once(cls, *args: Any) -> None:
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] = cast(int, cls._seen_logs[msg_str]) + 1
logger(*args)
class DNSEntry:
"""A DNS entry"""
def __init__(self, name: str, type_: int, class_: int) -> None:
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: Any) -> bool:
"""Equality test on name, type, and class"""
return (
self.name == other.name
and self.type == other.type
and self.class_ == other.class_
and isinstance(other, DNSEntry)
)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
@staticmethod
def get_class_(class_: int) -> str:
"""Class accessor"""
return _CLASSES.get(class_, "?(%s)" % class_)
@staticmethod
def get_type(t: int) -> str:
"""Type accessor"""
return _TYPES.get(t, "?(%s)" % t)
def entry_to_string(self, hdr: str, other: Optional[Union[bytes, str]]) -> str:
"""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" % cast(Any, other)
else:
result += "]"
return result
class DNSQuestion(DNSEntry):
"""A DNS question entry"""
def __init__(self, name: str, type_: int, class_: int) -> None:
DNSEntry.__init__(self, name, type_, class_)
def answered_by(self, rec: 'DNSRecord') -> bool:
"""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) -> str:
"""String representation"""
return DNSEntry.entry_to_string(self, "question", None)
class DNSRecord(DNSEntry):
"""A DNS record - like a DNS entry, but has a TTL"""
# TODO: Switch to just int ttl
def __init__(self, name: str, type_: int, class_: int, ttl: Union[float, int]) -> None:
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: Any) -> bool:
"""Abstract method"""
raise AbstractMethodException
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def suppressed_by(self, msg: 'DNSIncoming') -> bool:
"""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: 'DNSRecord') -> bool:
"""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: int) -> float:
"""Returns the time at which this record will have expired
by a certain percentage."""
return self.created + (percent * self.ttl * 10)
# TODO: Switch to just int here
def get_remaining_ttl(self, now: float) -> Union[int, float]:
"""Returns the remaining TTL in seconds."""
return max(0, (self._expiration_time - now) / 1000.0)
def is_expired(self, now: float) -> bool:
"""Returns true if this record has expired."""
return self._expiration_time <= now
def is_stale(self, now: float) -> bool:
"""Returns true if this record is at least half way expired."""
return self._stale_time <= now
def reset_ttl(self, other: 'DNSRecord') -> None:
"""Sets this record's TTL and created time to that of
another record."""
self.created = other.created
self.ttl = other.ttl
self._expiration_time = self.get_expiration_time(100)
self._stale_time = self.get_expiration_time(50)
def write(self, out: 'DNSOutgoing') -> None:
"""Abstract method"""
raise AbstractMethodException
def to_string(self, other: Union[bytes, str]) -> str:
"""String representation with additional information"""
arg = "%s/%s,%s" % (self.ttl, int(self.get_remaining_ttl(current_time_millis())), cast(Any, other))
return DNSEntry.entry_to_string(self, "record", arg)
class DNSAddress(DNSRecord):
"""A DNS address record"""
def __init__(self, name: str, type_: int, class_: int, ttl: int, address: bytes) -> None:
DNSRecord.__init__(self, name, type_, class_, ttl)
self.address = address
def write(self, out: 'DNSOutgoing') -> None:
"""Used in constructing an outgoing packet"""
out.write_string(self.address)
def __eq__(self, other: Any) -> bool:
"""Tests equality on address"""
return (
isinstance(other, DNSAddress) and DNSEntry.__eq__(self, other) and self.address == other.address
)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""String representation"""
try:
return self.to_string(str(socket.inet_ntoa(self.address)))
except Exception: # TODO stop catching all Exceptions
return self.to_string(str(self.address))
class DNSHinfo(DNSRecord):
"""A DNS host information record"""
def __init__(
self, name: str, type_: int, class_: int, ttl: int, cpu: Union[bytes, str], os: Union[bytes, str]
) -> None:
DNSRecord.__init__(self, name, type_, class_, ttl)
try:
self.cpu = cast(bytes, cpu).decode('utf-8')
except AttributeError:
self.cpu = cast(str, cpu)
try:
self.os = cast(bytes, os).decode('utf-8')
except AttributeError:
self.os = cast(str, os)
def write(self, out: 'DNSOutgoing') -> None:
"""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: Any) -> bool:
"""Tests equality on cpu and os"""
return (
isinstance(other, DNSHinfo)
and DNSEntry.__eq__(self, other)
and self.cpu == other.cpu
and self.os == other.os
)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""String representation"""
return self.to_string(self.cpu + " " + self.os)
class DNSPointer(DNSRecord):
"""A DNS pointer record"""
def __init__(self, name: str, type_: int, class_: int, ttl: int, alias: str) -> None:
DNSRecord.__init__(self, name, type_, class_, ttl)
self.alias = alias
def write(self, out: 'DNSOutgoing') -> None:
"""Used in constructing an outgoing packet"""
out.write_name(self.alias)
def __eq__(self, other: Any) -> bool:
"""Tests equality on alias"""
return isinstance(other, DNSPointer) and self.alias == other.alias and DNSEntry.__eq__(self, other)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""String representation"""
return self.to_string(self.alias)
class DNSText(DNSRecord):
"""A DNS text record"""
def __init__(self, name: str, type_: int, class_: int, ttl: int, text: bytes) -> None:
assert isinstance(text, (bytes, type(None)))
DNSRecord.__init__(self, name, type_, class_, ttl)
self.text = text
def write(self, out: 'DNSOutgoing') -> None:
"""Used in constructing an outgoing packet"""
out.write_string(self.text)
def __eq__(self, other: Any) -> bool:
"""Tests equality on text"""
return isinstance(other, DNSText) and self.text == other.text and DNSEntry.__eq__(self, other)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""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: str,
type_: int,
class_: int,
ttl: Union[float, int],
priority: int,
weight: int,
port: int,
server: str,
) -> None:
DNSRecord.__init__(self, name, type_, class_, ttl)
self.priority = priority
self.weight = weight
self.port = port
self.server = server
def write(self, out: 'DNSOutgoing') -> None:
"""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: Any) -> bool:
"""Tests equality on priority, weight, port and server"""
return (
isinstance(other, DNSService)
and self.priority == other.priority
and self.weight == other.weight
and self.port == other.port
and self.server == other.server
and DNSEntry.__eq__(self, other)
)
def __ne__(self, other: Any) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""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: bytes) -> None:
"""Constructor from string holding bytes of packet"""
self.offset = 0
self.data = data
self.questions = [] # type: List[DNSQuestion]
self.answers = [] # type: List[DNSRecord]
self.id = 0
self.flags = 0 # type: int
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_: bytes) -> tuple:
length = struct.calcsize(format_)
info = struct.unpack(format_, self.data[self.offset : self.offset + length])
self.offset += length
return info
def read_header(self) -> None:
"""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) -> None:
"""Reads questions section of packet"""
for i in range(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) -> bytes:
"""Reads a character string from the packet"""
length = self.data[self.offset]
self.offset += 1
return self.read_string(length)
def read_string(self, length: int) -> bytes:
"""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) -> int:
"""Reads an unsigned short from the packet"""
return cast(int, self.unpack(b'!H')[0])
def read_others(self) -> None:
"""Reads the answers, authorities and additionals section of the
packet"""
n = self.num_answers + self.num_authorities + self.num_additionals
for i in range(n):
domain = self.read_name()
type_, class_, ttl, length = self.unpack(b'!HHiH')
rec = None # type: Optional[DNSRecord]
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) -> bool:
"""Returns true if this is a query"""
return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY
def is_response(self) -> bool:
"""Returns true if this is a response"""
return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE
def read_utf(self, offset: int, length: int) -> str:
"""Reads a UTF-8 string of a given length from the packet"""
return str(self.data[offset : offset + length], 'utf-8', 'replace')
def read_name(self) -> str:
"""Reads a domain name from the packet"""
result = ''
off = self.offset
next_ = -1
first = off
while True:
length = 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) | 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 representation of an outgoing packet"""
def __init__(self, flags: int, multicast: bool = True) -> None:
self.finished = False
self.id = 0
self.multicast = multicast
self.flags = flags
self.names = {} # type: Dict[str, int]
self.data = [] # type: List[bytes]
self.size = 12
self.state = self.State.init
self.questions = [] # type: List[DNSQuestion]
self.answers = [] # type: List[Tuple[DNSRecord, float]]
self.authorities = [] # type: List[DNSPointer]
self.additionals = [] # type: List[DNSRecord]
def __repr__(self) -> str:
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: DNSQuestion) -> None:
"""Adds a question"""
self.questions.append(record)
def add_answer(self, inp: DNSIncoming, record: DNSRecord) -> None:
"""Adds an answer"""
if not record.suppressed_by(inp):
self.add_answer_at_time(record, 0)
def add_answer_at_time(self, record: Optional[DNSRecord], now: Union[float, int]) -> None:
"""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: DNSPointer) -> None:
"""Adds an authoritative answer"""
self.authorities.append(record)
def add_additional_answer(self, record: DNSRecord) -> None:
""" 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_: Union[bytes, str], value: Any) -> None:
self.data.append(struct.pack(format_, value))
self.size += struct.calcsize(format_)
def write_byte(self, value: int) -> None:
"""Writes a single byte to the packet"""
self.pack(b'!c', int2byte(value))
def insert_short(self, index: int, value: int) -> None:
"""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: int) -> None:
"""Writes an unsigned short to the packet"""
self.pack(b'!H', value)
def write_int(self, value: Union[float, int]) -> None:
"""Writes an unsigned integer to the packet"""
self.pack(b'!I', int(value))
def write_string(self, value: bytes) -> None:
"""Writes a string to the packet"""
assert isinstance(value, bytes)
self.data.append(value)
self.size += len(value)
def write_utf(self, s: str) -> None:
"""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: bytes) -> None:
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: str) -> None:
"""
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 = len(name_suffices)
# note the new names we are saving into the packet
name_length = len(name.encode('utf-8'))
for suffix in name_suffices[:count]:
self.names[suffix] = self.size + name_length - len(suffix.encode('utf-8')) - 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: DNSQuestion) -> None:
"""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: DNSRecord, now: float) -> int:
"""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) -> bytes:
"""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:
"""A cache of DNS entries"""
def __init__(self) -> None:
self.cache = {} # type: Dict[str, List[DNSRecord]]
def add(self, entry: DNSRecord) -> None:
"""Adds an entry"""
# Insert first in list so get returns newest entry
self.cache.setdefault(entry.key, []).insert(0, entry)
def remove(self, entry: DNSRecord) -> None:
"""Removes an entry"""
try:
list_ = self.cache[entry.key]
list_.remove(entry)
except (KeyError, ValueError):
pass
def get(self, entry: DNSEntry) -> Optional[DNSRecord]:
"""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
return None
except (KeyError, ValueError):
return None
def get_by_details(self, name: str, type_: int, class_: int) -> Optional[DNSRecord]:
"""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: str) -> List[DNSRecord]:
"""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: str, alias: str) -> Optional[DNSRecord]:
now = current_time_millis()
for record in self.entries_with_name(name):
if (
record.type == _TYPE_PTR
and not record.is_expired(now)
and cast(DNSPointer, record).alias == alias
):
return record
return None
def entries(self) -> List[DNSRecord]:
"""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 list(itertools.chain.from_iterable(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: 'Zeroconf') -> None:
threading.Thread.__init__(self, name='zeroconf-Engine')
self.daemon = True
self.zc = zc
self.readers = {} # type: Dict[socket.socket, Listener]
self.timeout = 5
self.condition = threading.Condition()
self.start()
def run(self) -> None:
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(cast(Sequence[Any], 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] not in (errno.EBADF, errno.ENOTCONN) or not self.zc.done:
raise
def add_reader(self, reader: 'Listener', socket_: socket.socket) -> None:
with self.condition:
self.readers[socket_] = reader
self.condition.notify()
def del_reader(self, socket_: socket.socket) -> None:
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: 'Zeroconf') -> None:
self.zc = zc
self.data = None # type: Optional[bytes]
def handle_read(self, socket_: socket.socket) -> None:
try:
data, (addr, port, *_v6) = 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, None, _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, None, _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: 'Zeroconf') -> None:
threading.Thread.__init__(self, name='zeroconf-Reaper')
self.daemon = True
self.zc = zc
self.start()
def run(self) -> None:
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:
def __init__(self) -> None:
self._handlers = [] # type: List[Callable[..., None]]
def fire(self, **kwargs: Any) -> None:
for h in list(self._handlers):
h(**kwargs)
@property
def registration_interface(self) -> 'SignalRegistrationInterface':
return SignalRegistrationInterface(self._handlers)
# NOTE: Callable quoting needed on Python 3.5.2, see
# https://github.com/jstasiak/python-zeroconf/issues/208 for details.
class SignalRegistrationInterface:
def __init__(self, handlers: List['Callable[..., None]']) -> None:
self._handlers = handlers
def register_handler(self, handler: 'Callable[..., None]') -> 'SignalRegistrationInterface':
self._handlers.append(handler)
return self
def unregister_handler(self, handler: 'Callable[..., None]') -> 'SignalRegistrationInterface':
self._handlers.remove(handler)
return self
class RecordUpdateListener:
def update_record(self, zc: 'Zeroconf', now: float, record: DNSRecord) -> None:
raise NotImplementedError()
class ServiceListener:
def add_service(self, zc: 'Zeroconf', type_: str, name: str) -> None:
raise NotImplementedError()
def remove_service(self, zc: 'Zeroconf', type_: str, name: str) -> None:
raise NotImplementedError()
def update_service(self, zc: 'Zeroconf', type_: str, name: str) -> None:
raise NotImplementedError()
class ServiceBrowser(RecordUpdateListener, 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: 'Zeroconf',
type_: str,
# NOTE: Callable quoting needed on Python 3.5.2, see
# https://github.com/jstasiak/python-zeroconf/issues/208 for details.
handlers: Optional[Union[ServiceListener, List['Callable[..., None]']]] = None,
listener: Optional[ServiceListener] = None,
addr: Optional[str] = None,
port: int = _MDNS_PORT,
delay: int = _BROWSER_TIME,
) -> 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_, allow_underscores=True)):
raise BadTypeInNameException
threading.Thread.__init__(self, name='zeroconf-ServiceBrowser_' + type_)
self.daemon = True
self.zc = zc
self.type = type_
self.addr = addr
self.port = port
self.multicast = self.addr in (None, _MDNS_ADDR, _MDNS_ADDR6)
self.services = {} # type: Dict[str, DNSRecord]
self.next_time = current_time_millis()
self.delay = delay
self._handlers_to_call = [] # type: List[Callable[[Zeroconf], None]]
self._service_state_changed = Signal()
self.done = False
if hasattr(handlers, 'add_service'):
listener = cast(ServiceListener, handlers)
handlers = None
# NOTE: Callable quoting needed on Python 3.5.2, see
# https://github.com/jstasiak/python-zeroconf/issues/208 for details.
handlers = cast(List['Callable[..., None]'], handlers or [])
if listener:
def on_change(
zeroconf: 'Zeroconf', service_type: str, name: str, state_change: ServiceStateChange
) -> None:
assert listener is not None
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)
elif state_change is ServiceStateChange.Updated:
if hasattr(listener, 'update_service'):
listener.update_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) -> SignalRegistrationInterface:
return self._service_state_changed.registration_interface
def update_record(self, zc: 'Zeroconf', now: float, record: DNSRecord) -> None:
"""Callback invoked by Zeroconf when new information arrives.
Updates information required by browser in the Zeroconf cache."""
def enqueue_callback(state_change: ServiceStateChange, name: str) -> None:
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:
assert isinstance(record, DNSPointer)
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
elif record.type == _TYPE_TXT and record.name.endswith(self.type):
assert isinstance(record, DNSText)
expired = record.is_expired(now)
if not expired:
enqueue_callback(ServiceStateChange.Updated, record.name)
def cancel(self) -> None:
self.done = True
self.zc.remove_listener(self)
self.join()
def run(self) -> None:
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, multicast=self.multicast)
out.add_question(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
for record in self.services.values():
if not record.is_stale(now):
out.add_answer_at_time(record, now)
self.zc.send(out, addr=self.addr, port=self.port)
self.next_time = now + self.delay
self.delay = min(_BROWSER_BACKOFF_LIMIT * 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(RecordUpdateListener):
text = b''
"""Service information"""
# FIXME(dtantsur): black 19.3b0 produces code that is not valid syntax on
# Python 3.5: https://github.com/python/black/issues/759
# fmt: off
def __init__(
self,
type_: str,
name: str,
address: Optional[Union[bytes, List[bytes]]] = None,
port: Optional[int] = None,
weight: int = 0,
priority: int = 0,
properties: Union[bytes, Dict] = b'',
server: Optional[str] = None,
host_ttl: int = _DNS_HOST_TTL,
other_ttl: int = _DNS_OTHER_TTL,
*,
addresses: Optional[List[bytes]] = None
) -> 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 (deprecated, use addresses)
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)
host_ttl: ttl used for A/SRV records
other_ttl: ttl used for PTR/TXT records
addresses: List of IP addresses as unsigned short (IPv4) or unsigned
128 bit number (IPv6), network byte order
"""
# Accept both none, or one, but not both.
if address is not None and addresses is not None:
raise TypeError("address and addresses cannot be provided together")
if not type_.endswith(service_type_name(name, allow_underscores=True)):
raise BadTypeInNameException
self.type = type_
self.name = name
if addresses is not None:
self._addresses = addresses
elif address is not None:
warnings.warn("address is deprecated, use addresses instead", DeprecationWarning)
if isinstance(address, list):
self._addresses = address
else:
self._addresses = [address]
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) not in (4, 16)]
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
if server:
self.server = server
else:
self.server = name
self._properties = {} # type: Dict
self._set_properties(properties)
self.host_ttl = host_ttl
self.other_ttl = other_ttl
# fmt: on
@property
def address(self) -> Optional[bytes]:
warnings.warn("ServiceInfo.address is deprecated, use addresses instead", DeprecationWarning)
try:
# Return the first V4 address for compatibility
return self.addresses[0]
except IndexError:
return None
@address.setter
def address(self, value: bytes) -> None:
warnings.warn("ServiceInfo.address is deprecated, use addresses instead", DeprecationWarning)
if value is None:
self._addresses = []
else:
self._addresses = [value]
@property
def addresses(self) -> List[bytes]:
"""IPv4 addresses of this service.
Only IPv4 addresses are returned for backward compatibility.
Use :meth:`addresses_by_version` or :meth:`parsed_addresses` to
include IPv6 addresses as well.
"""
return self.addresses_by_version(IPVersion.V4Only)
@addresses.setter
def addresses(self, value: List[bytes]) -> None:
"""Replace the addresses list.
This replaces all currently stored addresses, both IPv4 and IPv6.
"""
self._addresses = value
@property
def properties(self) -> Dict:
return self._properties
def addresses_by_version(self, version: IPVersion) -> List[bytes]:
"""List addresses matching IP version."""
if version == IPVersion.V4Only:
return [addr for addr in self._addresses if not _is_v6_address(addr)]
elif version == IPVersion.V6Only:
return list(filter(_is_v6_address, self._addresses))
else:
return self._addresses
def parsed_addresses(self, version: IPVersion = IPVersion.All) -> List[str]:
"""List addresses in their parsed string form."""
result = self.addresses_by_version(version)
return [
socket.inet_ntop(socket.AF_INET6 if _is_v6_address(addr) else socket.AF_INET, addr)
for addr in result
]
def _set_properties(self, properties: Union[bytes, Dict]) -> None:
"""Sets properties and text of this info from a dictionary"""
if isinstance(properties, dict):
self._properties = properties
list_ = []
result = b''
for key, value in properties.items():
if isinstance(key, str):
key = key.encode('utf-8')
if value is None:
suffix = b''
elif isinstance(value, str):
suffix = value.encode('utf-8')
elif isinstance(value, bytes):
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: bytes) -> None:
"""Sets properties and text given a text field"""
self.text = text
result = {} # type: Dict
end = len(text)
index = 0
strs = []
while index < end:
length = 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 # type: Tuple[bytes, Union[bool, bytes]]
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) -> str:
"""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: 'Zeroconf', now: float, record: Optional[DNSRecord]) -> None:
"""Updates service information from a DNS record"""
if record is not None and not record.is_expired(now):
if record.type in [_TYPE_A, _TYPE_AAAA]:
assert isinstance(record, DNSAddress)
# if record.name == self.name:
if record.name == self.server:
if record.address not in self._addresses:
self._addresses.append(record.address)
elif record.type == _TYPE_SRV:
assert isinstance(record, DNSService)
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))
self.update_record(zc, now, zc.cache.get_by_details(self.server, _TYPE_AAAA, _CLASS_IN))
elif record.type == _TYPE_TXT:
assert isinstance(record, DNSText)
if record.name == self.name:
self._set_text(record.text)
def request(self, zc: 'Zeroconf', timeout: float) -> bool:
"""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))
record_types_for_check_cache.append((_TYPE_AAAA, _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 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 self.server is None or self.text is None or not self._addresses:
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)
out.add_question(DNSQuestion(self.server, _TYPE_AAAA, _CLASS_IN))
out.add_answer_at_time(
zc.cache.get_by_details(self.server, _TYPE_AAAA, _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: object) -> bool:
"""Tests equality of service name"""
return isinstance(other, ServiceInfo) and other.name == self.name
def __ne__(self, other: object) -> bool:
"""Non-equality test"""
return not self.__eq__(other)
def __repr__(self) -> str:
"""String representation"""
return '%s(%s)' % (
type(self).__name__,
', '.join(
'%s=%r' % (name, getattr(self, name))
for name in (
'type',
'name',
'addresses',
'port',
'weight',
'priority',
'server',
'properties',
)
),
)
class ZeroconfServiceTypes(ServiceListener):
"""
Return all of the advertised services on any local networks
"""
def __init__(self) -> None:
self.found_services = set() # type: Set[str]
def add_service(self, zc: 'Zeroconf', type_: str, name: str) -> None:
self.found_services.add(name)
def remove_service(self, zc: 'Zeroconf', type_: str, name: str) -> None:
pass
@classmethod
def find(
cls,
zc: Optional['Zeroconf'] = None,
timeout: Union[int, float] = 5,
interfaces: InterfacesType = InterfaceChoice.All,
ip_version: Optional[IPVersion] = None,
) -> Tuple[str, ...]:
"""
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
:param interfaces: interfaces to listen on.
:param ip_version: IP protocol version to use.
:return: tuple of service type strings
"""
local_zc = zc or Zeroconf(interfaces=interfaces, ip_version=ip_version)
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() -> List[str]:
return list(
set(
addr.ip
for iface in ifaddr.get_adapters()
for addr in iface.ips
if addr.is_IPv4 and addr.network_prefix != 32 # Host only netmask 255.255.255.255
)
)
def get_all_addresses_v6() -> List[int]:
# IPv6 multicast uses positive indexes for interfaces
try:
nameindex = socket.if_nameindex
except AttributeError:
# Requires Python 3.8 on Windows. Fall back to Default.
QuietLogger.log_warning_once(
'if_nameindex is not available, falling back to using the default IPv6 interface'
)
return [0]
return [tpl[0] for tpl in nameindex()]
def ip_to_index(adapters: List[Any], ip: str) -> int:
if os.name != 'posix':
# Adapter names that ifaddr reports are not compatible with what if_nametoindex expects on Windows.
# We need https://github.com/pydron/ifaddr/pull/21 but it seems stuck on review.
raise RuntimeError('Converting from IP addresses to indexes is not supported on non-POSIX systems')
ipaddr = ipaddress.ip_address(ip)
for adapter in adapters:
for adapter_ip in adapter.ips:
# IPv6 addresses are represented as tuples
if isinstance(adapter_ip.ip, tuple) and ipaddress.ip_address(adapter_ip.ip[0]) == ipaddr:
return socket.if_nametoindex(adapter.name)
raise RuntimeError('No adapter found for IP address %s' % ip)
def ip6_addresses_to_indexes(interfaces: List[Union[str, int]]) -> List[int]:
"""Convert IPv6 interface addresses to interface indexes.
IPv4 addresses are ignored. The conversion currently only works on POSIX
systems.
:param interfaces: List of IP addresses and indexes.
:returns: List of indexes.
"""
result = []
adapters = ifaddr.get_adapters()
for iface in interfaces:
if isinstance(iface, int):
result.append(iface)
elif isinstance(iface, str) and ipaddress.ip_address(iface).version == 6:
result.append(ip_to_index(adapters, iface))
return result
def normalize_interface_choice(
choice: InterfacesType, ip_version: IPVersion = IPVersion.V4Only
) -> List[Union[str, int]]:
"""Convert the interfaces choice into internal representation.
:param choice: `InterfaceChoice` or list of interface addresses or indexes (IPv6 only).
:param ip_address: IP version to use (ignored if `choice` is a list).
:returns: List of IP addresses (for IPv4) and indexes (for IPv6).
"""
result = [] # type: List[Union[str, int]]
if choice is InterfaceChoice.Default:
if ip_version != IPVersion.V4Only:
# IPv6 multicast uses interface 0 to mean the default
result.append(0)
if ip_version != IPVersion.V6Only:
result.append('0.0.0.0')
elif choice is InterfaceChoice.All:
if ip_version != IPVersion.V4Only:
result.extend(get_all_addresses_v6())
if ip_version != IPVersion.V6Only:
result.extend(get_all_addresses())
if not result:
raise RuntimeError(
'No interfaces to listen on, check that any interfaces have IP version %s' % ip_version
)
elif isinstance(choice, list):
# First, take IPv4 addresses.
result = [i for i in choice if isinstance(i, str) and ipaddress.ip_address(i).version == 4]
# Unlike IP_ADD_MEMBERSHIP, IPV6_JOIN_GROUP requires interface indexes.
result += ip6_addresses_to_indexes(choice)
else:
raise TypeError("choice must be a list or InterfaceChoice, got %r" % choice)
return result
def new_socket(
port: int = _MDNS_PORT, ip_version: IPVersion = IPVersion.V4Only, apple_p2p: bool = False
) -> socket.socket:
if ip_version == IPVersion.V4Only:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
else:
s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
if ip_version == IPVersion.All:
# make V6 sockets work for both V4 and V6 (required for Windows)
try:
s.setsockopt(_IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
except OSError:
log.error('Support for dual V4-V6 sockets is not present, use IPVersion.V4 or IPVersion.V6')
raise
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 explicitly. 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
if port is _MDNS_PORT:
ttl = struct.pack(b'B', 255)
loop = struct.pack(b'B', 1)
if ip_version != IPVersion.V6Only:
# OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and
# IP_MULTICAST_LOOP socket options as an unsigned char.
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop)
if ip_version != IPVersion.V4Only:
# However, char doesn't work here (at least on Linux)
s.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, 255)
s.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, True)
if apple_p2p:
# SO_RECV_ANYIF = 0x1104
# https://opensource.apple.com/source/xnu/xnu-4570.41.2/bsd/sys/socket.h
s.setsockopt(socket.SOL_SOCKET, 0x1104, 1)
s.bind(('', port))
return s
def add_multicast_member(
listen_socket: socket.socket, interface: Union[str, int], apple_p2p: bool = False
) -> Optional[socket.socket]:
# This is based on assumptions in normalize_interface_choice
is_v6 = isinstance(interface, int)
log.debug('Adding %r to multicast group', interface)
try:
if is_v6:
iface_bin = struct.pack('@I', cast(int, interface))
_value = _MDNS_ADDR6_BYTES + iface_bin
listen_socket.setsockopt(_IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, _value)
else:
_value = _MDNS_ADDR_BYTES + socket.inet_aton(cast(str, interface))
listen_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, _value)
except socket.error as e:
_errno = get_errno(e)
if _errno == errno.EADDRINUSE:
log.info(
'Address in use when adding %s to multicast group, '
'it is expected to happen on some systems',
interface,
)
return None
elif _errno == errno.EADDRNOTAVAIL:
log.info(
'Address not available when adding %s to multicast '
'group, it is expected to happen on some systems',
interface,
)
return None
elif _errno == errno.EINVAL:
log.info('Interface of %s does not support multicast, ' 'it is expected in WSL', interface)
return None
else:
raise
respond_socket = new_socket(
ip_version=(IPVersion.V6Only if is_v6 else IPVersion.V4Only), apple_p2p=apple_p2p
)
log.debug('Configuring %s with multicast interface %s', respond_socket, interface)
if is_v6:
respond_socket.setsockopt(_IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, iface_bin)
else:
respond_socket.setsockopt(
socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(cast(str, interface))
)
return respond_socket
def create_sockets(
interfaces: InterfacesType = InterfaceChoice.All,
unicast: bool = False,
ip_version: IPVersion = IPVersion.V4Only,
apple_p2p: bool = False,
) -> Tuple[Optional[socket.socket], List[socket.socket]]:
if unicast:
listen_socket = None
else:
listen_socket = new_socket(ip_version=ip_version, apple_p2p=apple_p2p)
interfaces = normalize_interface_choice(interfaces, ip_version)
respond_sockets = []
for i in interfaces:
if not unicast:
respond_socket = add_multicast_member(cast(socket.socket, listen_socket), i, apple_p2p=apple_p2p)
else:
respond_socket = new_socket(port=0, ip_version=ip_version, apple_p2p=apple_p2p)
if respond_socket is not None:
respond_sockets.append(respond_socket)
return listen_socket, respond_sockets
def get_errno(e: Exception) -> int:
assert isinstance(e, socket.error)
return cast(int, e.args[0])
def can_send_to(sock: socket.socket, address: str) -> bool:
addr = ipaddress.ip_address(address)
return cast(bool, addr.version == 6 if sock.family == socket.AF_INET6 else addr.version == 4)
class Zeroconf(QuietLogger):
"""Implementation of Zeroconf Multicast DNS Service Discovery
Supports registration, unregistration, queries and browsing.
"""
def __init__(
self,
interfaces: InterfacesType = InterfaceChoice.All,
unicast: bool = False,
ip_version: Optional[IPVersion] = None,
apple_p2p: bool = False,
) -> None:
"""Creates an instance of the Zeroconf class, establishing
multicast communications, listening and reaping threads.
:param interfaces: :class:`InterfaceChoice` or a list of IP addresses
(IPv4 and IPv6) and interface indexes (IPv6 only).
IPv6 notes for non-POSIX systems:
* IPv6 addresses are not supported, use indexes instead.
* `InterfaceChoice.All` is an alias for `InterfaceChoice.Default`
on Python versions before 3.8.
Also listening on loopback (``::1``) doesn't work, use a real address.
:param ip_version: IP versions to support. If `choice` is a list, the default is detected
from it. Otherwise defaults to V4 only for backward compatibility.
:param apple_p2p: use AWDL interface (only macOS)
"""
if ip_version is None and isinstance(interfaces, list):
has_v6 = any(
isinstance(i, int) or (isinstance(i, str) and ipaddress.ip_address(i).version == 6)
for i in interfaces
)
has_v4 = any(isinstance(i, str) and ipaddress.ip_address(i).version == 4 for i in interfaces)
if has_v4 and has_v6:
ip_version = IPVersion.All
elif has_v6:
ip_version = IPVersion.V6Only
if ip_version is None:
ip_version = IPVersion.V4Only
# hook for threads
self._GLOBAL_DONE = False
self.unicast = unicast
if apple_p2p and not platform.system() == 'Darwin':
raise RuntimeError('Option `apple_p2p` is not supported on non-Apple platforms.')
self._listen_socket, self._respond_sockets = create_sockets(
interfaces, unicast, ip_version, apple_p2p=apple_p2p
)
self.listeners = [] # type: List[RecordUpdateListener]
self.browsers = {} # type: Dict[ServiceListener, ServiceBrowser]
self.services = {} # type: Dict[str, ServiceInfo]
self.servicetypes = {} # type: Dict[str, int]
self.cache = DNSCache()
self.condition = threading.Condition()
self.engine = Engine(self)
self.listener = Listener(self)
if not unicast:
self.engine.add_reader(self.listener, cast(socket.socket, self._listen_socket))
else:
for s in self._respond_sockets:
self.engine.add_reader(self.listener, s)
self.reaper = Reaper(self)
self.debug = None # type: Optional[DNSOutgoing]
@property
def done(self) -> bool:
return self._GLOBAL_DONE
def wait(self, timeout: float) -> None:
"""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) -> None:
"""Notifies all waiting threads"""
with self.condition:
self.condition.notify_all()
def get_service_info(self, type_: str, name: str, timeout: int = 3000) -> Optional[ServiceInfo]:
"""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
return None
def add_service_listener(self, type_: str, listener: ServiceListener) -> None:
"""Adds a listener for a particular service type. This object
will then have its add_service and remove_service methods called when
services of that type become available and unavailable."""
self.remove_service_listener(listener)
self.browsers[listener] = ServiceBrowser(self, type_, listener)
def remove_service_listener(self, listener: ServiceListener) -> None:
"""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) -> None:
"""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: ServiceInfo, ttl: Optional[int] = None, allow_name_change: bool = False
) -> None:
"""Registers service information to the network with a default TTL.
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."""
if ttl is not None:
# ttl argument is used to maintain backward compatibility
# Setting TTLs via ServiceInfo is preferred
info.host_ttl = ttl
info.other_ttl = ttl
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
self._broadcast_service(info)
def update_service(self, info: ServiceInfo) -> None:
"""Registers service information to the network with a default TTL.
Zeroconf will then respond to requests for information for that
service."""
assert self.services[info.name.lower()] is not None
self.services[info.name.lower()] = info
self._broadcast_service(info)
def _broadcast_service(self, info: ServiceInfo) -> None:
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, info.other_ttl, info.name), 0)
out.add_answer_at_time(
DNSService(
info.name,
_TYPE_SRV,
_CLASS_IN,
info.host_ttl,
info.priority,
info.weight,
cast(int, info.port),
info.server,
),
0,
)
out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN, info.other_ttl, info.text), 0)
for address in info.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_answer_at_time(DNSAddress(info.server, type_, _CLASS_IN, info.host_ttl, address), 0)
self.send(out)
i += 1
next_time += _REGISTER_TIME
def unregister_service(self, info: ServiceInfo) -> None:
"""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,
cast(int, info.port),
info.name,
),
0,
)
out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
for address in info.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_answer_at_time(DNSAddress(info.server, type_, _CLASS_IN, 0, address), 0)
self.send(out)
i += 1
next_time += _UNREGISTER_TIME
def unregister_all_services(self) -> None:
"""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,
cast(int, info.port),
info.server,
),
0,
)
out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
for address in info.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_answer_at_time(DNSAddress(info.server, type_, _CLASS_IN, 0, address), 0)
self.send(out)
i += 1
next_time += _UNREGISTER_TIME
def check_service(self, info: ServiceInfo, allow_name_change: bool) -> None:
"""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, info.other_ttl, info.name))
self.send(out)
i += 1
next_time += _CHECK_TIME
def add_listener(self, listener: RecordUpdateListener, question: Optional[DNSQuestion]) -> None:
"""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: RecordUpdateListener) -> None:
"""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: float, rec: DNSRecord) -> None:
"""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: DNSIncoming) -> None:
"""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:
if record.unique: # https://tools.ietf.org/html/rfc6762#section-10.2
for entry in self.cache.entries():
if DNSEntry.__eq__(entry, record) and (record.created - entry.created > 1000):
self.cache.remove(entry)
expired = record.is_expired(now)
maybe_entry = self.cache.get(record)
if not expired:
if maybe_entry is not None:
maybe_entry.reset_ttl(record)
else:
self.cache.add(record)
self.update_record(now, record)
else:
if maybe_entry is not None:
self.update_record(now, record)
self.cache.remove(maybe_entry)
def handle_query(self, msg: DNSIncoming, addr: Optional[str], port: int) -> None:
"""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_OTHER_TTL, stype
),
)
for service in self.services.values():
if question.name == service.type:
if out is None:
out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
out.add_answer(
msg,
DNSPointer(service.type, _TYPE_PTR, _CLASS_IN, service.other_ttl, service.name),
)
# Add recommended additional answers according to
# https://tools.ietf.org/html/rfc6763#section-12.1.
out.add_additional_answer(
DNSService(
service.name,
_TYPE_SRV,
_CLASS_IN | _CLASS_UNIQUE,
service.host_ttl,
service.priority,
service.weight,
cast(int, service.port),
service.server,
)
)
out.add_additional_answer(
DNSText(
service.name,
_TYPE_TXT,
_CLASS_IN | _CLASS_UNIQUE,
service.other_ttl,
service.text,
)
)
for address in service.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_additional_answer(
DNSAddress(
service.server,
type_,
_CLASS_IN | _CLASS_UNIQUE,
service.host_ttl,
address,
)
)
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():
for address in service.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_answer(
msg,
DNSAddress(
question.name,
type_,
_CLASS_IN | _CLASS_UNIQUE,
service.host_ttl,
address,
),
)
name_to_find = question.name.lower()
if name_to_find not in self.services:
continue
service = self.services[name_to_find]
if question.type in (_TYPE_SRV, _TYPE_ANY):
out.add_answer(
msg,
DNSService(
question.name,
_TYPE_SRV,
_CLASS_IN | _CLASS_UNIQUE,
service.host_ttl,
service.priority,
service.weight,
cast(int, 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,
service.other_ttl,
service.text,
),
)
if question.type == _TYPE_SRV:
for address in service.addresses_by_version(IPVersion.All):
type_ = _TYPE_AAAA if _is_v6_address(address) else _TYPE_A
out.add_additional_answer(
DNSAddress(
service.server,
type_,
_CLASS_IN | _CLASS_UNIQUE,
service.host_ttl,
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: DNSOutgoing, addr: Optional[str] = None, port: int = _MDNS_PORT) -> None:
"""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:
if addr is None:
real_addr = _MDNS_ADDR6 if s.family == socket.AF_INET6 else _MDNS_ADDR
elif not can_send_to(s, addr):
continue
else:
real_addr = addr
bytes_sent = s.sendto(packet, 0, (real_addr, port))
except Exception as exc: # TODO stop catching all Exceptions
if (
isinstance(exc, OSError)
and exc.errno == errno.ENETUNREACH
and s.family == socket.AF_INET6
):
# with IPv6 we don't have a reliable way to determine if an interface actually has IPv6
# support, so we have to try and ignore errors.
continue
# 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) -> None:
"""Ends the background threads, and prevent this instance from
servicing further queries."""
if not self._GLOBAL_DONE:
# remove service listeners
self.remove_all_service_listeners()
self.unregister_all_services()
self._GLOBAL_DONE = True
# shutdown recv socket and thread
if not self.unicast:
self.engine.del_reader(cast(socket.socket, self._listen_socket))
cast(socket.socket, self._listen_socket).close()
else:
for s in self._respond_sockets:
self.engine.del_reader(s)
self.engine.join()
# shutdown the rest
self.notify_all()
self.reaper.join()
for s in self._respond_sockets:
s.close()
python-zeroconf-0.24.4/zeroconf/py.typed 0000664 0000000 0000000 00000000000 13602475314 0020264 0 ustar 00root root 0000000 0000000 python-zeroconf-0.24.4/zeroconf/test.py 0000664 0000000 0000000 00000143515 13602475314 0020141 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Unit tests for zeroconf.py """
import copy
import logging
import socket
import struct
import time
import unittest
from threading import Event
from typing import Dict, Optional # noqa # used in type hints
from typing import cast
from nose.plugins.attrib import attr
import zeroconf as r
from zeroconf import (
DNSHinfo,
DNSText,
ServiceBrowser,
ServiceInfo,
ServiceStateChange,
Zeroconf,
ZeroconfServiceTypes,
)
log = logging.getLogger('zeroconf')
original_logging_level = logging.NOTSET
def setup_module():
global original_logging_level
original_logging_level = log.level
log.setLevel(logging.DEBUG)
def teardown_module():
if original_logging_level != logging.NOTSET:
log.setLevel(original_logging_level)
class TestDunder(unittest.TestCase):
def test_dns_text_repr(self):
# There was an issue on Python 3 that prevented DNSText's repr
# from working when the text was longer than 10 bytes
text = DNSText('irrelevant', 0, 0, 0, b'12345678901')
repr(text)
text = DNSText('irrelevant', 0, 0, 0, b'123')
repr(text)
def test_dns_hinfo_repr_eq(self):
hinfo = DNSHinfo('irrelevant', r._TYPE_HINFO, 0, 0, 'cpu', 'os')
assert hinfo == hinfo
repr(hinfo)
def test_dns_pointer_repr(self):
pointer = r.DNSPointer('irrelevant', r._TYPE_PTR, r._CLASS_IN, r._DNS_OTHER_TTL, '123')
repr(pointer)
def test_dns_address_repr(self):
address = r.DNSAddress('irrelevant', r._TYPE_SOA, r._CLASS_IN, 1, b'a')
repr(address)
def test_dns_question_repr(self):
question = r.DNSQuestion('irrelevant', r._TYPE_SRV, r._CLASS_IN | r._CLASS_UNIQUE)
repr(question)
assert not question != question
def test_dns_service_repr(self):
service = r.DNSService('irrelevant', r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL, 0, 0, 80, 'a')
repr(service)
def test_dns_record_abc(self):
record = r.DNSRecord('irrelevant', r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL)
self.assertRaises(r.AbstractMethodException, record.__eq__, record)
self.assertRaises(r.AbstractMethodException, record.write, None)
def test_dns_record_reset_ttl(self):
record = r.DNSRecord('irrelevant', r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL)
time.sleep(1)
record2 = r.DNSRecord('irrelevant', r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL)
now = r.current_time_millis()
assert record.created != record2.created
assert record.get_remaining_ttl(now) != record2.get_remaining_ttl(now)
record.reset_ttl(record2)
assert record.ttl == record2.ttl
assert record.created == record2.created
assert record.get_remaining_ttl(now) == record2.get_remaining_ttl(now)
def test_service_info_dunder(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
info = ServiceInfo(
type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, b'', "ash-2.local."
)
assert not info != info
repr(info)
def test_service_info_text_properties_not_given(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
info = ServiceInfo(
type_=type_,
name=registration_name,
address=socket.inet_aton("10.0.1.2"),
port=80,
server="ash-2.local.",
)
assert isinstance(info.text, bytes)
repr(info)
def test_dns_outgoing_repr(self):
dns_outgoing = r.DNSOutgoing(r._FLAGS_QR_QUERY)
repr(dns_outgoing)
class PacketGeneration(unittest.TestCase):
def test_parse_own_packet_simple(self):
generated = r.DNSOutgoing(0)
r.DNSIncoming(generated.packet())
def test_parse_own_packet_simple_unicast(self):
generated = r.DNSOutgoing(0, False)
r.DNSIncoming(generated.packet())
def test_parse_own_packet_flags(self):
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
r.DNSIncoming(generated.packet())
def test_parse_own_packet_question(self):
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
generated.add_question(r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN))
r.DNSIncoming(generated.packet())
def test_parse_own_packet_response(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
generated.add_answer_at_time(
r.DNSService("æøå.local.", r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL, 0, 0, 80, "foo.local."), 0
)
parsed = r.DNSIncoming(generated.packet())
self.assertEqual(len(generated.answers), 1)
self.assertEqual(len(generated.answers), len(parsed.answers))
def test_match_question(self):
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
generated.add_question(question)
parsed = r.DNSIncoming(generated.packet())
self.assertEqual(len(generated.questions), 1)
self.assertEqual(len(generated.questions), len(parsed.questions))
self.assertEqual(question, parsed.questions[0])
def test_suppress_answer(self):
query_generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
query_generated.add_question(question)
answer1 = r.DNSService(
"testname1.local.", r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL, 0, 0, 80, "foo.local."
)
staleanswer2 = r.DNSService(
"testname2.local.", r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL / 2, 0, 0, 80, "foo.local."
)
answer2 = r.DNSService(
"testname2.local.", r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL, 0, 0, 80, "foo.local."
)
query_generated.add_answer_at_time(answer1, 0)
query_generated.add_answer_at_time(staleanswer2, 0)
query = r.DNSIncoming(query_generated.packet())
# Should be suppressed
response = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
response.add_answer(query, answer1)
assert len(response.answers) == 0
# Should not be suppressed, TTL in query is too short
response.add_answer(query, answer2)
assert len(response.answers) == 1
# Should not be suppressed, name is different
tmp = copy.copy(answer1)
tmp.name = "testname3.local."
response.add_answer(query, tmp)
assert len(response.answers) == 2
# Should not be suppressed, type is different
tmp = copy.copy(answer1)
tmp.type = r._TYPE_A
response.add_answer(query, tmp)
assert len(response.answers) == 3
# Should not be suppressed, class is different
tmp = copy.copy(answer1)
tmp.class_ = r._CLASS_NONE
response.add_answer(query, tmp)
assert len(response.answers) == 4
# ::TODO:: could add additional tests for DNSAddress, DNSHinfo, DNSPointer, DNSText, DNSService
def test_dns_hinfo(self):
generated = r.DNSOutgoing(0)
generated.add_additional_answer(DNSHinfo('irrelevant', r._TYPE_HINFO, 0, 0, 'cpu', 'os'))
parsed = r.DNSIncoming(generated.packet())
answer = cast(r.DNSHinfo, parsed.answers[0])
self.assertEqual(answer.cpu, u'cpu')
self.assertEqual(answer.os, u'os')
generated = r.DNSOutgoing(0)
generated.add_additional_answer(DNSHinfo('irrelevant', r._TYPE_HINFO, 0, 0, 'cpu', 'x' * 257))
self.assertRaises(r.NamePartTooLongException, generated.packet)
class PacketForm(unittest.TestCase):
def test_transaction_id(self):
"""ID must be zero in a DNS-SD packet"""
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
bytes = generated.packet()
id = bytes[0] << 8 | bytes[1]
self.assertEqual(id, 0)
def test_query_header_bits(self):
generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
bytes = generated.packet()
flags = bytes[2] << 8 | bytes[3]
self.assertEqual(flags, 0x0)
def test_response_header_bits(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
bytes = generated.packet()
flags = bytes[2] << 8 | bytes[3]
self.assertEqual(flags, 0x8000)
def test_numbers(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
bytes = generated.packet()
(num_questions, num_answers, num_authorities, num_additionals) = struct.unpack('!4H', bytes[4:12])
self.assertEqual(num_questions, 0)
self.assertEqual(num_answers, 0)
self.assertEqual(num_authorities, 0)
self.assertEqual(num_additionals, 0)
def test_numbers_questions(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
for i in range(10):
generated.add_question(question)
bytes = generated.packet()
(num_questions, num_answers, num_authorities, num_additionals) = struct.unpack('!4H', bytes[4:12])
self.assertEqual(num_questions, 10)
self.assertEqual(num_answers, 0)
self.assertEqual(num_authorities, 0)
self.assertEqual(num_additionals, 0)
class Names(unittest.TestCase):
def test_long_name(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
question = r.DNSQuestion(
"this.is.a.very.long.name.with.lots.of.parts.in.it.local.", r._TYPE_SRV, r._CLASS_IN
)
generated.add_question(question)
r.DNSIncoming(generated.packet())
def test_exceedingly_long_name(self):
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
name = "%slocal." % ("part." * 1000)
question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
generated.add_question(question)
r.DNSIncoming(generated.packet())
def test_exceedingly_long_name_part(self):
name = "%s.local." % ("a" * 1000)
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
generated.add_question(question)
self.assertRaises(r.NamePartTooLongException, generated.packet)
def test_same_name(self):
name = "paired.local."
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
generated.add_question(question)
generated.add_question(question)
r.DNSIncoming(generated.packet())
def test_lots_of_names(self):
# instantiate a zeroconf instance
zc = Zeroconf(interfaces=['127.0.0.1'])
# create a bunch of servers
type_ = "_my-service._tcp.local."
name = 'a wonderful service'
server_count = 300
self.generate_many_hosts(zc, type_, name, server_count)
# verify that name changing works
self.verify_name_change(zc, type_, name, server_count)
# we are going to monkey patch the zeroconf send to check packet sizes
old_send = zc.send
longest_packet_len = 0
longest_packet = None # type: Optional[r.DNSOutgoing]
def send(out, addr=r._MDNS_ADDR, port=r._MDNS_PORT):
"""Sends an outgoing packet."""
packet = out.packet()
nonlocal longest_packet_len, longest_packet
if longest_packet_len < len(packet):
longest_packet_len = len(packet)
longest_packet = out
old_send(out, addr=addr, port=port)
# monkey patch the zeroconf send
setattr(zc, "send", send)
# dummy service callback
def on_service_state_change(zeroconf, service_type, state_change, name):
pass
# start a browser
browser = ServiceBrowser(zc, type_, [on_service_state_change])
# wait until the browse request packet has maxed out in size
sleep_count = 0
while sleep_count < 100 and longest_packet_len < r._MAX_MSG_ABSOLUTE - 100:
sleep_count += 1
time.sleep(0.1)
browser.cancel()
time.sleep(0.5)
import zeroconf
zeroconf.log.debug('sleep_count %d, sized %d', sleep_count, longest_packet_len)
# now the browser has sent at least one request, verify the size
assert longest_packet_len <= r._MAX_MSG_ABSOLUTE
assert longest_packet_len >= r._MAX_MSG_ABSOLUTE - 100
# mock zeroconf's logger warning() and debug()
from unittest.mock import patch
patch_warn = patch('zeroconf.log.warning')
patch_debug = patch('zeroconf.log.debug')
mocked_log_warn = patch_warn.start()
mocked_log_debug = patch_debug.start()
# now that we have a long packet in our possession, let's verify the
# exception handling.
out = longest_packet
assert out is not None
out.data.append(b'\0' * 1000)
# mock the zeroconf logger and check for the correct logging backoff
call_counts = mocked_log_warn.call_count, mocked_log_debug.call_count
# try to send an oversized packet
zc.send(out)
assert mocked_log_warn.call_count == call_counts[0] + 1
assert mocked_log_debug.call_count == call_counts[0]
zc.send(out)
assert mocked_log_warn.call_count == call_counts[0] + 1
assert mocked_log_debug.call_count == call_counts[0] + 1
# force a receive of an oversized packet
packet = out.packet()
s = zc._respond_sockets[0]
# mock the zeroconf logger and check for the correct logging backoff
call_counts = mocked_log_warn.call_count, mocked_log_debug.call_count
# force receive on oversized packet
s.sendto(packet, 0, (r._MDNS_ADDR, r._MDNS_PORT))
s.sendto(packet, 0, (r._MDNS_ADDR, r._MDNS_PORT))
time.sleep(2.0)
zeroconf.log.debug(
'warn %d debug %d was %s', mocked_log_warn.call_count, mocked_log_debug.call_count, call_counts
)
assert mocked_log_debug.call_count > call_counts[0]
# close our zeroconf which will close the sockets
zc.close()
# pop the big chunk off the end of the data and send on a closed socket
out.data.pop()
zc._GLOBAL_DONE = False
# mock the zeroconf logger and check for the correct logging backoff
call_counts = mocked_log_warn.call_count, mocked_log_debug.call_count
# send on a closed socket (force a socket error)
zc.send(out)
zeroconf.log.debug(
'warn %d debug %d was %s', mocked_log_warn.call_count, mocked_log_debug.call_count, call_counts
)
assert mocked_log_warn.call_count > call_counts[0]
assert mocked_log_debug.call_count > call_counts[0]
zc.send(out)
zeroconf.log.debug(
'warn %d debug %d was %s', mocked_log_warn.call_count, mocked_log_debug.call_count, call_counts
)
assert mocked_log_debug.call_count > call_counts[0] + 2
mocked_log_warn.stop()
mocked_log_debug.stop()
def verify_name_change(self, zc, type_, name, number_hosts):
desc = {'path': '/~paulsm/'}
info_service = ServiceInfo(
type_, '%s.%s' % (name, type_), socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
# verify name conflict
self.assertRaises(r.NonUniqueNameException, zc.register_service, info_service)
zc.register_service(info_service, allow_name_change=True)
assert info_service.name.split('.')[0] == '%s-%d' % (name, number_hosts + 1)
def generate_many_hosts(self, zc, type_, name, number_hosts):
records_per_server = 2
block_size = 25
number_hosts = int(((number_hosts - 1) / block_size + 1)) * block_size
for i in range(1, number_hosts + 1):
next_name = name if i == 1 else '%s-%d' % (name, i)
self.generate_host(zc, next_name, type_)
if i % block_size == 0:
sleep_count = 0
while sleep_count < 40 and i * records_per_server > len(zc.cache.entries_with_name(type_)):
sleep_count += 1
time.sleep(0.05)
@staticmethod
def generate_host(zc, host_name, type_):
name = '.'.join((host_name, type_))
out = r.DNSOutgoing(r._FLAGS_QR_RESPONSE | r._FLAGS_AA)
out.add_answer_at_time(r.DNSPointer(type_, r._TYPE_PTR, r._CLASS_IN, r._DNS_OTHER_TTL, name), 0)
out.add_answer_at_time(
r.DNSService(type_, r._TYPE_SRV, r._CLASS_IN, r._DNS_HOST_TTL, 0, 0, 80, name), 0
)
zc.send(out)
class Framework(unittest.TestCase):
def test_launch_and_close(self):
rv = r.Zeroconf(interfaces=r.InterfaceChoice.All)
rv.close()
rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default)
rv.close()
@unittest.skipIf(not socket.has_ipv6, 'Requires IPv6')
@attr('IPv6')
def test_launch_and_close_v4_v6(self):
rv = r.Zeroconf(interfaces=r.InterfaceChoice.All, ip_version=r.IPVersion.All)
rv.close()
rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default, ip_version=r.IPVersion.All)
rv.close()
@unittest.skipIf(not socket.has_ipv6, 'Requires IPv6')
@attr('IPv6')
def test_launch_and_close_v6_only(self):
rv = r.Zeroconf(interfaces=r.InterfaceChoice.All, ip_version=r.IPVersion.V6Only)
rv.close()
rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default, ip_version=r.IPVersion.V6Only)
rv.close()
def test_handle_response(self):
def mock_incoming_msg(service_state_change: r.ServiceStateChange) -> r.DNSIncoming:
ttl = 120
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
if service_state_change == r.ServiceStateChange.Updated:
generated.add_answer_at_time(
r.DNSText(service_name, r._TYPE_TXT, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_text), 0
)
return r.DNSIncoming(generated.packet())
if service_state_change == r.ServiceStateChange.Removed:
ttl = 0
generated.add_answer_at_time(
r.DNSPointer(service_type, r._TYPE_PTR, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_name), 0
)
generated.add_answer_at_time(
r.DNSService(
service_name, r._TYPE_SRV, r._CLASS_IN | r._CLASS_UNIQUE, ttl, 0, 0, 80, service_server
),
0,
)
generated.add_answer_at_time(
r.DNSText(service_name, r._TYPE_TXT, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_text), 0
)
generated.add_answer_at_time(
r.DNSAddress(
service_server,
r._TYPE_A,
r._CLASS_IN | r._CLASS_UNIQUE,
ttl,
socket.inet_aton(service_address),
),
0,
)
return r.DNSIncoming(generated.packet())
service_name = 'name._type._tcp.local.'
service_type = '_type._tcp.local.'
service_server = 'ash-2.local.'
service_text = b'path=/~paulsm/'
service_address = '10.0.1.2'
zeroconf = r.Zeroconf(interfaces=['127.0.0.1'])
try:
# service added
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Added))
dns_text = zeroconf.cache.get_by_details(service_name, r._TYPE_TXT, r._CLASS_IN)
assert dns_text is not None
assert cast(DNSText, dns_text).text == service_text # service_text is b'path=/~paulsm/'
# https://tools.ietf.org/html/rfc6762#section-10.2
# Instead of merging this new record additively into the cache in addition
# to any previous records with the same name, rrtype, and rrclass,
# all old records with that name, rrtype, and rrclass that were received
# more than one second ago are declared invalid,
# and marked to expire from the cache in one second.
time.sleep(1.1)
# service updated. currently only text record can be updated
service_text = b'path=/~humingchun/'
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Updated))
dns_text = zeroconf.cache.get_by_details(service_name, r._TYPE_TXT, r._CLASS_IN)
assert dns_text is not None
assert cast(DNSText, dns_text).text == service_text # service_text is b'path=/~humingchun/'
time.sleep(1.1)
# service removed
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Removed))
dns_text = zeroconf.cache.get_by_details(service_name, r._TYPE_TXT, r._CLASS_IN)
assert dns_text is None
finally:
zeroconf.close()
class Exceptions(unittest.TestCase):
browser = None # type: Zeroconf
@classmethod
def setUpClass(cls):
cls.browser = Zeroconf(interfaces=['127.0.0.1'])
@classmethod
def tearDownClass(cls):
cls.browser.close()
del cls.browser
def test_bad_service_info_name(self):
self.assertRaises(r.BadTypeInNameException, self.browser.get_service_info, "type", "type_not")
def test_bad_service_names(self):
bad_names_to_try = (
'',
'local',
'_tcp.local.',
'_udp.local.',
'._udp.local.',
'_@._tcp.local.',
'_A@._tcp.local.',
'_x--x._tcp.local.',
'_-x._udp.local.',
'_x-._tcp.local.',
'_22._udp.local.',
'_2-2._tcp.local.',
'_1234567890-abcde._udp.local.',
'\x00._x._udp.local.',
)
for name in bad_names_to_try:
self.assertRaises(r.BadTypeInNameException, self.browser.get_service_info, name, 'x.' + name)
def test_good_instance_names(self):
good_names_to_try = (
'.._x._tcp.local.',
'x.sub._http._tcp.local.',
'6d86f882b90facee9170ad3439d72a4d6ee9f511._zget._http._tcp.local.',
)
for name in good_names_to_try:
r.service_type_name(name)
def test_bad_types(self):
bad_names_to_try = (
'._x._tcp.local.',
'a' * 64 + '._sub._http._tcp.local.',
'a' * 62 + u'â._sub._http._tcp.local.',
)
for name in bad_names_to_try:
self.assertRaises(r.BadTypeInNameException, r.service_type_name, name)
def test_bad_sub_types(self):
bad_names_to_try = (
'_sub._http._tcp.local.',
'._sub._http._tcp.local.',
'\x7f._sub._http._tcp.local.',
'\x1f._sub._http._tcp.local.',
)
for name in bad_names_to_try:
self.assertRaises(r.BadTypeInNameException, r.service_type_name, name)
def test_good_service_names(self):
good_names_to_try = (
'_x._tcp.local.',
'_x._udp.local.',
'_12345-67890-abc._udp.local.',
'x._sub._http._tcp.local.',
'a' * 63 + '._sub._http._tcp.local.',
'a' * 61 + u'â._sub._http._tcp.local.',
)
for name in good_names_to_try:
r.service_type_name(name)
r.service_type_name('_one_two._tcp.local.', allow_underscores=True)
def test_invalid_addresses(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
bad = ('127.0.0.1', '::1', 42)
for addr in bad:
self.assertRaisesRegex(
TypeError,
'Addresses must be bytes',
ServiceInfo,
type_,
registration_name,
port=80,
addresses=[addr],
)
class TestDnsIncoming(unittest.TestCase):
def test_incoming_exception_handling(self):
generated = r.DNSOutgoing(0)
packet = generated.packet()
packet = packet[:8] + b'deadbeef' + packet[8:]
parsed = r.DNSIncoming(packet)
parsed = r.DNSIncoming(packet)
assert parsed.valid is False
def test_incoming_unknown_type(self):
generated = r.DNSOutgoing(0)
answer = r.DNSAddress('a', r._TYPE_SOA, r._CLASS_IN, 1, b'a')
generated.add_additional_answer(answer)
packet = generated.packet()
parsed = r.DNSIncoming(packet)
assert len(parsed.answers) == 0
assert parsed.is_query() != parsed.is_response()
def test_incoming_ipv6(self):
addr = "2606:2800:220:1:248:1893:25c8:1946" # example.com
packed = socket.inet_pton(socket.AF_INET6, addr)
generated = r.DNSOutgoing(0)
answer = r.DNSAddress('domain', r._TYPE_AAAA, r._CLASS_IN, 1, packed)
generated.add_additional_answer(answer)
packet = generated.packet()
parsed = r.DNSIncoming(packet)
record = parsed.answers[0]
assert isinstance(record, r.DNSAddress)
assert record.address == packed
class TestRegistrar(unittest.TestCase):
def test_ttl(self):
# instantiate a zeroconf instance
zc = Zeroconf(interfaces=['127.0.0.1'])
# service definition
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
# we are going to monkey patch the zeroconf send to check packet sizes
old_send = zc.send
nbr_answers = nbr_additionals = nbr_authorities = 0
def get_ttl(record_type):
if expected_ttl is not None:
return expected_ttl
elif record_type in [r._TYPE_A, r._TYPE_SRV]:
return r._DNS_HOST_TTL
else:
return r._DNS_OTHER_TTL
def send(out, addr=r._MDNS_ADDR, port=r._MDNS_PORT):
"""Sends an outgoing packet."""
nonlocal nbr_answers, nbr_additionals, nbr_authorities
for answer, time_ in out.answers:
nbr_answers += 1
assert answer.ttl == get_ttl(answer.type)
for answer in out.additionals:
nbr_additionals += 1
assert answer.ttl == get_ttl(answer.type)
for answer in out.authorities:
nbr_authorities += 1
assert answer.ttl == get_ttl(answer.type)
old_send(out, addr=addr, port=port)
# monkey patch the zeroconf send
setattr(zc, "send", send)
# register service with default TTL
expected_ttl = None
zc.register_service(info)
assert nbr_answers == 12 and nbr_additionals == 0 and nbr_authorities == 3
nbr_answers = nbr_additionals = nbr_authorities = 0
# query
query = r.DNSOutgoing(r._FLAGS_QR_QUERY | r._FLAGS_AA)
query.add_question(r.DNSQuestion(info.type, r._TYPE_PTR, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.name, r._TYPE_SRV, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.name, r._TYPE_TXT, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.server, r._TYPE_A, r._CLASS_IN))
zc.handle_query(r.DNSIncoming(query.packet()), r._MDNS_ADDR, r._MDNS_PORT)
assert nbr_answers == 4 and nbr_additionals == 4 and nbr_authorities == 0
nbr_answers = nbr_additionals = nbr_authorities = 0
# unregister
expected_ttl = 0
zc.unregister_service(info)
assert nbr_answers == 12 and nbr_additionals == 0 and nbr_authorities == 0
nbr_answers = nbr_additionals = nbr_authorities = 0
# register service with custom TTL
expected_ttl = r._DNS_HOST_TTL * 2
assert expected_ttl != r._DNS_HOST_TTL
zc.register_service(info, ttl=expected_ttl)
assert nbr_answers == 12 and nbr_additionals == 0 and nbr_authorities == 3
nbr_answers = nbr_additionals = nbr_authorities = 0
# query
query = r.DNSOutgoing(r._FLAGS_QR_QUERY | r._FLAGS_AA)
query.add_question(r.DNSQuestion(info.type, r._TYPE_PTR, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.name, r._TYPE_SRV, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.name, r._TYPE_TXT, r._CLASS_IN))
query.add_question(r.DNSQuestion(info.server, r._TYPE_A, r._CLASS_IN))
zc.handle_query(r.DNSIncoming(query.packet()), r._MDNS_ADDR, r._MDNS_PORT)
assert nbr_answers == 4 and nbr_additionals == 4 and nbr_authorities == 0
nbr_answers = nbr_additionals = nbr_authorities = 0
# unregister
expected_ttl = 0
zc.unregister_service(info)
assert nbr_answers == 12 and nbr_additionals == 0 and nbr_authorities == 0
nbr_answers = nbr_additionals = nbr_authorities = 0
class TestDNSCache(unittest.TestCase):
def test_order(self):
record1 = r.DNSAddress('a', r._TYPE_SOA, r._CLASS_IN, 1, b'a')
record2 = r.DNSAddress('a', r._TYPE_SOA, r._CLASS_IN, 1, b'b')
cache = r.DNSCache()
cache.add(record1)
cache.add(record2)
entry = r.DNSEntry('a', r._TYPE_SOA, r._CLASS_IN)
cached_record = cache.get(entry)
self.assertEqual(cached_record, record2)
class ServiceTypesQuery(unittest.TestCase):
def test_integration_with_listener(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=0.5)
assert type_ in service_types
service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
assert type_ in service_types
finally:
zeroconf_registrar.close()
@unittest.skipIf(not socket.has_ipv6, 'Requires IPv6')
def test_integration_with_listener_v6_records(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
addr = "2606:2800:220:1:248:1893:25c8:1946" # example.com
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name, socket.inet_pton(socket.AF_INET6, addr), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=0.5)
assert type_ in service_types
service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
assert type_ in service_types
finally:
zeroconf_registrar.close()
@unittest.skipIf(not socket.has_ipv6, 'Requires IPv6')
@attr('IPv6')
def test_integration_with_listener_ipv6(self):
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
zeroconf_registrar = Zeroconf(ip_version=r.IPVersion.V6Only)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(ip_version=r.IPVersion.V6Only, timeout=0.5)
assert type_ in service_types, service_types
service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
assert type_ in service_types, service_types
finally:
zeroconf_registrar.close()
def test_integration_with_subtype_and_listener(self):
subtype_ = "_subtype._sub"
type_ = "_type._tcp.local."
name = "xxxyyy"
# Note: discovery returns only DNS-SD type not subtype
discovery_type = "%s.%s" % (subtype_, type_)
registration_name = "%s.%s" % (name, type_)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(
discovery_type, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.register_service(info)
try:
service_types = ZeroconfServiceTypes.find(interfaces=['127.0.0.1'], timeout=0.5)
assert discovery_type in service_types
service_types = ZeroconfServiceTypes.find(zc=zeroconf_registrar, timeout=0.5)
assert discovery_type in service_types
finally:
zeroconf_registrar.close()
class ListenerTest(unittest.TestCase):
def test_integration_with_listener_class(self):
service_added = Event()
service_removed = Event()
service_updated = Event()
subtype_name = "My special Subtype"
type_ = "_http._tcp.local."
subtype = subtype_name + "._sub." + type_
name = "xxxyyyæøå"
registration_name = "%s.%s" % (name, subtype)
class MyListener(r.ServiceListener):
def add_service(self, zeroconf, type, name):
zeroconf.get_service_info(type, name)
service_added.set()
def remove_service(self, zeroconf, type, name):
service_removed.set()
def update_service(self, zeroconf, type, name):
pass
class MySubListener(r.ServiceListener):
def add_service(self, zeroconf, type, name):
pass
def remove_service(self, zeroconf, type, name):
pass
def update_service(self, zeroconf, type, name):
service_updated.set()
listener = MyListener()
zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
zeroconf_browser.add_service_listener(subtype, listener)
properties = dict(
prop_none=None,
prop_string=b'a_prop',
prop_float=1.0,
prop_blank=b'a blanked string',
prop_true=1,
prop_false=0,
)
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'} # type: Dict
desc.update(properties)
addresses = [socket.inet_aton("10.0.1.2")]
if socket.has_ipv6:
addresses.append(socket.inet_pton(socket.AF_INET6, "2001:db8::1"))
info_service = ServiceInfo(
subtype, registration_name, port=80, properties=desc, server="ash-2.local.", addresses=addresses
)
zeroconf_registrar.register_service(info_service)
try:
service_added.wait(1)
assert service_added.is_set()
# short pause to allow multicast timers to expire
time.sleep(3)
# clear the answer cache to force query
for record in zeroconf_browser.cache.entries():
zeroconf_browser.cache.remove(record)
# get service info without answer cache
info = zeroconf_browser.get_service_info(type_, registration_name)
assert info is not None
assert info.properties[b'prop_none'] is False
assert info.properties[b'prop_string'] == properties['prop_string']
assert info.properties[b'prop_float'] is False
assert info.properties[b'prop_blank'] == properties['prop_blank']
assert info.properties[b'prop_true'] is True
assert info.properties[b'prop_false'] is False
assert info.addresses == addresses[:1] # no V6 by default
all_addresses = info.addresses_by_version(r.IPVersion.All)
assert all_addresses == addresses, all_addresses
info = zeroconf_browser.get_service_info(subtype, registration_name)
assert info is not None
assert info.properties[b'prop_none'] is False
# Begin material test addition
sublistener = MySubListener()
zeroconf_browser.add_service_listener(registration_name, sublistener)
properties['prop_blank'] = b'an updated string'
desc.update(properties)
info_service = ServiceInfo(
subtype, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local."
)
zeroconf_registrar.update_service(info_service)
service_updated.wait(1)
assert service_updated.is_set()
info = zeroconf_browser.get_service_info(type_, registration_name)
assert info is not None
assert info.properties[b'prop_blank'] == properties['prop_blank']
# End material test addition
zeroconf_registrar.unregister_service(info_service)
service_removed.wait(1)
assert service_removed.is_set()
finally:
zeroconf_registrar.close()
zeroconf_browser.remove_service_listener(listener)
zeroconf_browser.close()
class TestServiceBrowser(unittest.TestCase):
def test_update_record(self):
service_name = 'name._type._tcp.local.'
service_type = '_type._tcp.local.'
service_server = 'ash-2.local.'
service_text = b'path=/~paulsm/'
service_address = '10.0.1.2'
service_added = False
service_removed = False
service_updated_count = 0
service_add_event = Event()
service_removed_event = Event()
service_updated_event = Event()
class MyServiceListener(r.ServiceListener):
def add_service(self, zc, type_, name) -> None:
nonlocal service_added
service_added = True
service_add_event.set()
def remove_service(self, zc, type_, name) -> None:
nonlocal service_added, service_removed
service_added = False
service_removed = True
service_removed_event.set()
def update_service(self, zc, type_, name) -> None:
nonlocal service_updated_count
service_updated_count += 1
service_info = zc.get_service_info(type_, name)
assert service_info.text == service_text
service_updated_event.set()
def mock_incoming_msg(service_state_change: r.ServiceStateChange) -> r.DNSIncoming:
ttl = 120
generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
if service_state_change == r.ServiceStateChange.Updated:
generated.add_answer_at_time(
r.DNSText(service_name, r._TYPE_TXT, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_text), 0
)
return r.DNSIncoming(generated.packet())
if service_state_change == r.ServiceStateChange.Removed:
ttl = 0
generated.add_answer_at_time(
r.DNSPointer(service_type, r._TYPE_PTR, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_name), 0
)
generated.add_answer_at_time(
r.DNSService(
service_name, r._TYPE_SRV, r._CLASS_IN | r._CLASS_UNIQUE, ttl, 0, 0, 80, service_server
),
0,
)
generated.add_answer_at_time(
r.DNSText(service_name, r._TYPE_TXT, r._CLASS_IN | r._CLASS_UNIQUE, ttl, service_text), 0
)
generated.add_answer_at_time(
r.DNSAddress(
service_server,
r._TYPE_A,
r._CLASS_IN | r._CLASS_UNIQUE,
ttl,
socket.inet_aton(service_address),
),
0,
)
return r.DNSIncoming(generated.packet())
zeroconf = r.Zeroconf(interfaces=['127.0.0.1'])
service_browser = r.ServiceBrowser(zeroconf, service_type, listener=MyServiceListener())
try:
# service added
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Added))
service_add_event.wait(1)
service_updated_event.wait(1)
assert service_added is True
assert service_updated_count == 1
assert service_removed is False
# service updated. currently only text record can be updated
service_updated_event.clear()
service_text = b'path=/~humingchun/'
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Updated))
service_updated_event.wait(1)
assert service_added is True
assert service_updated_count == 2
assert service_removed is False
# service removed
zeroconf.handle_response(mock_incoming_msg(r.ServiceStateChange.Removed))
service_removed_event.wait(1)
assert service_added is False
assert service_updated_count == 2
assert service_removed is True
finally:
service_browser.cancel()
zeroconf.remove_all_service_listeners()
zeroconf.close()
def test_backoff():
got_query = Event()
type_ = "_http._tcp.local."
zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
# we are going to monkey patch the zeroconf send to check query transmission
old_send = zeroconf_browser.send
time_offset = 0.0
start_time = time.time() * 1000
initial_query_interval = r._BROWSER_TIME / 1000
def current_time_millis():
"""Current system time in milliseconds"""
return start_time + time_offset * 1000
def send(out, addr=r._MDNS_ADDR, port=r._MDNS_PORT):
"""Sends an outgoing packet."""
got_query.set()
old_send(out, addr=addr, port=port)
# monkey patch the zeroconf send
setattr(zeroconf_browser, "send", send)
# monkey patch the zeroconf current_time_millis
r.current_time_millis = current_time_millis
# monkey patch the backoff limit to prevent test running forever
r._BROWSER_BACKOFF_LIMIT = 10 # seconds
# dummy service callback
def on_service_state_change(zeroconf, service_type, state_change, name):
pass
browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change])
try:
# Test that queries are sent at increasing intervals
sleep_count = 0
next_query_interval = 0.0
expected_query_time = 0.0
while True:
zeroconf_browser.notify_all()
sleep_count += 1
got_query.wait(0.1)
if time_offset == expected_query_time:
assert got_query.is_set()
got_query.clear()
if next_query_interval == r._BROWSER_BACKOFF_LIMIT:
# Only need to test up to the point where we've seen a query
# after the backoff limit has been hit
break
elif next_query_interval == 0:
next_query_interval = initial_query_interval
expected_query_time = initial_query_interval
else:
next_query_interval = min(2 * next_query_interval, r._BROWSER_BACKOFF_LIMIT)
expected_query_time += next_query_interval
else:
assert not got_query.is_set()
time_offset += initial_query_interval
finally:
browser.cancel()
zeroconf_browser.close()
def test_integration():
service_added = Event()
service_removed = Event()
unexpected_ttl = Event()
got_query = Event()
type_ = "_http._tcp.local."
registration_name = "xxxyyy.%s" % type_
def on_service_state_change(zeroconf, service_type, state_change, name):
if name == registration_name:
if state_change is ServiceStateChange.Added:
service_added.set()
elif state_change is ServiceStateChange.Removed:
service_removed.set()
zeroconf_browser = Zeroconf(interfaces=['127.0.0.1'])
# we are going to monkey patch the zeroconf send to check packet sizes
old_send = zeroconf_browser.send
time_offset = 0.0
def current_time_millis():
"""Current system time in milliseconds"""
return time.time() * 1000 + time_offset * 1000
expected_ttl = r._DNS_HOST_TTL
nbr_answers = 0
def send(out, addr=r._MDNS_ADDR, port=r._MDNS_PORT):
"""Sends an outgoing packet."""
pout = r.DNSIncoming(out.packet())
nonlocal nbr_answers
for answer in pout.answers:
nbr_answers += 1
if not answer.ttl > expected_ttl / 2:
unexpected_ttl.set()
got_query.set()
old_send(out, addr=addr, port=port)
# monkey patch the zeroconf send
setattr(zeroconf_browser, "send", send)
# monkey patch the zeroconf current_time_millis
r.current_time_millis = current_time_millis
# monkey patch the backoff limit to ensure we always get one query every 1/4 of the DNS TTL
r._BROWSER_BACKOFF_LIMIT = int(expected_ttl / 4)
service_added = Event()
service_removed = Event()
browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change])
zeroconf_registrar = Zeroconf(interfaces=['127.0.0.1'])
desc = {'path': '/~paulsm/'}
info = ServiceInfo(type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local.")
zeroconf_registrar.register_service(info)
try:
service_added.wait(1)
assert service_added.is_set()
# Test that we receive queries containing answers only if the remaining TTL
# is greater than half the original TTL
sleep_count = 0
test_iterations = 50
while nbr_answers < test_iterations:
# Increase simulated time shift by 1/4 of the TTL in seconds
time_offset += expected_ttl / 4
zeroconf_browser.notify_all()
sleep_count += 1
got_query.wait(0.1)
got_query.clear()
# Prevent the test running indefinitely in an error condition
assert sleep_count < test_iterations * 4
assert not unexpected_ttl.is_set()
# Don't remove service, allow close() to cleanup
finally:
zeroconf_registrar.close()
service_removed.wait(1)
assert service_removed.is_set()
browser.cancel()
zeroconf_browser.close()
def test_multiple_addresses():
type_ = "_http._tcp.local."
registration_name = "xxxyyy.%s" % type_
desc = {'path': '/~paulsm/'}
address_parsed = "10.0.1.2"
address = socket.inet_aton(address_parsed)
# Old way
info = ServiceInfo(type_, registration_name, address, 80, 0, 0, desc, "ash-2.local.")
assert info.address == address
assert info.addresses == [address]
# Updating works
address2 = socket.inet_aton("10.0.1.3")
info.address = address2
assert info.address == address2
assert info.addresses == [address2]
info.address = None
assert info.address is None
assert info.addresses == []
info.addresses = [address2]
assert info.address == address2
assert info.addresses == [address2]
# Compatibility way
info = ServiceInfo(type_, registration_name, [address, address], 80, 0, 0, desc, "ash-2.local.")
assert info.addresses == [address, address]
# New kwarg way
info = ServiceInfo(
type_, registration_name, None, 80, 0, 0, desc, "ash-2.local.", addresses=[address, address]
)
assert info.addresses == [address, address]
if socket.has_ipv6:
address_v6_parsed = "2001:db8::1"
address_v6 = socket.inet_pton(socket.AF_INET6, address_v6_parsed)
info = ServiceInfo(type_, registration_name, [address, address_v6], 80, 0, 0, desc, "ash-2.local.")
assert info.addresses == [address]
assert info.addresses_by_version(r.IPVersion.All) == [address, address_v6]
assert info.addresses_by_version(r.IPVersion.V4Only) == [address]
assert info.addresses_by_version(r.IPVersion.V6Only) == [address_v6]
assert info.parsed_addresses() == [address_parsed, address_v6_parsed]
assert info.parsed_addresses(r.IPVersion.V4Only) == [address_parsed]
assert info.parsed_addresses(r.IPVersion.V6Only) == [address_v6_parsed]
def test_ptr_optimization():
# instantiate a zeroconf instance
zc = Zeroconf(interfaces=['127.0.0.1'])
# service definition
type_ = "_test-srvc-type._tcp.local."
name = "xxxyyy"
registration_name = "%s.%s" % (name, type_)
desc = {'path': '/~paulsm/'}
info = ServiceInfo(type_, registration_name, socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local.")
# we are going to monkey patch the zeroconf send to check packet sizes
old_send = zc.send
nbr_answers = nbr_additionals = nbr_authorities = 0
has_srv = has_txt = has_a = False
def send(out, addr=r._MDNS_ADDR, port=r._MDNS_PORT):
"""Sends an outgoing packet."""
nonlocal nbr_answers, nbr_additionals, nbr_authorities
nonlocal has_srv, has_txt, has_a
nbr_answers += len(out.answers)
nbr_authorities += len(out.authorities)
for answer in out.additionals:
nbr_additionals += 1
if answer.type == r._TYPE_SRV:
has_srv = True
elif answer.type == r._TYPE_TXT:
has_txt = True
elif answer.type == r._TYPE_A:
has_a = True
old_send(out, addr=addr, port=port)
# monkey patch the zeroconf send
setattr(zc, "send", send)
# register
zc.register_service(info)
nbr_answers = nbr_additionals = nbr_authorities = 0
# query
query = r.DNSOutgoing(r._FLAGS_QR_QUERY | r._FLAGS_AA)
query.add_question(r.DNSQuestion(info.type, r._TYPE_PTR, r._CLASS_IN))
zc.handle_query(r.DNSIncoming(query.packet()), r._MDNS_ADDR, r._MDNS_PORT)
assert nbr_answers == 1 and nbr_additionals == 3 and nbr_authorities == 0
assert has_srv and has_txt and has_a
# unregister
zc.unregister_service(info)