]> git.saurik.com Git - apple/mdnsresponder.git/blob - Clients/dns-sd.c
mDNSResponder-379.38.1.tar.gz
[apple/mdnsresponder.git] / Clients / dns-sd.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2008 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 // 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)
185 #if _DNS_SD_H+0 >= 116
186 #define HAS_NAT_PMP_API 1
187 #define HAS_ADDRINFO_API 1
188 #else
189 #define kDNSServiceFlagsReturnIntermediates 0
190 #endif
191
192 //*************************************************************************************************************
193 // Globals
194
195 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
196
197 static int operation;
198 static uint32_t opinterface = kDNSServiceInterfaceIndexAny;
199 static DNSServiceRef client = NULL;
200 static DNSServiceRef client_pa = NULL; // DNSServiceRef for RegisterProxyAddressRecord
201 static DNSServiceRef sc1, sc2, sc3; // DNSServiceRefs for kDNSServiceFlagsShareConnection testing
202
203 static int num_printed;
204 static char addtest = 0;
205 static DNSRecordRef record = NULL;
206 static char myhinfoW[14] = "\002PC\012Windows XP";
207 static char myhinfoX[ 9] = "\003Mac\004OS X";
208 static char updatetest[3] = "\002AA";
209 static char bigNULL[8192]; // 8K is maximum rdata we support
210
211 #if _DNS_SD_LIBDISPATCH
212 dispatch_queue_t main_queue;
213 dispatch_source_t timer_source;
214 #endif
215
216 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
217 #define LONG_TIME 100000000
218
219 static volatile int stopNow = 0;
220 static volatile int timeOut = LONG_TIME;
221
222 #if _DNS_SD_LIBDISPATCH
223 #define EXIT_IF_LIBDISPATCH_FATAL_ERROR(E) \
224 if (main_queue && (E) == kDNSServiceErr_ServiceNotRunning) { fprintf(stderr, "Error code %d\n", (E)); exit(0); }
225 #else
226 #define EXIT_IF_LIBDISPATCH_FATAL_ERROR(E)
227 #endif
228
229 //*************************************************************************************************************
230 // Supporting Utility Functions
231
232 static uint16_t GetRRType(const char *s)
233 {
234 if (!strcasecmp(s, "A" )) return(kDNSServiceType_A);
235 else if (!strcasecmp(s, "NS" )) return(kDNSServiceType_NS);
236 else if (!strcasecmp(s, "MD" )) return(kDNSServiceType_MD);
237 else if (!strcasecmp(s, "MF" )) return(kDNSServiceType_MF);
238 else if (!strcasecmp(s, "CNAME" )) return(kDNSServiceType_CNAME);
239 else if (!strcasecmp(s, "SOA" )) return(kDNSServiceType_SOA);
240 else if (!strcasecmp(s, "MB" )) return(kDNSServiceType_MB);
241 else if (!strcasecmp(s, "MG" )) return(kDNSServiceType_MG);
242 else if (!strcasecmp(s, "MR" )) return(kDNSServiceType_MR);
243 else if (!strcasecmp(s, "NULL" )) return(kDNSServiceType_NULL);
244 else if (!strcasecmp(s, "WKS" )) return(kDNSServiceType_WKS);
245 else if (!strcasecmp(s, "PTR" )) return(kDNSServiceType_PTR);
246 else if (!strcasecmp(s, "HINFO" )) return(kDNSServiceType_HINFO);
247 else if (!strcasecmp(s, "MINFO" )) return(kDNSServiceType_MINFO);
248 else if (!strcasecmp(s, "MX" )) return(kDNSServiceType_MX);
249 else if (!strcasecmp(s, "TXT" )) return(kDNSServiceType_TXT);
250 else if (!strcasecmp(s, "RP" )) return(kDNSServiceType_RP);
251 else if (!strcasecmp(s, "AFSDB" )) return(kDNSServiceType_AFSDB);
252 else if (!strcasecmp(s, "X25" )) return(kDNSServiceType_X25);
253 else if (!strcasecmp(s, "ISDN" )) return(kDNSServiceType_ISDN);
254 else if (!strcasecmp(s, "RT" )) return(kDNSServiceType_RT);
255 else if (!strcasecmp(s, "NSAP" )) return(kDNSServiceType_NSAP);
256 else if (!strcasecmp(s, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR);
257 else if (!strcasecmp(s, "SIG" )) return(kDNSServiceType_SIG);
258 else if (!strcasecmp(s, "KEY" )) return(kDNSServiceType_KEY);
259 else if (!strcasecmp(s, "PX" )) return(kDNSServiceType_PX);
260 else if (!strcasecmp(s, "GPOS" )) return(kDNSServiceType_GPOS);
261 else if (!strcasecmp(s, "AAAA" )) return(kDNSServiceType_AAAA);
262 else if (!strcasecmp(s, "LOC" )) return(kDNSServiceType_LOC);
263 else if (!strcasecmp(s, "NXT" )) return(kDNSServiceType_NXT);
264 else if (!strcasecmp(s, "EID" )) return(kDNSServiceType_EID);
265 else if (!strcasecmp(s, "NIMLOC" )) return(kDNSServiceType_NIMLOC);
266 else if (!strcasecmp(s, "SRV" )) return(kDNSServiceType_SRV);
267 else if (!strcasecmp(s, "ATMA" )) return(kDNSServiceType_ATMA);
268 else if (!strcasecmp(s, "NAPTR" )) return(kDNSServiceType_NAPTR);
269 else if (!strcasecmp(s, "KX" )) return(kDNSServiceType_KX);
270 else if (!strcasecmp(s, "CERT" )) return(kDNSServiceType_CERT);
271 else if (!strcasecmp(s, "A6" )) return(kDNSServiceType_A6);
272 else if (!strcasecmp(s, "DNAME" )) return(kDNSServiceType_DNAME);
273 else if (!strcasecmp(s, "SINK" )) return(kDNSServiceType_SINK);
274 else if (!strcasecmp(s, "OPT" )) return(kDNSServiceType_OPT);
275 else if (!strcasecmp(s, "TKEY" )) return(kDNSServiceType_TKEY);
276 else if (!strcasecmp(s, "TSIG" )) return(kDNSServiceType_TSIG);
277 else if (!strcasecmp(s, "IXFR" )) return(kDNSServiceType_IXFR);
278 else if (!strcasecmp(s, "AXFR" )) return(kDNSServiceType_AXFR);
279 else if (!strcasecmp(s, "MAILB" )) return(kDNSServiceType_MAILB);
280 else if (!strcasecmp(s, "MAILA" )) return(kDNSServiceType_MAILA);
281 else if (!strcasecmp(s, "dnskey" )) return(kDNSServiceType_DNSKEY);
282 else if (!strcasecmp(s, "ds" )) return(kDNSServiceType_DS);
283 else if (!strcasecmp(s, "rrsig" )) return(kDNSServiceType_RRSIG);
284 else if (!strcasecmp(s, "nsec" )) return(kDNSServiceType_NSEC);
285 else if (!strcasecmp(s, "ANY" )) return(kDNSServiceType_ANY);
286 else return(atoi(s));
287 }
288
289 #if HAS_NAT_PMP_API | HAS_ADDRINFO_API
290 static DNSServiceProtocol GetProtocol(const char *s)
291 {
292 if (!strcasecmp(s, "v4" )) return(kDNSServiceProtocol_IPv4);
293 else if (!strcasecmp(s, "v6" )) return(kDNSServiceProtocol_IPv6);
294 else if (!strcasecmp(s, "v4v6" )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
295 else if (!strcasecmp(s, "v6v4" )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
296 else if (!strcasecmp(s, "udp" )) return(kDNSServiceProtocol_UDP);
297 else if (!strcasecmp(s, "tcp" )) return(kDNSServiceProtocol_TCP);
298 else if (!strcasecmp(s, "udptcp" )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
299 else if (!strcasecmp(s, "tcpudp" )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
300 else return(atoi(s));
301 }
302 #endif
303
304 //*************************************************************************************************************
305 // Sample callback functions for each of the operation types
306
307 static void printtimestamp(void)
308 {
309 struct tm tm;
310 int ms;
311 static char date[16];
312 static char new_date[16];
313 #ifdef _WIN32
314 SYSTEMTIME sysTime;
315 time_t uct = time(NULL);
316 tm = *localtime(&uct);
317 GetLocalTime(&sysTime);
318 ms = sysTime.wMilliseconds;
319 #else
320 struct timeval tv;
321 gettimeofday(&tv, NULL);
322 localtime_r((time_t*)&tv.tv_sec, &tm);
323 ms = tv.tv_usec/1000;
324 #endif
325 strftime(new_date, sizeof(new_date), "%a %d %b %Y", &tm);
326 if (strncmp(date, new_date, sizeof(new_date)))
327 {
328 printf("DATE: ---%s---\n", new_date); //display date only if it has changed
329 strncpy(date, new_date, sizeof(date));
330 }
331 printf("%2d:%02d:%02d.%03d ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms);
332 }
333
334 static void print_usage(const char *arg0, int print_all)
335 {
336 fprintf(stderr, "%s -E (Enumerate recommended registration domains)\n", arg0);
337 fprintf(stderr, "%s -F (Enumerate recommended browsing domains)\n", arg0);
338 fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", arg0);
339 fprintf(stderr, "%s -B <Type> <Domain> (Browse for services instances)\n", arg0);
340 fprintf(stderr, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", arg0);
341 fprintf(stderr, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...] (Proxy)\n", arg0);
342 fprintf(stderr, "%s -q <name> <rrtype> <rrclass> (Generic query for any record type)\n", arg0);
343 fprintf(stderr, "%s -Z <Type> <Domain> (Output results in Zone File format)\n", arg0);
344 #if HAS_ADDRINFO_API
345 fprintf(stderr, "%s -G v4/v6/v4v6 <name> (Get address information for hostname)\n", arg0);
346 #endif
347 fprintf(stderr, "%s -V (Get version of currently running daemon / system service)\n", arg0);
348
349 if (print_all) //Print all available options for dns-sd tool
350 {
351 fprintf(stderr, "%s -C <FQDN> <rrtype> <rrclass> (Query; reconfirming each result)\n", arg0);
352 #if HAS_NAT_PMP_API
353 fprintf(stderr, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL> (NAT Port Mapping)\n", arg0);
354 #endif
355 fprintf(stderr, "%s -A (Test Adding/Updating/Deleting a record)\n", arg0);
356 fprintf(stderr, "%s -U (Test updating a TXT record)\n", arg0);
357 fprintf(stderr, "%s -N (Test adding a large NULL record)\n", arg0);
358 fprintf(stderr, "%s -T (Test creating a large TXT record)\n", arg0);
359 fprintf(stderr, "%s -M (Test creating a registration with multiple TXT records)\n", arg0);
360 fprintf(stderr, "%s -I (Test registering and then immediately updating TXT record)\n", arg0);
361 fprintf(stderr, "%s -S (Test multiple operations on a shared socket)\n", arg0);
362 fprintf(stderr, "%s -i <Interface> (Run dns-sd cmd on a specific interface (en0/en1)\n", arg0);
363 fprintf(stderr, "%s -lo (Run dns-sd cmd using local only interface)\n", arg0);
364 fprintf(stderr, "%s -p2p (Use kDNSServiceInterfaceIndexP2P)\n", arg0);
365 fprintf(stderr, "%s -includep2p (Set kDNSServiceFlagsIncludeP2P flag)\n", arg0);
366 fprintf(stderr, "%s -includeAWDL (Set kDNSServiceFlagsIncludeAWDL flag)\n", arg0);
367 fprintf(stderr, "%s -tc (Set kDNSServiceFlagsBackgroundTrafficClass flag)\n", arg0);
368 }
369 }
370
371 #define DomainMsg(X) (((X) &kDNSServiceFlagsDefault) ? "(Default)" : \
372 ((X) &kDNSServiceFlagsAdd) ? "Added" : "Removed")
373
374 #define MAX_LABELS 128
375
376 static void DNSSD_API enum_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex,
377 DNSServiceErrorType errorCode, const char *replyDomain, void *context)
378 {
379 DNSServiceFlags partialflags = flags & ~(kDNSServiceFlagsMoreComing | kDNSServiceFlagsAdd | kDNSServiceFlagsDefault);
380 int labels = 0, depth = 0, i, initial = 0;
381 char text[64];
382 const char *label[MAX_LABELS];
383
384 (void)sdref; // Unused
385 (void)ifIndex; // Unused
386 (void)context; // Unused
387 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
388
389 // 1. Print the header
390 if (num_printed++ == 0) printf("Timestamp Recommended %s domain\n", operation == 'E' ? "Registration" : "Browsing");
391 printtimestamp();
392 if (errorCode)
393 printf("Error code %d\n", errorCode);
394 else if (!*replyDomain)
395 printf("Error: No reply domain\n");
396 else
397 {
398 printf("%-10s", DomainMsg(flags));
399 printf("%-8s", (flags & kDNSServiceFlagsMoreComing) ? "(More)" : "");
400 if (partialflags) printf("Flags: %4X ", partialflags);
401 else printf(" ");
402
403 // 2. Count the labels
404 while (replyDomain && *replyDomain && labels < MAX_LABELS)
405 {
406 label[labels++] = replyDomain;
407 replyDomain = GetNextLabel(replyDomain, text);
408 }
409
410 // 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
411 if (labels >= 3 && replyDomain - label[labels-1] <= 3 && label[labels-1] - label[labels-2] <= 4) initial = 3;
412 else if (labels >= 2 && replyDomain - label[labels-1] <= 4) initial = 2;
413 else initial = 1;
414 labels -= initial;
415
416 // 4. Print the initial one-, two- or three-label clump
417 for (i=0; i<initial; i++)
418 {
419 GetNextLabel(label[labels+i], text);
420 if (i>0) printf(".");
421 printf("%s", text);
422 }
423 printf("\n");
424
425 // 5. Print the remainder of the hierarchy
426 for (depth=0; depth<labels; depth++)
427 {
428 printf(" ");
429 for (i=0; i<=depth; i++) printf("- ");
430 GetNextLabel(label[labels-1-depth], text);
431 printf("> %s\n", text);
432 }
433 }
434
435 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
436 }
437
438 static int CopyLabels(char *dst, const char *lim, const char **srcp, int labels)
439 {
440 const char *src = *srcp;
441 while (*src != '.' || --labels > 0)
442 {
443 if (*src == '\\') *dst++ = *src++; // Make sure "\." doesn't confuse us
444 if (!*src || dst >= lim) return -1;
445 *dst++ = *src++;
446 if (!*src || dst >= lim) return -1;
447 }
448 *dst++ = 0;
449 *srcp = src + 1; // skip over final dot
450 return 0;
451 }
452
453 static void DNSSD_API zonedata_resolve(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
454 const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txt, void *context)
455 {
456 union { uint16_t s; u_char b[2]; } port = { opaqueport };
457 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
458
459 const char *p = fullname;
460 char n[kDNSServiceMaxDomainName];
461 char t[kDNSServiceMaxDomainName];
462
463 const unsigned char *max = txt + txtLen;
464
465 (void)sdref; // Unused
466 (void)ifIndex; // Unused
467 (void)context; // Unused
468
469 //if (!(flags & kDNSServiceFlagsAdd)) return;
470 if (errorCode) { printf("Error code %d\n", errorCode); return; }
471
472 if (CopyLabels(n, n + kDNSServiceMaxDomainName, &p, 3)) return; // Fetch name+type
473 p = fullname;
474 if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 1)) return; // Skip first label
475 if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 2)) return; // Fetch next two labels (service type)
476
477 if (num_printed++ == 0)
478 {
479 printf("\n");
480 printf("; To direct clients to browse a different domain, substitute that domain in place of '@'\n");
481 printf("%-47s PTR %s\n", "lb._dns-sd._udp", "@");
482 printf("\n");
483 printf("; In the list of services below, the SRV records will typically reference dot-local Multicast DNS names.\n");
484 printf("; When transferring this zone file data to your unicast DNS server, you'll need to replace those dot-local\n");
485 printf("; names with the correct fully-qualified (unicast) domain name of the target host offering the service.\n");
486 }
487
488 printf("\n");
489 printf("%-47s PTR %s\n", t, n);
490 printf("%-47s SRV 0 0 %d %s ; Replace with unicast FQDN of target host\n", n, PortAsNumber, hosttarget);
491 printf("%-47s TXT ", n);
492
493 while (txt < max)
494 {
495 const unsigned char *const end = txt + 1 + txt[0];
496 txt++; // Skip over length byte
497 printf(" \"");
498 while (txt<end)
499 {
500 if (*txt == '\\' || *txt == '\"') printf("\\");
501 printf("%c", *txt++);
502 }
503 printf("\"");
504 }
505 printf("\n");
506
507 DNSServiceRefDeallocate(sdref);
508 free(context);
509
510 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
511 }
512
513 static void DNSSD_API zonedata_browse(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
514 const char *replyName, const char *replyType, const char *replyDomain, void *context)
515 {
516 DNSServiceRef *newref;
517
518 (void)sdref; // Unused
519 (void)context; // Unused
520 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
521
522 if (!(flags & kDNSServiceFlagsAdd)) return;
523 if (errorCode) { printf("Error code %d\n", errorCode); return; }
524
525 newref = malloc(sizeof(*newref));
526 *newref = client;
527 DNSServiceResolve(newref, kDNSServiceFlagsShareConnection, ifIndex, replyName, replyType, replyDomain, zonedata_resolve, newref);
528 }
529
530 static void DNSSD_API browse_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
531 const char *replyName, const char *replyType, const char *replyDomain, void *context)
532 {
533 char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
534 (void)sdref; // Unused
535 (void)context; // Unused
536 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
537
538 if (num_printed++ == 0) printf("Timestamp A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
539 printtimestamp();
540 if (errorCode) printf("Error code %d\n", errorCode);
541 else printf("%s%6X%3d %-25s %-25s %s\n", op, flags, ifIndex, replyDomain, replyType, replyName);
542 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
543
544 // To test selective cancellation of operations of shared sockets,
545 // cancel the current operation when we've got a multiple of five results
546 //if (operation == 'S' && num_printed % 5 == 0) DNSServiceRefDeallocate(sdref);
547 }
548
549 static void ShowTXTRecord(uint16_t txtLen, const unsigned char *txtRecord)
550 {
551 const unsigned char *ptr = txtRecord;
552 const unsigned char *max = txtRecord + txtLen;
553 while (ptr < max)
554 {
555 const unsigned char *const end = ptr + 1 + ptr[0];
556 if (end > max) { printf("<< invalid data >>"); break; }
557 if (++ptr < end) printf(" "); // As long as string is non-empty, begin with a space
558 while (ptr<end)
559 {
560 // We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
561 // However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
562 // shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
563 // Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
564 // meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
565 // The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
566 // escapes to encode spaces and all other known shell metacharacters.
567 // (If we've missed any known shell metacharacters, please let us know.)
568 // In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
569 // Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
570 // the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
571 // The C compiler eats half of them, resulting in four appearing in the output.
572 // The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
573 // The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
574 if (strchr(" &;`'\"|*?~<>^()[]{}$", *ptr)) printf("\\");
575 if (*ptr == '\\') printf("\\\\\\\\");
576 else if (*ptr >= ' ' ) printf("%c", *ptr);
577 else printf("\\\\x%02X", *ptr);
578 ptr++;
579 }
580 }
581 }
582
583 static void DNSSD_API resolve_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
584 const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txtRecord, void *context)
585 {
586 union { uint16_t s; u_char b[2]; } port = { opaqueport };
587 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
588
589 (void)sdref; // Unused
590 (void)ifIndex; // Unused
591 (void)context; // Unused
592 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
593
594 if (errorCode)
595 printf("Error code %d\n", errorCode);
596 else
597 {
598 printtimestamp();
599 printf("%s can be reached at %s:%u (interface %d)", fullname, hosttarget, PortAsNumber, ifIndex);
600 if (flags) printf(" Flags: %X", flags);
601 // Don't show degenerate TXT records containing nothing but a single empty string
602 if (txtLen > 1) { printf("\n"); ShowTXTRecord(txtLen, txtRecord); }
603 printf("\n");
604 }
605
606 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
607 }
608
609 static void myTimerCallBack(void)
610 {
611 DNSServiceErrorType err = kDNSServiceErr_Unknown;
612
613 switch (operation)
614 {
615 case 'A':
616 {
617 switch (addtest)
618 {
619 case 0: printf("Adding Test HINFO record\n");
620 err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_HINFO, sizeof(myhinfoW), &myhinfoW[0], 0);
621 addtest = 1;
622 break;
623 case 1: printf("Updating Test HINFO record\n");
624 err = DNSServiceUpdateRecord(client, record, 0, sizeof(myhinfoX), &myhinfoX[0], 0);
625 addtest = 2;
626 break;
627 case 2: printf("Removing Test HINFO record\n");
628 err = DNSServiceRemoveRecord(client, record, 0);
629 addtest = 0;
630 break;
631 }
632 }
633 break;
634
635 case 'U':
636 {
637 if (updatetest[1] != 'Z') updatetest[1]++;
638 else updatetest[1] = 'A';
639 updatetest[0] = 3 - updatetest[0];
640 updatetest[2] = updatetest[1];
641 printtimestamp();
642 printf("Updating Test TXT record to %c\n", updatetest[1]);
643 err = DNSServiceUpdateRecord(client, NULL, 0, 1+updatetest[0], &updatetest[0], 0);
644 }
645 break;
646
647 case 'N':
648 {
649 printf("Adding big NULL record\n");
650 err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_NULL, sizeof(bigNULL), &bigNULL[0], 0);
651 if (err) printf("Failed: %d\n", err);else printf("Succeeded\n");
652 timeOut = LONG_TIME;
653 #if _DNS_SD_LIBDISPATCH
654 if (timer_source)
655 dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
656 (uint64_t)timeOut * NSEC_PER_SEC, 0);
657 #endif
658 }
659 break;
660 }
661
662 if (err != kDNSServiceErr_NoError)
663 {
664 fprintf(stderr, "DNSService add/update/remove failed %ld\n", (long int)err);
665 stopNow = 1;
666 }
667 }
668
669 static void DNSSD_API reg_reply(DNSServiceRef sdref, const DNSServiceFlags flags, DNSServiceErrorType errorCode,
670 const char *name, const char *regtype, const char *domain, void *context)
671 {
672 (void)sdref; // Unused
673 (void)flags; // Unused
674 (void)context; // Unused
675 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
676
677 printtimestamp();
678 printf("Got a reply for service %s.%s%s: ", name, regtype, domain);
679
680 if (errorCode == kDNSServiceErr_NoError)
681 {
682 if (flags & kDNSServiceFlagsAdd) printf("Name now registered and active\n");
683 else printf("Name registration removed\n");
684 if (operation == 'A' || operation == 'U' || operation == 'N')
685 {
686 timeOut = 5;
687 #if _DNS_SD_LIBDISPATCH
688 if (timer_source)
689 dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
690 (uint64_t)timeOut * NSEC_PER_SEC, 0);
691 #endif
692 }
693 }
694 else if (errorCode == kDNSServiceErr_NameConflict)
695 {
696 printf("Name in use, please choose another\n");
697 exit(-1);
698 }
699 else
700 printf("Error %d\n", errorCode);
701
702 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
703 }
704
705 // Output the wire-format domainname pointed to by rd
706 static int snprintd(char *p, int max, const unsigned char **rd)
707 {
708 const char *const buf = p;
709 const char *const end = p + max;
710 while (**rd) { p += snprintf(p, end-p, "%.*s.", **rd, *rd+1); *rd += 1 + **rd; }
711 *rd += 1; // Advance over the final zero byte
712 return(p-buf);
713 }
714
715 static void DNSSD_API qr_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
716 const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
717 {
718 char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
719 const unsigned char *rd = rdata;
720 const unsigned char *end = (const unsigned char *) rdata + rdlen;
721 char rdb[1000] = "", *p = rdb;
722 int unknowntype = 0;
723
724 (void)sdref; // Unused
725 (void)flags; // Unused
726 (void)ifIndex; // Unused
727 (void)ttl; // Unused
728 (void)context; // Unused
729 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
730
731 if (num_printed++ == 0) printf("Timestamp A/R Flags if %-30s%4s%4s Rdata\n", "Name", "T", "C");
732 printtimestamp();
733
734 if (!errorCode)
735 {
736 switch (rrtype)
737 {
738 case kDNSServiceType_A:
739 snprintf(rdb, sizeof(rdb), "%d.%d.%d.%d", rd[0], rd[1], rd[2], rd[3]);
740 break;
741
742 case kDNSServiceType_NS:
743 case kDNSServiceType_CNAME:
744 case kDNSServiceType_PTR:
745 case kDNSServiceType_DNAME:
746 p += snprintd(p, sizeof(rdb), &rd);
747 break;
748
749 case kDNSServiceType_SOA:
750 p += snprintd(p, rdb + sizeof(rdb) - p, &rd); // mname
751 p += snprintf(p, rdb + sizeof(rdb) - p, " ");
752 p += snprintd(p, rdb + sizeof(rdb) - p, &rd); // rname
753 p += snprintf(p, rdb + sizeof(rdb) - p, " Ser %d Ref %d Ret %d Exp %d Min %d",
754 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]));
755 break;
756
757 case kDNSServiceType_AAAA:
758 snprintf(rdb, sizeof(rdb), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
759 rd[0x0], rd[0x1], rd[0x2], rd[0x3], rd[0x4], rd[0x5], rd[0x6], rd[0x7],
760 rd[0x8], rd[0x9], rd[0xA], rd[0xB], rd[0xC], rd[0xD], rd[0xE], rd[0xF]);
761 break;
762
763 case kDNSServiceType_SRV:
764 p += snprintf(p, rdb + sizeof(rdb) - p, "%d %d %d ", // priority, weight, port
765 ntohs(*(unsigned short*)rd), ntohs(*(unsigned short*)(rd+2)), ntohs(*(unsigned short*)(rd+4)));
766 rd += 6;
767 p += snprintd(p, rdb + sizeof(rdb) - p, &rd); // target host
768 break;
769
770 default: snprintf(rdb, sizeof(rdb), "%d bytes%s", rdlen, rdlen ? ":" : ""); unknowntype = 1; break;
771 }
772 }
773
774 printf("%s%6X%3d %-30s%4d%4d %s", op, flags, ifIndex, fullname, rrtype, rrclass, rdb);
775 if (unknowntype) while (rd < end) printf(" %02X", *rd++);
776 if (errorCode)
777 {
778 if (errorCode == kDNSServiceErr_NoSuchRecord) printf("No Such Record");
779 else if (errorCode == kDNSServiceErr_Timeout)
780 {
781 printf("No Such Record\n");
782 printf("Query Timed Out\n");
783 exit(1);
784 }
785 }
786 printf("\n");
787
788 if (operation == 'C')
789 if (flags & kDNSServiceFlagsAdd)
790 DNSServiceReconfirmRecord(flags, ifIndex, fullname, rrtype, rrclass, rdlen, rdata);
791
792 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
793 }
794
795 #if HAS_NAT_PMP_API
796 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)
797 {
798 (void)sdref; // Unused
799 (void)flags; // Unused
800 (void)context; // Unused
801 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
802
803 if (num_printed++ == 0) printf("Timestamp if %-20s %-15s %-15s %-15s %-6s\n", "External Address", "Protocol", "Internal Port", "External Port", "TTL");
804 printtimestamp();
805 if (errorCode && errorCode != kDNSServiceErr_DoubleNAT) printf("Error code %d\n", errorCode);
806 else
807 {
808 const unsigned char *digits = (const unsigned char *)&publicAddress;
809 char addr[256];
810
811 snprintf(addr, sizeof(addr), "%d.%d.%d.%d", digits[0], digits[1], digits[2], digits[3]);
812 printf("%-4d %-20s %-15d %-15d %-15d %-6d%s\n", ifIndex, addr, protocol, ntohs(privatePort), ntohs(publicPort), ttl, errorCode == kDNSServiceErr_DoubleNAT ? " Double NAT" : "");
813 }
814
815 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
816 }
817 #endif
818
819 #if HAS_ADDRINFO_API
820 static void DNSSD_API addrinfo_reply(DNSServiceRef sdref, DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *hostname, const struct sockaddr *address, uint32_t ttl, void *context)
821 {
822 char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
823 char addr[256] = "";
824 (void) sdref;
825 (void) context;
826 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
827
828 if (num_printed++ == 0) printf("Timestamp A/R Flags if %-25s %-44s %s\n", "Hostname", "Address", "TTL");
829 printtimestamp();
830
831 if (address && address->sa_family == AF_INET)
832 {
833 const unsigned char *b = (const unsigned char *) &((struct sockaddr_in *)address)->sin_addr;
834 snprintf(addr, sizeof(addr), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
835 }
836 else if (address && address->sa_family == AF_INET6)
837 {
838 char if_name[IFNAMSIZ]; // Older Linux distributions don't define IF_NAMESIZE
839 const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)address;
840 const unsigned char *b = (const unsigned char * )&s6->sin6_addr;
841 if (!if_indextoname(s6->sin6_scope_id, if_name))
842 snprintf(if_name, sizeof(if_name), "<%d>", s6->sin6_scope_id);
843 snprintf(addr, sizeof(addr), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X%%%s",
844 b[0x0], b[0x1], b[0x2], b[0x3], b[0x4], b[0x5], b[0x6], b[0x7],
845 b[0x8], b[0x9], b[0xA], b[0xB], b[0xC], b[0xD], b[0xE], b[0xF], if_name);
846 }
847
848 printf("%s%6X%3d %-25s %-44s %d", op, flags, interfaceIndex, hostname, addr, ttl);
849 if (errorCode)
850 {
851 if (errorCode == kDNSServiceErr_NoSuchRecord) printf(" No Such Record");
852 else printf(" Error code %d", errorCode);
853 }
854 printf("\n");
855
856 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
857 }
858 #endif
859
860 //*************************************************************************************************************
861 // The main test function
862
863 static void HandleEvents(void)
864 #if _DNS_SD_LIBDISPATCH
865 {
866 main_queue = dispatch_get_main_queue();
867 if (client) DNSServiceSetDispatchQueue(client, main_queue);
868 if (client_pa) DNSServiceSetDispatchQueue(client_pa, main_queue);
869 if (operation == 'A' || operation == 'U' || operation == 'N')
870 {
871 timer_source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, main_queue);
872 if (timer_source)
873 {
874 // Start the timer "timeout" seconds into the future and repeat it every "timeout" seconds
875 dispatch_source_set_timer(timer_source, dispatch_time(DISPATCH_TIME_NOW, (uint64_t)timeOut * NSEC_PER_SEC),
876 (uint64_t)timeOut * NSEC_PER_SEC, 0);
877 dispatch_source_set_event_handler(timer_source, ^{myTimerCallBack();});
878 dispatch_resume(timer_source);
879 }
880 }
881 dispatch_main();
882 }
883 #else
884 {
885 int dns_sd_fd = client ? DNSServiceRefSockFD(client ) : -1;
886 int dns_sd_fd2 = client_pa ? DNSServiceRefSockFD(client_pa) : -1;
887 int nfds = dns_sd_fd + 1;
888 fd_set readfds;
889 struct timeval tv;
890 int result;
891
892 if (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;
893
894 while (!stopNow)
895 {
896 // 1. Set up the fd_set as usual here.
897 // This example client has no file descriptors of its own,
898 // but a real application would call FD_SET to add them to the set here
899 FD_ZERO(&readfds);
900
901 // 2. Add the fd for our client(s) to the fd_set
902 if (client ) FD_SET(dns_sd_fd, &readfds);
903 if (client_pa) FD_SET(dns_sd_fd2, &readfds);
904
905 // 3. Set up the timeout.
906 tv.tv_sec = timeOut;
907 tv.tv_usec = 0;
908
909 result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
910 if (result > 0)
911 {
912 DNSServiceErrorType err = kDNSServiceErr_NoError;
913 if (client && FD_ISSET(dns_sd_fd, &readfds)) err = DNSServiceProcessResult(client );
914 else if (client_pa && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client_pa);
915 if (err) { fprintf(stderr, "DNSServiceProcessResult returned %d\n", err); stopNow = 1; }
916 }
917 else if (result == 0)
918 myTimerCallBack();
919 else
920 {
921 printf("select() returned %d errno %d %s\n", result, errno, strerror(errno));
922 if (errno != EINTR) stopNow = 1;
923 }
924 }
925 }
926 #endif
927
928 static int getfirstoption(int argc, char **argv, const char *optstr, int *pOptInd)
929 // Return the recognized option in optstr and the option index of the next arg.
930 #if NOT_HAVE_GETOPT
931 {
932 int i;
933 for (i=1; i < argc; i++)
934 {
935 if (argv[i][0] == '-' && &argv[i][1] &&
936 NULL != strchr(optstr, argv[i][1]))
937 {
938 *pOptInd = i + 1;
939 return argv[i][1];
940 }
941 }
942 return -1;
943 }
944 #else
945 {
946 int o = getopt(argc, (char *const *)argv, optstr);
947 *pOptInd = optind;
948 return o;
949 }
950 #endif
951
952 static void DNSSD_API MyRegisterRecordCallback(DNSServiceRef service, DNSRecordRef rec, const DNSServiceFlags flags,
953 DNSServiceErrorType errorCode, void *context)
954 {
955 char *name = (char *)context;
956
957 (void)service; // Unused
958 (void)rec; // Unused
959 (void)flags; // Unused
960 EXIT_IF_LIBDISPATCH_FATAL_ERROR(errorCode);
961
962 printtimestamp();
963 printf("Got a reply for record %s: ", name);
964
965 switch (errorCode)
966 {
967 case kDNSServiceErr_NoError: printf("Name now registered and active\n"); break;
968 case kDNSServiceErr_NameConflict: printf("Name in use, please choose another\n"); exit(-1);
969 default: printf("Error %d\n", errorCode); break;
970 }
971 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
972 // DNSServiceRemoveRecord(service, rec, 0); to test record removal
973
974 #if 0 // To test updating of individual records registered via DNSServiceRegisterRecord
975 if (!errorCode)
976 {
977 int x = 0x11111111;
978 printf("Updating\n");
979 DNSServiceUpdateRecord(service, rec, 0, sizeof(x), &x, 0);
980 }
981 #endif
982
983 if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
984 }
985
986 static void getip(const char *const name, struct sockaddr_storage *result)
987 {
988 struct addrinfo *addrs = NULL;
989 int err = getaddrinfo(name, NULL, NULL, &addrs);
990 if (err) fprintf(stderr, "getaddrinfo error %d for %s", err, name);
991 else memcpy(result, addrs->ai_addr, SA_LEN(addrs->ai_addr));
992 if (addrs) freeaddrinfo(addrs);
993 }
994
995 static DNSServiceErrorType RegisterProxyAddressRecord(DNSServiceRef sdref, const char *host, const char *ip, DNSServiceFlags flags)
996 {
997 // Call getip() after the call DNSServiceCreateConnection().
998 // On the Win32 platform, WinSock must be initialized for getip() to succeed.
999 // Any DNSService* call will initialize WinSock for us, so we make sure
1000 // DNSServiceCreateConnection() is called before getip() is.
1001 struct sockaddr_storage hostaddr;
1002 getip(ip, &hostaddr);
1003 flags |= kDNSServiceFlagsUnique;
1004 if (hostaddr.ss_family == AF_INET)
1005 return(DNSServiceRegisterRecord(sdref, &record, flags, opinterface, host,
1006 kDNSServiceType_A, kDNSServiceClass_IN, 4, &((struct sockaddr_in *)&hostaddr)->sin_addr, 240, MyRegisterRecordCallback, (void*)host));
1007 else if (hostaddr.ss_family == AF_INET6)
1008 return(DNSServiceRegisterRecord(sdref, &record, flags, opinterface, host,
1009 kDNSServiceType_AAAA, kDNSServiceClass_IN, 16, &((struct sockaddr_in6*)&hostaddr)->sin6_addr, 240, MyRegisterRecordCallback, (void*)host));
1010 else return(kDNSServiceErr_BadParam);
1011 }
1012
1013 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
1014 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
1015 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
1016
1017 #define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
1018
1019 static DNSServiceErrorType RegisterService(DNSServiceRef *sdref,
1020 const char *nam, const char *typ, const char *dom, const char *host, const char *port, int argc, char **argv, DNSServiceFlags flags)
1021 {
1022 uint16_t PortAsNumber = atoi(port);
1023 Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
1024 unsigned char txt[2048] = "";
1025 unsigned char *ptr = txt;
1026 int i;
1027
1028 if (nam[0] == '.' && nam[1] == 0) nam = ""; // We allow '.' on the command line as a synonym for empty string
1029 if (dom[0] == '.' && dom[1] == 0) dom = ""; // We allow '.' on the command line as a synonym for empty string
1030
1031 printf("Registering Service %s.%s%s%s", nam[0] ? nam : "<<Default>>", typ, dom[0] ? "." : "", dom);
1032 if (host && *host) printf(" host %s", host);
1033 printf(" port %s", port);
1034
1035 if (argc)
1036 {
1037 for (i = 0; i < argc; i++)
1038 {
1039 const char *p = argv[i];
1040 *ptr = 0;
1041 while (*p && *ptr < 255 && ptr + 1 + *ptr < txt+sizeof(txt))
1042 {
1043 if (p[0] != '\\' || p[1] == 0) { ptr[++*ptr] = *p; p+=1; }
1044 else if (p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3])) { ptr[++*ptr] = HexPair(p+2); p+=4; }
1045 else { ptr[++*ptr] = p[1]; p+=2; }
1046 }
1047 ptr += 1 + *ptr;
1048 }
1049 printf(" TXT");
1050 ShowTXTRecord(ptr-txt, txt);
1051 }
1052 printf("\n");
1053
1054 //flags |= kDNSServiceFlagsAllowRemoteQuery;
1055 //flags |= kDNSServiceFlagsNoAutoRename;
1056
1057 return(DNSServiceRegister(sdref, flags, opinterface, nam, typ, dom, host, registerPort.NotAnInteger, (uint16_t) (ptr-txt), txt, reg_reply, NULL));
1058 }
1059
1060 #define TypeBufferSize 80
1061 static char *gettype(char *buffer, char *typ)
1062 {
1063 if (!typ || !*typ || (typ[0] == '.' && typ[1] == 0)) typ = "_http._tcp";
1064 if (!strchr(typ, '.')) { snprintf(buffer, TypeBufferSize, "%s._tcp", typ); typ = buffer; }
1065 return(typ);
1066 }
1067
1068 int main(int argc, char **argv)
1069 {
1070 DNSServiceErrorType err;
1071 char buffer[TypeBufferSize], *typ, *dom;
1072 int opi;
1073 DNSServiceFlags flags = 0;
1074
1075 // Extract the program name from argv[0], which by convention contains the path to this executable.
1076 // Note that this is just a voluntary convention, not enforced by the kernel --
1077 // the process calling exec() can pass bogus data in argv[0] if it chooses to.
1078 const char *a0 = strrchr(argv[0], kFilePathSep) + 1;
1079 if (a0 == (const char *)1) a0 = argv[0];
1080
1081 #if defined(_WIN32)
1082 HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
1083 #endif
1084
1085 #if TEST_NEW_CLIENTSTUB
1086 printf("Using embedded copy of dnssd_clientstub instead of system library\n");
1087 if (sizeof(argv) == 8) printf("Running in 64-bit mode\n");
1088 #endif
1089
1090 // Test code for TXTRecord functions
1091 //TXTRecordRef txtRecord;
1092 //TXTRecordCreate(&txtRecord, 0, NULL);
1093 //TXTRecordSetValue(&txtRecord, "aaa", 1, "b");
1094 //printf("%d\n", TXTRecordContainsKey(TXTRecordGetLength(&txtRecord), TXTRecordGetBytesPtr(&txtRecord), "Aaa"));
1095
1096 if (argc > 1 && !strcmp(argv[1], "-lo"))
1097 {
1098 argc--;
1099 argv++;
1100 opinterface = kDNSServiceInterfaceIndexLocalOnly;
1101 printf("Using LocalOnly\n");
1102 }
1103
1104 if (argc > 1 && (!strcmp(argv[1], "-p2p") || !strcmp(argv[1], "-P2P")))
1105 {
1106 argc--;
1107 argv++;
1108 opinterface = kDNSServiceInterfaceIndexP2P;
1109 }
1110
1111 if (argc > 1 && !strcasecmp(argv[1], "-includep2p"))
1112 {
1113 argc--;
1114 argv++;
1115 flags |= kDNSServiceFlagsIncludeP2P;
1116 printf("Setting kDNSServiceFlagsIncludeP2P\n");
1117 }
1118
1119 if (argc > 1 && !strcasecmp(argv[1], "-includeAWDL"))
1120 {
1121 argc--;
1122 argv++;
1123 flags |= kDNSServiceFlagsIncludeAWDL;
1124 printf("Setting kDNSServiceFlagsIncludeAWDL\n");
1125 }
1126
1127 if (argc > 1 && !strcasecmp(argv[1], "-tc"))
1128 {
1129 argc--;
1130 argv++;
1131 flags |= kDNSServiceFlagsBackgroundTrafficClass;
1132 printf("Setting kDNSServiceFlagsBackgroundTrafficClass\n");
1133 }
1134
1135 if (argc > 2 && !strcmp(argv[1], "-i"))
1136 {
1137 opinterface = if_nametoindex(argv[2]);
1138 if (!opinterface) opinterface = atoi(argv[2]);
1139 if (!opinterface) { fprintf(stderr, "Unknown interface %s\n", argv[2]); goto Fail; }
1140 argc -= 2;
1141 argv += 2;
1142 }
1143
1144 if (argc < 2) goto Fail; // Minimum command line is the command name and one argument
1145 operation = getfirstoption(argc, argv, "EFBZLlRPQqtCAUNTMISVHh"
1146 #if HAS_NAT_PMP_API
1147 "X"
1148 #endif
1149 #if HAS_ADDRINFO_API
1150 "G"
1151 #endif
1152 , &opi);
1153 if (operation == -1) goto Fail;
1154
1155 if (opinterface) printf("Using interface %d\n", opinterface);
1156
1157 switch (operation)
1158 {
1159 case 'E': printf("Looking for recommended registration domains:\n");
1160 err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsRegistrationDomains, opinterface, enum_reply, NULL);
1161 break;
1162
1163 case 'F': printf("Looking for recommended browsing domains:\n");
1164 err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsBrowseDomains, opinterface, enum_reply, NULL);
1165 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
1166 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
1167 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
1168 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
1169 break;
1170
1171 case 'B': typ = (argc < opi+1) ? "" : argv[opi+0];
1172 dom = (argc < opi+2) ? "" : argv[opi+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
1173 typ = gettype(buffer, typ);
1174 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
1175 printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1176 err = DNSServiceBrowse(&client, flags, opinterface, typ, dom, browse_reply, NULL);
1177 break;
1178
1179 case 'Z': typ = (argc < opi+1) ? "" : argv[opi+0];
1180 dom = (argc < opi+2) ? "" : argv[opi+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
1181 typ = gettype(buffer, typ);
1182 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
1183 printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1184 err = DNSServiceCreateConnection(&client);
1185 sc1 = client;
1186 err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, typ, dom, zonedata_browse, NULL);
1187 break;
1188
1189 case 'l':
1190 case 'L': {
1191 if (argc < opi+2) goto Fail;
1192 typ = (argc < opi+2) ? "" : argv[opi+1];
1193 dom = (argc < opi+3) ? "local" : argv[opi+2];
1194 typ = gettype(buffer, typ);
1195 if (dom[0] == '.' && dom[1] == 0) dom = "local"; // We allow '.' on the command line as a synonym for "local"
1196 printf("Lookup %s.%s.%s\n", argv[opi+0], typ, dom);
1197 if (operation == 'l') flags |= kDNSServiceFlagsWakeOnResolve;
1198 err = DNSServiceResolve(&client, flags, opinterface, argv[opi+0], typ, dom, resolve_reply, NULL);
1199 break;
1200 }
1201
1202 case 'R': if (argc < opi+4) goto Fail;
1203 typ = (argc < opi+2) ? "" : argv[opi+1];
1204 dom = (argc < opi+3) ? "" : argv[opi+2];
1205 typ = gettype(buffer, typ);
1206 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
1207 err = RegisterService(&client, argv[opi+0], typ, dom, NULL, argv[opi+3], argc-(opi+4), argv+(opi+4), flags);
1208 break;
1209
1210 case 'P': if (argc < opi+6) goto Fail;
1211 err = DNSServiceCreateConnection(&client_pa);
1212 if (err) { fprintf(stderr, "DNSServiceCreateConnection returned %d\n", err); return(err); }
1213 err = RegisterProxyAddressRecord(client_pa, argv[opi+4], argv[opi+5], flags);
1214 if (err) break;
1215 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);
1216 break;
1217
1218 case 't':
1219 case 'q':
1220 case 'Q':
1221 case 'C': {
1222 uint16_t rrtype, rrclass;
1223 flags |= kDNSServiceFlagsReturnIntermediates;
1224 if (operation == 'q') flags |= kDNSServiceFlagsSuppressUnusable;
1225 if (operation == 't') flags |= (kDNSServiceFlagsSuppressUnusable | kDNSServiceFlagsTimeout);
1226 if (argc < opi+1) goto Fail;
1227 rrtype = (argc <= opi+1) ? kDNSServiceType_A : GetRRType(argv[opi+1]);
1228 rrclass = (argc <= opi+2) ? kDNSServiceClass_IN : atoi(argv[opi+2]);
1229 if (rrtype == kDNSServiceType_TXT || rrtype == kDNSServiceType_PTR) flags |= kDNSServiceFlagsLongLivedQuery;
1230 err = DNSServiceQueryRecord(&client, flags, opinterface, argv[opi+0], rrtype, rrclass, qr_reply, NULL);
1231 break;
1232 }
1233
1234 case 'A':
1235 case 'U':
1236 case 'N': {
1237 Opaque16 registerPort = { { 0x12, 0x34 } };
1238 static const char TXT[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1239 printf("Registering Service Test._testupdate._tcp.local.\n");
1240 err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testupdate._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT)-1, TXT, reg_reply, NULL);
1241 break;
1242 }
1243
1244 case 'T': {
1245 Opaque16 registerPort = { { 0x23, 0x45 } };
1246 char TXT[1024];
1247 unsigned int i;
1248 for (i=0; i<sizeof(TXT); i++)
1249 if ((i & 0x1F) == 0) TXT[i] = 0x1F;else TXT[i] = 'A' + (i >> 5);
1250 printf("Registering Service Test._testlargetxt._tcp.local.\n");
1251 err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testlargetxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT), TXT, reg_reply, NULL);
1252 break;
1253 }
1254
1255 case 'M': {
1256 pid_t pid = getpid();
1257 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1258 static const char TXT1[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1259 static const char TXT2[] = "\xD" "Fourth String" "\xC" "Fifth String" "\xC" "Sixth String";
1260 printf("Registering Service Test._testdualtxt._tcp.local.\n");
1261 err = DNSServiceRegister(&client, flags, opinterface, "Test", "_testdualtxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT1)-1, TXT1, reg_reply, NULL);
1262 if (!err) err = DNSServiceAddRecord(client, &record, flags, kDNSServiceType_TXT, sizeof(TXT2)-1, TXT2, 0);
1263 break;
1264 }
1265
1266 case 'I': {
1267 pid_t pid = getpid();
1268 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1269 static const char TXT[] = "\x09" "Test Data";
1270 printf("Registering Service Test._testtxt._tcp.local.\n");
1271 err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testtxt._tcp.", "", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1272 if (!err) err = DNSServiceUpdateRecord(client, NULL, 0, sizeof(TXT)-1, TXT, 0);
1273 break;
1274 }
1275
1276 #if HAS_NAT_PMP_API
1277 case 'X': {
1278 if (argc == opi) // If no arguments, just fetch IP address
1279 err = DNSServiceNATPortMappingCreate(&client, 0, 0, 0, 0, 0, 0, port_mapping_create_reply, NULL);
1280 else if (argc >= opi+2 && atoi(argv[opi+0]) == 0)
1281 {
1282 DNSServiceProtocol prot = GetProtocol(argv[opi+0]); // Must specify TCP or UDP
1283 uint16_t IntPortAsNumber = atoi(argv[opi+1]); // Must specify internal port
1284 uint16_t ExtPortAsNumber = (argc < opi+3) ? 0 : atoi(argv[opi+2]); // Optional desired external port
1285 uint32_t ttl = (argc < opi+4) ? 0 : atoi(argv[opi+3]); // Optional desired lease lifetime
1286 Opaque16 intp = { { IntPortAsNumber >> 8, IntPortAsNumber & 0xFF } };
1287 Opaque16 extp = { { ExtPortAsNumber >> 8, ExtPortAsNumber & 0xFF } };
1288 err = DNSServiceNATPortMappingCreate(&client, 0, 0, prot, intp.NotAnInteger, extp.NotAnInteger, ttl, port_mapping_create_reply, NULL);
1289 }
1290 else goto Fail;
1291 break;
1292 }
1293 #endif
1294
1295 #if HAS_ADDRINFO_API
1296 case 'G': {
1297 flags |= kDNSServiceFlagsReturnIntermediates;
1298 if (argc != opi+2) goto Fail;
1299 else err = DNSServiceGetAddrInfo(&client, flags, opinterface, GetProtocol(argv[opi+0]), argv[opi+1], addrinfo_reply, NULL);
1300 break;
1301 }
1302 #endif
1303
1304 case 'S': {
1305 Opaque16 registerPort = { { 0x23, 0x45 } }; // 9029 decimal
1306 unsigned char txtrec[16] = "\xF" "/path=test.html";
1307 DNSRecordRef rec;
1308 unsigned char nulrec[4] = "1234";
1309
1310 err = DNSServiceCreateConnection(&client);
1311 if (err) { fprintf(stderr, "DNSServiceCreateConnection failed %ld\n", (long int)err); return (-1); }
1312
1313 sc1 = client;
1314 err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, "_http._tcp", "", browse_reply, NULL);
1315 if (err) { fprintf(stderr, "DNSServiceBrowse _http._tcp failed %ld\n", (long int)err); return (-1); }
1316
1317 sc2 = client;
1318 err = DNSServiceBrowse(&sc2, kDNSServiceFlagsShareConnection, opinterface, "_ftp._tcp", "", browse_reply, NULL);
1319 if (err) { fprintf(stderr, "DNSServiceBrowse _ftp._tcp failed %ld\n", (long int)err); return (-1); }
1320
1321 sc3 = client;
1322 err = DNSServiceRegister(&sc3, kDNSServiceFlagsShareConnection, opinterface, "kDNSServiceFlagsShareConnection",
1323 "_http._tcp", "local", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1324 if (err) { fprintf(stderr, "SharedConnection DNSServiceRegister failed %ld\n", (long int)err); return (-1); }
1325
1326 err = DNSServiceUpdateRecord(sc3, NULL, 0, sizeof(txtrec), txtrec, 0);
1327 if (err) { fprintf(stderr, "SharedConnection DNSServiceUpdateRecord failed %ld\n", (long int)err); return (-1); }
1328
1329 err = DNSServiceAddRecord(sc3, &rec, 0, kDNSServiceType_NULL, sizeof(nulrec), nulrec, 0);
1330 if (err) { fprintf(stderr, "SharedConnection DNSServiceAddRecord failed %ld\n", (long int)err); return (-1); }
1331
1332 err = DNSServiceRemoveRecord(sc3, rec, 0);
1333 if (err) { fprintf(stderr, "SharedConnection DNSServiceRemoveRecord failed %ld\n", (long int)err); return (-1); }
1334
1335 break;
1336 }
1337
1338 case 'V': {
1339 uint32_t v;
1340 uint32_t size = sizeof(v);
1341 err = DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion, &v, &size);
1342 if (err) fprintf(stderr, "DNSServiceGetProperty failed %ld\n", (long int)err);
1343 else printf("Currently running daemon (system service) is version %d.%d\n", v / 10000, v / 100 % 100);
1344 exit(0);
1345 }
1346
1347 case 'H': goto Fail;
1348
1349 default: goto Fail;
1350 }
1351
1352 if (!client || err != kDNSServiceErr_NoError) { fprintf(stderr, "DNSService call failed %ld\n", (long int)err); return (-1); }
1353 printtimestamp();
1354 printf("...STARTING...\n");
1355 HandleEvents();
1356
1357 // Be sure to deallocate the DNSServiceRef when you're finished
1358 if (client ) DNSServiceRefDeallocate(client );
1359 if (client_pa) DNSServiceRefDeallocate(client_pa);
1360 return 0;
1361
1362 Fail:
1363 if (operation == 'H') print_usage(a0,1);
1364 else print_usage(a0,0);
1365 return 0;
1366
1367 }
1368
1369 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
1370 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
1371 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
1372 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) # s
1373 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
1374
1375 // NOT static -- otherwise the compiler may optimize it out
1376 // The "@(#) " pattern is a special prefix the "what" command looks for
1377 const char VersionString_SCCS[] = "@(#) dns-sd " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
1378
1379 #if _BUILDING_XCODE_PROJECT_
1380 // If the process crashes, then this string will be magically included in the automatically-generated crash log
1381 const char *__crashreporter_info__ = VersionString_SCCS + 5;
1382 asm (".desc ___crashreporter_info__, 0x10");
1383 #endif