diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..dc84959d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+build/
+
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 00000000..3c09140a
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,17 @@
+language: python
+python:
+ - "2.6"
+ - "2.7"
+ - "3.3"
+ - "3.4"
+ - "pypy"
+ - "pypy3"
+matrix:
+ fast_finish: true
+install:
+ - pip install -r requirements-dev.txt
+script:
+ - make test_coverage
+ - make flake8
+after_success:
+ - coveralls
diff --git a/Browser.py b/Browser.py
deleted file mode 100755
index 7347f39a..00000000
--- a/Browser.py
+++ /dev/null
@@ -1,30 +0,0 @@
-from Zeroconf import *
-import socket
-
-class MyListener(object):
- def __init__(self):
- self.r = Zeroconf()
- pass
-
- def removeService(self, zeroconf, type, name):
- print "Service", name, "removed"
-
- def addService(self, zeroconf, type, name):
- print "Service", name, "added"
- print "Type is", type
- info = self.r.getServiceInfo(type, name)
- print "Address is", str(socket.inet_ntoa(info.getAddress()))
- print "Port is", info.getPort()
- print "Weight is", info.getWeight()
- print "Priority is", info.getPriority()
- print "Server is", info.getServer()
- print "Text is", info.getText()
- print "Properties are", info.getProperties()
-
-if __name__ == '__main__':
- print "Multicast DNS Service Discovery for Python Browser test"
- r = Zeroconf()
- print "1. Testing browsing for a service..."
- type = "_http._tcp.local."
- listener = MyListener()
- browser = ServiceBrowser(r, type, listener)
diff --git a/COPYING b/COPYING
new file mode 100644
index 00000000..2cba2ac7
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,458 @@
+ 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
diff --git a/Makefile b/Makefile
new file mode 100644
index 00000000..5c3ebbbc
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,23 @@
+.PHONY: all virtualenv
+MAX_LINE_LENGTH=110
+
+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
+
+flake8:
+ flake8 --max-line-length=$(MAX_LINE_LENGTH) examples *.py
+
+test:
+ nosetests -v
+
+test_coverage:
+ nosetests -v --with-coverage --cover-package=zeroconf
+
+autopep8:
+ autopep8 --max-line-length=$(MAX_LINE_LENGTH) -i examples *.py
diff --git a/README b/README
deleted file mode 100644
index 266b1c5b..00000000
--- a/README
+++ /dev/null
@@ -1,4 +0,0 @@
-This is Multicast DNS Service Discovery for Python v0.12 by Paul Scott-Murphy.
-
-Zeroconf.py is the implementation file, look at the end for examples of
-basic use. You can also view Browser.py to see how to browse for services.
diff --git a/README.rst b/README.rst
new file mode 100644
index 00000000..bb862296
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,275 @@
+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
+
+
+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 2.6, 2.7, 3.3+
+* PyPy 2.2+ (possibly 1.9-2.1 as well)
+* PyPy3 2.4+
+
+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.
+
+
+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:
+
+.. code-block:: python
+
+ from six.moves import input
+ from zeroconf import ServiceBrowser, Zeroconf
+
+
+ class MyListener(object):
+
+ 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).
+
+See examples directory for more.
+
+Changelog
+=========
+
+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.
diff --git a/Zeroconf.py b/Zeroconf.py
deleted file mode 100755
index 8efaf033..00000000
--- a/Zeroconf.py
+++ /dev/null
@@ -1,1557 +0,0 @@
-""" Multicast DNS Service Discovery for Python, v0.12
- Copyright (C) 2003, Paul Scott-Murphy
-
- This module provides a framework for the use of DNS Service Discovery
- using IP multicast. It has been tested against the JRendezvous
- implementation from StrangeBerry,
- and against the mDNSResponder from Mac OS X 10.3.8.
-
- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""
-
-"""0.12 update - allow selection of binding interface
- typo fix - Thanks A. M. Kuchlingi
- removed all use of word 'Rendezvous' - this is an API change"""
-
-"""0.11 update - 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 update - 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 update - remove all records on service unregistration
- fix DOS security problem with readName"""
-
-"""0.08 update - changed licensing to LGPL"""
-
-"""0.07 update - faster shutdown on engine
- pointer encoding of outgoing names
- ServiceBrowser now works
- new unit tests"""
-
-"""0.06 update - small improvements with unit tests
- added defined exception types
- new style objects
- fixed hostname/interface problem
- fixed socket timeout problem
- fixed addServiceListener() typo bug
- using select() for socket reads
- tested on Debian unstable with Python 2.2.2"""
-
-"""0.05 update - ensure case insensitivty on domain names
- support for unicast DNS queries"""
-
-"""0.04 update - added some unit tests
- added __ne__ adjuncts where required
- ensure names end in '.local.'
- timeout on receiving socket for clean shutdown"""
-
-__author__ = "Paul Scott-Murphy"
-__email__ = "paul at scott dash murphy dot com"
-__version__ = "0.12"
-
-import string
-import time
-import struct
-import socket
-import threading
-import select
-import traceback
-
-__all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
-
-# hook for threads
-
-globals()['_GLOBAL_DONE'] = 0
-
-# Some timing constants
-
-_UNREGISTER_TIME = 125
-_CHECK_TIME = 175
-_REGISTER_TIME = 225
-_LISTENER_TIME = 200
-_BROWSER_TIME = 500
-
-# Some DNS constants
-
-_MDNS_ADDR = '224.0.0.251'
-_MDNS_PORT = 5353;
-_DNS_PORT = 53;
-_DNS_TTL = 60 * 60; # one hour default TTL
-
-_MAX_MSG_TYPICAL = 1460 # unused
-_MAX_MSG_ABSOLUTE = 8972
-
-_FLAGS_QR_MASK = 0x8000 # query response mask
-_FLAGS_QR_QUERY = 0x0000 # query
-_FLAGS_QR_RESPONSE = 0x8000 # response
-
-_FLAGS_AA = 0x0400 # Authorative 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" }
-
-# utility functions
-
-def currentTimeMillis():
- """Current system time in milliseconds"""
- return time.time() * 1000
-
-# Exceptions
-
-class NonLocalNameException(Exception):
- pass
-
-class NonUniqueNameException(Exception):
- pass
-
-class NamePartTooLongException(Exception):
- pass
-
-class AbstractMethodException(Exception):
- pass
-
-class BadTypeInNameException(Exception):
- pass
-
-# implementation classes
-
-class DNSEntry(object):
- """A DNS entry"""
-
- def __init__(self, name, type, clazz):
- self.key = string.lower(name)
- self.name = name
- self.type = type
- self.clazz = clazz & _CLASS_MASK
- self.unique = (clazz & _CLASS_UNIQUE) != 0
-
- def __eq__(self, other):
- """Equality test on name, type, and class"""
- if isinstance(other, DNSEntry):
- return self.name == other.name and self.type == other.type and self.clazz == other.clazz
- return 0
-
- def __ne__(self, other):
- """Non-equality test"""
- return not self.__eq__(other)
-
- def getClazz(self, clazz):
- """Class accessor"""
- try:
- return _CLASSES[clazz]
- except:
- return "?(%s)" % (clazz)
-
- def getType(self, type):
- """Type accessor"""
- try:
- return _TYPES[type]
- except:
- return "?(%s)" % (type)
-
- def toString(self, hdr, other):
- """String representation with additional information"""
- result = "%s[%s,%s" % (hdr, self.getType(self.type), self.getClazz(self.clazz))
- if self.unique:
- result += "-unique,"
- else:
- result += ","
- result += self.name
- if other is not None:
- result += ",%s]" % (other)
- else:
- result += "]"
- return result
-
-class DNSQuestion(DNSEntry):
- """A DNS question entry"""
-
- def __init__(self, name, type, clazz):
- if not name.endswith(".local."):
- raise NonLocalNameException
- DNSEntry.__init__(self, name, type, clazz)
-
- def answeredBy(self, rec):
- """Returns true if the question is answered by the record"""
- return self.clazz == rec.clazz and (self.type == rec.type or self.type == _TYPE_ANY) and self.name == rec.name
-
- def __repr__(self):
- """String representation"""
- return DNSEntry.toString(self, "question", None)
-
-
-class DNSRecord(DNSEntry):
- """A DNS record - like a DNS entry, but has a TTL"""
-
- def __init__(self, name, type, clazz, ttl):
- DNSEntry.__init__(self, name, type, clazz)
- self.ttl = ttl
- self.created = currentTimeMillis()
-
- def __eq__(self, other):
- """Tests equality as per DNSRecord"""
- if isinstance(other, DNSRecord):
- return DNSEntry.__eq__(self, other)
- return 0
-
- def suppressedBy(self, msg):
- """Returns true if any answer in a message can suffice for the
- information held in this record."""
- for record in msg.answers:
- if self.suppressedByAnswer(record):
- return 1
- return 0
-
- def suppressedByAnswer(self, other):
- """Returns true if another record has same name, type and class,
- and if its TTL is at least half of this record's."""
- if self == other and other.ttl > (self.ttl / 2):
- return 1
- return 0
-
- def getExpirationTime(self, percent):
- """Returns the time at which this record will have expired
- by a certain percentage."""
- return self.created + (percent * self.ttl * 10)
-
- def getRemainingTTL(self, now):
- """Returns the remaining TTL in seconds."""
- return max(0, (self.getExpirationTime(100) - now) / 1000)
-
- def isExpired(self, now):
- """Returns true if this record has expired."""
- return self.getExpirationTime(100) <= now
-
- def isStale(self, now):
- """Returns true if this record is at least half way expired."""
- return self.getExpirationTime(50) <= now
-
- def resetTTL(self, other):
- """Sets this record's TTL and created time to that of
- another record."""
- self.created = other.created
- self.ttl = other.ttl
-
- def write(self, out):
- """Abstract method"""
- raise AbstractMethodException
-
- def toString(self, other):
- """String representation with addtional information"""
- arg = "%s/%s,%s" % (self.ttl, self.getRemainingTTL(currentTimeMillis()), other)
- return DNSEntry.toString(self, "record", arg)
-
-class DNSAddress(DNSRecord):
- """A DNS address record"""
-
- def __init__(self, name, type, clazz, ttl, address):
- DNSRecord.__init__(self, name, type, clazz, ttl)
- self.address = address
-
- def write(self, out):
- """Used in constructing an outgoing packet"""
- out.writeString(self.address, len(self.address))
-
- def __eq__(self, other):
- """Tests equality on address"""
- if isinstance(other, DNSAddress):
- return self.address == other.address
- return 0
-
- def __repr__(self):
- """String representation"""
- try:
- return socket.inet_ntoa(self.address)
- except:
- return self.address
-
-class DNSHinfo(DNSRecord):
- """A DNS host information record"""
-
- def __init__(self, name, type, clazz, ttl, cpu, os):
- DNSRecord.__init__(self, name, type, clazz, ttl)
- self.cpu = cpu
- self.os = os
-
- def write(self, out):
- """Used in constructing an outgoing packet"""
- out.writeString(self.cpu, len(self.cpu))
- out.writeString(self.os, len(self.os))
-
- def __eq__(self, other):
- """Tests equality on cpu and os"""
- if isinstance(other, DNSHinfo):
- return self.cpu == other.cpu and self.os == other.os
- return 0
-
- def __repr__(self):
- """String representation"""
- return self.cpu + " " + self.os
-
-class DNSPointer(DNSRecord):
- """A DNS pointer record"""
-
- def __init__(self, name, type, clazz, ttl, alias):
- DNSRecord.__init__(self, name, type, clazz, ttl)
- self.alias = alias
-
- def write(self, out):
- """Used in constructing an outgoing packet"""
- out.writeName(self.alias)
-
- def __eq__(self, other):
- """Tests equality on alias"""
- if isinstance(other, DNSPointer):
- return self.alias == other.alias
- return 0
-
- def __repr__(self):
- """String representation"""
- return self.toString(self.alias)
-
-class DNSText(DNSRecord):
- """A DNS text record"""
-
- def __init__(self, name, type, clazz, ttl, text):
- DNSRecord.__init__(self, name, type, clazz, ttl)
- self.text = text
-
- def write(self, out):
- """Used in constructing an outgoing packet"""
- out.writeString(self.text, len(self.text))
-
- def __eq__(self, other):
- """Tests equality on text"""
- if isinstance(other, DNSText):
- return self.text == other.text
- return 0
-
- def __repr__(self):
- """String representation"""
- if len(self.text) > 10:
- return self.toString(self.text[:7] + "...")
- else:
- return self.toString(self.text)
-
-class DNSService(DNSRecord):
- """A DNS service record"""
-
- def __init__(self, name, type, clazz, ttl, priority, weight, port, server):
- DNSRecord.__init__(self, name, type, clazz, ttl)
- self.priority = priority
- self.weight = weight
- self.port = port
- self.server = server
-
- def write(self, out):
- """Used in constructing an outgoing packet"""
- out.writeShort(self.priority)
- out.writeShort(self.weight)
- out.writeShort(self.port)
- out.writeName(self.server)
-
- def __eq__(self, other):
- """Tests equality on priority, weight, port and server"""
- if isinstance(other, DNSService):
- return self.priority == other.priority and self.weight == other.weight and self.port == other.port and self.server == other.server
- return 0
-
- def __repr__(self):
- """String representation"""
- return self.toString("%s:%s" % (self.server, self.port))
-
-class DNSIncoming(object):
- """Object representation of an incoming DNS packet"""
-
- def __init__(self, data):
- """Constructor from string holding bytes of packet"""
- self.offset = 0
- self.data = data
- self.questions = []
- self.answers = []
- self.numQuestions = 0
- self.numAnswers = 0
- self.numAuthorities = 0
- self.numAdditionals = 0
-
- self.readHeader()
- self.readQuestions()
- self.readOthers()
-
- def readHeader(self):
- """Reads header portion of packet"""
- format = '!HHHHHH'
- length = struct.calcsize(format)
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
-
- self.id = info[0]
- self.flags = info[1]
- self.numQuestions = info[2]
- self.numAnswers = info[3]
- self.numAuthorities = info[4]
- self.numAdditionals = info[5]
-
- def readQuestions(self):
- """Reads questions section of packet"""
- format = '!HH'
- length = struct.calcsize(format)
- for i in range(0, self.numQuestions):
- name = self.readName()
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
-
- question = DNSQuestion(name, info[0], info[1])
- self.questions.append(question)
-
- def readInt(self):
- """Reads an integer from the packet"""
- format = '!I'
- length = struct.calcsize(format)
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
- return info[0]
-
- def readCharacterString(self):
- """Reads a character string from the packet"""
- length = ord(self.data[self.offset])
- self.offset += 1
- return self.readString(length)
-
- def readString(self, len):
- """Reads a string of a given length from the packet"""
- format = '!' + str(len) + 's'
- length = struct.calcsize(format)
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
- return info[0]
-
- def readUnsignedShort(self):
- """Reads an unsigned short from the packet"""
- format = '!H'
- length = struct.calcsize(format)
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
- return info[0]
-
- def readOthers(self):
- """Reads the answers, authorities and additionals section of the packet"""
- format = '!HHiH'
- length = struct.calcsize(format)
- n = self.numAnswers + self.numAuthorities + self.numAdditionals
- for i in range(0, n):
- domain = self.readName()
- info = struct.unpack(format, self.data[self.offset:self.offset+length])
- self.offset += length
-
- rec = None
- if info[0] == _TYPE_A:
- rec = DNSAddress(domain, info[0], info[1], info[2], self.readString(4))
- elif info[0] == _TYPE_CNAME or info[0] == _TYPE_PTR:
- rec = DNSPointer(domain, info[0], info[1], info[2], self.readName())
- elif info[0] == _TYPE_TXT:
- rec = DNSText(domain, info[0], info[1], info[2], self.readString(info[3]))
- elif info[0] == _TYPE_SRV:
- rec = DNSService(domain, info[0], info[1], info[2], self.readUnsignedShort(), self.readUnsignedShort(), self.readUnsignedShort(), self.readName())
- elif info[0] == _TYPE_HINFO:
- rec = DNSHinfo(domain, info[0], info[1], info[2], self.readCharacterString(), self.readCharacterString())
- elif info[0] == _TYPE_AAAA:
- rec = DNSAddress(domain, info[0], info[1], info[2], self.readString(16))
- else:
- # Try to ignore types we don't know about
- # this may mean the rest of the name is
- # unable to be parsed, and may show errors
- # so this is left for debugging. New types
- # encountered need to be parsed properly.
- #
- #print "UNKNOWN TYPE = " + str(info[0])
- #raise BadTypeInNameException
- pass
-
- if rec is not None:
- self.answers.append(rec)
-
- def isQuery(self):
- """Returns true if this is a query"""
- return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY
-
- def isResponse(self):
- """Returns true if this is a response"""
- return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE
-
- def readUTF(self, offset, len):
- """Reads a UTF-8 string of a given length from the packet"""
- result = self.data[offset:offset+len].decode('utf-8')
- return result
-
- def readName(self):
- """Reads a domain name from the packet"""
- result = ''
- off = self.offset
- next = -1
- first = off
-
- while 1:
- len = ord(self.data[off])
- off += 1
- if len == 0:
- break
- t = len & 0xC0
- if t == 0x00:
- result = ''.join((result, self.readUTF(off, len) + '.'))
- off += len
- elif t == 0xC0:
- if next < 0:
- next = off + 1
- off = ((len & 0x3F) << 8) | ord(self.data[off])
- if off >= first:
- raise "Bad domain name (circular) at " + str(off)
- first = off
- else:
- raise "Bad domain name at " + str(off)
-
- if next >= 0:
- self.offset = next
- else:
- self.offset = off
-
- return result
-
-
-class DNSOutgoing(object):
- """Object representation of an outgoing packet"""
-
- def __init__(self, flags, multicast = 1):
- self.finished = 0
- self.id = 0
- self.multicast = multicast
- self.flags = flags
- self.names = {}
- self.data = []
- self.size = 12
-
- self.questions = []
- self.answers = []
- self.authorities = []
- self.additionals = []
-
- def addQuestion(self, record):
- """Adds a question"""
- self.questions.append(record)
-
- def addAnswer(self, inp, record):
- """Adds an answer"""
- if not record.suppressedBy(inp):
- self.addAnswerAtTime(record, 0)
-
- def addAnswerAtTime(self, record, now):
- """Adds an answer if if does not expire by a certain time"""
- if record is not None:
- if now == 0 or not record.isExpired(now):
- self.answers.append((record, now))
-
- def addAuthorativeAnswer(self, record):
- """Adds an authoritative answer"""
- self.authorities.append(record)
-
- def addAdditionalAnswer(self, record):
- """Adds an additional answer"""
- self.additionals.append(record)
-
- def writeByte(self, value):
- """Writes a single byte to the packet"""
- format = '!c'
- self.data.append(struct.pack(format, chr(value)))
- self.size += 1
-
- def insertShort(self, index, value):
- """Inserts an unsigned short in a certain position in the packet"""
- format = '!H'
- self.data.insert(index, struct.pack(format, value))
- self.size += 2
-
- def writeShort(self, value):
- """Writes an unsigned short to the packet"""
- format = '!H'
- self.data.append(struct.pack(format, value))
- self.size += 2
-
- def writeInt(self, value):
- """Writes an unsigned integer to the packet"""
- format = '!I'
- self.data.append(struct.pack(format, value))
- self.size += 4
-
- def writeString(self, value, length):
- """Writes a string to the packet"""
- format = '!' + str(length) + 's'
- self.data.append(struct.pack(format, value))
- self.size += length
-
- def writeUTF(self, s):
- """Writes a UTF-8 string of a given length to the packet"""
- utfstr = s.encode('utf-8')
- length = len(utfstr)
- if length > 64:
- raise NamePartTooLongException
- self.writeByte(length)
- self.writeString(utfstr, length)
-
- def writeName(self, name):
- """Writes a domain name to the packet"""
-
- try:
- # Find existing instance of this name in packet
- #
- index = self.names[name]
- except KeyError:
- # No record of this name already, so write it
- # out as normal, recording the location of the name
- # for future pointers to it.
- #
- self.names[name] = self.size
- parts = name.split('.')
- if parts[-1] == '':
- parts = parts[:-1]
- for part in parts:
- self.writeUTF(part)
- self.writeByte(0)
- return
-
- # An index was found, so write a pointer to it
- #
- self.writeByte((index >> 8) | 0xC0)
- self.writeByte(index)
-
- def writeQuestion(self, question):
- """Writes a question to the packet"""
- self.writeName(question.name)
- self.writeShort(question.type)
- self.writeShort(question.clazz)
-
- def writeRecord(self, record, now):
- """Writes a record (answer, authoritative answer, additional) to
- the packet"""
- self.writeName(record.name)
- self.writeShort(record.type)
- if record.unique and self.multicast:
- self.writeShort(record.clazz | _CLASS_UNIQUE)
- else:
- self.writeShort(record.clazz)
- if now == 0:
- self.writeInt(record.ttl)
- else:
- self.writeInt(record.getRemainingTTL(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 = len(''.join(self.data[index:]))
- self.insertShort(index, length) # Here is the short we adjusted for
-
- def packet(self):
- """Returns a string containing the packet's bytes
-
- No further parts should be added to the packet once this
- is done."""
- if not self.finished:
- self.finished = 1
- for question in self.questions:
- self.writeQuestion(question)
- for answer, time in self.answers:
- self.writeRecord(answer, time)
- for authority in self.authorities:
- self.writeRecord(authority, 0)
- for additional in self.additionals:
- self.writeRecord(additional, 0)
-
- self.insertShort(0, len(self.additionals))
- self.insertShort(0, len(self.authorities))
- self.insertShort(0, len(self.answers))
- self.insertShort(0, len(self.questions))
- self.insertShort(0, self.flags)
- if self.multicast:
- self.insertShort(0, 0)
- else:
- self.insertShort(0, self.id)
- return ''.join(self.data)
-
-
-class DNSCache(object):
- """A cache of DNS entries"""
-
- def __init__(self):
- self.cache = {}
-
- def add(self, entry):
- """Adds an entry"""
- try:
- list = self.cache[entry.key]
- except:
- list = self.cache[entry.key] = []
- list.append(entry)
-
- def remove(self, entry):
- """Removes an entry"""
- try:
- list = self.cache[entry.key]
- list.remove(entry)
- except:
- pass
-
- def get(self, entry):
- """Gets an entry by key. Will return None if there is no
- matching entry."""
- try:
- list = self.cache[entry.key]
- return list[list.index(entry)]
- except:
- return None
-
- def getByDetails(self, name, type, clazz):
- """Gets an entry by details. Will return None if there is
- no matching entry."""
- entry = DNSEntry(name, type, clazz)
- return self.get(entry)
-
- def entriesWithName(self, name):
- """Returns a list of entries whose key matches the name."""
- try:
- return self.cache[name]
- except:
- return []
-
- def entries(self):
- """Returns a list of all entries"""
- def add(x, y): return x+y
- try:
- return reduce(add, self.cache.values())
- except:
- return []
-
-
-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, zeroconf):
- threading.Thread.__init__(self)
- self.zeroconf = zeroconf
- self.readers = {} # maps socket to reader
- self.timeout = 5
- self.condition = threading.Condition()
- self.start()
-
- def run(self):
- while not globals()['_GLOBAL_DONE']:
- rs = self.getReaders()
- if len(rs) == 0:
- # No sockets to manage, but we wait for the timeout
- # or addition of a socket
- #
- self.condition.acquire()
- self.condition.wait(self.timeout)
- self.condition.release()
- else:
- try:
- rr, wr, er = select.select(rs, [], [], self.timeout)
- for socket in rr:
- try:
- self.readers[socket].handle_read()
- except:
- # Ignore errors that occur on shutdown
- pass
- except:
- pass
-
- def getReaders(self):
- result = []
- self.condition.acquire()
- result = self.readers.keys()
- self.condition.release()
- return result
-
- def addReader(self, reader, socket):
- self.condition.acquire()
- self.readers[socket] = reader
- self.condition.notify()
- self.condition.release()
-
- def delReader(self, socket):
- self.condition.acquire()
- del(self.readers[socket])
- self.condition.notify()
- self.condition.release()
-
- def notify(self):
- self.condition.acquire()
- self.condition.notify()
- self.condition.release()
-
-class Listener(object):
- """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 availble for reading."""
-
- def __init__(self, zeroconf):
- self.zeroconf = zeroconf
- self.zeroconf.engine.addReader(self, self.zeroconf.socket)
-
- def handle_read(self):
- data, (addr, port) = self.zeroconf.socket.recvfrom(_MAX_MSG_ABSOLUTE)
- self.data = data
- msg = DNSIncoming(data)
- if msg.isQuery():
- # Always multicast responses
- #
- if port == _MDNS_PORT:
- self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT)
- # If it's not a multicast query, reply via unicast
- # and multicast
- #
- elif port == _DNS_PORT:
- self.zeroconf.handleQuery(msg, addr, port)
- self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT)
- else:
- self.zeroconf.handleResponse(msg)
-
-
-class Reaper(threading.Thread):
- """A Reaper is used by this module to remove cache entries that
- have expired."""
-
- def __init__(self, zeroconf):
- threading.Thread.__init__(self)
- self.zeroconf = zeroconf
- self.start()
-
- def run(self):
- while 1:
- self.zeroconf.wait(10 * 1000)
- if globals()['_GLOBAL_DONE']:
- return
- now = currentTimeMillis()
- for record in self.zeroconf.cache.entries():
- if record.isExpired(now):
- self.zeroconf.updateRecord(now, record)
- self.zeroconf.cache.remove(record)
-
-
-class ServiceBrowser(threading.Thread):
- """Used to browse for a service of a specific type.
-
- The listener object will have its addService() and
- removeService() methods called when this browser
- discovers changes in the services availability."""
-
- def __init__(self, zeroconf, type, listener):
- """Creates a browser for a specific type"""
- threading.Thread.__init__(self)
- self.zeroconf = zeroconf
- self.type = type
- self.listener = listener
- self.services = {}
- self.nextTime = currentTimeMillis()
- self.delay = _BROWSER_TIME
- self.list = []
-
- self.done = 0
-
- self.zeroconf.addListener(self, DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
- self.start()
-
- def updateRecord(self, zeroconf, now, record):
- """Callback invoked by Zeroconf when new information arrives.
-
- Updates information required by browser in the Zeroconf cache."""
- if record.type == _TYPE_PTR and record.name == self.type:
- expired = record.isExpired(now)
- try:
- oldrecord = self.services[record.alias.lower()]
- if not expired:
- oldrecord.resetTTL(record)
- else:
- del(self.services[record.alias.lower()])
- callback = lambda x: self.listener.removeService(x, self.type, record.alias)
- self.list.append(callback)
- return
- except:
- if not expired:
- self.services[record.alias.lower()] = record
- callback = lambda x: self.listener.addService(x, self.type, record.alias)
- self.list.append(callback)
-
- expires = record.getExpirationTime(75)
- if expires < self.nextTime:
- self.nextTime = expires
-
- def cancel(self):
- self.done = 1
- self.zeroconf.notifyAll()
-
- def run(self):
- while 1:
- event = None
- now = currentTimeMillis()
- if len(self.list) == 0 and self.nextTime > now:
- self.zeroconf.wait(self.nextTime - now)
- if globals()['_GLOBAL_DONE'] or self.done:
- return
- now = currentTimeMillis()
-
- if self.nextTime <= now:
- out = DNSOutgoing(_FLAGS_QR_QUERY)
- out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
- for record in self.services.values():
- if not record.isExpired(now):
- out.addAnswerAtTime(record, now)
- self.zeroconf.send(out)
- self.nextTime = now + self.delay
- self.delay = min(20 * 1000, self.delay * 2)
-
- if len(self.list) > 0:
- event = self.list.pop(0)
-
- if event is not None:
- event(self.zeroconf)
-
-
-class ServiceInfo(object):
- """Service information"""
-
- def __init__(self, type, name, address=None, port=None, weight=0, priority=0, properties=None, server=None):
- """Create a service description.
-
- type: fully qualified service type name
- name: fully qualified service name
- address: IP address as unsigned short, network byte order
- port: port that the service runs on
- weight: weight of the service
- priority: priority of the service
- properties: dictionary of properties (or a string holding the bytes for the text field)
- server: fully qualified name for service host (defaults to name)"""
-
- if not name.endswith(type):
- raise BadTypeInNameException
- self.type = type
- self.name = name
- self.address = address
- self.port = port
- self.weight = weight
- self.priority = priority
- if server:
- self.server = server
- else:
- self.server = name
- self.setProperties(properties)
-
- def setProperties(self, properties):
- """Sets properties and text of this info from a dictionary"""
- if isinstance(properties, dict):
- self.properties = properties
- list = []
- result = ''
- for key in properties:
- value = properties[key]
- if value is None:
- suffix = ''.encode('utf-8')
- elif isinstance(value, str):
- suffix = value.encode('utf-8')
- elif isinstance(value, int):
- if value:
- suffix = 'true'
- else:
- suffix = 'false'
- else:
- suffix = ''.encode('utf-8')
- list.append('='.join((key, suffix)))
- for item in list:
- result = ''.join((result, struct.pack('!c', chr(len(item))), item))
- self.text = result
- else:
- self.text = properties
-
- def setText(self, text):
- """Sets properties and text given a text field"""
- self.text = text
- try:
- result = {}
- end = len(text)
- index = 0
- strs = []
- while index < end:
- length = ord(text[index])
- index += 1
- strs.append(text[index:index+length])
- index += length
-
- for s in strs:
- eindex = s.find('=')
- if eindex == -1:
- # No equals sign at all
- key = s
- value = 0
- else:
- key = s[:eindex]
- value = s[eindex+1:]
- if value == 'true':
- value = 1
- elif value == 'false' or not value:
- value = 0
-
- # Only update non-existent properties
- if key and result.get(key) == None:
- result[key] = value
-
- self.properties = result
- except:
- traceback.print_exc()
- self.properties = None
-
- def getType(self):
- """Type accessor"""
- return self.type
-
- def getName(self):
- """Name accessor"""
- if self.type is not None and self.name.endswith("." + self.type):
- return self.name[:len(self.name) - len(self.type) - 1]
- return self.name
-
- def getAddress(self):
- """Address accessor"""
- return self.address
-
- def getPort(self):
- """Port accessor"""
- return self.port
-
- def getPriority(self):
- """Pirority accessor"""
- return self.priority
-
- def getWeight(self):
- """Weight accessor"""
- return self.weight
-
- def getProperties(self):
- """Properties accessor"""
- return self.properties
-
- def getText(self):
- """Text accessor"""
- return self.text
-
- def getServer(self):
- """Server accessor"""
- return self.server
-
- def updateRecord(self, zeroconf, now, record):
- """Updates service information from a DNS record"""
- if record is not None and not record.isExpired(now):
- if record.type == _TYPE_A:
- if record.name == self.name:
- self.address = record.address
- elif record.type == _TYPE_SRV:
- if record.name == self.name:
- self.server = record.server
- self.port = record.port
- self.weight = record.weight
- self.priority = record.priority
- self.address = None
- self.updateRecord(zeroconf, now, zeroconf.cache.getByDetails(self.server, _TYPE_A, _CLASS_IN))
- elif record.type == _TYPE_TXT:
- if record.name == self.name:
- self.setText(record.text)
-
- def request(self, zeroconf, timeout):
- """Returns true if the service could be discovered on the
- network, and updates this object with details discovered.
- """
- now = currentTimeMillis()
- delay = _LISTENER_TIME
- next = now + delay
- last = now + timeout
- result = 0
- try:
- zeroconf.addListener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN))
- while self.server is None or self.address is None or self.text is None:
- if last <= now:
- return 0
- if next <= now:
- out = DNSOutgoing(_FLAGS_QR_QUERY)
- out.addQuestion(DNSQuestion(self.name, _TYPE_SRV, _CLASS_IN))
- out.addAnswerAtTime(zeroconf.cache.getByDetails(self.name, _TYPE_SRV, _CLASS_IN), now)
- out.addQuestion(DNSQuestion(self.name, _TYPE_TXT, _CLASS_IN))
- out.addAnswerAtTime(zeroconf.cache.getByDetails(self.name, _TYPE_TXT, _CLASS_IN), now)
- if self.server is not None:
- out.addQuestion(DNSQuestion(self.server, _TYPE_A, _CLASS_IN))
- out.addAnswerAtTime(zeroconf.cache.getByDetails(self.server, _TYPE_A, _CLASS_IN), now)
- zeroconf.send(out)
- next = now + delay
- delay = delay * 2
-
- zeroconf.wait(min(next, last) - now)
- now = currentTimeMillis()
- result = 1
- finally:
- zeroconf.removeListener(self)
-
- return result
-
- def __eq__(self, other):
- """Tests equality of service name"""
- if isinstance(other, ServiceInfo):
- return other.name == self.name
- return 0
-
- def __ne__(self, other):
- """Non-equality test"""
- return not self.__eq__(other)
-
- def __repr__(self):
- """String representation"""
- result = "service[%s,%s:%s," % (self.name, socket.inet_ntoa(self.getAddress()), self.port)
- if self.text is None:
- result += "None"
- else:
- if len(self.text) < 20:
- result += self.text
- else:
- result += self.text[:17] + "..."
- result += "]"
- return result
-
-
-class Zeroconf(object):
- """Implementation of Zeroconf Multicast DNS Service Discovery
-
- Supports registration, unregistration, queries and browsing.
- """
- def __init__(self, bindaddress=None):
- """Creates an instance of the Zeroconf class, establishing
- multicast communications, listening and reaping threads."""
- globals()['_GLOBAL_DONE'] = 0
- if bindaddress is None:
- self.intf = socket.gethostbyname(socket.gethostname())
- else:
- self.intf = bindaddress
- self.group = ('', _MDNS_PORT)
- self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- try:
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
- except:
- # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
- # multicast UDP sockets (p 731, "TCP/IP Illustrated,
- # Volume 2"), but some BSD-derived systems require
- # SO_REUSEPORT to be specified explicity. Also, not all
- # versions of Python have SO_REUSEPORT available. So
- # if you're on a BSD-based system, and haven't upgraded
- # to Python 2.3 yet, you may find this library doesn't
- # work as expected.
- #
- pass
- self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 255)
- self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
- try:
- self.socket.bind(self.group)
- except:
- # Some versions of linux raise an exception even though
- # the SO_REUSE* options have been set, so ignore it
- #
- pass
- self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.intf) + socket.inet_aton('0.0.0.0'))
- self.socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
-
- self.listeners = []
- self.browsers = []
- self.services = {}
-
- self.cache = DNSCache()
-
- self.condition = threading.Condition()
-
- self.engine = Engine(self)
- self.listener = Listener(self)
- self.reaper = Reaper(self)
-
- def isLoopback(self):
- return self.intf.startswith("127.0.0.1")
-
- def isLinklocal(self):
- return self.intf.startswith("169.254.")
-
- def wait(self, timeout):
- """Calling thread waits for a given number of milliseconds or
- until notified."""
- self.condition.acquire()
- self.condition.wait(timeout/1000)
- self.condition.release()
-
- def notifyAll(self):
- """Notifies all waiting threads"""
- self.condition.acquire()
- self.condition.notifyAll()
- self.condition.release()
-
- def getServiceInfo(self, type, name, timeout=3000):
- """Returns network's service information for a particular
- name and type, or None if no service matches by the timeout,
- which defaults to 3 seconds."""
- info = ServiceInfo(type, name)
- if info.request(self, timeout):
- return info
- return None
-
- def addServiceListener(self, type, listener):
- """Adds a listener for a particular service type. This object
- will then have its updateRecord method called when information
- arrives for that type."""
- self.removeServiceListener(listener)
- self.browsers.append(ServiceBrowser(self, type, listener))
-
- def removeServiceListener(self, listener):
- """Removes a listener from the set that is currently listening."""
- for browser in self.browsers:
- if browser.listener == listener:
- browser.cancel()
- del(browser)
-
- def registerService(self, info, ttl=_DNS_TTL):
- """Registers service information to the network with a default TTL
- of 60 seconds. Zeroconf will then respond to requests for
- information for that service. The name of the service may be
- changed if needed to make it unique on the network."""
- self.checkService(info)
- self.services[info.name.lower()] = info
- now = currentTimeMillis()
- nextTime = now
- i = 0
- while i < 3:
- if now < nextTime:
- self.wait(nextTime - now)
- now = currentTimeMillis()
- continue
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
- out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0)
- out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, ttl, info.priority, info.weight, info.port, info.server), 0)
- out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0)
- if info.address:
- out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, ttl, info.address), 0)
- self.send(out)
- i += 1
- nextTime += _REGISTER_TIME
-
- def unregisterService(self, info):
- """Unregister a service."""
- try:
- del(self.services[info.name.lower()])
- except:
- pass
- now = currentTimeMillis()
- nextTime = now
- i = 0
- while i < 3:
- if now < nextTime:
- self.wait(nextTime - now)
- now = currentTimeMillis()
- continue
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
- out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
- out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.name), 0)
- out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
- if info.address:
- out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, info.address), 0)
- self.send(out)
- i += 1
- nextTime += _UNREGISTER_TIME
-
- def unregisterAllServices(self):
- """Unregister all registered services."""
- if len(self.services) > 0:
- now = currentTimeMillis()
- nextTime = now
- i = 0
- while i < 3:
- if now < nextTime:
- self.wait(nextTime - now)
- now = currentTimeMillis()
- continue
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
- for info in self.services.values():
- out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
- out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.server), 0)
- out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
- if info.address:
- out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, info.address), 0)
- self.send(out)
- i += 1
- nextTime += _UNREGISTER_TIME
-
- def checkService(self, info):
- """Checks the network for a unique service name, modifying the
- ServiceInfo passed in if it is not unique."""
- now = currentTimeMillis()
- nextTime = now
- i = 0
- while i < 3:
- for record in self.cache.entriesWithName(info.type):
- if record.type == _TYPE_PTR and not record.isExpired(now) and record.alias == info.name:
- if (info.name.find('.') < 0):
- info.name = info.name + ".[" + info.address + ":" + info.port + "]." + info.type
- self.checkService(info)
- return
- raise NonUniqueNameException
- if now < nextTime:
- self.wait(nextTime - now)
- now = currentTimeMillis()
- continue
- out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA)
- self.debug = out
- out.addQuestion(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN))
- out.addAuthorativeAnswer(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, info.name))
- self.send(out)
- i += 1
- nextTime += _CHECK_TIME
-
- def addListener(self, listener, question):
- """Adds a listener for a given question. The listener will have
- its updateRecord method called when information is available to
- answer the question."""
- now = currentTimeMillis()
- self.listeners.append(listener)
- if question is not None:
- for record in self.cache.entriesWithName(question.name):
- if question.answeredBy(record) and not record.isExpired(now):
- listener.updateRecord(self, now, record)
- self.notifyAll()
-
- def removeListener(self, listener):
- """Removes a listener."""
- try:
- self.listeners.remove(listener)
- self.notifyAll()
- except:
- pass
-
- def updateRecord(self, now, rec):
- """Used to notify listeners of new information that has updated
- a record."""
- for listener in self.listeners:
- listener.updateRecord(self, now, rec)
- self.notifyAll()
-
- def handleResponse(self, msg):
- """Deal with incoming response packets. All answers
- are held in the cache, and listeners are notified."""
- now = currentTimeMillis()
- for record in msg.answers:
- expired = record.isExpired(now)
- if record in self.cache.entries():
- if expired:
- self.cache.remove(record)
- else:
- entry = self.cache.get(record)
- if entry is not None:
- entry.resetTTL(record)
- record = entry
- else:
- self.cache.add(record)
-
- self.updateRecord(now, record)
-
- def handleQuery(self, msg, addr, port):
- """Deal with incoming query packets. Provides a response if
- possible."""
- out = None
-
- # Support unicast client responses
- #
- if port != _MDNS_PORT:
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, 0)
- for question in msg.questions:
- out.addQuestion(question)
-
- for question in msg.questions:
- if question.type == _TYPE_PTR:
- for service in self.services.values():
- if question.name == service.type:
- if out is None:
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
- out.addAnswer(msg, DNSPointer(service.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, service.name))
- else:
- try:
- if out is None:
- out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
-
- # Answer A record queries for any service addresses we know
- if question.type == _TYPE_A or question.type == _TYPE_ANY:
- for service in self.services.values():
- if service.server == question.name.lower():
- out.addAnswer(msg, DNSAddress(question.name, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address))
-
- service = self.services.get(question.name.lower(), None)
- if not service: continue
-
- if question.type == _TYPE_SRV or question.type == _TYPE_ANY:
- out.addAnswer(msg, DNSService(question.name, _TYPE_SRV, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.priority, service.weight, service.port, service.server))
- if question.type == _TYPE_TXT or question.type == _TYPE_ANY:
- out.addAnswer(msg, DNSText(question.name, _TYPE_TXT, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.text))
- if question.type == _TYPE_SRV:
- out.addAdditionalAnswer(DNSAddress(service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address))
- except:
- traceback.print_exc()
-
- if out is not None and out.answers:
- out.id = msg.id
- self.send(out, addr, port)
-
- def send(self, out, addr = _MDNS_ADDR, port = _MDNS_PORT):
- """Sends an outgoing packet."""
- # This is a quick test to see if we can parse the packets we generate
- #temp = DNSIncoming(out.packet())
- try:
- bytes_sent = self.socket.sendto(out.packet(), 0, (addr, port))
- except:
- # Ignore this, it may be a temporary loss of network connection
- pass
-
- def close(self):
- """Ends the background threads, and prevent this instance from
- servicing further queries."""
- if globals()['_GLOBAL_DONE'] == 0:
- globals()['_GLOBAL_DONE'] = 1
- self.notifyAll()
- self.engine.notify()
- self.unregisterAllServices()
- self.socket.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
- self.socket.close()
-
-# Test a few module features, including service registration, service
-# query (for Zoe), and service unregistration.
-
-if __name__ == '__main__':
- print "Multicast DNS Service Discovery for Python, version", __version__
- r = Zeroconf()
- print "1. Testing registration of a service..."
- desc = {'version':'0.10','a':'test value', 'b':'another value'}
- info = ServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.", socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
- print " Registering service..."
- r.registerService(info)
- print " Registration done."
- print "2. Testing query of service information..."
- print " Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))
- print " Query done."
- print "3. Testing query of own service..."
- print " Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local."))
- print " Query done."
- print "4. Testing unregister of service information..."
- r.unregisterService(info)
- print " Unregister done."
- r.close()
diff --git a/ZeroconfTest.py b/ZeroconfTest.py
deleted file mode 100755
index 4a435bd9..00000000
--- a/ZeroconfTest.py
+++ /dev/null
@@ -1,165 +0,0 @@
-""" Multicast DNS Service Discovery for Python, v0.12
- Copyright (C) 2003, Paul Scott-Murphy
-
- This module provides a unit test suite for the Multicast DNS
- Service Discovery for Python module.
-
- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""
-
-__author__ = "Paul Scott-Murphy"
-__email__ = "paul at scott dash murphy dot com"
-__version__ = "0.12"
-
-import Zeroconf as r
-import unittest
-
-
-class PacketGeneration(unittest.TestCase):
-
- def testParseOwnPacketSimple(self):
- generated = r.DNSOutgoing(0)
- parsed = r.DNSIncoming(generated.packet())
-
- def testParseOwnPacketSimpleUnicast(self):
- generated = r.DNSOutgoing(0, 0)
- parsed = r.DNSIncoming(generated.packet())
-
- def testParseOwnPacketFlags(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
- parsed = r.DNSIncoming(generated.packet())
-
- def testParseOwnPacketQuestion(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
- generated.addQuestion(r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN))
- parsed = r.DNSIncoming(generated.packet())
-
- def testMatchQuestion(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
- question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
- generated.addQuestion(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])
-
-
-class PacketForm(unittest.TestCase):
-
- def testTransactionID(self):
- """ID must be zero in a DNS-SD packet"""
- generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
- bytes = generated.packet()
- id = ord(bytes[0]) << 8 | ord(bytes[1])
- self.assertEqual(id, 0)
-
- def testQueryHeaderBits(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
- bytes = generated.packet()
- flags = ord(bytes[2]) << 8 | ord(bytes[3])
- self.assertEqual(flags, 0x0)
-
- def testResponseHeaderBits(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- bytes = generated.packet()
- flags = ord(bytes[2]) << 8 | ord(bytes[3])
- self.assertEqual(flags, 0x8000)
-
- def testNumbers(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- bytes = generated.packet()
- numQuestions = ord(bytes[4]) << 8 | ord(bytes[5])
- numAnswers = ord(bytes[6]) << 8 | ord(bytes[7])
- numAuthorities = ord(bytes[8]) << 8 | ord(bytes[9])
- numAddtionals = ord(bytes[10]) << 8 | ord(bytes[11])
- self.assertEqual(numQuestions, 0)
- self.assertEqual(numAnswers, 0)
- self.assertEqual(numAuthorities, 0)
- self.assertEqual(numAddtionals, 0)
-
- def testNumbersQuestions(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
- for i in range(0, 10):
- generated.addQuestion(question)
- bytes = generated.packet()
- numQuestions = ord(bytes[4]) << 8 | ord(bytes[5])
- numAnswers = ord(bytes[6]) << 8 | ord(bytes[7])
- numAuthorities = ord(bytes[8]) << 8 | ord(bytes[9])
- numAddtionals = ord(bytes[10]) << 8 | ord(bytes[11])
- self.assertEqual(numQuestions, 10)
- self.assertEqual(numAnswers, 0)
- self.assertEqual(numAuthorities, 0)
- self.assertEqual(numAddtionals, 0)
-
- def testNumbersAnswers(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- question = r.DNSQuestion("testname.local.", r._TYPE_SRV, r._CLASS_IN)
- for i in range(0, 10):
- generated.addQuestion(question)
- bytes = generated.packet()
- numQuestions = ord(bytes[4]) << 8 | ord(bytes[5])
- numAnswers = ord(bytes[6]) << 8 | ord(bytes[7])
- numAuthorities = ord(bytes[8]) << 8 | ord(bytes[9])
- numAddtionals = ord(bytes[10]) << 8 | ord(bytes[11])
- self.assertEqual(numQuestions, 10)
- self.assertEqual(numAnswers, 0)
- self.assertEqual(numAuthorities, 0)
- self.assertEqual(numAddtionals, 0)
-
-
-class Names(unittest.TestCase):
-
- def testNonLocalName(self):
- self.assertRaises(r.NonLocalNameException, r.DNSQuestion, "this.wont.work.com.", r._TYPE_SRV, r._CLASS_IN)
-
- def testLongName(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.addQuestion(question)
- parsed = r.DNSIncoming(generated.packet())
-
- def testExceedinglyLongName(self):
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- name = "%slocal." % ("part." * 1000)
- question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
- generated.addQuestion(question)
- parsed = r.DNSIncoming(generated.packet())
-
- def testExceedinglyLongNamePart(self):
- name = "%s.local." % ("a" * 1000)
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
- generated.addQuestion(question)
- self.assertRaises(r.NamePartTooLongException, generated.packet)
-
- def testSameName(self):
- name = "paired.local."
- generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
- question = r.DNSQuestion(name, r._TYPE_SRV, r._CLASS_IN)
- generated.addQuestion(question)
- generated.addQuestion(question)
- parsed = r.DNSIncoming(generated.packet())
-
-
-class Framework(unittest.TestCase):
-
- def testLaunchAndClose(self):
- rv = r.Zeroconf()
- rv.close()
-
-if __name__ == '__main__':
- unittest.main()
diff --git a/ZeroconfTest2.py b/ZeroconfTest2.py
deleted file mode 100755
index 2071e3d6..00000000
--- a/ZeroconfTest2.py
+++ /dev/null
@@ -1,36 +0,0 @@
-""" Multicast DNS Service Discovery for Python, v0.11
- Copyright (C) 2003, Paul Scott-Murphy
-
- This module provides a unit test suite for the Multicast DNS
- Service Discovery for Python module.
-
- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-"""
-
-__author__ = "Paul Scott-Murphy"
-__email__ = "paul at scott dash murphy dot com"
-__version__ = "0.12"
-
-from Zeroconf import *
-import socket
-
-desc = {'path':'/~paulsm/'}
-info = ServiceInfo("_http._tcp.local.", "Paul's Test Web Site._http._tcp.local.", socket.inet_aton("10.0.1.2"), 80, 0, 0, desc, "ash-2.local.")
-
-r = Zeroconf()
-print "Registration of a service..."
-r.registerService(info)
-print "Waiting..."
diff --git a/examples/browser.py b/examples/browser.py
new file mode 100755
index 00000000..633ea0e1
--- /dev/null
+++ b/examples/browser.py
@@ -0,0 +1,49 @@
+#!/usr/bin/env python
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+""" Example of browsing for a service (in this case, HTTP) """
+
+import logging
+import socket
+import sys
+from time import sleep
+
+from zeroconf import ServiceBrowser, ServiceStateChange, Zeroconf
+
+
+def on_service_state_change(zeroconf, service_type, name, state_change):
+ 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:
+ print(" Address: %s:%d" % (socket.inet_ntoa(info.address), info.port))
+ 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)
+ if len(sys.argv) > 1:
+ assert sys.argv[1:] == ['--debug']
+ logging.getLogger('zeroconf').setLevel(logging.DEBUG)
+
+ zeroconf = Zeroconf()
+ 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()
diff --git a/examples/old_browser.py b/examples/old_browser.py
new file mode 100755
index 00000000..4ad1cc13
--- /dev/null
+++ b/examples/old_browser.py
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+""" Example of browsing for a service (in this case, HTTP) """
+
+import logging
+import socket
+import sys
+from time import sleep
+
+from zeroconf import ServiceBrowser, Zeroconf
+
+
+class MyListener(object):
+
+ def remove_service(self, zeroconf, type, name):
+ print("Service %s removed" % (name,))
+ print('\n')
+
+ def add_service(self, zeroconf, type, name):
+ print("Service %s added" % (name,))
+ print(" Type is %s" % (type,))
+ info = zeroconf.get_service_info(type, name)
+ if info:
+ print(" Address is %s:%d" % (socket.inet_ntoa(info.address),
+ info.port))
+ print(" Weight is %d, Priority is %d" % (info.weight,
+ info.priority))
+ print(" Server is", info.server)
+ if info.properties:
+ print(" Properties are")
+ for key, value in info.properties.items():
+ print(" %s: %s" % (key, value))
+ else:
+ print(" No info")
+ print('\n')
+
+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()
+ print("\nBrowsing services, press Ctrl-C to exit...\n")
+ listener = MyListener()
+ browser = ServiceBrowser(zeroconf, "_http._tcp.local.", listener)
+ try:
+ while True:
+ sleep(0.1)
+ except KeyboardInterrupt:
+ pass
+ finally:
+ zeroconf.close()
diff --git a/examples/registration.py b/examples/registration.py
new file mode 100755
index 00000000..f292ea2c
--- /dev/null
+++ b/examples/registration.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python
+
+""" Example of announcing a service (in this case, a fake HTTP server) """
+
+import logging
+import socket
+import sys
+from time import sleep
+
+from zeroconf import ServiceInfo, Zeroconf
+
+if __name__ == '__main__':
+ logging.basicConfig(level=logging.DEBUG)
+ if len(sys.argv) > 1:
+ assert sys.argv[1:] == ['--debug']
+ logging.getLogger('zeroconf').setLevel(logging.DEBUG)
+
+ desc = {'path': '/~paulsm/'}
+
+ info = ServiceInfo("_http._tcp.local.",
+ "Paul's Test Web Site._http._tcp.local.",
+ socket.inet_aton("127.0.0.1"), 80, 0, 0,
+ desc, "ash-2.local.")
+
+ zeroconf = Zeroconf()
+ 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()
diff --git a/examples/self_test.py b/examples/self_test.py
new file mode 100755
index 00000000..00c022d2
--- /dev/null
+++ b/examples/self_test.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+import logging
+import socket
+import sys
+
+from zeroconf import __version__, ServiceInfo, Zeroconf
+
+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'}
+ info = ServiceInfo("_http._tcp.local.",
+ "My Service Name._http._tcp.local.",
+ socket.inet_aton("127.0.0.1"), 1234, 0, 0, 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...")
+ info = r.get_service_info("_http._tcp.local.", "My Service Name._http._tcp.local.")
+ assert info
+ print(" Getting self: %s" % (info,))
+ print(" Query done.")
+ print("4. Testing unregister of service information...")
+ r.unregister_service(info)
+ print(" Unregister done.")
+ r.close()
diff --git a/lgpl.txt b/lgpl.txt
deleted file mode 100755
index fdbedf8e..00000000
--- a/lgpl.txt
+++ /dev/null
@@ -1,151 +0,0 @@
-GNU Lesser General Public License
-
-Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 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.
-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
\ No newline at end of file
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 00000000..bc92af54
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,14 @@
+autopep8
+coveralls
+coverage
+enum34
+flake8
+flake8-blind-except
+# Upper bound because of https://github.com/public/flake8-import-order/issues/42
+flake8-import-order>=0.4.0, <0.6.0
+mock
+netifaces
+nose
+pep8==1.5.7
+pep8-naming
+six
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 00000000..51017e12
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,7 @@
+[wheel]
+universal = 1
+
+[flake8]
+show-source = 1
+import-order-style=google
+application-import-names=zeroconf
diff --git a/setup.py b/setup.py
new file mode 100755
index 00000000..54e05e1b
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,58 @@
+#!/usr/bin/env python
+from __future__ import absolute_import, division, print_function
+
+from os.path import abspath, dirname, join
+
+from setuptools import setup
+
+PROJECT_ROOT = abspath(dirname(__file__))
+with open(join(PROJECT_ROOT, 'README.rst')) as f:
+ readme = f.read()
+
+version = (
+ [l for l in open(join(PROJECT_ROOT, 'zeroconf.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',
+ py_modules=['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',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.6',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: Implementation :: CPython',
+ 'Programming Language :: Python :: Implementation :: PyPy',
+ ],
+ keywords=[
+ 'Bonjour', 'Avahi', 'Zeroconf', 'Multicast DNS', 'Service Discovery',
+ 'mDNS',
+ ],
+ install_requires=[
+ 'enum-compat',
+ 'netifaces',
+ 'six',
+ ],
+)
diff --git a/test_zeroconf.py b/test_zeroconf.py
new file mode 100644
index 00000000..ad1c00dc
--- /dev/null
+++ b/test_zeroconf.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+""" Unit tests for zeroconf.py """
+
+import logging
+import socket
+import struct
+import unittest
+from threading import Event
+
+from mock import Mock
+from six import indexbytes
+from six.moves import xrange
+
+import zeroconf as r
+from zeroconf import (
+ DNSText,
+ Listener,
+ ServiceBrowser,
+ ServiceInfo,
+ ServiceStateChange,
+ Zeroconf,
+)
+
+log = logging.getLogger('zeroconf')
+original_logging_level = [None]
+
+
+def setup_module():
+ original_logging_level[0] = log.level
+ log.setLevel(logging.DEBUG)
+
+
+def teardown_module():
+ log.setLevel(original_logging_level[0])
+
+
+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, 0)
+ 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_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])
+
+
+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 = indexbytes(bytes, 0) << 8 | indexbytes(bytes, 1)
+ self.assertEqual(id, 0)
+
+ def test_query_header_bits(self):
+ generated = r.DNSOutgoing(r._FLAGS_QR_QUERY)
+ bytes = generated.packet()
+ flags = indexbytes(bytes, 2) << 8 | indexbytes(bytes, 3)
+ self.assertEqual(flags, 0x0)
+
+ def test_response_header_bits(self):
+ generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
+ bytes = generated.packet()
+ flags = indexbytes(bytes, 2) << 8 | indexbytes(bytes, 3)
+ self.assertEqual(flags, 0x8000)
+
+ def test_numbers(self):
+ generated = r.DNSOutgoing(r._FLAGS_QR_RESPONSE)
+ bytes = generated.packet()
+ (numQuestions, numAnswers, numAuthorities,
+ numAdditionals) = struct.unpack('!4H', bytes[4:12])
+ self.assertEqual(numQuestions, 0)
+ self.assertEqual(numAnswers, 0)
+ self.assertEqual(numAuthorities, 0)
+ self.assertEqual(numAdditionals, 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 xrange(10):
+ generated.add_question(question)
+ bytes = generated.packet()
+ (numQuestions, numAnswers, numAuthorities,
+ numAdditionals) = struct.unpack('!4H', bytes[4:12])
+ self.assertEqual(numQuestions, 10)
+ self.assertEqual(numAnswers, 0)
+ self.assertEqual(numAuthorities, 0)
+ self.assertEqual(numAdditionals, 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())
+
+
+class Framework(unittest.TestCase):
+
+ def test_launch_and_close(self):
+ rv = r.Zeroconf()
+ rv.close()
+
+
+def test_integration():
+ service_added = Event()
+ service_removed = 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()
+ browser = ServiceBrowser(zeroconf_browser, type_, [on_service_state_change])
+
+ zeroconf_registrar = Zeroconf()
+ 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()
+ zeroconf_registrar.unregister_service(info)
+ service_removed.wait(1)
+ assert service_removed.is_set()
+ finally:
+ zeroconf_registrar.close()
+ browser.cancel()
+ zeroconf_browser.close()
+
+
+def test_listener_handles_closed_socket_situation_gracefully():
+ error = socket.error(socket.EBADF)
+ error.errno = socket.EBADF
+
+ zeroconf = Mock()
+ zeroconf.socket.recvfrom.side_effect = error
+
+ listener = Listener(zeroconf)
+ listener.handle_read(zeroconf.socket)
+
+
+def test_dnstext_repr_works():
+ # 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', None, 0, 0, b'12345678901')
+ repr(text)
+
+
+def test_close_waits_for_threads():
+ class Dummy(object):
+ def add_service(self, zeroconf_obj, service_type, name):
+ pass
+ def remove_service(self, zeroconf_obj, service_type, name):
+ pass
+
+ z = Zeroconf()
+ z.add_service_listener('_privet._tcp.local.', listener=Dummy())
+ z.close()
+ assert not z.browsers[0].is_alive()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/zeroconf.py b/zeroconf.py
new file mode 100644
index 00000000..4392d449
--- /dev/null
+++ b/zeroconf.py
@@ -0,0 +1,1708 @@
+from __future__ import absolute_import, division, print_function, unicode_literals
+
+""" Multicast DNS Service Discovery for Python, v0.14-wmcbrine
+ Copyright 2003 Paul Scott-Murphy, 2014 William McBrine
+
+ This module provides a framework for the use of DNS Service Discovery
+ using IP multicast.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
+ USA
+"""
+
+import enum
+import errno
+import logging
+import select
+import socket
+import struct
+import threading
+import time
+from functools import reduce
+
+import netifaces
+from six import binary_type, indexbytes, int2byte, iteritems, text_type
+from six.moves import xrange
+
+__author__ = 'Paul Scott-Murphy, William McBrine'
+__maintainer__ = 'Jakub Stasiak '
+__version__ = '0.17.4'
+__license__ = 'LGPL'
+
+
+try:
+ NullHandler = logging.NullHandler
+except AttributeError:
+ # Python 2.6 fallback
+ class NullHandler(logging.Handler):
+
+ def emit(self, record):
+ pass
+
+__all__ = [
+ "__version__",
+ "Zeroconf", "ServiceInfo", "ServiceBrowser",
+ "Error", "InterfaceChoice", "ServiceStateChange",
+]
+
+
+log = logging.getLogger(__name__)
+log.addHandler(NullHandler())
+
+if log.level == logging.NOTSET:
+ log.setLevel(logging.WARN)
+
+# hook for threads
+
+_GLOBAL_DONE = False
+
+# Some timing constants
+
+_UNREGISTER_TIME = 125
+_CHECK_TIME = 175
+_REGISTER_TIME = 225
+_LISTENER_TIME = 200
+_BROWSER_TIME = 500
+
+# Some DNS constants
+
+_MDNS_ADDR = '224.0.0.251'
+_MDNS_PORT = 5353
+_DNS_PORT = 53
+_DNS_TTL = 60 * 60 # one hour default TTL
+
+_MAX_MSG_TYPICAL = 1460 # unused
+_MAX_MSG_ABSOLUTE = 8972
+
+_FLAGS_QR_MASK = 0x8000 # query response mask
+_FLAGS_QR_QUERY = 0x0000 # query
+_FLAGS_QR_RESPONSE = 0x8000 # response
+
+_FLAGS_AA = 0x0400 # Authorative 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"}
+
+# utility functions
+
+
+def current_time_millis():
+ """Current system time in milliseconds"""
+ return time.time() * 1000
+
+# Exceptions
+
+
+class Error(Exception):
+ pass
+
+
+class NonLocalNameException(Exception):
+ pass
+
+
+class NonUniqueNameException(Exception):
+ pass
+
+
+class NamePartTooLongException(Exception):
+ pass
+
+
+class AbstractMethodException(Exception):
+ pass
+
+
+class BadTypeInNameException(Exception):
+ pass
+
+# implementation classes
+
+
+class DNSEntry(object):
+
+ """A DNS entry"""
+
+ def __init__(self, name, type, class_):
+ self.key = name.lower()
+ self.name = name
+ self.type = type
+ self.class_ = class_ & _CLASS_MASK
+ self.unique = (class_ & _CLASS_UNIQUE) != 0
+
+ def __eq__(self, other):
+ """Equality test on name, type, and class"""
+ return (isinstance(other, DNSEntry) and
+ self.name == other.name and
+ self.type == other.type and
+ self.class_ == other.class_)
+
+ def __ne__(self, other):
+ """Non-equality test"""
+ return not self.__eq__(other)
+
+ def get_class_(self, class_):
+ """Class accessor"""
+ return _CLASSES.get(class_, "?(%s)" % class_)
+
+ def get_type(self, t):
+ """Type accessor"""
+ return _TYPES.get(t, "?(%s)" % t)
+
+ def to_string(self, hdr, other):
+ """String representation with additional information"""
+ result = "%s[%s,%s" % (hdr, self.get_type(self.type),
+ self.get_class_(self.class_))
+ if self.unique:
+ result += "-unique,"
+ else:
+ result += ","
+ result += self.name
+ if other is not None:
+ result += ",%s]" % (other)
+ else:
+ result += "]"
+ return result
+
+
+class DNSQuestion(DNSEntry):
+
+ """A DNS question entry"""
+
+ def __init__(self, name, type, class_):
+ # if not name.endswith(".local."):
+ # raise NonLocalNameException
+ DNSEntry.__init__(self, name, type, class_)
+
+ def answered_by(self, rec):
+ """Returns true if the question is answered by the record"""
+ return (self.class_ == rec.class_ and
+ (self.type == rec.type or self.type == _TYPE_ANY) and
+ self.name == rec.name)
+
+ def __repr__(self):
+ """String representation"""
+ return DNSEntry.to_string(self, "question", None)
+
+
+class DNSRecord(DNSEntry):
+
+ """A DNS record - like a DNS entry, but has a TTL"""
+
+ def __init__(self, name, type, class_, ttl):
+ DNSEntry.__init__(self, name, type, class_)
+ self.ttl = ttl
+ self.created = current_time_millis()
+
+ def __eq__(self, other):
+ """Tests equality as per DNSRecord"""
+ return isinstance(other, DNSRecord) and DNSEntry.__eq__(self, other)
+
+ def suppressed_by(self, msg):
+ """Returns true if any answer in a message can suffice for the
+ information held in this record."""
+ for record in msg.answers:
+ if self.suppressed_by_answer(record):
+ return True
+ return False
+
+ def suppressed_by_answer(self, other):
+ """Returns true if another record has same name, type and class,
+ and if its TTL is at least half of this record's."""
+ return self == other and other.ttl > (self.ttl / 2)
+
+ def get_expiration_time(self, percent):
+ """Returns the time at which this record will have expired
+ by a certain percentage."""
+ return self.created + (percent * self.ttl * 10)
+
+ def get_remaining_ttl(self, now):
+ """Returns the remaining TTL in seconds."""
+ return max(0, (self.get_expiration_time(100) - now) / 1000)
+
+ def is_expired(self, now):
+ """Returns true if this record has expired."""
+ return self.get_expiration_time(100) <= now
+
+ def is_stale(self, now):
+ """Returns true if this record is at least half way expired."""
+ return self.get_expiration_time(50) <= now
+
+ def reset_ttl(self, other):
+ """Sets this record's TTL and created time to that of
+ another record."""
+ self.created = other.created
+ self.ttl = other.ttl
+
+ def write(self, out):
+ """Abstract method"""
+ raise AbstractMethodException
+
+ def to_string(self, other):
+ """String representation with addtional information"""
+ arg = "%s/%s,%s" % (self.ttl,
+ self.get_remaining_ttl(current_time_millis()), other)
+ return DNSEntry.to_string(self, "record", arg)
+
+
+class DNSAddress(DNSRecord):
+
+ """A DNS address record"""
+
+ def __init__(self, name, type, class_, ttl, address):
+ DNSRecord.__init__(self, name, type, class_, ttl)
+ self.address = address
+
+ def write(self, out):
+ """Used in constructing an outgoing packet"""
+ out.write_string(self.address)
+
+ def __eq__(self, other):
+ """Tests equality on address"""
+ return isinstance(other, DNSAddress) and self.address == other.address
+
+ def __repr__(self):
+ """String representation"""
+ try:
+ return socket.inet_ntoa(self.address)
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+ return self.address
+
+
+class DNSHinfo(DNSRecord):
+
+ """A DNS host information record"""
+
+ def __init__(self, name, type, class_, ttl, cpu, os):
+ DNSRecord.__init__(self, name, type, class_, ttl)
+ self.cpu = cpu
+ self.os = os
+
+ def write(self, out):
+ """Used in constructing an outgoing packet"""
+ out.write_string(self.cpu)
+ out.write_string(self.oso)
+
+ def __eq__(self, other):
+ """Tests equality on cpu and os"""
+ return (isinstance(other, DNSHinfo) and
+ self.cpu == other.cpu and self.os == other.os)
+
+ def __repr__(self):
+ """String representation"""
+ return self.cpu + " " + self.os
+
+
+class DNSPointer(DNSRecord):
+
+ """A DNS pointer record"""
+
+ def __init__(self, name, type, class_, ttl, alias):
+ DNSRecord.__init__(self, name, type, class_, ttl)
+ self.alias = alias
+
+ def write(self, out):
+ """Used in constructing an outgoing packet"""
+ out.write_name(self.alias)
+
+ def __eq__(self, other):
+ """Tests equality on alias"""
+ return isinstance(other, DNSPointer) and self.alias == other.alias
+
+ def __repr__(self):
+ """String representation"""
+ return self.to_string(self.alias)
+
+
+class DNSText(DNSRecord):
+
+ """A DNS text record"""
+
+ def __init__(self, name, type_, class_, ttl, text):
+ assert isinstance(text, (bytes, type(None)))
+ DNSRecord.__init__(self, name, type_, class_, ttl)
+ self.text = text
+
+ def write(self, out):
+ """Used in constructing an outgoing packet"""
+ out.write_string(self.text)
+
+ def __eq__(self, other):
+ """Tests equality on text"""
+ return isinstance(other, DNSText) and self.text == other.text
+
+ def __repr__(self):
+ """String representation"""
+ if len(self.text) > 10:
+ return self.to_string(self.text[:7]) + "..."
+ else:
+ return self.to_string(self.text)
+
+
+class DNSService(DNSRecord):
+
+ """A DNS service record"""
+
+ def __init__(self, name, type, class_, ttl, priority, weight, port, server):
+ DNSRecord.__init__(self, name, type, class_, ttl)
+ self.priority = priority
+ self.weight = weight
+ self.port = port
+ self.server = server
+
+ def write(self, out):
+ """Used in constructing an outgoing packet"""
+ out.write_short(self.priority)
+ out.write_short(self.weight)
+ out.write_short(self.port)
+ out.write_name(self.server)
+
+ def __eq__(self, other):
+ """Tests equality on priority, weight, port and server"""
+ return (isinstance(other, DNSService) and
+ self.priority == other.priority and
+ self.weight == other.weight and
+ self.port == other.port and
+ self.server == other.server)
+
+ def __repr__(self):
+ """String representation"""
+ return self.to_string("%s:%s" % (self.server, self.port))
+
+
+class DNSIncoming(object):
+
+ """Object representation of an incoming DNS packet"""
+
+ def __init__(self, data):
+ """Constructor from string holding bytes of packet"""
+ self.offset = 0
+ self.data = data
+ self.questions = []
+ self.answers = []
+ self.num_questions = 0
+ self.num_answers = 0
+ self.num_authorities = 0
+ self.num_additionals = 0
+
+ self.read_header()
+ self.read_questions()
+ self.read_others()
+
+ def unpack(self, format):
+ length = struct.calcsize(format)
+ info = struct.unpack(format, self.data[self.offset:self.offset + length])
+ self.offset += length
+ return info
+
+ def read_header(self):
+ """Reads header portion of packet"""
+ (self.id, self.flags, self.num_questions, self.num_answers,
+ self.num_quthorities, self.num_additionals) = self.unpack(b'!6H')
+
+ def read_questions(self):
+ """Reads questions section of packet"""
+ for i in xrange(self.num_questions):
+ name = self.read_name()
+ type, class_ = self.unpack(b'!HH')
+
+ question = DNSQuestion(name, type, class_)
+ self.questions.append(question)
+
+ def read_int(self):
+ """Reads an integer from the packet"""
+ return self.unpack(b'!I')[0]
+
+ def read_character_string(self):
+ """Reads a character string from the packet"""
+ length = indexbytes(self.data, self.offset)
+ self.offset += 1
+ return self.read_string(length)
+
+ def read_string(self, length):
+ """Reads a string of a given length from the packet"""
+ info = self.data[self.offset:self.offset + length]
+ self.offset += length
+ return info
+
+ def read_unsigned_short(self):
+ """Reads an unsigned short from the packet"""
+ return self.unpack(b'!H')[0]
+
+ def read_others(self):
+ """Reads the answers, authorities and additionals section of the
+ packet"""
+ n = self.num_answers + self.num_authorities + self.num_additionals
+ for i in xrange(n):
+ domain = self.read_name()
+ type, class_, ttl, length = self.unpack(b'!HHiH')
+
+ rec = None
+ if type == _TYPE_A:
+ rec = DNSAddress(domain, type, class_, ttl, self.read_string(4))
+ elif type == _TYPE_CNAME or type == _TYPE_PTR:
+ rec = DNSPointer(domain, type, class_, ttl, self.read_name())
+ elif type == _TYPE_TXT:
+ rec = DNSText(domain, type, class_, ttl, self.read_string(length))
+ elif type == _TYPE_SRV:
+ rec = DNSService(domain, type, class_, ttl,
+ self.read_unsigned_short(), self.read_unsigned_short(),
+ self.read_unsigned_short(), self.read_name())
+ elif type == _TYPE_HINFO:
+ rec = DNSHinfo(domain, type, class_, ttl,
+ self.read_character_string(), self.read_character_string())
+ elif type == _TYPE_AAAA:
+ rec = DNSAddress(domain, type, class_, ttl, self.read_string(16))
+ else:
+ # Try to ignore types we don't know about
+ # Skip the payload for the resource record so the next
+ # records can be parsed correctly
+ self.offset += length
+
+ if rec is not None:
+ self.answers.append(rec)
+
+ def is_query(self):
+ """Returns true if this is a query"""
+ return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY
+
+ def is_response(self):
+ """Returns true if this is a response"""
+ return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE
+
+ def read_utf(self, offset, length):
+ """Reads a UTF-8 string of a given length from the packet"""
+ return text_type(self.data[offset:offset + length], 'utf-8', 'replace')
+
+ def read_name(self):
+ """Reads a domain name from the packet"""
+ result = ''
+ off = self.offset
+ next = -1
+ first = off
+
+ while True:
+ length = indexbytes(self.data, off)
+ off += 1
+ if length == 0:
+ break
+ t = length & 0xC0
+ if t == 0x00:
+ result = ''.join((result, self.read_utf(off, length) + '.'))
+ off += length
+ elif t == 0xC0:
+ if next < 0:
+ next = off + 1
+ off = ((length & 0x3F) << 8) | indexbytes(self.data, off)
+ if off >= first:
+ # TODO raise more specific exception
+ raise Exception("Bad domain name (circular) at %s" % (off,))
+ first = off
+ else:
+ # TODO raise more specific exception
+ raise Exception("Bad domain name at %s" % (off,))
+
+ if next >= 0:
+ self.offset = next
+ else:
+ self.offset = off
+
+ return result
+
+
+class DNSOutgoing(object):
+
+ """Object representation of an outgoing packet"""
+
+ def __init__(self, flags, multicast=True):
+ self.finished = False
+ self.id = 0
+ self.multicast = multicast
+ self.flags = flags
+ self.names = {}
+ self.data = []
+ self.size = 12
+
+ self.questions = []
+ self.answers = []
+ self.authorities = []
+ self.additionals = []
+
+ def add_question(self, record):
+ """Adds a question"""
+ self.questions.append(record)
+
+ def add_answer(self, inp, record):
+ """Adds an answer"""
+ if not record.suppressed_by(inp):
+ self.add_answer_at_time(record, 0)
+
+ def add_answer_at_time(self, record, now):
+ """Adds an answer if if does not expire by a certain time"""
+ if record is not None:
+ if now == 0 or not record.is_expired(now):
+ self.answers.append((record, now))
+
+ def add_authorative_answer(self, record):
+ """Adds an authoritative answer"""
+ self.authorities.append(record)
+
+ def add_additional_answer(self, record):
+ """Adds an additional answer"""
+ self.additionals.append(record)
+
+ def pack(self, format, value):
+ self.data.append(struct.pack(format, value))
+ self.size += struct.calcsize(format)
+
+ def write_byte(self, value):
+ """Writes a single byte to the packet"""
+ self.pack(b'!c', int2byte(value))
+
+ def insert_short(self, index, value):
+ """Inserts an unsigned short in a certain position in the packet"""
+ self.data.insert(index, struct.pack(b'!H', value))
+ self.size += 2
+
+ def write_short(self, value):
+ """Writes an unsigned short to the packet"""
+ self.pack(b'!H', value)
+
+ def write_int(self, value):
+ """Writes an unsigned integer to the packet"""
+ self.pack(b'!I', int(value))
+
+ def write_string(self, value):
+ """Writes a string to the packet"""
+ assert isinstance(value, bytes)
+ self.data.append(value)
+ self.size += len(value)
+
+ def write_utf(self, s):
+ """Writes a UTF-8 string of a given length to the packet"""
+ utfstr = s.encode('utf-8')
+ length = len(utfstr)
+ if length > 64:
+ raise NamePartTooLongException
+ self.write_byte(length)
+ self.write_string(utfstr)
+
+ def write_name(self, name):
+ """Writes a domain name to the packet"""
+
+ if name in self.names:
+ # Find existing instance of this name in packet
+ #
+ index = self.names[name]
+
+ # An index was found, so write a pointer to it
+ #
+ self.write_byte((index >> 8) | 0xC0)
+ self.write_byte(index & 0xFF)
+ else:
+ # No record of this name already, so write it
+ # out as normal, recording the location of the name
+ # for future pointers to it.
+ #
+ self.names[name] = self.size
+ parts = name.split('.')
+ if parts[-1] == '':
+ parts = parts[:-1]
+ for part in parts:
+ self.write_utf(part)
+ self.write_byte(0)
+
+ def write_question(self, question):
+ """Writes a question to the packet"""
+ self.write_name(question.name)
+ self.write_short(question.type)
+ self.write_short(question.class_)
+
+ def write_record(self, record, now):
+ """Writes a record (answer, authoritative answer, additional) to
+ the packet"""
+ 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 = len(b''.join(self.data[index:]))
+ self.insert_short(index, length) # Here is the short we adjusted for
+
+ def packet(self):
+ """Returns a string containing the packet's bytes
+
+ No further parts should be added to the packet once this
+ is done."""
+ if not self.finished:
+ self.finished = True
+ for question in self.questions:
+ self.write_question(question)
+ for answer, time_ in self.answers:
+ self.write_record(answer, time_)
+ for authority in self.authorities:
+ self.write_record(authority, 0)
+ for additional in self.additionals:
+ self.write_record(additional, 0)
+
+ self.insert_short(0, len(self.additionals))
+ self.insert_short(0, len(self.authorities))
+ self.insert_short(0, len(self.answers))
+ self.insert_short(0, len(self.questions))
+ self.insert_short(0, self.flags)
+ if self.multicast:
+ self.insert_short(0, 0)
+ else:
+ self.insert_short(0, self.id)
+ return b''.join(self.data)
+
+
+class DNSCache(object):
+
+ """A cache of DNS entries"""
+
+ def __init__(self):
+ self.cache = {}
+
+ def add(self, entry):
+ """Adds an entry"""
+ self.cache.setdefault(entry.key, []).append(entry)
+
+ def remove(self, entry):
+ """Removes an entry"""
+ try:
+ list_ = self.cache[entry.key]
+ list_.remove(entry)
+ except (KeyError, ValueError):
+ pass
+
+ def get(self, entry):
+ """Gets an entry by key. Will return None if there is no
+ matching entry."""
+ try:
+ list_ = self.cache[entry.key]
+ return list_[list_.index(entry)]
+ except (KeyError, ValueError):
+ return None
+
+ def get_by_details(self, name, type, class_):
+ """Gets an entry by details. Will return None if there is
+ no matching entry."""
+ entry = DNSEntry(name, type, class_)
+ return self.get(entry)
+
+ def entries_with_name(self, name):
+ """Returns a list of entries whose key matches the name."""
+ try:
+ return self.cache[name]
+ except KeyError:
+ return []
+
+ def entries(self):
+ """Returns a list of all entries"""
+ if not self.cache:
+ return []
+ else:
+ return reduce(lambda a, b: a + b, self.cache.values())
+
+
+class Engine(threading.Thread):
+
+ """An engine wraps read access to sockets, allowing objects that
+ need to receive data from sockets to be called back when the
+ sockets are ready.
+
+ A reader needs a handle_read() method, which is called when the socket
+ it is interested in is ready for reading.
+
+ Writers are not implemented here, because we only send short
+ packets.
+ """
+
+ def __init__(self, zc):
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.zc = zc
+ self.readers = {} # maps socket to reader
+ self.timeout = 5
+ self.condition = threading.Condition()
+ self.start()
+
+ def run(self):
+ while not _GLOBAL_DONE:
+ rs = self.get_readers()
+ if len(rs) == 0:
+ # No sockets to manage, but we wait for the timeout
+ # or addition of a socket
+ #
+ with self.condition:
+ self.condition.wait(self.timeout)
+ else:
+ try:
+ rr, wr, er = select.select(rs, [], [], self.timeout)
+ for socket_ in rr:
+ try:
+ self.readers[socket_].handle_read(socket_)
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+
+ def get_readers(self):
+ result = []
+ with self.condition:
+ result = self.readers.keys()
+ return result
+
+ def add_reader(self, reader, socket):
+ with self.condition:
+ self.readers[socket] = reader
+ self.condition.notify()
+
+ def del_reader(self, socket):
+ with self.condition:
+ del self.readers[socket]
+ self.condition.notify()
+
+ def notify(self):
+ with self.condition:
+ self.condition.notify()
+
+
+class Listener(object):
+
+ """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 availble for reading."""
+
+ def __init__(self, zc):
+ self.zc = zc
+
+ def handle_read(self, socket_):
+ try:
+ data, (addr, port) = socket_.recvfrom(_MAX_MSG_ABSOLUTE)
+ except socket.error as e:
+ # If the socket was closed by another thread -- which happens
+ # regularly on shutdown -- an EBADF exception is thrown here.
+ # Ignore it.
+ if e.errno == socket.EBADF:
+ return
+ else:
+ raise e
+ else:
+ log.debug('Received %r from %r:%r', data, addr, port)
+
+ self.data = data
+ msg = DNSIncoming(data)
+ if msg.is_query():
+ # Always multicast responses
+ #
+ if port == _MDNS_PORT:
+ self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT)
+ # If it's not a multicast query, reply via unicast
+ # and multicast
+ #
+ elif port == _DNS_PORT:
+ self.zc.handle_query(msg, addr, port)
+ self.zc.handle_query(msg, _MDNS_ADDR, _MDNS_PORT)
+ else:
+ self.zc.handle_response(msg)
+
+
+class Reaper(threading.Thread):
+
+ """A Reaper is used by this module to remove cache entries that
+ have expired."""
+
+ def __init__(self, zc):
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.zc = zc
+ self.start()
+
+ def run(self):
+ while True:
+ self.zc.wait(10 * 1000)
+ if _GLOBAL_DONE:
+ return
+ now = current_time_millis()
+ for record in self.zc.cache.entries():
+ if record.is_expired(now):
+ self.zc.update_record(now, record)
+ self.zc.cache.remove(record)
+
+
+class Signal(object):
+ def __init__(self):
+ self._handlers = []
+
+ def fire(self, **kwargs):
+ for h in list(self._handlers):
+ h(**kwargs)
+
+ @property
+ def registration_interface(self):
+ return SignalRegistrationInterface(self._handlers)
+
+
+class SignalRegistrationInterface(object):
+
+ def __init__(self, handlers):
+ self._handlers = handlers
+
+ def register_handler(self, handler):
+ self._handlers.append(handler)
+ return self
+
+ def unregister_handler(self, handler):
+ self._handlers.remove(handler)
+ return self
+
+
+class ServiceBrowser(threading.Thread):
+
+ """Used to browse for a service of a specific type.
+
+ The listener object will have its add_service() and
+ remove_service() methods called when this browser
+ discovers changes in the services availability."""
+
+ def __init__(self, zc, type_, handlers=None, listener=None):
+ """Creates a browser for a specific type"""
+ assert handlers or listener, 'You need to specify at least one handler'
+ threading.Thread.__init__(self)
+ self.daemon = True
+ self.zc = zc
+ self.type = type_
+ self.services = {}
+ self.next_time = current_time_millis()
+ self.delay = _BROWSER_TIME
+ self._handlers_to_call = []
+
+ self.done = False
+
+ self.zc.add_listener(self, DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
+
+ self._service_state_changed = Signal()
+
+ if hasattr(handlers, 'add_service'):
+ listener = handlers
+ handlers = None
+
+ handlers = handlers or []
+
+ if listener:
+ def on_change(zeroconf, service_type, name, state_change):
+ args = (zeroconf, service_type, name)
+ if state_change is ServiceStateChange.Added:
+ listener.add_service(*args)
+ elif state_change is ServiceStateChange.Removed:
+ listener.remove_service(*args)
+ else:
+ raise NotImplementedError(state_change)
+ handlers.append(on_change)
+
+ for h in handlers:
+ self.service_state_changed.register_handler(h)
+
+ self.start()
+
+ @property
+ def service_state_changed(self):
+ return self._service_state_changed.registration_interface
+
+ def update_record(self, zc, now, record):
+ """Callback invoked by Zeroconf when new information arrives.
+
+ Updates information required by browser in the Zeroconf cache."""
+
+ def enqueue_callback(state_change, name):
+ self._handlers_to_call.append(
+ lambda zeroconf: self._service_state_changed.fire(
+ zeroconf=zeroconf,
+ service_type=self.type,
+ name=name,
+ state_change=state_change,
+ ))
+
+ if record.type == _TYPE_PTR and record.name == self.type:
+ expired = record.is_expired(now)
+ service_key = record.alias.lower()
+ try:
+ old_record = self.services[service_key]
+ except KeyError:
+ if not expired:
+ self.services[service_key] = record
+ enqueue_callback(ServiceStateChange.Added, record.alias)
+ else:
+ if not expired:
+ old_record.reset_ttl(record)
+ else:
+ del self.services[service_key]
+ enqueue_callback(ServiceStateChange.Removed, record.alias)
+ return
+
+ expires = record.get_expiration_time(75)
+ if expires < self.next_time:
+ self.next_time = expires
+
+ def cancel(self):
+ self.done = True
+ self.zc.notify_all()
+
+ def run(self):
+ 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 _GLOBAL_DONE or self.done:
+ return
+ now = current_time_millis()
+
+ if self.next_time <= now:
+ out = DNSOutgoing(_FLAGS_QR_QUERY)
+ out.add_question(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
+ for record in self.services.values():
+ if not record.is_expired(now):
+ out.add_answer_at_time(record, now)
+ self.zc.send(out)
+ self.next_time = now + self.delay
+ self.delay = min(20 * 1000, self.delay * 2)
+
+ if len(self._handlers_to_call) > 0:
+ handler = self._handlers_to_call.pop(0)
+ handler(self.zc)
+
+
+class ServiceInfo(object):
+
+ """Service information"""
+
+ def __init__(self, type, name, address=None, port=None, weight=0,
+ priority=0, properties=None, server=None):
+ """Create a service description.
+
+ type: fully qualified service type name
+ name: fully qualified service name
+ address: IP address as unsigned short, network byte order
+ port: port that the service runs on
+ weight: weight of the service
+ priority: priority of the service
+ properties: dictionary of properties (or a string holding the
+ bytes for the text field)
+ server: fully qualified name for service host (defaults to name)"""
+
+ if not name.endswith(type):
+ raise BadTypeInNameException
+ self.type = type
+ self.name = name
+ self.address = address
+ self.port = port
+ self.weight = weight
+ self.priority = priority
+ if server:
+ self.server = server
+ else:
+ self.server = name
+ self._set_properties(properties)
+
+ @property
+ def properties(self):
+ return self._properties
+
+ def _set_properties(self, properties):
+ """Sets properties and text of this info from a dictionary"""
+ if isinstance(properties, dict):
+ self._properties = properties
+ list = []
+ result = b''
+ for key, value in iteritems(properties):
+ if isinstance(key, text_type):
+ key = key.encode('utf-8')
+
+ if value is None:
+ suffix = b''
+ elif isinstance(value, text_type):
+ suffix = value.encode('utf-8')
+ elif isinstance(value, binary_type):
+ suffix = value
+ elif isinstance(value, int):
+ if value:
+ suffix = b'true'
+ else:
+ suffix = b'false'
+ else:
+ suffix = b''
+ list.append(b'='.join((key, suffix)))
+ for item in list:
+ result = b''.join((result, int2byte(len(item)), item))
+ self.text = result
+ else:
+ self.text = properties
+
+ def _set_text(self, text):
+ """Sets properties and text given a text field"""
+ self.text = text
+ result = {}
+ end = len(text)
+ index = 0
+ strs = []
+ while index < end:
+ length = indexbytes(text, index)
+ index += 1
+ strs.append(text[index:index + length])
+ index += length
+
+ for s in strs:
+ parts = s.split(b'=', 1)
+ try:
+ key, value = parts
+ except ValueError:
+ # No equals sign at all
+ key = s
+ value = False
+ else:
+ if value == b'true':
+ value = True
+ elif value == b'false' or not value:
+ value = False
+
+ # Only update non-existent properties
+ if key and result.get(key) is None:
+ result[key] = value
+
+ self._properties = result
+
+ def get_name(self):
+ """Name accessor"""
+ if self.type is not None and self.name.endswith("." + self.type):
+ return self.name[:len(self.name) - len(self.type) - 1]
+ return self.name
+
+ def update_record(self, zc, now, record):
+ """Updates service information from a DNS record"""
+ if record is not None and not record.is_expired(now):
+ if record.type == _TYPE_A:
+ # if record.name == self.name:
+ if record.name == self.server:
+ self.address = record.address
+ elif record.type == _TYPE_SRV:
+ if record.name == self.name:
+ self.server = record.server
+ self.port = record.port
+ self.weight = record.weight
+ self.priority = record.priority
+ # self.address = None
+ self.update_record(zc, now,
+ zc.cache.get_by_details(self.server, _TYPE_A, _CLASS_IN))
+ elif record.type == _TYPE_TXT:
+ if record.name == self.name:
+ self._set_text(record.text)
+
+ def request(self, zc, timeout):
+ """Returns true if the service could be discovered on the
+ network, and updates this object with details discovered.
+ """
+ now = current_time_millis()
+ delay = _LISTENER_TIME
+ next = now + delay
+ last = now + timeout
+ result = False
+ try:
+ zc.add_listener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN))
+ while (self.server is None or self.address is None or
+ self.text is None):
+ if last <= now:
+ return False
+ if next <= now:
+ out = DNSOutgoing(_FLAGS_QR_QUERY)
+ out.add_question(DNSQuestion(self.name, _TYPE_SRV,
+ _CLASS_IN))
+ out.add_answer_at_time(zc.cache.get_by_details(self.name,
+ _TYPE_SRV, _CLASS_IN), now)
+ out.add_question(DNSQuestion(self.name, _TYPE_TXT,
+ _CLASS_IN))
+ out.add_answer_at_time(zc.cache.get_by_details(self.name,
+ _TYPE_TXT, _CLASS_IN), now)
+ if self.server is not None:
+ out.add_question(DNSQuestion(self.server,
+ _TYPE_A, _CLASS_IN))
+ out.add_answer_at_time(zc.cache.get_by_details(self.server,
+ _TYPE_A, _CLASS_IN), now)
+ zc.send(out)
+ next = now + delay
+ delay = delay * 2
+
+ zc.wait(min(next, last) - now)
+ now = current_time_millis()
+ result = True
+ finally:
+ zc.remove_listener(self)
+
+ return result
+
+ def __eq__(self, other):
+ """Tests equality of service name"""
+ if isinstance(other, ServiceInfo):
+ return other.name == self.name
+ return False
+
+ def __ne__(self, other):
+ """Non-equality test"""
+ return not self.__eq__(other)
+
+ def __repr__(self):
+ """String representation"""
+ return '%s(%s)' % (
+ type(self).__name__,
+ ', '.join(
+ '%s=%r' % (name, getattr(self, name))
+ for name in (
+ 'type', 'name', 'address', 'port', 'weight', 'priority',
+ 'server', 'properties',
+ )
+ )
+ )
+
+
+@enum.unique
+class InterfaceChoice(enum.Enum):
+ Default = 1
+ All = 2
+
+
+@enum.unique
+class ServiceStateChange(enum.Enum):
+ Added = 1
+ Removed = 2
+
+
+HOST_ONLY_NETWORK_MASK = '255.255.255.255'
+
+
+def get_all_addresses(address_family):
+ return list(set(
+ addr['addr']
+ for iface in netifaces.interfaces()
+ for addr in netifaces.ifaddresses(iface).get(address_family, [])
+ if addr.get('netmask') != HOST_ONLY_NETWORK_MASK
+ ))
+
+
+def normalize_interface_choice(choice, address_family):
+ if choice is InterfaceChoice.Default:
+ choice = ['0.0.0.0']
+ elif choice is InterfaceChoice.All:
+ choice = get_all_addresses(address_family)
+ return choice
+
+
+def new_socket():
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+
+ # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
+ # multicast UDP sockets (p 731, "TCP/IP Illustrated,
+ # Volume 2"), but some BSD-derived systems require
+ # SO_REUSEPORT to be specified explicity. Also, not all
+ # versions of Python have SO_REUSEPORT available.
+ # Catch OSError and socket.error for kernel versions <3.9 because lacking
+ # SO_REUSEPORT support.
+ try:
+ reuseport = socket.SO_REUSEPORT
+ except AttributeError:
+ pass
+ else:
+ try:
+ s.setsockopt(socket.SOL_SOCKET, reuseport, 1)
+ except (OSError, socket.error) as err: # OSError on python 3, socket.error on python 2
+ if not err.errno == errno.ENOPROTOOPT:
+ raise
+
+ # OpenBSD needs the ttl and loop values for the IP_MULTICAST_TTL and
+ # IP_MULTICAST_LOOP socket options as an unsigned char.
+ ttl = struct.pack(b'B', 255)
+ s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)
+ loop = struct.pack(b'B', 1)
+ s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, loop)
+
+ s.bind(('', _MDNS_PORT))
+ return s
+
+
+def get_errno(e):
+ assert isinstance(e, socket.error)
+ return e.args[0]
+
+
+class Zeroconf(object):
+
+ """Implementation of Zeroconf Multicast DNS Service Discovery
+
+ Supports registration, unregistration, queries and browsing.
+ """
+
+ def __init__(
+ self,
+ interfaces=InterfaceChoice.All,
+ ):
+ """Creates an instance of the Zeroconf class, establishing
+ multicast communications, listening and reaping threads.
+
+ :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
+ """
+ global _GLOBAL_DONE
+ _GLOBAL_DONE = False
+
+ self._listen_socket = new_socket()
+ interfaces = normalize_interface_choice(interfaces, socket.AF_INET)
+
+ self._respond_sockets = []
+
+ for i in interfaces:
+ log.debug('Adding %r to multicast group', i)
+ try:
+ self._listen_socket.setsockopt(
+ socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
+ socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
+ except socket.error as e:
+ if get_errno(e) == errno.EADDRINUSE:
+ log.info(
+ 'Address in use when adding %s to multicast group, '
+ 'it is expected to happen on some systems', i,
+ )
+ elif get_errno(e) == errno.EADDRNOTAVAIL:
+ log.info(
+ 'Address not available when adding %s to multicast group, '
+ 'it is expected to happen on some systems', i,
+ )
+ continue
+ else:
+ raise
+
+ respond_socket = new_socket()
+ respond_socket.setsockopt(
+ socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))
+
+ self._respond_sockets.append(respond_socket)
+
+ self.listeners = []
+ self.browsers = []
+ self.services = {}
+ self.servicetypes = {}
+
+ self.cache = DNSCache()
+
+ self.condition = threading.Condition()
+
+ self.engine = Engine(self)
+ self.listener = Listener(self)
+ self.engine.add_reader(self.listener, self._listen_socket)
+ self.reaper = Reaper(self)
+
+ def wait(self, timeout):
+ """Calling thread waits for a given number of milliseconds or
+ until notified."""
+ with self.condition:
+ self.condition.wait(timeout / 1000)
+
+ def notify_all(self):
+ """Notifies all waiting threads"""
+ with self.condition:
+ self.condition.notify_all()
+
+ def get_service_info(self, type, name, timeout=3000):
+ """Returns network's service information for a particular
+ name and type, or None if no service matches by the timeout,
+ which defaults to 3 seconds."""
+ info = ServiceInfo(type, name)
+ if info.request(self, timeout):
+ return info
+ return None
+
+ def add_service_listener(self, type, listener):
+ """Adds a listener for a particular service type. This object
+ will then have its update_record method called when information
+ arrives for that type."""
+ self.remove_service_listener(listener)
+ self.browsers.append(ServiceBrowser(self, type, listener))
+
+ def remove_service_listener(self, listener):
+ """Removes a listener from the set that is currently listening."""
+ for browser in self.browsers:
+ if browser.listener == listener:
+ browser.cancel()
+ del browser
+
+ def register_service(self, info, ttl=_DNS_TTL):
+ """Registers service information to the network with a default TTL
+ of 60 seconds. Zeroconf will then respond to requests for
+ information for that service. The name of the service may be
+ changed if needed to make it unique on the network."""
+ self.check_service(info)
+ self.services[info.name.lower()] = info
+ if info.type in self.servicetypes:
+ self.servicetypes[info.type] += 1
+ else:
+ self.servicetypes[info.type] = 1
+ now = current_time_millis()
+ next_time = now
+ i = 0
+ while i < 3:
+ if now < next_time:
+ self.wait(next_time - now)
+ now = current_time_millis()
+ continue
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+ out.add_answer_at_time(DNSPointer(info.type, _TYPE_PTR,
+ _CLASS_IN, ttl, info.name), 0)
+ out.add_answer_at_time(DNSService(info.name, _TYPE_SRV,
+ _CLASS_IN, ttl, info.priority, info.weight, info.port,
+ info.server), 0)
+ out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN,
+ ttl, info.text), 0)
+ if info.address:
+ out.add_answer_at_time(DNSAddress(info.server, _TYPE_A,
+ _CLASS_IN, ttl, info.address), 0)
+ self.send(out)
+ i += 1
+ next_time += _REGISTER_TIME
+
+ def unregister_service(self, info):
+ """Unregister a service."""
+ try:
+ del self.services[info.name.lower()]
+ if self.servicetypes[info.type] > 1:
+ self.servicetypes[info.type] -= 1
+ else:
+ del self.servicetypes[info.type]
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+ now = current_time_millis()
+ next_time = now
+ i = 0
+ while i < 3:
+ if now < next_time:
+ self.wait(next_time - now)
+ now = current_time_millis()
+ continue
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+ out.add_answer_at_time(DNSPointer(info.type, _TYPE_PTR,
+ _CLASS_IN, 0, info.name), 0)
+ out.add_answer_at_time(DNSService(info.name, _TYPE_SRV,
+ _CLASS_IN, 0, info.priority, info.weight, info.port,
+ info.name), 0)
+ out.add_answer_at_time(DNSText(info.name, _TYPE_TXT, _CLASS_IN,
+ 0, info.text), 0)
+ if info.address:
+ out.add_answer_at_time(DNSAddress(info.server, _TYPE_A,
+ _CLASS_IN, 0, info.address), 0)
+ self.send(out)
+ i += 1
+ next_time += _UNREGISTER_TIME
+
+ def unregister_all_services(self):
+ """Unregister all registered services."""
+ if len(self.services) > 0:
+ now = current_time_millis()
+ next_time = now
+ i = 0
+ while i < 3:
+ if now < next_time:
+ self.wait(next_time - now)
+ now = current_time_millis()
+ continue
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+ for info in self.services.values():
+ out.add_answer_at_time(DNSPointer(info.type, _TYPE_PTR,
+ _CLASS_IN, 0, info.name), 0)
+ out.add_answer_at_time(DNSService(info.name, _TYPE_SRV,
+ _CLASS_IN, 0, info.priority, info.weight,
+ info.port, info.server), 0)
+ out.add_answer_at_time(DNSText(info.name, _TYPE_TXT,
+ _CLASS_IN, 0, info.text), 0)
+ if info.address:
+ out.add_answer_at_time(DNSAddress(info.server,
+ _TYPE_A, _CLASS_IN, 0, info.address), 0)
+ self.send(out)
+ i += 1
+ next_time += _UNREGISTER_TIME
+
+ def check_service(self, info):
+ """Checks the network for a unique service name, modifying the
+ ServiceInfo passed in if it is not unique."""
+ now = current_time_millis()
+ next_time = now
+ i = 0
+ while i < 3:
+ for record in self.cache.entries_with_name(info.type):
+ if (record.type == _TYPE_PTR and
+ not record.is_expired(now) and
+ record.alias == info.name):
+ if info.name.find('.') < 0:
+ info.name = '%s.[%s:%s].%s' % (info.name,
+ info.address, info.port, info.type)
+
+ self.check_service(info)
+ return
+ raise NonUniqueNameException
+ if now < next_time:
+ self.wait(next_time - now)
+ now = current_time_millis()
+ continue
+ out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA)
+ self.debug = out
+ out.add_question(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN))
+ out.add_authorative_answer(DNSPointer(info.type, _TYPE_PTR,
+ _CLASS_IN, _DNS_TTL, info.name))
+ self.send(out)
+ i += 1
+ next_time += _CHECK_TIME
+
+ def add_listener(self, listener, question):
+ """Adds a listener for a given question. The listener will have
+ its update_record method called when information is available to
+ answer the question."""
+ now = current_time_millis()
+ self.listeners.append(listener)
+ if question is not None:
+ for record in self.cache.entries_with_name(question.name):
+ if question.answered_by(record) and not record.is_expired(now):
+ listener.update_record(self, now, record)
+ self.notify_all()
+
+ def remove_listener(self, listener):
+ """Removes a listener."""
+ try:
+ self.listeners.remove(listener)
+ self.notify_all()
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+
+ def update_record(self, now, rec):
+ """Used to notify listeners of new information that has updated
+ a record."""
+ for listener in self.listeners:
+ listener.update_record(self, now, rec)
+ self.notify_all()
+
+ def handle_response(self, msg):
+ """Deal with incoming response packets. All answers
+ are held in the cache, and listeners are notified."""
+ now = current_time_millis()
+ for record in msg.answers:
+ expired = record.is_expired(now)
+ if record in self.cache.entries():
+ if expired:
+ self.cache.remove(record)
+ else:
+ entry = self.cache.get(record)
+ if entry is not None:
+ entry.reset_ttl(record)
+ record = entry
+ else:
+ self.cache.add(record)
+
+ self.update_record(now, record)
+
+ def handle_query(self, msg, addr, port):
+ """Deal with incoming query packets. Provides a response if
+ possible."""
+ out = None
+
+ # Support unicast client responses
+ #
+ if port != _MDNS_PORT:
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, False)
+ for question in msg.questions:
+ out.add_question(question)
+
+ for question in msg.questions:
+ if question.type == _TYPE_PTR:
+ if question.name == "_services._dns-sd._udp.local.":
+ for stype in self.servicetypes.keys():
+ if out is None:
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+ out.add_answer(msg,
+ DNSPointer("_services._dns-sd._udp.local.",
+ _TYPE_PTR, _CLASS_IN, _DNS_TTL, stype))
+ for service in self.services.values():
+ if question.name == service.type:
+ if out is None:
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+ out.add_answer(msg,
+ DNSPointer(service.type, _TYPE_PTR,
+ _CLASS_IN, _DNS_TTL, service.name))
+ else:
+ try:
+ if out is None:
+ out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
+
+ # Answer A record queries for any service addresses we know
+ if question.type in (_TYPE_A, _TYPE_ANY):
+ for service in self.services.values():
+ if service.server == question.name.lower():
+ out.add_answer(msg, DNSAddress(question.name,
+ _TYPE_A, _CLASS_IN | _CLASS_UNIQUE,
+ _DNS_TTL, service.address))
+
+ service = self.services.get(question.name.lower(), None)
+ if not service:
+ continue
+
+ if question.type in (_TYPE_SRV, _TYPE_ANY):
+ out.add_answer(msg, DNSService(question.name,
+ _TYPE_SRV, _CLASS_IN | _CLASS_UNIQUE,
+ _DNS_TTL, service.priority, service.weight,
+ service.port, service.server))
+ if question.type in (_TYPE_TXT, _TYPE_ANY):
+ out.add_answer(msg, DNSText(question.name,
+ _TYPE_TXT, _CLASS_IN | _CLASS_UNIQUE,
+ _DNS_TTL, service.text))
+ if question.type == _TYPE_SRV:
+ out.add_additional_answer(DNSAddress(service.server,
+ _TYPE_A, _CLASS_IN | _CLASS_UNIQUE,
+ _DNS_TTL, service.address))
+ except Exception as e: # TODO stop catching all Exceptions
+ log.exception('Unknown error, possibly benign: %r', e)
+
+ if out is not None and out.answers:
+ out.id = msg.id
+ self.send(out, addr, port)
+
+ def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT):
+ """Sends an outgoing packet."""
+ packet = out.packet()
+ log.debug('Sending %r as %r...', out, packet)
+ for s in self._respond_sockets:
+ bytes_sent = s.sendto(packet, 0, (addr, port))
+ if bytes_sent != len(packet):
+ raise Error(
+ 'Should not happen, sent %d out of %d bytes' % (
+ bytes_sent, len(packet)))
+
+ def _check_threads(self):
+ """Check if any threads are still active.
+
+ Returns:
+ True if the Reaper or Engine started by this object is still alive or
+ if any ServiceBrowser known to this object is still alive. Otherwise
+ False.
+ """
+ threads = [self.reaper, self.engine] + self.browsers
+ for t in threads:
+ if isinstance(t, threading.Thread) and t.is_alive():
+ return True
+ return False
+
+ def close(self):
+ """Ends the background threads, and prevent this instance from
+ servicing further queries.
+
+ This operation blocks until all threads exit.
+ """
+ global _GLOBAL_DONE
+ if not _GLOBAL_DONE:
+ _GLOBAL_DONE = True
+ self.notify_all()
+ self.engine.notify()
+ self.unregister_all_services()
+
+ # Wait for threads to actually die before destroying the sockets
+ threads_alive = self._check_threads()
+ while threads_alive:
+ time.sleep(0.01)
+ threads_alive = self._check_threads()
+
+ for s in [self._listen_socket] + self._respond_sockets:
+ s.close()