Mercurial > hg
annotate hgext/zeroconf/Zeroconf.py @ 42642:464aa857c717 stable
amend: add a test for a simplified version of issue6157
Differential Revision: https://phab.mercurial-scm.org/D6666
author | Valentin Gatien-Baron <valentin.gatienbaron@gmail.com> |
---|---|
date | Mon, 22 Jul 2019 06:33:00 -0400 |
parents | 8306b6c29add |
children | 2372284d9457 |
rev | line source |
---|---|
28296
a73394e7b47c
zeroconf: use absolute_import
timeless <timeless@mozdev.org>
parents:
28295
diff
changeset
|
1 from __future__ import absolute_import, print_function |
28295
01815c159856
zeroconf: use print function
timeless <timeless@mozdev.org>
parents:
28249
diff
changeset
|
2 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
3 """ Multicast DNS Service Discovery for Python, v0.12 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
4 Copyright (C) 2003, Paul Scott-Murphy |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
5 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
6 This module provides a framework for the use of DNS Service Discovery |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
7 using IP multicast. It has been tested against the JRendezvous |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
8 implementation from <a href="http://strangeberry.com">StrangeBerry</a>, |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
9 and against the mDNSResponder from Mac OS X 10.3.8. |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
10 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
11 This library is free software; you can redistribute it and/or |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
12 modify it under the terms of the GNU Lesser General Public |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
13 License as published by the Free Software Foundation; either |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
14 version 2.1 of the License, or (at your option) any later version. |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
15 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
16 This library is distributed in the hope that it will be useful, |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
17 but WITHOUT ANY WARRANTY; without even the implied warranty of |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
19 Lesser General Public License for more details. |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
20 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
21 You should have received a copy of the GNU Lesser General Public |
15782
7de7630053cb
Remove FSF mailing address from GPL headers
Martin Geisler <mg@aragost.com>
parents:
14494
diff
changeset
|
22 License along with this library; if not, see |
7de7630053cb
Remove FSF mailing address from GPL headers
Martin Geisler <mg@aragost.com>
parents:
14494
diff
changeset
|
23 <http://www.gnu.org/licenses/>. |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
24 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
25 """ |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
26 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
27 """0.12 update - allow selection of binding interface |
28298 | 28 typo fix - Thanks A. M. Kuchlingi |
29 removed all use of word 'Rendezvous' - this is an API change""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
30 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
31 """0.11 update - correction to comments for addListener method |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
32 support for new record types seen from OS X |
28298 | 33 - IPv6 address |
34 - hostinfo | |
35 ignore unknown DNS record types | |
36 fixes to name decoding | |
28299 | 37 works alongside other processes using port 5353 (e.g. Mac OS X) |
28298 | 38 tested against Mac OS X 10.3.2's mDNSResponder |
39 corrections to removal of list entries for service browser""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
40 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
41 """0.10 update - Jonathon Paisley contributed these corrections: |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
42 always multicast replies, even when query is unicast |
28298 | 43 correct a pointer encoding problem |
44 can now write records in any order | |
45 traceback shown on failure | |
46 better TXT record parsing | |
47 server is now separate from name | |
48 can cancel a service browser | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
49 |
28298 | 50 modified some unit tests to accommodate these changes""" |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
51 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
52 """0.09 update - remove all records on service unregistration |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
53 fix DOS security problem with readName""" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
54 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
55 """0.08 update - changed licensing to LGPL""" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
56 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
57 """0.07 update - faster shutdown on engine |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
58 pointer encoding of outgoing names |
28298 | 59 ServiceBrowser now works |
60 new unit tests""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
61 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
62 """0.06 update - small improvements with unit tests |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
63 added defined exception types |
28298 | 64 new style objects |
65 fixed hostname/interface problem | |
66 fixed socket timeout problem | |
67 fixed addServiceListener() typo bug | |
68 using select() for socket reads | |
69 tested on Debian unstable with Python 2.2.2""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
70 |
17424
e7cfe3587ea4
fix trivial spelling errors
Mads Kiilerich <mads@kiilerich.com>
parents:
15782
diff
changeset
|
71 """0.05 update - ensure case insensitivity on domain names |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
72 support for unicast DNS queries""" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
73 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
74 """0.04 update - added some unit tests |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
75 added __ne__ adjuncts where required |
28298 | 76 ensure names end in '.local.' |
77 timeout on receiving socket for clean shutdown""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
78 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
79 __author__ = "Paul Scott-Murphy" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
80 __email__ = "paul at scott dash murphy dot com" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
81 __version__ = "0.12" |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
82 |
34447
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
83 import errno |
28422
e2c6092ad422
zeroconf: replace reduce+add with itertools.chain
timeless <timeless@mozdev.org>
parents:
28421
diff
changeset
|
84 import itertools |
28296
a73394e7b47c
zeroconf: use absolute_import
timeless <timeless@mozdev.org>
parents:
28295
diff
changeset
|
85 import select |
a73394e7b47c
zeroconf: use absolute_import
timeless <timeless@mozdev.org>
parents:
28295
diff
changeset
|
86 import socket |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
87 import struct |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
88 import threading |
28296
a73394e7b47c
zeroconf: use absolute_import
timeless <timeless@mozdev.org>
parents:
28295
diff
changeset
|
89 import time |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
90 import traceback |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
91 |
42551
8306b6c29add
py3: hack around inconsistency of type of name passed to DNSQuestion
Pulkit Goyal <7895pulkit@gmail.com>
parents:
42550
diff
changeset
|
92 from mercurial import pycompat |
8306b6c29add
py3: hack around inconsistency of type of name passed to DNSQuestion
Pulkit Goyal <7895pulkit@gmail.com>
parents:
42550
diff
changeset
|
93 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
94 __all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"] |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
95 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
96 # hook for threads |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
97 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
98 globals()['_GLOBAL_DONE'] = 0 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
99 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
100 # Some timing constants |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
101 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
102 _UNREGISTER_TIME = 125 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
103 _CHECK_TIME = 175 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
104 _REGISTER_TIME = 225 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
105 _LISTENER_TIME = 200 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
106 _BROWSER_TIME = 500 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
107 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
108 # Some DNS constants |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
109 |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
110 _MDNS_ADDR = r'224.0.0.251' |
28297 | 111 _MDNS_PORT = 5353 |
112 _DNS_PORT = 53 | |
113 _DNS_TTL = 60 * 60 # one hour default TTL | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
114 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
115 _MAX_MSG_TYPICAL = 1460 # unused |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
116 _MAX_MSG_ABSOLUTE = 8972 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
117 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
118 _FLAGS_QR_MASK = 0x8000 # query response mask |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
119 _FLAGS_QR_QUERY = 0x0000 # query |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
120 _FLAGS_QR_RESPONSE = 0x8000 # response |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
121 |
17476 | 122 _FLAGS_AA = 0x0400 # Authoritative answer |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
123 _FLAGS_TC = 0x0200 # Truncated |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
124 _FLAGS_RD = 0x0100 # Recursion desired |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
125 _FLAGS_RA = 0x8000 # Recursion available |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
126 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
127 _FLAGS_Z = 0x0040 # Zero |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
128 _FLAGS_AD = 0x0020 # Authentic data |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
129 _FLAGS_CD = 0x0010 # Checking disabled |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
130 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
131 _CLASS_IN = 1 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
132 _CLASS_CS = 2 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
133 _CLASS_CH = 3 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
134 _CLASS_HS = 4 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
135 _CLASS_NONE = 254 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
136 _CLASS_ANY = 255 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
137 _CLASS_MASK = 0x7FFF |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
138 _CLASS_UNIQUE = 0x8000 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
139 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
140 _TYPE_A = 1 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
141 _TYPE_NS = 2 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
142 _TYPE_MD = 3 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
143 _TYPE_MF = 4 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
144 _TYPE_CNAME = 5 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
145 _TYPE_SOA = 6 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
146 _TYPE_MB = 7 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
147 _TYPE_MG = 8 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
148 _TYPE_MR = 9 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
149 _TYPE_NULL = 10 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
150 _TYPE_WKS = 11 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
151 _TYPE_PTR = 12 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
152 _TYPE_HINFO = 13 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
153 _TYPE_MINFO = 14 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
154 _TYPE_MX = 15 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
155 _TYPE_TXT = 16 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
156 _TYPE_AAAA = 28 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
157 _TYPE_SRV = 33 |
27637
b502138f5faa
cleanup: remove superfluous space after space after equals (python)
timeless <timeless@mozdev.org>
parents:
17537
diff
changeset
|
158 _TYPE_ANY = 255 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
159 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
160 # Mapping constants to names |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
161 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
162 _CLASSES = { _CLASS_IN : "in", |
28298 | 163 _CLASS_CS : "cs", |
164 _CLASS_CH : "ch", | |
165 _CLASS_HS : "hs", | |
166 _CLASS_NONE : "none", | |
167 _CLASS_ANY : "any" } | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
168 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
169 _TYPES = { _TYPE_A : "a", |
28298 | 170 _TYPE_NS : "ns", |
171 _TYPE_MD : "md", | |
172 _TYPE_MF : "mf", | |
173 _TYPE_CNAME : "cname", | |
174 _TYPE_SOA : "soa", | |
175 _TYPE_MB : "mb", | |
176 _TYPE_MG : "mg", | |
177 _TYPE_MR : "mr", | |
178 _TYPE_NULL : "null", | |
179 _TYPE_WKS : "wks", | |
180 _TYPE_PTR : "ptr", | |
181 _TYPE_HINFO : "hinfo", | |
182 _TYPE_MINFO : "minfo", | |
183 _TYPE_MX : "mx", | |
184 _TYPE_TXT : "txt", | |
185 _TYPE_AAAA : "quada", | |
186 _TYPE_SRV : "srv", | |
187 _TYPE_ANY : "any" } | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
188 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
189 # utility functions |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
190 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
191 def currentTimeMillis(): |
28298 | 192 """Current system time in milliseconds""" |
193 return time.time() * 1000 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
194 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
195 # Exceptions |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
196 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
197 class NonLocalNameException(Exception): |
28298 | 198 pass |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
199 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
200 class NonUniqueNameException(Exception): |
28298 | 201 pass |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
202 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
203 class NamePartTooLongException(Exception): |
28298 | 204 pass |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
205 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
206 class AbstractMethodException(Exception): |
28298 | 207 pass |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
208 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
209 class BadTypeInNameException(Exception): |
28298 | 210 pass |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
211 |
11435
7c58cde598fe
zeroconf: Use BadDomainName exception instead of string exceptions
Javi Merino <cibervicho@gmail.com>
parents:
10514
diff
changeset
|
212 class BadDomainName(Exception): |
28298 | 213 def __init__(self, pos): |
214 Exception.__init__(self, "at position %s" % pos) | |
11435
7c58cde598fe
zeroconf: Use BadDomainName exception instead of string exceptions
Javi Merino <cibervicho@gmail.com>
parents:
10514
diff
changeset
|
215 |
7c58cde598fe
zeroconf: Use BadDomainName exception instead of string exceptions
Javi Merino <cibervicho@gmail.com>
parents:
10514
diff
changeset
|
216 class BadDomainNameCircular(BadDomainName): |
28298 | 217 pass |
11435
7c58cde598fe
zeroconf: Use BadDomainName exception instead of string exceptions
Javi Merino <cibervicho@gmail.com>
parents:
10514
diff
changeset
|
218 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
219 # implementation classes |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
220 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
221 class DNSEntry(object): |
28298 | 222 """A DNS entry""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
223 |
28298 | 224 def __init__(self, name, type, clazz): |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
225 self.key = name.lower() |
28298 | 226 self.name = name |
227 self.type = type | |
228 self.clazz = clazz & _CLASS_MASK | |
229 self.unique = (clazz & _CLASS_UNIQUE) != 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
230 |
28298 | 231 def __eq__(self, other): |
232 """Equality test on name, type, and class""" | |
233 if isinstance(other, DNSEntry): | |
28299 | 234 return (self.name == other.name and self.type == other.type and |
235 self.clazz == other.clazz) | |
28298 | 236 return 0 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
237 |
28298 | 238 def __ne__(self, other): |
239 """Non-equality test""" | |
240 return not self.__eq__(other) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
241 |
28298 | 242 def getClazz(self, clazz): |
243 """Class accessor""" | |
244 try: | |
245 return _CLASSES[clazz] | |
246 except KeyError: | |
247 return "?(%s)" % (clazz) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
248 |
28298 | 249 def getType(self, type): |
250 """Type accessor""" | |
251 try: | |
252 return _TYPES[type] | |
253 except KeyError: | |
254 return "?(%s)" % (type) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
255 |
28298 | 256 def toString(self, hdr, other): |
257 """String representation with additional information""" | |
28299 | 258 result = ("%s[%s,%s" % |
259 (hdr, self.getType(self.type), self.getClazz(self.clazz))) | |
28298 | 260 if self.unique: |
261 result += "-unique," | |
262 else: | |
263 result += "," | |
264 result += self.name | |
265 if other is not None: | |
266 result += ",%s]" % (other) | |
267 else: | |
268 result += "]" | |
269 return result | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
270 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
271 class DNSQuestion(DNSEntry): |
28298 | 272 """A DNS question entry""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
273 |
28298 | 274 def __init__(self, name, type, clazz): |
42551
8306b6c29add
py3: hack around inconsistency of type of name passed to DNSQuestion
Pulkit Goyal <7895pulkit@gmail.com>
parents:
42550
diff
changeset
|
275 if pycompat.ispy3 and isinstance(name, str): |
8306b6c29add
py3: hack around inconsistency of type of name passed to DNSQuestion
Pulkit Goyal <7895pulkit@gmail.com>
parents:
42550
diff
changeset
|
276 name = name.encode('ascii') |
28298 | 277 if not name.endswith(".local."): |
278 raise NonLocalNameException(name) | |
279 DNSEntry.__init__(self, name, type, clazz) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
280 |
28298 | 281 def answeredBy(self, rec): |
282 """Returns true if the question is answered by the record""" | |
28299 | 283 return (self.clazz == rec.clazz and |
284 (self.type == rec.type or self.type == _TYPE_ANY) and | |
285 self.name == rec.name) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
286 |
28298 | 287 def __repr__(self): |
288 """String representation""" | |
289 return DNSEntry.toString(self, "question", None) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
290 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
291 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
292 class DNSRecord(DNSEntry): |
28298 | 293 """A DNS record - like a DNS entry, but has a TTL""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
294 |
28298 | 295 def __init__(self, name, type, clazz, ttl): |
296 DNSEntry.__init__(self, name, type, clazz) | |
297 self.ttl = ttl | |
298 self.created = currentTimeMillis() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
299 |
28298 | 300 def __eq__(self, other): |
301 """Tests equality as per DNSRecord""" | |
302 if isinstance(other, DNSRecord): | |
303 return DNSEntry.__eq__(self, other) | |
304 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
305 |
28298 | 306 def suppressedBy(self, msg): |
307 """Returns true if any answer in a message can suffice for the | |
308 information held in this record.""" | |
309 for record in msg.answers: | |
310 if self.suppressedByAnswer(record): | |
311 return 1 | |
312 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
313 |
28298 | 314 def suppressedByAnswer(self, other): |
315 """Returns true if another record has same name, type and class, | |
316 and if its TTL is at least half of this record's.""" | |
317 if self == other and other.ttl > (self.ttl / 2): | |
318 return 1 | |
319 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
320 |
28298 | 321 def getExpirationTime(self, percent): |
322 """Returns the time at which this record will have expired | |
323 by a certain percentage.""" | |
324 return self.created + (percent * self.ttl * 10) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
325 |
28298 | 326 def getRemainingTTL(self, now): |
327 """Returns the remaining TTL in seconds.""" | |
328 return max(0, (self.getExpirationTime(100) - now) / 1000) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
329 |
28298 | 330 def isExpired(self, now): |
331 """Returns true if this record has expired.""" | |
332 return self.getExpirationTime(100) <= now | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
333 |
28298 | 334 def isStale(self, now): |
335 """Returns true if this record is at least half way expired.""" | |
336 return self.getExpirationTime(50) <= now | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
337 |
28298 | 338 def resetTTL(self, other): |
339 """Sets this record's TTL and created time to that of | |
340 another record.""" | |
341 self.created = other.created | |
342 self.ttl = other.ttl | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
343 |
28298 | 344 def write(self, out): |
345 """Abstract method""" | |
346 raise AbstractMethodException | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
347 |
28298 | 348 def toString(self, other): |
349 """String representation with additional information""" | |
28299 | 350 arg = ("%s/%s,%s" % |
351 (self.ttl, self.getRemainingTTL(currentTimeMillis()), other)) | |
28298 | 352 return DNSEntry.toString(self, "record", arg) |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
353 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
354 class DNSAddress(DNSRecord): |
28298 | 355 """A DNS address record""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
356 |
28298 | 357 def __init__(self, name, type, clazz, ttl, address): |
358 DNSRecord.__init__(self, name, type, clazz, ttl) | |
359 self.address = address | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
360 |
28298 | 361 def write(self, out): |
362 """Used in constructing an outgoing packet""" | |
363 out.writeString(self.address, len(self.address)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
364 |
28298 | 365 def __eq__(self, other): |
366 """Tests equality on address""" | |
367 if isinstance(other, DNSAddress): | |
368 return self.address == other.address | |
369 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
370 |
28298 | 371 def __repr__(self): |
372 """String representation""" | |
373 try: | |
374 return socket.inet_ntoa(self.address) | |
375 except Exception: | |
376 return self.address | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
377 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
378 class DNSHinfo(DNSRecord): |
28298 | 379 """A DNS host information record""" |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
380 |
28298 | 381 def __init__(self, name, type, clazz, ttl, cpu, os): |
382 DNSRecord.__init__(self, name, type, clazz, ttl) | |
383 self.cpu = cpu | |
384 self.os = os | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
385 |
28298 | 386 def write(self, out): |
387 """Used in constructing an outgoing packet""" | |
388 out.writeString(self.cpu, len(self.cpu)) | |
389 out.writeString(self.os, len(self.os)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
390 |
28298 | 391 def __eq__(self, other): |
392 """Tests equality on cpu and os""" | |
393 if isinstance(other, DNSHinfo): | |
394 return self.cpu == other.cpu and self.os == other.os | |
395 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
396 |
28298 | 397 def __repr__(self): |
398 """String representation""" | |
399 return self.cpu + " " + self.os | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
400 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
401 class DNSPointer(DNSRecord): |
28298 | 402 """A DNS pointer record""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
403 |
28298 | 404 def __init__(self, name, type, clazz, ttl, alias): |
405 DNSRecord.__init__(self, name, type, clazz, ttl) | |
406 self.alias = alias | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
407 |
28298 | 408 def write(self, out): |
409 """Used in constructing an outgoing packet""" | |
410 out.writeName(self.alias) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
411 |
28298 | 412 def __eq__(self, other): |
413 """Tests equality on alias""" | |
414 if isinstance(other, DNSPointer): | |
415 return self.alias == other.alias | |
416 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
417 |
28298 | 418 def __repr__(self): |
419 """String representation""" | |
420 return self.toString(self.alias) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
421 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
422 class DNSText(DNSRecord): |
28298 | 423 """A DNS text record""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
424 |
28298 | 425 def __init__(self, name, type, clazz, ttl, text): |
426 DNSRecord.__init__(self, name, type, clazz, ttl) | |
427 self.text = text | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
428 |
28298 | 429 def write(self, out): |
430 """Used in constructing an outgoing packet""" | |
431 out.writeString(self.text, len(self.text)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
432 |
28298 | 433 def __eq__(self, other): |
434 """Tests equality on text""" | |
435 if isinstance(other, DNSText): | |
436 return self.text == other.text | |
437 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
438 |
28298 | 439 def __repr__(self): |
440 """String representation""" | |
441 if len(self.text) > 10: | |
442 return self.toString(self.text[:7] + "...") | |
443 else: | |
444 return self.toString(self.text) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
445 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
446 class DNSService(DNSRecord): |
28298 | 447 """A DNS service record""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
448 |
28298 | 449 def __init__(self, name, type, clazz, ttl, priority, weight, port, server): |
450 DNSRecord.__init__(self, name, type, clazz, ttl) | |
451 self.priority = priority | |
452 self.weight = weight | |
453 self.port = port | |
454 self.server = server | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
455 |
28298 | 456 def write(self, out): |
457 """Used in constructing an outgoing packet""" | |
458 out.writeShort(self.priority) | |
459 out.writeShort(self.weight) | |
460 out.writeShort(self.port) | |
461 out.writeName(self.server) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
462 |
28298 | 463 def __eq__(self, other): |
464 """Tests equality on priority, weight, port and server""" | |
465 if isinstance(other, DNSService): | |
28299 | 466 return (self.priority == other.priority and |
467 self.weight == other.weight and | |
468 self.port == other.port and | |
469 self.server == other.server) | |
28298 | 470 return 0 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
471 |
28298 | 472 def __repr__(self): |
473 """String representation""" | |
474 return self.toString("%s:%s" % (self.server, self.port)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
475 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
476 class DNSIncoming(object): |
28298 | 477 """Object representation of an incoming DNS packet""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
478 |
28298 | 479 def __init__(self, data): |
480 """Constructor from string holding bytes of packet""" | |
481 self.offset = 0 | |
482 self.data = data | |
483 self.questions = [] | |
484 self.answers = [] | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
485 self.numquestions = 0 |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
486 self.numanswers = 0 |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
487 self.numauthorities = 0 |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
488 self.numadditionals = 0 |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
489 |
28298 | 490 self.readHeader() |
491 self.readQuestions() | |
492 self.readOthers() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
493 |
28298 | 494 def readHeader(self): |
495 """Reads header portion of packet""" | |
496 format = '!HHHHHH' | |
497 length = struct.calcsize(format) | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
498 info = struct.unpack(format, |
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
499 self.data[self.offset:self.offset + length]) |
28298 | 500 self.offset += length |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
501 |
28298 | 502 self.id = info[0] |
503 self.flags = info[1] | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
504 self.numquestions = info[2] |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
505 self.numanswers = info[3] |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
506 self.numauthorities = info[4] |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
507 self.numadditionals = info[5] |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
508 |
28298 | 509 def readQuestions(self): |
510 """Reads questions section of packet""" | |
511 format = '!HH' | |
512 length = struct.calcsize(format) | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
513 for i in range(0, self.numquestions): |
28298 | 514 name = self.readName() |
28299 | 515 info = struct.unpack(format, |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
516 self.data[self.offset:self.offset + length]) |
28298 | 517 self.offset += length |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
518 |
28298 | 519 try: |
520 question = DNSQuestion(name, info[0], info[1]) | |
521 self.questions.append(question) | |
522 except NonLocalNameException: | |
523 pass | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
524 |
28298 | 525 def readInt(self): |
526 """Reads an integer from the packet""" | |
527 format = '!I' | |
528 length = struct.calcsize(format) | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
529 info = struct.unpack(format, |
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
530 self.data[self.offset:self.offset + length]) |
28298 | 531 self.offset += length |
532 return info[0] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
533 |
28298 | 534 def readCharacterString(self): |
535 """Reads a character string from the packet""" | |
536 length = ord(self.data[self.offset]) | |
537 self.offset += 1 | |
538 return self.readString(length) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
539 |
28298 | 540 def readString(self, len): |
541 """Reads a string of a given length from the packet""" | |
42550
683aeef12830
py3: add r'' prefixes and do ('%d' % int) instead of str(int)
Pulkit Goyal <7895pulkit@gmail.com>
parents:
41519
diff
changeset
|
542 format = '!%ds' % len |
28298 | 543 length = struct.calcsize(format) |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
544 info = struct.unpack(format, |
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
545 self.data[self.offset:self.offset + length]) |
28298 | 546 self.offset += length |
547 return info[0] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
548 |
28298 | 549 def readUnsignedShort(self): |
550 """Reads an unsigned short from the packet""" | |
551 format = '!H' | |
552 length = struct.calcsize(format) | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
553 info = struct.unpack(format, |
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
554 self.data[self.offset:self.offset + length]) |
28298 | 555 self.offset += length |
556 return info[0] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
557 |
28298 | 558 def readOthers(self): |
28299 | 559 """Reads answers, authorities and additionals section of the packet""" |
28298 | 560 format = '!HHiH' |
561 length = struct.calcsize(format) | |
28504
3c90090320ad
zeroconf: remove leftover camelcase identifier
Martin von Zweigbergk <martinvonz@google.com>
parents:
28422
diff
changeset
|
562 n = self.numanswers + self.numauthorities + self.numadditionals |
28298 | 563 for i in range(0, n): |
564 domain = self.readName() | |
28299 | 565 info = struct.unpack(format, |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
566 self.data[self.offset:self.offset + length]) |
28298 | 567 self.offset += length |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
568 |
28298 | 569 rec = None |
570 if info[0] == _TYPE_A: | |
28299 | 571 rec = DNSAddress(domain, info[0], info[1], info[2], |
572 self.readString(4)) | |
28298 | 573 elif info[0] == _TYPE_CNAME or info[0] == _TYPE_PTR: |
28299 | 574 rec = DNSPointer(domain, info[0], info[1], info[2], |
575 self.readName()) | |
28298 | 576 elif info[0] == _TYPE_TXT: |
28299 | 577 rec = DNSText(domain, info[0], info[1], info[2], |
578 self.readString(info[3])) | |
28298 | 579 elif info[0] == _TYPE_SRV: |
28299 | 580 rec = DNSService(domain, info[0], info[1], info[2], |
581 self.readUnsignedShort(), | |
582 self.readUnsignedShort(), | |
583 self.readUnsignedShort(), | |
584 self.readName()) | |
28298 | 585 elif info[0] == _TYPE_HINFO: |
28299 | 586 rec = DNSHinfo(domain, info[0], info[1], info[2], |
587 self.readCharacterString(), | |
588 self.readCharacterString()) | |
28298 | 589 elif info[0] == _TYPE_AAAA: |
28299 | 590 rec = DNSAddress(domain, info[0], info[1], info[2], |
591 self.readString(16)) | |
28298 | 592 else: |
593 # Try to ignore types we don't know about | |
594 # this may mean the rest of the name is | |
595 # unable to be parsed, and may show errors | |
596 # so this is left for debugging. New types | |
597 # encountered need to be parsed properly. | |
598 # | |
599 #print "UNKNOWN TYPE = " + str(info[0]) | |
600 #raise BadTypeInNameException | |
601 self.offset += info[3] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
602 |
28298 | 603 if rec is not None: |
604 self.answers.append(rec) | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
605 |
28298 | 606 def isQuery(self): |
607 """Returns true if this is a query""" | |
608 return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
609 |
28298 | 610 def isResponse(self): |
611 """Returns true if this is a response""" | |
612 return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
613 |
28298 | 614 def readUTF(self, offset, len): |
615 """Reads a UTF-8 string of a given length from the packet""" | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
616 return self.data[offset:offset + len].decode('utf-8') |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
617 |
28298 | 618 def readName(self): |
619 """Reads a domain name from the packet""" | |
42550
683aeef12830
py3: add r'' prefixes and do ('%d' % int) instead of str(int)
Pulkit Goyal <7895pulkit@gmail.com>
parents:
41519
diff
changeset
|
620 result = r'' |
28298 | 621 off = self.offset |
622 next = -1 | |
623 first = off | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
624 |
28298 | 625 while True: |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
626 len = ord(self.data[off:off + 1]) |
28298 | 627 off += 1 |
628 if len == 0: | |
629 break | |
630 t = len & 0xC0 | |
631 if t == 0x00: | |
42550
683aeef12830
py3: add r'' prefixes and do ('%d' % int) instead of str(int)
Pulkit Goyal <7895pulkit@gmail.com>
parents:
41519
diff
changeset
|
632 result = r''.join((result, self.readUTF(off, len) + r'.')) |
28298 | 633 off += len |
634 elif t == 0xC0: | |
635 if next < 0: | |
636 next = off + 1 | |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
637 off = ((len & 0x3F) << 8) | ord(self.data[off:off + 1]) |
28298 | 638 if off >= first: |
639 raise BadDomainNameCircular(off) | |
640 first = off | |
641 else: | |
642 raise BadDomainName(off) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
643 |
28298 | 644 if next >= 0: |
645 self.offset = next | |
646 else: | |
647 self.offset = off | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
648 |
28298 | 649 return result |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
650 |
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
651 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
652 class DNSOutgoing(object): |
28298 | 653 """Object representation of an outgoing packet""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
654 |
28302
e96a3ae025ed
zeroconf: remove whitespace around = for named parameters
timeless <timeless@mozdev.org>
parents:
28301
diff
changeset
|
655 def __init__(self, flags, multicast=1): |
28298 | 656 self.finished = 0 |
657 self.id = 0 | |
658 self.multicast = multicast | |
659 self.flags = flags | |
660 self.names = {} | |
661 self.data = [] | |
662 self.size = 12 | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
663 |
28298 | 664 self.questions = [] |
665 self.answers = [] | |
666 self.authorities = [] | |
667 self.additionals = [] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
668 |
28298 | 669 def addQuestion(self, record): |
670 """Adds a question""" | |
671 self.questions.append(record) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
672 |
28298 | 673 def addAnswer(self, inp, record): |
674 """Adds an answer""" | |
675 if not record.suppressedBy(inp): | |
676 self.addAnswerAtTime(record, 0) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
677 |
28298 | 678 def addAnswerAtTime(self, record, now): |
679 """Adds an answer if if does not expire by a certain time""" | |
680 if record is not None: | |
681 if now == 0 or not record.isExpired(now): | |
682 self.answers.append((record, now)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
683 |
28298 | 684 def addAuthoritativeAnswer(self, record): |
685 """Adds an authoritative answer""" | |
686 self.authorities.append(record) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
687 |
28298 | 688 def addAdditionalAnswer(self, record): |
689 """Adds an additional answer""" | |
690 self.additionals.append(record) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
691 |
28298 | 692 def writeByte(self, value): |
693 """Writes a single byte to the packet""" | |
694 format = '!c' | |
695 self.data.append(struct.pack(format, chr(value))) | |
696 self.size += 1 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
697 |
28298 | 698 def insertShort(self, index, value): |
699 """Inserts an unsigned short in a certain position in the packet""" | |
700 format = '!H' | |
701 self.data.insert(index, struct.pack(format, value)) | |
702 self.size += 2 | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
703 |
28298 | 704 def writeShort(self, value): |
705 """Writes an unsigned short to the packet""" | |
706 format = '!H' | |
707 self.data.append(struct.pack(format, value)) | |
708 self.size += 2 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
709 |
28298 | 710 def writeInt(self, value): |
711 """Writes an unsigned integer to the packet""" | |
712 format = '!I' | |
713 self.data.append(struct.pack(format, int(value))) | |
714 self.size += 4 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
715 |
28298 | 716 def writeString(self, value, length): |
717 """Writes a string to the packet""" | |
718 format = '!' + str(length) + 's' | |
719 self.data.append(struct.pack(format, value)) | |
720 self.size += length | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
721 |
28298 | 722 def writeUTF(self, s): |
723 """Writes a UTF-8 string of a given length to the packet""" | |
724 utfstr = s.encode('utf-8') | |
725 length = len(utfstr) | |
726 if length > 64: | |
727 raise NamePartTooLongException | |
728 self.writeByte(length) | |
729 self.writeString(utfstr, length) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
730 |
28298 | 731 def writeName(self, name): |
732 """Writes a domain name to the packet""" | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
733 |
28298 | 734 try: |
735 # Find existing instance of this name in packet | |
736 # | |
737 index = self.names[name] | |
738 except KeyError: | |
739 # No record of this name already, so write it | |
740 # out as normal, recording the location of the name | |
741 # for future pointers to it. | |
742 # | |
743 self.names[name] = self.size | |
744 parts = name.split('.') | |
745 if parts[-1] == '': | |
746 parts = parts[:-1] | |
747 for part in parts: | |
748 self.writeUTF(part) | |
749 self.writeByte(0) | |
750 return | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
751 |
28298 | 752 # An index was found, so write a pointer to it |
753 # | |
754 self.writeByte((index >> 8) | 0xC0) | |
755 self.writeByte(index) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
756 |
28298 | 757 def writeQuestion(self, question): |
758 """Writes a question to the packet""" | |
759 self.writeName(question.name) | |
760 self.writeShort(question.type) | |
761 self.writeShort(question.clazz) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
762 |
28298 | 763 def writeRecord(self, record, now): |
764 """Writes a record (answer, authoritative answer, additional) to | |
765 the packet""" | |
766 self.writeName(record.name) | |
767 self.writeShort(record.type) | |
768 if record.unique and self.multicast: | |
769 self.writeShort(record.clazz | _CLASS_UNIQUE) | |
770 else: | |
771 self.writeShort(record.clazz) | |
772 if now == 0: | |
773 self.writeInt(record.ttl) | |
774 else: | |
775 self.writeInt(record.getRemainingTTL(now)) | |
776 index = len(self.data) | |
777 # Adjust size for the short we will write before this record | |
778 # | |
779 self.size += 2 | |
780 record.write(self) | |
781 self.size -= 2 | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
782 |
28298 | 783 length = len(''.join(self.data[index:])) |
784 self.insertShort(index, length) # Here is the short we adjusted for | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
785 |
28298 | 786 def packet(self): |
787 """Returns a string containing the packet's bytes | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
788 |
28298 | 789 No further parts should be added to the packet once this |
790 is done.""" | |
791 if not self.finished: | |
792 self.finished = 1 | |
793 for question in self.questions: | |
794 self.writeQuestion(question) | |
795 for answer, time_ in self.answers: | |
796 self.writeRecord(answer, time_) | |
797 for authority in self.authorities: | |
798 self.writeRecord(authority, 0) | |
799 for additional in self.additionals: | |
800 self.writeRecord(additional, 0) | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
801 |
28298 | 802 self.insertShort(0, len(self.additionals)) |
803 self.insertShort(0, len(self.authorities)) | |
804 self.insertShort(0, len(self.answers)) | |
805 self.insertShort(0, len(self.questions)) | |
806 self.insertShort(0, self.flags) | |
807 if self.multicast: | |
808 self.insertShort(0, 0) | |
809 else: | |
810 self.insertShort(0, self.id) | |
811 return ''.join(self.data) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
812 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
813 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
814 class DNSCache(object): |
28298 | 815 """A cache of DNS entries""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
816 |
28298 | 817 def __init__(self): |
818 self.cache = {} | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
819 |
28298 | 820 def add(self, entry): |
821 """Adds an entry""" | |
822 try: | |
823 list = self.cache[entry.key] | |
824 except KeyError: | |
825 list = self.cache[entry.key] = [] | |
826 list.append(entry) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
827 |
28298 | 828 def remove(self, entry): |
829 """Removes an entry""" | |
830 try: | |
831 list = self.cache[entry.key] | |
832 list.remove(entry) | |
833 except KeyError: | |
834 pass | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
835 |
28298 | 836 def get(self, entry): |
837 """Gets an entry by key. Will return None if there is no | |
838 matching entry.""" | |
839 try: | |
840 list = self.cache[entry.key] | |
841 return list[list.index(entry)] | |
842 except (KeyError, ValueError): | |
843 return None | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
844 |
28298 | 845 def getByDetails(self, name, type, clazz): |
846 """Gets an entry by details. Will return None if there is | |
847 no matching entry.""" | |
848 entry = DNSEntry(name, type, clazz) | |
849 return self.get(entry) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
850 |
28298 | 851 def entriesWithName(self, name): |
852 """Returns a list of entries whose key matches the name.""" | |
853 try: | |
854 return self.cache[name] | |
855 except KeyError: | |
856 return [] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
857 |
28298 | 858 def entries(self): |
859 """Returns a list of all entries""" | |
860 try: | |
28422
e2c6092ad422
zeroconf: replace reduce+add with itertools.chain
timeless <timeless@mozdev.org>
parents:
28421
diff
changeset
|
861 return list(itertools.chain.from_iterable(self.cache.values())) |
28298 | 862 except Exception: |
863 return [] | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
864 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
865 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
866 class Engine(threading.Thread): |
28298 | 867 """An engine wraps read access to sockets, allowing objects that |
868 need to receive data from sockets to be called back when the | |
869 sockets are ready. | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
870 |
28298 | 871 A reader needs a handle_read() method, which is called when the socket |
872 it is interested in is ready for reading. | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
873 |
28298 | 874 Writers are not implemented here, because we only send short |
875 packets. | |
876 """ | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
877 |
28298 | 878 def __init__(self, zeroconf): |
879 threading.Thread.__init__(self) | |
880 self.zeroconf = zeroconf | |
881 self.readers = {} # maps socket to reader | |
882 self.timeout = 5 | |
883 self.condition = threading.Condition() | |
884 self.start() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
885 |
28298 | 886 def run(self): |
887 while not globals()['_GLOBAL_DONE']: | |
888 rs = self.getReaders() | |
889 if len(rs) == 0: | |
890 # No sockets to manage, but we wait for the timeout | |
891 # or addition of a socket | |
892 # | |
893 self.condition.acquire() | |
894 self.condition.wait(self.timeout) | |
895 self.condition.release() | |
896 else: | |
897 try: | |
898 rr, wr, er = select.select(rs, [], [], self.timeout) | |
899 for sock in rr: | |
900 try: | |
901 self.readers[sock].handle_read() | |
902 except Exception: | |
903 if not globals()['_GLOBAL_DONE']: | |
904 traceback.print_exc() | |
905 except Exception: | |
906 pass | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
907 |
28298 | 908 def getReaders(self): |
909 self.condition.acquire() | |
910 result = self.readers.keys() | |
911 self.condition.release() | |
912 return result | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
913 |
28298 | 914 def addReader(self, reader, socket): |
915 self.condition.acquire() | |
916 self.readers[socket] = reader | |
917 self.condition.notify() | |
918 self.condition.release() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
919 |
28298 | 920 def delReader(self, socket): |
921 self.condition.acquire() | |
28301
fd8a4d2d6541
zeroconf: del is not a function
timeless <timeless@mozdev.org>
parents:
28300
diff
changeset
|
922 del self.readers[socket] |
28298 | 923 self.condition.notify() |
924 self.condition.release() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
925 |
28298 | 926 def notify(self): |
927 self.condition.acquire() | |
928 self.condition.notify() | |
929 self.condition.release() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
930 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
931 class Listener(object): |
28298 | 932 """A Listener is used by this module to listen on the multicast |
933 group to which DNS messages are sent, allowing the implementation | |
934 to cache information as it arrives. | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
935 |
28298 | 936 It requires registration with an Engine object in order to have |
937 the read() method called when a socket is available for reading.""" | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
938 |
28298 | 939 def __init__(self, zeroconf): |
940 self.zeroconf = zeroconf | |
941 self.zeroconf.engine.addReader(self, self.zeroconf.socket) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
942 |
28298 | 943 def handle_read(self): |
34447
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
944 sock = self.zeroconf.socket |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
945 try: |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
946 data, (addr, port) = sock.recvfrom(_MAX_MSG_ABSOLUTE) |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
947 except socket.error as e: |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
948 if e.errno == errno.EBADF: |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
949 # some other thread may close the socket |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
950 return |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
951 else: |
5385b76fd1fd
zeroconf: do not crash if socket being read is closed by another thread
Jun Wu <quark@fb.com>
parents:
28504
diff
changeset
|
952 raise |
28298 | 953 self.data = data |
954 msg = DNSIncoming(data) | |
955 if msg.isQuery(): | |
956 # Always multicast responses | |
957 # | |
958 if port == _MDNS_PORT: | |
959 self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT) | |
960 # If it's not a multicast query, reply via unicast | |
961 # and multicast | |
962 # | |
963 elif port == _DNS_PORT: | |
964 self.zeroconf.handleQuery(msg, addr, port) | |
965 self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT) | |
966 else: | |
967 self.zeroconf.handleResponse(msg) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
968 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
969 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
970 class Reaper(threading.Thread): |
28298 | 971 """A Reaper is used by this module to remove cache entries that |
972 have expired.""" | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
973 |
28298 | 974 def __init__(self, zeroconf): |
975 threading.Thread.__init__(self) | |
976 self.zeroconf = zeroconf | |
977 self.start() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
978 |
28298 | 979 def run(self): |
980 while True: | |
981 self.zeroconf.wait(10 * 1000) | |
982 if globals()['_GLOBAL_DONE']: | |
983 return | |
984 now = currentTimeMillis() | |
985 for record in self.zeroconf.cache.entries(): | |
986 if record.isExpired(now): | |
987 self.zeroconf.updateRecord(now, record) | |
988 self.zeroconf.cache.remove(record) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
989 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
990 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
991 class ServiceBrowser(threading.Thread): |
28298 | 992 """Used to browse for a service of a specific type. |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
993 |
28298 | 994 The listener object will have its addService() and |
995 removeService() methods called when this browser | |
996 discovers changes in the services availability.""" | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
997 |
28298 | 998 def __init__(self, zeroconf, type, listener): |
999 """Creates a browser for a specific type""" | |
1000 threading.Thread.__init__(self) | |
1001 self.zeroconf = zeroconf | |
1002 self.type = type | |
1003 self.listener = listener | |
1004 self.services = {} | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1005 self.nexttime = currentTimeMillis() |
28298 | 1006 self.delay = _BROWSER_TIME |
1007 self.list = [] | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1008 |
28298 | 1009 self.done = 0 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1010 |
28299 | 1011 self.zeroconf.addListener(self, DNSQuestion(self.type, _TYPE_PTR, |
1012 _CLASS_IN)) | |
28298 | 1013 self.start() |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1014 |
28298 | 1015 def updateRecord(self, zeroconf, now, record): |
1016 """Callback invoked by Zeroconf when new information arrives. | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1017 |
28298 | 1018 Updates information required by browser in the Zeroconf cache.""" |
1019 if record.type == _TYPE_PTR and record.name == self.type: | |
1020 expired = record.isExpired(now) | |
1021 try: | |
1022 oldrecord = self.services[record.alias.lower()] | |
1023 if not expired: | |
1024 oldrecord.resetTTL(record) | |
1025 else: | |
28301
fd8a4d2d6541
zeroconf: del is not a function
timeless <timeless@mozdev.org>
parents:
28300
diff
changeset
|
1026 del self.services[record.alias.lower()] |
28299 | 1027 callback = (lambda x: |
1028 self.listener.removeService(x, self.type, record.alias)) | |
28298 | 1029 self.list.append(callback) |
1030 return | |
1031 except Exception: | |
1032 if not expired: | |
1033 self.services[record.alias.lower()] = record | |
28299 | 1034 callback = (lambda x: |
1035 self.listener.addService(x, self.type, record.alias)) | |
28298 | 1036 self.list.append(callback) |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1037 |
28298 | 1038 expires = record.getExpirationTime(75) |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1039 if expires < self.nexttime: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1040 self.nexttime = expires |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1041 |
28298 | 1042 def cancel(self): |
1043 self.done = 1 | |
1044 self.zeroconf.notifyAll() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1045 |
28298 | 1046 def run(self): |
1047 while True: | |
1048 event = None | |
1049 now = currentTimeMillis() | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1050 if len(self.list) == 0 and self.nexttime > now: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1051 self.zeroconf.wait(self.nexttime - now) |
28298 | 1052 if globals()['_GLOBAL_DONE'] or self.done: |
1053 return | |
1054 now = currentTimeMillis() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1055 |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1056 if self.nexttime <= now: |
28298 | 1057 out = DNSOutgoing(_FLAGS_QR_QUERY) |
1058 out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN)) | |
1059 for record in self.services.values(): | |
1060 if not record.isExpired(now): | |
1061 out.addAnswerAtTime(record, now) | |
1062 self.zeroconf.send(out) | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1063 self.nexttime = now + self.delay |
28298 | 1064 self.delay = min(20 * 1000, self.delay * 2) |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1065 |
28298 | 1066 if len(self.list) > 0: |
1067 event = self.list.pop(0) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1068 |
28298 | 1069 if event is not None: |
1070 event(self.zeroconf) | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1071 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1072 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1073 class ServiceInfo(object): |
28298 | 1074 """Service information""" |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1075 |
28299 | 1076 def __init__(self, type, name, address=None, port=None, weight=0, |
1077 priority=0, properties=None, server=None): | |
28298 | 1078 """Create a service description. |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1079 |
28298 | 1080 type: fully qualified service type name |
1081 name: fully qualified service name | |
1082 address: IP address as unsigned short, network byte order | |
1083 port: port that the service runs on | |
1084 weight: weight of the service | |
1085 priority: priority of the service | |
28299 | 1086 properties: dictionary of properties (or a string holding the bytes for |
1087 the text field) | |
28298 | 1088 server: fully qualified name for service host (defaults to name)""" |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1089 |
28298 | 1090 if not name.endswith(type): |
1091 raise BadTypeInNameException | |
1092 self.type = type | |
1093 self.name = name | |
1094 self.address = address | |
1095 self.port = port | |
1096 self.weight = weight | |
1097 self.priority = priority | |
1098 if server: | |
1099 self.server = server | |
1100 else: | |
1101 self.server = name | |
1102 self.setProperties(properties) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1103 |
28298 | 1104 def setProperties(self, properties): |
1105 """Sets properties and text of this info from a dictionary""" | |
1106 if isinstance(properties, dict): | |
1107 self.properties = properties | |
1108 list = [] | |
1109 result = '' | |
1110 for key in properties: | |
1111 value = properties[key] | |
1112 if value is None: | |
1113 suffix = '' | |
1114 elif isinstance(value, str): | |
1115 suffix = value | |
1116 elif isinstance(value, int): | |
1117 if value: | |
1118 suffix = 'true' | |
1119 else: | |
1120 suffix = 'false' | |
1121 else: | |
1122 suffix = '' | |
1123 list.append('='.join((key, suffix))) | |
1124 for item in list: | |
28299 | 1125 result = ''.join((result, struct.pack('!c', chr(len(item))), |
1126 item)) | |
28298 | 1127 self.text = result |
1128 else: | |
1129 self.text = properties | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1130 |
28298 | 1131 def setText(self, text): |
1132 """Sets properties and text given a text field""" | |
1133 self.text = text | |
1134 try: | |
1135 result = {} | |
1136 end = len(text) | |
1137 index = 0 | |
1138 strs = [] | |
1139 while index < end: | |
1140 length = ord(text[index]) | |
1141 index += 1 | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1142 strs.append(text[index:index + length]) |
28298 | 1143 index += length |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1144 |
28298 | 1145 for s in strs: |
1146 eindex = s.find('=') | |
1147 if eindex == -1: | |
1148 # No equals sign at all | |
1149 key = s | |
1150 value = 0 | |
1151 else: | |
1152 key = s[:eindex] | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1153 value = s[eindex + 1:] |
28298 | 1154 if value == 'true': |
1155 value = 1 | |
1156 elif value == 'false' or not value: | |
1157 value = 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1158 |
28298 | 1159 # Only update non-existent properties |
28420
d03b7800672c
zeroconf: compare singleton using is
timeless <timeless@mozdev.org>
parents:
28419
diff
changeset
|
1160 if key and result.get(key) is None: |
28298 | 1161 result[key] = value |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1162 |
28298 | 1163 self.properties = result |
1164 except Exception: | |
1165 traceback.print_exc() | |
1166 self.properties = None | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1167 |
28298 | 1168 def getType(self): |
1169 """Type accessor""" | |
1170 return self.type | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1171 |
28298 | 1172 def getName(self): |
1173 """Name accessor""" | |
1174 if self.type is not None and self.name.endswith("." + self.type): | |
1175 return self.name[:len(self.name) - len(self.type) - 1] | |
1176 return self.name | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1177 |
28298 | 1178 def getAddress(self): |
1179 """Address accessor""" | |
1180 return self.address | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1181 |
28298 | 1182 def getPort(self): |
1183 """Port accessor""" | |
1184 return self.port | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1185 |
28298 | 1186 def getPriority(self): |
1187 """Priority accessor""" | |
1188 return self.priority | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1189 |
28298 | 1190 def getWeight(self): |
1191 """Weight accessor""" | |
1192 return self.weight | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1193 |
28298 | 1194 def getProperties(self): |
1195 """Properties accessor""" | |
1196 return self.properties | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1197 |
28298 | 1198 def getText(self): |
1199 """Text accessor""" | |
1200 return self.text | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1201 |
28298 | 1202 def getServer(self): |
1203 """Server accessor""" | |
1204 return self.server | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1205 |
28298 | 1206 def updateRecord(self, zeroconf, now, record): |
1207 """Updates service information from a DNS record""" | |
1208 if record is not None and not record.isExpired(now): | |
1209 if record.type == _TYPE_A: | |
1210 #if record.name == self.name: | |
1211 if record.name == self.server: | |
1212 self.address = record.address | |
1213 elif record.type == _TYPE_SRV: | |
1214 if record.name == self.name: | |
1215 self.server = record.server | |
1216 self.port = record.port | |
1217 self.weight = record.weight | |
1218 self.priority = record.priority | |
1219 #self.address = None | |
28299 | 1220 self.updateRecord(zeroconf, now, |
1221 zeroconf.cache.getByDetails(self.server, | |
1222 _TYPE_A, _CLASS_IN)) | |
28298 | 1223 elif record.type == _TYPE_TXT: |
1224 if record.name == self.name: | |
1225 self.setText(record.text) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1226 |
28298 | 1227 def request(self, zeroconf, timeout): |
1228 """Returns true if the service could be discovered on the | |
1229 network, and updates this object with details discovered. | |
1230 """ | |
1231 now = currentTimeMillis() | |
1232 delay = _LISTENER_TIME | |
1233 next = now + delay | |
1234 last = now + timeout | |
1235 try: | |
28299 | 1236 zeroconf.addListener(self, DNSQuestion(self.name, _TYPE_ANY, |
1237 _CLASS_IN)) | |
1238 while (self.server is None or self.address is None or | |
1239 self.text is None): | |
28298 | 1240 if last <= now: |
1241 return 0 | |
1242 if next <= now: | |
1243 out = DNSOutgoing(_FLAGS_QR_QUERY) | |
28299 | 1244 out.addQuestion(DNSQuestion(self.name, _TYPE_SRV, |
1245 _CLASS_IN)) | |
1246 out.addAnswerAtTime( | |
1247 zeroconf.cache.getByDetails(self.name, | |
1248 _TYPE_SRV, | |
1249 _CLASS_IN), | |
1250 now) | |
1251 out.addQuestion(DNSQuestion(self.name, _TYPE_TXT, | |
1252 _CLASS_IN)) | |
1253 out.addAnswerAtTime( | |
1254 zeroconf.cache.getByDetails(self.name, _TYPE_TXT, | |
1255 _CLASS_IN), | |
1256 now) | |
28298 | 1257 if self.server is not None: |
28299 | 1258 out.addQuestion( |
1259 DNSQuestion(self.server, _TYPE_A, _CLASS_IN)) | |
1260 out.addAnswerAtTime( | |
1261 zeroconf.cache.getByDetails(self.server, _TYPE_A, | |
1262 _CLASS_IN), | |
1263 now) | |
28298 | 1264 zeroconf.send(out) |
1265 next = now + delay | |
1266 delay = delay * 2 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1267 |
28298 | 1268 zeroconf.wait(min(next, last) - now) |
1269 now = currentTimeMillis() | |
1270 result = 1 | |
1271 finally: | |
1272 zeroconf.removeListener(self) | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1273 |
28298 | 1274 return result |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1275 |
28298 | 1276 def __eq__(self, other): |
1277 """Tests equality of service name""" | |
1278 if isinstance(other, ServiceInfo): | |
1279 return other.name == self.name | |
1280 return 0 | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1281 |
28298 | 1282 def __ne__(self, other): |
1283 """Non-equality test""" | |
1284 return not self.__eq__(other) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1285 |
28298 | 1286 def __repr__(self): |
1287 """String representation""" | |
28299 | 1288 result = ("service[%s,%s:%s," % |
1289 (self.name, socket.inet_ntoa(self.getAddress()), self.port)) | |
28298 | 1290 if self.text is None: |
1291 result += "None" | |
1292 else: | |
1293 if len(self.text) < 20: | |
1294 result += self.text | |
1295 else: | |
1296 result += self.text[:17] + "..." | |
1297 result += "]" | |
1298 return result | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1299 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1300 |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1301 class Zeroconf(object): |
28298 | 1302 """Implementation of Zeroconf Multicast DNS Service Discovery |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1303 |
28298 | 1304 Supports registration, unregistration, queries and browsing. |
1305 """ | |
1306 def __init__(self, bindaddress=None): | |
1307 """Creates an instance of the Zeroconf class, establishing | |
1308 multicast communications, listening and reaping threads.""" | |
1309 globals()['_GLOBAL_DONE'] = 0 | |
1310 if bindaddress is None: | |
1311 self.intf = socket.gethostbyname(socket.gethostname()) | |
1312 else: | |
1313 self.intf = bindaddress | |
1314 self.group = ('', _MDNS_PORT) | |
1315 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
1316 try: | |
1317 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) | |
1318 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) | |
1319 except Exception: | |
1320 # SO_REUSEADDR should be equivalent to SO_REUSEPORT for | |
1321 # multicast UDP sockets (p 731, "TCP/IP Illustrated, | |
1322 # Volume 2"), but some BSD-derived systems require | |
1323 # SO_REUSEPORT to be specified explicitly. Also, not all | |
1324 # versions of Python have SO_REUSEPORT available. So | |
1325 # if you're on a BSD-based system, and haven't upgraded | |
1326 # to Python 2.3 yet, you may find this library doesn't | |
1327 # work as expected. | |
1328 # | |
1329 pass | |
1330 self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, "\xff") | |
1331 self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, "\x01") | |
1332 try: | |
1333 self.socket.bind(self.group) | |
1334 except Exception: | |
1335 # Some versions of linux raise an exception even though | |
1336 # SO_REUSEADDR and SO_REUSEPORT have been set, so ignore it | |
1337 pass | |
28299 | 1338 self.socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
1339 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0')) |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1340 |
28298 | 1341 self.listeners = [] |
1342 self.browsers = [] | |
1343 self.services = {} | |
1344 self.servicetypes = {} | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1345 |
28298 | 1346 self.cache = DNSCache() |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1347 |
28298 | 1348 self.condition = threading.Condition() |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1349 |
28298 | 1350 self.engine = Engine(self) |
1351 self.listener = Listener(self) | |
1352 self.reaper = Reaper(self) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1353 |
28298 | 1354 def isLoopback(self): |
1355 return self.intf.startswith("127.0.0.1") | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1356 |
28298 | 1357 def isLinklocal(self): |
1358 return self.intf.startswith("169.254.") | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1359 |
28298 | 1360 def wait(self, timeout): |
1361 """Calling thread waits for a given number of milliseconds or | |
1362 until notified.""" | |
1363 self.condition.acquire() | |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1364 self.condition.wait(timeout / 1000) |
28298 | 1365 self.condition.release() |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1366 |
28298 | 1367 def notifyAll(self): |
1368 """Notifies all waiting threads""" | |
1369 self.condition.acquire() | |
1370 self.condition.notifyAll() | |
1371 self.condition.release() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1372 |
28298 | 1373 def getServiceInfo(self, type, name, timeout=3000): |
1374 """Returns network's service information for a particular | |
1375 name and type, or None if no service matches by the timeout, | |
1376 which defaults to 3 seconds.""" | |
1377 info = ServiceInfo(type, name) | |
1378 if info.request(self, timeout): | |
1379 return info | |
1380 return None | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1381 |
28298 | 1382 def addServiceListener(self, type, listener): |
1383 """Adds a listener for a particular service type. This object | |
1384 will then have its updateRecord method called when information | |
1385 arrives for that type.""" | |
1386 self.removeServiceListener(listener) | |
1387 self.browsers.append(ServiceBrowser(self, type, listener)) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1388 |
28298 | 1389 def removeServiceListener(self, listener): |
1390 """Removes a listener from the set that is currently listening.""" | |
1391 for browser in self.browsers: | |
1392 if browser.listener == listener: | |
1393 browser.cancel() | |
28301
fd8a4d2d6541
zeroconf: del is not a function
timeless <timeless@mozdev.org>
parents:
28300
diff
changeset
|
1394 del browser |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1395 |
28298 | 1396 def registerService(self, info, ttl=_DNS_TTL): |
1397 """Registers service information to the network with a default TTL | |
1398 of 60 seconds. Zeroconf will then respond to requests for | |
1399 information for that service. The name of the service may be | |
1400 changed if needed to make it unique on the network.""" | |
1401 self.checkService(info) | |
1402 self.services[info.name.lower()] = info | |
28421
6d72cc613fc4
zeroconf: replace has_key with in
timeless <timeless@mozdev.org>
parents:
28420
diff
changeset
|
1403 if info.type in self.servicetypes: |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1404 self.servicetypes[info.type] += 1 |
28298 | 1405 else: |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1406 self.servicetypes[info.type] = 1 |
28298 | 1407 now = currentTimeMillis() |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1408 nexttime = now |
28298 | 1409 i = 0 |
1410 while i < 3: | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1411 if now < nexttime: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1412 self.wait(nexttime - now) |
28298 | 1413 now = currentTimeMillis() |
1414 continue | |
1415 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
28299 | 1416 out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, |
1417 _CLASS_IN, ttl, info.name), 0) | |
1418 out.addAnswerAtTime( | |
1419 DNSService( | |
1420 info.name, _TYPE_SRV, | |
1421 _CLASS_IN, ttl, info.priority, info.weight, info.port, | |
1422 info.server), | |
1423 0) | |
1424 out.addAnswerAtTime( | |
1425 DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), | |
1426 0) | |
28298 | 1427 if info.address: |
28299 | 1428 out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, |
1429 _CLASS_IN, ttl, info.address), 0) | |
28298 | 1430 self.send(out) |
1431 i += 1 | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1432 nexttime += _REGISTER_TIME |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1433 |
28298 | 1434 def unregisterService(self, info): |
1435 """Unregister a service.""" | |
1436 try: | |
28301
fd8a4d2d6541
zeroconf: del is not a function
timeless <timeless@mozdev.org>
parents:
28300
diff
changeset
|
1437 del self.services[info.name.lower()] |
28300
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1438 if self.servicetypes[info.type] > 1: |
15c5f50e7e13
zeroconf: add whitespace around operator
timeless <timeless@mozdev.org>
parents:
28299
diff
changeset
|
1439 self.servicetypes[info.type] -= 1 |
28298 | 1440 else: |
1441 del self.servicetypes[info.type] | |
1442 except KeyError: | |
1443 pass | |
1444 now = currentTimeMillis() | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1445 nexttime = now |
28298 | 1446 i = 0 |
1447 while i < 3: | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1448 if now < nexttime: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1449 self.wait(nexttime - now) |
28298 | 1450 now = currentTimeMillis() |
1451 continue | |
1452 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
28299 | 1453 out.addAnswerAtTime( |
1454 DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0) | |
1455 out.addAnswerAtTime( | |
1456 DNSService(info.name, _TYPE_SRV, | |
1457 _CLASS_IN, 0, info.priority, info.weight, info.port, | |
1458 info.name), | |
1459 0) | |
1460 out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, | |
1461 _CLASS_IN, 0, info.text), 0) | |
28298 | 1462 if info.address: |
28299 | 1463 out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, |
1464 _CLASS_IN, 0, info.address), 0) | |
28298 | 1465 self.send(out) |
1466 i += 1 | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1467 nexttime += _UNREGISTER_TIME |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1468 |
28298 | 1469 def unregisterAllServices(self): |
1470 """Unregister all registered services.""" | |
1471 if len(self.services) > 0: | |
1472 now = currentTimeMillis() | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1473 nexttime = now |
28298 | 1474 i = 0 |
1475 while i < 3: | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1476 if now < nexttime: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1477 self.wait(nexttime - now) |
28298 | 1478 now = currentTimeMillis() |
1479 continue | |
1480 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
1481 for info in self.services.values(): | |
28299 | 1482 out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, |
1483 _CLASS_IN, 0, info.name), 0) | |
1484 out.addAnswerAtTime( | |
1485 DNSService(info.name, _TYPE_SRV, | |
1486 _CLASS_IN, 0, info.priority, info.weight, | |
1487 info.port, info.server), | |
1488 0) | |
1489 out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, | |
1490 _CLASS_IN, 0, info.text), 0) | |
28298 | 1491 if info.address: |
28299 | 1492 out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, |
1493 _CLASS_IN, 0, info.address), 0) | |
28298 | 1494 self.send(out) |
1495 i += 1 | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1496 nexttime += _UNREGISTER_TIME |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1497 |
28298 | 1498 def checkService(self, info): |
1499 """Checks the network for a unique service name, modifying the | |
1500 ServiceInfo passed in if it is not unique.""" | |
1501 now = currentTimeMillis() | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1502 nexttime = now |
28298 | 1503 i = 0 |
1504 while i < 3: | |
1505 for record in self.cache.entriesWithName(info.type): | |
28299 | 1506 if (record.type == _TYPE_PTR and not record.isExpired(now) and |
1507 record.alias == info.name): | |
28298 | 1508 if (info.name.find('.') < 0): |
28299 | 1509 info.name = ("%w.[%s:%d].%s" % |
1510 (info.name, info.address, info.port, info.type)) | |
28298 | 1511 self.checkService(info) |
1512 return | |
1513 raise NonUniqueNameException | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1514 if now < nexttime: |
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1515 self.wait(nexttime - now) |
28298 | 1516 now = currentTimeMillis() |
1517 continue | |
1518 out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA) | |
1519 self.debug = out | |
1520 out.addQuestion(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN)) | |
28299 | 1521 out.addAuthoritativeAnswer(DNSPointer(info.type, _TYPE_PTR, |
1522 _CLASS_IN, _DNS_TTL, info.name)) | |
28298 | 1523 self.send(out) |
1524 i += 1 | |
28419
eb9d0e828c30
zeroconf: remove camelcase in identifiers
timeless <timeless@mozdev.org>
parents:
28302
diff
changeset
|
1525 nexttime += _CHECK_TIME |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1526 |
28298 | 1527 def addListener(self, listener, question): |
1528 """Adds a listener for a given question. The listener will have | |
1529 its updateRecord method called when information is available to | |
1530 answer the question.""" | |
1531 now = currentTimeMillis() | |
1532 self.listeners.append(listener) | |
1533 if question is not None: | |
1534 for record in self.cache.entriesWithName(question.name): | |
1535 if question.answeredBy(record) and not record.isExpired(now): | |
1536 listener.updateRecord(self, now, record) | |
1537 self.notifyAll() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1538 |
28298 | 1539 def removeListener(self, listener): |
1540 """Removes a listener.""" | |
1541 try: | |
1542 self.listeners.remove(listener) | |
1543 self.notifyAll() | |
1544 except Exception: | |
1545 pass | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1546 |
28298 | 1547 def updateRecord(self, now, rec): |
1548 """Used to notify listeners of new information that has updated | |
1549 a record.""" | |
1550 for listener in self.listeners: | |
1551 listener.updateRecord(self, now, rec) | |
1552 self.notifyAll() | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1553 |
28298 | 1554 def handleResponse(self, msg): |
1555 """Deal with incoming response packets. All answers | |
1556 are held in the cache, and listeners are notified.""" | |
1557 now = currentTimeMillis() | |
1558 for record in msg.answers: | |
1559 expired = record.isExpired(now) | |
1560 if record in self.cache.entries(): | |
1561 if expired: | |
1562 self.cache.remove(record) | |
1563 else: | |
1564 entry = self.cache.get(record) | |
1565 if entry is not None: | |
1566 entry.resetTTL(record) | |
1567 record = entry | |
1568 else: | |
1569 self.cache.add(record) | |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1570 |
28298 | 1571 self.updateRecord(now, record) |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1572 |
28298 | 1573 def handleQuery(self, msg, addr, port): |
1574 """Deal with incoming query packets. Provides a response if | |
1575 possible.""" | |
1576 out = None | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1577 |
28298 | 1578 # Support unicast client responses |
1579 # | |
1580 if port != _MDNS_PORT: | |
1581 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, 0) | |
1582 for question in msg.questions: | |
1583 out.addQuestion(question) | |
7874
d812029cda85
cleanup: drop variables for unused return values
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7071
diff
changeset
|
1584 |
28298 | 1585 for question in msg.questions: |
1586 if question.type == _TYPE_PTR: | |
1587 if question.name == "_services._dns-sd._udp.local.": | |
1588 for stype in self.servicetypes.keys(): | |
1589 if out is None: | |
1590 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
28299 | 1591 out.addAnswer(msg, |
1592 DNSPointer( | |
1593 "_services._dns-sd._udp.local.", | |
1594 _TYPE_PTR, _CLASS_IN, | |
1595 _DNS_TTL, stype)) | |
28298 | 1596 for service in self.services.values(): |
1597 if question.name == service.type: | |
1598 if out is None: | |
1599 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
28299 | 1600 out.addAnswer(msg, DNSPointer(service.type, _TYPE_PTR, |
1601 _CLASS_IN, _DNS_TTL, service.name)) | |
28298 | 1602 else: |
1603 try: | |
1604 if out is None: | |
1605 out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA) | |
7874
d812029cda85
cleanup: drop variables for unused return values
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7071
diff
changeset
|
1606 |
28298 | 1607 # Answer A record queries for any service addresses we know |
1608 if question.type == _TYPE_A or question.type == _TYPE_ANY: | |
1609 for service in self.services.values(): | |
1610 if service.server == question.name.lower(): | |
28299 | 1611 out.addAnswer(msg, |
1612 DNSAddress(question.name, _TYPE_A, | |
1613 _CLASS_IN | _CLASS_UNIQUE, | |
1614 _DNS_TTL, service.address)) | |
7874
d812029cda85
cleanup: drop variables for unused return values
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7071
diff
changeset
|
1615 |
28298 | 1616 service = self.services.get(question.name.lower(), None) |
35629
31451f3f4b56
style: remove multiple statement on a single line in zeroconf
Boris Feld <boris.feld@octobus.net>
parents:
34447
diff
changeset
|
1617 if not service: |
31451f3f4b56
style: remove multiple statement on a single line in zeroconf
Boris Feld <boris.feld@octobus.net>
parents:
34447
diff
changeset
|
1618 continue |
7874
d812029cda85
cleanup: drop variables for unused return values
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7071
diff
changeset
|
1619 |
28299 | 1620 if (question.type == _TYPE_SRV or |
1621 question.type == _TYPE_ANY): | |
1622 out.addAnswer(msg, | |
1623 DNSService(question.name, _TYPE_SRV, | |
1624 _CLASS_IN | _CLASS_UNIQUE, | |
1625 _DNS_TTL, service.priority, | |
1626 service.weight, service.port, | |
1627 service.server)) | |
1628 if (question.type == _TYPE_TXT or | |
1629 question.type == _TYPE_ANY): | |
1630 out.addAnswer(msg, DNSText(question.name, _TYPE_TXT, | |
1631 _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.text)) | |
28298 | 1632 if question.type == _TYPE_SRV: |
28299 | 1633 out.addAdditionalAnswer( |
1634 DNSAddress(service.server, _TYPE_A, | |
1635 _CLASS_IN | _CLASS_UNIQUE, | |
1636 _DNS_TTL, service.address)) | |
28298 | 1637 except Exception: |
1638 traceback.print_exc() | |
7874
d812029cda85
cleanup: drop variables for unused return values
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7071
diff
changeset
|
1639 |
28298 | 1640 if out is not None and out.answers: |
1641 out.id = msg.id | |
1642 self.send(out, addr, port) | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1643 |
28302
e96a3ae025ed
zeroconf: remove whitespace around = for named parameters
timeless <timeless@mozdev.org>
parents:
28301
diff
changeset
|
1644 def send(self, out, addr=_MDNS_ADDR, port=_MDNS_PORT): |
28298 | 1645 """Sends an outgoing packet.""" |
1646 # This is a quick test to see if we can parse the packets we generate | |
1647 #temp = DNSIncoming(out.packet()) | |
1648 try: | |
1649 self.socket.sendto(out.packet(), 0, (addr, port)) | |
1650 except Exception: | |
1651 # Ignore this, it may be a temporary loss of network connection | |
1652 pass | |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1653 |
28298 | 1654 def close(self): |
1655 """Ends the background threads, and prevent this instance from | |
1656 servicing further queries.""" | |
1657 if globals()['_GLOBAL_DONE'] == 0: | |
1658 globals()['_GLOBAL_DONE'] = 1 | |
1659 self.notifyAll() | |
1660 self.engine.notify() | |
1661 self.unregisterAllServices() | |
28299 | 1662 self.socket.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, |
41519
a36f462cf533
zeroconf: Python 3 porting of vendored library
Gregory Szorc <gregory.szorc@gmail.com>
parents:
41365
diff
changeset
|
1663 socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(r'0.0.0.0')) |
28298 | 1664 self.socket.close() |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1665 |
7071
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1666 # Test a few module features, including service registration, service |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1667 # query (for Zoe), and service unregistration. |
643c751e60b2
zeroconf: initial implementation
Matt Mackall <mpm@selenic.com>
parents:
diff
changeset
|
1668 |
7877
eba7f12b0c51
cleanup: whitespace cleanup
Peter Arrenbrecht <peter.arrenbrecht@gmail.com>
parents:
7874
diff
changeset
|
1669 if __name__ == '__main__': |
28298 | 1670 print("Multicast DNS Service Discovery for Python, version", __version__) |
1671 r = Zeroconf() | |
1672 print("1. Testing registration of a service...") | |
1673 desc = {'version':'0.10','a':'test value', 'b':'another value'} | |
28299 | 1674 info = ServiceInfo("_http._tcp.local.", |
1675 "My Service Name._http._tcp.local.", | |
1676 socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc) | |
28298 | 1677 print(" Registering service...") |
1678 r.registerService(info) | |
1679 print(" Registration done.") | |
1680 print("2. Testing query of service information...") | |
28299 | 1681 print(" Getting ZOE service:", |
1682 str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))) | |
28298 | 1683 print(" Query done.") |
1684 print("3. Testing query of own service...") | |
28299 | 1685 print(" Getting self:", |
1686 str(r.getServiceInfo("_http._tcp.local.", | |
1687 "My Service Name._http._tcp.local."))) | |
28298 | 1688 print(" Query done.") |
1689 print("4. Testing unregister of service information...") | |
1690 r.unregisterService(info) | |
1691 print(" Unregister done.") | |
1692 r.close() |