This repository has been archived by the owner on Sep 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
pybonjour.py
2073 lines (1614 loc) · 62 KB
/
pybonjour.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
################################################################################
#
# Copyright (c) 2007-2008 Christopher J. Stawarz
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
################################################################################
"""
Pure-Python interface to Apple Bonjour and compatible DNS-SD libraries
pybonjour provides a pure-Python interface (via ctypes) to Apple
Bonjour and compatible DNS-SD libraries (such as Avahi). It allows
Python scripts to take advantage of Zero Configuration Networking
(Zeroconf) to register, discover, and resolve services on both local
and wide-area networks. Since pybonjour is implemented in pure
Python, scripts that use it can easily be ported to Mac OS X, Windows,
Linux, and other systems that run Bonjour.
Note on strings: Internally, all strings used in DNS-SD are UTF-8
strings. String arguments passed to the DNS-SD functions provided by
pybonjour must be either unicode instances or str instances that can
be converted to unicode using the default encoding. (Passing a
non-convertible str will result in an exception.) Strings returned
from pybonjour (either directly from API functions or passed to
application callbacks) are always unicode instances.
"""
__author__ = 'Christopher Stawarz <[email protected]>'
__version__ = '1.1.1'
import ctypes
import os
import re
import socket
import sys
################################################################################
#
# Global setup
#
################################################################################
class _DummyLock(object):
@staticmethod
def acquire():
pass
@staticmethod
def release():
pass
_global_lock = _DummyLock()
if sys.platform == 'win32':
# Need to use the stdcall variants
_libdnssd = ctypes.windll.dnssd
_CFunc = ctypes.WINFUNCTYPE
else:
if sys.platform == 'darwin':
_libdnssd = 'libSystem.B.dylib'
else:
_libdnssd = 'libdns_sd.so.1'
# If libdns_sd is actually Avahi's Bonjour compatibility
# layer, silence its annoying warning messages, and use a real
# RLock as the global lock, since the compatibility layer
# isn't thread safe.
try:
ctypes.cdll.LoadLibrary('libavahi-client.so.3')
except OSError:
pass
else:
os.environ['AVAHI_COMPAT_NOWARN'] = '1'
import threading
_global_lock = threading.RLock()
_libdnssd = ctypes.cdll.LoadLibrary(_libdnssd)
_CFunc = ctypes.CFUNCTYPE
################################################################################
#
# Constants
#
################################################################################
#
# General flags
#
kDNSServiceFlagsMoreComing = 0x1
kDNSServiceFlagsAdd = 0x2
kDNSServiceFlagsDefault = 0x4
kDNSServiceFlagsNoAutoRename = 0x8
kDNSServiceFlagsShared = 0x10
kDNSServiceFlagsUnique = 0x20
kDNSServiceFlagsBrowseDomains = 0x40
kDNSServiceFlagsRegistrationDomains = 0x80
kDNSServiceFlagsLongLivedQuery = 0x100
kDNSServiceFlagsAllowRemoteQuery = 0x200
kDNSServiceFlagsForceMulticast = 0x400
kDNSServiceFlagsReturnCNAME = 0x800
#
# Service classes
#
kDNSServiceClass_IN = 1
#
# Service types
#
kDNSServiceType_A = 1
kDNSServiceType_NS = 2
kDNSServiceType_MD = 3
kDNSServiceType_MF = 4
kDNSServiceType_CNAME = 5
kDNSServiceType_SOA = 6
kDNSServiceType_MB = 7
kDNSServiceType_MG = 8
kDNSServiceType_MR = 9
kDNSServiceType_NULL = 10
kDNSServiceType_WKS = 11
kDNSServiceType_PTR = 12
kDNSServiceType_HINFO = 13
kDNSServiceType_MINFO = 14
kDNSServiceType_MX = 15
kDNSServiceType_TXT = 16
kDNSServiceType_RP = 17
kDNSServiceType_AFSDB = 18
kDNSServiceType_X25 = 19
kDNSServiceType_ISDN = 20
kDNSServiceType_RT = 21
kDNSServiceType_NSAP = 22
kDNSServiceType_NSAP_PTR = 23
kDNSServiceType_SIG = 24
kDNSServiceType_KEY = 25
kDNSServiceType_PX = 26
kDNSServiceType_GPOS = 27
kDNSServiceType_AAAA = 28
kDNSServiceType_LOC = 29
kDNSServiceType_NXT = 30
kDNSServiceType_EID = 31
kDNSServiceType_NIMLOC = 32
kDNSServiceType_SRV = 33
kDNSServiceType_ATMA = 34
kDNSServiceType_NAPTR = 35
kDNSServiceType_KX = 36
kDNSServiceType_CERT = 37
kDNSServiceType_A6 = 38
kDNSServiceType_DNAME = 39
kDNSServiceType_SINK = 40
kDNSServiceType_OPT = 41
kDNSServiceType_TKEY = 249
kDNSServiceType_TSIG = 250
kDNSServiceType_IXFR = 251
kDNSServiceType_AXFR = 252
kDNSServiceType_MAILB = 253
kDNSServiceType_MAILA = 254
kDNSServiceType_ANY = 255
#
# Error codes
#
kDNSServiceErr_NoError = 0
kDNSServiceErr_Unknown = -65537
kDNSServiceErr_NoSuchName = -65538
kDNSServiceErr_NoMemory = -65539
kDNSServiceErr_BadParam = -65540
kDNSServiceErr_BadReference = -65541
kDNSServiceErr_BadState = -65542
kDNSServiceErr_BadFlags = -65543
kDNSServiceErr_Unsupported = -65544
kDNSServiceErr_NotInitialized = -65545
kDNSServiceErr_AlreadyRegistered = -65547
kDNSServiceErr_NameConflict = -65548
kDNSServiceErr_Invalid = -65549
kDNSServiceErr_Firewall = -65550
kDNSServiceErr_Incompatible = -65551
kDNSServiceErr_BadInterfaceIndex = -65552
kDNSServiceErr_Refused = -65553
kDNSServiceErr_NoSuchRecord = -65554
kDNSServiceErr_NoAuth = -65555
kDNSServiceErr_NoSuchKey = -65556
kDNSServiceErr_NATTraversal = -65557
kDNSServiceErr_DoubleNAT = -65558
kDNSServiceErr_BadTime = -65559
#
# Other constants
#
kDNSServiceMaxServiceName = 64
kDNSServiceMaxDomainName = 1005
kDNSServiceInterfaceIndexAny = 0
kDNSServiceInterfaceIndexLocalOnly = -1
################################################################################
#
# Error handling
#
################################################################################
class BonjourError(Exception):
"""
Exception representing an error returned by the DNS-SD library.
The errorCode attribute contains the actual integer error code
returned.
"""
_errmsg = {
kDNSServiceErr_NoSuchName: 'no such name',
kDNSServiceErr_NoMemory: 'no memory',
kDNSServiceErr_BadParam: 'bad param',
kDNSServiceErr_BadReference: 'bad reference',
kDNSServiceErr_BadState: 'bad state',
kDNSServiceErr_BadFlags: 'bad flags',
kDNSServiceErr_Unsupported: 'unsupported',
kDNSServiceErr_NotInitialized: 'not initialized',
kDNSServiceErr_AlreadyRegistered: 'already registered',
kDNSServiceErr_NameConflict: 'name conflict',
kDNSServiceErr_Invalid: 'invalid',
kDNSServiceErr_Firewall: 'firewall',
kDNSServiceErr_Incompatible: 'incompatible',
kDNSServiceErr_BadInterfaceIndex: 'bad interface index',
kDNSServiceErr_Refused: 'refused',
kDNSServiceErr_NoSuchRecord: 'no such record',
kDNSServiceErr_NoAuth: 'no auth',
kDNSServiceErr_NoSuchKey: 'no such key',
kDNSServiceErr_NATTraversal: 'NAT traversal',
kDNSServiceErr_DoubleNAT: 'double NAT',
kDNSServiceErr_BadTime: 'bad time',
}
@classmethod
def _errcheck(cls, result, func, args):
if result != kDNSServiceErr_NoError:
raise cls(result)
return args
def __init__(self, errorCode):
self.errorCode = errorCode
Exception.__init__(self,
(errorCode, self._errmsg.get(errorCode, 'unknown')))
################################################################################
#
# Data types
#
################################################################################
class _utf8_char_p(ctypes.c_char_p):
@classmethod
def from_param(cls, obj):
if (obj is not None) and (not isinstance(obj, cls)):
if not isinstance(obj, basestring):
raise TypeError('parameter must be a string type instance')
if not isinstance(obj, unicode):
obj = unicode(obj)
obj = obj.encode('utf-8')
return ctypes.c_char_p.from_param(obj)
def decode(self):
if self.value is None:
return None
return self.value.decode('utf-8')
class _utf8_char_p_non_null(_utf8_char_p):
@classmethod
def from_param(cls, obj):
if obj is None:
raise ValueError('parameter cannot be None')
return _utf8_char_p.from_param(obj)
_DNSServiceFlags = ctypes.c_uint32
_DNSServiceErrorType = ctypes.c_int32
class DNSRecordRef(ctypes.c_void_p):
"""
A DNSRecordRef pointer. DO NOT CREATE INSTANCES OF THIS CLASS!
Only instances returned by the DNS-SD library are valid. Using
others will likely cause the Python interpreter to crash.
Application code should not use any of the methods of this class.
The only valid use of a DNSRecordRef instance is as an argument to
a DNS-SD function.
To compare two DNSRecordRef instances for equality, use '=='
rather than 'is'.
"""
@classmethod
def from_param(cls, obj):
if type(obj) is not cls:
raise TypeError("expected '%s', got '%s'" %
(cls.__name__, type(obj).__name__))
if obj.value is None:
raise ValueError('invalid %s instance' % cls.__name__)
return obj
def __eq__(self, other):
return ((type(other) is type(self)) and (other.value == self.value))
def __ne__(self, other):
return not (other == self)
def _invalidate(self):
self.value = None
def _valid(self):
return (self.value is not None)
class _DNSRecordRef_or_null(DNSRecordRef):
@classmethod
def from_param(cls, obj):
if obj is None:
return obj
return DNSRecordRef.from_param(obj)
class DNSServiceRef(DNSRecordRef):
"""
A DNSServiceRef pointer. DO NOT CREATE INSTANCES OF THIS CLASS!
Only instances returned by the DNS-SD library are valid. Using
others will likely cause the Python interpreter to crash.
An instance of this class represents an active connection to the
mDNS daemon. The connection remains open until the close() method
is called (which also terminates the associated browse, resolve,
etc.). Note that this method is *not* called automatically when
the instance is deallocated; therefore, application code must be
certain to call close() when the connection is no longer needed.
The primary use of a DNSServiceRef instance is in conjunction with
select() or poll() to determine when a response from the daemon is
available. When the file descriptor returned by fileno() is ready
for reading, a reply from the daemon is available and should be
processed by passing the DNSServiceRef instance to
DNSServiceProcessResult(), which will invoke the appropriate
application callback function. (Note that the file descriptor
should never be read from or written to directly.)
The DNSServiceRef class supports the context management protocol
introduced in Python 2.5, meaning applications can use the 'with'
statement to ensure that DNSServiceRef instances are closed
regardless of whether an exception occurs, e.g.
sdRef = DNSServiceBrowse(...)
with sdRef:
# sdRef will be closed regardless of how this block is
# exited
...
To compare two DNSServiceRef instances for equality, use '=='
rather than 'is'.
"""
def __init__(self, *args, **kwargs):
DNSRecordRef.__init__(self, *args, **kwargs)
# Since callback functions are called asynchronously, we need
# to hold onto references to them for as long as they're in
# use. Otherwise, Python could deallocate them before we call
# DNSServiceProcessResult(), meaning the Bonjour library would
# dereference freed memory when it tried to invoke the
# callback.
self._callbacks = []
# A DNSRecordRef is invalidated if DNSServiceRefDeallocate()
# is called on the corresponding DNSServiceRef, so we need to
# keep track of all our record refs and invalidate them when
# we're closed.
self._record_refs = []
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def _add_callback(self, cb):
self._callbacks.append(cb)
def _add_record_ref(self, ref):
self._record_refs.append(ref)
def close(self):
"""
Close the connection to the mDNS daemon and terminate any
associated browse, resolve, etc. operations.
"""
if self._valid():
for ref in self._record_refs:
ref._invalidate()
del self._record_refs
_global_lock.acquire()
try:
_DNSServiceRefDeallocate(self)
finally:
_global_lock.release()
self._invalidate()
del self._callbacks
def fileno(self):
"""
Return the file descriptor associated with this connection.
This descriptor should never be read from or written to
directly. It should only be passed to select() or poll() to
determine when a response from the mDNS daemon is available.
"""
_global_lock.acquire()
try:
fd = _DNSServiceRefSockFD(self)
finally:
_global_lock.release()
return fd
_DNSServiceDomainEnumReply = _CFunc(
None,
DNSServiceRef, # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_DNSServiceErrorType, # errorCode
_utf8_char_p, # replyDomain
ctypes.c_void_p, # context
)
_DNSServiceRegisterReply = _CFunc(
None,
DNSServiceRef, # sdRef
_DNSServiceFlags, # flags
_DNSServiceErrorType, # errorCode
_utf8_char_p, # name
_utf8_char_p, # regtype
_utf8_char_p, # domain
ctypes.c_void_p, # context
)
_DNSServiceBrowseReply = _CFunc(
None,
DNSServiceRef, # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_DNSServiceErrorType, # errorCode
_utf8_char_p, # serviceName
_utf8_char_p, # regtype
_utf8_char_p, # replyDomain
ctypes.c_void_p, # context
)
_DNSServiceResolveReply = _CFunc(
None,
DNSServiceRef, # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_DNSServiceErrorType, # errorCode
_utf8_char_p, # fullname
_utf8_char_p, # hosttarget
ctypes.c_uint16, # port
ctypes.c_uint16, # txtLen
ctypes.c_void_p, # txtRecord (not null-terminated, so c_void_p)
ctypes.c_void_p, # context
)
_DNSServiceRegisterRecordReply = _CFunc(
None,
DNSServiceRef, # sdRef
DNSRecordRef, # RecordRef
_DNSServiceFlags, # flags
_DNSServiceErrorType, # errorCode
ctypes.c_void_p, # context
)
_DNSServiceQueryRecordReply = _CFunc(
None,
DNSServiceRef, # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_DNSServiceErrorType, # errorCode
_utf8_char_p, # fullname
ctypes.c_uint16, # rrtype
ctypes.c_uint16, # rrclass
ctypes.c_uint16, # rdlen
ctypes.c_void_p, # rdata
ctypes.c_uint32, # ttl
ctypes.c_void_p, # context
)
################################################################################
#
# Low-level function bindings
#
################################################################################
def _create_function_bindings():
ERRCHECK = True
NO_ERRCHECK = False
OUTPARAM = (lambda index: index)
NO_OUTPARAM = None
specs = {
#'funcname':
#(
# return_type,
# errcheck,
# outparam,
# (
# param_1_type,
# param_2_type,
# ...
# param_n_type,
# )),
'DNSServiceRefSockFD':
(
ctypes.c_int,
NO_ERRCHECK,
NO_OUTPARAM,
(
DNSServiceRef, # sdRef
)),
'DNSServiceProcessResult':
(
_DNSServiceErrorType,
ERRCHECK,
NO_OUTPARAM,
(
DNSServiceRef, # sdRef
)),
'DNSServiceRefDeallocate':
(
None,
NO_ERRCHECK,
NO_OUTPARAM,
(
DNSServiceRef, # sdRef
)),
'DNSServiceEnumerateDomains':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_DNSServiceDomainEnumReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceRegister':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p, # name
_utf8_char_p_non_null, # regtype
_utf8_char_p, # domain
_utf8_char_p, # host
ctypes.c_uint16, # port
ctypes.c_uint16, # txtLen
ctypes.c_void_p, # txtRecord
_DNSServiceRegisterReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceAddRecord':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(1),
(
DNSServiceRef, # sdRef
ctypes.POINTER(DNSRecordRef), # RecordRef
_DNSServiceFlags, # flags
ctypes.c_uint16, # rrtype
ctypes.c_uint16, # rdlen
ctypes.c_void_p, # rdata
ctypes.c_uint32, # ttl
)),
'DNSServiceUpdateRecord':
(
_DNSServiceErrorType,
ERRCHECK,
NO_OUTPARAM,
(
DNSServiceRef, # sdRef
_DNSRecordRef_or_null, # RecordRef
_DNSServiceFlags, # flags
ctypes.c_uint16, # rdlen
ctypes.c_void_p, # rdata
ctypes.c_uint32, # ttl
)),
'DNSServiceRemoveRecord':
(
_DNSServiceErrorType,
ERRCHECK,
NO_OUTPARAM,
(
DNSServiceRef, # sdRef
DNSRecordRef, # RecordRef
_DNSServiceFlags, # flags
)),
'DNSServiceBrowse':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p_non_null, # regtype
_utf8_char_p, # domain
_DNSServiceBrowseReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceResolve':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p_non_null, # name
_utf8_char_p_non_null, # regtype
_utf8_char_p_non_null, # domain
_DNSServiceResolveReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceCreateConnection':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
)),
'DNSServiceRegisterRecord':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(1),
(
DNSServiceRef, # sdRef
ctypes.POINTER(DNSRecordRef), # RecordRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p_non_null, # fullname
ctypes.c_uint16, # rrtype
ctypes.c_uint16, # rrclass
ctypes.c_uint16, # rdlen
ctypes.c_void_p, # rdata
ctypes.c_uint32, # ttl
_DNSServiceRegisterRecordReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceQueryRecord':
(
_DNSServiceErrorType,
ERRCHECK,
OUTPARAM(0),
(
ctypes.POINTER(DNSServiceRef), # sdRef
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p_non_null, # fullname
ctypes.c_uint16, # rrtype
ctypes.c_uint16, # rrclass
_DNSServiceQueryRecordReply, # callBack
ctypes.c_void_p, # context
)),
'DNSServiceReconfirmRecord':
(
None, # _DNSServiceErrorType in more recent versions
NO_ERRCHECK,
NO_OUTPARAM,
(
_DNSServiceFlags, # flags
ctypes.c_uint32, # interfaceIndex
_utf8_char_p_non_null, # fullname
ctypes.c_uint16, # rrtype
ctypes.c_uint16, # rrclass
ctypes.c_uint16, # rdlen
ctypes.c_void_p, # rdata
)),
'DNSServiceConstructFullName':
(
ctypes.c_int,
ERRCHECK,
OUTPARAM(0),
(
ctypes.c_char * kDNSServiceMaxDomainName, # fullName
_utf8_char_p, # service
_utf8_char_p_non_null, # regtype
_utf8_char_p_non_null, # domain
)),
}
for name, (restype, errcheck, outparam, argtypes) in specs.iteritems():
prototype = _CFunc(restype, *argtypes)
paramflags = [1] * len(argtypes)
if outparam is not None:
paramflags[outparam] = 2
paramflags = tuple((val,) for val in paramflags)
func = prototype((name, _libdnssd), paramflags)
if errcheck:
func.errcheck = BonjourError._errcheck
globals()['_' + name] = func
# Only need to do this once
_create_function_bindings()
del _create_function_bindings
################################################################################
#
# Internal utility types and functions
#
################################################################################
class _NoDefault(object):
def __repr__(self):
return '<NO DEFAULT>'
def check(self, obj):
if obj is self:
raise ValueError('required parameter value missing')
_NO_DEFAULT = _NoDefault()
def _string_to_length_and_void_p(string):
if isinstance(string, TXTRecord):
string = str(string)
void_p = ctypes.cast(ctypes.c_char_p(string), ctypes.c_void_p)
return len(string), void_p
def _length_and_void_p_to_string(length, void_p):
char_p = ctypes.cast(void_p, ctypes.POINTER(ctypes.c_char))
return ''.join(char_p[i] for i in xrange(length))
################################################################################
#
# High-level functions
#
################################################################################
def DNSServiceProcessResult(
sdRef,
):
"""
Read a reply from the daemon, calling the appropriate application
callback. This call will block until the daemon's response is
received. Use sdRef in conjunction with select() or poll() to
determine the presence of a response from the server before
calling this function to process the reply without blocking. Call
this function at any point if it is acceptable to block until the
daemon's response arrives. Note that the client is responsible
for ensuring that DNSServiceProcessResult() is called whenever
there is a reply from the daemon; the daemon may terminate its
connection with a client that does not process the daemon's
responses.
sdRef:
A DNSServiceRef returned by any of the DNSService calls that
take a callback parameter.
"""
_global_lock.acquire()
try:
_DNSServiceProcessResult(sdRef)
finally:
_global_lock.release()
def DNSServiceEnumerateDomains(
flags,
interfaceIndex = kDNSServiceInterfaceIndexAny,
callBack = None,
):
"""
Asynchronously enumerate domains available for browsing and
registration.
The enumeration MUST be cancelled by closing the returned
DNSServiceRef when no more domains are to be found.
flags:
Possible values are:
kDNSServiceFlagsBrowseDomains to enumerate domains
recommended for browsing.
kDNSServiceFlagsRegistrationDomains to enumerate domains
recommended for registration.
interfaceIndex:
If non-zero, specifies the interface on which to look for
domains. Most applications will pass
kDNSServiceInterfaceIndexAny (0) to enumerate domains on all
interfaces.
callBack:
The function to be called when a domain is found or the call
asynchronously fails. Its signature should be
callBack(sdRef, flags, interfaceIndex, errorCode, replyDomain).
return value:
A DNSServiceRef instance.
Callback Parameters:
sdRef:
The DNSServiceRef returned by DNSServiceEnumerateDomains().
flags:
Possible values are:
kDNSServiceFlagsMoreComing
kDNSServiceFlagsAdd
kDNSServiceFlagsDefault
interfaceIndex:
Specifies the interface on which the domain exists.
errorCode:
Will be kDNSServiceErr_NoError (0) on success, otherwise
indicates the failure that occurred (in which case other
parameters are undefined).
replyDomain:
The name of the domain.
"""
@_DNSServiceDomainEnumReply
def _callback(sdRef, flags, interfaceIndex, errorCode, replyDomain,
context):
if callBack is not None:
callBack(sdRef, flags, interfaceIndex, errorCode,
replyDomain.decode())
_global_lock.acquire()
try:
sdRef = _DNSServiceEnumerateDomains(flags,
interfaceIndex,
_callback,
None)
finally:
_global_lock.release()
sdRef._add_callback(_callback)
return sdRef
def DNSServiceRegister(
flags = 0,
interfaceIndex = kDNSServiceInterfaceIndexAny,
name = None,
regtype = _NO_DEFAULT,
domain = None,
host = None,
port = _NO_DEFAULT,
txtRecord = '',
callBack = None,
):
"""
Register a service that is discovered via DNSServiceBrowse() and
DNSServiceResolve() calls.
flags:
Indicates the renaming behavior on name conflict. Most
applications will pass 0.