xref: /titanic_50/usr/src/cmd/cmd-inet/usr.bin/dns-sd/dns-sd.c (revision 6a37fc30652374065d6e4ab52366c499e5a34b66)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2002-2013 Apple Inc. All rights reserved.
4  *
5  * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
6  * ("Apple") in consideration of your agreement to the following terms, and your
7  * use, installation, modification or redistribution of this Apple software
8  * constitutes acceptance of these terms.  If you do not agree with these terms,
9  * please do not use, install, modify or redistribute this Apple software.
10  *
11  * In consideration of your agreement to abide by the following terms, and subject
12  * to these terms, Apple grants you a personal, non-exclusive license, under Apple's
13  * copyrights in this original Apple software (the "Apple Software"), to use,
14  * reproduce, modify and redistribute the Apple Software, with or without
15  * modifications, in source and/or binary forms; provided that if you redistribute
16  * the Apple Software in its entirety and without modifications, you must retain
17  * this notice and the following text and disclaimers in all such redistributions of
18  * the Apple Software.  Neither the name, trademarks, service marks or logos of
19  * Apple Computer, Inc. may be used to endorse or promote products derived from the
20  * Apple Software without specific prior written permission from Apple.  Except as
21  * expressly stated in this notice, no other rights or licenses, express or implied,
22  * are granted by Apple herein, including but not limited to any patent rights that
23  * may be infringed by your derivative works or by other works in which the Apple
24  * Software may be incorporated.
25  *
26  * The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
27  * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
28  * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
30  * COMBINATION WITH YOUR PRODUCTS.
31  *
32  * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
34  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
36  * OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
37  * (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
38  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39  *
40    To build this tool, copy and paste the following into a command line:
41 
42    OS X:
43    gcc dns-sd.c -o dns-sd
44 
45    POSIX systems:
46    gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
47 
48    Windows:
49    cl dns-sd.c -I../mDNSShared -DNOT_HAVE_GETOPT ws2_32.lib ..\mDNSWindows\DLL\Release\dnssd.lib
50    (may require that you run a Visual Studio script such as vsvars32.bat first)
51  */
52 
53 // For testing changes to dnssd_clientstub.c, uncomment this line and the code will be compiled
54 // with an embedded copy of the client stub instead of linking the system library version at runtime.
55 // This also useful to work around link errors when you're working on an older version of Mac OS X,
56 // and trying to build a newer version of the "dns-sd" command which uses new API entry points that
57 // aren't in the system's /usr/lib/libSystem.dylib.
58 //#define TEST_NEW_CLIENTSTUB 1
59 
60 // When building mDNSResponder for Mac OS X 10.4 and earlier, /usr/lib/libSystem.dylib is built using its own private
61 // copy of dnssd_clientstub.c, which is old and doesn't have all the entry points defined in the latest version, so
62 // when we're building dns-sd.c on Mac OS X 10.4 or earlier, we automatically set TEST_NEW_CLIENTSTUB so that we'll
63 // embed a copy of the latest dnssd_clientstub.c instead of trying to link to the incomplete version in libSystem.dylib
64 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1040
65 #define TEST_NEW_CLIENTSTUB 1
66 #endif
67 
68 #include <ctype.h>
69 #include <stdio.h>          // For stdout, stderr
70 #include <stdlib.h>         // For exit()
71 #include <string.h>         // For strlen(), strcpy()
72 #include <errno.h>          // For errno, EINTR
73 #include <time.h>
74 #include <sys/types.h>      // For u_char
75 
76 #ifdef _WIN32
77     #include <winsock2.h>
78     #include <ws2tcpip.h>
79     #include <Iphlpapi.h>
80     #include <process.h>
81 typedef int pid_t;
82     #define getpid     _getpid
83     #define strcasecmp _stricmp
84     #define snprintf   _snprintf
85 static const char kFilePathSep = '\\';
86     #ifndef HeapEnableTerminationOnCorruption
87     #     define HeapEnableTerminationOnCorruption (HEAP_INFORMATION_CLASS)1
88     #endif
89     #if !defined(IFNAMSIZ)
90      #define IFNAMSIZ 16
91     #endif
92     #define if_nametoindex if_nametoindex_win
93     #define if_indextoname if_indextoname_win
94 
95 typedef PCHAR (WINAPI * if_indextoname_funcptr_t)(ULONG index, PCHAR name);
96 typedef ULONG (WINAPI * if_nametoindex_funcptr_t)(PCSTR name);
97 
98 unsigned if_nametoindex_win(const char *ifname)
99 {
100     HMODULE library;
101     unsigned index = 0;
102 
103     // Try and load the IP helper library dll
104     if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL )
105     {
106         if_nametoindex_funcptr_t if_nametoindex_funcptr;
107 
108         // On Vista and above there is a Posix like implementation of if_nametoindex
109         if ((if_nametoindex_funcptr = (if_nametoindex_funcptr_t) GetProcAddress(library, "if_nametoindex")) != NULL )
110         {
111             index = if_nametoindex_funcptr(ifname);
112         }
113 
114         FreeLibrary(library);
115     }
116 
117     return index;
118 }
119 
120 char * if_indextoname_win( unsigned ifindex, char *ifname)
121 {
122     HMODULE library;
123     char * name = NULL;
124 
125     // Try and load the IP helper library dll
126     if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL )
127     {
128         if_indextoname_funcptr_t if_indextoname_funcptr;
129 
130         // On Vista and above there is a Posix like implementation of if_indextoname
131         if ((if_indextoname_funcptr = (if_indextoname_funcptr_t) GetProcAddress(library, "if_indextoname")) != NULL )
132         {
133             name = if_indextoname_funcptr(ifindex, ifname);
134         }
135 
136         FreeLibrary(library);
137     }
138 
139     return name;
140 }
141 
142 static size_t _sa_len(const struct sockaddr *addr)
143 {
144     if (addr->sa_family == AF_INET) return (sizeof(struct sockaddr_in));
145     else if (addr->sa_family == AF_INET6) return (sizeof(struct sockaddr_in6));
146     else return (sizeof(struct sockaddr));
147 }
148 
149 #   define SA_LEN(addr) (_sa_len(addr))
150 
151 #else
152     #include <unistd.h>         // For getopt() and optind
153     #include <netdb.h>          // For getaddrinfo()
154     #include <sys/time.h>       // For struct timeval
155     #include <sys/socket.h>     // For AF_INET
156     #include <netinet/in.h>     // For struct sockaddr_in()
157     #include <arpa/inet.h>      // For inet_addr()
158     #include <net/if.h>         // For if_nametoindex()
159 static const char kFilePathSep = '/';
160 // #ifndef NOT_HAVE_SA_LEN
161 //  #define SA_LEN(addr) ((addr)->sa_len)
162 // #else
163     #define SA_LEN(addr) (((addr)->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))
164 // #endif
165 #endif
166 
167 #if (TEST_NEW_CLIENTSTUB && !defined(__APPLE_API_PRIVATE))
168 #define __APPLE_API_PRIVATE 1
169 #endif
170 
171 // DNSServiceSetDispatchQueue is not supported on 10.6 & prior
172 #if !TEST_NEW_CLIENTSTUB && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ - (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ % 10) <= 1060)
173 #undef _DNS_SD_LIBDISPATCH
174 #endif
175 #include "dns_sd.h"
176 #include "ClientCommon.h"
177 
178 #if TEST_NEW_CLIENTSTUB
179 #include "../mDNSShared/dnssd_ipc.c"
180 #include "../mDNSShared/dnssd_clientlib.c"
181 #include "../mDNSShared/dnssd_clientstub.c"
182 #endif
183 
184 #if _DNS_SD_LIBDISPATCH
185 #include <dispatch/private.h>
186 #endif
187 
188 // The "+0" is to cope with the case where _DNS_SD_H is defined but empty (e.g. on Mac OS X 10.4 and earlier)
189 #if _DNS_SD_H+0 >= 116
190 #define HAS_NAT_PMP_API 1
191 #define HAS_ADDRINFO_API 1
192 #else
193 #define kDNSServiceFlagsReturnIntermediates 0
194 #endif
195 
196 //*************************************************************************************************************
197 // Globals
198 
199 #define DS_FIXED_SIZE   4
200 typedef struct
201 {
202     unsigned short keyTag;
203     unsigned char alg;
204     unsigned char digestType;
205     unsigned char  *digest;
206 } rdataDS;
207 
208 #define DNSKEY_FIXED_SIZE    4
209 typedef struct
210 {
211     unsigned short flags;
212     unsigned char proto;
213     unsigned char alg;
214     unsigned char *data;
215 } rdataDNSKey;
216 
217 //size of rdataRRSIG excluding signerName and signature (which are variable fields)
218 #define RRSIG_FIXED_SIZE      18
219 typedef struct
220 {
221     unsigned short typeCovered;
222     unsigned char alg;
223     unsigned char labels;
224     unsigned int origTTL;
225     unsigned int sigExpireTime;
226     unsigned int sigInceptTime;
227     unsigned short keyTag;
228     char signerName[256];
229     //unsigned char *signature
230 } rdataRRSig;
231 
232 #define RR_TYPE_SIZE 16
233 
234 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
235 
236 static int operation;
237 static uint32_t opinterface = kDNSServiceInterfaceIndexAny;
238 static DNSServiceRef client    = NULL;
239 static DNSServiceRef client_pa = NULL;  // DNSServiceRef for RegisterProxyAddressRecord
240 static DNSServiceRef sc1, sc2, sc3;     // DNSServiceRefs for kDNSServiceFlagsShareConnection testing
241 
242 static int num_printed;
243 static char addtest = 0;
244 static DNSRecordRef record = NULL;
245 static char myhinfoW[14] = "\002PC\012Windows XP";
246 static char myhinfoX[ 9] = "\003Mac\004OS X";
247 static char updatetest[3] = "\002AA";
248 static char bigNULL[8192];  // 8K is maximum rdata we support
249 
250 #if _DNS_SD_LIBDISPATCH
251 dispatch_queue_t main_queue;
252 dispatch_source_t timer_source;
253 #endif
254 
255 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
256 #define LONG_TIME 100000000
257 
258 static volatile int stopNow = 0;
259 static volatile int timeOut = LONG_TIME;
260 
261 #if _DNS_SD_LIBDISPATCH
262 #define EXIT_IF_LIBDISPATCH_FATAL_ERROR(E) \
263     if (main_queue && (E) == kDNSServiceErr_ServiceNotRunning) { fprintf(stderr, "Error code %d\n", (E)); exit(0); }
264 #else
265 #define EXIT_IF_LIBDISPATCH_FATAL_ERROR(E)
266 #endif
267 
268 //*************************************************************************************************************
269 // Supporting Utility Functions
270 static uint16_t GetRRClass(const char *s)
271 {
272     if (!strcasecmp(s, "IN"))
273         return kDNSServiceClass_IN;
274     else
275         return(atoi(s));
276 }
277 
278 static uint16_t GetRRType(const char *s)
279 {
280     if      (!strcasecmp(s, "A"       )) return(kDNSServiceType_A);
281     else if (!strcasecmp(s, "NS"      )) return(kDNSServiceType_NS);
282     else if (!strcasecmp(s, "MD"      )) return(kDNSServiceType_MD);
283     else if (!strcasecmp(s, "MF"      )) return(kDNSServiceType_MF);
284     else if (!strcasecmp(s, "CNAME"   )) return(kDNSServiceType_CNAME);
285     else if (!strcasecmp(s, "SOA"     )) return(kDNSServiceType_SOA);
286     else if (!strcasecmp(s, "MB"      )) return(kDNSServiceType_MB);
287     else if (!strcasecmp(s, "MG"      )) return(kDNSServiceType_MG);
288     else if (!strcasecmp(s, "MR"      )) return(kDNSServiceType_MR);
289     else if (!strcasecmp(s, "NULL"    )) return(kDNSServiceType_NULL);
290     else if (!strcasecmp(s, "WKS"     )) return(kDNSServiceType_WKS);
291     else if (!strcasecmp(s, "PTR"     )) return(kDNSServiceType_PTR);
292     else if (!strcasecmp(s, "HINFO"   )) return(kDNSServiceType_HINFO);
293     else if (!strcasecmp(s, "MINFO"   )) return(kDNSServiceType_MINFO);
294     else if (!strcasecmp(s, "MX"      )) return(kDNSServiceType_MX);
295     else if (!strcasecmp(s, "TXT"     )) return(kDNSServiceType_TXT);
296     else if (!strcasecmp(s, "RP"      )) return(kDNSServiceType_RP);
297     else if (!strcasecmp(s, "AFSDB"   )) return(kDNSServiceType_AFSDB);
298     else if (!strcasecmp(s, "X25"     )) return(kDNSServiceType_X25);
299     else if (!strcasecmp(s, "ISDN"    )) return(kDNSServiceType_ISDN);
300     else if (!strcasecmp(s, "RT"      )) return(kDNSServiceType_RT);
301     else if (!strcasecmp(s, "NSAP"    )) return(kDNSServiceType_NSAP);
302     else if (!strcasecmp(s, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR);
303     else if (!strcasecmp(s, "SIG"     )) return(kDNSServiceType_SIG);
304     else if (!strcasecmp(s, "KEY"     )) return(kDNSServiceType_KEY);
305     else if (!strcasecmp(s, "PX"      )) return(kDNSServiceType_PX);
306     else if (!strcasecmp(s, "GPOS"    )) return(kDNSServiceType_GPOS);
307     else if (!strcasecmp(s, "AAAA"    )) return(kDNSServiceType_AAAA);
308     else if (!strcasecmp(s, "LOC"     )) return(kDNSServiceType_LOC);
309     else if (!strcasecmp(s, "NXT"     )) return(kDNSServiceType_NXT);
310     else if (!strcasecmp(s, "EID"     )) return(kDNSServiceType_EID);
311     else if (!strcasecmp(s, "NIMLOC"  )) return(kDNSServiceType_NIMLOC);
312     else if (!strcasecmp(s, "SRV"     )) return(kDNSServiceType_SRV);
313     else if (!strcasecmp(s, "ATMA"    )) return(kDNSServiceType_ATMA);
314     else if (!strcasecmp(s, "NAPTR"   )) return(kDNSServiceType_NAPTR);
315     else if (!strcasecmp(s, "KX"      )) return(kDNSServiceType_KX);
316     else if (!strcasecmp(s, "CERT"    )) return(kDNSServiceType_CERT);
317     else if (!strcasecmp(s, "A6"      )) return(kDNSServiceType_A6);
318     else if (!strcasecmp(s, "DNAME"   )) return(kDNSServiceType_DNAME);
319     else if (!strcasecmp(s, "SINK"    )) return(kDNSServiceType_SINK);
320     else if (!strcasecmp(s, "OPT"     )) return(kDNSServiceType_OPT);
321     else if (!strcasecmp(s, "TKEY"    )) return(kDNSServiceType_TKEY);
322     else if (!strcasecmp(s, "TSIG"    )) return(kDNSServiceType_TSIG);
323     else if (!strcasecmp(s, "IXFR"    )) return(kDNSServiceType_IXFR);
324     else if (!strcasecmp(s, "AXFR"    )) return(kDNSServiceType_AXFR);
325     else if (!strcasecmp(s, "MAILB"   )) return(kDNSServiceType_MAILB);
326     else if (!strcasecmp(s, "MAILA"   )) return(kDNSServiceType_MAILA);
327     else if (!strcasecmp(s, "dnskey"  )) return(kDNSServiceType_DNSKEY);
328     else if (!strcasecmp(s, "ds"      )) return(kDNSServiceType_DS);
329     else if (!strcasecmp(s, "rrsig"   )) return(kDNSServiceType_RRSIG);
330     else if (!strcasecmp(s, "nsec"    )) return(kDNSServiceType_NSEC);
331     else if (!strcasecmp(s, "ANY"     )) return(kDNSServiceType_ANY);
332     else return(atoi(s));
333 }
334 
335 static char *DNSTypeName(unsigned short rr_type)
336 {
337     switch (rr_type)
338     {
339         case kDNSServiceType_A:         return("Addr");
340         case kDNSServiceType_NS:        return("NS");
341         case kDNSServiceType_MX:        return("MX");
342         case kDNSServiceType_CNAME:     return("CNAME");
343         case kDNSServiceType_SOA:       return("SOA");
344         case kDNSServiceType_PTR:       return("PTR");
345         case kDNSServiceType_AAAA:      return("AAAA");
346         case kDNSServiceType_NSEC:      return("NSEC");
347         case kDNSServiceType_TSIG:      return("TSIG");
348         case kDNSServiceType_RRSIG:     return("RRSIG");
349         case kDNSServiceType_DNSKEY:    return("DNSKEY");
350         case kDNSServiceType_DS:        return("DS");
351         default:
352         {
353             static char buffer[RR_TYPE_SIZE];
354             snprintf(buffer, sizeof(buffer), "TYPE%d", rr_type);
355             return(buffer);
356         }
357     }
358 }
359 
360 static unsigned short swap16(unsigned short x)
361 {
362     unsigned char *ptr = (unsigned char *)&x;
363     return (unsigned short)((unsigned short)ptr[0] << 8 | ptr[1]);
364 }
365 
366 static unsigned int swap32(unsigned int x)
367 {
368     unsigned char *ptr = (unsigned char *)&x;
369     return (unsigned int)((unsigned int)ptr[0] << 24 | (unsigned int)ptr[1] << 16 | (unsigned int)ptr[2] << 8 | ptr[3]);
370 }
371 static unsigned int keytag(unsigned char *key, unsigned int keysize)
372 {
373     unsigned long ac;
374     unsigned int i;
375 
376     for (ac = 0, i = 0; i < keysize; ++i)
377         ac += (i & 1) ? key[i] : key[i] << 8;
378     ac += (ac >> 16) & 0xFFFF;
379     return ac & 0xFFFF;
380 }
381 
382 static void base64Encode(char *buffer, int buflen, void *rdata, unsigned int rdlen)
383 {
384 #if _DNS_SD_LIBDISPATCH
385     const void *result = NULL;
386     size_t size;
387     dispatch_data_t src_data = NULL, dest_data = NULL, null_str = NULL, data = NULL, map = NULL;
388 
389     src_data = dispatch_data_create(rdata, rdlen, dispatch_get_global_queue(0, 0), ^{});
390     if (!src_data)
391         goto done;
392 
393     dest_data = dispatch_data_create_with_transform(src_data, DISPATCH_DATA_FORMAT_TYPE_NONE, DISPATCH_DATA_FORMAT_TYPE_BASE64);
394     if (!dest_data)
395         goto done;
396 
397     null_str = dispatch_data_create("", 1, dispatch_get_global_queue(0, 0), ^{});
398     if (!null_str)
399         goto done;
400 
401     data = dispatch_data_create_concat(dest_data, null_str);
402     if (!data)
403         goto done;
404 
405     map = dispatch_data_create_map(data, &result, &size);
406     if (!map)
407         goto done;
408 
409     snprintf(buffer, buflen, " %s", (char *)result);
410 
411 done:
412     if (src_data) dispatch_release(src_data);
413     if (dest_data) dispatch_release(dest_data);
414     if (data)     dispatch_release(data);
415     if (null_str) dispatch_release(null_str);
416     if (map)      dispatch_release(map);
417     return;
418 #else  //_DNS_SD_LIBDISPATCH
419     snprintf(buffer, buflen, " %s", ".");
420     return;
421 #endif //_DNS_SD_LIBDISPATCH
422 }
423 
424 #if HAS_NAT_PMP_API | HAS_ADDRINFO_API
425 static DNSServiceProtocol GetProtocol(const char *s)
426 {
427     if      (!strcasecmp(s, "v4"      )) return(kDNSServiceProtocol_IPv4);
428     else if (!strcasecmp(s, "v6"      )) return(kDNSServiceProtocol_IPv6);
429     else if (!strcasecmp(s, "v4v6"    )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
430     else if (!strcasecmp(s, "v6v4"    )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
431     else if (!strcasecmp(s, "udp"     )) return(kDNSServiceProtocol_UDP);
432     else if (!strcasecmp(s, "tcp"     )) return(kDNSServiceProtocol_TCP);
433     else if (!strcasecmp(s, "udptcp"  )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
434     else if (!strcasecmp(s, "tcpudp"  )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
435     else return(atoi(s));
436 }
437 #endif
438 
439 
440 //*************************************************************************************************************
441 // Sample callback functions for each of the operation types
442 
443 static void printtimestamp(void)
444 {
445     struct tm tm;
446     int ms;
447     static char date[16];
448     static char new_date[16];
449 #ifdef _WIN32
450     SYSTEMTIME sysTime;
451     time_t uct = time(NULL);
452     tm = *localtime(&uct);
453     GetLocalTime(&sysTime);
454     ms = sysTime.wMilliseconds;
455 #else
456     struct timeval tv;
457     gettimeofday(&tv, NULL);
458     localtime_r((time_t*)&tv.tv_sec, &tm);
459     ms = tv.tv_usec/1000;
460 #endif
461     strftime(new_date, sizeof(new_date), "%a %d %b %Y", &tm);
462     if (strncmp(date, new_date, sizeof(new_date)))
463     {
464         printf("DATE: ---%s---\n", new_date); //display date only if it has changed
465         strncpy(date, new_date, sizeof(date));
466     }
467     printf("%2d:%02d:%02d.%03d  ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms);
468 }
469 
470 // formating time to RFC 4034 format
471 static void FormatTime(unsigned long te, unsigned char *buf, int bufsize)
472 {
473     struct tm tmTime;
474 #ifdef _WIN32
475 	__time32_t t = (__time32_t) te;
476 	_gmtime32_s(&tmTime, &t);
477 #else
478     // Time since epoch : strftime takes "tm". Convert seconds to "tm" using
479     // gmtime_r first and then use strftime
480 	time_t t = (time_t)te;
481 	gmtime_r(&t, &tmTime);
482 #endif
483     strftime((char *)buf, bufsize, "%Y%m%d%H%M%S", &tmTime);
484 }
485 
486 static void print_usage(const char *arg0, int print_all)
487 {
488     fprintf(stderr, "%s -E                              (Enumerate recommended registration domains)\n", arg0);
489     fprintf(stderr, "%s -F                                  (Enumerate recommended browsing domains)\n", arg0);
490     fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...]             (Register a service)\n", arg0);
491     fprintf(stderr, "%s -B        <Type> <Domain>                    (Browse for services instances)\n", arg0);
492     fprintf(stderr, "%s -L <Name> <Type> <Domain>                       (Look up a service instance)\n", arg0);
493     fprintf(stderr, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...]              (Proxy)\n", arg0);
494     fprintf(stderr, "%s -q <name> <rrtype> <rrclass>             (Generic query for any record type)\n", arg0);
495     fprintf(stderr, "%s -D <name> <rrtype> <rrclass>(Validate query for any record type with DNSSEC)\n", arg0);
496     fprintf(stderr, "%s -Z        <Type> <Domain>               (Output results in Zone File format)\n", arg0);
497 #if HAS_ADDRINFO_API
498     fprintf(stderr, "%s -G     v4/v6/v4v6 <name>              (Get address information for hostname)\n", arg0);
499     fprintf(stderr, "%s -g v4/v6/v4v6 <name>        (Validate address info for hostname with DNSSEC)\n", arg0);
500 #endif
501     fprintf(stderr, "%s -V                (Get version of currently running daemon / system service)\n", arg0);
502 
503     if (print_all)  //Print all available options for dns-sd tool
504     {
505         fprintf(stderr, "%s -C <FQDN> <rrtype> <rrclass>               (Query; reconfirming each result)\n", arg0);
506 #if HAS_NAT_PMP_API
507         fprintf(stderr, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL>               (NAT Port Mapping)\n", arg0);
508 #endif
509         fprintf(stderr, "%s -A                                  (Test Adding/Updating/Deleting a record)\n", arg0);
510         fprintf(stderr, "%s -U                                              (Test updating a TXT record)\n", arg0);
511         fprintf(stderr, "%s -N                                         (Test adding a large NULL record)\n", arg0);
512         fprintf(stderr, "%s -T                                        (Test creating a large TXT record)\n", arg0);
513         fprintf(stderr, "%s -M                  (Test creating a registration with multiple TXT records)\n", arg0);
514         fprintf(stderr, "%s -I               (Test registering and then immediately updating TXT record)\n", arg0);
515         fprintf(stderr, "%s -S                             (Test multiple operations on a shared socket)\n", arg0);
516         fprintf(stderr, "%s -i <Interface>             (Run dns-sd cmd on a specific interface (en0/en1)\n", arg0);
517         fprintf(stderr, "%s -lo                              (Run dns-sd cmd using local only interface)\n", arg0);
518         fprintf(stderr, "%s -p2p                                      (Use kDNSServiceInterfaceIndexP2P)\n", arg0);
519         fprintf(stderr, "%s -includep2p                            (Set kDNSServiceFlagsIncludeP2P flag)\n", arg0);
520         fprintf(stderr, "%s -includeAWDL                          (Set kDNSServiceFlagsIncludeAWDL flag)\n", arg0);
521         fprintf(stderr, "%s -optional                        (Set kDNSServiceFlagsValidateOptional flag)\n", arg0);
522         fprintf(stderr, "%s -tc                        (Set kDNSServiceFlagsBackgroundTrafficClass flag)\n", arg0);
523         fprintf(stderr, "%s -unicastResponse                  (Set kDNSServiceFlagsUnicastResponse flag)\n", arg0);
524         fprintf(stderr, "%s -t1                                  (Set kDNSServiceFlagsThresholdOne flag)\n", arg0);
525         fprintf(stderr, "%s -tFinder                          (Set kDNSServiceFlagsThresholdFinder flag)\n", arg0);
526         fprintf(stderr, "%s -timeout                                  (Set kDNSServiceFlagsTimeout flag)\n", arg0);
527     }
528 }
529 
530 #define DomainMsg(X) (((X) &kDNSServiceFlagsDefault) ? "(Default)" : \
531                       ((X) &kDNSServiceFlagsAdd)     ? "Added"     : "Removed")
532 
533 #define MAX_LABELS 128
534 
535 static void DNSSD_API enum_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex,
536                                  DNSServiceErrorType errorCode, const char *replyDomain, void *context)
537 {
538     DNSServiceFlags partialflags = flags & ~(kDNSServiceFlagsMoreComing | kDNSServiceFlagsAdd | kDNSServiceFlagsDefault);
539     int labels = 0, depth = 0, i, initial = 0;
540     char text[64];
541     const char *label[MAX_LABELS];
542 
543     (void)sdref;        // Unused
544     (void)ifIndex;      // Unused
545     (void)context;      // Unused
546     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
547 
548     // 1. Print the header
549     if (num_printed++ == 0) printf("Timestamp     Recommended %s domain\n", operation == 'E' ? "Registration" : "Browsing");
550     printtimestamp();
551     if (errorCode)
552         printf("Error code %d\n", errorCode);
553     else if (!*replyDomain)
554         printf("Error: No reply domain\n");
555     else
556     {
557         printf("%-10s", DomainMsg(flags));
558         printf("%-8s", (flags & kDNSServiceFlagsMoreComing) ? "(More)" : "");
559         if (partialflags) printf("Flags: %4X  ", partialflags);
560         else printf("             ");
561 
562         // 2. Count the labels
563         while (replyDomain && *replyDomain && labels < MAX_LABELS)
564         {
565             label[labels++] = replyDomain;
566             replyDomain = GetNextLabel(replyDomain, text);
567         }
568 
569         // 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
570         if      (labels >= 3 && replyDomain - label[labels-1] <= 3 && label[labels-1] - label[labels-2] <= 4) initial = 3;
571         else if (labels >= 2 && replyDomain - label[labels-1] <= 4) initial = 2;
572         else initial = 1;
573         labels -= initial;
574 
575         // 4. Print the initial one-, two- or three-label clump
576         for (i=0; i<initial; i++)
577         {
578             GetNextLabel(label[labels+i], text);
579             if (i>0) printf(".");
580             printf("%s", text);
581         }
582         printf("\n");
583 
584         // 5. Print the remainder of the hierarchy
585         for (depth=0; depth<labels; depth++)
586         {
587             printf("                                             ");
588             for (i=0; i<=depth; i++) printf("- ");
589             GetNextLabel(label[labels-1-depth], text);
590             printf("> %s\n", text);
591         }
592     }
593 
594     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
595 }
596 
597 static int CopyLabels(char *dst, const char *lim, const char **srcp, int labels)
598 {
599     const char *src = *srcp;
600     while (*src != '.' || --labels > 0)
601     {
602         if (*src == '\\') *dst++ = *src++;  // Make sure "\." doesn't confuse us
603         if (!*src || dst >= lim) return -1;
604         *dst++ = *src++;
605         if (!*src || dst >= lim) return -1;
606     }
607     *dst++ = 0;
608     *srcp = src + 1;    // skip over final dot
609     return 0;
610 }
611 
612 static void DNSSD_API zonedata_resolve(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
613                                        const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txt, void *context)
614 {
615     union { uint16_t s; u_char b[2]; } port = { opaqueport };
616     uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
617 
618     const char *p = fullname;
619     char n[kDNSServiceMaxDomainName];
620     char t[kDNSServiceMaxDomainName];
621 
622     const unsigned char *max = txt + txtLen;
623 
624     (void)sdref;        // Unused
625     (void)ifIndex;      // Unused
626     (void)context;      // Unused
627 
628     //if (!(flags & kDNSServiceFlagsAdd)) return;
629     if (errorCode) { printf("Error code %d\n", errorCode); return; }
630 
631     if (CopyLabels(n, n + kDNSServiceMaxDomainName, &p, 3)) return;     // Fetch name+type
632     p = fullname;
633     if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 1)) return;     // Skip first label
634     if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 2)) return;     // Fetch next two labels (service type)
635 
636     if (num_printed++ == 0)
637     {
638         printf("\n");
639         printf("; To direct clients to browse a different domain, substitute that domain in place of '@'\n");
640         printf("%-47s PTR     %s\n", "lb._dns-sd._udp", "@");
641         printf("\n");
642         printf("; In the list of services below, the SRV records will typically reference dot-local Multicast DNS names.\n");
643         printf("; When transferring this zone file data to your unicast DNS server, you'll need to replace those dot-local\n");
644         printf("; names with the correct fully-qualified (unicast) domain name of the target host offering the service.\n");
645     }
646 
647     printf("\n");
648     printf("%-47s PTR     %s\n", t, n);
649     printf("%-47s SRV     0 0 %d %s ; Replace with unicast FQDN of target host\n", n, PortAsNumber, hosttarget);
650     printf("%-47s TXT    ", n);
651 
652     while (txt < max)
653     {
654         const unsigned char *const end = txt + 1 + txt[0];
655         txt++;      // Skip over length byte
656         printf(" \"");
657         while (txt<end)
658         {
659             if (*txt == '\\' || *txt == '\"') printf("\\");
660             printf("%c", *txt++);
661         }
662         printf("\"");
663     }
664     printf("\n");
665 
666     DNSServiceRefDeallocate(sdref);
667     free(context);
668 
669     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
670 }
671 
672 static void DNSSD_API zonedata_browse(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
673                                       const char *replyName, const char *replyType, const char *replyDomain, void *context)
674 {
675     DNSServiceRef *newref;
676 
677     (void)sdref;        // Unused
678     (void)context;      // Unused
679     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
680 
681     if (!(flags & kDNSServiceFlagsAdd)) return;
682     if (errorCode) { printf("Error code %d\n", errorCode); return; }
683 
684     newref = malloc(sizeof(*newref));
685     *newref = client;
686     DNSServiceResolve(newref, kDNSServiceFlagsShareConnection, ifIndex, replyName, replyType, replyDomain, zonedata_resolve, newref);
687 }
688 
689 static void DNSSD_API browse_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
690                                    const char *replyName, const char *replyType, const char *replyDomain, void *context)
691 {
692     char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
693     (void)sdref;        // Unused
694     (void)context;      // Unused
695     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
696 
697     if (num_printed++ == 0) printf("Timestamp     A/R    Flags  if %-20s %-20s %s\n", "Domain", "Service Type", "Instance Name");
698     printtimestamp();
699     if (errorCode)
700         printf("Error code %d\n", errorCode);
701     else
702         printf("%s %8X %3d %-20s %-20s %s\n",
703                 op, flags, ifIndex, replyDomain, replyType, replyName);
704     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
705 
706     // To test selective cancellation of operations of shared sockets,
707     // cancel the current operation when we've got a multiple of five results
708     //if (operation == 'S' && num_printed % 5 == 0) DNSServiceRefDeallocate(sdref);
709 }
710 
711 static void ShowTXTRecord(uint16_t txtLen, const unsigned char *txtRecord)
712 {
713     const unsigned char *ptr = txtRecord;
714     const unsigned char *max = txtRecord + txtLen;
715     while (ptr < max)
716     {
717         const unsigned char *const end = ptr + 1 + ptr[0];
718         if (end > max) { printf("<< invalid data >>"); break; }
719         if (++ptr < end) printf(" ");   // As long as string is non-empty, begin with a space
720         while (ptr<end)
721         {
722             // We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
723             // However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
724             // shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
725             // Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
726             // meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
727             // The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
728             // escapes to encode spaces and all other known shell metacharacters.
729             // (If we've missed any known shell metacharacters, please let us know.)
730             // In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
731             // Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
732             // the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
733             // The C compiler eats half of them, resulting in four appearing in the output.
734             // The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
735             // The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
736             if (strchr(" &;`'\"|*?~<>^()[]{}$", *ptr)) printf("\\");
737             if      (*ptr == '\\') printf("\\\\\\\\");
738             else if (*ptr >= ' ' ) printf("%c",        *ptr);
739             else printf("\\\\x%02X", *ptr);
740             ptr++;
741         }
742     }
743 }
744 
745 static void DNSSD_API resolve_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
746                                     const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txtRecord, void *context)
747 {
748     union { uint16_t s; u_char b[2]; } port = { opaqueport };
749     uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
750 
751     (void)sdref;        // Unused
752     (void)ifIndex;      // Unused
753     (void)context;      // Unused
754     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
755 
756     if (errorCode)
757         printf("Error code %d\n", errorCode);
758     else
759     {
760         printtimestamp();
761         printf("%s can be reached at %s:%u (interface %d)", fullname, hosttarget, PortAsNumber, ifIndex);
762         if (flags) printf(" Flags: %X", flags);
763         // Don't show degenerate TXT records containing nothing but a single empty string
764         if (txtLen > 1) { printf("\n"); ShowTXTRecord(txtLen, txtRecord); }
765         printf("\n");
766     }
767 
768     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
769 }
770 
771 static void myTimerCallBack(void)
772 {
773     DNSServiceErrorType err = kDNSServiceErr_Unknown;
774 
775     switch (operation)
776     {
777     case 'A':
778     {
779         switch (addtest)
780         {
781         case 0: printf("Adding Test HINFO record\n");
782             err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_HINFO, sizeof(myhinfoW), &myhinfoW[0], 0);
783             addtest = 1;
784             break;
785         case 1: printf("Updating Test HINFO record\n");
786             err = DNSServiceUpdateRecord(client, record, 0, sizeof(myhinfoX), &myhinfoX[0], 0);
787             addtest = 2;
788             break;
789         case 2: printf("Removing Test HINFO record\n");
790             err = DNSServiceRemoveRecord(client, record, 0);
791             addtest = 0;
792             break;
793         }
794     }
795     break;
796 
797     case 'U':
798     {
799         if (updatetest[1] != 'Z') updatetest[1]++;
800         else updatetest[1] = 'A';
801         updatetest[0] = 3 - updatetest[0];
802         updatetest[2] = updatetest[1];
803         printtimestamp();
804         printf("Updating Test TXT record to %c\n", updatetest[1]);
805         err = DNSServiceUpdateRecord(client, NULL, 0, 1+updatetest[0], &updatetest[0], 0);
806     }
807     break;
808 
809     case 'N':
810     {
811         printf("Adding big NULL record\n");
812         err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_NULL, sizeof(bigNULL), &bigNULL[0], 0);
813         if (err) printf("Failed: %d\n", err);else printf("Succeeded\n");
814         timeOut = LONG_TIME;
815 #if _DNS_SD_LIBDISPATCH
816         if (timer_source)
817             dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
818                                       (uint64_t)timeOut * NSEC_PER_SEC, 0);
819 #endif
820     }
821     break;
822     }
823 
824     if (err != kDNSServiceErr_NoError)
825     {
826         fprintf(stderr, "DNSService add/update/remove failed %ld\n", (long int)err);
827         stopNow = 1;
828     }
829 }
830 
831 static void DNSSD_API reg_reply(DNSServiceRef sdref, const DNSServiceFlags flags, DNSServiceErrorType errorCode,
832                                 const char *name, const char *regtype, const char *domain, void *context)
833 {
834     (void)sdref;    // Unused
835     (void)flags;    // Unused
836     (void)context;  // Unused
837     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
838 
839     printtimestamp();
840     printf("Got a reply for service %s.%s%s: ", name, regtype, domain);
841 
842     if (errorCode == kDNSServiceErr_NoError)
843     {
844         if (flags & kDNSServiceFlagsAdd) printf("Name now registered and active\n");
845         else printf("Name registration removed\n");
846         if (operation == 'A' || operation == 'U' || operation == 'N')
847         {
848             timeOut = 5;
849 #if _DNS_SD_LIBDISPATCH
850             if (timer_source)
851                 dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
852                                           (uint64_t)timeOut * NSEC_PER_SEC, 0);
853 #endif
854         }
855     }
856     else if (errorCode == kDNSServiceErr_NameConflict)
857     {
858         printf("Name in use, please choose another\n");
859         exit(-1);
860     }
861     else
862         printf("Error %d\n", errorCode);
863 
864     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
865 }
866 
867 // Output the wire-format domainname pointed to by rd
868 static int snprintd(char *p, int max, const unsigned char **rd)
869 {
870     const char *const buf = p;
871     const char *const end = p + max;
872     while (**rd)
873     {
874         p += snprintf(p, end-p, "%.*s.", **rd, *rd+1);
875         *rd += 1 + **rd;
876     }
877     *rd += 1;   // Advance over the final zero byte
878     return(p-buf);
879 }
880 
881 static void ParseDNSSECRecords(uint16_t rrtype, char *rdb, char *p, unsigned const char *rd, uint16_t rdlen)
882 {
883     int rdb_size = 1000;
884     switch (rrtype)
885     {
886         case kDNSServiceType_DS:
887         {
888             unsigned char *ptr;
889             int i;
890             rdataDS *rrds = (rdataDS *)rd;
891             p += snprintf(p, rdb + rdb_size - p, "%d  %d  %d  ",
892                           rrds->alg, swap16(rrds->keyTag), rrds->digestType);
893             ptr = (unsigned char *)(rd + DS_FIXED_SIZE);
894             for (i = 0; i < (rdlen - DS_FIXED_SIZE); i++)
895                 p += snprintf(p, rdb + rdb_size - p, "%x", ptr[i]);
896             break;
897         }
898 
899         case kDNSServiceType_DNSKEY:
900         {
901             rdataDNSKey *rrkey = (rdataDNSKey *)rd;
902             p += snprintf(p, rdb + rdb_size - p, "%d  %d  %d  %u", swap16(rrkey->flags), rrkey->proto,
903                           rrkey->alg, (unsigned int)keytag((unsigned char *)rrkey, rdlen));
904             base64Encode(p, rdb + rdb_size - p, (unsigned char *)(rd + DNSKEY_FIXED_SIZE), rdlen - DNSKEY_FIXED_SIZE);
905             break;
906         }
907 
908         case kDNSServiceType_NSEC:
909         {
910             unsigned char *next = (unsigned char *)rd;
911             int len, bitmaplen;
912             int win, wlen, type;
913             unsigned char *bmap;
914             char *l = NULL;
915 
916             l = p;
917             p += snprintd(p, rdb + rdb_size - p, &rd);
918             len = p - l + 1;
919 
920             bitmaplen = rdlen - len;
921             bmap = (unsigned char *)((unsigned char *)next + len);
922 
923             while (bitmaplen > 0)
924             {
925                 int i;
926 
927                 if (bitmaplen < 3)
928                 {
929                     printf("Case NSEC: malformed nsec, bitmaplen %d short\n", bitmaplen);
930                     break;
931                 }
932 
933                 win = *bmap++;
934                 wlen = *bmap++;
935                 bitmaplen -= 2;
936                 if (bitmaplen < wlen || wlen < 1 || wlen > 32)
937                 {
938                     printf("Case NSEC: malformed nsec, bitmaplen %d wlen %d\n", bitmaplen, wlen);
939                     break;
940                 }
941                 if (win < 0 || win >= 256)
942                 {
943                     printf("Case NSEC: malformed nsec, bad window win %d\n", win);
944                     break;
945                 }
946                 type = win * 256;
947                 for (i = 0; i < wlen * 8; i++)
948                 {
949                     if (bmap[i>>3] & (128 >> (i&7)))
950                         p += snprintf(p, rdb + rdb_size - p, " %s ", DNSTypeName(type + i));
951                 }
952                 bmap += wlen;
953                 bitmaplen -= wlen;
954             }
955             break;
956         }
957 
958         case kDNSServiceType_RRSIG:
959         {
960             rdataRRSig *rrsig = (rdataRRSig *)rd;
961             unsigned char expTimeBuf[64];
962             unsigned char inceptTimeBuf[64];
963             unsigned long inceptClock;
964             unsigned long expClock;
965             const unsigned char *q = NULL;
966             char *k = NULL;
967             int len;
968 
969             expClock = (unsigned long)swap32(rrsig->sigExpireTime);
970             FormatTime(expClock, expTimeBuf, sizeof(expTimeBuf));
971 
972             inceptClock = (unsigned long)swap32(rrsig->sigInceptTime);
973             FormatTime(inceptClock, inceptTimeBuf, sizeof(inceptTimeBuf));
974 
975             p += snprintf(p, rdb + rdb_size - p, " %-7s  %d  %d  %d  %s  %s  %7d  ",
976                           DNSTypeName(swap16(rrsig->typeCovered)), rrsig->alg, rrsig->labels, swap32(rrsig->origTTL),
977                           expTimeBuf, inceptTimeBuf, swap16(rrsig->keyTag));
978 
979             q = (const unsigned char *)&rrsig->signerName;
980             k = p;
981             p += snprintd(p, rdb + rdb_size - p, &q);
982             len = p - k + 1;
983 
984             base64Encode(p, rdb + rdb_size - p, (unsigned char *)(rd + len + RRSIG_FIXED_SIZE), rdlen - (len + RRSIG_FIXED_SIZE));
985             break;
986         }
987     }
988     return;
989 }
990 
991 static void DNSSD_API qr_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
992                                const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
993 {
994     char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
995     const unsigned char *rd  = rdata;
996     const unsigned char *end = (const unsigned char *) rdata + rdlen;
997     char rdb[1000] = "0.0.0.0", *p = rdb;
998     int unknowntype = 0;
999     char dnssec_status[15] = "Unknown";
1000     char rr_type[RR_TYPE_SIZE];
1001     char rr_class[3];
1002     DNSServiceFlags check_flags = flags;//local flags for dnssec status checking
1003 
1004     (void)sdref;    // Unused
1005     (void)ifIndex;  // Unused
1006     (void)ttl;      // Unused
1007     (void)context;  // Unused
1008     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
1009 
1010     if (num_printed++ == 0)
1011     {
1012         if (operation == 'D')
1013             printf("Timestamp     A/R if %-30s%-6s%-7s%-18s Rdata\n", "Name", "Type", "Class", "DNSSECStatus");
1014         else
1015             printf("Timestamp     A/R Flags if %-30s%-6s%-7s Rdata\n", "Name", "Type", "Class");
1016     }
1017     printtimestamp();
1018 
1019     switch (rrclass)
1020     {
1021         case kDNSServiceClass_IN:
1022             strncpy(rr_class, "IN", sizeof(rr_class));
1023             break;
1024         default:
1025             snprintf(rr_class, sizeof(rr_class), "%d", rrclass);
1026             break;
1027     }
1028     strncpy(rr_type, DNSTypeName(rrtype), sizeof(rr_type));
1029 
1030     if (!errorCode) //to avoid printing garbage in rdata
1031     {
1032         if (!(check_flags & (kDNSServiceFlagsValidate | kDNSServiceFlagsValidateOptional)))
1033         {
1034             switch (rrtype)
1035             {
1036                 case kDNSServiceType_A:
1037                     snprintf(rdb, sizeof(rdb), "%d.%d.%d.%d", rd[0], rd[1], rd[2], rd[3]);
1038                     break;
1039 
1040                 case kDNSServiceType_NS:
1041                 case kDNSServiceType_CNAME:
1042                 case kDNSServiceType_PTR:
1043                 case kDNSServiceType_DNAME:
1044                     p += snprintd(p, sizeof(rdb), &rd);
1045                     break;
1046 
1047                 case kDNSServiceType_SOA:
1048                     p += snprintd(p, rdb + sizeof(rdb) - p, &rd);           // mname
1049                     p += snprintf(p, rdb + sizeof(rdb) - p, " ");
1050                     p += snprintd(p, rdb + sizeof(rdb) - p, &rd);           // rname
1051                     p += snprintf(p, rdb + sizeof(rdb) - p, " Ser %d Ref %d Ret %d Exp %d Min %d",
1052                           ntohl(((uint32_t*)rd)[0]), ntohl(((uint32_t*)rd)[1]), ntohl(((uint32_t*)rd)[2]), ntohl(((uint32_t*)rd)[3]), ntohl(((uint32_t*)rd)[4]));
1053                     break;
1054 
1055                 case kDNSServiceType_AAAA:
1056                     snprintf(rdb, sizeof(rdb), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
1057                         rd[0x0], rd[0x1], rd[0x2], rd[0x3], rd[0x4], rd[0x5], rd[0x6], rd[0x7],
1058                         rd[0x8], rd[0x9], rd[0xA], rd[0xB], rd[0xC], rd[0xD], rd[0xE], rd[0xF]);
1059                     break;
1060 
1061                 case kDNSServiceType_SRV:
1062                     p += snprintf(p, rdb + sizeof(rdb) - p, "%d %d %d ",        // priority, weight, port
1063                           ntohs(*(unsigned short*)rd), ntohs(*(unsigned short*)(rd+2)), ntohs(*(unsigned short*)(rd+4)));
1064                     rd += 6;
1065                     p += snprintd(p, rdb + sizeof(rdb) - p, &rd);               // target host
1066                     break;
1067 
1068                 case kDNSServiceType_DS:
1069                 case kDNSServiceType_DNSKEY:
1070                 case kDNSServiceType_NSEC:
1071                 case kDNSServiceType_RRSIG:
1072                     ParseDNSSECRecords(rrtype, rdb, p, rd, rdlen);
1073                     break;
1074 
1075                 default:
1076                     snprintf(rdb, sizeof(rdb), "%d bytes%s", rdlen, rdlen ? ":" : "");
1077                     unknowntype = 1;
1078                     break;
1079             }
1080         }
1081         else
1082         {
1083             strncpy(rdb, "----", sizeof(rdb));
1084             //Clear all o/p bits, and then check for dnssec status
1085             check_flags &= ~kDNSServiceOutputFlags;
1086             if (check_flags & kDNSServiceFlagsSecure)
1087                 strncpy(dnssec_status, "Secure", sizeof(dnssec_status));
1088             else if (check_flags & kDNSServiceFlagsInsecure)
1089                 strncpy(dnssec_status, "Insecure", sizeof(dnssec_status));
1090             else if (check_flags & kDNSServiceFlagsIndeterminate)
1091                 strncpy(dnssec_status, "Indeterminate", sizeof(dnssec_status));
1092             else if (check_flags & kDNSServiceFlagsBogus)
1093                 strncpy(dnssec_status, "Bogus", sizeof(dnssec_status));
1094         }
1095     }
1096 
1097     if (operation == 'D')
1098         printf("%s%3d %-30s%-6s%-7s%-18s %s", op, ifIndex, fullname, rr_type, rr_class, dnssec_status, rdb);
1099     else
1100         printf("%s%6X%3d %-30s%-7s%-6s %s", op, flags, ifIndex, fullname, rr_type, rr_class, rdb);
1101     if (unknowntype)
1102     {
1103         while (rd < end)
1104             printf(" %02X", *rd++);
1105     }
1106     if (errorCode)
1107     {
1108         if (errorCode == kDNSServiceErr_NoSuchRecord)
1109             printf("    No Such Record");
1110         else if (errorCode == kDNSServiceErr_Timeout)
1111         {
1112             printf("    No Such Record\n");
1113             printf("Query Timed Out\n");
1114             exit(1);
1115         }
1116     }
1117     printf("\n");
1118 
1119     if (operation == 'C')
1120         if (flags & kDNSServiceFlagsAdd)
1121             DNSServiceReconfirmRecord(flags, ifIndex, fullname, rrtype, rrclass, rdlen, rdata);
1122 
1123     if (!(flags & kDNSServiceFlagsMoreComing))
1124         fflush(stdout);
1125 }
1126 
1127 #if HAS_NAT_PMP_API
1128 static void DNSSD_API port_mapping_create_reply(DNSServiceRef sdref, DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode, uint32_t publicAddress, uint32_t protocol, uint16_t privatePort, uint16_t publicPort, uint32_t ttl, void *context)
1129 {
1130     (void)sdref;       // Unused
1131     (void)flags;       // Unused
1132     (void)context;     // Unused
1133     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
1134 
1135     if (num_printed++ == 0) printf("Timestamp     if   %-20s %-15s %-15s %-15s %-6s\n", "External Address", "Protocol", "Internal Port", "External Port", "TTL");
1136     printtimestamp();
1137     if (errorCode && errorCode != kDNSServiceErr_DoubleNAT) printf("Error code %d\n", errorCode);
1138     else
1139     {
1140         const unsigned char *digits = (const unsigned char *)&publicAddress;
1141         char addr[256];
1142 
1143         snprintf(addr, sizeof(addr), "%d.%d.%d.%d", digits[0], digits[1], digits[2], digits[3]);
1144         printf("%-4d %-20s %-15d %-15d %-15d %-6d%s\n", ifIndex, addr, protocol, ntohs(privatePort), ntohs(publicPort), ttl, errorCode == kDNSServiceErr_DoubleNAT ? " Double NAT" : "");
1145     }
1146 
1147     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
1148 }
1149 #endif
1150 
1151 #if HAS_ADDRINFO_API
1152 static void DNSSD_API addrinfo_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context)
1153 {
1154     char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
1155     char addr[256] = "";
1156     char dnssec_status[15] = "Unknown";
1157     DNSServiceFlags check_flags = flags;
1158 	(void) sdref;
1159 	(void) context;
1160 
1161     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
1162 
1163     if (num_printed++ == 0)
1164     {
1165         if (operation == 'g')
1166             printf("Timestamp     A/R if %-25s %-44s %-18s\n", "Hostname", "Address", "DNSSECStatus");
1167         else
1168             printf("Timestamp     A/R Flags if %-38s %-44s %s\n", "Hostname", "Address", "TTL");
1169     }
1170     printtimestamp();
1171 
1172     if (address && address->sa_family == AF_INET)
1173     {
1174         const unsigned char *b = (const unsigned char *) &((struct sockaddr_in *)address)->sin_addr;
1175         snprintf(addr, sizeof(addr), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
1176     }
1177     else if (address && address->sa_family == AF_INET6)
1178     {
1179         char if_name[IFNAMSIZ];     // Older Linux distributions don't define IF_NAMESIZE
1180         const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)address;
1181         const unsigned char       *b  = (const unsigned char *      )&s6->sin6_addr;
1182         if (!if_indextoname(s6->sin6_scope_id, if_name))
1183             snprintf(if_name, sizeof(if_name), "<%d>", s6->sin6_scope_id);
1184             snprintf(addr, sizeof(addr), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X%%%s",
1185             b[0x0], b[0x1], b[0x2], b[0x3], b[0x4], b[0x5], b[0x6], b[0x7],
1186             b[0x8], b[0x9], b[0xA], b[0xB], b[0xC], b[0xD], b[0xE], b[0xF], if_name);
1187     }
1188 
1189     //go through this only if you have a dnssec validation status
1190     if (!errorCode && (check_flags & (kDNSServiceFlagsValidate | kDNSServiceFlagsValidateOptional)))
1191     {
1192         strncpy(addr, "----", sizeof(addr));
1193         //Clear all o/p bits, and then check for dnssec status
1194         check_flags &= ~kDNSServiceOutputFlags;
1195         if (check_flags & kDNSServiceFlagsSecure)
1196             strncpy(dnssec_status, "Secure", sizeof(dnssec_status));
1197         else if (check_flags & kDNSServiceFlagsInsecure)
1198             strncpy(dnssec_status, "Insecure", sizeof(dnssec_status));
1199         else if (check_flags & kDNSServiceFlagsIndeterminate)
1200             strncpy(dnssec_status, "Indeterminate", sizeof(dnssec_status));
1201         else if (check_flags & kDNSServiceFlagsBogus)
1202             strncpy(dnssec_status, "Bogus", sizeof(dnssec_status));
1203     }
1204 
1205     if (operation == 'g')
1206         printf("%s%3d %-25s %-44s %-18s", op, interfaceIndex, hostname, addr, dnssec_status);
1207     else
1208         printf("%s%6X%3d %-38s %-44s %d", op, flags, interfaceIndex, hostname, addr, ttl);
1209     if (errorCode)
1210     {
1211         if (errorCode == kDNSServiceErr_NoSuchRecord)
1212             printf("   No Such Record");
1213         else
1214             printf("   Error code %d", errorCode);
1215     }
1216     printf("\n");
1217 
1218     if (!(flags & kDNSServiceFlagsMoreComing))
1219         fflush(stdout);
1220 }
1221 #endif
1222 
1223 //*************************************************************************************************************
1224 // The main test function
1225 
1226 static void HandleEvents(void)
1227 #if _DNS_SD_LIBDISPATCH
1228 {
1229     main_queue = dispatch_get_main_queue();
1230     if (client) DNSServiceSetDispatchQueue(client, main_queue);
1231     if (client_pa) DNSServiceSetDispatchQueue(client_pa, main_queue);
1232     if (operation == 'A' || operation == 'U' || operation == 'N')
1233     {
1234         timer_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_queue);
1235         if (timer_source)
1236         {
1237             // Start the timer "timeout" seconds into the future and repeat it every "timeout" seconds
1238             dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
1239                                       (uint64_t)timeOut * NSEC_PER_SEC, 0);
1240             dispatch_source_set_event_handler(timer_source, ^{myTimerCallBack();});
1241             dispatch_resume(timer_source);
1242         }
1243     }
1244     dispatch_main();
1245 }
1246 #else
1247 {
1248     int dns_sd_fd  = client    ? DNSServiceRefSockFD(client   ) : -1;
1249     int dns_sd_fd2 = client_pa ? DNSServiceRefSockFD(client_pa) : -1;
1250     int nfds = dns_sd_fd + 1;
1251     fd_set readfds;
1252     struct timeval tv;
1253     int result;
1254 
1255     if (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;
1256 
1257     while (!stopNow)
1258     {
1259         // 1. Set up the fd_set as usual here.
1260         // This example client has no file descriptors of its own,
1261         // but a real application would call FD_SET to add them to the set here
1262         FD_ZERO(&readfds);
1263 
1264         // 2. Add the fd for our client(s) to the fd_set
1265         if (client   ) FD_SET(dns_sd_fd, &readfds);
1266         if (client_pa) FD_SET(dns_sd_fd2, &readfds);
1267 
1268         // 3. Set up the timeout.
1269         tv.tv_sec  = timeOut;
1270         tv.tv_usec = 0;
1271 
1272         result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
1273         if (result > 0)
1274         {
1275             DNSServiceErrorType err = kDNSServiceErr_NoError;
1276             if      (client    && FD_ISSET(dns_sd_fd, &readfds)) err = DNSServiceProcessResult(client   );
1277             else if (client_pa && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client_pa);
1278             if (err) { fprintf(stderr, "DNSServiceProcessResult returned %d\n", err); stopNow = 1; }
1279         }
1280         else if (result == 0)
1281             myTimerCallBack();
1282         else
1283         {
1284             printf("select() returned %d errno %d %s\n", result, errno, strerror(errno));
1285             if (errno != EINTR) stopNow = 1;
1286         }
1287     }
1288 }
1289 #endif
1290 
1291 static int getfirstoption(int argc, char **argv, const char *optstr, int *pOptInd)
1292 // Return the recognized option in optstr and the option index of the next arg.
1293 #if NOT_HAVE_GETOPT
1294 {
1295     int i;
1296     for (i=1; i < argc; i++)
1297     {
1298         if (argv[i][0] == '-' && &argv[i][1] &&
1299             NULL != strchr(optstr, argv[i][1]))
1300         {
1301             *pOptInd = i + 1;
1302             return argv[i][1];
1303         }
1304     }
1305     return -1;
1306 }
1307 #else
1308 {
1309     int o = getopt(argc, (char *const *)argv, optstr);
1310     *pOptInd = optind;
1311     return o;
1312 }
1313 #endif
1314 
1315 static void DNSSD_API MyRegisterRecordCallback(DNSServiceRef service, DNSRecordRef rec, const DNSServiceFlags flags,
1316                                                DNSServiceErrorType errorCode, void *context)
1317 {
1318     char *name = (char *)context;
1319 
1320     (void)service;  // Unused
1321     (void)rec;      // Unused
1322     (void)flags;    // Unused
1323     EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
1324 
1325     printtimestamp();
1326     printf("Got a reply for record %s: ", name);
1327 
1328     switch (errorCode)
1329     {
1330     case kDNSServiceErr_NoError:      printf("Name now registered and active\n"); break;
1331     case kDNSServiceErr_NameConflict: printf("Name in use, please choose another\n"); exit(-1);
1332     default:                          printf("Error %d\n", errorCode); break;
1333     }
1334     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
1335     // DNSServiceRemoveRecord(service, rec, 0); to test record removal
1336 
1337 #if 0   // To test updating of individual records registered via DNSServiceRegisterRecord
1338     if (!errorCode)
1339     {
1340         int x = 0x11111111;
1341         printf("Updating\n");
1342         DNSServiceUpdateRecord(service, rec, 0, sizeof(x), &x, 0);
1343     }
1344 #endif
1345 
1346     if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
1347 }
1348 
1349 static void getip(const char *const name, struct sockaddr_storage *result)
1350 {
1351     struct addrinfo *addrs = NULL;
1352     int err = getaddrinfo(name, NULL, NULL, &addrs);
1353     if (err) fprintf(stderr, "getaddrinfo error %d for %s", err, name);
1354     else memcpy(result, addrs->ai_addr, SA_LEN(addrs->ai_addr));
1355     if (addrs) freeaddrinfo(addrs);
1356 }
1357 
1358 static DNSServiceErrorType RegisterProxyAddressRecord(DNSServiceRef sdref, const char *host, const char *ip, DNSServiceFlags flags)
1359 {
1360     // Call getip() after the call DNSServiceCreateConnection().
1361     // On the Win32 platform, WinSock must be initialized for getip() to succeed.
1362     // Any DNSService* call will initialize WinSock for us, so we make sure
1363     // DNSServiceCreateConnection() is called before getip() is.
1364     struct sockaddr_storage hostaddr;
1365     getip(ip, &hostaddr);
1366     flags |= kDNSServiceFlagsUnique;
1367     if (hostaddr.ss_family == AF_INET)
1368         return(DNSServiceRegisterRecord(sdref, &record, flags, opinterface, host,
1369                                         kDNSServiceType_A,    kDNSServiceClass_IN,  4, &((struct sockaddr_in *)&hostaddr)->sin_addr,  240, MyRegisterRecordCallback, (void*)host));
1370     else if (hostaddr.ss_family == AF_INET6)
1371         return(DNSServiceRegisterRecord(sdref, &record, flags, opinterface, host,
1372                                         kDNSServiceType_AAAA, kDNSServiceClass_IN, 16, &((struct sockaddr_in6*)&hostaddr)->sin6_addr, 240, MyRegisterRecordCallback, (void*)host));
1373     else return(kDNSServiceErr_BadParam);
1374 }
1375 
1376 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :  \
1377                     ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :  \
1378                     ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
1379 
1380 #define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
1381 
1382 static DNSServiceErrorType RegisterService(DNSServiceRef *sdref,
1383                                            const char *nam, const char *typ, const char *dom, const char *host, const char *port, int argc, char **argv, DNSServiceFlags flags)
1384 {
1385     uint16_t PortAsNumber = atoi(port);
1386     Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
1387     unsigned char txt[2048] = "";
1388     unsigned char *ptr = txt;
1389     int i;
1390 
1391     if (nam[0] == '.' && nam[1] == 0) nam = "";   // We allow '.' on the command line as a synonym for empty string
1392     if (dom[0] == '.' && dom[1] == 0) dom = "";   // We allow '.' on the command line as a synonym for empty string
1393 
1394     printf("Registering Service %s.%s%s%s", nam[0] ? nam : "<<Default>>", typ, dom[0] ? "." : "", dom);
1395     if (host && *host) printf(" host %s", host);
1396     printf(" port %s", port);
1397 
1398     if (argc)
1399     {
1400         for (i = 0; i < argc; i++)
1401         {
1402             const char *p = argv[i];
1403             *ptr = 0;
1404             while (*p && *ptr < 255 && ptr + 1 + *ptr < txt+sizeof(txt))
1405             {
1406                 if      (p[0] != '\\' || p[1] == 0)                       { ptr[++*ptr] = *p;           p+=1; }
1407                 else if (p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3])) { ptr[++*ptr] = HexPair(p+2); p+=4; }
1408                 else                                                      { ptr[++*ptr] = p[1];         p+=2; }
1409             }
1410             ptr += 1 + *ptr;
1411         }
1412         printf(" TXT");
1413         ShowTXTRecord(ptr-txt, txt);
1414     }
1415     printf("\n");
1416 
1417     //flags |= kDNSServiceFlagsAllowRemoteQuery;
1418     //flags |= kDNSServiceFlagsNoAutoRename;
1419 
1420     return(DNSServiceRegister(sdref, flags, opinterface, nam, typ, dom, host, registerPort.NotAnInteger, (uint16_t) (ptr-txt), txt, reg_reply, NULL));
1421 }
1422 
1423 #define TypeBufferSize 80
1424 static char *gettype(char *buffer, char *typ)
1425 {
1426     if (!typ || !*typ || (typ[0] == '.' && typ[1] == 0)) typ = "_http._tcp";
1427     if (!strchr(typ, '.')) { snprintf(buffer, TypeBufferSize, "%s._tcp", typ); typ = buffer; }
1428     return(typ);
1429 }
1430 
1431 int main(int argc, char **argv)
1432 {
1433     DNSServiceErrorType err;
1434     char buffer[TypeBufferSize], *typ, *dom;
1435     int opi;
1436     DNSServiceFlags flags = 0;
1437     int optional = 0;
1438 
1439     // Extract the program name from argv[0], which by convention contains the path to this executable.
1440     // Note that this is just a voluntary convention, not enforced by the kernel --
1441     // the process calling exec() can pass bogus data in argv[0] if it chooses to.
1442     const char *a0 = strrchr(argv[0], kFilePathSep) + 1;
1443     if (a0 == (const char *)1) a0 = argv[0];
1444 
1445 #if defined(_WIN32)
1446     HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
1447 #endif
1448 
1449 #if TEST_NEW_CLIENTSTUB
1450     printf("Using embedded copy of dnssd_clientstub instead of system library\n");
1451     if (sizeof(argv) == 8) printf("Running in 64-bit mode\n");
1452 #endif
1453 
1454     // Test code for TXTRecord functions
1455     //TXTRecordRef txtRecord;
1456     //TXTRecordCreate(&txtRecord, 0, NULL);
1457     //TXTRecordSetValue(&txtRecord, "aaa", 1, "b");
1458     //printf("%d\n", TXTRecordContainsKey(TXTRecordGetLength(&txtRecord), TXTRecordGetBytesPtr(&txtRecord), "Aaa"));
1459 
1460     if (argc > 1 && !strcmp(argv[1], "-lo"))
1461     {
1462         argc--;
1463         argv++;
1464         opinterface = kDNSServiceInterfaceIndexLocalOnly;
1465         printf("Using LocalOnly\n");
1466     }
1467 
1468     if (argc > 1 && (!strcmp(argv[1], "-p2p") || !strcmp(argv[1], "-P2P")))
1469     {
1470         argc--;
1471         argv++;
1472         opinterface = kDNSServiceInterfaceIndexP2P;
1473     }
1474 
1475     if (argc > 1 && !strcasecmp(argv[1], "-includep2p"))
1476     {
1477         argc--;
1478         argv++;
1479         flags |= kDNSServiceFlagsIncludeP2P;
1480         printf("Setting kDNSServiceFlagsIncludeP2P\n");
1481     }
1482 
1483     if (argc > 1 && !strcasecmp(argv[1], "-includeAWDL"))
1484     {
1485         argc--;
1486         argv++;
1487         flags |= kDNSServiceFlagsIncludeAWDL;
1488         printf("Setting kDNSServiceFlagsIncludeAWDL\n");
1489     }
1490 
1491     if (argc > 1 && !strcasecmp(argv[1], "-tc"))
1492     {
1493         argc--;
1494         argv++;
1495         flags |= kDNSServiceFlagsBackgroundTrafficClass;
1496         printf("Setting kDNSServiceFlagsBackgroundTrafficClass\n");
1497     }
1498 
1499     if (argc > 1 && !strcasecmp(argv[1], "-t1"))
1500     {
1501         argc--;
1502         argv++;
1503         flags |= kDNSServiceFlagsThresholdOne;
1504         printf("Setting kDNSServiceFlagsThresholdOne\n");
1505     }
1506 
1507     if (argc > 1 && !strcasecmp(argv[1], "-tFinder"))
1508     {
1509         argc--;
1510         argv++;
1511         flags |= kDNSServiceFlagsThresholdFinder;
1512         printf("Setting kDNSServiceFlagsThresholdFinder\n");
1513     }
1514 
1515     if (argc > 1 && !strcasecmp(argv[1], "-wo"))
1516     {
1517         argc--;
1518         argv++;
1519         flags |= kDNSServiceFlagsWakeOnlyService;
1520         printf("Setting kDNSServiceFlagsWakeOnlyService\n");
1521     }
1522 
1523     if (argc > 1 && !strcasecmp(argv[1], "-unicastResponse"))
1524     {
1525         argc--;
1526         argv++;
1527         flags |= kDNSServiceFlagsUnicastResponse;
1528         printf("Setting kDNSServiceFlagsUnicastResponse\n");
1529     }
1530     if (argc > 1 && !strcasecmp(argv[1], "-timeout"))
1531     {
1532         argc--;
1533         argv++;
1534         flags |= kDNSServiceFlagsTimeout;
1535         printf("Setting kDNSServiceFlagsTimeout\n");
1536     }
1537     if (argc > 1 && !strcasecmp(argv[1], "-optional"))
1538     {
1539         argc--;
1540         argv++;
1541         optional = 1;
1542         printf("Setting DNSSEC optional flag\n");
1543     }
1544 
1545     if (argc > 2 && !strcmp(argv[1], "-i"))
1546     {
1547         opinterface = if_nametoindex(argv[2]);
1548         if (!opinterface) opinterface = atoi(argv[2]);
1549         if (!opinterface) { fprintf(stderr, "Unknown interface %s\n", argv[2]); goto Fail; }
1550         argc -= 2;
1551         argv += 2;
1552     }
1553 
1554     if (argc < 2) goto Fail;        // Minimum command line is the command name and one argument
1555     operation = getfirstoption(argc, argv, "EFBZLlRPQqCAUNTMISVHhD"
1556                                 #if HAS_NAT_PMP_API
1557                                "X"
1558                                 #endif
1559                                 #if HAS_ADDRINFO_API
1560                                "Gg"
1561                                 #endif
1562                                , &opi);
1563     if (operation == -1) goto Fail;
1564 
1565     if (opinterface) printf("Using interface %d\n", opinterface);
1566 
1567     switch (operation)
1568     {
1569     case 'E':   printf("Looking for recommended registration domains:\n");
1570         err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsRegistrationDomains, opinterface, enum_reply, NULL);
1571         break;
1572 
1573     case 'F':   printf("Looking for recommended browsing domains:\n");
1574         err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsBrowseDomains, opinterface, enum_reply, NULL);
1575         //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
1576         //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
1577         //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
1578         //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
1579         break;
1580 
1581     case 'B':   typ = (argc < opi+1) ? "" : argv[opi+0];
1582         dom = (argc < opi+2) ? "" : argv[opi+1];              // Missing domain argument is the same as empty string i.e. use system default(s)
1583         typ = gettype(buffer, typ);
1584         if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;               // We allow '.' on the command line as a synonym for empty string
1585         printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1586         err = DNSServiceBrowse(&client, flags, opinterface, typ, dom, browse_reply, NULL);
1587         break;
1588 
1589     case 'Z':   typ = (argc < opi+1) ? "" : argv[opi+0];
1590         dom = (argc < opi+2) ? "" : argv[opi+1];              // Missing domain argument is the same as empty string i.e. use system default(s)
1591         typ = gettype(buffer, typ);
1592         if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;               // We allow '.' on the command line as a synonym for empty string
1593         printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1594         err = DNSServiceCreateConnection(&client);
1595         sc1 = client;
1596         err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, typ, dom, zonedata_browse, NULL);
1597         break;
1598 
1599     case 'l':
1600     case 'L':   {
1601         if (argc < opi+2) goto Fail;
1602         typ = (argc < opi+2) ? ""      : argv[opi+1];
1603         dom = (argc < opi+3) ? "local" : argv[opi+2];
1604         typ = gettype(buffer, typ);
1605         if (dom[0] == '.' && dom[1] == 0) dom = "local";               // We allow '.' on the command line as a synonym for "local"
1606         printf("Lookup %s.%s.%s\n", argv[opi+0], typ, dom);
1607         if (operation == 'l') flags |= kDNSServiceFlagsWakeOnResolve;
1608         err = DNSServiceResolve(&client, flags, opinterface, argv[opi+0], typ, dom, resolve_reply, NULL);
1609         break;
1610     }
1611 
1612     case 'R':   if (argc < opi+4) goto Fail;
1613         typ = (argc < opi+2) ? "" : argv[opi+1];
1614         dom = (argc < opi+3) ? "" : argv[opi+2];
1615         typ = gettype(buffer, typ);
1616         if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;               // We allow '.' on the command line as a synonym for empty string
1617         err = RegisterService(&client, argv[opi+0], typ, dom, NULL, argv[opi+3], argc-(opi+4), argv+(opi+4), flags);
1618         break;
1619 
1620 
1621     case 'P':   if (argc < opi+6) goto Fail;
1622         err = DNSServiceCreateConnection(&client_pa);
1623         if (err) { fprintf(stderr, "DNSServiceCreateConnection returned %d\n", err); return(err); }
1624         err = RegisterProxyAddressRecord(client_pa, argv[opi+4], argv[opi+5], flags);
1625         if (err) break;
1626         err = RegisterService(&client, argv[opi+0], gettype(buffer, argv[opi+1]), argv[opi+2], argv[opi+4], argv[opi+3], argc-(opi+6), argv+(opi+6), flags);
1627         break;
1628 
1629     case 'D':
1630     case 'q':
1631     case 'Q':
1632     case 'C':   {
1633         uint16_t rrtype, rrclass;
1634         flags |= kDNSServiceFlagsReturnIntermediates;
1635         if (operation == 'q')
1636             flags |= kDNSServiceFlagsSuppressUnusable;
1637         if (argc < opi+1)
1638             goto Fail;
1639         rrtype = (argc <= opi+1) ? kDNSServiceType_A  : GetRRType(argv[opi+1]);
1640         rrclass = (argc <= opi+2) ? kDNSServiceClass_IN : GetRRClass(argv[opi+2]);
1641         if (rrtype == kDNSServiceType_TXT || rrtype == kDNSServiceType_PTR)
1642             flags |= kDNSServiceFlagsLongLivedQuery;
1643         if (operation == 'D')
1644         {
1645             flags |= kDNSServiceFlagsSuppressUnusable;
1646             if (optional)
1647                 flags |= kDNSServiceFlagsValidateOptional;
1648             else
1649                 flags |= kDNSServiceFlagsValidate;
1650         }
1651         err = DNSServiceQueryRecord(&client, flags, opinterface, argv[opi+0], rrtype, rrclass, qr_reply, NULL);
1652         break;
1653     }
1654 
1655     case 'A':
1656     case 'U':
1657     case 'N':   {
1658         Opaque16 registerPort = { { 0x12, 0x34 } };
1659         static const char TXT[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1660         printf("Registering Service Test._testupdate._tcp.local.\n");
1661         err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testupdate._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT)-1, TXT, reg_reply, NULL);
1662         break;
1663     }
1664 
1665     case 'T':   {
1666         Opaque16 registerPort = { { 0x23, 0x45 } };
1667         char TXT[1024];
1668         unsigned int i;
1669         for (i=0; i<sizeof(TXT); i++)
1670             if ((i & 0x1F) == 0) TXT[i] = 0x1F;else TXT[i] = 'A' + (i >> 5);
1671         printf("Registering Service Test._testlargetxt._tcp.local.\n");
1672         err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testlargetxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT), TXT, reg_reply, NULL);
1673         break;
1674     }
1675 
1676     case 'M':   {
1677         pid_t pid = getpid();
1678         Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1679         static const char TXT1[] = "\xC" "First String"  "\xD" "Second String" "\xC" "Third String";
1680         static const char TXT2[] = "\xD" "Fourth String" "\xC" "Fifth String"  "\xC" "Sixth String";
1681         printf("Registering Service Test._testdualtxt._tcp.local.\n");
1682         err = DNSServiceRegister(&client, flags, opinterface, "Test", "_testdualtxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT1)-1, TXT1, reg_reply, NULL);
1683         if (!err) err = DNSServiceAddRecord(client, &record, flags, kDNSServiceType_TXT, sizeof(TXT2)-1, TXT2, 0);
1684         break;
1685     }
1686 
1687     case 'I':   {
1688         pid_t pid = getpid();
1689         Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1690         static const char TXT[] = "\x09" "Test Data";
1691         printf("Registering Service Test._testtxt._tcp.local.\n");
1692         err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testtxt._tcp.", "", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1693         if (!err) err = DNSServiceUpdateRecord(client, NULL, 0, sizeof(TXT)-1, TXT, 0);
1694         break;
1695     }
1696 
1697 #if HAS_NAT_PMP_API
1698     case 'X':   {
1699         if (argc == opi)                // If no arguments, just fetch IP address
1700             err = DNSServiceNATPortMappingCreate(&client, 0, 0, 0, 0, 0, 0, port_mapping_create_reply, NULL);
1701         else if (argc >= opi+2 && atoi(argv[opi+0]) == 0)
1702         {
1703             DNSServiceProtocol prot  = GetProtocol(argv[opi+0]);                                    // Must specify TCP or UDP
1704             uint16_t IntPortAsNumber = atoi(argv[opi+1]);                                       // Must specify internal port
1705             uint16_t ExtPortAsNumber = (argc < opi+3) ? 0 : atoi(argv[opi+2]);              // Optional desired external port
1706             uint32_t ttl             = (argc < opi+4) ? 0 : atoi(argv[opi+3]);              // Optional desired lease lifetime
1707             Opaque16 intp = { { IntPortAsNumber >> 8, IntPortAsNumber & 0xFF } };
1708             Opaque16 extp = { { ExtPortAsNumber >> 8, ExtPortAsNumber & 0xFF } };
1709             err = DNSServiceNATPortMappingCreate(&client, 0, 0, prot, intp.NotAnInteger, extp.NotAnInteger, ttl, port_mapping_create_reply, NULL);
1710         }
1711         else goto Fail;
1712         break;
1713     }
1714 #endif
1715 
1716 #if HAS_ADDRINFO_API
1717     case 'g':
1718     case 'G':   {
1719         flags |= kDNSServiceFlagsReturnIntermediates;
1720         if (operation == 'g')
1721         {
1722             flags |= kDNSServiceFlagsSuppressUnusable;
1723             if (optional)
1724                 flags |= kDNSServiceFlagsValidateOptional;
1725             else
1726                 flags |= kDNSServiceFlagsValidate;
1727         }
1728         if (argc != opi+2)
1729             goto Fail;
1730         else
1731             err = DNSServiceGetAddrInfo(&client, flags, opinterface, GetProtocol(argv[opi+0]), argv[opi+1], addrinfo_reply, NULL);
1732         break;
1733     }
1734 #endif
1735 
1736     case 'S':   {
1737         Opaque16 registerPort = { { 0x23, 0x45 } };                 // 9029 decimal
1738         unsigned char txtrec[16] = "\xF" "/path=test.html";
1739         DNSRecordRef rec;
1740         unsigned char nulrec[4] = "1234";
1741 
1742         err = DNSServiceCreateConnection(&client);
1743         if (err) { fprintf(stderr, "DNSServiceCreateConnection failed %ld\n", (long int)err); return (-1); }
1744 
1745         sc1 = client;
1746         err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, "_http._tcp", "", browse_reply, NULL);
1747         if (err) { fprintf(stderr, "DNSServiceBrowse _http._tcp failed %ld\n", (long int)err); return (-1); }
1748 
1749         sc2 = client;
1750         err = DNSServiceBrowse(&sc2, kDNSServiceFlagsShareConnection, opinterface, "_ftp._tcp", "", browse_reply, NULL);
1751         if (err) { fprintf(stderr, "DNSServiceBrowse _ftp._tcp failed %ld\n", (long int)err); return (-1); }
1752 
1753         sc3 = client;
1754         err = DNSServiceRegister(&sc3, kDNSServiceFlagsShareConnection, opinterface, "kDNSServiceFlagsShareConnection",
1755                                  "_http._tcp", "local", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1756         if (err) { fprintf(stderr, "SharedConnection DNSServiceRegister failed %ld\n", (long int)err); return (-1); }
1757 
1758         err = DNSServiceUpdateRecord(sc3, NULL, 0, sizeof(txtrec), txtrec, 0);
1759         if (err) { fprintf(stderr, "SharedConnection DNSServiceUpdateRecord failed %ld\n", (long int)err); return (-1); }
1760 
1761         err = DNSServiceAddRecord(sc3, &rec, 0, kDNSServiceType_NULL, sizeof(nulrec), nulrec, 0);
1762         if (err) { fprintf(stderr, "SharedConnection DNSServiceAddRecord failed %ld\n", (long int)err); return (-1); }
1763 
1764         err = DNSServiceRemoveRecord(sc3, rec, 0);
1765         if (err) { fprintf(stderr, "SharedConnection DNSServiceRemoveRecord failed %ld\n", (long int)err); return (-1); }
1766 
1767         break;
1768     }
1769 
1770     case 'V':   {
1771         uint32_t v;
1772         uint32_t size = sizeof(v);
1773         err = DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion, &v, &size);
1774         if (err) fprintf(stderr, "DNSServiceGetProperty failed %ld\n", (long int)err);
1775         else printf("Currently running daemon (system service) is version %d.%d.%d\n",  v / 10000, v / 100 % 100, v % 100);
1776         exit(0);
1777     }
1778 
1779     case 'H': goto Fail;
1780 
1781     default: goto Fail;
1782     }
1783 
1784     if (!client || err != kDNSServiceErr_NoError)
1785     {
1786         fprintf(stderr, "DNSService call failed %ld%s\n", (long int)err,
1787             (err == kDNSServiceErr_ServiceNotRunning) ? " (Service Not Running)" : "");
1788         return (-1);
1789     }
1790     printtimestamp();
1791     printf("...STARTING...\n");
1792     HandleEvents();
1793 
1794     // Be sure to deallocate the DNSServiceRef when you're finished
1795     if (client   ) DNSServiceRefDeallocate(client   );
1796     if (client_pa) DNSServiceRefDeallocate(client_pa);
1797     return 0;
1798 
1799 Fail:
1800     if (operation == 'H') print_usage(a0,1);
1801     else print_usage(a0,0);
1802     return 0;
1803 
1804 }
1805 
1806 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
1807 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
1808 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
1809 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) # s
1810 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
1811 
1812 // NOT static -- otherwise the compiler may optimize it out
1813 // The "@(#) " pattern is a special prefix the "what" command looks for
1814 const char VersionString_SCCS[] = "@(#) dns-sd " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
1815 
1816 #if _BUILDING_XCODE_PROJECT_
1817 // If the process crashes, then this string will be magically included in the automatically-generated crash log
1818 const char *__crashreporter_info__ = VersionString_SCCS + 5;
1819 asm (".desc ___crashreporter_info__, 0x10");
1820 #endif
1821