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