• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright © 2020-2024 by OpenPrinting.
4  * Copyright (c) 2003-2004, Apple Computer, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright notice,
10  *     this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright notice,
12  *     this list of conditions and the following disclaimer in the documentation
13  *     and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of its
15  *     contributors may be used to endorse or promote products derived from this
16  *     software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 
31 /*! @header     DNS Service Discovery
32  *
33  * @discussion  This section describes the functions, callbacks, and data structures
34  *              that make up the DNS Service Discovery API.
35  *
36  *              The DNS Service Discovery API is part of Bonjour, Apple's implementation
37  *              of zero-configuration networking (ZEROCONF).
38  *
39  *              Bonjour allows you to register a network service, such as a
40  *              printer or file server, so that it can be found by name or browsed
41  *              for by service type and domain. Using Bonjour, applications can
42  *              discover what services are available on the network, along with
43  *              all the information -- such as name, IP address, and port --
44  *              necessary to access a particular service.
45  *
46  *              In effect, Bonjour combines the functions of a local DNS server and
47  *              AppleTalk. Bonjour allows applications to provide user-friendly printer
48  *              and server browsing, among other things, over standard IP networks.
49  *              This behavior is a result of combining protocols such as multicast and
50  *              DNS to add new functionality to the network (such as multicast DNS).
51  *
52  *              Bonjour gives applications easy access to services over local IP
53  *              networks without requiring the service or the application to support
54  *              an AppleTalk or a Netbeui stack, and without requiring a DNS server
55  *              for the local network.
56  */
57 
58 
59 /* _DNS_SD_H contains the mDNSResponder version number for this header file, formatted as follows:
60  *   Major part of the build number * 10000 +
61  *   minor part of the build number *   100
62  * For example, Mac OS X 10.4.9 has mDNSResponder-108.4, which would be represented as
63  * version 1080400. This allows C code to do simple greater-than and less-than comparisons:
64  * e.g. an application that requires the DNSServiceGetProperty() call (new in mDNSResponder-126) can check:
65  *
66  *   #if _DNS_SD_H+0 >= 1260000
67  *   ... some C code that calls DNSServiceGetProperty() ...
68  *   #endif
69  *
70  * The version defined in this header file symbol allows for compile-time
71  * checking, so that C code building with earlier versions of the header file
72  * can avoid compile errors trying to use functions that aren't even defined
73  * in those earlier versions. Similar checks may also be performed at run-time:
74  *  => weak linking -- to avoid link failures if run with an earlier
75  *     version of the library that's missing some desired symbol, or
76  *  => DNSServiceGetProperty(DaemonVersion) -- to verify whether the running daemon
77  *     ("system service" on Windows) meets some required minimum functionality level.
78  */
79 
80 #ifndef _DNS_SD_H
81 #define _DNS_SD_H 3331000
82 
83 #ifdef  __cplusplus
84     extern "C" {
85 #endif
86 
87 /* Set to 1 if libdispatch is supported
88  * Note: May also be set by project and/or Makefile
89  */
90 #ifndef _DNS_SD_LIBDISPATCH
91 #define _DNS_SD_LIBDISPATCH 0
92 #endif /* ndef _DNS_SD_LIBDISPATCH */
93 
94 /* standard calling convention under Win32 is __stdcall */
95 /* Note: When compiling Intel EFI (Extensible Firmware Interface) under MS Visual Studio, the */
96 /* _WIN32 symbol is defined by the compiler even though it's NOT compiling code for Windows32 */
97 #if defined(_WIN32) && !defined(EFI32) && !defined(EFI64)
98 #define DNSSD_API __stdcall
99 #else
100 #define DNSSD_API
101 #endif
102 
103 /* stdint.h does not exist on FreeBSD 4.x; its types are defined in sys/types.h instead */
104 #if defined(__FreeBSD__) && (__FreeBSD__ < 5)
105 #include <sys/types.h>
106 
107 /* Likewise, on Sun, standard integer types are in sys/types.h */
108 #elif defined(__sun__)
109 #include <sys/types.h>
110 
111 /* EFI does not have stdint.h, or anything else equivalent */
112 #elif defined(EFI32) || defined(EFI64) || defined(EFIX64)
113 #include "Tiano.h"
114 #if !defined(_STDINT_H_)
115 typedef UINT8       uint8_t;
116 typedef INT8        int8_t;
117 typedef UINT16      uint16_t;
118 typedef INT16       int16_t;
119 typedef UINT32      uint32_t;
120 typedef INT32       int32_t;
121 #endif
122 /* Windows has its own differences */
123 #elif defined(_WIN32)
124 #include <windows.h>
125 #define _UNUSED
126 #ifndef _MSL_STDINT_H
127 typedef UINT8       uint8_t;
128 typedef INT8        int8_t;
129 typedef UINT16      uint16_t;
130 typedef INT16       int16_t;
131 typedef UINT32      uint32_t;
132 typedef INT32       int32_t;
133 #endif
134 
135 /* All other Posix platforms use stdint.h */
136 #else
137 #include <stdint.h>
138 #endif
139 
140 #if _DNS_SD_LIBDISPATCH
141 #include <dispatch/dispatch.h>
142 #endif
143 
144 /* DNSServiceRef, DNSRecordRef
145  *
146  * Opaque internal data types.
147  * Note: client is responsible for serializing access to these structures if
148  * they are shared between concurrent threads.
149  */
150 
151 typedef struct _DNSServiceRef_t *DNSServiceRef;
152 typedef struct _DNSRecordRef_t *DNSRecordRef;
153 
154 struct sockaddr;
155 
156 /*! @enum General flags
157  * Most DNS-SD API functions and callbacks include a DNSServiceFlags parameter.
158  * As a general rule, any given bit in the 32-bit flags field has a specific fixed meaning,
159  * regardless of the function or callback being used. For any given function or callback,
160  * typically only a subset of the possible flags are meaningful, and all others should be zero.
161  * The discussion section for each API call describes which flags are valid for that call
162  * and callback. In some cases, for a particular call, it may be that no flags are currently
163  * defined, in which case the DNSServiceFlags parameter exists purely to allow future expansion.
164  * In all cases, developers should expect that in future releases, it is possible that new flag
165  * values will be defined, and write code with this in mind. For example, code that tests
166  *     if (flags == kDNSServiceFlagsAdd) ...
167  * will fail if, in a future release, another bit in the 32-bit flags field is also set.
168  * The reliable way to test whether a particular bit is set is not with an equality test,
169  * but with a bitwise mask:
170  *     if (flags & kDNSServiceFlagsAdd) ...
171  */
172 enum
173     {
174     kDNSServiceFlagsMoreComing          = 0x1,
175     /* MoreComing indicates to a callback that at least one more result is
176      * queued and will be delivered following immediately after this one.
177      * When the MoreComing flag is set, applications should not immediately
178      * update their UI, because this can result in a great deal of ugly flickering
179      * on the screen, and can waste a great deal of CPU time repeatedly updating
180      * the screen with content that is then immediately erased, over and over.
181      * Applications should wait until until MoreComing is not set, and then
182      * update their UI when no more changes are imminent.
183      * When MoreComing is not set, that doesn't mean there will be no more
184      * answers EVER, just that there are no more answers immediately
185      * available right now at this instant. If more answers become available
186      * in the future they will be delivered as usual.
187      */
188 
189     kDNSServiceFlagsAdd                 = 0x2,
190     kDNSServiceFlagsDefault             = 0x4,
191     /* Flags for domain enumeration and browse/query reply callbacks.
192      * "Default" applies only to enumeration and is only valid in
193      * conjunction with "Add". An enumeration callback with the "Add"
194      * flag NOT set indicates a "Remove", i.e. the domain is no longer
195      * valid.
196      */
197 
198     kDNSServiceFlagsNoAutoRename        = 0x8,
199     /* Flag for specifying renaming behavior on name conflict when registering
200      * non-shared records. By default, name conflicts are automatically handled
201      * by renaming the service. NoAutoRename overrides this behavior - with this
202      * flag set, name conflicts will result in a callback. The NoAutorename flag
203      * is only valid if a name is explicitly specified when registering a service
204      * (i.e. the default name is not used.)
205      */
206 
207     kDNSServiceFlagsShared              = 0x10,
208     kDNSServiceFlagsUnique              = 0x20,
209     /* Flag for registering individual records on a connected
210      * DNSServiceRef. Shared indicates that there may be multiple records
211      * with this name on the network (e.g. PTR records). Unique indicates that the
212      * record's name is to be unique on the network (e.g. SRV records).
213      */
214 
215     kDNSServiceFlagsBrowseDomains       = 0x40,
216     kDNSServiceFlagsRegistrationDomains = 0x80,
217     /* Flags for specifying domain enumeration type in DNSServiceEnumerateDomains.
218      * BrowseDomains enumerates domains recommended for browsing, RegistrationDomains
219      * enumerates domains recommended for registration.
220      */
221 
222     kDNSServiceFlagsLongLivedQuery      = 0x100,
223     /* Flag for creating a long-lived unicast query for the DNSServiceQueryRecord call. */
224 
225     kDNSServiceFlagsAllowRemoteQuery    = 0x200,
226     /* Flag for creating a record for which we will answer remote queries
227      * (queries from hosts more than one hop away; hosts not directly connected to the local link).
228      */
229 
230     kDNSServiceFlagsForceMulticast      = 0x400,
231     /* Flag for signifying that a query or registration should be performed exclusively via multicast
232      * DNS, even for a name in a domain (e.g. foo.apple.com.) that would normally imply unicast DNS.
233      */
234 
235     kDNSServiceFlagsForce               = 0x800,
236     /* Flag for signifying a "stronger" variant of an operation.
237      * Currently defined only for DNSServiceReconfirmRecord(), where it forces a record to
238      * be removed from the cache immediately, instead of querying for a few seconds before
239      * concluding that the record is no longer valid and then removing it. This flag should
240      * be used with caution because if a service browsing PTR record is indeed still valid
241      * on the network, forcing its removal will result in a user-interface flap -- the
242      * discovered service instance will disappear, and then re-appear moments later.
243      */
244 
245     kDNSServiceFlagsReturnIntermediates = 0x1000,
246     /* Flag for returning intermediate results.
247      * For example, if a query results in an authoritative NXDomain (name does not exist)
248      * then that result is returned to the client. However the query is not implicitly
249      * cancelled -- it remains active and if the answer subsequently changes
250      * (e.g. because a VPN tunnel is subsequently established) then that positive
251      * result will still be returned to the client.
252      * Similarly, if a query results in a CNAME record, then in addition to following
253      * the CNAME referral, the intermediate CNAME result is also returned to the client.
254      * When this flag is not set, NXDomain errors are not returned, and CNAME records
255      * are followed silently without informing the client of the intermediate steps.
256      * (In earlier builds this flag was briefly calledkDNSServiceFlagsReturnCNAME)
257      */
258 
259     kDNSServiceFlagsNonBrowsable        = 0x2000,
260     /* A service registered with the NonBrowsable flag set can be resolved using
261      * DNSServiceResolve(), but will not be discoverable using DNSServiceBrowse().
262      * This is for cases where the name is actually a GUID; it is found by other means;
263      * there is no end-user benefit to browsing to find a long list of opaque GUIDs.
264      * Using the NonBrowsable flag creates SRV+TXT without the cost of also advertising
265      * an associated PTR record.
266      */
267 
268     kDNSServiceFlagsShareConnection     = 0x4000,
269     /* For efficiency, clients that perform many concurrent operations may want to use a
270      * single Unix Domain Socket connection with the background daemon, instead of having a
271      * separate connection for each independent operation. To use this mode, clients first
272      * call DNSServiceCreateConnection(&MainRef) to initialize the main DNSServiceRef.
273      * For each subsequent operation that is to share that same connection, the client copies
274      * the MainRef, and then passes the address of that copy, setting the ShareConnection flag
275      * to tell the library that this DNSServiceRef is not a typical uninitialized DNSServiceRef;
276      * it's a copy of an existing DNSServiceRef whose connection information should be reused.
277      *
278      * For example:
279      *
280      * DNSServiceErrorType error;
281      * DNSServiceRef MainRef;
282      * error = DNSServiceCreateConnection(&MainRef);
283      * if (error) ...
284      * DNSServiceRef BrowseRef = MainRef;  // Important: COPY the primary DNSServiceRef first...
285      * error = DNSServiceBrowse(&BrowseRef, kDNSServiceFlagsShareConnection, ...); // then use the copy
286      * if (error) ...
287      * ...
288      * DNSServiceRefDeallocate(BrowseRef); // Terminate the browse operation
289      * DNSServiceRefDeallocate(MainRef);   // Terminate the shared connection
290      *
291      * Notes:
292      *
293      * 1. Collective kDNSServiceFlagsMoreComing flag
294      * When callbacks are invoked using a shared DNSServiceRef, the
295      * kDNSServiceFlagsMoreComing flag applies collectively to *all* active
296      * operations sharing the same parent DNSServiceRef. If the MoreComing flag is
297      * set it means that there are more results queued on this parent DNSServiceRef,
298      * but not necessarily more results for this particular callback function.
299      * The implication of this for client programmers is that when a callback
300      * is invoked with the MoreComing flag set, the code should update its
301      * internal data structures with the new result, and set a variable indicating
302      * that its UI needs to be updated. Then, later when a callback is eventually
303      * invoked with the MoreComing flag not set, the code should update *all*
304      * stale UI elements related to that shared parent DNSServiceRef that need
305      * updating, not just the UI elements related to the particular callback
306      * that happened to be the last one to be invoked.
307      *
308      * 2. Canceling operations and kDNSServiceFlagsMoreComing
309      * Whenever you cancel any operation for which you had deferred UI updates
310      * waiting because of a kDNSServiceFlagsMoreComing flag, you should perform
311      * those deferred UI updates. This is because, after cancelling the operation,
312      * you can no longer wait for a callback *without* MoreComing set, to tell
313      * you do perform your deferred UI updates (the operation has been canceled,
314      * so there will be no more callbacks). An implication of the collective
315      * kDNSServiceFlagsMoreComing flag for shared connections is that this
316      * guideline applies more broadly -- any time you cancel an operation on
317      * a shared connection, you should perform all deferred UI updates for all
318      * operations sharing that connection. This is because the MoreComing flag
319      * might have been referring to events coming for the operation you canceled,
320      * which will now not be coming because the operation has been canceled.
321      *
322      * 3. Only share DNSServiceRef's created with DNSServiceCreateConnection
323      * Calling DNSServiceCreateConnection(&ref) creates a special shareable DNSServiceRef.
324      * DNSServiceRef's created by other calls like DNSServiceBrowse() or DNSServiceResolve()
325      * cannot be shared by copying them and using kDNSServiceFlagsShareConnection.
326      *
327      * 4. Don't Double-Deallocate
328      * Calling DNSServiceRefDeallocate(ref) for a particular operation's DNSServiceRef terminates
329      * just that operation. Calling DNSServiceRefDeallocate(ref) for the main shared DNSServiceRef
330      * (the parent DNSServiceRef, originally created by DNSServiceCreateConnection(&ref))
331      * automatically terminates the shared connection and all operations that were still using it.
332      * After doing this, DO NOT then attempt to deallocate any remaining subordinate DNSServiceRef's.
333      * The memory used by those subordinate DNSServiceRef's has already been freed, so any attempt
334      * to do a DNSServiceRefDeallocate (or any other operation) on them will result in accesses
335      * to freed memory, leading to crashes or other equally undesirable results.
336      *
337      * 5. Thread Safety
338      * The dns_sd.h API does not presuppose any particular threading model, and consequently
339      * does no locking of its own (which would require linking some specific threading library).
340      * If client code calls API routines on the same DNSServiceRef concurrently
341      * from multiple threads, it is the client's responsibility to use a mutext
342      * lock or take similar appropriate precautions to serialize those calls.
343      */
344 
345     kDNSServiceFlagsSuppressUnusable    = 0x8000,
346     /*
347      * This flag is meaningful only in DNSServiceQueryRecord which suppresses unusable queries on the
348      * wire. If "hostname" is a wide-area unicast DNS hostname (i.e. not a ".local." name)
349      * but this host has no routable IPv6 address, then the call will not try to look up IPv6 addresses
350      * for "hostname", since any addresses it found would be unlikely to be of any use anyway. Similarly,
351      * if this host has no routable IPv4 address, the call will not try to look up IPv4 addresses for
352      * "hostname".
353      */
354 
355     kDNSServiceFlagsTimeout            = 0x10000,
356     /*
357      * When kDNServiceFlagsTimeout is passed to DNSServiceQueryRecord or DNSServiceGetAddrInfo, the query is
358      * stopped after a certain number of seconds have elapsed. The time at which the query will be stopped
359      * is determined by the system and cannot be configured by the user. The query will be stopped irrespective
360      * of whether a response was given earlier or not. When the query is stopped, the callback will be called
361      * with an error code of kDNSServiceErr_Timeout and a NULL sockaddr will be returned for DNSServiceGetAddrInfo
362      * and zero length rdata will be returned for DNSServiceQueryRecord.
363      */
364 
365     kDNSServiceFlagsIncludeP2P          = 0x20000,
366     /*
367      * Include P2P interfaces when kDNSServiceInterfaceIndexAny is specified.
368      * By default, specifying kDNSServiceInterfaceIndexAny does not include P2P interfaces.
369      */
370     kDNSServiceFlagsWakeOnResolve      = 0x40000
371     /*
372      * This flag is meaningful only in DNSServiceResolve. When set, it tries to send a magic packet
373      * to wake up the client.
374      */
375     };
376 
377 /* Possible protocols for DNSServiceNATPortMappingCreate(). */
378 enum
379     {
380     kDNSServiceProtocol_IPv4 = 0x01,
381     kDNSServiceProtocol_IPv6 = 0x02,
382     /* 0x04 and 0x08 reserved for future internetwork protocols */
383 
384     kDNSServiceProtocol_UDP  = 0x10,
385     kDNSServiceProtocol_TCP  = 0x20
386     /* 0x40 and 0x80 reserved for future transport protocols, e.g. SCTP [RFC 2960]
387      * or DCCP [RFC 4340]. If future NAT gateways are created that support port
388      * mappings for these protocols, new constants will be defined here.
389      */
390     };
391 
392 /*
393  * The values for DNS Classes and Types are listed in RFC 1035, and are available
394  * on every OS in its DNS header file. Unfortunately every OS does not have the
395  * same header file containing DNS Class and Type constants, and the names of
396  * the constants are not consistent. For example, BIND 8 uses "T_A",
397  * BIND 9 uses "ns_t_a", Windows uses "DNS_TYPE_A", etc.
398  * For this reason, these constants are also listed here, so that code using
399  * the DNS-SD programming APIs can use these constants, so that the same code
400  * can compile on all our supported platforms.
401  */
402 
403 enum
404     {
405     kDNSServiceClass_IN       = 1       /* Internet */
406     };
407 
408 enum
409     {
410     kDNSServiceType_A          = 1,      /* Host address. */
411     kDNSServiceType_NS         = 2,      /* Authoritative server. */
412     kDNSServiceType_MD         = 3,      /* Mail destination. */
413     kDNSServiceType_MF         = 4,      /* Mail forwarder. */
414     kDNSServiceType_CNAME      = 5,      /* Canonical name. */
415     kDNSServiceType_SOA        = 6,      /* Start of authority zone. */
416     kDNSServiceType_MB         = 7,      /* Mailbox domain name. */
417     kDNSServiceType_MG         = 8,      /* Mail group member. */
418     kDNSServiceType_MR         = 9,      /* Mail rename name. */
419     kDNSServiceType_NULL       = 10,     /* Null resource record. */
420     kDNSServiceType_WKS        = 11,     /* Well known service. */
421     kDNSServiceType_PTR        = 12,     /* Domain name pointer. */
422     kDNSServiceType_HINFO      = 13,     /* Host information. */
423     kDNSServiceType_MINFO      = 14,     /* Mailbox information. */
424     kDNSServiceType_MX         = 15,     /* Mail routing information. */
425     kDNSServiceType_TXT        = 16,     /* One or more text strings (NOT "zero or more..."). */
426     kDNSServiceType_RP         = 17,     /* Responsible person. */
427     kDNSServiceType_AFSDB      = 18,     /* AFS cell database. */
428     kDNSServiceType_X25        = 19,     /* X_25 calling address. */
429     kDNSServiceType_ISDN       = 20,     /* ISDN calling address. */
430     kDNSServiceType_RT         = 21,     /* Router. */
431     kDNSServiceType_NSAP       = 22,     /* NSAP address. */
432     kDNSServiceType_NSAP_PTR   = 23,     /* Reverse NSAP lookup (deprecated). */
433     kDNSServiceType_SIG        = 24,     /* Security signature. */
434     kDNSServiceType_KEY        = 25,     /* Security key. */
435     kDNSServiceType_PX         = 26,     /* X.400 mail mapping. */
436     kDNSServiceType_GPOS       = 27,     /* Geographical position (withdrawn). */
437     kDNSServiceType_AAAA       = 28,     /* IPv6 Address. */
438     kDNSServiceType_LOC        = 29,     /* Location Information. */
439     kDNSServiceType_NXT        = 30,     /* Next domain (security). */
440     kDNSServiceType_EID        = 31,     /* Endpoint identifier. */
441     kDNSServiceType_NIMLOC     = 32,     /* Nimrod Locator. */
442     kDNSServiceType_SRV        = 33,     /* Server Selection. */
443     kDNSServiceType_ATMA       = 34,     /* ATM Address */
444     kDNSServiceType_NAPTR      = 35,     /* Naming Authority PoinTeR */
445     kDNSServiceType_KX         = 36,     /* Key Exchange */
446     kDNSServiceType_CERT       = 37,     /* Certification record */
447     kDNSServiceType_A6         = 38,     /* IPv6 Address (deprecated) */
448     kDNSServiceType_DNAME      = 39,     /* Non-terminal DNAME (for IPv6) */
449     kDNSServiceType_SINK       = 40,     /* Kitchen sink (experimental) */
450     kDNSServiceType_OPT        = 41,     /* EDNS0 option (meta-RR) */
451     kDNSServiceType_APL        = 42,     /* Address Prefix List */
452     kDNSServiceType_DS         = 43,     /* Delegation Signer */
453     kDNSServiceType_SSHFP      = 44,     /* SSH Key Fingerprint */
454     kDNSServiceType_IPSECKEY   = 45,     /* IPSECKEY */
455     kDNSServiceType_RRSIG      = 46,     /* RRSIG */
456     kDNSServiceType_NSEC       = 47,     /* Denial of Existence */
457     kDNSServiceType_DNSKEY     = 48,     /* DNSKEY */
458     kDNSServiceType_DHCID      = 49,     /* DHCP Client Identifier */
459     kDNSServiceType_NSEC3      = 50,     /* Hashed Authenticated Denial of Existence */
460     kDNSServiceType_NSEC3PARAM = 51,     /* Hashed Authenticated Denial of Existence */
461 
462     kDNSServiceType_HIP        = 55,     /* Host Identity Protocol */
463 
464     kDNSServiceType_SPF        = 99,     /* Sender Policy Framework for E-Mail */
465     kDNSServiceType_UINFO      = 100,    /* IANA-Reserved */
466     kDNSServiceType_UID        = 101,    /* IANA-Reserved */
467     kDNSServiceType_GID        = 102,    /* IANA-Reserved */
468     kDNSServiceType_UNSPEC     = 103,    /* IANA-Reserved */
469 
470     kDNSServiceType_TKEY       = 249,    /* Transaction key */
471     kDNSServiceType_TSIG       = 250,    /* Transaction signature. */
472     kDNSServiceType_IXFR       = 251,    /* Incremental zone transfer. */
473     kDNSServiceType_AXFR       = 252,    /* Transfer zone of authority. */
474     kDNSServiceType_MAILB      = 253,    /* Transfer mailbox records. */
475     kDNSServiceType_MAILA      = 254,    /* Transfer mail agent records. */
476     kDNSServiceType_ANY        = 255     /* Wildcard match. */
477     };
478 
479 /* possible error code values */
480 enum
481     {
482     kDNSServiceErr_NoError                   = 0,
483     kDNSServiceErr_Unknown                   = -65537,  /* 0xFFFE FFFF */
484     kDNSServiceErr_NoSuchName                = -65538,
485     kDNSServiceErr_NoMemory                  = -65539,
486     kDNSServiceErr_BadParam                  = -65540,
487     kDNSServiceErr_BadReference              = -65541,
488     kDNSServiceErr_BadState                  = -65542,
489     kDNSServiceErr_BadFlags                  = -65543,
490     kDNSServiceErr_Unsupported               = -65544,
491     kDNSServiceErr_NotInitialized            = -65545,
492     kDNSServiceErr_AlreadyRegistered         = -65547,
493     kDNSServiceErr_NameConflict              = -65548,
494     kDNSServiceErr_Invalid                   = -65549,
495     kDNSServiceErr_Firewall                  = -65550,
496     kDNSServiceErr_Incompatible              = -65551,  /* client library incompatible with daemon */
497     kDNSServiceErr_BadInterfaceIndex         = -65552,
498     kDNSServiceErr_Refused                   = -65553,
499     kDNSServiceErr_NoSuchRecord              = -65554,
500     kDNSServiceErr_NoAuth                    = -65555,
501     kDNSServiceErr_NoSuchKey                 = -65556,
502     kDNSServiceErr_NATTraversal              = -65557,
503     kDNSServiceErr_DoubleNAT                 = -65558,
504     kDNSServiceErr_BadTime                   = -65559,  /* Codes up to here existed in Tiger */
505     kDNSServiceErr_BadSig                    = -65560,
506     kDNSServiceErr_BadKey                    = -65561,
507     kDNSServiceErr_Transient                 = -65562,
508     kDNSServiceErr_ServiceNotRunning         = -65563,  /* Background daemon not running */
509     kDNSServiceErr_NATPortMappingUnsupported = -65564,  /* NAT doesn't support NAT-PMP or UPnP */
510     kDNSServiceErr_NATPortMappingDisabled    = -65565,  /* NAT supports NAT-PMP or UPnP but it's disabled by the administrator */
511     kDNSServiceErr_NoRouter                  = -65566,  /* No router currently configured (probably no network connectivity) */
512     kDNSServiceErr_PollingMode               = -65567,
513     kDNSServiceErr_Timeout                   = -65568
514 
515     /* mDNS Error codes are in the range
516      * FFFE FF00 (-65792) to FFFE FFFF (-65537) */
517     };
518 
519 /* Maximum length, in bytes, of a service name represented as a */
520 /* literal C-String, including the terminating NULL at the end. */
521 
522 #define kDNSServiceMaxServiceName 64
523 
524 /* Maximum length, in bytes, of a domain name represented as an *escaped* C-String */
525 /* including the final trailing dot, and the C-String terminating NULL at the end. */
526 
527 #define kDNSServiceMaxDomainName 1009
528 
529 /*
530  * Notes on DNS Name Escaping
531  *   -- or --
532  * "Why is kDNSServiceMaxDomainName 1009, when the maximum legal domain name is 256 bytes?"
533  *
534  * All strings used in the DNS-SD APIs are UTF-8 strings. Apart from the exceptions noted below,
535  * the APIs expect the strings to be properly escaped, using the conventional DNS escaping rules:
536  *
537  *   '\\' represents a single literal '\' in the name
538  *   '\.' represents a single literal '.' in the name
539  *   '\ddd', where ddd is a three-digit decimal value from 000 to 255,
540  *        represents a single literal byte with that value.
541  *   A bare unescaped '.' is a label separator, marking a boundary between domain and subdomain.
542  *
543  * The exceptions, that do not use escaping, are the routines where the full
544  * DNS name of a resource is broken, for convenience, into servicename/regtype/domain.
545  * In these routines, the "servicename" is NOT escaped. It does not need to be, since
546  * it is, by definition, just a single literal string. Any characters in that string
547  * represent exactly what they are. The "regtype" portion is, technically speaking,
548  * escaped, but since legal regtypes are only allowed to contain letters, digits,
549  * and hyphens, there is nothing to escape, so the issue is moot. The "domain"
550  * portion is also escaped, though most domains in use on the public Internet
551  * today, like regtypes, don't contain any characters that need to be escaped.
552  * As DNS-SD becomes more popular, rich-text domains for service discovery will
553  * become common, so software should be written to cope with domains with escaping.
554  *
555  * The servicename may be up to 63 bytes of UTF-8 text (not counting the C-String
556  * terminating NULL at the end). The regtype is of the form _service._tcp or
557  * _service._udp, where the "service" part is 1-15 characters, which may be
558  * letters, digits, or hyphens. The domain part of the three-part name may be
559  * any legal domain, providing that the resulting servicename+regtype+domain
560  * name does not exceed 256 bytes.
561  *
562  * For most software, these issues are transparent. When browsing, the discovered
563  * servicenames should simply be displayed as-is. When resolving, the discovered
564  * servicename/regtype/domain are simply passed unchanged to DNSServiceResolve().
565  * When a DNSServiceResolve() succeeds, the returned fullname is already in
566  * the correct format to pass to standard system DNS APIs such as res_query().
567  * For converting from servicename/regtype/domain to a single properly-escaped
568  * full DNS name, the helper function DNSServiceConstructFullName() is provided.
569  *
570  * The following (highly contrived) example illustrates the escaping process.
571  * Suppose you have an service called "Dr. Smith\Dr. Johnson", of type "_ftp._tcp"
572  * in subdomain "4th. Floor" of subdomain "Building 2" of domain "apple.com."
573  * The full (escaped) DNS name of this service's SRV record would be:
574  * Dr\.\032Smith\\Dr\.\032Johnson._ftp._tcp.4th\.\032Floor.Building\0322.apple.com.
575  */
576 
577 
578 /*
579  * Constants for specifying an interface index
580  *
581  * Specific interface indexes are identified via a 32-bit unsigned integer returned
582  * by the if_nametoindex() family of calls.
583  *
584  * If the client passes 0 for interface index, that means "do the right thing",
585  * which (at present) means, "if the name is in an mDNS local multicast domain
586  * (e.g. 'local.', '254.169.in-addr.arpa.', '{8,9,A,B}.E.F.ip6.arpa.') then multicast
587  * on all applicable interfaces, otherwise send via unicast to the appropriate
588  * DNS server." Normally, most clients will use 0 for interface index to
589  * automatically get the default sensible behaviour.
590  *
591  * If the client passes a positive interface index, then for multicast names that
592  * indicates to do the operation only on that one interface. For unicast names the
593  * interface index is ignored unless kDNSServiceFlagsForceMulticast is also set.
594  *
595  * If the client passes kDNSServiceInterfaceIndexLocalOnly when registering
596  * a service, then that service will be found *only* by other local clients
597  * on the same machine that are browsing using kDNSServiceInterfaceIndexLocalOnly
598  * or kDNSServiceInterfaceIndexAny.
599  * If a client has a 'private' service, accessible only to other processes
600  * running on the same machine, this allows the client to advertise that service
601  * in a way such that it does not inadvertently appear in service lists on
602  * all the other machines on the network.
603  *
604  * If the client passes kDNSServiceInterfaceIndexLocalOnly when browsing
605  * then it will find *all* records registered on that same local machine.
606  * Clients explicitly wishing to discover *only* LocalOnly services can
607  * accomplish this by inspecting the interfaceIndex of each service reported
608  * to their DNSServiceBrowseReply() callback function, and discarding those
609  * where the interface index is not kDNSServiceInterfaceIndexLocalOnly.
610  *
611  * kDNSServiceInterfaceIndexP2P is meaningful only in Browse, QueryRecord,
612  * and Resolve operations. It should not be used in other DNSService APIs.
613  *
614  * - If kDNSServiceInterfaceIndexP2P is passed to DNSServiceBrowse or
615  *   DNSServiceQueryRecord, it restricts the operation to P2P.
616  *
617  * - If kDNSServiceInterfaceIndexP2P is passed to DNSServiceResolve, it is
618  *   mapped internally to kDNSServiceInterfaceIndexAny, because resolving
619  *   a P2P service may create and/or enable an interface whose index is not
620  *   known a priori. The resolve callback will indicate the index of the
621  *   interface via which the service can be accessed.
622  *
623  * If applications pass kDNSServiceInterfaceIndexAny to DNSServiceBrowse
624  * or DNSServiceQueryRecord, they must set the kDNSServiceFlagsIncludeP2P flag
625  * to include P2P. In this case, if a service instance or the record being queried
626  * is found over P2P, the resulting ADD event will indicate kDNSServiceInterfaceIndexP2P
627  * as the interface index.
628  */
629 
630 #define kDNSServiceInterfaceIndexAny 0
631 #define kDNSServiceInterfaceIndexLocalOnly ((uint32_t)-1)
632 #define kDNSServiceInterfaceIndexUnicast   ((uint32_t)-2)
633 #define kDNSServiceInterfaceIndexP2P       ((uint32_t)-3)
634 
635 typedef uint32_t DNSServiceFlags;
636 typedef uint32_t DNSServiceProtocol;
637 typedef int32_t  DNSServiceErrorType;
638 
639 
640 /*********************************************************************************************
641  *
642  * Version checking
643  *
644  *********************************************************************************************/
645 
646 /* DNSServiceGetProperty() Parameters:
647  *
648  * property:        The requested property.
649  *                  Currently the only property defined is kDNSServiceProperty_DaemonVersion.
650  *
651  * result:          Place to store result.
652  *                  For retrieving DaemonVersion, this should be the address of a uint32_t.
653  *
654  * size:            Pointer to uint32_t containing size of the result location.
655  *                  For retrieving DaemonVersion, this should be sizeof(uint32_t).
656  *                  On return the uint32_t is updated to the size of the data returned.
657  *                  For DaemonVersion, the returned size is always sizeof(uint32_t), but
658  *                  future properties could be defined which return variable-sized results.
659  *
660  * return value:    Returns kDNSServiceErr_NoError on success, or kDNSServiceErr_ServiceNotRunning
661  *                  if the daemon (or "system service" on Windows) is not running.
662  */
663 
664 DNSServiceErrorType DNSSD_API DNSServiceGetProperty
665     (
666     const char *property,  /* Requested property (i.e. kDNSServiceProperty_DaemonVersion) */
667     void       *result,    /* Pointer to place to store result */
668     uint32_t   *size       /* size of result location */
669     );
670 
671 /*
672  * When requesting kDNSServiceProperty_DaemonVersion, the result pointer must point
673  * to a 32-bit unsigned integer, and the size parameter must be set to sizeof(uint32_t).
674  *
675  * On return, the 32-bit unsigned integer contains the version number, formatted as follows:
676  *   Major part of the build number * 10000 +
677  *   minor part of the build number *   100
678  *
679  * For example, Mac OS X 10.4.9 has mDNSResponder-108.4, which would be represented as
680  * version 1080400. This allows applications to do simple greater-than and less-than comparisons:
681  * e.g. an application that requires at least mDNSResponder-108.4 can check:
682  *
683  *   if (version >= 1080400) ...
684  *
685  * Example usage:
686  *
687  * uint32_t version;
688  * uint32_t size = sizeof(version);
689  * DNSServiceErrorType err = DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion, &version, &size);
690  * if (!err) printf("Bonjour version is %d.%d\n", version / 10000, version / 100 % 100);
691  */
692 
693 #define kDNSServiceProperty_DaemonVersion "DaemonVersion"
694 
695 
696 /*********************************************************************************************
697  *
698  * Unix Domain Socket access, DNSServiceRef deallocation, and data processing functions
699  *
700  *********************************************************************************************/
701 
702 /* DNSServiceRefSockFD()
703  *
704  * Access underlying Unix domain socket for an initialized DNSServiceRef.
705  * The DNS Service Discovery implementation uses this socket to communicate between the client and
706  * the mDNSResponder daemon. The application MUST NOT directly read from or write to this socket.
707  * Access to the socket is provided so that it can be used as a kqueue event source, a CFRunLoop
708  * event source, in a select() loop, etc. When the underlying event management subsystem (kqueue/
709  * select/CFRunLoop etc.) indicates to the client that data is available for reading on the
710  * socket, the client should call DNSServiceProcessResult(), which will extract the daemon's
711  * reply from the socket, and pass it to the appropriate application callback. By using a run
712  * loop or select(), results from the daemon can be processed asynchronously. Alternatively,
713  * a client can choose to fork a thread and have it loop calling "DNSServiceProcessResult(ref);"
714  * If DNSServiceProcessResult() is called when no data is available for reading on the socket, it
715  * will block until data does become available, and then process the data and return to the caller.
716  * When data arrives on the socket, the client is responsible for calling DNSServiceProcessResult(ref)
717  * in a timely fashion -- if the client allows a large backlog of data to build up the daemon
718  * may terminate the connection.
719  *
720  * sdRef:           A DNSServiceRef initialized by any of the DNSService calls.
721  *
722  * return value:    The DNSServiceRef's underlying socket descriptor, or -1 on
723  *                  error.
724  */
725 
726 int DNSSD_API DNSServiceRefSockFD(DNSServiceRef sdRef);
727 
728 
729 /* DNSServiceProcessResult()
730  *
731  * Read a reply from the daemon, calling the appropriate application callback. This call will
732  * block until the daemon's response is received. Use DNSServiceRefSockFD() in
733  * conjunction with a run loop or select() to determine the presence of a response from the
734  * server before calling this function to process the reply without blocking. Call this function
735  * at any point if it is acceptable to block until the daemon's response arrives. Note that the
736  * client is responsible for ensuring that DNSServiceProcessResult() is called whenever there is
737  * a reply from the daemon - the daemon may terminate its connection with a client that does not
738  * process the daemon's responses.
739  *
740  * sdRef:           A DNSServiceRef initialized by any of the DNSService calls
741  *                  that take a callback parameter.
742  *
743  * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns
744  *                  an error code indicating the specific failure that occurred.
745  */
746 
747 DNSServiceErrorType DNSSD_API DNSServiceProcessResult(DNSServiceRef sdRef);
748 
749 
750 /* DNSServiceRefDeallocate()
751  *
752  * Terminate a connection with the daemon and free memory associated with the DNSServiceRef.
753  * Any services or records registered with this DNSServiceRef will be deregistered. Any
754  * Browse, Resolve, or Query operations called with this reference will be terminated.
755  *
756  * Note: If the reference's underlying socket is used in a run loop or select() call, it should
757  * be removed BEFORE DNSServiceRefDeallocate() is called, as this function closes the reference's
758  * socket.
759  *
760  * Note: If the reference was initialized with DNSServiceCreateConnection(), any DNSRecordRefs
761  * created via this reference will be invalidated by this call - the resource records are
762  * deregistered, and their DNSRecordRefs may not be used in subsequent functions. Similarly,
763  * if the reference was initialized with DNSServiceRegister, and an extra resource record was
764  * added to the service via DNSServiceAddRecord(), the DNSRecordRef created by the Add() call
765  * is invalidated when this function is called - the DNSRecordRef may not be used in subsequent
766  * functions.
767  *
768  * Note: This call is to be used only with the DNSServiceRef defined by this API. It is
769  * not compatible with dns_service_discovery_ref objects defined in the legacy Mach-based
770  * DNSServiceDiscovery.h API.
771  *
772  * sdRef:           A DNSServiceRef initialized by any of the DNSService calls.
773  *
774  */
775 
776 void DNSSD_API DNSServiceRefDeallocate(DNSServiceRef sdRef);
777 
778 
779 /*********************************************************************************************
780  *
781  * Domain Enumeration
782  *
783  *********************************************************************************************/
784 
785 /* DNSServiceEnumerateDomains()
786  *
787  * Asynchronously enumerate domains available for browsing and registration.
788  *
789  * The enumeration MUST be cancelled via DNSServiceRefDeallocate() when no more domains
790  * are to be found.
791  *
792  * Note that the names returned are (like all of DNS-SD) UTF-8 strings,
793  * and are escaped using standard DNS escaping rules.
794  * (See "Notes on DNS Name Escaping" earlier in this file for more details.)
795  * A graphical browser displaying a hierarchical tree-structured view should cut
796  * the names at the bare dots to yield individual labels, then de-escape each
797  * label according to the escaping rules, and then display the resulting UTF-8 text.
798  *
799  * DNSServiceDomainEnumReply Callback Parameters:
800  *
801  * sdRef:           The DNSServiceRef initialized by DNSServiceEnumerateDomains().
802  *
803  * flags:           Possible values are:
804  *                  kDNSServiceFlagsMoreComing
805  *                  kDNSServiceFlagsAdd
806  *                  kDNSServiceFlagsDefault
807  *
808  * interfaceIndex:  Specifies the interface on which the domain exists. (The index for a given
809  *                  interface is determined via the if_nametoindex() family of calls.)
810  *
811  * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise indicates
812  *                  the failure that occurred (other parameters are undefined if errorCode is nonzero).
813  *
814  * replyDomain:     The name of the domain.
815  *
816  * context:         The context pointer passed to DNSServiceEnumerateDomains.
817  *
818  */
819 
820 typedef void (DNSSD_API *DNSServiceDomainEnumReply)
821     (
822     DNSServiceRef                       sdRef,
823     DNSServiceFlags                     flags,
824     uint32_t                            interfaceIndex,
825     DNSServiceErrorType                 errorCode,
826     const char                          *replyDomain,
827     void                                *context
828     );
829 
830 
831 /* DNSServiceEnumerateDomains() Parameters:
832  *
833  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds
834  *                  then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError,
835  *                  and the enumeration operation will run indefinitely until the client
836  *                  terminates it by passing this DNSServiceRef to DNSServiceRefDeallocate().
837  *
838  * flags:           Possible values are:
839  *                  kDNSServiceFlagsBrowseDomains to enumerate domains recommended for browsing.
840  *                  kDNSServiceFlagsRegistrationDomains to enumerate domains recommended
841  *                  for registration.
842  *
843  * interfaceIndex:  If non-zero, specifies the interface on which to look for domains.
844  *                  (the index for a given interface is determined via the if_nametoindex()
845  *                  family of calls.) Most applications will pass 0 to enumerate domains on
846  *                  all interfaces. See "Constants for specifying an interface index" for more details.
847  *
848  * callBack:        The function to be called when a domain is found or the call asynchronously
849  *                  fails.
850  *
851  * context:         An application context pointer which is passed to the callback function
852  *                  (may be NULL).
853  *
854  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
855  *                  errors are delivered to the callback), otherwise returns an error code indicating
856  *                  the error that occurred (the callback is not invoked and the DNSServiceRef
857  *                  is not initialized).
858  */
859 
860 DNSServiceErrorType DNSSD_API DNSServiceEnumerateDomains
861     (
862     DNSServiceRef                       *sdRef,
863     DNSServiceFlags                     flags,
864     uint32_t                            interfaceIndex,
865     DNSServiceDomainEnumReply           callBack,
866     void                                *context  /* may be NULL */
867     );
868 
869 
870 /*********************************************************************************************
871  *
872  *  Service Registration
873  *
874  *********************************************************************************************/
875 
876 /* Register a service that is discovered via Browse() and Resolve() calls.
877  *
878  * DNSServiceRegisterReply() Callback Parameters:
879  *
880  * sdRef:           The DNSServiceRef initialized by DNSServiceRegister().
881  *
882  * flags:           When a name is successfully registered, the callback will be
883  *                  invoked with the kDNSServiceFlagsAdd flag set. When Wide-Area
884  *                  DNS-SD is in use, it is possible for a single service to get
885  *                  more than one success callback (e.g. one in the "local" multicast
886  *                  DNS domain, and another in a wide-area unicast DNS domain).
887  *                  If a successfully-registered name later suffers a name conflict
888  *                  or similar problem and has to be deregistered, the callback will
889  *                  be invoked with the kDNSServiceFlagsAdd flag not set. The callback
890  *                  is *not* invoked in the case where the caller explicitly terminates
891  *                  the service registration by calling DNSServiceRefDeallocate(ref);
892  *
893  * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
894  *                  indicate the failure that occurred (including name conflicts,
895  *                  if the kDNSServiceFlagsNoAutoRename flag was used when registering.)
896  *                  Other parameters are undefined if errorCode is nonzero.
897  *
898  * name:            The service name registered (if the application did not specify a name in
899  *                  DNSServiceRegister(), this indicates what name was automatically chosen).
900  *
901  * regtype:         The type of service registered, as it was passed to the callout.
902  *
903  * domain:          The domain on which the service was registered (if the application did not
904  *                  specify a domain in DNSServiceRegister(), this indicates the default domain
905  *                  on which the service was registered).
906  *
907  * context:         The context pointer that was passed to the callout.
908  *
909  */
910 
911 typedef void (DNSSD_API *DNSServiceRegisterReply)
912     (
913     DNSServiceRef                       sdRef,
914     DNSServiceFlags                     flags,
915     DNSServiceErrorType                 errorCode,
916     const char                          *name,
917     const char                          *regtype,
918     const char                          *domain,
919     void                                *context
920     );
921 
922 
923 /* DNSServiceRegister() Parameters:
924  *
925  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds
926  *                  then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError,
927  *                  and the registration will remain active indefinitely until the client
928  *                  terminates it by passing this DNSServiceRef to DNSServiceRefDeallocate().
929  *
930  * interfaceIndex:  If non-zero, specifies the interface on which to register the service
931  *                  (the index for a given interface is determined via the if_nametoindex()
932  *                  family of calls.) Most applications will pass 0 to register on all
933  *                  available interfaces. See "Constants for specifying an interface index" for more details.
934  *
935  * flags:           Indicates the renaming behavior on name conflict (most applications
936  *                  will pass 0). See flag definitions above for details.
937  *
938  * name:            If non-NULL, specifies the service name to be registered.
939  *                  Most applications will not specify a name, in which case the computer
940  *                  name is used (this name is communicated to the client via the callback).
941  *                  If a name is specified, it must be 1-63 bytes of UTF-8 text.
942  *                  If the name is longer than 63 bytes it will be automatically truncated
943  *                  to a legal length, unless the NoAutoRename flag is set,
944  *                  in which case kDNSServiceErr_BadParam will be returned.
945  *
946  * regtype:         The service type followed by the protocol, separated by a dot
947  *                  (e.g. "_ftp._tcp"). The service type must be an underscore, followed
948  *                  by 1-15 characters, which may be letters, digits, or hyphens.
949  *                  The transport protocol must be "_tcp" or "_udp". New service types
950  *                  should be registered at <http://www.dns-sd.org/ServiceTypes.html>.
951  *
952  *                  Additional subtypes of the primary service type (where a service
953  *                  type has defined subtypes) follow the primary service type in a
954  *                  comma-separated list, with no additional spaces, e.g.
955  *                      "_primarytype._tcp,_subtype1,_subtype2,_subtype3"
956  *                  Subtypes provide a mechanism for filtered browsing: A client browsing
957  *                  for "_primarytype._tcp" will discover all instances of this type;
958  *                  a client browsing for "_primarytype._tcp,_subtype2" will discover only
959  *                  those instances that were registered with "_subtype2" in their list of
960  *                  registered subtypes.
961  *
962  *                  The subtype mechanism can be illustrated with some examples using the
963  *                  dns-sd command-line tool:
964  *
965  *                  % dns-sd -R Simple _test._tcp "" 1001 &
966  *                  % dns-sd -R Better _test._tcp,HasFeatureA "" 1002 &
967  *                  % dns-sd -R Best   _test._tcp,HasFeatureA,HasFeatureB "" 1003 &
968  *
969  *                  Now:
970  *                  % dns-sd -B _test._tcp             # will find all three services
971  *                  % dns-sd -B _test._tcp,HasFeatureA # finds "Better" and "Best"
972  *                  % dns-sd -B _test._tcp,HasFeatureB # finds only "Best"
973  *
974  *                  Subtype labels may be up to 63 bytes long, and may contain any eight-
975  *                  bit byte values, including zero bytes. However, due to the nature of
976  *                  using a C-string-based API, conventional DNS escaping must be used for
977  *                  dots ('.'), commas (','), backslashes ('\') and zero bytes, as shown below:
978  *
979  *                  % dns-sd -R Test '_test._tcp,s\.one,s\,two,s\\three,s\000four' local 123
980  *
981  * domain:          If non-NULL, specifies the domain on which to advertise the service.
982  *                  Most applications will not specify a domain, instead automatically
983  *                  registering in the default domain(s).
984  *
985  * host:            If non-NULL, specifies the SRV target host name. Most applications
986  *                  will not specify a host, instead automatically using the machine's
987  *                  default host name(s). Note that specifying a non-NULL host does NOT
988  *                  create an address record for that host - the application is responsible
989  *                  for ensuring that the appropriate address record exists, or creating it
990  *                  via DNSServiceRegisterRecord().
991  *
992  * port:            The port, in network byte order, on which the service accepts connections.
993  *                  Pass 0 for a "placeholder" service (i.e. a service that will not be discovered
994  *                  by browsing, but will cause a name conflict if another client tries to
995  *                  register that same name). Most clients will not use placeholder services.
996  *
997  * txtLen:          The length of the txtRecord, in bytes. Must be zero if the txtRecord is NULL.
998  *
999  * txtRecord:       The TXT record rdata. A non-NULL txtRecord MUST be a properly formatted DNS
1000  *                  TXT record, i.e. <length byte> <data> <length byte> <data> ...
1001  *                  Passing NULL for the txtRecord is allowed as a synonym for txtLen=1, txtRecord="",
1002  *                  i.e. it creates a TXT record of length one containing a single empty string.
1003  *                  RFC 1035 doesn't allow a TXT record to contain *zero* strings, so a single empty
1004  *                  string is the smallest legal DNS TXT record.
1005  *                  As with the other parameters, the DNSServiceRegister call copies the txtRecord
1006  *                  data; e.g. if you allocated the storage for the txtRecord parameter with malloc()
1007  *                  then you can safely free that memory right after the DNSServiceRegister call returns.
1008  *
1009  * callBack:        The function to be called when the registration completes or asynchronously
1010  *                  fails. The client MAY pass NULL for the callback -  The client will NOT be notified
1011  *                  of the default values picked on its behalf, and the client will NOT be notified of any
1012  *                  asynchronous errors (e.g. out of memory errors, etc.) that may prevent the registration
1013  *                  of the service. The client may NOT pass the NoAutoRename flag if the callback is NULL.
1014  *                  The client may still deregister the service at any time via DNSServiceRefDeallocate().
1015  *
1016  * context:         An application context pointer which is passed to the callback function
1017  *                  (may be NULL).
1018  *
1019  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1020  *                  errors are delivered to the callback), otherwise returns an error code indicating
1021  *                  the error that occurred (the callback is never invoked and the DNSServiceRef
1022  *                  is not initialized).
1023  */
1024 
1025 DNSServiceErrorType DNSSD_API DNSServiceRegister
1026     (
1027     DNSServiceRef                       *sdRef,
1028     DNSServiceFlags                     flags,
1029     uint32_t                            interfaceIndex,
1030     const char                          *name,         /* may be NULL */
1031     const char                          *regtype,
1032     const char                          *domain,       /* may be NULL */
1033     const char                          *host,         /* may be NULL */
1034     uint16_t                            port,          /* In network byte order */
1035     uint16_t                            txtLen,
1036     const void                          *txtRecord,    /* may be NULL */
1037     DNSServiceRegisterReply             callBack,      /* may be NULL */
1038     void                                *context       /* may be NULL */
1039     );
1040 
1041 
1042 /* DNSServiceAddRecord()
1043  *
1044  * Add a record to a registered service. The name of the record will be the same as the
1045  * registered service's name.
1046  * The record can later be updated or deregistered by passing the RecordRef initialized
1047  * by this function to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
1048  *
1049  * Note that the DNSServiceAddRecord/UpdateRecord/RemoveRecord are *NOT* thread-safe
1050  * with respect to a single DNSServiceRef. If you plan to have multiple threads
1051  * in your program simultaneously add, update, or remove records from the same
1052  * DNSServiceRef, then it's the caller's responsibility to use a mutext lock
1053  * or take similar appropriate precautions to serialize those calls.
1054  *
1055  * Parameters;
1056  *
1057  * sdRef:           A DNSServiceRef initialized by DNSServiceRegister().
1058  *
1059  * RecordRef:       A pointer to an uninitialized DNSRecordRef. Upon succesful completion of this
1060  *                  call, this ref may be passed to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
1061  *                  If the above DNSServiceRef is passed to DNSServiceRefDeallocate(), RecordRef is also
1062  *                  invalidated and may not be used further.
1063  *
1064  * flags:           Currently ignored, reserved for future use.
1065  *
1066  * rrtype:          The type of the record (e.g. kDNSServiceType_TXT, kDNSServiceType_SRV, etc)
1067  *
1068  * rdlen:           The length, in bytes, of the rdata.
1069  *
1070  * rdata:           The raw rdata to be contained in the added resource record.
1071  *
1072  * ttl:             The time to live of the resource record, in seconds.
1073  *                  Most clients should pass 0 to indicate that the system should
1074  *                  select a sensible default value.
1075  *
1076  * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
1077  *                  error code indicating the error that occurred (the RecordRef is not initialized).
1078  */
1079 
1080 DNSServiceErrorType DNSSD_API DNSServiceAddRecord
1081     (
1082     DNSServiceRef                       sdRef,
1083     DNSRecordRef                        *RecordRef,
1084     DNSServiceFlags                     flags,
1085     uint16_t                            rrtype,
1086     uint16_t                            rdlen,
1087     const void                          *rdata,
1088     uint32_t                            ttl
1089     );
1090 
1091 
1092 /* DNSServiceUpdateRecord
1093  *
1094  * Update a registered resource record. The record must either be:
1095  *   - The primary txt record of a service registered via DNSServiceRegister()
1096  *   - A record added to a registered service via DNSServiceAddRecord()
1097  *   - An individual record registered by DNSServiceRegisterRecord()
1098  *
1099  * Parameters:
1100  *
1101  * sdRef:           A DNSServiceRef that was initialized by DNSServiceRegister()
1102  *                  or DNSServiceCreateConnection().
1103  *
1104  * RecordRef:       A DNSRecordRef initialized by DNSServiceAddRecord, or NULL to update the
1105  *                  service's primary txt record.
1106  *
1107  * flags:           Currently ignored, reserved for future use.
1108  *
1109  * rdlen:           The length, in bytes, of the new rdata.
1110  *
1111  * rdata:           The new rdata to be contained in the updated resource record.
1112  *
1113  * ttl:             The time to live of the updated resource record, in seconds.
1114  *                  Most clients should pass 0 to indicate that the system should
1115  *                  select a sensible default value.
1116  *
1117  * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
1118  *                  error code indicating the error that occurred.
1119  */
1120 
1121 DNSServiceErrorType DNSSD_API DNSServiceUpdateRecord
1122     (
1123     DNSServiceRef                       sdRef,
1124     DNSRecordRef                        RecordRef,     /* may be NULL */
1125     DNSServiceFlags                     flags,
1126     uint16_t                            rdlen,
1127     const void                          *rdata,
1128     uint32_t                            ttl
1129     );
1130 
1131 
1132 /* DNSServiceRemoveRecord
1133  *
1134  * Remove a record previously added to a service record set via DNSServiceAddRecord(), or deregister
1135  * an record registered individually via DNSServiceRegisterRecord().
1136  *
1137  * Parameters:
1138  *
1139  * sdRef:           A DNSServiceRef initialized by DNSServiceRegister() (if the
1140  *                  record being removed was registered via DNSServiceAddRecord()) or by
1141  *                  DNSServiceCreateConnection() (if the record being removed was registered via
1142  *                  DNSServiceRegisterRecord()).
1143  *
1144  * recordRef:       A DNSRecordRef initialized by a successful call to DNSServiceAddRecord()
1145  *                  or DNSServiceRegisterRecord().
1146  *
1147  * flags:           Currently ignored, reserved for future use.
1148  *
1149  * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns an
1150  *                  error code indicating the error that occurred.
1151  */
1152 
1153 DNSServiceErrorType DNSSD_API DNSServiceRemoveRecord
1154     (
1155     DNSServiceRef                 sdRef,
1156     DNSRecordRef                  RecordRef,
1157     DNSServiceFlags               flags
1158     );
1159 
1160 
1161 /*********************************************************************************************
1162  *
1163  *  Service Discovery
1164  *
1165  *********************************************************************************************/
1166 
1167 /* Browse for instances of a service.
1168  *
1169  * DNSServiceBrowseReply() Parameters:
1170  *
1171  * sdRef:           The DNSServiceRef initialized by DNSServiceBrowse().
1172  *
1173  * flags:           Possible values are kDNSServiceFlagsMoreComing and kDNSServiceFlagsAdd.
1174  *                  See flag definitions for details.
1175  *
1176  * interfaceIndex:  The interface on which the service is advertised. This index should
1177  *                  be passed to DNSServiceResolve() when resolving the service.
1178  *
1179  * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will
1180  *                  indicate the failure that occurred. Other parameters are undefined if
1181  *                  the errorCode is nonzero.
1182  *
1183  * serviceName:     The discovered service name. This name should be displayed to the user,
1184  *                  and stored for subsequent use in the DNSServiceResolve() call.
1185  *
1186  * regtype:         The service type, which is usually (but not always) the same as was passed
1187  *                  to DNSServiceBrowse(). One case where the discovered service type may
1188  *                  not be the same as the requested service type is when using subtypes:
1189  *                  The client may want to browse for only those ftp servers that allow
1190  *                  anonymous connections. The client will pass the string "_ftp._tcp,_anon"
1191  *                  to DNSServiceBrowse(), but the type of the service that's discovered
1192  *                  is simply "_ftp._tcp". The regtype for each discovered service instance
1193  *                  should be stored along with the name, so that it can be passed to
1194  *                  DNSServiceResolve() when the service is later resolved.
1195  *
1196  * domain:          The domain of the discovered service instance. This may or may not be the
1197  *                  same as the domain that was passed to DNSServiceBrowse(). The domain for each
1198  *                  discovered service instance should be stored along with the name, so that
1199  *                  it can be passed to DNSServiceResolve() when the service is later resolved.
1200  *
1201  * context:         The context pointer that was passed to the callout.
1202  *
1203  */
1204 
1205 typedef void (DNSSD_API *DNSServiceBrowseReply)
1206     (
1207     DNSServiceRef                       sdRef,
1208     DNSServiceFlags                     flags,
1209     uint32_t                            interfaceIndex,
1210     DNSServiceErrorType                 errorCode,
1211     const char                          *serviceName,
1212     const char                          *regtype,
1213     const char                          *replyDomain,
1214     void                                *context
1215     );
1216 
1217 
1218 /* DNSServiceBrowse() Parameters:
1219  *
1220  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds
1221  *                  then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError,
1222  *                  and the browse operation will run indefinitely until the client
1223  *                  terminates it by passing this DNSServiceRef to DNSServiceRefDeallocate().
1224  *
1225  * flags:           Currently ignored, reserved for future use.
1226  *
1227  * interfaceIndex:  If non-zero, specifies the interface on which to browse for services
1228  *                  (the index for a given interface is determined via the if_nametoindex()
1229  *                  family of calls.) Most applications will pass 0 to browse on all available
1230  *                  interfaces. See "Constants for specifying an interface index" for more details.
1231  *
1232  * regtype:         The service type being browsed for followed by the protocol, separated by a
1233  *                  dot (e.g. "_ftp._tcp"). The transport protocol must be "_tcp" or "_udp".
1234  *                  A client may optionally specify a single subtype to perform filtered browsing:
1235  *                  e.g. browsing for "_primarytype._tcp,_subtype" will discover only those
1236  *                  instances of "_primarytype._tcp" that were registered specifying "_subtype"
1237  *                  in their list of registered subtypes.
1238  *
1239  * domain:          If non-NULL, specifies the domain on which to browse for services.
1240  *                  Most applications will not specify a domain, instead browsing on the
1241  *                  default domain(s).
1242  *
1243  * callBack:        The function to be called when an instance of the service being browsed for
1244  *                  is found, or if the call asynchronously fails.
1245  *
1246  * context:         An application context pointer which is passed to the callback function
1247  *                  (may be NULL).
1248  *
1249  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1250  *                  errors are delivered to the callback), otherwise returns an error code indicating
1251  *                  the error that occurred (the callback is not invoked and the DNSServiceRef
1252  *                  is not initialized).
1253  */
1254 
1255 DNSServiceErrorType DNSSD_API DNSServiceBrowse
1256     (
1257     DNSServiceRef                       *sdRef,
1258     DNSServiceFlags                     flags,
1259     uint32_t                            interfaceIndex,
1260     const char                          *regtype,
1261     const char                          *domain,    /* may be NULL */
1262     DNSServiceBrowseReply               callBack,
1263     void                                *context    /* may be NULL */
1264     );
1265 
1266 
1267 /* DNSServiceResolve()
1268  *
1269  * Resolve a service name discovered via DNSServiceBrowse() to a target host name, port number, and
1270  * txt record.
1271  *
1272  * Note: Applications should NOT use DNSServiceResolve() solely for txt record monitoring - use
1273  * DNSServiceQueryRecord() instead, as it is more efficient for this task.
1274  *
1275  * Note: When the desired results have been returned, the client MUST terminate the resolve by calling
1276  * DNSServiceRefDeallocate().
1277  *
1278  * Note: DNSServiceResolve() behaves correctly for typical services that have a single SRV record
1279  * and a single TXT record. To resolve non-standard services with multiple SRV or TXT records,
1280  * DNSServiceQueryRecord() should be used.
1281  *
1282  * DNSServiceResolveReply Callback Parameters:
1283  *
1284  * sdRef:           The DNSServiceRef initialized by DNSServiceResolve().
1285  *
1286  * flags:           Possible values: kDNSServiceFlagsMoreComing
1287  *
1288  * interfaceIndex:  The interface on which the service was resolved.
1289  *
1290  * errorCode:       Will be kDNSServiceErr_NoError (0) on success, otherwise will
1291  *                  indicate the failure that occurred. Other parameters are undefined if
1292  *                  the errorCode is nonzero.
1293  *
1294  * fullname:        The full service domain name, in the form <servicename>.<protocol>.<domain>.
1295  *                  (This name is escaped following standard DNS rules, making it suitable for
1296  *                  passing to standard system DNS APIs such as res_query(), or to the
1297  *                  special-purpose functions included in this API that take fullname parameters.
1298  *                  See "Notes on DNS Name Escaping" earlier in this file for more details.)
1299  *
1300  * hosttarget:      The target hostname of the machine providing the service. This name can
1301  *                  be passed to functions like gethostbyname() to identify the host's IP address.
1302  *
1303  * port:            The port, in network byte order, on which connections are accepted for this service.
1304  *
1305  * txtLen:          The length of the txt record, in bytes.
1306  *
1307  * txtRecord:       The service's primary txt record, in standard txt record format.
1308  *
1309  * context:         The context pointer that was passed to the callout.
1310  *
1311  * NOTE: In earlier versions of this header file, the txtRecord parameter was declared "const char *"
1312  * This is incorrect, since it contains length bytes which are values in the range 0 to 255, not -128 to +127.
1313  * Depending on your compiler settings, this change may cause signed/unsigned mismatch warnings.
1314  * These should be fixed by updating your own callback function definition to match the corrected
1315  * function signature using "const unsigned char *txtRecord". Making this change may also fix inadvertent
1316  * bugs in your callback function, where it could have incorrectly interpreted a length byte with value 250
1317  * as being -6 instead, with various bad consequences ranging from incorrect operation to software crashes.
1318  * If you need to maintain portable code that will compile cleanly with both the old and new versions of
1319  * this header file, you should update your callback function definition to use the correct unsigned value,
1320  * and then in the place where you pass your callback function to DNSServiceResolve(), use a cast to eliminate
1321  * the compiler warning, e.g.:
1322  *   DNSServiceResolve(sd, flags, index, name, regtype, domain, (DNSServiceResolveReply)MyCallback, context);
1323  * This will ensure that your code compiles cleanly without warnings (and more importantly, works correctly)
1324  * with both the old header and with the new corrected version.
1325  *
1326  */
1327 
1328 typedef void (DNSSD_API *DNSServiceResolveReply)
1329     (
1330     DNSServiceRef                       sdRef,
1331     DNSServiceFlags                     flags,
1332     uint32_t                            interfaceIndex,
1333     DNSServiceErrorType                 errorCode,
1334     const char                          *fullname,
1335     const char                          *hosttarget,
1336     uint16_t                            port,        /* In network byte order */
1337     uint16_t                            txtLen,
1338     const unsigned char                 *txtRecord,
1339     void                                *context
1340     );
1341 
1342 
1343 /* DNSServiceResolve() Parameters
1344  *
1345  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds
1346  *                  then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError,
1347  *                  and the resolve operation will run indefinitely until the client
1348  *                  terminates it by passing this DNSServiceRef to DNSServiceRefDeallocate().
1349  *
1350  * flags:           Specifying kDNSServiceFlagsForceMulticast will cause query to be
1351  *                  performed with a link-local mDNS query, even if the name is an
1352  *                  apparently non-local name (i.e. a name not ending in ".local.")
1353  *
1354  * interfaceIndex:  The interface on which to resolve the service. If this resolve call is
1355  *                  as a result of a currently active DNSServiceBrowse() operation, then the
1356  *                  interfaceIndex should be the index reported in the DNSServiceBrowseReply
1357  *                  callback. If this resolve call is using information previously saved
1358  *                  (e.g. in a preference file) for later use, then use interfaceIndex 0, because
1359  *                  the desired service may now be reachable via a different physical interface.
1360  *                  See "Constants for specifying an interface index" for more details.
1361  *
1362  * name:            The name of the service instance to be resolved, as reported to the
1363  *                  DNSServiceBrowseReply() callback.
1364  *
1365  * regtype:         The type of the service instance to be resolved, as reported to the
1366  *                  DNSServiceBrowseReply() callback.
1367  *
1368  * domain:          The domain of the service instance to be resolved, as reported to the
1369  *                  DNSServiceBrowseReply() callback.
1370  *
1371  * callBack:        The function to be called when a result is found, or if the call
1372  *                  asynchronously fails.
1373  *
1374  * context:         An application context pointer which is passed to the callback function
1375  *                  (may be NULL).
1376  *
1377  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1378  *                  errors are delivered to the callback), otherwise returns an error code indicating
1379  *                  the error that occurred (the callback is never invoked and the DNSServiceRef
1380  *                  is not initialized).
1381  */
1382 
1383 DNSServiceErrorType DNSSD_API DNSServiceResolve
1384     (
1385     DNSServiceRef                       *sdRef,
1386     DNSServiceFlags                     flags,
1387     uint32_t                            interfaceIndex,
1388     const char                          *name,
1389     const char                          *regtype,
1390     const char                          *domain,
1391     DNSServiceResolveReply              callBack,
1392     void                                *context  /* may be NULL */
1393     );
1394 
1395 
1396 /*********************************************************************************************
1397  *
1398  *  Querying Individual Specific Records
1399  *
1400  *********************************************************************************************/
1401 
1402 /* DNSServiceQueryRecord
1403  *
1404  * Query for an arbitrary DNS record.
1405  *
1406  * DNSServiceQueryRecordReply() Callback Parameters:
1407  *
1408  * sdRef:           The DNSServiceRef initialized by DNSServiceQueryRecord().
1409  *
1410  * flags:           Possible values are kDNSServiceFlagsMoreComing and
1411  *                  kDNSServiceFlagsAdd. The Add flag is NOT set for PTR records
1412  *                  with a ttl of 0, i.e. "Remove" events.
1413  *
1414  * interfaceIndex:  The interface on which the query was resolved (the index for a given
1415  *                  interface is determined via the if_nametoindex() family of calls).
1416  *                  See "Constants for specifying an interface index" for more details.
1417  *
1418  * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
1419  *                  indicate the failure that occurred. Other parameters are undefined if
1420  *                  errorCode is nonzero.
1421  *
1422  * fullname:        The resource record's full domain name.
1423  *
1424  * rrtype:          The resource record's type (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
1425  *
1426  * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
1427  *
1428  * rdlen:           The length, in bytes, of the resource record rdata.
1429  *
1430  * rdata:           The raw rdata of the resource record.
1431  *
1432  * ttl:             If the client wishes to cache the result for performance reasons,
1433  *                  the TTL indicates how long the client may legitimately hold onto
1434  *                  this result, in seconds. After the TTL expires, the client should
1435  *                  consider the result no longer valid, and if it requires this data
1436  *                  again, it should be re-fetched with a new query. Of course, this
1437  *                  only applies to clients that cancel the asynchronous operation when
1438  *                  they get a result. Clients that leave the asynchronous operation
1439  *                  running can safely assume that the data remains valid until they
1440  *                  get another callback telling them otherwise.
1441  *
1442  * context:         The context pointer that was passed to the callout.
1443  *
1444  */
1445 
1446 typedef void (DNSSD_API *DNSServiceQueryRecordReply)
1447     (
1448     DNSServiceRef                       sdRef,
1449     DNSServiceFlags                     flags,
1450     uint32_t                            interfaceIndex,
1451     DNSServiceErrorType                 errorCode,
1452     const char                          *fullname,
1453     uint16_t                            rrtype,
1454     uint16_t                            rrclass,
1455     uint16_t                            rdlen,
1456     const void                          *rdata,
1457     uint32_t                            ttl,
1458     void                                *context
1459     );
1460 
1461 
1462 /* DNSServiceQueryRecord() Parameters:
1463  *
1464  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds
1465  *                  then it initializes the DNSServiceRef, returns kDNSServiceErr_NoError,
1466  *                  and the query operation will run indefinitely until the client
1467  *                  terminates it by passing this DNSServiceRef to DNSServiceRefDeallocate().
1468  *
1469  * flags:           kDNSServiceFlagsForceMulticast or kDNSServiceFlagsLongLivedQuery.
1470  *                  Pass kDNSServiceFlagsLongLivedQuery to create a "long-lived" unicast
1471  *                  query in a non-local domain. Without setting this flag, unicast queries
1472  *                  will be one-shot - that is, only answers available at the time of the call
1473  *                  will be returned. By setting this flag, answers (including Add and Remove
1474  *                  events) that become available after the initial call is made will generate
1475  *                  callbacks. This flag has no effect on link-local multicast queries.
1476  *
1477  * interfaceIndex:  If non-zero, specifies the interface on which to issue the query
1478  *                  (the index for a given interface is determined via the if_nametoindex()
1479  *                  family of calls.) Passing 0 causes the name to be queried for on all
1480  *                  interfaces. See "Constants for specifying an interface index" for more details.
1481  *
1482  * fullname:        The full domain name of the resource record to be queried for.
1483  *
1484  * rrtype:          The numerical type of the resource record to be queried for
1485  *                  (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
1486  *
1487  * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
1488  *
1489  * callBack:        The function to be called when a result is found, or if the call
1490  *                  asynchronously fails.
1491  *
1492  * context:         An application context pointer which is passed to the callback function
1493  *                  (may be NULL).
1494  *
1495  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1496  *                  errors are delivered to the callback), otherwise returns an error code indicating
1497  *                  the error that occurred (the callback is never invoked and the DNSServiceRef
1498  *                  is not initialized).
1499  */
1500 
1501 DNSServiceErrorType DNSSD_API DNSServiceQueryRecord
1502     (
1503     DNSServiceRef                       *sdRef,
1504     DNSServiceFlags                     flags,
1505     uint32_t                            interfaceIndex,
1506     const char                          *fullname,
1507     uint16_t                            rrtype,
1508     uint16_t                            rrclass,
1509     DNSServiceQueryRecordReply          callBack,
1510     void                                *context  /* may be NULL */
1511     );
1512 
1513 
1514 /*********************************************************************************************
1515  *
1516  *  Unified lookup of both IPv4 and IPv6 addresses for a fully qualified hostname
1517  *
1518  *********************************************************************************************/
1519 
1520 /* DNSServiceGetAddrInfo
1521  *
1522  * Queries for the IP address of a hostname by using either Multicast or Unicast DNS.
1523  *
1524  * DNSServiceGetAddrInfoReply() parameters:
1525  *
1526  * sdRef:           The DNSServiceRef initialized by DNSServiceGetAddrInfo().
1527  *
1528  * flags:           Possible values are kDNSServiceFlagsMoreComing and
1529  *                  kDNSServiceFlagsAdd.
1530  *
1531  * interfaceIndex:  The interface to which the answers pertain.
1532  *
1533  * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
1534  *                  indicate the failure that occurred.  Other parameters are
1535  *                  undefined if errorCode is nonzero.
1536  *
1537  * hostname:        The fully qualified domain name of the host to be queried for.
1538  *
1539  * address:         IPv4 or IPv6 address.
1540  *
1541  * ttl:             If the client wishes to cache the result for performance reasons,
1542  *                  the TTL indicates how long the client may legitimately hold onto
1543  *                  this result, in seconds. After the TTL expires, the client should
1544  *                  consider the result no longer valid, and if it requires this data
1545  *                  again, it should be re-fetched with a new query. Of course, this
1546  *                  only applies to clients that cancel the asynchronous operation when
1547  *                  they get a result. Clients that leave the asynchronous operation
1548  *                  running can safely assume that the data remains valid until they
1549  *                  get another callback telling them otherwise.
1550  *
1551  * context:         The context pointer that was passed to the callout.
1552  *
1553  */
1554 
1555 typedef void (DNSSD_API *DNSServiceGetAddrInfoReply)
1556     (
1557     DNSServiceRef                    sdRef,
1558     DNSServiceFlags                  flags,
1559     uint32_t                         interfaceIndex,
1560     DNSServiceErrorType              errorCode,
1561     const char                       *hostname,
1562     const struct sockaddr            *address,
1563     uint32_t                         ttl,
1564     void                             *context
1565     );
1566 
1567 
1568 /* DNSServiceGetAddrInfo() Parameters:
1569  *
1570  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds then it
1571  *                  initializes the DNSServiceRef, returns kDNSServiceErr_NoError, and the query
1572  *                  begins and will last indefinitely until the client terminates the query
1573  *                  by passing this DNSServiceRef to DNSServiceRefDeallocate().
1574  *
1575  * flags:           kDNSServiceFlagsForceMulticast or kDNSServiceFlagsLongLivedQuery.
1576  *                  Pass kDNSServiceFlagsLongLivedQuery to create a "long-lived" unicast
1577  *                  query in a non-local domain. Without setting this flag, unicast queries
1578  *                  will be one-shot - that is, only answers available at the time of the call
1579  *                  will be returned. By setting this flag, answers (including Add and Remove
1580  *                  events) that become available after the initial call is made will generate
1581  *                  callbacks. This flag has no effect on link-local multicast queries.
1582  *
1583  * interfaceIndex:  The interface on which to issue the query.  Passing 0 causes the query to be
1584  *                  sent on all active interfaces via Multicast or the primary interface via Unicast.
1585  *
1586  * protocol:        Pass in kDNSServiceProtocol_IPv4 to look up IPv4 addresses, or kDNSServiceProtocol_IPv6
1587  *                  to look up IPv6 addresses, or both to look up both kinds. If neither flag is
1588  *                  set, the system will apply an intelligent heuristic, which is (currently)
1589  *                  that it will attempt to look up both, except:
1590  *
1591  *                   * If "hostname" is a wide-area unicast DNS hostname (i.e. not a ".local." name)
1592  *                     but this host has no routable IPv6 address, then the call will not try to
1593  *                     look up IPv6 addresses for "hostname", since any addresses it found would be
1594  *                     unlikely to be of any use anyway. Similarly, if this host has no routable
1595  *                     IPv4 address, the call will not try to look up IPv4 addresses for "hostname".
1596  *
1597  * hostname:        The fully qualified domain name of the host to be queried for.
1598  *
1599  * callBack:        The function to be called when the query succeeds or fails asynchronously.
1600  *
1601  * context:         An application context pointer which is passed to the callback function
1602  *                  (may be NULL).
1603  *
1604  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1605  *                  errors are delivered to the callback), otherwise returns an error code indicating
1606  *                  the error that occurred.
1607  */
1608 
1609 DNSServiceErrorType DNSSD_API DNSServiceGetAddrInfo
1610     (
1611     DNSServiceRef                    *sdRef,
1612     DNSServiceFlags                  flags,
1613     uint32_t                         interfaceIndex,
1614     DNSServiceProtocol               protocol,
1615     const char                       *hostname,
1616     DNSServiceGetAddrInfoReply       callBack,
1617     void                             *context          /* may be NULL */
1618     );
1619 
1620 
1621 /*********************************************************************************************
1622  *
1623  *  Special Purpose Calls:
1624  *  DNSServiceCreateConnection(), DNSServiceRegisterRecord(), DNSServiceReconfirmRecord()
1625  *  (most applications will not use these)
1626  *
1627  *********************************************************************************************/
1628 
1629 /* DNSServiceCreateConnection()
1630  *
1631  * Create a connection to the daemon allowing efficient registration of
1632  * multiple individual records.
1633  *
1634  * Parameters:
1635  *
1636  * sdRef:           A pointer to an uninitialized DNSServiceRef. Deallocating
1637  *                  the reference (via DNSServiceRefDeallocate()) severs the
1638  *                  connection and deregisters all records registered on this connection.
1639  *
1640  * return value:    Returns kDNSServiceErr_NoError on success, otherwise returns
1641  *                  an error code indicating the specific failure that occurred (in which
1642  *                  case the DNSServiceRef is not initialized).
1643  */
1644 
1645 DNSServiceErrorType DNSSD_API DNSServiceCreateConnection(DNSServiceRef *sdRef);
1646 
1647 
1648 /* DNSServiceRegisterRecord
1649  *
1650  * Register an individual resource record on a connected DNSServiceRef.
1651  *
1652  * Note that name conflicts occurring for records registered via this call must be handled
1653  * by the client in the callback.
1654  *
1655  * DNSServiceRegisterRecordReply() parameters:
1656  *
1657  * sdRef:           The connected DNSServiceRef initialized by
1658  *                  DNSServiceCreateConnection().
1659  *
1660  * RecordRef:       The DNSRecordRef initialized by DNSServiceRegisterRecord(). If the above
1661  *                  DNSServiceRef is passed to DNSServiceRefDeallocate(), this DNSRecordRef is
1662  *                  invalidated, and may not be used further.
1663  *
1664  * flags:           Currently unused, reserved for future use.
1665  *
1666  * errorCode:       Will be kDNSServiceErr_NoError on success, otherwise will
1667  *                  indicate the failure that occurred (including name conflicts.)
1668  *                  Other parameters are undefined if errorCode is nonzero.
1669  *
1670  * context:         The context pointer that was passed to the callout.
1671  *
1672  */
1673 
1674  typedef void (DNSSD_API *DNSServiceRegisterRecordReply)
1675     (
1676     DNSServiceRef                       sdRef,
1677     DNSRecordRef                        RecordRef,
1678     DNSServiceFlags                     flags,
1679     DNSServiceErrorType                 errorCode,
1680     void                                *context
1681     );
1682 
1683 
1684 /* DNSServiceRegisterRecord() Parameters:
1685  *
1686  * sdRef:           A DNSServiceRef initialized by DNSServiceCreateConnection().
1687  *
1688  * RecordRef:       A pointer to an uninitialized DNSRecordRef. Upon succesful completion of this
1689  *                  call, this ref may be passed to DNSServiceUpdateRecord() or DNSServiceRemoveRecord().
1690  *                  (To deregister ALL records registered on a single connected DNSServiceRef
1691  *                  and deallocate each of their corresponding DNSServiceRecordRefs, call
1692  *                  DNSServiceRefDeallocate()).
1693  *
1694  * flags:           Possible values are kDNSServiceFlagsShared or kDNSServiceFlagsUnique
1695  *                  (see flag type definitions for details).
1696  *
1697  * interfaceIndex:  If non-zero, specifies the interface on which to register the record
1698  *                  (the index for a given interface is determined via the if_nametoindex()
1699  *                  family of calls.) Passing 0 causes the record to be registered on all interfaces.
1700  *                  See "Constants for specifying an interface index" for more details.
1701  *
1702  * fullname:        The full domain name of the resource record.
1703  *
1704  * rrtype:          The numerical type of the resource record (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
1705  *
1706  * rrclass:         The class of the resource record (usually kDNSServiceClass_IN)
1707  *
1708  * rdlen:           Length, in bytes, of the rdata.
1709  *
1710  * rdata:           A pointer to the raw rdata, as it is to appear in the DNS record.
1711  *
1712  * ttl:             The time to live of the resource record, in seconds.
1713  *                  Most clients should pass 0 to indicate that the system should
1714  *                  select a sensible default value.
1715  *
1716  * callBack:        The function to be called when a result is found, or if the call
1717  *                  asynchronously fails (e.g. because of a name conflict.)
1718  *
1719  * context:         An application context pointer which is passed to the callback function
1720  *                  (may be NULL).
1721  *
1722  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1723  *                  errors are delivered to the callback), otherwise returns an error code indicating
1724  *                  the error that occurred (the callback is never invoked and the DNSRecordRef is
1725  *                  not initialized).
1726  */
1727 
1728 DNSServiceErrorType DNSSD_API DNSServiceRegisterRecord
1729     (
1730     DNSServiceRef                       sdRef,
1731     DNSRecordRef                        *RecordRef,
1732     DNSServiceFlags                     flags,
1733     uint32_t                            interfaceIndex,
1734     const char                          *fullname,
1735     uint16_t                            rrtype,
1736     uint16_t                            rrclass,
1737     uint16_t                            rdlen,
1738     const void                          *rdata,
1739     uint32_t                            ttl,
1740     DNSServiceRegisterRecordReply       callBack,
1741     void                                *context    /* may be NULL */
1742     );
1743 
1744 
1745 /* DNSServiceReconfirmRecord
1746  *
1747  * Instruct the daemon to verify the validity of a resource record that appears
1748  * to be out of date (e.g. because TCP connection to a service's target failed.)
1749  * Causes the record to be flushed from the daemon's cache (as well as all other
1750  * daemons' caches on the network) if the record is determined to be invalid.
1751  * Use this routine conservatively. Reconfirming a record necessarily consumes
1752  * network bandwidth, so this should not be done indiscriminately.
1753  *
1754  * Parameters:
1755  *
1756  * flags:           Pass kDNSServiceFlagsForce to force immediate deletion of record,
1757  *                  instead of after some number of reconfirmation queries have gone unanswered.
1758  *
1759  * interfaceIndex:  Specifies the interface of the record in question.
1760  *                  The caller must specify the interface.
1761  *                  This API (by design) causes increased network traffic, so it requires
1762  *                  the caller to be precise about which record should be reconfirmed.
1763  *                  It is not possible to pass zero for the interface index to perform
1764  *                  a "wildcard" reconfirmation, where *all* matching records are reconfirmed.
1765  *
1766  * fullname:        The resource record's full domain name.
1767  *
1768  * rrtype:          The resource record's type (e.g. kDNSServiceType_PTR, kDNSServiceType_SRV, etc)
1769  *
1770  * rrclass:         The class of the resource record (usually kDNSServiceClass_IN).
1771  *
1772  * rdlen:           The length, in bytes, of the resource record rdata.
1773  *
1774  * rdata:           The raw rdata of the resource record.
1775  *
1776  */
1777 
1778 DNSServiceErrorType DNSSD_API DNSServiceReconfirmRecord
1779     (
1780     DNSServiceFlags                    flags,
1781     uint32_t                           interfaceIndex,
1782     const char                         *fullname,
1783     uint16_t                           rrtype,
1784     uint16_t                           rrclass,
1785     uint16_t                           rdlen,
1786     const void                         *rdata
1787     );
1788 
1789 
1790 /*********************************************************************************************
1791  *
1792  *  NAT Port Mapping
1793  *
1794  *********************************************************************************************/
1795 
1796 /* DNSServiceNATPortMappingCreate
1797  *
1798  * Request a port mapping in the NAT gateway, which maps a port on the local machine
1799  * to an external port on the NAT. The NAT should support either the NAT-PMP or the UPnP IGD
1800  * protocol for this API to create a successful mapping.
1801  *
1802  * The port mapping will be renewed indefinitely until the client process exits, or
1803  * explicitly terminates the port mapping request by calling DNSServiceRefDeallocate().
1804  * The client callback will be invoked, informing the client of the NAT gateway's
1805  * external IP address and the external port that has been allocated for this client.
1806  * The client should then record this external IP address and port using whatever
1807  * directory service mechanism it is using to enable peers to connect to it.
1808  * (Clients advertising services using Wide-Area DNS-SD DO NOT need to use this API
1809  * -- when a client calls DNSServiceRegister() NAT mappings are automatically created
1810  * and the external IP address and port for the service are recorded in the global DNS.
1811  * Only clients using some directory mechanism other than Wide-Area DNS-SD need to use
1812  * this API to explicitly map their own ports.)
1813  *
1814  * It's possible that the client callback could be called multiple times, for example
1815  * if the NAT gateway's IP address changes, or if a configuration change results in a
1816  * different external port being mapped for this client. Over the lifetime of any long-lived
1817  * port mapping, the client should be prepared to handle these notifications of changes
1818  * in the environment, and should update its recorded address and/or port as appropriate.
1819  *
1820  * NOTE: There are two unusual aspects of how the DNSServiceNATPortMappingCreate API works,
1821  * which were intentionally designed to help simplify client code:
1822  *
1823  *  1. It's not an error to request a NAT mapping when the machine is not behind a NAT gateway.
1824  *     In other NAT mapping APIs, if you request a NAT mapping and the machine is not behind a NAT
1825  *     gateway, then the API returns an error code -- it can't get you a NAT mapping if there's no
1826  *     NAT gateway. The DNSServiceNATPortMappingCreate API takes a different view. Working out
1827  *     whether or not you need a NAT mapping can be tricky and non-obvious, particularly on
1828  *     a machine with multiple active network interfaces. Rather than make every client recreate
1829  *     this logic for deciding whether a NAT mapping is required, the PortMapping API does that
1830  *     work for you. If the client calls the PortMapping API when the machine already has a
1831  *     routable public IP address, then instead of complaining about it and giving an error,
1832  *     the PortMapping API just invokes your callback, giving the machine's public address
1833  *     and your own port number. This means you don't need to write code to work out whether
1834  *     your client needs to call the PortMapping API -- just call it anyway, and if it wasn't
1835  *     necessary, no harm is done:
1836  *
1837  *     - If the machine already has a routable public IP address, then your callback
1838  *       will just be invoked giving your own address and port.
1839  *     - If a NAT mapping is required and obtained, then your callback will be invoked
1840  *       giving you the external address and port.
1841  *     - If a NAT mapping is required but not obtained from the local NAT gateway,
1842  *       or the machine has no network connectivity, then your callback will be
1843  *       invoked giving zero address and port.
1844  *
1845  *  2. In other NAT mapping APIs, if a laptop computer is put to sleep and woken up on a new
1846  *     network, it's the client's job to notice this, and work out whether a NAT mapping
1847  *     is required on the new network, and make a new NAT mapping request if necessary.
1848  *     The DNSServiceNATPortMappingCreate API does this for you, automatically.
1849  *     The client just needs to make one call to the PortMapping API, and its callback will
1850  *     be invoked any time the mapping state changes. This property complements point (1) above.
1851  *     If the client didn't make a NAT mapping request just because it determined that one was
1852  *     not required at that particular moment in time, the client would then have to monitor
1853  *     for network state changes to determine if a NAT port mapping later became necessary.
1854  *     By unconditionally making a NAT mapping request, even when a NAT mapping not to be
1855  *     necessary, the PortMapping API will then begin monitoring network state changes on behalf of
1856  *     the client, and if a NAT mapping later becomes necessary, it will automatically create a NAT
1857  *     mapping and inform the client with a new callback giving the new address and port information.
1858  *
1859  * DNSServiceNATPortMappingReply() parameters:
1860  *
1861  * sdRef:           The DNSServiceRef initialized by DNSServiceNATPortMappingCreate().
1862  *
1863  * flags:           Currently unused, reserved for future use.
1864  *
1865  * interfaceIndex:  The interface through which the NAT gateway is reached.
1866  *
1867  * errorCode:       Will be kDNSServiceErr_NoError on success.
1868  *                  Will be kDNSServiceErr_DoubleNAT when the NAT gateway is itself behind one or
1869  *                  more layers of NAT, in which case the other parameters have the defined values.
1870  *                  For other failures, will indicate the failure that occurred, and the other
1871  *                  parameters are undefined.
1872  *
1873  * externalAddress: Four byte IPv4 address in network byte order.
1874  *
1875  * protocol:        Will be kDNSServiceProtocol_UDP or kDNSServiceProtocol_TCP or both.
1876  *
1877  * internalPort:    The port on the local machine that was mapped.
1878  *
1879  * externalPort:    The actual external port in the NAT gateway that was mapped.
1880  *                  This is likely to be different than the requested external port.
1881  *
1882  * ttl:             The lifetime of the NAT port mapping created on the gateway.
1883  *                  This controls how quickly stale mappings will be garbage-collected
1884  *                  if the client machine crashes, suffers a power failure, is disconnected
1885  *                  from the network, or suffers some other unfortunate demise which
1886  *                  causes it to vanish without explicitly removing its NAT port mapping.
1887  *                  It's possible that the ttl value will differ from the requested ttl value.
1888  *
1889  * context:         The context pointer that was passed to the callout.
1890  *
1891  */
1892 
1893 typedef void (DNSSD_API *DNSServiceNATPortMappingReply)
1894     (
1895     DNSServiceRef                    sdRef,
1896     DNSServiceFlags                  flags,
1897     uint32_t                         interfaceIndex,
1898     DNSServiceErrorType              errorCode,
1899     uint32_t                         externalAddress,   /* four byte IPv4 address in network byte order */
1900     DNSServiceProtocol               protocol,
1901     uint16_t                         internalPort,      /* In network byte order */
1902     uint16_t                         externalPort,      /* In network byte order and may be different than the requested port */
1903     uint32_t                         ttl,               /* may be different than the requested ttl */
1904     void                             *context
1905     );
1906 
1907 
1908 /* DNSServiceNATPortMappingCreate() Parameters:
1909  *
1910  * sdRef:           A pointer to an uninitialized DNSServiceRef. If the call succeeds then it
1911  *                  initializes the DNSServiceRef, returns kDNSServiceErr_NoError, and the nat
1912  *                  port mapping will last indefinitely until the client terminates the port
1913  *                  mapping request by passing this DNSServiceRef to DNSServiceRefDeallocate().
1914  *
1915  * flags:           Currently ignored, reserved for future use.
1916  *
1917  * interfaceIndex:  The interface on which to create port mappings in a NAT gateway. Passing 0 causes
1918  *                  the port mapping request to be sent on the primary interface.
1919  *
1920  * protocol:        To request a port mapping, pass in kDNSServiceProtocol_UDP, or kDNSServiceProtocol_TCP,
1921  *                  or (kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP) to map both.
1922  *                  The local listening port number must also be specified in the internalPort parameter.
1923  *                  To just discover the NAT gateway's external IP address, pass zero for protocol,
1924  *                  internalPort, externalPort and ttl.
1925  *
1926  * internalPort:    The port number in network byte order on the local machine which is listening for packets.
1927  *
1928  * externalPort:    The requested external port in network byte order in the NAT gateway that you would
1929  *                  like to map to the internal port. Pass 0 if you don't care which external port is chosen for you.
1930  *
1931  * ttl:             The requested renewal period of the NAT port mapping, in seconds.
1932  *                  If the client machine crashes, suffers a power failure, is disconnected from
1933  *                  the network, or suffers some other unfortunate demise which causes it to vanish
1934  *                  unexpectedly without explicitly removing its NAT port mappings, then the NAT gateway
1935  *                  will garbage-collect old stale NAT port mappings when their lifetime expires.
1936  *                  Requesting a short TTL causes such orphaned mappings to be garbage-collected
1937  *                  more promptly, but consumes system resources and network bandwidth with
1938  *                  frequent renewal packets to keep the mapping from expiring.
1939  *                  Requesting a long TTL is more efficient on the network, but in the event of the
1940  *                  client vanishing, stale NAT port mappings will not be garbage-collected as quickly.
1941  *                  Most clients should pass 0 to use a system-wide default value.
1942  *
1943  * callBack:        The function to be called when the port mapping request succeeds or fails asynchronously.
1944  *
1945  * context:         An application context pointer which is passed to the callback function
1946  *                  (may be NULL).
1947  *
1948  * return value:    Returns kDNSServiceErr_NoError on success (any subsequent, asynchronous
1949  *                  errors are delivered to the callback), otherwise returns an error code indicating
1950  *                  the error that occurred.
1951  *
1952  *                  If you don't actually want a port mapped, and are just calling the API
1953  *                  because you want to find out the NAT's external IP address (e.g. for UI
1954  *                  display) then pass zero for protocol, internalPort, externalPort and ttl.
1955  */
1956 
1957 DNSServiceErrorType DNSSD_API DNSServiceNATPortMappingCreate
1958     (
1959     DNSServiceRef                    *sdRef,
1960     DNSServiceFlags                  flags,
1961     uint32_t                         interfaceIndex,
1962     DNSServiceProtocol               protocol,          /* TCP and/or UDP          */
1963     uint16_t                         internalPort,      /* network byte order      */
1964     uint16_t                         externalPort,      /* network byte order      */
1965     uint32_t                         ttl,               /* time to live in seconds */
1966     DNSServiceNATPortMappingReply    callBack,
1967     void                             *context           /* may be NULL             */
1968     );
1969 
1970 
1971 /*********************************************************************************************
1972  *
1973  *  General Utility Functions
1974  *
1975  *********************************************************************************************/
1976 
1977 /* DNSServiceConstructFullName()
1978  *
1979  * Concatenate a three-part domain name (as returned by the above callbacks) into a
1980  * properly-escaped full domain name. Note that callbacks in the above functions ALREADY ESCAPE
1981  * strings where necessary.
1982  *
1983  * Parameters:
1984  *
1985  * fullName:        A pointer to a buffer that where the resulting full domain name is to be written.
1986  *                  The buffer must be kDNSServiceMaxDomainName (1009) bytes in length to
1987  *                  accommodate the longest legal domain name without buffer overrun.
1988  *
1989  * service:         The service name - any dots or backslashes must NOT be escaped.
1990  *                  May be NULL (to construct a PTR record name, e.g.
1991  *                  "_ftp._tcp.apple.com.").
1992  *
1993  * regtype:         The service type followed by the protocol, separated by a dot
1994  *                  (e.g. "_ftp._tcp").
1995  *
1996  * domain:          The domain name, e.g. "apple.com.". Literal dots or backslashes,
1997  *                  if any, must be escaped, e.g. "1st\. Floor.apple.com."
1998  *
1999  * return value:    Returns kDNSServiceErr_NoError (0) on success, kDNSServiceErr_BadParam on error.
2000  *
2001  */
2002 
2003 DNSServiceErrorType DNSSD_API DNSServiceConstructFullName
2004     (
2005     char                            * const fullName,
2006     const char                      * const service,      /* may be NULL */
2007     const char                      * const regtype,
2008     const char                      * const domain
2009     );
2010 
2011 
2012 /*********************************************************************************************
2013  *
2014  *   TXT Record Construction Functions
2015  *
2016  *********************************************************************************************/
2017 
2018 /*
2019  * A typical calling sequence for TXT record construction is something like:
2020  *
2021  * Client allocates storage for TXTRecord data (e.g. declare buffer on the stack)
2022  * TXTRecordCreate();
2023  * TXTRecordSetValue();
2024  * TXTRecordSetValue();
2025  * TXTRecordSetValue();
2026  * ...
2027  * DNSServiceRegister( ... TXTRecordGetLength(), TXTRecordGetBytesPtr() ... );
2028  * TXTRecordDeallocate();
2029  * Explicitly deallocate storage for TXTRecord data (if not allocated on the stack)
2030  */
2031 
2032 
2033 /* TXTRecordRef
2034  *
2035  * Opaque internal data type.
2036  * Note: Represents a DNS-SD TXT record.
2037  */
2038 
2039 typedef union _TXTRecordRef_t { char PrivateData[16]; char *ForceNaturalAlignment; } TXTRecordRef;
2040 
2041 
2042 /* TXTRecordCreate()
2043  *
2044  * Creates a new empty TXTRecordRef referencing the specified storage.
2045  *
2046  * If the buffer parameter is NULL, or the specified storage size is not
2047  * large enough to hold a key subsequently added using TXTRecordSetValue(),
2048  * then additional memory will be added as needed using malloc().
2049  *
2050  * On some platforms, when memory is low, malloc() may fail. In this
2051  * case, TXTRecordSetValue() will return kDNSServiceErr_NoMemory, and this
2052  * error condition will need to be handled as appropriate by the caller.
2053  *
2054  * You can avoid the need to handle this error condition if you ensure
2055  * that the storage you initially provide is large enough to hold all
2056  * the key/value pairs that are to be added to the record.
2057  * The caller can precompute the exact length required for all of the
2058  * key/value pairs to be added, or simply provide a fixed-sized buffer
2059  * known in advance to be large enough.
2060  * A no-value (key-only) key requires  (1 + key length) bytes.
2061  * A key with empty value requires     (1 + key length + 1) bytes.
2062  * A key with non-empty value requires (1 + key length + 1 + value length).
2063  * For most applications, DNS-SD TXT records are generally
2064  * less than 100 bytes, so in most cases a simple fixed-sized
2065  * 256-byte buffer will be more than sufficient.
2066  * Recommended size limits for DNS-SD TXT Records are discussed in
2067  * <http://files.dns-sd.org/draft-cheshire-dnsext-dns-sd.txt>
2068  *
2069  * Note: When passing parameters to and from these TXT record APIs,
2070  * the key name does not include the '=' character. The '=' character
2071  * is the separator between the key and value in the on-the-wire
2072  * packet format; it is not part of either the key or the value.
2073  *
2074  * txtRecord:       A pointer to an uninitialized TXTRecordRef.
2075  *
2076  * bufferLen:       The size of the storage provided in the "buffer" parameter.
2077  *
2078  * buffer:          Optional caller-supplied storage used to hold the TXTRecord data.
2079  *                  This storage must remain valid for as long as
2080  *                  the TXTRecordRef.
2081  */
2082 
2083 void DNSSD_API TXTRecordCreate
2084     (
2085     TXTRecordRef     *txtRecord,
2086     uint16_t         bufferLen,
2087     void             *buffer
2088     );
2089 
2090 
2091 /* TXTRecordDeallocate()
2092  *
2093  * Releases any resources allocated in the course of preparing a TXT Record
2094  * using TXTRecordCreate()/TXTRecordSetValue()/TXTRecordRemoveValue().
2095  * Ownership of the buffer provided in TXTRecordCreate() returns to the client.
2096  *
2097  * txtRecord:           A TXTRecordRef initialized by calling TXTRecordCreate().
2098  *
2099  */
2100 
2101 void DNSSD_API TXTRecordDeallocate
2102     (
2103     TXTRecordRef     *txtRecord
2104     );
2105 
2106 
2107 /* TXTRecordSetValue()
2108  *
2109  * Adds a key (optionally with value) to a TXTRecordRef. If the "key" already
2110  * exists in the TXTRecordRef, then the current value will be replaced with
2111  * the new value.
2112  * Keys may exist in four states with respect to a given TXT record:
2113  *  - Absent (key does not appear at all)
2114  *  - Present with no value ("key" appears alone)
2115  *  - Present with empty value ("key=" appears in TXT record)
2116  *  - Present with non-empty value ("key=value" appears in TXT record)
2117  * For more details refer to "Data Syntax for DNS-SD TXT Records" in
2118  * <http://files.dns-sd.org/draft-cheshire-dnsext-dns-sd.txt>
2119  *
2120  * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
2121  *
2122  * key:             A null-terminated string which only contains printable ASCII
2123  *                  values (0x20-0x7E), excluding '=' (0x3D). Keys should be
2124  *                  9 characters or fewer (not counting the terminating null).
2125  *
2126  * valueSize:       The size of the value.
2127  *
2128  * value:           Any binary value. For values that represent
2129  *                  textual data, UTF-8 is STRONGLY recommended.
2130  *                  For values that represent textual data, valueSize
2131  *                  should NOT include the terminating null (if any)
2132  *                  at the end of the string.
2133  *                  If NULL, then "key" will be added with no value.
2134  *                  If non-NULL but valueSize is zero, then "key=" will be
2135  *                  added with empty value.
2136  *
2137  * return value:    Returns kDNSServiceErr_NoError on success.
2138  *                  Returns kDNSServiceErr_Invalid if the "key" string contains
2139  *                  illegal characters.
2140  *                  Returns kDNSServiceErr_NoMemory if adding this key would
2141  *                  exceed the available storage.
2142  */
2143 
2144 DNSServiceErrorType DNSSD_API TXTRecordSetValue
2145     (
2146     TXTRecordRef     *txtRecord,
2147     const char       *key,
2148     uint8_t          valueSize,        /* may be zero */
2149     const void       *value            /* may be NULL */
2150     );
2151 
2152 
2153 /* TXTRecordRemoveValue()
2154  *
2155  * Removes a key from a TXTRecordRef. The "key" must be an
2156  * ASCII string which exists in the TXTRecordRef.
2157  *
2158  * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
2159  *
2160  * key:             A key name which exists in the TXTRecordRef.
2161  *
2162  * return value:    Returns kDNSServiceErr_NoError on success.
2163  *                  Returns kDNSServiceErr_NoSuchKey if the "key" does not
2164  *                  exist in the TXTRecordRef.
2165  */
2166 
2167 DNSServiceErrorType DNSSD_API TXTRecordRemoveValue
2168     (
2169     TXTRecordRef     *txtRecord,
2170     const char       *key
2171     );
2172 
2173 
2174 /* TXTRecordGetLength()
2175  *
2176  * Allows you to determine the length of the raw bytes within a TXTRecordRef.
2177  *
2178  * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
2179  *
2180  * return value:    Returns the size of the raw bytes inside a TXTRecordRef
2181  *                  which you can pass directly to DNSServiceRegister() or
2182  *                  to DNSServiceUpdateRecord().
2183  *                  Returns 0 if the TXTRecordRef is empty.
2184  */
2185 
2186 uint16_t DNSSD_API TXTRecordGetLength
2187     (
2188     const TXTRecordRef *txtRecord
2189     );
2190 
2191 
2192 /* TXTRecordGetBytesPtr()
2193  *
2194  * Allows you to retrieve a pointer to the raw bytes within a TXTRecordRef.
2195  *
2196  * txtRecord:       A TXTRecordRef initialized by calling TXTRecordCreate().
2197  *
2198  * return value:    Returns a pointer to the raw bytes inside the TXTRecordRef
2199  *                  which you can pass directly to DNSServiceRegister() or
2200  *                  to DNSServiceUpdateRecord().
2201  */
2202 
2203 const void * DNSSD_API TXTRecordGetBytesPtr
2204     (
2205     const TXTRecordRef *txtRecord
2206     );
2207 
2208 
2209 /*********************************************************************************************
2210  *
2211  *   TXT Record Parsing Functions
2212  *
2213  *********************************************************************************************/
2214 
2215 /*
2216  * A typical calling sequence for TXT record parsing is something like:
2217  *
2218  * Receive TXT record data in DNSServiceResolve() callback
2219  * if (TXTRecordContainsKey(txtLen, txtRecord, "key")) then do something
2220  * val1ptr = TXTRecordGetValuePtr(txtLen, txtRecord, "key1", &len1);
2221  * val2ptr = TXTRecordGetValuePtr(txtLen, txtRecord, "key2", &len2);
2222  * ...
2223  * memcpy(myval1, val1ptr, len1);
2224  * memcpy(myval2, val2ptr, len2);
2225  * ...
2226  * return;
2227  *
2228  * If you wish to retain the values after return from the DNSServiceResolve()
2229  * callback, then you need to copy the data to your own storage using memcpy()
2230  * or similar, as shown in the example above.
2231  *
2232  * If for some reason you need to parse a TXT record you built yourself
2233  * using the TXT record construction functions above, then you can do
2234  * that using TXTRecordGetLength and TXTRecordGetBytesPtr calls:
2235  * TXTRecordGetValue(TXTRecordGetLength(x), TXTRecordGetBytesPtr(x), key, &len);
2236  *
2237  * Most applications only fetch keys they know about from a TXT record and
2238  * ignore the rest.
2239  * However, some debugging tools wish to fetch and display all keys.
2240  * To do that, use the TXTRecordGetCount() and TXTRecordGetItemAtIndex() calls.
2241  */
2242 
2243 /* TXTRecordContainsKey()
2244  *
2245  * Allows you to determine if a given TXT Record contains a specified key.
2246  *
2247  * txtLen:          The size of the received TXT Record.
2248  *
2249  * txtRecord:       Pointer to the received TXT Record bytes.
2250  *
2251  * key:             A null-terminated ASCII string containing the key name.
2252  *
2253  * return value:    Returns 1 if the TXT Record contains the specified key.
2254  *                  Otherwise, it returns 0.
2255  */
2256 
2257 int DNSSD_API TXTRecordContainsKey
2258     (
2259     uint16_t         txtLen,
2260     const void       *txtRecord,
2261     const char       *key
2262     );
2263 
2264 
2265 /* TXTRecordGetValuePtr()
2266  *
2267  * Allows you to retrieve the value for a given key from a TXT Record.
2268  *
2269  * txtLen:          The size of the received TXT Record
2270  *
2271  * txtRecord:       Pointer to the received TXT Record bytes.
2272  *
2273  * key:             A null-terminated ASCII string containing the key name.
2274  *
2275  * valueLen:        On output, will be set to the size of the "value" data.
2276  *
2277  * return value:    Returns NULL if the key does not exist in this TXT record,
2278  *                  or exists with no value (to differentiate between
2279  *                  these two cases use TXTRecordContainsKey()).
2280  *                  Returns pointer to location within TXT Record bytes
2281  *                  if the key exists with empty or non-empty value.
2282  *                  For empty value, valueLen will be zero.
2283  *                  For non-empty value, valueLen will be length of value data.
2284  */
2285 
2286 const void * DNSSD_API TXTRecordGetValuePtr
2287     (
2288     uint16_t         txtLen,
2289     const void       *txtRecord,
2290     const char       *key,
2291     uint8_t          *valueLen
2292     );
2293 
2294 
2295 /* TXTRecordGetCount()
2296  *
2297  * Returns the number of keys stored in the TXT Record. The count
2298  * can be used with TXTRecordGetItemAtIndex() to iterate through the keys.
2299  *
2300  * txtLen:          The size of the received TXT Record.
2301  *
2302  * txtRecord:       Pointer to the received TXT Record bytes.
2303  *
2304  * return value:    Returns the total number of keys in the TXT Record.
2305  *
2306  */
2307 
2308 uint16_t DNSSD_API TXTRecordGetCount
2309     (
2310     uint16_t         txtLen,
2311     const void       *txtRecord
2312     );
2313 
2314 
2315 /* TXTRecordGetItemAtIndex()
2316  *
2317  * Allows you to retrieve a key name and value pointer, given an index into
2318  * a TXT Record. Legal index values range from zero to TXTRecordGetCount()-1.
2319  * It's also possible to iterate through keys in a TXT record by simply
2320  * calling TXTRecordGetItemAtIndex() repeatedly, beginning with index zero
2321  * and increasing until TXTRecordGetItemAtIndex() returns kDNSServiceErr_Invalid.
2322  *
2323  * On return:
2324  * For keys with no value, *value is set to NULL and *valueLen is zero.
2325  * For keys with empty value, *value is non-NULL and *valueLen is zero.
2326  * For keys with non-empty value, *value is non-NULL and *valueLen is non-zero.
2327  *
2328  * txtLen:          The size of the received TXT Record.
2329  *
2330  * txtRecord:       Pointer to the received TXT Record bytes.
2331  *
2332  * itemIndex:       An index into the TXT Record.
2333  *
2334  * keyBufLen:       The size of the string buffer being supplied.
2335  *
2336  * key:             A string buffer used to store the key name.
2337  *                  On return, the buffer contains a null-terminated C string
2338  *                  giving the key name. DNS-SD TXT keys are usually
2339  *                  9 characters or fewer. To hold the maximum possible
2340  *                  key name, the buffer should be 256 bytes long.
2341  *
2342  * valueLen:        On output, will be set to the size of the "value" data.
2343  *
2344  * value:           On output, *value is set to point to location within TXT
2345  *                  Record bytes that holds the value data.
2346  *
2347  * return value:    Returns kDNSServiceErr_NoError on success.
2348  *                  Returns kDNSServiceErr_NoMemory if keyBufLen is too short.
2349  *                  Returns kDNSServiceErr_Invalid if index is greater than
2350  *                  TXTRecordGetCount()-1.
2351  */
2352 
2353 DNSServiceErrorType DNSSD_API TXTRecordGetItemAtIndex
2354     (
2355     uint16_t         txtLen,
2356     const void       *txtRecord,
2357     uint16_t         itemIndex,
2358     uint16_t         keyBufLen,
2359     char             *key,
2360     uint8_t          *valueLen,
2361     const void       **value
2362     );
2363 
2364 #if _DNS_SD_LIBDISPATCH
2365 /*
2366 * DNSServiceSetDispatchQueue
2367 *
2368 * Allows you to schedule a DNSServiceRef on a serial dispatch queue for receiving asynchronous
2369 * callbacks.  It's the clients responsibility to ensure that the provided dispatch queue is running.
2370 *
2371 * A typical application that uses CFRunLoopRun or dispatch_main on its main thread will
2372 * usually schedule DNSServiceRefs on its main queue (which is always a serial queue)
2373 * using "DNSServiceSetDispatchQueue(sdref, dispatch_get_main_queue());"
2374 *
2375 * If there is any error during the processing of events, the application callback will
2376 * be called with an error code. For shared connections, each subordinate DNSServiceRef
2377 * will get its own error callback. Currently these error callbacks only happen
2378 * if the mDNSResponder daemon is manually terminated or crashes, and the error
2379 * code in this case is kDNSServiceErr_ServiceNotRunning. The application must call
2380 * DNSServiceRefDeallocate to free the DNSServiceRef when it gets such an error code.
2381 * These error callbacks are rare and should not normally happen on customer machines,
2382 * but application code should be written defensively to handle such error callbacks
2383 * gracefully if they occur.
2384 *
2385 * After using DNSServiceSetDispatchQueue on a DNSServiceRef, calling DNSServiceProcessResult
2386 * on the same DNSServiceRef will result in undefined behavior and should be avoided.
2387 *
2388 * Once the application successfully schedules a DNSServiceRef on a serial dispatch queue using
2389 * DNSServiceSetDispatchQueue, it cannot remove the DNSServiceRef from the dispatch queue, or use
2390 * DNSServiceSetDispatchQueue a second time to schedule the DNSServiceRef onto a different serial dispatch
2391 * queue. Once scheduled onto a dispatch queue a DNSServiceRef will deliver events to that queue until
2392 * the application no longer requires that operation and terminates it using DNSServiceRefDeallocate.
2393 *
2394 * service:         DNSServiceRef that was allocated and returned to the application, when the
2395 *                  application calls one of the DNSService API.
2396 *
2397 * queue:           dispatch queue where the application callback will be scheduled
2398 *
2399 * return value:    Returns kDNSServiceErr_NoError on success.
2400 *                  Returns kDNSServiceErr_NoMemory if it cannot create a dispatch source
2401 *                  Returns kDNSServiceErr_BadParam if the service param is invalid or the
2402 *                  queue param is invalid
2403 */
2404 
2405 DNSServiceErrorType DNSSD_API DNSServiceSetDispatchQueue
2406   (
2407   DNSServiceRef service,
2408   dispatch_queue_t queue
2409   );
2410 #endif //_DNS_SD_LIBDISPATCH
2411 
2412 #ifdef __APPLE_API_PRIVATE
2413 
2414 #define kDNSServiceCompPrivateDNS   "PrivateDNS"
2415 #define kDNSServiceCompMulticastDNS "MulticastDNS"
2416 
2417 #endif //__APPLE_API_PRIVATE
2418 
2419 /* Some C compiler cleverness. We can make the compiler check certain things for us,
2420  * and report errors at compile-time if anything is wrong. The usual way to do this would
2421  * be to use a run-time "if" statement or the conventional run-time "assert" mechanism, but
2422  * then you don't find out what's wrong until you run the software. This way, if the assertion
2423  * condition is false, the array size is negative, and the compiler complains immediately.
2424  */
2425 
2426 struct CompileTimeAssertionChecks_DNS_SD
2427     {
2428     char assert0[(sizeof(union _TXTRecordRef_t) == 16) ? 1 : -1];
2429     };
2430 
2431 #ifdef  __cplusplus
2432     }
2433 #endif
2434 
2435 #endif  /* _DNS_SD_H */
2436