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 * Formatting notes:
41 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
42 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
43 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
44 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
45 * therefore common sense dictates that if they are part of a compound statement then they
46 * should be indented to the same level as everything else in that compound statement.
47 * Indenting curly braces at the same level as the "if" implies that curly braces are
48 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
49 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
50 * understand why variable y is not of type "char*" just proves the point that poor code
51 * layout leads people to unfortunate misunderstandings about how the C language really works.)
52
53To build this tool, copy and paste the following into a command line:
54
55OS X:
56gcc dns-sd.c -o dns-sd
57
58POSIX systems:
59gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
60
61Windows:
62cl dns-sd.c -I../mDNSShared -DNOT_HAVE_GETOPT ws2_32.lib ..\mDNSWindows\DLL\Release\dnssd.lib
63(may require that you run a Visual Studio script such as vsvars32.bat first)
64*/
65
66// For testing changes to dnssd_clientstub.c, uncomment this line and the code will be compiled
67// with an embedded copy of the client stub instead of linking the system library version at runtime.
68// This also useful to work around link errors when you're working on an older version of Mac OS X,
69// and trying to build a newer version of the "dns-sd" command which uses new API entry points that
70// aren't in the system's /usr/lib/libSystem.dylib.
71//#define TEST_NEW_CLIENTSTUB 1
72
73#include <ctype.h>
74#include <stdio.h>			// For stdout, stderr
75#include <stdlib.h>			// For exit()
76#include <string.h>			// For strlen(), strcpy()
77#include <errno.h>			// For errno, EINTR
78#include <time.h>
79#include <sys/types.h>		// For u_char
80
81#ifdef _WIN32
82	#include <winsock2.h>
83	#include <ws2tcpip.h>
84	#include <Iphlpapi.h>
85	#include <process.h>
86	typedef int        pid_t;
87	#define getpid     _getpid
88	#define strcasecmp _stricmp
89	#define snprintf   _snprintf
90	static const char kFilePathSep = '\\';
91	#ifndef HeapEnableTerminationOnCorruption
92	#     define HeapEnableTerminationOnCorruption (HEAP_INFORMATION_CLASS)1
93	#endif
94	#if !defined(IFNAMSIZ)
95	 #define IFNAMSIZ 16
96    #endif
97	#define if_nametoindex if_nametoindex_win
98	#define if_indextoname if_indextoname_win
99
100	typedef PCHAR (WINAPI * if_indextoname_funcptr_t)(ULONG index, PCHAR name);
101	typedef ULONG (WINAPI * if_nametoindex_funcptr_t)(PCSTR name);
102
103	unsigned if_nametoindex_win(const char *ifname)
104		{
105		HMODULE library;
106		unsigned index = 0;
107
108		// Try and load the IP helper library dll
109		if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL )
110			{
111			if_nametoindex_funcptr_t if_nametoindex_funcptr;
112
113			// On Vista and above there is a Posix like implementation of if_nametoindex
114			if ((if_nametoindex_funcptr = (if_nametoindex_funcptr_t) GetProcAddress(library, "if_nametoindex")) != NULL )
115				{
116				index = if_nametoindex_funcptr(ifname);
117				}
118
119			FreeLibrary(library);
120			}
121
122		return index;
123		}
124
125	char * if_indextoname_win( unsigned ifindex, char *ifname)
126		{
127		HMODULE library;
128		char * name = NULL;
129
130		// Try and load the IP helper library dll
131		if ((library = LoadLibrary(TEXT("Iphlpapi")) ) != NULL )
132			{
133			if_indextoname_funcptr_t if_indextoname_funcptr;
134
135			// On Vista and above there is a Posix like implementation of if_indextoname
136			if ((if_indextoname_funcptr = (if_indextoname_funcptr_t) GetProcAddress(library, "if_indextoname")) != NULL )
137				{
138				name = if_indextoname_funcptr(ifindex, ifname);
139				}
140
141			FreeLibrary(library);
142			}
143
144		return name;
145		}
146
147#else
148	#include <unistd.h>			// For getopt() and optind
149	#include <netdb.h>			// For getaddrinfo()
150	#include <sys/time.h>		// For struct timeval
151	#include <sys/socket.h>		// For AF_INET
152	#include <netinet/in.h>		// For struct sockaddr_in()
153	#include <arpa/inet.h>		// For inet_addr()
154	#include <net/if.h>			// For if_nametoindex()
155	static const char kFilePathSep = '/';
156#endif
157
158#if (TEST_NEW_CLIENTSTUB && !defined(__APPLE_API_PRIVATE))
159#define __APPLE_API_PRIVATE 1
160#endif
161
162#include "dns_sd.h"
163
164#include "ClientCommon.h"
165
166#if TEST_NEW_CLIENTSTUB
167#include "../mDNSShared/dnssd_ipc.c"
168#include "../mDNSShared/dnssd_clientlib.c"
169#include "../mDNSShared/dnssd_clientstub.c"
170#endif
171
172// 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)
173#if _DNS_SD_H+0 >= 116
174#define HAS_NAT_PMP_API 1
175#define HAS_ADDRINFO_API 1
176#else
177#define kDNSServiceFlagsReturnIntermediates 0
178#endif
179
180//*************************************************************************************************************
181// Globals
182
183typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
184
185static int operation;
186static uint32_t opinterface = kDNSServiceInterfaceIndexAny;
187static DNSServiceRef client    = NULL;
188static DNSServiceRef client_pa = NULL;	// DNSServiceRef for RegisterProxyAddressRecord
189static DNSServiceRef sc1, sc2, sc3;		// DNSServiceRefs for kDNSServiceFlagsShareConnection testing
190
191static int num_printed;
192static char addtest = 0;
193static DNSRecordRef record = NULL;
194static char myhinfoW[14] = "\002PC\012Windows XP";
195static char myhinfoX[ 9] = "\003Mac\004OS X";
196static char updatetest[3] = "\002AA";
197static char bigNULL[8192];	// 8K is maximum rdata we support
198
199// Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
200#define LONG_TIME 100000000
201
202static volatile int stopNow = 0;
203static volatile int timeOut = LONG_TIME;
204
205//*************************************************************************************************************
206// Supporting Utility Functions
207
208static uint16_t GetRRType(const char *s)
209	{
210	if      (!strcasecmp(s, "A"       )) return(kDNSServiceType_A);
211	else if (!strcasecmp(s, "NS"      )) return(kDNSServiceType_NS);
212	else if (!strcasecmp(s, "MD"      )) return(kDNSServiceType_MD);
213	else if (!strcasecmp(s, "MF"      )) return(kDNSServiceType_MF);
214	else if (!strcasecmp(s, "CNAME"   )) return(kDNSServiceType_CNAME);
215	else if (!strcasecmp(s, "SOA"     )) return(kDNSServiceType_SOA);
216	else if (!strcasecmp(s, "MB"      )) return(kDNSServiceType_MB);
217	else if (!strcasecmp(s, "MG"      )) return(kDNSServiceType_MG);
218	else if (!strcasecmp(s, "MR"      )) return(kDNSServiceType_MR);
219	else if (!strcasecmp(s, "NULL"    )) return(kDNSServiceType_NULL);
220	else if (!strcasecmp(s, "WKS"     )) return(kDNSServiceType_WKS);
221	else if (!strcasecmp(s, "PTR"     )) return(kDNSServiceType_PTR);
222	else if (!strcasecmp(s, "HINFO"   )) return(kDNSServiceType_HINFO);
223	else if (!strcasecmp(s, "MINFO"   )) return(kDNSServiceType_MINFO);
224	else if (!strcasecmp(s, "MX"      )) return(kDNSServiceType_MX);
225	else if (!strcasecmp(s, "TXT"     )) return(kDNSServiceType_TXT);
226	else if (!strcasecmp(s, "RP"      )) return(kDNSServiceType_RP);
227	else if (!strcasecmp(s, "AFSDB"   )) return(kDNSServiceType_AFSDB);
228	else if (!strcasecmp(s, "X25"     )) return(kDNSServiceType_X25);
229	else if (!strcasecmp(s, "ISDN"    )) return(kDNSServiceType_ISDN);
230	else if (!strcasecmp(s, "RT"      )) return(kDNSServiceType_RT);
231	else if (!strcasecmp(s, "NSAP"    )) return(kDNSServiceType_NSAP);
232	else if (!strcasecmp(s, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR);
233	else if (!strcasecmp(s, "SIG"     )) return(kDNSServiceType_SIG);
234	else if (!strcasecmp(s, "KEY"     )) return(kDNSServiceType_KEY);
235	else if (!strcasecmp(s, "PX"      )) return(kDNSServiceType_PX);
236	else if (!strcasecmp(s, "GPOS"    )) return(kDNSServiceType_GPOS);
237	else if (!strcasecmp(s, "AAAA"    )) return(kDNSServiceType_AAAA);
238	else if (!strcasecmp(s, "LOC"     )) return(kDNSServiceType_LOC);
239	else if (!strcasecmp(s, "NXT"     )) return(kDNSServiceType_NXT);
240	else if (!strcasecmp(s, "EID"     )) return(kDNSServiceType_EID);
241	else if (!strcasecmp(s, "NIMLOC"  )) return(kDNSServiceType_NIMLOC);
242	else if (!strcasecmp(s, "SRV"     )) return(kDNSServiceType_SRV);
243	else if (!strcasecmp(s, "ATMA"    )) return(kDNSServiceType_ATMA);
244	else if (!strcasecmp(s, "NAPTR"   )) return(kDNSServiceType_NAPTR);
245	else if (!strcasecmp(s, "KX"      )) return(kDNSServiceType_KX);
246	else if (!strcasecmp(s, "CERT"    )) return(kDNSServiceType_CERT);
247	else if (!strcasecmp(s, "A6"      )) return(kDNSServiceType_A6);
248	else if (!strcasecmp(s, "DNAME"   )) return(kDNSServiceType_DNAME);
249	else if (!strcasecmp(s, "SINK"    )) return(kDNSServiceType_SINK);
250	else if (!strcasecmp(s, "OPT"     )) return(kDNSServiceType_OPT);
251	else if (!strcasecmp(s, "TKEY"    )) return(kDNSServiceType_TKEY);
252	else if (!strcasecmp(s, "TSIG"    )) return(kDNSServiceType_TSIG);
253	else if (!strcasecmp(s, "IXFR"    )) return(kDNSServiceType_IXFR);
254	else if (!strcasecmp(s, "AXFR"    )) return(kDNSServiceType_AXFR);
255	else if (!strcasecmp(s, "MAILB"   )) return(kDNSServiceType_MAILB);
256	else if (!strcasecmp(s, "MAILA"   )) return(kDNSServiceType_MAILA);
257	else if (!strcasecmp(s, "ANY"     )) return(kDNSServiceType_ANY);
258	else                                 return(atoi(s));
259	}
260
261#if HAS_NAT_PMP_API | HAS_ADDRINFO_API
262static DNSServiceProtocol GetProtocol(const char *s)
263	{
264	if      (!strcasecmp(s, "v4"      )) return(kDNSServiceProtocol_IPv4);
265	else if (!strcasecmp(s, "v6"      )) return(kDNSServiceProtocol_IPv6);
266	else if (!strcasecmp(s, "v4v6"    )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
267	else if (!strcasecmp(s, "v6v4"    )) return(kDNSServiceProtocol_IPv4 | kDNSServiceProtocol_IPv6);
268	else if (!strcasecmp(s, "udp"     )) return(kDNSServiceProtocol_UDP);
269	else if (!strcasecmp(s, "tcp"     )) return(kDNSServiceProtocol_TCP);
270	else if (!strcasecmp(s, "udptcp"  )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
271	else if (!strcasecmp(s, "tcpudp"  )) return(kDNSServiceProtocol_UDP | kDNSServiceProtocol_TCP);
272	else                                 return(atoi(s));
273	}
274#endif
275
276//*************************************************************************************************************
277// Sample callback functions for each of the operation types
278
279static void printtimestamp(void)
280	{
281	struct tm tm;
282	int ms;
283#ifdef _WIN32
284	SYSTEMTIME sysTime;
285	time_t uct = time(NULL);
286	tm = *localtime(&uct);
287	GetLocalTime(&sysTime);
288	ms = sysTime.wMilliseconds;
289#else
290	struct timeval tv;
291	gettimeofday(&tv, NULL);
292	localtime_r((time_t*)&tv.tv_sec, &tm);
293	ms = tv.tv_usec/1000;
294#endif
295	printf("%2d:%02d:%02d.%03d  ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms);
296	}
297
298#define DomainMsg(X) (((X) & kDNSServiceFlagsDefault) ? "(Default)" : \
299                      ((X) & kDNSServiceFlagsAdd)     ? "Added"     : "Removed")
300
301#define MAX_LABELS 128
302
303static void DNSSD_API enum_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex,
304	DNSServiceErrorType errorCode, const char *replyDomain, void *context)
305	{
306	DNSServiceFlags partialflags = flags & ~(kDNSServiceFlagsMoreComing | kDNSServiceFlagsAdd | kDNSServiceFlagsDefault);
307	int labels = 0, depth = 0, i, initial = 0;
308	char text[64];
309	const char *label[MAX_LABELS];
310
311	(void)sdref;        // Unused
312	(void)ifIndex;      // Unused
313	(void)context;      // Unused
314
315	// 1. Print the header
316	if (num_printed++ == 0) printf("Timestamp     Recommended %s domain\n", operation == 'E' ? "Registration" : "Browsing");
317	printtimestamp();
318	if (errorCode)
319		printf("Error code %d\n", errorCode);
320	else if (!*replyDomain)
321		printf("Error: No reply domain\n");
322	else
323		{
324		printf("%-10s", DomainMsg(flags));
325		printf("%-8s", (flags & kDNSServiceFlagsMoreComing) ? "(More)" : "");
326		if (partialflags) printf("Flags: %4X  ", partialflags);
327		else printf("             ");
328
329		// 2. Count the labels
330		while (replyDomain && *replyDomain && labels < MAX_LABELS)
331			{
332			label[labels++] = replyDomain;
333			replyDomain = GetNextLabel(replyDomain, text);
334			}
335
336		// 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
337		if      (labels >= 3 && replyDomain - label[labels-1] <= 3 && label[labels-1] - label[labels-2] <= 4) initial = 3;
338		else if (labels >= 2 && replyDomain - label[labels-1] <= 4) initial = 2;
339		else initial = 1;
340		labels -= initial;
341
342		// 4. Print the initial one-, two- or three-label clump
343		for (i=0; i<initial; i++)
344			{
345			GetNextLabel(label[labels+i], text);
346			if (i>0) printf(".");
347			printf("%s", text);
348			}
349		printf("\n");
350
351		// 5. Print the remainder of the hierarchy
352		for (depth=0; depth<labels; depth++)
353			{
354			printf("                                             ");
355			for (i=0; i<=depth; i++) printf("- ");
356			GetNextLabel(label[labels-1-depth], text);
357			printf("> %s\n", text);
358			}
359		}
360
361	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
362	}
363
364static int CopyLabels(char *dst, const char *lim, const char **srcp, int labels)
365	{
366	const char *src = *srcp;
367	while (*src != '.' || --labels > 0)
368		{
369		if (*src == '\\') *dst++ = *src++;	// Make sure "\." doesn't confuse us
370		if (!*src || dst >= lim) return -1;
371		*dst++ = *src++;
372		if (!*src || dst >= lim) return -1;
373		}
374	*dst++ = 0;
375	*srcp = src + 1;	// skip over final dot
376	return 0;
377	}
378
379static void DNSSD_API zonedata_resolve(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
380	const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txt, void *context)
381	{
382	union { uint16_t s; u_char b[2]; } port = { opaqueport };
383	uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
384
385	const char *p = fullname;
386	char n[kDNSServiceMaxDomainName];
387	char t[kDNSServiceMaxDomainName];
388
389	const unsigned char *max = txt + txtLen;
390
391	(void)sdref;        // Unused
392	(void)ifIndex;      // Unused
393	(void)context;      // Unused
394
395	//if (!(flags & kDNSServiceFlagsAdd)) return;
396	if (errorCode) { printf("Error code %d\n", errorCode); return; }
397
398	if (CopyLabels(n, n + kDNSServiceMaxDomainName, &p, 3)) return;		// Fetch name+type
399	p = fullname;
400	if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 1)) return;		// Skip first label
401	if (CopyLabels(t, t + kDNSServiceMaxDomainName, &p, 2)) return;		// Fetch next two labels (service type)
402
403	if (num_printed++ == 0)
404		{
405		printf("\n");
406		printf("; To direct clients to browse a different domain, substitute that domain in place of '@'\n");
407		printf("%-47s PTR     %s\n", "lb._dns-sd._udp", "@");
408		printf("\n");
409		printf("; In the list of services below, the SRV records will typically reference dot-local Multicast DNS names.\n");
410		printf("; When transferring this zone file data to your unicast DNS server, you'll need to replace those dot-local\n");
411		printf("; names with the correct fully-qualified (unicast) domain name of the target host offering the service.\n");
412		}
413
414	printf("\n");
415	printf("%-47s PTR     %s\n", t, n);
416	printf("%-47s SRV     0 0 %d %s ; Replace with unicast FQDN of target host\n", n, PortAsNumber, hosttarget);
417	printf("%-47s TXT    ", n);
418
419	while (txt < max)
420		{
421		const unsigned char *const end = txt + 1 + txt[0];
422		txt++;		// Skip over length byte
423		printf(" \"");
424		while (txt<end)
425			{
426			if (*txt == '\\' || *txt == '\"') printf("\\");
427			printf("%c", *txt++);
428			}
429		printf("\"");
430		}
431	printf("\n");
432
433	DNSServiceRefDeallocate(sdref);
434	free(context);
435
436	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
437	}
438
439static void DNSSD_API zonedata_browse(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
440	const char *replyName, const char *replyType, const char *replyDomain, void *context)
441	{
442	DNSServiceRef *newref;
443
444	(void)sdref;        // Unused
445	(void)context;      // Unused
446
447	if (!(flags & kDNSServiceFlagsAdd)) return;
448	if (errorCode) { printf("Error code %d\n", errorCode); return; }
449
450	newref = malloc(sizeof(*newref));
451	*newref = client;
452	DNSServiceResolve(newref, kDNSServiceFlagsShareConnection, ifIndex, replyName, replyType, replyDomain, zonedata_resolve, newref);
453	}
454
455static void DNSSD_API browse_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
456	const char *replyName, const char *replyType, const char *replyDomain, void *context)
457	{
458	char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
459	(void)sdref;        // Unused
460	(void)context;      // Unused
461	if (num_printed++ == 0) printf("Timestamp     A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
462	printtimestamp();
463	if (errorCode) printf("Error code %d\n", errorCode);
464	else printf("%s%6X%3d %-25s %-25s %s\n", op, flags, ifIndex, replyDomain, replyType, replyName);
465	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
466
467	// To test selective cancellation of operations of shared sockets,
468	// cancel the current operation when we've got a multiple of five results
469	//if (operation == 'S' && num_printed % 5 == 0) DNSServiceRefDeallocate(sdref);
470	}
471
472static void ShowTXTRecord(uint16_t txtLen, const unsigned char *txtRecord)
473	{
474	const unsigned char *ptr = txtRecord;
475	const unsigned char *max = txtRecord + txtLen;
476	while (ptr < max)
477		{
478		const unsigned char *const end = ptr + 1 + ptr[0];
479		if (end > max) { printf("<< invalid data >>"); break; }
480		if (++ptr < end) printf(" ");   // As long as string is non-empty, begin with a space
481		while (ptr<end)
482			{
483			// We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
484			// However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
485			// shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
486			// Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
487			// meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
488			// The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
489			// escapes to encode spaces and all other known shell metacharacters.
490			// (If we've missed any known shell metacharacters, please let us know.)
491			// In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
492			// Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
493			// the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
494			// The C compiler eats half of them, resulting in four appearing in the output.
495			// The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
496			// The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
497			if (strchr(" &;`'\"|*?~<>^()[]{}$", *ptr)) printf("\\");
498			if      (*ptr == '\\') printf("\\\\\\\\");
499			else if (*ptr >= ' ' ) printf("%c",        *ptr);
500			else                   printf("\\\\x%02X", *ptr);
501			ptr++;
502			}
503		}
504	}
505
506static void DNSSD_API resolve_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
507	const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txtRecord, void *context)
508	{
509	union { uint16_t s; u_char b[2]; } port = { opaqueport };
510	uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
511
512	(void)sdref;        // Unused
513	(void)ifIndex;      // Unused
514	(void)context;      // Unused
515
516	printtimestamp();
517	if (errorCode) printf("Error code %d\n", errorCode);
518	else
519		{
520		printf("%s can be reached at %s:%u (interface %d)", fullname, hosttarget, PortAsNumber, ifIndex);
521		if (flags) printf(" Flags: %X", flags);
522		// Don't show degenerate TXT records containing nothing but a single empty string
523		if (txtLen > 1) { printf("\n"); ShowTXTRecord(txtLen, txtRecord); }
524		printf("\n");
525		}
526
527	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
528	}
529
530static void myTimerCallBack(void)
531	{
532	DNSServiceErrorType err = kDNSServiceErr_Unknown;
533
534	switch (operation)
535		{
536		case 'A':
537			{
538			switch (addtest)
539				{
540				case 0: printf("Adding Test HINFO record\n");
541						err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_HINFO, sizeof(myhinfoW), &myhinfoW[0], 0);
542						addtest = 1;
543						break;
544				case 1: printf("Updating Test HINFO record\n");
545						err = DNSServiceUpdateRecord(client, record, 0, sizeof(myhinfoX), &myhinfoX[0], 0);
546						addtest = 2;
547						break;
548				case 2: printf("Removing Test HINFO record\n");
549						err = DNSServiceRemoveRecord(client, record, 0);
550						addtest = 0;
551						break;
552				}
553			}
554			break;
555
556		case 'U':
557			{
558			if (updatetest[1] != 'Z') updatetest[1]++;
559			else                      updatetest[1] = 'A';
560			updatetest[0] = 3 - updatetest[0];
561			updatetest[2] = updatetest[1];
562			printtimestamp();
563			printf("Updating Test TXT record to %c\n", updatetest[1]);
564			err = DNSServiceUpdateRecord(client, NULL, 0, 1+updatetest[0], &updatetest[0], 0);
565			}
566			break;
567
568		case 'N':
569			{
570			printf("Adding big NULL record\n");
571			err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_NULL, sizeof(bigNULL), &bigNULL[0], 0);
572			if (err) printf("Failed: %d\n", err); else printf("Succeeded\n");
573			timeOut = LONG_TIME;
574			}
575			break;
576		}
577
578	if (err != kDNSServiceErr_NoError)
579		{
580		fprintf(stderr, "DNSService add/update/remove failed %ld\n", (long int)err);
581		stopNow = 1;
582		}
583	}
584
585static void DNSSD_API reg_reply(DNSServiceRef sdref, const DNSServiceFlags flags, DNSServiceErrorType errorCode,
586	const char *name, const char *regtype, const char *domain, void *context)
587	{
588	(void)sdref;    // Unused
589	(void)flags;    // Unused
590	(void)context;  // Unused
591
592	printtimestamp();
593	printf("Got a reply for service %s.%s%s: ", name, regtype, domain);
594
595	if (errorCode == kDNSServiceErr_NoError)
596		{
597		if (flags & kDNSServiceFlagsAdd) printf("Name now registered and active\n");
598		else printf("Name registration removed\n");
599		if (operation == 'A' || operation == 'U' || operation == 'N') timeOut = 5;
600		}
601	else if (errorCode == kDNSServiceErr_NameConflict)
602		{
603		printf("Name in use, please choose another\n");
604		exit(-1);
605		}
606	else
607		printf("Error %d\n", errorCode);
608
609	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
610	}
611
612// Output the wire-format domainname pointed to by rd
613static int snprintd(char *p, int max, const unsigned char **rd)
614	{
615	const char *const buf = p;
616	const char *const end = p + max;
617	while (**rd) { p += snprintf(p, end-p, "%.*s.", **rd, *rd+1); *rd += 1 + **rd; }
618	*rd += 1;	// Advance over the final zero byte
619	return(p-buf);
620	}
621
622static void DNSSD_API qr_reply(DNSServiceRef sdref, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
623	const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
624	{
625	char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
626	const unsigned char *rd  = rdata;
627	const unsigned char *end = (const unsigned char *) rdata + rdlen;
628	char rdb[1000] = "", *p = rdb;
629	int unknowntype = 0;
630
631	(void)sdref;    // Unused
632	(void)flags;    // Unused
633	(void)ifIndex;  // Unused
634	(void)ttl;      // Unused
635	(void)context;  // Unused
636
637	if (num_printed++ == 0) printf("Timestamp     A/R Flags if %-30s%4s%4s Rdata\n", "Name", "T", "C");
638	printtimestamp();
639
640	if (!errorCode)
641		{
642		switch (rrtype)
643			{
644			case kDNSServiceType_A:
645				snprintf(rdb, sizeof(rdb), "%d.%d.%d.%d", rd[0], rd[1], rd[2], rd[3]);
646				break;
647
648			case kDNSServiceType_NS:
649			case kDNSServiceType_CNAME:
650			case kDNSServiceType_PTR:
651			case kDNSServiceType_DNAME:
652				p += snprintd(p, sizeof(rdb), &rd);
653				break;
654
655			case kDNSServiceType_SOA:
656				p += snprintd(p, rdb + sizeof(rdb) - p, &rd);		// mname
657				p += snprintf(p, rdb + sizeof(rdb) - p, " ");
658				p += snprintd(p, rdb + sizeof(rdb) - p, &rd);		// rname
659				p += snprintf(p, rdb + sizeof(rdb) - p, " Ser %d Ref %d Ret %d Exp %d Min %d",
660					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]));
661				break;
662
663			case kDNSServiceType_AAAA:
664				snprintf(rdb, sizeof(rdb), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
665					rd[0x0], rd[0x1], rd[0x2], rd[0x3], rd[0x4], rd[0x5], rd[0x6], rd[0x7],
666					rd[0x8], rd[0x9], rd[0xA], rd[0xB], rd[0xC], rd[0xD], rd[0xE], rd[0xF]);
667				break;
668
669			case kDNSServiceType_SRV:
670				p += snprintf(p, rdb + sizeof(rdb) - p, "%d %d %d ",	// priority, weight, port
671					ntohs(*(unsigned short*)rd), ntohs(*(unsigned short*)(rd+2)), ntohs(*(unsigned short*)(rd+4)));
672				rd += 6;
673				p += snprintd(p, rdb + sizeof(rdb) - p, &rd);			// target host
674				break;
675
676			default : snprintf(rdb, sizeof(rdb), "%d bytes%s", rdlen, rdlen ? ":" : ""); unknowntype = 1; break;
677			}
678		}
679
680	printf("%s%6X%3d %-30s%4d%4d %s", op, flags, ifIndex, fullname, rrtype, rrclass, rdb);
681	if (unknowntype) while (rd < end) printf(" %02X", *rd++);
682	if (errorCode)
683		{
684		if (errorCode == kDNSServiceErr_NoSuchRecord) printf("No Such Record");
685		else                                          printf("Error code %d", errorCode);
686		}
687	printf("\n");
688
689	if (operation == 'C')
690		if (flags & kDNSServiceFlagsAdd)
691			DNSServiceReconfirmRecord(flags, ifIndex, fullname, rrtype, rrclass, rdlen, rdata);
692
693	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
694	}
695
696#if HAS_NAT_PMP_API
697static 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)
698	{
699	(void)sdref;       // Unused
700	(void)context;     // Unused
701	(void)flags;       // Unused
702
703	if (num_printed++ == 0) printf("Timestamp     if   %-20s %-15s %-15s %-15s %-6s\n", "External Address", "Protocol", "Internal Port", "External Port", "TTL");
704	printtimestamp();
705	if (errorCode && errorCode != kDNSServiceErr_DoubleNAT) printf("Error code %d\n", errorCode);
706	else
707		{
708		const unsigned char *digits = (const unsigned char *)&publicAddress;
709		char                 addr[256];
710
711		snprintf(addr, sizeof(addr), "%d.%d.%d.%d", digits[0], digits[1], digits[2], digits[3]);
712		printf("%-4d %-20s %-15d %-15d %-15d %-6d%s\n", ifIndex, addr, protocol, ntohs(privatePort), ntohs(publicPort), ttl, errorCode == kDNSServiceErr_DoubleNAT ? " Double NAT" : "");
713		}
714	fflush(stdout);
715	}
716#endif
717
718#if HAS_ADDRINFO_API
719static 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)
720	{
721	char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
722	char addr[256] = "";
723	(void) sdref;
724	(void) context;
725
726	if (num_printed++ == 0) printf("Timestamp     A/R Flags if %-25s %-44s %s\n", "Hostname", "Address", "TTL");
727	printtimestamp();
728
729	if (address && address->sa_family == AF_INET)
730		{
731		const unsigned char *b = (const unsigned char *) &((struct sockaddr_in *)address)->sin_addr;
732		snprintf(addr, sizeof(addr), "%d.%d.%d.%d", b[0], b[1], b[2], b[3]);
733		}
734	else if (address && address->sa_family == AF_INET6)
735		{
736		char if_name[IFNAMSIZ];		// Older Linux distributions don't define IF_NAMESIZE
737		const struct sockaddr_in6 *s6 = (const struct sockaddr_in6 *)address;
738		const unsigned char       *b  = (const unsigned char *      )&s6->sin6_addr;
739		if (!if_indextoname(s6->sin6_scope_id, if_name))
740			snprintf(if_name, sizeof(if_name), "<%d>", s6->sin6_scope_id);
741		snprintf(addr, sizeof(addr), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X%%%s",
742				b[0x0], b[0x1], b[0x2], b[0x3], b[0x4], b[0x5], b[0x6], b[0x7],
743				b[0x8], b[0x9], b[0xA], b[0xB], b[0xC], b[0xD], b[0xE], b[0xF], if_name);
744		}
745
746	printf("%s%6X%3d %-25s %-44s %d", op, flags, interfaceIndex, hostname, addr, ttl);
747	if (errorCode)
748		{
749		if (errorCode == kDNSServiceErr_NoSuchRecord) printf("   No Such Record");
750		else                                          printf("   Error code %d", errorCode);
751		}
752	printf("\n");
753
754	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
755	}
756#endif
757
758//*************************************************************************************************************
759// The main test function
760
761static void HandleEvents(void)
762	{
763	int dns_sd_fd  = client    ? DNSServiceRefSockFD(client   ) : -1;
764	int dns_sd_fd2 = client_pa ? DNSServiceRefSockFD(client_pa) : -1;
765	int nfds = dns_sd_fd + 1;
766	fd_set readfds;
767	struct timeval tv;
768	int result;
769
770	if (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;
771
772	while (!stopNow)
773		{
774		// 1. Set up the fd_set as usual here.
775		// This example client has no file descriptors of its own,
776		// but a real application would call FD_SET to add them to the set here
777		FD_ZERO(&readfds);
778
779		// 2. Add the fd for our client(s) to the fd_set
780		if (client   ) FD_SET(dns_sd_fd , &readfds);
781		if (client_pa) FD_SET(dns_sd_fd2, &readfds);
782
783		// 3. Set up the timeout.
784		tv.tv_sec  = timeOut;
785		tv.tv_usec = 0;
786
787		result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
788		if (result > 0)
789			{
790			DNSServiceErrorType err = kDNSServiceErr_NoError;
791			if      (client    && FD_ISSET(dns_sd_fd , &readfds)) err = DNSServiceProcessResult(client   );
792			else if (client_pa && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client_pa);
793			if (err) { fprintf(stderr, "DNSServiceProcessResult returned %d\n", err); stopNow = 1; }
794			}
795		else if (result == 0)
796			myTimerCallBack();
797		else
798			{
799			printf("select() returned %d errno %d %s\n", result, errno, strerror(errno));
800			if (errno != EINTR) stopNow = 1;
801			}
802		}
803	}
804
805static int getfirstoption(int argc, char **argv, const char *optstr, int *pOptInd)
806// Return the recognized option in optstr and the option index of the next arg.
807#if NOT_HAVE_GETOPT
808	{
809	int i;
810	for (i=1; i < argc; i++)
811		{
812		if (argv[i][0] == '-' && &argv[i][1] &&
813			 NULL != strchr(optstr, argv[i][1]))
814			{
815			*pOptInd = i + 1;
816			return argv[i][1];
817			}
818		}
819	return -1;
820	}
821#else
822	{
823	int o = getopt(argc, (char *const *)argv, optstr);
824	*pOptInd = optind;
825	return o;
826	}
827#endif
828
829static void DNSSD_API MyRegisterRecordCallback(DNSServiceRef service, DNSRecordRef rec, const DNSServiceFlags flags,
830    DNSServiceErrorType errorCode, void *context)
831	{
832	char *name = (char *)context;
833
834	(void)service;	// Unused
835	(void)rec;	// Unused
836	(void)flags;	// Unused
837
838	printtimestamp();
839	printf("Got a reply for record %s: ", name);
840
841	switch (errorCode)
842		{
843		case kDNSServiceErr_NoError:      printf("Name now registered and active\n"); break;
844		case kDNSServiceErr_NameConflict: printf("Name in use, please choose another\n"); exit(-1);
845		default:                          printf("Error %d\n", errorCode); break;
846		}
847	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
848	// DNSServiceRemoveRecord(service, rec, 0); to test record removal
849	}
850
851static unsigned long getip(const char *const name)
852	{
853	unsigned long ip = 0;
854	struct addrinfo hints;
855	struct addrinfo *addrs = NULL;
856
857	memset(&hints, 0, sizeof(hints));
858	hints.ai_family = AF_INET;
859
860	if (getaddrinfo(name, NULL, &hints, &addrs) == 0)
861		{
862		ip = ((struct sockaddr_in*) addrs->ai_addr)->sin_addr.s_addr;
863		}
864
865	if (addrs)
866		{
867		freeaddrinfo(addrs);
868		}
869
870	return(ip);
871	}
872
873static DNSServiceErrorType RegisterProxyAddressRecord(DNSServiceRef sdref, const char *host, const char *ip)
874	{
875	// Call getip() after the call DNSServiceCreateConnection().
876	// On the Win32 platform, WinSock must be initialized for getip() to succeed.
877	// Any DNSService* call will initialize WinSock for us, so we make sure
878	// DNSServiceCreateConnection() is called before getip() is.
879	unsigned long addr = getip(ip);
880	return(DNSServiceRegisterRecord(sdref, &record, kDNSServiceFlagsUnique, opinterface, host,
881		kDNSServiceType_A, kDNSServiceClass_IN, sizeof(addr), &addr, 240, MyRegisterRecordCallback, (void*)host));
882	// Note, should probably add support for creating proxy AAAA records too, one day
883	}
884
885#define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :  \
886					((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :  \
887					((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
888
889#define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
890
891static DNSServiceErrorType RegisterService(DNSServiceRef *sdref,
892	const char *nam, const char *typ, const char *dom, const char *host, const char *port, int argc, char **argv)
893	{
894	DNSServiceFlags flags = 0;
895	uint16_t PortAsNumber = atoi(port);
896	Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
897	unsigned char txt[2048] = "";
898	unsigned char *ptr = txt;
899	int i;
900
901	if (nam[0] == '.' && nam[1] == 0) nam = "";   // We allow '.' on the command line as a synonym for empty string
902	if (dom[0] == '.' && dom[1] == 0) dom = "";   // We allow '.' on the command line as a synonym for empty string
903
904	printf("Registering Service %s.%s%s%s", nam[0] ? nam : "<<Default>>", typ, dom[0] ? "." : "", dom);
905	if (host && *host) printf(" host %s", host);
906	printf(" port %s", port);
907
908	if (argc)
909		{
910		for (i = 0; i < argc; i++)
911			{
912			const char *p = argv[i];
913			*ptr = 0;
914			while (*p && *ptr < 255 && ptr + 1 + *ptr < txt+sizeof(txt))
915				{
916				if      (p[0] != '\\' || p[1] == 0)                       { ptr[++*ptr] = *p;           p+=1; }
917				else if (p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3])) { ptr[++*ptr] = HexPair(p+2); p+=4; }
918				else                                                      { ptr[++*ptr] = p[1];         p+=2; }
919				}
920			ptr += 1 + *ptr;
921			}
922		printf(" TXT");
923		ShowTXTRecord(ptr-txt, txt);
924		}
925	printf("\n");
926
927	//flags |= kDNSServiceFlagsAllowRemoteQuery;
928	//flags |= kDNSServiceFlagsNoAutoRename;
929
930	return(DNSServiceRegister(sdref, flags, opinterface, nam, typ, dom, host, registerPort.NotAnInteger, (uint16_t) (ptr-txt), txt, reg_reply, NULL));
931	}
932
933#define TypeBufferSize 80
934static char *gettype(char *buffer, char *typ)
935	{
936	if (!typ || !*typ || (typ[0] == '.' && typ[1] == 0)) typ = "_http._tcp";
937	if (!strchr(typ, '.')) { snprintf(buffer, TypeBufferSize, "%s._tcp", typ); typ = buffer; }
938	return(typ);
939	}
940
941int main(int argc, char **argv)
942	{
943	DNSServiceErrorType err;
944	char buffer[TypeBufferSize], *typ, *dom;
945	int opi;
946
947	// Extract the program name from argv[0], which by convention contains the path to this executable.
948	// Note that this is just a voluntary convention, not enforced by the kernel --
949	// the process calling exec() can pass bogus data in argv[0] if it chooses to.
950	const char *a0 = strrchr(argv[0], kFilePathSep) + 1;
951	if (a0 == (const char *)1) a0 = argv[0];
952
953#if defined(_WIN32)
954	HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0);
955#endif
956
957#if TEST_NEW_CLIENTSTUB
958	printf("Using embedded copy of dnssd_clientstub instead of system library\n");
959	if (sizeof(argv) == 8) printf("Running in 64-bit mode\n");
960#endif
961
962	// Test code for TXTRecord functions
963	//TXTRecordRef txtRecord;
964	//TXTRecordCreate(&txtRecord, 0, NULL);
965	//TXTRecordSetValue(&txtRecord, "aaa", 1, "b");
966	//printf("%d\n", TXTRecordContainsKey(TXTRecordGetLength(&txtRecord), TXTRecordGetBytesPtr(&txtRecord), "Aaa"));
967
968	if (argc > 1 && !strcmp(argv[1], "-lo"))
969		{
970		argc--;
971		argv++;
972		opinterface = kDNSServiceInterfaceIndexLocalOnly;
973		printf("Using LocalOnly\n");
974		}
975
976	if (argc > 2 && !strcmp(argv[1], "-i"))
977		{
978		opinterface = if_nametoindex(argv[2]);
979		if (!opinterface) opinterface = atoi(argv[2]);
980		if (!opinterface) { fprintf(stderr, "Unknown interface %s\n", argv[2]); goto Fail; }
981		argc -= 2;
982		argv += 2;
983		}
984
985	if (argc < 2) goto Fail;        // Minimum command line is the command name and one argument
986	operation = getfirstoption(argc, argv, "EFBZLRPQCAUNTMISV"
987								#if HAS_NAT_PMP_API
988									"X"
989								#endif
990								#if HAS_ADDRINFO_API
991									"G"
992								#endif
993								, &opi);
994	if (operation == -1) goto Fail;
995
996	if (opinterface) printf("Using interface %d\n", opinterface);
997
998	switch (operation)
999		{
1000		case 'E':	printf("Looking for recommended registration domains:\n");
1001					err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsRegistrationDomains, opinterface, enum_reply, NULL);
1002					break;
1003
1004		case 'F':	printf("Looking for recommended browsing domains:\n");
1005					err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsBrowseDomains, opinterface, enum_reply, NULL);
1006					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
1007					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
1008					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
1009					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
1010					break;
1011
1012		case 'B':	typ = (argc < opi+1) ? "" : argv[opi+0];
1013					dom = (argc < opi+2) ? "" : argv[opi+1];  // Missing domain argument is the same as empty string i.e. use system default(s)
1014					typ = gettype(buffer, typ);
1015					if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;   // We allow '.' on the command line as a synonym for empty string
1016					printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1017					err = DNSServiceBrowse(&client, 0, opinterface, typ, dom, browse_reply, NULL);
1018					break;
1019
1020		case 'Z':	typ = (argc < opi+1) ? "" : argv[opi+0];
1021					dom = (argc < opi+2) ? "" : argv[opi+1];  // Missing domain argument is the same as empty string i.e. use system default(s)
1022					typ = gettype(buffer, typ);
1023					if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;   // We allow '.' on the command line as a synonym for empty string
1024					printf("Browsing for %s%s%s\n", typ, dom[0] ? "." : "", dom);
1025					err = DNSServiceCreateConnection(&client);
1026					sc1 = client;
1027					err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, typ, dom, zonedata_browse, NULL);
1028					break;
1029
1030		case 'L':	if (argc < opi+2) goto Fail;
1031					typ = (argc < opi+2) ? ""      : argv[opi+1];
1032					dom = (argc < opi+3) ? "local" : argv[opi+2];
1033					typ = gettype(buffer, typ);
1034					if (dom[0] == '.' && dom[1] == 0) dom = "local";   // We allow '.' on the command line as a synonym for "local"
1035					printf("Lookup %s.%s.%s\n", argv[opi+0], typ, dom);
1036					err = DNSServiceResolve(&client, 0, opinterface, argv[opi+0], typ, dom, resolve_reply, NULL);
1037					break;
1038
1039		case 'R':	if (argc < opi+4) goto Fail;
1040					typ = (argc < opi+2) ? "" : argv[opi+1];
1041					dom = (argc < opi+3) ? "" : argv[opi+2];
1042					typ = gettype(buffer, typ);
1043					if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;   // We allow '.' on the command line as a synonym for empty string
1044					err = RegisterService(&client, argv[opi+0], typ, dom, NULL, argv[opi+3], argc-(opi+4), argv+(opi+4));
1045					break;
1046
1047		case 'P':	if (argc < opi+6) goto Fail;
1048					err = DNSServiceCreateConnection(&client_pa);
1049					if (err) { fprintf(stderr, "DNSServiceCreateConnection returned %d\n", err); return(err); }
1050					err = RegisterProxyAddressRecord(client_pa, argv[opi+4], argv[opi+5]);
1051					//err = RegisterProxyAddressRecord(client_pa, "two", argv[opi+5]);
1052					if (err) break;
1053					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));
1054					//DNSServiceRemoveRecord(client_pa, record, 0);
1055					//DNSServiceRemoveRecord(client_pa, record, 0);
1056					break;
1057
1058		case 'Q':
1059		case 'C':	{
1060					uint16_t rrtype, rrclass;
1061					DNSServiceFlags flags = kDNSServiceFlagsReturnIntermediates;
1062					if (argc < opi+1) goto Fail;
1063					rrtype = (argc <= opi+1) ? kDNSServiceType_A  : GetRRType(argv[opi+1]);
1064					rrclass = (argc <= opi+2) ? kDNSServiceClass_IN : atoi(argv[opi+2]);
1065					if (rrtype == kDNSServiceType_TXT || rrtype == kDNSServiceType_PTR) flags |= kDNSServiceFlagsLongLivedQuery;
1066					err = DNSServiceQueryRecord(&client, flags, opinterface, argv[opi+0], rrtype, rrclass, qr_reply, NULL);
1067					break;
1068					}
1069
1070		case 'A':
1071		case 'U':
1072		case 'N':	{
1073					Opaque16 registerPort = { { 0x12, 0x34 } };
1074					static const char TXT[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1075					printf("Registering Service Test._testupdate._tcp.local.\n");
1076					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testupdate._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT)-1, TXT, reg_reply, NULL);
1077					break;
1078					}
1079
1080		case 'T':	{
1081					Opaque16 registerPort = { { 0x23, 0x45 } };
1082					char TXT[1024];
1083					unsigned int i;
1084					for (i=0; i<sizeof(TXT); i++)
1085						if ((i & 0x1F) == 0) TXT[i] = 0x1F; else TXT[i] = 'A' + (i >> 5);
1086					printf("Registering Service Test._testlargetxt._tcp.local.\n");
1087					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testlargetxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT), TXT, reg_reply, NULL);
1088					break;
1089					}
1090
1091		case 'M':	{
1092					pid_t pid = getpid();
1093					Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1094					static const char TXT1[] = "\xC" "First String"  "\xD" "Second String" "\xC" "Third String";
1095					static const char TXT2[] = "\xD" "Fourth String" "\xC" "Fifth String"  "\xC" "Sixth String";
1096					printf("Registering Service Test._testdualtxt._tcp.local.\n");
1097					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testdualtxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT1)-1, TXT1, reg_reply, NULL);
1098					if (!err) err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_TXT, sizeof(TXT2)-1, TXT2, 0);
1099					break;
1100					}
1101
1102		case 'I':	{
1103					pid_t pid = getpid();
1104					Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
1105					static const char TXT[] = "\x09" "Test Data";
1106					printf("Registering Service Test._testtxt._tcp.local.\n");
1107					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testtxt._tcp.", "", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1108					if (!err) err = DNSServiceUpdateRecord(client, NULL, 0, sizeof(TXT)-1, TXT, 0);
1109					break;
1110					}
1111
1112#if HAS_NAT_PMP_API
1113		case 'X':   {
1114					if (argc == opi)	// If no arguments, just fetch IP address
1115						err = DNSServiceNATPortMappingCreate(&client, 0, 0, 0, 0, 0, 0, port_mapping_create_reply, NULL);
1116					else if (argc >= opi+2 && atoi(argv[opi+0]) == 0)
1117						{
1118						DNSServiceProtocol prot  = GetProtocol(argv[opi+0]);						// Must specify TCP or UDP
1119						uint16_t IntPortAsNumber = atoi(argv[opi+1]);							// Must specify internal port
1120						uint16_t ExtPortAsNumber = (argc < opi+3) ? 0 : atoi(argv[opi+2]);	// Optional desired external port
1121						uint32_t ttl             = (argc < opi+4) ? 0 : atoi(argv[opi+3]);	// Optional desired lease lifetime
1122						Opaque16 intp = { { IntPortAsNumber >> 8, IntPortAsNumber & 0xFF } };
1123						Opaque16 extp = { { ExtPortAsNumber >> 8, ExtPortAsNumber & 0xFF } };
1124						err = DNSServiceNATPortMappingCreate(&client, 0, 0, prot, intp.NotAnInteger, extp.NotAnInteger, ttl, port_mapping_create_reply, NULL);
1125						}
1126					else goto Fail;
1127					break;
1128		            }
1129#endif
1130
1131#if HAS_ADDRINFO_API
1132		case 'G':   {
1133					if (argc != opi+2) goto Fail;
1134					else err = DNSServiceGetAddrInfo(&client, kDNSServiceFlagsReturnIntermediates, opinterface, GetProtocol(argv[opi+0]), argv[opi+1], addrinfo_reply, NULL);
1135					break;
1136		            }
1137#endif
1138
1139		case 'S':	{
1140					Opaque16 registerPort = { { 0x23, 0x45 } };
1141					unsigned char txtrec[16] = "\xF" "/path=test.html";
1142					DNSRecordRef rec;
1143					unsigned char nulrec[4] = "1234";
1144
1145					err = DNSServiceCreateConnection(&client);
1146					if (err) { fprintf(stderr, "DNSServiceCreateConnection failed %ld\n", (long int)err); return (-1); }
1147
1148					sc1 = client;
1149					err = DNSServiceBrowse(&sc1, kDNSServiceFlagsShareConnection, opinterface, "_http._tcp", "", browse_reply, NULL);
1150					if (err) { fprintf(stderr, "DNSServiceBrowse _http._tcp failed %ld\n", (long int)err); return (-1); }
1151
1152					sc2 = client;
1153					err = DNSServiceBrowse(&sc2, kDNSServiceFlagsShareConnection, opinterface, "_ftp._tcp", "", browse_reply, NULL);
1154					if (err) { fprintf(stderr, "DNSServiceBrowse _ftp._tcp failed %ld\n", (long int)err); return (-1); }
1155
1156					sc3 = client;
1157					err = DNSServiceRegister(&sc3, kDNSServiceFlagsShareConnection, opinterface, "kDNSServiceFlagsShareConnection",
1158						"_http._tcp", "local", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
1159					if (err) { fprintf(stderr, "SharedConnection DNSServiceRegister failed %ld\n", (long int)err); return (-1); }
1160
1161					err = DNSServiceUpdateRecord(sc3, NULL, 0, sizeof(txtrec), txtrec, 0);
1162					if (err) { fprintf(stderr, "SharedConnection DNSServiceUpdateRecord failed %ld\n", (long int)err); return (-1); }
1163
1164					err = DNSServiceAddRecord(sc3, &rec, 0, kDNSServiceType_NULL, sizeof(nulrec), nulrec, 0);
1165					if (err) { fprintf(stderr, "SharedConnection DNSServiceAddRecord failed %ld\n", (long int)err); return (-1); }
1166
1167					err = DNSServiceRemoveRecord(sc3, rec, 0);
1168					if (err) { fprintf(stderr, "SharedConnection DNSServiceRemoveRecord failed %ld\n", (long int)err); return (-1); }
1169
1170					break;
1171					}
1172
1173		case 'V':   {
1174					uint32_t v;
1175					uint32_t size = sizeof(v);
1176					err = DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion, &v, &size);
1177					if (err) fprintf(stderr, "DNSServiceGetProperty failed %ld\n", (long int)err);
1178					else printf("Currently running daemon (system service) is version %d.%d\n", v / 10000, v / 100 % 100);
1179					exit(0);
1180    				}
1181
1182		default: goto Fail;
1183		}
1184
1185	if (!client || err != kDNSServiceErr_NoError) { fprintf(stderr, "DNSService call failed %ld\n", (long int)err); return (-1); }
1186	HandleEvents();
1187
1188	// Be sure to deallocate the DNSServiceRef when you're finished
1189	if (client   ) DNSServiceRefDeallocate(client   );
1190	if (client_pa) DNSServiceRefDeallocate(client_pa);
1191	return 0;
1192
1193Fail:
1194	fprintf(stderr, "%s -E                  (Enumerate recommended registration domains)\n", a0);
1195	fprintf(stderr, "%s -F                      (Enumerate recommended browsing domains)\n", a0);
1196	fprintf(stderr, "%s -B        <Type> <Domain>        (Browse for services instances)\n", a0);
1197	fprintf(stderr, "%s -L <Name> <Type> <Domain>           (Look up a service instance)\n", a0);
1198	fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", a0);
1199	fprintf(stderr, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...]  (Proxy)\n", a0);
1200	fprintf(stderr, "%s -Z        <Type> <Domain>   (Output results in Zone File format)\n", a0);
1201	fprintf(stderr, "%s -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)\n", a0);
1202	fprintf(stderr, "%s -C <FQDN> <rrtype> <rrclass>   (Query; reconfirming each result)\n", a0);
1203#if HAS_NAT_PMP_API
1204	fprintf(stderr, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL>   (NAT Port Mapping)\n", a0);
1205#endif
1206#if HAS_ADDRINFO_API
1207	fprintf(stderr, "%s -G v4/v6/v4v6 <Hostname>  (Get address information for hostname)\n", a0);
1208#endif
1209	fprintf(stderr, "%s -V    (Get version of currently running daemon / system service)\n", a0);
1210
1211	fprintf(stderr, "%s -A                      (Test Adding/Updating/Deleting a record)\n", a0);
1212	fprintf(stderr, "%s -U                                  (Test updating a TXT record)\n", a0);
1213	fprintf(stderr, "%s -N                             (Test adding a large NULL record)\n", a0);
1214	fprintf(stderr, "%s -T                            (Test creating a large TXT record)\n", a0);
1215	fprintf(stderr, "%s -M      (Test creating a registration with multiple TXT records)\n", a0);
1216	fprintf(stderr, "%s -I   (Test registering and then immediately updating TXT record)\n", a0);
1217	fprintf(stderr, "%s -S                 (Test multiple operations on a shared socket)\n", a0);
1218	return 0;
1219	}
1220
1221// Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
1222// e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
1223// To expand "version" to its value before making the string, use STRINGIFY(version) instead
1224#define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
1225#define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
1226
1227// NOT static -- otherwise the compiler may optimize it out
1228// The "@(#) " pattern is a special prefix the "what" command looks for
1229const char VersionString_SCCS[] = "@(#) dns-sd " STRINGIFY(mDNSResponderVersion);
1230
1231#if _BUILDING_XCODE_PROJECT_
1232// If the process crashes, then this string will be magically included in the automatically-generated crash log
1233const char *__crashreporter_info__ = VersionString_SCCS + 5;
1234asm(".desc ___crashreporter_info__, 0x10");
1235#endif
1236