1
0

Zeroconf.py 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  1. """ Multicast DNS Service Discovery for Python, v0.12
  2. Copyright (C) 2003, Paul Scott-Murphy
  3. This module provides a framework for the use of DNS Service Discovery
  4. using IP multicast. It has been tested against the JRendezvous
  5. implementation from <a href="http://strangeberry.com">StrangeBerry</a>,
  6. and against the mDNSResponder from Mac OS X 10.3.8.
  7. This library is free software; you can redistribute it and/or
  8. modify it under the terms of the GNU Lesser General Public
  9. License as published by the Free Software Foundation; either
  10. version 2.1 of the License, or (at your option) any later version.
  11. This library is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. Lesser General Public License for more details.
  15. You should have received a copy of the GNU Lesser General Public
  16. License along with this library; if not, write to the Free Software
  17. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  18. """
  19. """0.12 update - allow selection of binding interface
  20. typo fix - Thanks A. M. Kuchlingi
  21. removed all use of word 'Rendezvous' - this is an API change"""
  22. """0.11 update - correction to comments for addListener method
  23. support for new record types seen from OS X
  24. - IPv6 address
  25. - hostinfo
  26. ignore unknown DNS record types
  27. fixes to name decoding
  28. works alongside other processes using port 5353 (e.g. on Mac OS X)
  29. tested against Mac OS X 10.3.2's mDNSResponder
  30. corrections to removal of list entries for service browser"""
  31. """0.10 update - Jonathon Paisley contributed these corrections:
  32. always multicast replies, even when query is unicast
  33. correct a pointer encoding problem
  34. can now write records in any order
  35. traceback shown on failure
  36. better TXT record parsing
  37. server is now separate from name
  38. can cancel a service browser
  39. modified some unit tests to accommodate these changes"""
  40. """0.09 update - remove all records on service unregistration
  41. fix DOS security problem with readName"""
  42. """0.08 update - changed licensing to LGPL"""
  43. """0.07 update - faster shutdown on engine
  44. pointer encoding of outgoing names
  45. ServiceBrowser now works
  46. new unit tests"""
  47. """0.06 update - small improvements with unit tests
  48. added defined exception types
  49. new style objects
  50. fixed hostname/interface problem
  51. fixed socket timeout problem
  52. fixed addServiceListener() typo bug
  53. using select() for socket reads
  54. tested on Debian unstable with Python 2.2.2"""
  55. """0.05 update - ensure case insensitivty on domain names
  56. support for unicast DNS queries"""
  57. """0.04 update - added some unit tests
  58. added __ne__ adjuncts where required
  59. ensure names end in '.local.'
  60. timeout on receiving socket for clean shutdown"""
  61. __author__ = "Paul Scott-Murphy"
  62. __email__ = "paul at scott dash murphy dot com"
  63. __version__ = "0.12"
  64. import string
  65. import time
  66. import struct
  67. import socket
  68. import threading
  69. import select
  70. import traceback
  71. __all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
  72. # hook for threads
  73. globals()['_GLOBAL_DONE'] = 0
  74. # Some timing constants
  75. _UNREGISTER_TIME = 125
  76. _CHECK_TIME = 175
  77. _REGISTER_TIME = 225
  78. _LISTENER_TIME = 200
  79. _BROWSER_TIME = 500
  80. # Some DNS constants
  81. _MDNS_ADDR = '224.0.0.251'
  82. _MDNS_PORT = 5353;
  83. _DNS_PORT = 53;
  84. _DNS_TTL = 60 * 60; # one hour default TTL
  85. _MAX_MSG_TYPICAL = 1460 # unused
  86. _MAX_MSG_ABSOLUTE = 8972
  87. _FLAGS_QR_MASK = 0x8000 # query response mask
  88. _FLAGS_QR_QUERY = 0x0000 # query
  89. _FLAGS_QR_RESPONSE = 0x8000 # response
  90. _FLAGS_AA = 0x0400 # Authorative answer
  91. _FLAGS_TC = 0x0200 # Truncated
  92. _FLAGS_RD = 0x0100 # Recursion desired
  93. _FLAGS_RA = 0x8000 # Recursion available
  94. _FLAGS_Z = 0x0040 # Zero
  95. _FLAGS_AD = 0x0020 # Authentic data
  96. _FLAGS_CD = 0x0010 # Checking disabled
  97. _CLASS_IN = 1
  98. _CLASS_CS = 2
  99. _CLASS_CH = 3
  100. _CLASS_HS = 4
  101. _CLASS_NONE = 254
  102. _CLASS_ANY = 255
  103. _CLASS_MASK = 0x7FFF
  104. _CLASS_UNIQUE = 0x8000
  105. _TYPE_A = 1
  106. _TYPE_NS = 2
  107. _TYPE_MD = 3
  108. _TYPE_MF = 4
  109. _TYPE_CNAME = 5
  110. _TYPE_SOA = 6
  111. _TYPE_MB = 7
  112. _TYPE_MG = 8
  113. _TYPE_MR = 9
  114. _TYPE_NULL = 10
  115. _TYPE_WKS = 11
  116. _TYPE_PTR = 12
  117. _TYPE_HINFO = 13
  118. _TYPE_MINFO = 14
  119. _TYPE_MX = 15
  120. _TYPE_TXT = 16
  121. _TYPE_AAAA = 28
  122. _TYPE_SRV = 33
  123. _TYPE_ANY = 255
  124. # Mapping constants to names
  125. _CLASSES = { _CLASS_IN : "in",
  126. _CLASS_CS : "cs",
  127. _CLASS_CH : "ch",
  128. _CLASS_HS : "hs",
  129. _CLASS_NONE : "none",
  130. _CLASS_ANY : "any" }
  131. _TYPES = { _TYPE_A : "a",
  132. _TYPE_NS : "ns",
  133. _TYPE_MD : "md",
  134. _TYPE_MF : "mf",
  135. _TYPE_CNAME : "cname",
  136. _TYPE_SOA : "soa",
  137. _TYPE_MB : "mb",
  138. _TYPE_MG : "mg",
  139. _TYPE_MR : "mr",
  140. _TYPE_NULL : "null",
  141. _TYPE_WKS : "wks",
  142. _TYPE_PTR : "ptr",
  143. _TYPE_HINFO : "hinfo",
  144. _TYPE_MINFO : "minfo",
  145. _TYPE_MX : "mx",
  146. _TYPE_TXT : "txt",
  147. _TYPE_AAAA : "quada",
  148. _TYPE_SRV : "srv",
  149. _TYPE_ANY : "any" }
  150. # utility functions
  151. def currentTimeMillis():
  152. """Current system time in milliseconds"""
  153. return time.time() * 1000
  154. # Exceptions
  155. class NonLocalNameException(Exception):
  156. pass
  157. class NonUniqueNameException(Exception):
  158. pass
  159. class NamePartTooLongException(Exception):
  160. pass
  161. class AbstractMethodException(Exception):
  162. pass
  163. class BadTypeInNameException(Exception):
  164. pass
  165. # implementation classes
  166. class DNSEntry(object):
  167. """A DNS entry"""
  168. def __init__(self, name, type, clazz):
  169. self.key = string.lower(name)
  170. self.name = name
  171. self.type = type
  172. self.clazz = clazz & _CLASS_MASK
  173. self.unique = (clazz & _CLASS_UNIQUE) != 0
  174. def __eq__(self, other):
  175. """Equality test on name, type, and class"""
  176. if isinstance(other, DNSEntry):
  177. return self.name == other.name and self.type == other.type and self.clazz == other.clazz
  178. return 0
  179. def __ne__(self, other):
  180. """Non-equality test"""
  181. return not self.__eq__(other)
  182. def getClazz(self, clazz):
  183. """Class accessor"""
  184. try:
  185. return _CLASSES[clazz]
  186. except:
  187. return "?(%s)" % (clazz)
  188. def getType(self, type):
  189. """Type accessor"""
  190. try:
  191. return _TYPES[type]
  192. except:
  193. return "?(%s)" % (type)
  194. def toString(self, hdr, other):
  195. """String representation with additional information"""
  196. result = "%s[%s,%s" % (hdr, self.getType(self.type), self.getClazz(self.clazz))
  197. if self.unique:
  198. result += "-unique,"
  199. else:
  200. result += ","
  201. result += self.name
  202. if other is not None:
  203. result += ",%s]" % (other)
  204. else:
  205. result += "]"
  206. return result
  207. class DNSQuestion(DNSEntry):
  208. """A DNS question entry"""
  209. def __init__(self, name, type, clazz):
  210. if not name.endswith(".local."):
  211. raise NonLocalNameException
  212. DNSEntry.__init__(self, name, type, clazz)
  213. def answeredBy(self, rec):
  214. """Returns true if the question is answered by the record"""
  215. return self.clazz == rec.clazz and (self.type == rec.type or self.type == _TYPE_ANY) and self.name == rec.name
  216. def __repr__(self):
  217. """String representation"""
  218. return DNSEntry.toString(self, "question", None)
  219. class DNSRecord(DNSEntry):
  220. """A DNS record - like a DNS entry, but has a TTL"""
  221. def __init__(self, name, type, clazz, ttl):
  222. DNSEntry.__init__(self, name, type, clazz)
  223. self.ttl = ttl
  224. self.created = currentTimeMillis()
  225. def __eq__(self, other):
  226. """Tests equality as per DNSRecord"""
  227. if isinstance(other, DNSRecord):
  228. return DNSEntry.__eq__(self, other)
  229. return 0
  230. def suppressedBy(self, msg):
  231. """Returns true if any answer in a message can suffice for the
  232. information held in this record."""
  233. for record in msg.answers:
  234. if self.suppressedByAnswer(record):
  235. return 1
  236. return 0
  237. def suppressedByAnswer(self, other):
  238. """Returns true if another record has same name, type and class,
  239. and if its TTL is at least half of this record's."""
  240. if self == other and other.ttl > (self.ttl / 2):
  241. return 1
  242. return 0
  243. def getExpirationTime(self, percent):
  244. """Returns the time at which this record will have expired
  245. by a certain percentage."""
  246. return self.created + (percent * self.ttl * 10)
  247. def getRemainingTTL(self, now):
  248. """Returns the remaining TTL in seconds."""
  249. return max(0, (self.getExpirationTime(100) - now) / 1000)
  250. def isExpired(self, now):
  251. """Returns true if this record has expired."""
  252. return self.getExpirationTime(100) <= now
  253. def isStale(self, now):
  254. """Returns true if this record is at least half way expired."""
  255. return self.getExpirationTime(50) <= now
  256. def resetTTL(self, other):
  257. """Sets this record's TTL and created time to that of
  258. another record."""
  259. self.created = other.created
  260. self.ttl = other.ttl
  261. def write(self, out):
  262. """Abstract method"""
  263. raise AbstractMethodException
  264. def toString(self, other):
  265. """String representation with addtional information"""
  266. arg = "%s/%s,%s" % (self.ttl, self.getRemainingTTL(currentTimeMillis()), other)
  267. return DNSEntry.toString(self, "record", arg)
  268. class DNSAddress(DNSRecord):
  269. """A DNS address record"""
  270. def __init__(self, name, type, clazz, ttl, address):
  271. DNSRecord.__init__(self, name, type, clazz, ttl)
  272. self.address = address
  273. def write(self, out):
  274. """Used in constructing an outgoing packet"""
  275. out.writeString(self.address, len(self.address))
  276. def __eq__(self, other):
  277. """Tests equality on address"""
  278. if isinstance(other, DNSAddress):
  279. return self.address == other.address
  280. return 0
  281. def __repr__(self):
  282. """String representation"""
  283. try:
  284. return socket.inet_ntoa(self.address)
  285. except:
  286. return self.address
  287. class DNSHinfo(DNSRecord):
  288. """A DNS host information record"""
  289. def __init__(self, name, type, clazz, ttl, cpu, os):
  290. DNSRecord.__init__(self, name, type, clazz, ttl)
  291. self.cpu = cpu
  292. self.os = os
  293. def write(self, out):
  294. """Used in constructing an outgoing packet"""
  295. out.writeString(self.cpu, len(self.cpu))
  296. out.writeString(self.os, len(self.os))
  297. def __eq__(self, other):
  298. """Tests equality on cpu and os"""
  299. if isinstance(other, DNSHinfo):
  300. return self.cpu == other.cpu and self.os == other.os
  301. return 0
  302. def __repr__(self):
  303. """String representation"""
  304. return self.cpu + " " + self.os
  305. class DNSPointer(DNSRecord):
  306. """A DNS pointer record"""
  307. def __init__(self, name, type, clazz, ttl, alias):
  308. DNSRecord.__init__(self, name, type, clazz, ttl)
  309. self.alias = alias
  310. def write(self, out):
  311. """Used in constructing an outgoing packet"""
  312. out.writeName(self.alias)
  313. def __eq__(self, other):
  314. """Tests equality on alias"""
  315. if isinstance(other, DNSPointer):
  316. return self.alias == other.alias
  317. return 0
  318. def __repr__(self):
  319. """String representation"""
  320. return self.toString(self.alias)
  321. class DNSText(DNSRecord):
  322. """A DNS text record"""
  323. def __init__(self, name, type, clazz, ttl, text):
  324. DNSRecord.__init__(self, name, type, clazz, ttl)
  325. self.text = text
  326. def write(self, out):
  327. """Used in constructing an outgoing packet"""
  328. out.writeString(self.text, len(self.text))
  329. def __eq__(self, other):
  330. """Tests equality on text"""
  331. if isinstance(other, DNSText):
  332. return self.text == other.text
  333. return 0
  334. def __repr__(self):
  335. """String representation"""
  336. if len(self.text) > 10:
  337. return self.toString(self.text[:7] + "...")
  338. else:
  339. return self.toString(self.text)
  340. class DNSService(DNSRecord):
  341. """A DNS service record"""
  342. def __init__(self, name, type, clazz, ttl, priority, weight, port, server):
  343. DNSRecord.__init__(self, name, type, clazz, ttl)
  344. self.priority = priority
  345. self.weight = weight
  346. self.port = port
  347. self.server = server
  348. def write(self, out):
  349. """Used in constructing an outgoing packet"""
  350. out.writeShort(self.priority)
  351. out.writeShort(self.weight)
  352. out.writeShort(self.port)
  353. out.writeName(self.server)
  354. def __eq__(self, other):
  355. """Tests equality on priority, weight, port and server"""
  356. if isinstance(other, DNSService):
  357. return self.priority == other.priority and self.weight == other.weight and self.port == other.port and self.server == other.server
  358. return 0
  359. def __repr__(self):
  360. """String representation"""
  361. return self.toString("%s:%s" % (self.server, self.port))
  362. class DNSIncoming(object):
  363. """Object representation of an incoming DNS packet"""
  364. def __init__(self, data):
  365. """Constructor from string holding bytes of packet"""
  366. self.offset = 0
  367. self.data = data
  368. self.questions = []
  369. self.answers = []
  370. self.numQuestions = 0
  371. self.numAnswers = 0
  372. self.numAuthorities = 0
  373. self.numAdditionals = 0
  374. self.readHeader()
  375. self.readQuestions()
  376. self.readOthers()
  377. def readHeader(self):
  378. """Reads header portion of packet"""
  379. format = '!HHHHHH'
  380. length = struct.calcsize(format)
  381. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  382. self.offset += length
  383. self.id = info[0]
  384. self.flags = info[1]
  385. self.numQuestions = info[2]
  386. self.numAnswers = info[3]
  387. self.numAuthorities = info[4]
  388. self.numAdditionals = info[5]
  389. def readQuestions(self):
  390. """Reads questions section of packet"""
  391. format = '!HH'
  392. length = struct.calcsize(format)
  393. for i in xrange(self.numQuestions):
  394. name = self.readName()
  395. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  396. self.offset += length
  397. try:
  398. question = DNSQuestion(name, info[0], info[1])
  399. self.questions.append(question)
  400. except NonLocalNameException:
  401. # invalid question ?
  402. pass
  403. def readInt(self):
  404. """Reads an integer from the packet"""
  405. format = '!I'
  406. length = struct.calcsize(format)
  407. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  408. self.offset += length
  409. return info[0]
  410. def readCharacterString(self):
  411. """Reads a character string from the packet"""
  412. length = ord(self.data[self.offset])
  413. self.offset += 1
  414. return self.readString(length)
  415. def readString(self, len):
  416. """Reads a string of a given length from the packet"""
  417. format = '!' + str(len) + 's'
  418. length = struct.calcsize(format)
  419. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  420. self.offset += length
  421. return info[0]
  422. def readUnsignedShort(self):
  423. """Reads an unsigned short from the packet"""
  424. format = '!H'
  425. length = struct.calcsize(format)
  426. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  427. self.offset += length
  428. return info[0]
  429. def readOthers(self):
  430. """Reads the answers, authorities and additionals section of the packet"""
  431. format = '!HHiH'
  432. length = struct.calcsize(format)
  433. n = self.numAnswers + self.numAuthorities + self.numAdditionals
  434. for i in xrange(n):
  435. domain = self.readName()
  436. info = struct.unpack(format, self.data[self.offset:self.offset+length])
  437. self.offset += length
  438. rec = None
  439. if info[0] == _TYPE_A:
  440. rec = DNSAddress(domain, info[0], info[1], info[2], self.readString(4))
  441. elif info[0] == _TYPE_CNAME or info[0] == _TYPE_PTR:
  442. rec = DNSPointer(domain, info[0], info[1], info[2], self.readName())
  443. elif info[0] == _TYPE_TXT:
  444. rec = DNSText(domain, info[0], info[1], info[2], self.readString(info[3]))
  445. elif info[0] == _TYPE_SRV:
  446. rec = DNSService(domain, info[0], info[1], info[2], self.readUnsignedShort(), self.readUnsignedShort(), self.readUnsignedShort(), self.readName())
  447. elif info[0] == _TYPE_HINFO:
  448. rec = DNSHinfo(domain, info[0], info[1], info[2], self.readCharacterString(), self.readCharacterString())
  449. elif info[0] == _TYPE_AAAA:
  450. rec = DNSAddress(domain, info[0], info[1], info[2], self.readString(16))
  451. else:
  452. # Try to ignore types we don't know about
  453. # this may mean the rest of the name is
  454. # unable to be parsed, and may show errors
  455. # so this is left for debugging. New types
  456. # encountered need to be parsed properly.
  457. #
  458. #print "UNKNOWN TYPE = " + str(info[0])
  459. #raise BadTypeInNameException
  460. pass
  461. if rec is not None:
  462. self.answers.append(rec)
  463. def isQuery(self):
  464. """Returns true if this is a query"""
  465. return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_QUERY
  466. def isResponse(self):
  467. """Returns true if this is a response"""
  468. return (self.flags & _FLAGS_QR_MASK) == _FLAGS_QR_RESPONSE
  469. def readUTF(self, offset, len):
  470. """Reads a UTF-8 string of a given length from the packet"""
  471. result = self.data[offset:offset+len].decode('utf-8')
  472. return result
  473. def readName(self):
  474. """Reads a domain name from the packet"""
  475. result = ''
  476. off = self.offset
  477. next = -1
  478. first = off
  479. while 1:
  480. len = ord(self.data[off])
  481. off += 1
  482. if len == 0:
  483. break
  484. t = len & 0xC0
  485. if t == 0x00:
  486. result = ''.join((result, self.readUTF(off, len) + '.'))
  487. off += len
  488. elif t == 0xC0:
  489. if next < 0:
  490. next = off + 1
  491. off = ((len & 0x3F) << 8) | ord(self.data[off])
  492. if off >= first:
  493. raise "Bad domain name (circular) at " + str(off)
  494. first = off
  495. else:
  496. raise "Bad domain name at " + str(off)
  497. if next >= 0:
  498. self.offset = next
  499. else:
  500. self.offset = off
  501. return result
  502. class DNSOutgoing(object):
  503. """Object representation of an outgoing packet"""
  504. def __init__(self, flags, multicast = 1):
  505. self.finished = 0
  506. self.id = 0
  507. self.multicast = multicast
  508. self.flags = flags
  509. self.names = {}
  510. self.data = []
  511. self.size = 12
  512. self.questions = []
  513. self.answers = []
  514. self.authorities = []
  515. self.additionals = []
  516. def addQuestion(self, record):
  517. """Adds a question"""
  518. self.questions.append(record)
  519. def addAnswer(self, inp, record):
  520. """Adds an answer"""
  521. if not record.suppressedBy(inp):
  522. self.addAnswerAtTime(record, 0)
  523. def addAnswerAtTime(self, record, now):
  524. """Adds an answer if if does not expire by a certain time"""
  525. if record is not None:
  526. if now == 0 or not record.isExpired(now):
  527. self.answers.append((record, now))
  528. def addAuthorativeAnswer(self, record):
  529. """Adds an authoritative answer"""
  530. self.authorities.append(record)
  531. def addAdditionalAnswer(self, record):
  532. """Adds an additional answer"""
  533. self.additionals.append(record)
  534. def writeByte(self, value):
  535. """Writes a single byte to the packet"""
  536. format = '!c'
  537. self.data.append(struct.pack(format, chr(value)))
  538. self.size += 1
  539. def insertShort(self, index, value):
  540. """Inserts an unsigned short in a certain position in the packet"""
  541. format = '!H'
  542. self.data.insert(index, struct.pack(format, int(value)))
  543. self.size += struct.calcsize(format)
  544. def writeShort(self, value):
  545. """Writes an unsigned short to the packet"""
  546. format = '!H'
  547. self.data.append(struct.pack(format, int(value)))
  548. self.size += struct.calcsize(format)
  549. def writeInt(self, value):
  550. """Writes an unsigned integer to the packet"""
  551. format = '!I'
  552. self.data.append(struct.pack(format, int(value)))
  553. self.size += struct.calcsize(format)
  554. def writeString(self, value, length):
  555. """Writes a string to the packet"""
  556. format = '!' + str(length) + 's'
  557. self.data.append(struct.pack(format, value))
  558. self.size += struct.calcsize(format)
  559. def writeUTF(self, s):
  560. """Writes a UTF-8 string of a given length to the packet"""
  561. utfstr = s.encode('utf-8')
  562. length = len(utfstr)
  563. if length > 64:
  564. raise NamePartTooLongException
  565. self.writeByte(length)
  566. self.writeString(utfstr, length)
  567. def writeName(self, name):
  568. """Writes a domain name to the packet"""
  569. try:
  570. # Find existing instance of this name in packet
  571. #
  572. index = self.names[name]
  573. except KeyError:
  574. # No record of this name already, so write it
  575. # out as normal, recording the location of the name
  576. # for future pointers to it.
  577. #
  578. self.names[name] = self.size
  579. parts = name.split('.')
  580. if parts[-1] == '':
  581. parts = parts[:-1]
  582. for part in parts:
  583. self.writeUTF(part)
  584. self.writeByte(0)
  585. return
  586. # An index was found, so write a pointer to it
  587. #
  588. self.writeByte((index >> 8) | 0xC0)
  589. self.writeByte(index)
  590. def writeQuestion(self, question):
  591. """Writes a question to the packet"""
  592. self.writeName(question.name)
  593. self.writeShort(question.type)
  594. self.writeShort(question.clazz)
  595. def writeRecord(self, record, now):
  596. """Writes a record (answer, authoritative answer, additional) to
  597. the packet"""
  598. self.writeName(record.name)
  599. self.writeShort(record.type)
  600. if record.unique and self.multicast:
  601. self.writeShort(record.clazz | _CLASS_UNIQUE)
  602. else:
  603. self.writeShort(record.clazz)
  604. if now == 0:
  605. self.writeInt(record.ttl)
  606. else:
  607. self.writeInt(record.getRemainingTTL(now))
  608. index = len(self.data)
  609. # Adjust size for the short we will write before this record
  610. #
  611. self.size += 2
  612. record.write(self)
  613. self.size -= 2
  614. length = len(''.join(self.data[index:]))
  615. self.insertShort(index, length) # Here is the short we adjusted for
  616. def packet(self):
  617. """Returns a string containing the packet's bytes
  618. No further parts should be added to the packet once this
  619. is done."""
  620. if not self.finished:
  621. self.finished = 1
  622. for question in self.questions:
  623. self.writeQuestion(question)
  624. for answer, time in self.answers:
  625. self.writeRecord(answer, time)
  626. for authority in self.authorities:
  627. self.writeRecord(authority, 0)
  628. for additional in self.additionals:
  629. self.writeRecord(additional, 0)
  630. self.insertShort(0, len(self.additionals))
  631. self.insertShort(0, len(self.authorities))
  632. self.insertShort(0, len(self.answers))
  633. self.insertShort(0, len(self.questions))
  634. self.insertShort(0, self.flags)
  635. if self.multicast:
  636. self.insertShort(0, 0)
  637. else:
  638. self.insertShort(0, self.id)
  639. return ''.join(self.data)
  640. class DNSCache(object):
  641. """A cache of DNS entries"""
  642. def __init__(self):
  643. self.cache = {}
  644. def add(self, entry):
  645. """Adds an entry"""
  646. try:
  647. list = self.cache[entry.key]
  648. except:
  649. list = self.cache[entry.key] = []
  650. list.append(entry)
  651. def remove(self, entry):
  652. """Removes an entry"""
  653. try:
  654. list = self.cache[entry.key]
  655. list.remove(entry)
  656. except:
  657. pass
  658. def get(self, entry):
  659. """Gets an entry by key. Will return None if there is no
  660. matching entry."""
  661. try:
  662. list = self.cache[entry.key]
  663. return list[list.index(entry)]
  664. except:
  665. return None
  666. def getByDetails(self, name, type, clazz):
  667. """Gets an entry by details. Will return None if there is
  668. no matching entry."""
  669. entry = DNSEntry(name, type, clazz)
  670. return self.get(entry)
  671. def entriesWithName(self, name):
  672. """Returns a list of entries whose key matches the name."""
  673. try:
  674. return self.cache[name]
  675. except:
  676. return []
  677. def entries(self):
  678. """Returns a list of all entries"""
  679. def add(x, y): return x+y
  680. try:
  681. return reduce(add, self.cache.values())
  682. except:
  683. return []
  684. class Engine(threading.Thread):
  685. """An engine wraps read access to sockets, allowing objects that
  686. need to receive data from sockets to be called back when the
  687. sockets are ready.
  688. A reader needs a handle_read() method, which is called when the socket
  689. it is interested in is ready for reading.
  690. Writers are not implemented here, because we only send short
  691. packets.
  692. """
  693. def __init__(self, zeroconf):
  694. threading.Thread.__init__(self)
  695. self.setDaemon(True) # Added by David Harrison
  696. self.zeroconf = zeroconf
  697. self.readers = {} # maps socket to reader
  698. self.timeout = 5
  699. self.condition = threading.Condition()
  700. self.start()
  701. def run(self):
  702. while not globals()['_GLOBAL_DONE']:
  703. rs = self.getReaders()
  704. if len(rs) == 0:
  705. # No sockets to manage, but we wait for the timeout
  706. # or addition of a socket
  707. #
  708. self.condition.acquire()
  709. self.condition.wait(self.timeout)
  710. self.condition.release()
  711. else:
  712. try:
  713. rr, wr, er = select.select(rs, [], [], self.timeout)
  714. for socket in rr:
  715. try:
  716. self.readers[socket].handle_read()
  717. except socket.error, e:
  718. if e == socket.EBADF:
  719. ## what should I do here?
  720. # data, (addr, port) = self.zeroconf.socket.recvfrom(_MAX_MSG_ABSOLUTE)
  721. # File "C:\Python24\lib\socket.py", line 144, in _dummy
  722. # raise error(EBADF, 'Bad file descriptor')
  723. # error: (9, 'Bad file descriptor')
  724. pass
  725. else:
  726. traceback.print_exc()
  727. except:
  728. traceback.print_exc()
  729. except:
  730. pass
  731. def getReaders(self):
  732. result = []
  733. self.condition.acquire()
  734. result = self.readers.keys()
  735. self.condition.release()
  736. return result
  737. def addReader(self, reader, socket):
  738. self.condition.acquire()
  739. self.readers[socket] = reader
  740. self.condition.notify()
  741. self.condition.release()
  742. def delReader(self, socket):
  743. self.condition.acquire()
  744. del(self.readers[socket])
  745. self.condition.notify()
  746. self.condition.release()
  747. def notify(self):
  748. self.condition.acquire()
  749. self.condition.notify()
  750. self.condition.release()
  751. class Listener(object):
  752. """A Listener is used by this module to listen on the multicast
  753. group to which DNS messages are sent, allowing the implementation
  754. to cache information as it arrives.
  755. It requires registration with an Engine object in order to have
  756. the read() method called when a socket is availble for reading."""
  757. def __init__(self, zeroconf):
  758. self.zeroconf = zeroconf
  759. self.zeroconf.engine.addReader(self, self.zeroconf.socket)
  760. def handle_read(self):
  761. data, (addr, port) = self.zeroconf.socket.recvfrom(_MAX_MSG_ABSOLUTE)
  762. self.data = data
  763. msg = DNSIncoming(data)
  764. if msg.isQuery():
  765. # Always multicast responses
  766. #
  767. if port == _MDNS_PORT:
  768. self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT)
  769. # If it's not a multicast query, reply via unicast
  770. # and multicast
  771. #
  772. elif port == _DNS_PORT:
  773. self.zeroconf.handleQuery(msg, addr, port)
  774. self.zeroconf.handleQuery(msg, _MDNS_ADDR, _MDNS_PORT)
  775. else:
  776. self.zeroconf.handleResponse(msg)
  777. class Reaper(threading.Thread):
  778. """A Reaper is used by this module to remove cache entries that
  779. have expired."""
  780. def __init__(self, zeroconf):
  781. threading.Thread.__init__(self)
  782. self.setDaemon(True) # Added by David Harrison
  783. self.zeroconf = zeroconf
  784. self.start()
  785. def run(self):
  786. while 1:
  787. self.zeroconf.wait(10 * 1000)
  788. if globals()['_GLOBAL_DONE']:
  789. return
  790. now = currentTimeMillis()
  791. for record in self.zeroconf.cache.entries():
  792. if record.isExpired(now):
  793. self.zeroconf.updateRecord(now, record)
  794. self.zeroconf.cache.remove(record)
  795. class ServiceBrowser(threading.Thread):
  796. """Used to browse for a service of a specific type.
  797. The listener object will have its addService() and
  798. removeService() methods called when this browser
  799. discovers changes in the services availability."""
  800. def __init__(self, zeroconf, type, listener):
  801. """Creates a browser for a specific type"""
  802. threading.Thread.__init__(self)
  803. self.setDaemon(True) # Added by David Harrison
  804. self.zeroconf = zeroconf
  805. self.type = type
  806. self.listener = listener
  807. self.services = {}
  808. self.nextTime = currentTimeMillis()
  809. self.delay = _BROWSER_TIME
  810. self.list = []
  811. self.done = 0
  812. self.zeroconf.addListener(self, DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
  813. self.start()
  814. def updateRecord(self, zeroconf, now, record):
  815. """Callback invoked by Zeroconf when new information arrives.
  816. Updates information required by browser in the Zeroconf cache."""
  817. if record.type == _TYPE_PTR and record.name == self.type:
  818. expired = record.isExpired(now)
  819. try:
  820. oldrecord = self.services[record.alias.lower()]
  821. if not expired:
  822. oldrecord.resetTTL(record)
  823. else:
  824. del(self.services[record.alias.lower()])
  825. callback = lambda x: self.listener.removeService(x, self.type, record.alias)
  826. self.list.append(callback)
  827. return
  828. except:
  829. if not expired:
  830. self.services[record.alias.lower()] = record
  831. callback = lambda x: self.listener.addService(x, self.type, record.alias)
  832. self.list.append(callback)
  833. expires = record.getExpirationTime(75)
  834. if expires < self.nextTime:
  835. self.nextTime = expires
  836. def cancel(self):
  837. self.done = 1
  838. self.zeroconf.notifyAll()
  839. def run(self):
  840. while 1:
  841. event = None
  842. now = currentTimeMillis()
  843. if len(self.list) == 0 and self.nextTime > now:
  844. self.zeroconf.wait(self.nextTime - now)
  845. if globals()['_GLOBAL_DONE'] or self.done:
  846. return
  847. now = currentTimeMillis()
  848. if self.nextTime <= now:
  849. out = DNSOutgoing(_FLAGS_QR_QUERY)
  850. out.addQuestion(DNSQuestion(self.type, _TYPE_PTR, _CLASS_IN))
  851. for record in self.services.values():
  852. if not record.isExpired(now):
  853. out.addAnswerAtTime(record, now)
  854. self.zeroconf.send(out)
  855. self.nextTime = now + self.delay
  856. self.delay = min(20 * 1000, self.delay * 2)
  857. if len(self.list) > 0:
  858. event = self.list.pop(0)
  859. if event is not None:
  860. event(self.zeroconf)
  861. class ServiceInfo(object):
  862. """Service information"""
  863. def __init__(self, type, name, address=None, port=None, weight=0, priority=0, properties=None, server=None):
  864. """Create a service description.
  865. type: fully qualified service type name
  866. name: fully qualified service name
  867. address: IP address as unsigned short, network byte order
  868. port: port that the service runs on
  869. weight: weight of the service
  870. priority: priority of the service
  871. properties: dictionary of properties (or a string holding the bytes for the text field)
  872. server: fully qualified name for service host (defaults to name)"""
  873. if not name.endswith(type):
  874. raise BadTypeInNameException
  875. self.type = type
  876. self.name = name
  877. self.address = address
  878. self.port = port
  879. self.weight = weight
  880. self.priority = priority
  881. if server:
  882. self.server = server
  883. else:
  884. self.server = name
  885. self.setProperties(properties)
  886. def setProperties(self, properties):
  887. """Sets properties and text of this info from a dictionary"""
  888. if isinstance(properties, dict):
  889. self.properties = properties
  890. list = []
  891. result = ''
  892. for key in properties:
  893. value = properties[key]
  894. if value is None:
  895. suffix = ''.encode('utf-8')
  896. elif isinstance(value, str):
  897. suffix = value.encode('utf-8')
  898. elif isinstance(value, int):
  899. if value:
  900. suffix = 'true'
  901. else:
  902. suffix = 'false'
  903. else:
  904. suffix = ''.encode('utf-8')
  905. list.append('='.join((key, suffix)))
  906. for item in list:
  907. result = ''.join((result, struct.pack('!c', chr(len(item))), item))
  908. self.text = result
  909. else:
  910. self.text = properties
  911. def setText(self, text):
  912. """Sets properties and text given a text field"""
  913. self.text = text
  914. try:
  915. result = {}
  916. end = len(text)
  917. index = 0
  918. strs = []
  919. while index < end:
  920. length = ord(text[index])
  921. index += 1
  922. strs.append(text[index:index+length])
  923. index += length
  924. for s in strs:
  925. eindex = s.find('=')
  926. if eindex == -1:
  927. # No equals sign at all
  928. key = s
  929. value = 0
  930. else:
  931. key = s[:eindex]
  932. value = s[eindex+1:]
  933. if value == 'true':
  934. value = 1
  935. elif value == 'false' or not value:
  936. value = 0
  937. # Only update non-existent properties
  938. if key and result.get(key) == None:
  939. result[key] = value
  940. self.properties = result
  941. except:
  942. traceback.print_exc()
  943. self.properties = None
  944. def getType(self):
  945. """Type accessor"""
  946. return self.type
  947. def getName(self):
  948. """Name accessor"""
  949. if self.type is not None and self.name.endswith("." + self.type):
  950. return self.name[:len(self.name) - len(self.type) - 1]
  951. return self.name
  952. def getAddress(self):
  953. """Address accessor"""
  954. return self.address
  955. def getPort(self):
  956. """Port accessor"""
  957. return self.port
  958. def getPriority(self):
  959. """Pirority accessor"""
  960. return self.priority
  961. def getWeight(self):
  962. """Weight accessor"""
  963. return self.weight
  964. def getProperties(self):
  965. """Properties accessor"""
  966. return self.properties
  967. def getText(self):
  968. """Text accessor"""
  969. return self.text
  970. def getServer(self):
  971. """Server accessor"""
  972. return self.server
  973. def updateRecord(self, zeroconf, now, record):
  974. """Updates service information from a DNS record"""
  975. if record is not None and not record.isExpired(now):
  976. if record.type == _TYPE_A:
  977. if record.name == self.name:
  978. self.address = record.address
  979. elif record.type == _TYPE_SRV:
  980. if record.name == self.name:
  981. self.server = record.server
  982. self.port = record.port
  983. self.weight = record.weight
  984. self.priority = record.priority
  985. self.address = None
  986. self.updateRecord(zeroconf, now, zeroconf.cache.getByDetails(self.server, _TYPE_A, _CLASS_IN))
  987. elif record.type == _TYPE_TXT:
  988. if record.name == self.name:
  989. self.setText(record.text)
  990. def request(self, zeroconf, timeout):
  991. """Returns true if the service could be discovered on the
  992. network, and updates this object with details discovered.
  993. """
  994. now = currentTimeMillis()
  995. delay = _LISTENER_TIME
  996. next = now + delay
  997. last = now + timeout
  998. result = 0
  999. try:
  1000. zeroconf.addListener(self, DNSQuestion(self.name, _TYPE_ANY, _CLASS_IN))
  1001. while self.server is None or self.address is None or self.text is None:
  1002. if last <= now:
  1003. return 0
  1004. if next <= now:
  1005. out = DNSOutgoing(_FLAGS_QR_QUERY)
  1006. out.addQuestion(DNSQuestion(self.name, _TYPE_SRV, _CLASS_IN))
  1007. out.addAnswerAtTime(zeroconf.cache.getByDetails(self.name, _TYPE_SRV, _CLASS_IN), now)
  1008. out.addQuestion(DNSQuestion(self.name, _TYPE_TXT, _CLASS_IN))
  1009. out.addAnswerAtTime(zeroconf.cache.getByDetails(self.name, _TYPE_TXT, _CLASS_IN), now)
  1010. if self.server is not None:
  1011. out.addQuestion(DNSQuestion(self.server, _TYPE_A, _CLASS_IN))
  1012. out.addAnswerAtTime(zeroconf.cache.getByDetails(self.server, _TYPE_A, _CLASS_IN), now)
  1013. zeroconf.send(out)
  1014. next = now + delay
  1015. delay = delay * 2
  1016. zeroconf.wait(min(next, last) - now)
  1017. now = currentTimeMillis()
  1018. result = 1
  1019. finally:
  1020. zeroconf.removeListener(self)
  1021. return result
  1022. def __eq__(self, other):
  1023. """Tests equality of service name"""
  1024. if isinstance(other, ServiceInfo):
  1025. return other.name == self.name
  1026. return 0
  1027. def __ne__(self, other):
  1028. """Non-equality test"""
  1029. return not self.__eq__(other)
  1030. def __repr__(self):
  1031. """String representation"""
  1032. result = "service[%s,%s:%s," % (self.name, socket.inet_ntoa(self.getAddress()), self.port)
  1033. if self.text is None:
  1034. result += "None"
  1035. else:
  1036. if len(self.text) < 20:
  1037. result += self.text
  1038. else:
  1039. result += self.text[:17] + "..."
  1040. result += "]"
  1041. return result
  1042. class Zeroconf(object):
  1043. """Implementation of Zeroconf Multicast DNS Service Discovery
  1044. Supports registration, unregistration, queries and browsing.
  1045. """
  1046. def __init__(self, bindaddress=None):
  1047. """Creates an instance of the Zeroconf class, establishing
  1048. multicast communications, listening and reaping threads."""
  1049. globals()['_GLOBAL_DONE'] = 0
  1050. if bindaddress is None:
  1051. self.intf = socket.gethostbyname(socket.gethostname())
  1052. else:
  1053. self.intf = bindaddress
  1054. self.group = ('', _MDNS_PORT)
  1055. self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1056. try:
  1057. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  1058. self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
  1059. except:
  1060. # SO_REUSEADDR should be equivalent to SO_REUSEPORT for
  1061. # multicast UDP sockets (p 731, "TCP/IP Illustrated,
  1062. # Volume 2"), but some BSD-derived systems require
  1063. # SO_REUSEPORT to be specified explicity. Also, not all
  1064. # versions of Python have SO_REUSEPORT available. So
  1065. # if you're on a BSD-based system, and haven't upgraded
  1066. # to Python 2.3 yet, you may find this library doesn't
  1067. # work as expected.
  1068. #
  1069. pass
  1070. self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_TTL, 255)
  1071. self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_LOOP, 1)
  1072. try:
  1073. self.socket.bind(self.group)
  1074. except:
  1075. # Some versions of linux raise an exception even though
  1076. # the SO_REUSE* options have been set, so ignore it
  1077. #
  1078. pass
  1079. self.socket.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(self.intf) + socket.inet_aton('0.0.0.0'))
  1080. self.socket.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
  1081. self.listeners = []
  1082. self.browsers = []
  1083. self.services = {}
  1084. self.cache = DNSCache()
  1085. self.condition = threading.Condition()
  1086. self.engine = Engine(self)
  1087. self.listener = Listener(self)
  1088. self.reaper = Reaper(self)
  1089. def isLoopback(self):
  1090. return self.intf.startswith("127.0.0.1")
  1091. def isLinklocal(self):
  1092. return self.intf.startswith("169.254.")
  1093. def wait(self, timeout):
  1094. """Calling thread waits for a given number of milliseconds or
  1095. until notified."""
  1096. self.condition.acquire()
  1097. self.condition.wait(timeout/1000)
  1098. self.condition.release()
  1099. def notifyAll(self):
  1100. """Notifies all waiting threads"""
  1101. self.condition.acquire()
  1102. self.condition.notifyAll()
  1103. self.condition.release()
  1104. def getServiceInfo(self, type, name, timeout=3000):
  1105. """Returns network's service information for a particular
  1106. name and type, or None if no service matches by the timeout,
  1107. which defaults to 3 seconds."""
  1108. info = ServiceInfo(type, name)
  1109. if info.request(self, timeout):
  1110. return info
  1111. return None
  1112. def addServiceListener(self, type, listener):
  1113. """Adds a listener for a particular service type. This object
  1114. will then have its updateRecord method called when information
  1115. arrives for that type."""
  1116. self.removeServiceListener(listener)
  1117. self.browsers.append(ServiceBrowser(self, type, listener))
  1118. def removeServiceListener(self, listener):
  1119. """Removes a listener from the set that is currently listening."""
  1120. for browser in self.browsers:
  1121. if browser.listener == listener:
  1122. browser.cancel()
  1123. del(browser)
  1124. def registerService(self, info, ttl=_DNS_TTL):
  1125. """Registers service information to the network with a default TTL
  1126. of 60 seconds. Zeroconf will then respond to requests for
  1127. information for that service. The name of the service may be
  1128. changed if needed to make it unique on the network."""
  1129. self.checkService(info)
  1130. self.services[info.name.lower()] = info
  1131. now = currentTimeMillis()
  1132. nextTime = now
  1133. i = 0
  1134. while i < 3:
  1135. if now < nextTime:
  1136. self.wait(nextTime - now)
  1137. now = currentTimeMillis()
  1138. continue
  1139. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
  1140. out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, ttl, info.name), 0)
  1141. out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, ttl, info.priority, info.weight, info.port, info.server), 0)
  1142. out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, ttl, info.text), 0)
  1143. if info.address:
  1144. out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, ttl, info.address), 0)
  1145. self.send(out)
  1146. i += 1
  1147. nextTime += _REGISTER_TIME
  1148. def unregisterService(self, info):
  1149. """Unregister a service."""
  1150. try:
  1151. del(self.services[info.name.lower()])
  1152. except:
  1153. pass
  1154. now = currentTimeMillis()
  1155. nextTime = now
  1156. i = 0
  1157. while i < 3:
  1158. if now < nextTime:
  1159. self.wait(nextTime - now)
  1160. now = currentTimeMillis()
  1161. continue
  1162. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
  1163. out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
  1164. out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.name), 0)
  1165. out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
  1166. if info.address:
  1167. out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, info.address), 0)
  1168. self.send(out)
  1169. i += 1
  1170. nextTime += _UNREGISTER_TIME
  1171. def unregisterAllServices(self):
  1172. """Unregister all registered services."""
  1173. if len(self.services) > 0:
  1174. now = currentTimeMillis()
  1175. nextTime = now
  1176. i = 0
  1177. while i < 3:
  1178. if now < nextTime:
  1179. self.wait(nextTime - now)
  1180. now = currentTimeMillis()
  1181. continue
  1182. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
  1183. for info in self.services.values():
  1184. out.addAnswerAtTime(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, 0, info.name), 0)
  1185. out.addAnswerAtTime(DNSService(info.name, _TYPE_SRV, _CLASS_IN, 0, info.priority, info.weight, info.port, info.server), 0)
  1186. out.addAnswerAtTime(DNSText(info.name, _TYPE_TXT, _CLASS_IN, 0, info.text), 0)
  1187. if info.address:
  1188. out.addAnswerAtTime(DNSAddress(info.server, _TYPE_A, _CLASS_IN, 0, info.address), 0)
  1189. self.send(out)
  1190. i += 1
  1191. nextTime += _UNREGISTER_TIME
  1192. def checkService(self, info):
  1193. """Checks the network for a unique service name, modifying the
  1194. ServiceInfo passed in if it is not unique."""
  1195. now = currentTimeMillis()
  1196. nextTime = now
  1197. i = 0
  1198. while i < 3:
  1199. for record in self.cache.entriesWithName(info.type):
  1200. if record.type == _TYPE_PTR and not record.isExpired(now) and record.alias == info.name:
  1201. if (info.name.find('.') < 0):
  1202. info.name = info.name + ".[" + info.address + ":" + info.port + "]." + info.type
  1203. self.checkService(info)
  1204. return
  1205. raise NonUniqueNameException
  1206. if now < nextTime:
  1207. self.wait(nextTime - now)
  1208. now = currentTimeMillis()
  1209. continue
  1210. out = DNSOutgoing(_FLAGS_QR_QUERY | _FLAGS_AA)
  1211. self.debug = out
  1212. out.addQuestion(DNSQuestion(info.type, _TYPE_PTR, _CLASS_IN))
  1213. out.addAuthorativeAnswer(DNSPointer(info.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, info.name))
  1214. self.send(out)
  1215. i += 1
  1216. nextTime += _CHECK_TIME
  1217. def addListener(self, listener, question):
  1218. """Adds a listener for a given question. The listener will have
  1219. its updateRecord method called when information is available to
  1220. answer the question."""
  1221. now = currentTimeMillis()
  1222. self.listeners.append(listener)
  1223. if question is not None:
  1224. for record in self.cache.entriesWithName(question.name):
  1225. if question.answeredBy(record) and not record.isExpired(now):
  1226. listener.updateRecord(self, now, record)
  1227. self.notifyAll()
  1228. def removeListener(self, listener):
  1229. """Removes a listener."""
  1230. try:
  1231. self.listeners.remove(listener)
  1232. self.notifyAll()
  1233. except:
  1234. pass
  1235. def updateRecord(self, now, rec):
  1236. """Used to notify listeners of new information that has updated
  1237. a record."""
  1238. for listener in self.listeners:
  1239. listener.updateRecord(self, now, rec)
  1240. self.notifyAll()
  1241. def handleResponse(self, msg):
  1242. """Deal with incoming response packets. All answers
  1243. are held in the cache, and listeners are notified."""
  1244. now = currentTimeMillis()
  1245. for record in msg.answers:
  1246. expired = record.isExpired(now)
  1247. if record in self.cache.entries():
  1248. if expired:
  1249. self.cache.remove(record)
  1250. else:
  1251. entry = self.cache.get(record)
  1252. if entry is not None:
  1253. entry.resetTTL(record)
  1254. record = entry
  1255. else:
  1256. self.cache.add(record)
  1257. self.updateRecord(now, record)
  1258. def handleQuery(self, msg, addr, port):
  1259. """Deal with incoming query packets. Provides a response if
  1260. possible."""
  1261. out = None
  1262. # Support unicast client responses
  1263. #
  1264. if port != _MDNS_PORT:
  1265. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA, 0)
  1266. for question in msg.questions:
  1267. out.addQuestion(question)
  1268. for question in msg.questions:
  1269. if question.type == _TYPE_PTR:
  1270. for service in self.services.values():
  1271. if question.name == service.type:
  1272. if out is None:
  1273. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
  1274. out.addAnswer(msg, DNSPointer(service.type, _TYPE_PTR, _CLASS_IN, _DNS_TTL, service.name))
  1275. else:
  1276. try:
  1277. if out is None:
  1278. out = DNSOutgoing(_FLAGS_QR_RESPONSE | _FLAGS_AA)
  1279. # Answer A record queries for any service addresses we know
  1280. if question.type == _TYPE_A or question.type == _TYPE_ANY:
  1281. for service in self.services.values():
  1282. if service.server == question.name.lower():
  1283. out.addAnswer(msg, DNSAddress(question.name, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address))
  1284. service = self.services.get(question.name.lower(), None)
  1285. if not service: continue
  1286. if question.type == _TYPE_SRV or question.type == _TYPE_ANY:
  1287. out.addAnswer(msg, DNSService(question.name, _TYPE_SRV, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.priority, service.weight, service.port, service.server))
  1288. if question.type == _TYPE_TXT or question.type == _TYPE_ANY:
  1289. out.addAnswer(msg, DNSText(question.name, _TYPE_TXT, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.text))
  1290. if question.type == _TYPE_SRV:
  1291. out.addAdditionalAnswer(DNSAddress(service.server, _TYPE_A, _CLASS_IN | _CLASS_UNIQUE, _DNS_TTL, service.address))
  1292. except:
  1293. traceback.print_exc()
  1294. if out is not None and out.answers:
  1295. out.id = msg.id
  1296. self.send(out, addr, port)
  1297. def send(self, out, addr = _MDNS_ADDR, port = _MDNS_PORT):
  1298. """Sends an outgoing packet."""
  1299. # This is a quick test to see if we can parse the packets we generate
  1300. #temp = DNSIncoming(out.packet())
  1301. try:
  1302. bytes_sent = self.socket.sendto(out.packet(), 0, (addr, port))
  1303. except:
  1304. # Ignore this, it may be a temporary loss of network connection
  1305. pass
  1306. def close(self):
  1307. """Ends the background threads, and prevent this instance from
  1308. servicing further queries."""
  1309. if globals()['_GLOBAL_DONE'] == 0:
  1310. globals()['_GLOBAL_DONE'] = 1
  1311. self.notifyAll()
  1312. self.engine.notify()
  1313. self.unregisterAllServices()
  1314. self.socket.setsockopt(socket.SOL_IP, socket.IP_DROP_MEMBERSHIP, socket.inet_aton(_MDNS_ADDR) + socket.inet_aton('0.0.0.0'))
  1315. self.socket.close()
  1316. # Test a few module features, including service registration, service
  1317. # query (for Zoe), and service unregistration.
  1318. if __name__ == '__main__':
  1319. print "Multicast DNS Service Discovery for Python, version", __version__
  1320. r = Zeroconf()
  1321. print "1. Testing registration of a service..."
  1322. desc = {'version':'0.10','a':'test value', 'b':'another value'}
  1323. info = ServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local.", socket.inet_aton("127.0.0.1"), 1234, 0, 0, desc)
  1324. print " Registering service..."
  1325. r.registerService(info)
  1326. print " Registration done."
  1327. print "2. Testing query of service information..."
  1328. print " Getting ZOE service:", str(r.getServiceInfo("_http._tcp.local.", "ZOE._http._tcp.local."))
  1329. print " Query done."
  1330. print "3. Testing query of own service..."
  1331. print " Getting self:", str(r.getServiceInfo("_http._tcp.local.", "My Service Name._http._tcp.local."))
  1332. print " Query done."
  1333. print "4. Testing unregister of service information..."
  1334. r.unregisterService(info)
  1335. print " Unregister done."
  1336. r.close()