1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2013 Apple Inc. All rights reserved.
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.
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.
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.
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.
40 To build this tool, copy and paste the following into a command line:
43 gcc dns-sd.c -o dns-sd
46 gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
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)
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
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
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
74 #include <sys/types.h> // For u_char
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
89 #if !defined(IFNAMSIZ)
92 #define if_nametoindex if_nametoindex_win
93 #define if_indextoname if_indextoname_win
95 typedef PCHAR (WINAPI
* if_indextoname_funcptr_t
)(ULONG index
, PCHAR name
);
96 typedef ULONG (WINAPI
* if_nametoindex_funcptr_t
)(PCSTR name
);
98 unsigned if_nametoindex_win(const char *ifname
)
103 // Try and load the IP helper library dll
104 if ((library
= LoadLibrary(TEXT("Iphlpapi")) ) != NULL
)
106 if_nametoindex_funcptr_t if_nametoindex_funcptr
;
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
)
111 index
= if_nametoindex_funcptr(ifname
);
114 FreeLibrary(library
);
120 char * if_indextoname_win( unsigned ifindex
, char *ifname
)
125 // Try and load the IP helper library dll
126 if ((library
= LoadLibrary(TEXT("Iphlpapi")) ) != NULL
)
128 if_indextoname_funcptr_t if_indextoname_funcptr
;
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
)
133 name
= if_indextoname_funcptr(ifindex
, ifname
);
136 FreeLibrary(library
);
142 static size_t _sa_len(const struct sockaddr
*addr
)
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
));
149 # define SA_LEN(addr) (_sa_len(addr))
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)
163 #define SA_LEN(addr) (((addr)->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))
167 #if (TEST_NEW_CLIENTSTUB && !defined(__APPLE_API_PRIVATE))
168 #define __APPLE_API_PRIVATE 1
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
176 #include "ClientCommon.h"
178 #if TEST_NEW_CLIENTSTUB
179 #include "../mDNSShared/dnssd_ipc.c"
180 #include "../mDNSShared/dnssd_clientlib.c"
181 #include "../mDNSShared/dnssd_clientstub.c"
184 #if _DNS_SD_LIBDISPATCH
185 #include <dispatch/private.h>
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
193 #define kDNSServiceFlagsReturnIntermediates 0
196 //*************************************************************************************************************
199 #define DS_FIXED_SIZE 4
202 unsigned short keyTag
;
204 unsigned char digestType
;
205 unsigned char *digest
;
208 #define DNSKEY_FIXED_SIZE 4
211 unsigned short flags
;
217 //size of rdataRRSIG excluding signerName and signature (which are variable fields)
218 #define RRSIG_FIXED_SIZE 18
221 unsigned short typeCovered
;
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
232 #define RR_TYPE_SIZE 16
234 typedef union { unsigned char b
[2]; unsigned short NotAnInteger
; } Opaque16
;
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
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
250 #if _DNS_SD_LIBDISPATCH
251 dispatch_queue_t main_queue
;
252 dispatch_source_t timer_source
;
255 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
256 #define LONG_TIME 100000000
258 static volatile int stopNow
= 0;
259 static volatile int timeOut
= LONG_TIME
;
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); }
265 #define EXIT_IF_LIBDISPATCH_FATAL_ERROR(E)
268 //*************************************************************************************************************
269 // Supporting Utility Functions
270 static uint16_t GetRRClass(const char *s
)
272 if (!strcasecmp(s
, "IN"))
273 return kDNSServiceClass_IN
;
278 static uint16_t GetRRType(const char *s
)
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
));
335 static char *DNSTypeName(unsigned short rr_type
)
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");
353 static char buffer
[RR_TYPE_SIZE
];
354 snprintf(buffer
, sizeof(buffer
), "TYPE%d", rr_type
);
360 static unsigned short swap16(unsigned short x
)
362 unsigned char *ptr
= (unsigned char *)&x
;
363 return (unsigned short)((unsigned short)ptr
[0] << 8 | ptr
[1]);
366 static unsigned int swap32(unsigned int x
)
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]);
371 static unsigned int keytag(unsigned char *key
, unsigned int keysize
)
376 for (ac
= 0, i
= 0; i
< keysize
; ++i
)
377 ac
+= (i
& 1) ? key
[i
] : key
[i
] << 8;
378 ac
+= (ac
>> 16) & 0xFFFF;
382 static void base64Encode(char *buffer
, int buflen
, void *rdata
, unsigned int rdlen
)
384 #if _DNS_SD_LIBDISPATCH
385 const void *result
= NULL
;
387 dispatch_data_t src_data
= NULL
, dest_data
= NULL
, null_str
= NULL
, data
= NULL
, map
= NULL
;
389 src_data
= dispatch_data_create(rdata
, rdlen
, dispatch_get_global_queue(0, 0), ^{});
393 dest_data
= dispatch_data_create_with_transform(src_data
, DISPATCH_DATA_FORMAT_TYPE_NONE
, DISPATCH_DATA_FORMAT_TYPE_BASE64
);
397 null_str
= dispatch_data_create("", 1, dispatch_get_global_queue(0, 0), ^{});
401 data
= dispatch_data_create_concat(dest_data
, null_str
);
405 map
= dispatch_data_create_map(data
, &result
, &size
);
409 snprintf(buffer
, buflen
, " %s", (char *)result
);
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
);
418 #else //_DNS_SD_LIBDISPATCH
419 snprintf(buffer
, buflen
, " %s", ".");
421 #endif //_DNS_SD_LIBDISPATCH
424 #if HAS_NAT_PMP_API | HAS_ADDRINFO_API
425 static DNSServiceProtocol
GetProtocol(const char *s
)
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
));
440 //*************************************************************************************************************
441 // Sample callback functions for each of the operation types
443 static void printtimestamp(void)
447 static char date
[16];
448 static char new_date
[16];
451 time_t uct
= time(NULL
);
452 tm
= *localtime(&uct
);
453 GetLocalTime(&sysTime
);
454 ms
= sysTime
.wMilliseconds
;
457 gettimeofday(&tv
, NULL
);
458 localtime_r((time_t*)&tv
.tv_sec
, &tm
);
459 ms
= tv
.tv_usec
/1000;
461 strftime(new_date
, sizeof(new_date
), "%a %d %b %Y", &tm
);
462 if (strncmp(date
, new_date
, sizeof(new_date
)))
464 printf("DATE: ---%s---\n", new_date
); //display date only if it has changed
465 strncpy(date
, new_date
, sizeof(date
));
467 printf("%2d:%02d:%02d.%03d ", tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, ms
);
470 // formating time to RFC 4034 format
471 static void FormatTime(unsigned long te
, unsigned char *buf
, int bufsize
)
475 __time32_t t
= (__time32_t
) te
;
476 _gmtime32_s(&tmTime
, &t
);
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
);
483 strftime((char *)buf
, bufsize
, "%Y%m%d%H%M%S", &tmTime
);
486 static void print_usage(const char *arg0
, int print_all
)
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
);
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
);
501 fprintf(stderr
, "%s -V (Get version of currently running daemon / system service)\n", arg0
);
503 if (print_all
) //Print all available options for dns-sd tool
505 fprintf(stderr
, "%s -C <FQDN> <rrtype> <rrclass> (Query; reconfirming each result)\n", arg0
);
507 fprintf(stderr
, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL> (NAT Port Mapping)\n", arg0
);
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
);
530 #define DomainMsg(X) (((X) &kDNSServiceFlagsDefault) ? "(Default)" : \
531 ((X) &kDNSServiceFlagsAdd) ? "Added" : "Removed")
533 #define MAX_LABELS 128
535 static void DNSSD_API
enum_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
,
536 DNSServiceErrorType errorCode
, const char *replyDomain
, void *context
)
538 DNSServiceFlags partialflags
= flags
& ~(kDNSServiceFlagsMoreComing
| kDNSServiceFlagsAdd
| kDNSServiceFlagsDefault
);
539 int labels
= 0, depth
= 0, i
, initial
= 0;
541 const char *label
[MAX_LABELS
];
543 (void)sdref
; // Unused
544 (void)ifIndex
; // Unused
545 (void)context
; // Unused
546 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
548 // 1. Print the header
549 if (num_printed
++ == 0) printf("Timestamp Recommended %s domain\n", operation
== 'E' ? "Registration" : "Browsing");
552 printf("Error code %d\n", errorCode
);
553 else if (!*replyDomain
)
554 printf("Error: No reply domain\n");
557 printf("%-10s", DomainMsg(flags
));
558 printf("%-8s", (flags
& kDNSServiceFlagsMoreComing
) ? "(More)" : "");
559 if (partialflags
) printf("Flags: %4X ", partialflags
);
562 // 2. Count the labels
563 while (replyDomain
&& *replyDomain
&& labels
< MAX_LABELS
)
565 label
[labels
++] = replyDomain
;
566 replyDomain
= GetNextLabel(replyDomain
, text
);
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;
575 // 4. Print the initial one-, two- or three-label clump
576 for (i
=0; i
<initial
; i
++)
578 GetNextLabel(label
[labels
+i
], text
);
579 if (i
>0) printf(".");
584 // 5. Print the remainder of the hierarchy
585 for (depth
=0; depth
<labels
; depth
++)
588 for (i
=0; i
<=depth
; i
++) printf("- ");
589 GetNextLabel(label
[labels
-1-depth
], text
);
590 printf("> %s\n", text
);
594 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
597 static int CopyLabels(char *dst
, const char *lim
, const char **srcp
, int labels
)
599 const char *src
= *srcp
;
600 while (*src
!= '.' || --labels
> 0)
602 if (*src
== '\\') *dst
++ = *src
++; // Make sure "\." doesn't confuse us
603 if (!*src
|| dst
>= lim
) return -1;
605 if (!*src
|| dst
>= lim
) return -1;
608 *srcp
= src
+ 1; // skip over final dot
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
)
615 union { uint16_t s
; u_char b
[2]; } port
= { opaqueport
};
616 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
618 const char *p
= fullname
;
619 char n
[kDNSServiceMaxDomainName
];
620 char t
[kDNSServiceMaxDomainName
];
622 const unsigned char *max
= txt
+ txtLen
;
624 (void)sdref
; // Unused
625 (void)ifIndex
; // Unused
626 (void)context
; // Unused
628 //if (!(flags & kDNSServiceFlagsAdd)) return;
629 if (errorCode
) { printf("Error code %d\n", errorCode
); return; }
631 if (CopyLabels(n
, n
+ kDNSServiceMaxDomainName
, &p
, 3)) return; // Fetch name+type
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)
636 if (num_printed
++ == 0)
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", "@");
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");
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
);
654 const unsigned char *const end
= txt
+ 1 + txt
[0];
655 txt
++; // Skip over length byte
659 if (*txt
== '\\' || *txt
== '\"') printf("\\");
660 printf("%c", *txt
++);
666 DNSServiceRefDeallocate(sdref
);
669 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
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
)
675 DNSServiceRef
*newref
;
677 (void)sdref
; // Unused
678 (void)context
; // Unused
679 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
681 if (!(flags
& kDNSServiceFlagsAdd
)) return;
682 if (errorCode
) { printf("Error code %d\n", errorCode
); return; }
684 newref
= malloc(sizeof(*newref
));
686 DNSServiceResolve(newref
, kDNSServiceFlagsShareConnection
, ifIndex
, replyName
, replyType
, replyDomain
, zonedata_resolve
, newref
);
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
)
692 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
693 (void)sdref
; // Unused
694 (void)context
; // Unused
695 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
697 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-20s %-20s %s\n", "Domain", "Service Type", "Instance Name");
700 printf("Error code %d\n", errorCode
);
702 printf("%s %8X %3d %-20s %-20s %s\n",
703 op
, flags
, ifIndex
, replyDomain
, replyType
, replyName
);
704 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
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);
711 static void ShowTXTRecord(uint16_t txtLen
, const unsigned char *txtRecord
)
713 const unsigned char *ptr
= txtRecord
;
714 const unsigned char *max
= txtRecord
+ txtLen
;
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
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
);
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
)
748 union { uint16_t s
; u_char b
[2]; } port
= { opaqueport
};
749 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
751 (void)sdref
; // Unused
752 (void)ifIndex
; // Unused
753 (void)context
; // Unused
754 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
757 printf("Error code %d\n", errorCode
);
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
); }
768 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
771 static void myTimerCallBack(void)
773 DNSServiceErrorType err
= kDNSServiceErr_Unknown
;
781 case 0: printf("Adding Test HINFO record\n");
782 err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_HINFO
, sizeof(myhinfoW
), &myhinfoW
[0], 0);
785 case 1: printf("Updating Test HINFO record\n");
786 err
= DNSServiceUpdateRecord(client
, record
, 0, sizeof(myhinfoX
), &myhinfoX
[0], 0);
789 case 2: printf("Removing Test HINFO record\n");
790 err
= DNSServiceRemoveRecord(client
, record
, 0);
799 if (updatetest
[1] != 'Z') updatetest
[1]++;
800 else updatetest
[1] = 'A';
801 updatetest
[0] = 3 - updatetest
[0];
802 updatetest
[2] = updatetest
[1];
804 printf("Updating Test TXT record to %c\n", updatetest
[1]);
805 err
= DNSServiceUpdateRecord(client
, NULL
, 0, 1+updatetest
[0], &updatetest
[0], 0);
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");
815 #if _DNS_SD_LIBDISPATCH
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);
824 if (err
!= kDNSServiceErr_NoError
)
826 fprintf(stderr
, "DNSService add/update/remove failed %ld\n", (long int)err
);
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
)
834 (void)sdref
; // Unused
835 (void)flags
; // Unused
836 (void)context
; // Unused
837 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
840 printf("Got a reply for service %s.%s%s: ", name
, regtype
, domain
);
842 if (errorCode
== kDNSServiceErr_NoError
)
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')
849 #if _DNS_SD_LIBDISPATCH
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);
856 else if (errorCode
== kDNSServiceErr_NameConflict
)
858 printf("Name in use, please choose another\n");
862 printf("Error %d\n", errorCode
);
864 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
867 // Output the wire-format domainname pointed to by rd
868 static int snprintd(char *p
, int max
, const unsigned char **rd
)
870 const char *const buf
= p
;
871 const char *const end
= p
+ max
;
874 p
+= snprintf(p
, end
-p
, "%.*s.", **rd
, *rd
+1);
877 *rd
+= 1; // Advance over the final zero byte
881 static void ParseDNSSECRecords(uint16_t rrtype
, char *rdb
, char *p
, unsigned const char *rd
, uint16_t rdlen
)
886 case kDNSServiceType_DS
:
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
]);
899 case kDNSServiceType_DNSKEY
:
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
);
908 case kDNSServiceType_NSEC
:
910 unsigned char *next
= (unsigned char *)rd
;
917 p
+= snprintd(p
, rdb
+ rdb_size
- p
, &rd
);
920 bitmaplen
= rdlen
- len
;
921 bmap
= (unsigned char *)((unsigned char *)next
+ len
);
923 while (bitmaplen
> 0)
929 printf("Case NSEC: malformed nsec, bitmaplen %d short\n", bitmaplen
);
936 if (bitmaplen
< wlen
|| wlen
< 1 || wlen
> 32)
938 printf("Case NSEC: malformed nsec, bitmaplen %d wlen %d\n", bitmaplen
, wlen
);
941 if (win
< 0 || win
>= 256)
943 printf("Case NSEC: malformed nsec, bad window win %d\n", win
);
947 for (i
= 0; i
< wlen
* 8; i
++)
949 if (bmap
[i
>>3] & (128 >> (i
&7)))
950 p
+= snprintf(p
, rdb
+ rdb_size
- p
, " %s ", DNSTypeName(type
+ i
));
958 case kDNSServiceType_RRSIG
:
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
;
969 expClock
= (unsigned long)swap32(rrsig
->sigExpireTime
);
970 FormatTime(expClock
, expTimeBuf
, sizeof(expTimeBuf
));
972 inceptClock
= (unsigned long)swap32(rrsig
->sigInceptTime
);
973 FormatTime(inceptClock
, inceptTimeBuf
, sizeof(inceptTimeBuf
));
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
));
979 q
= (const unsigned char *)&rrsig
->signerName
;
981 p
+= snprintd(p
, rdb
+ rdb_size
- p
, &q
);
984 base64Encode(p
, rdb
+ rdb_size
- p
, (unsigned char *)(rd
+ len
+ RRSIG_FIXED_SIZE
), rdlen
- (len
+ RRSIG_FIXED_SIZE
));
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
)
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
;
999 char dnssec_status
[15] = "Unknown";
1000 char rr_type
[RR_TYPE_SIZE
];
1002 DNSServiceFlags check_flags
= flags
;//local flags for dnssec status checking
1004 (void)sdref
; // Unused
1005 (void)ifIndex
; // Unused
1006 (void)ttl
; // Unused
1007 (void)context
; // Unused
1008 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
1010 if (num_printed
++ == 0)
1012 if (operation
== 'D')
1013 printf("Timestamp A/R if %-30s%-6s%-7s%-18s Rdata\n", "Name", "Type", "Class", "DNSSECStatus");
1015 printf("Timestamp A/R Flags if %-30s%-6s%-7s Rdata\n", "Name", "Type", "Class");
1021 case kDNSServiceClass_IN
:
1022 strncpy(rr_class
, "IN", sizeof(rr_class
));
1025 snprintf(rr_class
, sizeof(rr_class
), "%d", rrclass
);
1028 strncpy(rr_type
, DNSTypeName(rrtype
), sizeof(rr_type
));
1030 if (!errorCode
) //to avoid printing garbage in rdata
1032 if (!(check_flags
& (kDNSServiceFlagsValidate
| kDNSServiceFlagsValidateOptional
)))
1036 case kDNSServiceType_A
:
1037 snprintf(rdb
, sizeof(rdb
), "%d.%d.%d.%d", rd
[0], rd
[1], rd
[2], rd
[3]);
1040 case kDNSServiceType_NS
:
1041 case kDNSServiceType_CNAME
:
1042 case kDNSServiceType_PTR
:
1043 case kDNSServiceType_DNAME
:
1044 p
+= snprintd(p
, sizeof(rdb
), &rd
);
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]));
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]);
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)));
1065 p
+= snprintd(p
, rdb
+ sizeof(rdb
) - p
, &rd
); // target host
1068 case kDNSServiceType_DS
:
1069 case kDNSServiceType_DNSKEY
:
1070 case kDNSServiceType_NSEC
:
1071 case kDNSServiceType_RRSIG
:
1072 ParseDNSSECRecords(rrtype
, rdb
, p
, rd
, rdlen
);
1076 snprintf(rdb
, sizeof(rdb
), "%d bytes%s", rdlen
, rdlen
? ":" : "");
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
));
1097 if (operation
== 'D')
1098 printf("%s%3d %-30s%-6s%-7s%-18s %s", op
, ifIndex
, fullname
, rr_type
, rr_class
, dnssec_status
, rdb
);
1100 printf("%s%6X%3d %-30s%-7s%-6s %s", op
, flags
, ifIndex
, fullname
, rr_type
, rr_class
, rdb
);
1104 printf(" %02X", *rd
++);
1108 if (errorCode
== kDNSServiceErr_NoSuchRecord
)
1109 printf(" No Such Record");
1110 else if (errorCode
== kDNSServiceErr_Timeout
)
1112 printf(" No Such Record\n");
1113 printf("Query Timed Out\n");
1119 if (operation
== 'C')
1120 if (flags
& kDNSServiceFlagsAdd
)
1121 DNSServiceReconfirmRecord(flags
, ifIndex
, fullname
, rrtype
, rrclass
, rdlen
, rdata
);
1123 if (!(flags
& kDNSServiceFlagsMoreComing
))
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
)
1130 (void)sdref
; // Unused
1131 (void)flags
; // Unused
1132 (void)context
; // Unused
1133 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
1135 if (num_printed
++ == 0) printf("Timestamp if %-20s %-15s %-15s %-15s %-6s\n", "External Address", "Protocol", "Internal Port", "External Port", "TTL");
1137 if (errorCode
&& errorCode
!= kDNSServiceErr_DoubleNAT
) printf("Error code %d\n", errorCode
);
1140 const unsigned char *digits
= (const unsigned char *)&publicAddress
;
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" : "");
1147 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
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
)
1154 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
1155 char addr
[256] = "";
1156 char dnssec_status
[15] = "Unknown";
1157 DNSServiceFlags check_flags
= flags
;
1161 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
1163 if (num_printed
++ == 0)
1165 if (operation
== 'g')
1166 printf("Timestamp A/R if %-25s %-44s %-18s\n", "Hostname", "Address", "DNSSECStatus");
1168 printf("Timestamp A/R Flags if %-38s %-44s %s\n", "Hostname", "Address", "TTL");
1172 if (address
&& address
->sa_family
== AF_INET
)
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]);
1177 else if (address
&& address
->sa_family
== AF_INET6
)
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
);
1189 //go through this only if you have a dnssec validation status
1190 if (!errorCode
&& (check_flags
& (kDNSServiceFlagsValidate
| kDNSServiceFlagsValidateOptional
)))
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
));
1205 if (operation
== 'g')
1206 printf("%s%3d %-25s %-44s %-18s", op
, interfaceIndex
, hostname
, addr
, dnssec_status
);
1208 printf("%s%6X%3d %-38s %-44s %d", op
, flags
, interfaceIndex
, hostname
, addr
, ttl
);
1211 if (errorCode
== kDNSServiceErr_NoSuchRecord
)
1212 printf(" No Such Record");
1214 printf(" Error code %d", errorCode
);
1218 if (!(flags
& kDNSServiceFlagsMoreComing
))
1223 //*************************************************************************************************************
1224 // The main test function
1226 static void HandleEvents(void)
1227 #if _DNS_SD_LIBDISPATCH
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')
1234 timer_source
= dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER
, 0, 0, main_queue
);
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
);
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;
1255 if (dns_sd_fd2
> dns_sd_fd
) nfds
= dns_sd_fd2
+ 1;
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
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
);
1268 // 3. Set up the timeout.
1269 tv
.tv_sec
= timeOut
;
1272 result
= select(nfds
, &readfds
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
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; }
1280 else if (result
== 0)
1284 printf("select() returned %d errno %d %s\n", result
, errno
, strerror(errno
));
1285 if (errno
!= EINTR
) stopNow
= 1;
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.
1296 for (i
=1; i
< argc
; i
++)
1298 if (argv
[i
][0] == '-' && &argv
[i
][1] &&
1299 NULL
!= strchr(optstr
, argv
[i
][1]))
1309 int o
= getopt(argc
, (char *const *)argv
, optstr
);
1315 static void DNSSD_API
MyRegisterRecordCallback(DNSServiceRef service
, DNSRecordRef rec
, const DNSServiceFlags flags
,
1316 DNSServiceErrorType errorCode
, void *context
)
1318 char *name
= (char *)context
;
1320 (void)service
; // Unused
1321 (void)rec
; // Unused
1322 (void)flags
; // Unused
1323 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode
);
1326 printf("Got a reply for record %s: ", name
);
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;
1334 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
1335 // DNSServiceRemoveRecord(service, rec, 0); to test record removal
1337 #if 0 // To test updating of individual records registered via DNSServiceRegisterRecord
1341 printf("Updating\n");
1342 DNSServiceUpdateRecord(service
, rec
, 0, sizeof(x
), &x
, 0);
1346 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
1349 static void getip(const char *const name
, struct sockaddr_storage
*result
)
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
);
1358 static DNSServiceErrorType
RegisterProxyAddressRecord(DNSServiceRef sdref
, const char *host
, const char *ip
, DNSServiceFlags flags
)
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
);
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)
1380 #define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
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
)
1385 uint16_t PortAsNumber
= atoi(port
);
1386 Opaque16 registerPort
= { { PortAsNumber
>> 8, PortAsNumber
& 0xFF } };
1387 unsigned char txt
[2048] = "";
1388 unsigned char *ptr
= txt
;
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
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
);
1400 for (i
= 0; i
< argc
; i
++)
1402 const char *p
= argv
[i
];
1404 while (*p
&& *ptr
< 255 && ptr
+ 1 + *ptr
< txt
+sizeof(txt
))
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; }
1413 ShowTXTRecord(ptr
-txt
, txt
);
1417 //flags |= kDNSServiceFlagsAllowRemoteQuery;
1418 //flags |= kDNSServiceFlagsNoAutoRename;
1420 return(DNSServiceRegister(sdref
, flags
, opinterface
, nam
, typ
, dom
, host
, registerPort
.NotAnInteger
, (uint16_t) (ptr
-txt
), txt
, reg_reply
, NULL
));
1423 #define TypeBufferSize 80
1424 static char *gettype(char *buffer
, char *typ
)
1426 if (!typ
|| !*typ
|| (typ
[0] == '.' && typ
[1] == 0)) typ
= "_http._tcp";
1427 if (!strchr(typ
, '.')) { snprintf(buffer
, TypeBufferSize
, "%s._tcp", typ
); typ
= buffer
; }
1431 int main(int argc
, char **argv
)
1433 DNSServiceErrorType err
;
1434 char buffer
[TypeBufferSize
], *typ
, *dom
;
1436 DNSServiceFlags flags
= 0;
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];
1446 HeapSetInformation(NULL
, HeapEnableTerminationOnCorruption
, NULL
, 0);
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");
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"));
1460 if (argc
> 1 && !strcmp(argv
[1], "-lo"))
1464 opinterface
= kDNSServiceInterfaceIndexLocalOnly
;
1465 printf("Using LocalOnly\n");
1468 if (argc
> 1 && (!strcmp(argv
[1], "-p2p") || !strcmp(argv
[1], "-P2P")))
1472 opinterface
= kDNSServiceInterfaceIndexP2P
;
1475 if (argc
> 1 && !strcasecmp(argv
[1], "-includep2p"))
1479 flags
|= kDNSServiceFlagsIncludeP2P
;
1480 printf("Setting kDNSServiceFlagsIncludeP2P\n");
1483 if (argc
> 1 && !strcasecmp(argv
[1], "-includeAWDL"))
1487 flags
|= kDNSServiceFlagsIncludeAWDL
;
1488 printf("Setting kDNSServiceFlagsIncludeAWDL\n");
1491 if (argc
> 1 && !strcasecmp(argv
[1], "-tc"))
1495 flags
|= kDNSServiceFlagsBackgroundTrafficClass
;
1496 printf("Setting kDNSServiceFlagsBackgroundTrafficClass\n");
1499 if (argc
> 1 && !strcasecmp(argv
[1], "-t1"))
1503 flags
|= kDNSServiceFlagsThresholdOne
;
1504 printf("Setting kDNSServiceFlagsThresholdOne\n");
1507 if (argc
> 1 && !strcasecmp(argv
[1], "-tFinder"))
1511 flags
|= kDNSServiceFlagsThresholdFinder
;
1512 printf("Setting kDNSServiceFlagsThresholdFinder\n");
1515 if (argc
> 1 && !strcasecmp(argv
[1], "-wo"))
1519 flags
|= kDNSServiceFlagsWakeOnlyService
;
1520 printf("Setting kDNSServiceFlagsWakeOnlyService\n");
1523 if (argc
> 1 && !strcasecmp(argv
[1], "-unicastResponse"))
1527 flags
|= kDNSServiceFlagsUnicastResponse
;
1528 printf("Setting kDNSServiceFlagsUnicastResponse\n");
1530 if (argc
> 1 && !strcasecmp(argv
[1], "-timeout"))
1534 flags
|= kDNSServiceFlagsTimeout
;
1535 printf("Setting kDNSServiceFlagsTimeout\n");
1537 if (argc
> 1 && !strcasecmp(argv
[1], "-optional"))
1542 printf("Setting DNSSEC optional flag\n");
1545 if (argc
> 2 && !strcmp(argv
[1], "-i"))
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
; }
1554 if (argc
< 2) goto Fail
; // Minimum command line is the command name and one argument
1555 operation
= getfirstoption(argc
, argv
, "EFBZLlRPQqCAUNTMISVHhD"
1559 #if HAS_ADDRINFO_API
1563 if (operation
== -1) goto Fail
;
1565 if (opinterface
) printf("Using interface %d\n", opinterface
);
1569 case 'E': printf("Looking for recommended registration domains:\n");
1570 err
= DNSServiceEnumerateDomains(&client
, kDNSServiceFlagsRegistrationDomains
, opinterface
, enum_reply
, NULL
);
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);
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
);
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
);
1596 err
= DNSServiceBrowse(&sc1
, kDNSServiceFlagsShareConnection
, opinterface
, typ
, dom
, zonedata_browse
, NULL
);
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
);
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
);
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
);
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
);
1633 uint16_t rrtype
, rrclass
;
1634 flags
|= kDNSServiceFlagsReturnIntermediates
;
1635 if (operation
== 'q')
1636 flags
|= kDNSServiceFlagsSuppressUnusable
;
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')
1645 flags
|= kDNSServiceFlagsSuppressUnusable
;
1647 flags
|= kDNSServiceFlagsValidateOptional
;
1649 flags
|= kDNSServiceFlagsValidate
;
1651 err
= DNSServiceQueryRecord(&client
, flags
, opinterface
, argv
[opi
+0], rrtype
, rrclass
, qr_reply
, NULL
);
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
);
1666 Opaque16 registerPort
= { { 0x23, 0x45 } };
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
);
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);
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);
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)
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
);
1716 #if HAS_ADDRINFO_API
1719 flags
|= kDNSServiceFlagsReturnIntermediates
;
1720 if (operation
== 'g')
1722 flags
|= kDNSServiceFlagsSuppressUnusable
;
1724 flags
|= kDNSServiceFlagsValidateOptional
;
1726 flags
|= kDNSServiceFlagsValidate
;
1731 err
= DNSServiceGetAddrInfo(&client
, flags
, opinterface
, GetProtocol(argv
[opi
+0]), argv
[opi
+1], addrinfo_reply
, NULL
);
1737 Opaque16 registerPort
= { { 0x23, 0x45 } }; // 9029 decimal
1738 unsigned char txtrec
[16] = "\xF" "/path=test.html";
1740 unsigned char nulrec
[4] = "1234";
1742 err
= DNSServiceCreateConnection(&client
);
1743 if (err
) { fprintf(stderr
, "DNSServiceCreateConnection failed %ld\n", (long int)err
); return (-1); }
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); }
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); }
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); }
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); }
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); }
1764 err
= DNSServiceRemoveRecord(sc3
, rec
, 0);
1765 if (err
) { fprintf(stderr
, "SharedConnection DNSServiceRemoveRecord failed %ld\n", (long int)err
); return (-1); }
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);
1779 case 'H': goto Fail
;
1784 if (!client
|| err
!= kDNSServiceErr_NoError
)
1786 fprintf(stderr
, "DNSService call failed %ld%s\n", (long int)err
,
1787 (err
== kDNSServiceErr_ServiceNotRunning
) ? " (Service Not Running)" : "");
1791 printf("...STARTING...\n");
1794 // Be sure to deallocate the DNSServiceRef when you're finished
1795 if (client
) DNSServiceRefDeallocate(client
);
1796 if (client_pa
) DNSServiceRefDeallocate(client_pa
);
1800 if (operation
== 'H') print_usage(a0
,1);
1801 else print_usage(a0
,0);
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)
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__
")";
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");