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