xref: /onnv-gate/usr/src/cmd/cmd-inet/usr.bin/dns-sd.c (revision 4904:cd464a980538)
1*4904Srs200217 /* -*- Mode: C; tab-width: 4 -*-
2*4904Srs200217  *
3*4904Srs200217  * Copyright (c) 2002-2006 Apple Computer, Inc. All rights reserved.
4*4904Srs200217  *
5*4904Srs200217  * Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc.
6*4904Srs200217  * ("Apple") in consideration of your agreement to the following terms, and your
7*4904Srs200217  * use, installation, modification or redistribution of this Apple software
8*4904Srs200217  * constitutes acceptance of these terms.  If you do not agree with these terms,
9*4904Srs200217  * please do not use, install, modify or redistribute this Apple software.
10*4904Srs200217  *
11*4904Srs200217  * In consideration of your agreement to abide by the following terms, and subject
12*4904Srs200217  * to these terms, Apple grants you a personal, non-exclusive license, under Apple's
13*4904Srs200217  * copyrights in this original Apple software (the "Apple Software"), to use,
14*4904Srs200217  * reproduce, modify and redistribute the Apple Software, with or without
15*4904Srs200217  * modifications, in source and/or binary forms; provided that if you redistribute
16*4904Srs200217  * the Apple Software in its entirety and without modifications, you must retain
17*4904Srs200217  * this notice and the following text and disclaimers in all such redistributions of
18*4904Srs200217  * the Apple Software.  Neither the name, trademarks, service marks or logos of
19*4904Srs200217  * Apple Computer, Inc. may be used to endorse or promote products derived from the
20*4904Srs200217  * Apple Software without specific prior written permission from Apple.  Except as
21*4904Srs200217  * expressly stated in this notice, no other rights or licenses, express or implied,
22*4904Srs200217  * are granted by Apple herein, including but not limited to any patent rights that
23*4904Srs200217  * may be infringed by your derivative works or by other works in which the Apple
24*4904Srs200217  * Software may be incorporated.
25*4904Srs200217  *
26*4904Srs200217  * The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO
27*4904Srs200217  * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
28*4904Srs200217  * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29*4904Srs200217  * PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
30*4904Srs200217  * COMBINATION WITH YOUR PRODUCTS.
31*4904Srs200217  *
32*4904Srs200217  * IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
33*4904Srs200217  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
34*4904Srs200217  * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35*4904Srs200217  * ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
36*4904Srs200217  * OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
37*4904Srs200217  * (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
38*4904Srs200217  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39*4904Srs200217  *
40*4904Srs200217  * Formatting notes:
41*4904Srs200217  * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
42*4904Srs200217  * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
43*4904Srs200217  * but for the sake of brevity here I will say just this: Curly braces are not syntactially
44*4904Srs200217  * part of an "if" statement; they are the beginning and ending markers of a compound statement;
45*4904Srs200217  * therefore common sense dictates that if they are part of a compound statement then they
46*4904Srs200217  * should be indented to the same level as everything else in that compound statement.
47*4904Srs200217  * Indenting curly braces at the same level as the "if" implies that curly braces are
48*4904Srs200217  * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
49*4904Srs200217  * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
50*4904Srs200217  * understand why variable y is not of type "char*" just proves the point that poor code
51*4904Srs200217  * layout leads people to unfortunate misunderstandings about how the C language really works.)
52*4904Srs200217 
53*4904Srs200217 To build this tool, copy and paste the following into a command line:
54*4904Srs200217 
55*4904Srs200217 OS X:
56*4904Srs200217 gcc dns-sd.c -o dns-sd
57*4904Srs200217 
58*4904Srs200217 POSIX systems:
59*4904Srs200217 gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
60*4904Srs200217 
61*4904Srs200217 Windows:
62*4904Srs200217 cl dns-sd.c -I../mDNSShared -DNOT_HAVE_GETOPT ws2_32.lib ..\mDNSWindows\DLL\Release\dnssd.lib
63*4904Srs200217 (may require that you run a Visual Studio script such as vsvars32.bat first)
64*4904Srs200217 */
65*4904Srs200217 
66*4904Srs200217 #pragma ident	"%Z%%M%	%I%	%E% SMI"
67*4904Srs200217 
68*4904Srs200217 // For testing changes to dnssd_clientstub.c, uncomment this line and the #include below
69*4904Srs200217 // #define __APPLE_API_PRIVATE 1
70*4904Srs200217 
71*4904Srs200217 #include "dns_sd.h"
72*4904Srs200217 #include <ctype.h>
73*4904Srs200217 #include <stdio.h>			// For stdout, stderr
74*4904Srs200217 #include <stdlib.h>			// For exit()
75*4904Srs200217 #include <string.h>			// For strlen(), strcpy(), bzero()
76*4904Srs200217 #include <errno.h>			// For errno, EINTR
77*4904Srs200217 #include <time.h>
78*4904Srs200217 #include <sys/types.h>		// For u_char
79*4904Srs200217 
80*4904Srs200217 #ifdef _WIN32
81*4904Srs200217 #include <winsock2.h>
82*4904Srs200217 #include <ws2tcpip.h>
83*4904Srs200217 #include <process.h>
84*4904Srs200217 typedef int        pid_t;
85*4904Srs200217 #define getpid     _getpid
86*4904Srs200217 #define strcasecmp _stricmp
87*4904Srs200217 #define snprintf   _snprintf
88*4904Srs200217 static const char kFilePathSep = '\\';
89*4904Srs200217 #else
90*4904Srs200217 #include <unistd.h>			// For getopt() and optind
91*4904Srs200217 #include <netdb.h>			// For getaddrinfo()
92*4904Srs200217 #include <sys/time.h>		// For struct timeval
93*4904Srs200217 #include <sys/socket.h>		// For AF_INET
94*4904Srs200217 #include <netinet/in.h>		// For struct sockaddr_in()
95*4904Srs200217 #include <arpa/inet.h>		// For inet_addr()
96*4904Srs200217 static const char kFilePathSep = '/';
97*4904Srs200217 #endif
98*4904Srs200217 
99*4904Srs200217 //#include "../mDNSShared/dnssd_clientstub.c"
100*4904Srs200217 
101*4904Srs200217 //*************************************************************************************************************
102*4904Srs200217 // Globals
103*4904Srs200217 
104*4904Srs200217 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
105*4904Srs200217 
106*4904Srs200217 static int operation;
107*4904Srs200217 static uint32_t opinterface = kDNSServiceInterfaceIndexAny;
108*4904Srs200217 static DNSServiceRef client  = NULL;
109*4904Srs200217 static DNSServiceRef client2 = NULL;
110*4904Srs200217 static int num_printed;
111*4904Srs200217 static char addtest = 0;
112*4904Srs200217 static DNSRecordRef record = NULL;
113*4904Srs200217 static char myhinfoW[14] = "\002PC\012Windows XP";
114*4904Srs200217 static char myhinfoX[ 9] = "\003Mac\004OS X";
115*4904Srs200217 static char updatetest[3] = "\002AA";
116*4904Srs200217 static char bigNULL[8200];
117*4904Srs200217 
118*4904Srs200217 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
119*4904Srs200217 #define LONG_TIME 100000000
120*4904Srs200217 
121*4904Srs200217 static volatile int stopNow = 0;
122*4904Srs200217 static volatile int timeOut = LONG_TIME;
123*4904Srs200217 
124*4904Srs200217 //*************************************************************************************************************
125*4904Srs200217 // Supporting Utility Function
126*4904Srs200217 
GetRRType(const char * s)127*4904Srs200217 static uint16_t GetRRType(const char *s)
128*4904Srs200217 	{
129*4904Srs200217 	if      (!strcasecmp(s, "A"       )) return(kDNSServiceType_A);
130*4904Srs200217 	else if (!strcasecmp(s, "NS"      )) return(kDNSServiceType_NS);
131*4904Srs200217 	else if (!strcasecmp(s, "MD"      )) return(kDNSServiceType_MD);
132*4904Srs200217 	else if (!strcasecmp(s, "MF"      )) return(kDNSServiceType_MF);
133*4904Srs200217 	else if (!strcasecmp(s, "CNAME"   )) return(kDNSServiceType_CNAME);
134*4904Srs200217 	else if (!strcasecmp(s, "SOA"     )) return(kDNSServiceType_SOA);
135*4904Srs200217 	else if (!strcasecmp(s, "MB"      )) return(kDNSServiceType_MB);
136*4904Srs200217 	else if (!strcasecmp(s, "MG"      )) return(kDNSServiceType_MG);
137*4904Srs200217 	else if (!strcasecmp(s, "MR"      )) return(kDNSServiceType_MR);
138*4904Srs200217 	else if (!strcasecmp(s, "NULL"    )) return(kDNSServiceType_NULL);
139*4904Srs200217 	else if (!strcasecmp(s, "WKS"     )) return(kDNSServiceType_WKS);
140*4904Srs200217 	else if (!strcasecmp(s, "PTR"     )) return(kDNSServiceType_PTR);
141*4904Srs200217 	else if (!strcasecmp(s, "HINFO"   )) return(kDNSServiceType_HINFO);
142*4904Srs200217 	else if (!strcasecmp(s, "MINFO"   )) return(kDNSServiceType_MINFO);
143*4904Srs200217 	else if (!strcasecmp(s, "MX"      )) return(kDNSServiceType_MX);
144*4904Srs200217 	else if (!strcasecmp(s, "TXT"     )) return(kDNSServiceType_TXT);
145*4904Srs200217 	else if (!strcasecmp(s, "RP"      )) return(kDNSServiceType_RP);
146*4904Srs200217 	else if (!strcasecmp(s, "AFSDB"   )) return(kDNSServiceType_AFSDB);
147*4904Srs200217 	else if (!strcasecmp(s, "X25"     )) return(kDNSServiceType_X25);
148*4904Srs200217 	else if (!strcasecmp(s, "ISDN"    )) return(kDNSServiceType_ISDN);
149*4904Srs200217 	else if (!strcasecmp(s, "RT"      )) return(kDNSServiceType_RT);
150*4904Srs200217 	else if (!strcasecmp(s, "NSAP"    )) return(kDNSServiceType_NSAP);
151*4904Srs200217 	else if (!strcasecmp(s, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR);
152*4904Srs200217 	else if (!strcasecmp(s, "SIG"     )) return(kDNSServiceType_SIG);
153*4904Srs200217 	else if (!strcasecmp(s, "KEY"     )) return(kDNSServiceType_KEY);
154*4904Srs200217 	else if (!strcasecmp(s, "PX"      )) return(kDNSServiceType_PX);
155*4904Srs200217 	else if (!strcasecmp(s, "GPOS"    )) return(kDNSServiceType_GPOS);
156*4904Srs200217 	else if (!strcasecmp(s, "AAAA"    )) return(kDNSServiceType_AAAA);
157*4904Srs200217 	else if (!strcasecmp(s, "LOC"     )) return(kDNSServiceType_LOC);
158*4904Srs200217 	else if (!strcasecmp(s, "NXT"     )) return(kDNSServiceType_NXT);
159*4904Srs200217 	else if (!strcasecmp(s, "EID"     )) return(kDNSServiceType_EID);
160*4904Srs200217 	else if (!strcasecmp(s, "NIMLOC"  )) return(kDNSServiceType_NIMLOC);
161*4904Srs200217 	else if (!strcasecmp(s, "SRV"     )) return(kDNSServiceType_SRV);
162*4904Srs200217 	else if (!strcasecmp(s, "ATMA"    )) return(kDNSServiceType_ATMA);
163*4904Srs200217 	else if (!strcasecmp(s, "NAPTR"   )) return(kDNSServiceType_NAPTR);
164*4904Srs200217 	else if (!strcasecmp(s, "KX"      )) return(kDNSServiceType_KX);
165*4904Srs200217 	else if (!strcasecmp(s, "CERT"    )) return(kDNSServiceType_CERT);
166*4904Srs200217 	else if (!strcasecmp(s, "A6"      )) return(kDNSServiceType_A6);
167*4904Srs200217 	else if (!strcasecmp(s, "DNAME"   )) return(kDNSServiceType_DNAME);
168*4904Srs200217 	else if (!strcasecmp(s, "SINK"    )) return(kDNSServiceType_SINK);
169*4904Srs200217 	else if (!strcasecmp(s, "OPT"     )) return(kDNSServiceType_OPT);
170*4904Srs200217 	else if (!strcasecmp(s, "TKEY"    )) return(kDNSServiceType_TKEY);
171*4904Srs200217 	else if (!strcasecmp(s, "TSIG"    )) return(kDNSServiceType_TSIG);
172*4904Srs200217 	else if (!strcasecmp(s, "IXFR"    )) return(kDNSServiceType_IXFR);
173*4904Srs200217 	else if (!strcasecmp(s, "AXFR"    )) return(kDNSServiceType_AXFR);
174*4904Srs200217 	else if (!strcasecmp(s, "MAILB"   )) return(kDNSServiceType_MAILB);
175*4904Srs200217 	else if (!strcasecmp(s, "MAILA"   )) return(kDNSServiceType_MAILA);
176*4904Srs200217 	else if (!strcasecmp(s, "ANY"     )) return(kDNSServiceType_ANY);
177*4904Srs200217 	else                                 return(atoi(s));
178*4904Srs200217 	}
179*4904Srs200217 
180*4904Srs200217 //*************************************************************************************************************
181*4904Srs200217 // Sample callback functions for each of the operation types
182*4904Srs200217 
printtimestamp(void)183*4904Srs200217 static void printtimestamp(void)
184*4904Srs200217 	{
185*4904Srs200217 	struct tm tm;
186*4904Srs200217 	int ms;
187*4904Srs200217 #ifdef _WIN32
188*4904Srs200217 	SYSTEMTIME sysTime;
189*4904Srs200217 	time_t uct = time(NULL);
190*4904Srs200217 	tm = *localtime(&uct);
191*4904Srs200217 	GetLocalTime(&sysTime);
192*4904Srs200217 	ms = sysTime.wMilliseconds;
193*4904Srs200217 #else
194*4904Srs200217 	struct timeval tv;
195*4904Srs200217 	gettimeofday(&tv, NULL);
196*4904Srs200217 	localtime_r((time_t*)&tv.tv_sec, &tm);
197*4904Srs200217 	ms = tv.tv_usec/1000;
198*4904Srs200217 #endif
199*4904Srs200217 	printf("%2d:%02d:%02d.%03d  ", tm.tm_hour, tm.tm_min, tm.tm_sec, ms);
200*4904Srs200217 	}
201*4904Srs200217 
202*4904Srs200217 #define DomainMsg(X) (((X) & kDNSServiceFlagsDefault) ? "(Default)" : \
203*4904Srs200217                       ((X) & kDNSServiceFlagsAdd)     ? "Added"     : "Removed")
204*4904Srs200217 
GetNextLabel(const char * cstr,char label[64])205*4904Srs200217 static const char *GetNextLabel(const char *cstr, char label[64])
206*4904Srs200217 	{
207*4904Srs200217 	char *ptr = label;
208*4904Srs200217 	while (*cstr && *cstr != '.')								// While we have characters in the label...
209*4904Srs200217 		{
210*4904Srs200217 		char c = *cstr++;
211*4904Srs200217 		if (c == '\\')
212*4904Srs200217 			{
213*4904Srs200217 			c = *cstr++;
214*4904Srs200217 			if (isdigit(cstr[-1]) && isdigit(cstr[0]) && isdigit(cstr[1]))
215*4904Srs200217 				{
216*4904Srs200217 				int v0 = cstr[-1] - '0';						// then interpret as three-digit decimal
217*4904Srs200217 				int v1 = cstr[ 0] - '0';
218*4904Srs200217 				int v2 = cstr[ 1] - '0';
219*4904Srs200217 				int val = v0 * 100 + v1 * 10 + v2;
220*4904Srs200217 				if (val <= 255) { c = (char)val; cstr += 2; }	// If valid three-digit decimal value, use it
221*4904Srs200217 				}
222*4904Srs200217 			}
223*4904Srs200217 		*ptr++ = c;
224*4904Srs200217 		if (ptr >= label+64) return(NULL);
225*4904Srs200217 		}
226*4904Srs200217 	if (*cstr) cstr++;											// Skip over the trailing dot (if present)
227*4904Srs200217 	*ptr++ = 0;
228*4904Srs200217 	return(cstr);
229*4904Srs200217 	}
230*4904Srs200217 
enum_reply(DNSServiceRef client,const DNSServiceFlags flags,uint32_t ifIndex,DNSServiceErrorType errorCode,const char * replyDomain,void * context)231*4904Srs200217 static void DNSSD_API enum_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex,
232*4904Srs200217 	DNSServiceErrorType errorCode, const char *replyDomain, void *context)
233*4904Srs200217 	{
234*4904Srs200217 	DNSServiceFlags partialflags = flags & ~(kDNSServiceFlagsMoreComing | kDNSServiceFlagsAdd | kDNSServiceFlagsDefault);
235*4904Srs200217 	int labels = 0, depth = 0, i, initial = 0;
236*4904Srs200217 	char text[64];
237*4904Srs200217 	const char *label[128];
238*4904Srs200217 
239*4904Srs200217 	(void)client;       // Unused
240*4904Srs200217 	(void)ifIndex;      // Unused
241*4904Srs200217 	(void)context;      // Unused
242*4904Srs200217 
243*4904Srs200217 	// 1. Print the header
244*4904Srs200217 	if (num_printed++ == 0) printf("Timestamp     Recommended %s domain\n", operation == 'E' ? "Registration" : "Browsing");
245*4904Srs200217 	printtimestamp();
246*4904Srs200217 	if (errorCode)
247*4904Srs200217 		printf("Error code %d\n", errorCode);
248*4904Srs200217 	else if (!*replyDomain)
249*4904Srs200217 		printf("Error: No reply domain\n");
250*4904Srs200217 	else
251*4904Srs200217 		{
252*4904Srs200217 		printf("%-10s", DomainMsg(flags));
253*4904Srs200217 		printf("%-8s", (flags & kDNSServiceFlagsMoreComing) ? "(More)" : "");
254*4904Srs200217 		if (partialflags) printf("Flags: %4X  ", partialflags);
255*4904Srs200217 		else printf("             ");
256*4904Srs200217 
257*4904Srs200217 		// 2. Count the labels
258*4904Srs200217 		while (*replyDomain)
259*4904Srs200217 			{
260*4904Srs200217 			label[labels++] = replyDomain;
261*4904Srs200217 			replyDomain = GetNextLabel(replyDomain, text);
262*4904Srs200217 			}
263*4904Srs200217 
264*4904Srs200217 		// 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
265*4904Srs200217 		if      (labels >= 3 && replyDomain - label[labels-1] <= 3 && label[labels-1] - label[labels-2] <= 4) initial = 3;
266*4904Srs200217 		else if (labels >= 2 && replyDomain - label[labels-1] <= 4) initial = 2;
267*4904Srs200217 		else initial = 1;
268*4904Srs200217 		labels -= initial;
269*4904Srs200217 
270*4904Srs200217 		// 4. Print the initial one-, two- or three-label clump
271*4904Srs200217 		for (i=0; i<initial; i++)
272*4904Srs200217 			{
273*4904Srs200217 			GetNextLabel(label[labels+i], text);
274*4904Srs200217 			if (i>0) printf(".");
275*4904Srs200217 			printf("%s", text);
276*4904Srs200217 			}
277*4904Srs200217 		printf("\n");
278*4904Srs200217 
279*4904Srs200217 		// 5. Print the remainder of the hierarchy
280*4904Srs200217 		for (depth=0; depth<labels; depth++)
281*4904Srs200217 			{
282*4904Srs200217 			printf("                                             ");
283*4904Srs200217 			for (i=0; i<=depth; i++) printf("- ");
284*4904Srs200217 			GetNextLabel(label[labels-1-depth], text);
285*4904Srs200217 			printf("> %s\n", text);
286*4904Srs200217 			}
287*4904Srs200217 		}
288*4904Srs200217 
289*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
290*4904Srs200217 	}
291*4904Srs200217 
browse_reply(DNSServiceRef client,const DNSServiceFlags flags,uint32_t ifIndex,DNSServiceErrorType errorCode,const char * replyName,const char * replyType,const char * replyDomain,void * context)292*4904Srs200217 static void DNSSD_API browse_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
293*4904Srs200217 	const char *replyName, const char *replyType, const char *replyDomain, void *context)
294*4904Srs200217 	{
295*4904Srs200217 	char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
296*4904Srs200217 	(void)client;       // Unused
297*4904Srs200217 	(void)context;      // Unused
298*4904Srs200217 	if (num_printed++ == 0) printf("Timestamp     A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
299*4904Srs200217 	printtimestamp();
300*4904Srs200217 	if (errorCode) printf("Error code %d\n", errorCode);
301*4904Srs200217 	else printf("%s%6X%3d %-25s %-25s %s\n", op, flags, ifIndex, replyDomain, replyType, replyName);
302*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
303*4904Srs200217 	}
304*4904Srs200217 
ShowTXTRecord(uint16_t txtLen,const unsigned char * txtRecord)305*4904Srs200217 static void ShowTXTRecord(uint16_t txtLen, const unsigned char *txtRecord)
306*4904Srs200217 	{
307*4904Srs200217 	const unsigned char *ptr = txtRecord;
308*4904Srs200217 	const unsigned char *max = txtRecord + txtLen;
309*4904Srs200217 	while (ptr < max)
310*4904Srs200217 		{
311*4904Srs200217 		const unsigned char *const end = ptr + 1 + ptr[0];
312*4904Srs200217 		if (end > max) { printf("<< invalid data >>"); break; }
313*4904Srs200217 		if (++ptr < end) printf(" ");   // As long as string is non-empty, begin with a space
314*4904Srs200217 		while (ptr<end)
315*4904Srs200217 			{
316*4904Srs200217 			// We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
317*4904Srs200217 			// However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
318*4904Srs200217 			// shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
319*4904Srs200217 			// Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
320*4904Srs200217 			// meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
321*4904Srs200217 			// The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
322*4904Srs200217 			// escapes to encode spaces and all other known shell metacharacters.
323*4904Srs200217 			// (If we've missed any known shell metacharacters, please let us know.)
324*4904Srs200217 			// In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
325*4904Srs200217 			// Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
326*4904Srs200217 			// the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
327*4904Srs200217 			// The C compiler eats half of them, resulting in four appearing in the output.
328*4904Srs200217 			// The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
329*4904Srs200217 			// The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
330*4904Srs200217 			if (strchr(" &;`'\"|*?~<>^()[]{}$", *ptr)) printf("\\");
331*4904Srs200217 			if      (*ptr == '\\') printf("\\\\\\\\");
332*4904Srs200217 			else if (*ptr >= ' ' ) printf("%c",        *ptr);
333*4904Srs200217 			else                   printf("\\\\x%02X", *ptr);
334*4904Srs200217 			ptr++;
335*4904Srs200217 			}
336*4904Srs200217 		}
337*4904Srs200217 	}
338*4904Srs200217 
resolve_reply(DNSServiceRef client,const DNSServiceFlags flags,uint32_t ifIndex,DNSServiceErrorType errorCode,const char * fullname,const char * hosttarget,uint16_t opaqueport,uint16_t txtLen,const unsigned char * txtRecord,void * context)339*4904Srs200217 static void DNSSD_API resolve_reply(DNSServiceRef client, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
340*4904Srs200217 	const char *fullname, const char *hosttarget, uint16_t opaqueport, uint16_t txtLen, const unsigned char *txtRecord, void *context)
341*4904Srs200217 	{
342*4904Srs200217 	union { uint16_t s; u_char b[2]; } port = { opaqueport };
343*4904Srs200217 	uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
344*4904Srs200217 
345*4904Srs200217 	(void)client;       // Unused
346*4904Srs200217 	(void)ifIndex;      // Unused
347*4904Srs200217 	(void)context;      // Unused
348*4904Srs200217 
349*4904Srs200217 	printtimestamp();
350*4904Srs200217 	if (errorCode) printf("Error code %d\n", errorCode);
351*4904Srs200217 	else
352*4904Srs200217 		{
353*4904Srs200217 		printf("%s can be reached at %s:%u", fullname, hosttarget, PortAsNumber);
354*4904Srs200217 		if (flags) printf(" Flags: %X", flags);
355*4904Srs200217 		// Don't show degenerate TXT records containing nothing but a single empty string
356*4904Srs200217 		if (txtLen > 1) { printf("\n"); ShowTXTRecord(txtLen, txtRecord); }
357*4904Srs200217 		printf("\n");
358*4904Srs200217 		}
359*4904Srs200217 
360*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
361*4904Srs200217 	}
362*4904Srs200217 
myTimerCallBack(void)363*4904Srs200217 static void myTimerCallBack(void)
364*4904Srs200217 	{
365*4904Srs200217 	DNSServiceErrorType err = kDNSServiceErr_Unknown;
366*4904Srs200217 
367*4904Srs200217 	switch (operation)
368*4904Srs200217 		{
369*4904Srs200217 		case 'A':
370*4904Srs200217 			{
371*4904Srs200217 			switch (addtest)
372*4904Srs200217 				{
373*4904Srs200217 				case 0: printf("Adding Test HINFO record\n");
374*4904Srs200217 						err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_HINFO, sizeof(myhinfoW), &myhinfoW[0], 0);
375*4904Srs200217 						addtest = 1;
376*4904Srs200217 						break;
377*4904Srs200217 				case 1: printf("Updating Test HINFO record\n");
378*4904Srs200217 						err = DNSServiceUpdateRecord(client, record, 0, sizeof(myhinfoX), &myhinfoX[0], 0);
379*4904Srs200217 						addtest = 2;
380*4904Srs200217 						break;
381*4904Srs200217 				case 2: printf("Removing Test HINFO record\n");
382*4904Srs200217 						err = DNSServiceRemoveRecord(client, record, 0);
383*4904Srs200217 						addtest = 0;
384*4904Srs200217 						break;
385*4904Srs200217 				}
386*4904Srs200217 			}
387*4904Srs200217 			break;
388*4904Srs200217 
389*4904Srs200217 		case 'U':
390*4904Srs200217 			{
391*4904Srs200217 			if (updatetest[1] != 'Z') updatetest[1]++;
392*4904Srs200217 			else                      updatetest[1] = 'A';
393*4904Srs200217 			updatetest[0] = 3 - updatetest[0];
394*4904Srs200217 			updatetest[2] = updatetest[1];
395*4904Srs200217 			printf("Updating Test TXT record to %c\n", updatetest[1]);
396*4904Srs200217 			err = DNSServiceUpdateRecord(client, NULL, 0, 1+updatetest[0], &updatetest[0], 0);
397*4904Srs200217 			}
398*4904Srs200217 			break;
399*4904Srs200217 
400*4904Srs200217 		case 'N':
401*4904Srs200217 			{
402*4904Srs200217 			printf("Adding big NULL record\n");
403*4904Srs200217 			err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_NULL, sizeof(bigNULL), &bigNULL[0], 0);
404*4904Srs200217 			timeOut = LONG_TIME;
405*4904Srs200217 			}
406*4904Srs200217 			break;
407*4904Srs200217 		}
408*4904Srs200217 
409*4904Srs200217 	if (err != kDNSServiceErr_NoError)
410*4904Srs200217 		{
411*4904Srs200217 		fprintf(stderr, "DNSService call failed %ld\n", (long int)err);
412*4904Srs200217 		stopNow = 1;
413*4904Srs200217 		}
414*4904Srs200217 	}
415*4904Srs200217 
reg_reply(DNSServiceRef client,const DNSServiceFlags flags,DNSServiceErrorType errorCode,const char * name,const char * regtype,const char * domain,void * context)416*4904Srs200217 static void DNSSD_API reg_reply(DNSServiceRef client, const DNSServiceFlags flags, DNSServiceErrorType errorCode,
417*4904Srs200217 	const char *name, const char *regtype, const char *domain, void *context)
418*4904Srs200217 	{
419*4904Srs200217 	(void)client;   // Unused
420*4904Srs200217 	(void)flags;    // Unused
421*4904Srs200217 	(void)context;  // Unused
422*4904Srs200217 
423*4904Srs200217 	printf("Got a reply for %s.%s%s: ", name, regtype, domain);
424*4904Srs200217 
425*4904Srs200217 	if (errorCode == kDNSServiceErr_NoError)
426*4904Srs200217 		{
427*4904Srs200217 		printf("Name now registered and active\n");
428*4904Srs200217 		if (operation == 'A' || operation == 'U' || operation == 'N') timeOut = 5;
429*4904Srs200217 		}
430*4904Srs200217 	else if (errorCode == kDNSServiceErr_NameConflict)
431*4904Srs200217 		{
432*4904Srs200217 		printf("Name in use, please choose another\n");
433*4904Srs200217 		exit(-1);
434*4904Srs200217 		}
435*4904Srs200217 	else
436*4904Srs200217 		printf("Error %d\n", errorCode);
437*4904Srs200217 
438*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
439*4904Srs200217 	}
440*4904Srs200217 
qr_reply(DNSServiceRef sdRef,const DNSServiceFlags flags,uint32_t ifIndex,DNSServiceErrorType errorCode,const char * fullname,uint16_t rrtype,uint16_t rrclass,uint16_t rdlen,const void * rdata,uint32_t ttl,void * context)441*4904Srs200217 static void DNSSD_API qr_reply(DNSServiceRef sdRef, const DNSServiceFlags flags, uint32_t ifIndex, DNSServiceErrorType errorCode,
442*4904Srs200217 	const char *fullname, uint16_t rrtype, uint16_t rrclass, uint16_t rdlen, const void *rdata, uint32_t ttl, void *context)
443*4904Srs200217 	{
444*4904Srs200217 	char *op = (flags & kDNSServiceFlagsAdd) ? "Add" : "Rmv";
445*4904Srs200217 	const unsigned char *rd  = rdata;
446*4904Srs200217 	const unsigned char *end = (const unsigned char *) rdata + rdlen;
447*4904Srs200217 	char rdb[1000];
448*4904Srs200217 	int unknowntype = 0;
449*4904Srs200217 
450*4904Srs200217 	(void)sdRef;    // Unused
451*4904Srs200217 	(void)flags;    // Unused
452*4904Srs200217 	(void)ifIndex;  // Unused
453*4904Srs200217 	(void)ttl;      // Unused
454*4904Srs200217 	(void)context;  // Unused
455*4904Srs200217 
456*4904Srs200217 	if (num_printed++ == 0) printf("Timestamp     A/R Flags if %-30s%4s%4s Rdata\n", "Name", "T", "C");
457*4904Srs200217 	printtimestamp();
458*4904Srs200217 	if (errorCode)
459*4904Srs200217 		printf("Error code %d\n", errorCode);
460*4904Srs200217 	else
461*4904Srs200217 		{
462*4904Srs200217 		switch (rrtype)
463*4904Srs200217 			{
464*4904Srs200217 			case kDNSServiceType_A: sprintf(rdb, "%d.%d.%d.%d", rd[0], rd[1], rd[2], rd[3]); break;
465*4904Srs200217 			case kDNSServiceType_AAAA: sprintf(rdb, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
466*4904Srs200217 				rd[0x0], rd[0x1], rd[0x2], rd[0x3], rd[0x4], rd[0x5], rd[0x6], rd[0x7],
467*4904Srs200217 				rd[0x8], rd[0x9], rd[0xA], rd[0xB], rd[0xC], rd[0xD], rd[0xE], rd[0xF]); break;
468*4904Srs200217 				break;
469*4904Srs200217 			default : sprintf(rdb, "%d bytes%s", rdlen, rdlen ? ":" : ""); unknowntype = 1; break;
470*4904Srs200217 			}
471*4904Srs200217 
472*4904Srs200217 		printf("%s%6X%3d %-30s%4d%4d %s", op, flags, ifIndex, fullname, rrtype, rrclass, rdb);
473*4904Srs200217 		if (unknowntype) while (rd < end) printf(" %02X", *rd++);
474*4904Srs200217 		printf("\n");
475*4904Srs200217 
476*4904Srs200217 		if (operation == 'C')
477*4904Srs200217 			if (flags & kDNSServiceFlagsAdd)
478*4904Srs200217 				DNSServiceReconfirmRecord(flags, ifIndex, fullname, rrtype, rrclass, rdlen, rdata);
479*4904Srs200217 		}
480*4904Srs200217 
481*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
482*4904Srs200217 	}
483*4904Srs200217 
484*4904Srs200217 //*************************************************************************************************************
485*4904Srs200217 // The main test function
486*4904Srs200217 
HandleEvents(void)487*4904Srs200217 static void HandleEvents(void)
488*4904Srs200217 	{
489*4904Srs200217 	int dns_sd_fd  = client  ? DNSServiceRefSockFD(client ) : -1;
490*4904Srs200217 	int dns_sd_fd2 = client2 ? DNSServiceRefSockFD(client2) : -1;
491*4904Srs200217 	int nfds = dns_sd_fd + 1;
492*4904Srs200217 	fd_set readfds;
493*4904Srs200217 	struct timeval tv;
494*4904Srs200217 	int result;
495*4904Srs200217 
496*4904Srs200217 	if (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;
497*4904Srs200217 
498*4904Srs200217 	while (!stopNow)
499*4904Srs200217 		{
500*4904Srs200217 		// 1. Set up the fd_set as usual here.
501*4904Srs200217 		// This example client has no file descriptors of its own,
502*4904Srs200217 		// but a real application would call FD_SET to add them to the set here
503*4904Srs200217 		FD_ZERO(&readfds);
504*4904Srs200217 
505*4904Srs200217 		// 2. Add the fd for our client(s) to the fd_set
506*4904Srs200217 		if (client ) FD_SET(dns_sd_fd , &readfds);
507*4904Srs200217 		if (client2) FD_SET(dns_sd_fd2, &readfds);
508*4904Srs200217 
509*4904Srs200217 		// 3. Set up the timeout.
510*4904Srs200217 		tv.tv_sec  = timeOut;
511*4904Srs200217 		tv.tv_usec = 0;
512*4904Srs200217 
513*4904Srs200217 		result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
514*4904Srs200217 		if (result > 0)
515*4904Srs200217 			{
516*4904Srs200217 			DNSServiceErrorType err = kDNSServiceErr_NoError;
517*4904Srs200217 			if      (client  && FD_ISSET(dns_sd_fd , &readfds)) err = DNSServiceProcessResult(client );
518*4904Srs200217 			else if (client2 && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client2);
519*4904Srs200217 			if (err) { fprintf(stderr, "DNSServiceProcessResult returned %d\n", err); stopNow = 1; }
520*4904Srs200217 			}
521*4904Srs200217 		else if (result == 0)
522*4904Srs200217 			myTimerCallBack();
523*4904Srs200217 		else
524*4904Srs200217 			{
525*4904Srs200217 			printf("select() returned %d errno %d %s\n", result, errno, strerror(errno));
526*4904Srs200217 			if (errno != EINTR) stopNow = 1;
527*4904Srs200217 			}
528*4904Srs200217 		}
529*4904Srs200217 	}
530*4904Srs200217 
getfirstoption(int argc,char ** argv,const char * optstr,int * pOptInd)531*4904Srs200217 static int getfirstoption( int argc, char **argv, const char *optstr, int *pOptInd)
532*4904Srs200217 // Return the recognized option in optstr and the option index of the next arg.
533*4904Srs200217 #if NOT_HAVE_GETOPT
534*4904Srs200217 	{
535*4904Srs200217 	int i;
536*4904Srs200217 	for ( i=1; i < argc; i++)
537*4904Srs200217 		{
538*4904Srs200217 		if ( argv[i][0] == '-' && &argv[i][1] &&
539*4904Srs200217 			 NULL != strchr( optstr, argv[i][1]))
540*4904Srs200217 			{
541*4904Srs200217 			*pOptInd = i + 1;
542*4904Srs200217 			return argv[i][1];
543*4904Srs200217 			}
544*4904Srs200217 		}
545*4904Srs200217 	return -1;
546*4904Srs200217 	}
547*4904Srs200217 #else
548*4904Srs200217 	{
549*4904Srs200217 	int operation = getopt(argc, (char * const *)argv, optstr);
550*4904Srs200217 	*pOptInd = optind;
551*4904Srs200217 	return operation;
552*4904Srs200217 	}
553*4904Srs200217 #endif
554*4904Srs200217 
MyRegisterRecordCallback(DNSServiceRef service,DNSRecordRef record,const DNSServiceFlags flags,DNSServiceErrorType errorCode,void * context)555*4904Srs200217 static void DNSSD_API MyRegisterRecordCallback(DNSServiceRef service, DNSRecordRef record, const DNSServiceFlags flags,
556*4904Srs200217     DNSServiceErrorType errorCode, void * context)
557*4904Srs200217 	{
558*4904Srs200217 	char *name = (char *)context;
559*4904Srs200217 
560*4904Srs200217 	(void)service;	// Unused
561*4904Srs200217 	(void)record;	// Unused
562*4904Srs200217 	(void)flags;	// Unused
563*4904Srs200217 
564*4904Srs200217 	printf("Got a reply for %s: ", name);
565*4904Srs200217 	switch (errorCode)
566*4904Srs200217 		{
567*4904Srs200217 		case kDNSServiceErr_NoError:      printf("Name now registered and active\n"); break;
568*4904Srs200217 		case kDNSServiceErr_NameConflict: printf("Name in use, please choose another\n"); exit(-1);
569*4904Srs200217 		default:                          printf("Error %d\n", errorCode); break;
570*4904Srs200217 		}
571*4904Srs200217 	if (!(flags & kDNSServiceFlagsMoreComing)) fflush(stdout);
572*4904Srs200217 	}
573*4904Srs200217 
getip(const char * const name)574*4904Srs200217 static unsigned long getip(const char *const name)
575*4904Srs200217 	{
576*4904Srs200217 	unsigned long ip = 0;
577*4904Srs200217 	struct addrinfo hints;
578*4904Srs200217 	struct addrinfo * addrs = NULL;
579*4904Srs200217 
580*4904Srs200217 	memset(&hints, 0, sizeof(hints));
581*4904Srs200217 	hints.ai_family = AF_INET;
582*4904Srs200217 
583*4904Srs200217 	if (getaddrinfo(name, NULL, &hints, &addrs) == 0)
584*4904Srs200217 		{
585*4904Srs200217 		ip = ((struct sockaddr_in*) addrs->ai_addr)->sin_addr.s_addr;
586*4904Srs200217 		}
587*4904Srs200217 
588*4904Srs200217 	if (addrs)
589*4904Srs200217 		{
590*4904Srs200217 		freeaddrinfo(addrs);
591*4904Srs200217 		}
592*4904Srs200217 
593*4904Srs200217 	return(ip);
594*4904Srs200217 	}
595*4904Srs200217 
RegisterProxyAddressRecord(DNSServiceRef * sdRef,const char * host,const char * ip)596*4904Srs200217 static DNSServiceErrorType RegisterProxyAddressRecord(DNSServiceRef *sdRef, const char *host, const char *ip)
597*4904Srs200217 	{
598*4904Srs200217 	// Call getip() after the call DNSServiceCreateConnection().
599*4904Srs200217 	// On the Win32 platform, WinSock must be initialized for getip() to succeed.
600*4904Srs200217 	// Any DNSService* call will initialize WinSock for us, so we make sure
601*4904Srs200217 	// DNSServiceCreateConnection() is called before getip() is.
602*4904Srs200217 	unsigned long addr = 0;
603*4904Srs200217 	DNSServiceErrorType err = DNSServiceCreateConnection(sdRef);
604*4904Srs200217 	if (err) { fprintf(stderr, "DNSServiceCreateConnection returned %d\n", err); return(err); }
605*4904Srs200217 	addr = getip(ip);
606*4904Srs200217 	return(DNSServiceRegisterRecord(*sdRef, &record, kDNSServiceFlagsUnique, kDNSServiceInterfaceIndexAny, host,
607*4904Srs200217 		kDNSServiceType_A, kDNSServiceClass_IN, sizeof(addr), &addr, 240, MyRegisterRecordCallback, (void*)host));
608*4904Srs200217 	// Note, should probably add support for creating proxy AAAA records too, one day
609*4904Srs200217 	}
610*4904Srs200217 
611*4904Srs200217 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0'     ) :  \
612*4904Srs200217 					((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) :  \
613*4904Srs200217 					((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
614*4904Srs200217 
615*4904Srs200217 #define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
616*4904Srs200217 
RegisterService(DNSServiceRef * sdRef,const char * nam,const char * typ,const char * dom,const char * host,const char * port,int argc,char ** argv)617*4904Srs200217 static DNSServiceErrorType RegisterService(DNSServiceRef *sdRef,
618*4904Srs200217 	const char *nam, const char *typ, const char *dom, const char *host, const char *port, int argc, char **argv)
619*4904Srs200217 	{
620*4904Srs200217 	uint16_t PortAsNumber = atoi(port);
621*4904Srs200217 	Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
622*4904Srs200217 	unsigned char txt[2048] = "";
623*4904Srs200217 	unsigned char *ptr = txt;
624*4904Srs200217 	int i;
625*4904Srs200217 
626*4904Srs200217 	if (nam[0] == '.' && nam[1] == 0) nam = "";   // We allow '.' on the command line as a synonym for empty string
627*4904Srs200217 	if (dom[0] == '.' && dom[1] == 0) dom = "";   // We allow '.' on the command line as a synonym for empty string
628*4904Srs200217 
629*4904Srs200217 	printf("Registering Service %s.%s%s%s", nam[0] ? nam : "<<Default>>", typ, dom[0] ? "." : "", dom);
630*4904Srs200217 	if (host && *host) printf(" host %s", host);
631*4904Srs200217 	printf(" port %s\n", port);
632*4904Srs200217 
633*4904Srs200217 	if (argc)
634*4904Srs200217 		{
635*4904Srs200217 		for (i = 0; i < argc; i++)
636*4904Srs200217 			{
637*4904Srs200217 			const char *p = argv[i];
638*4904Srs200217 			*ptr = 0;
639*4904Srs200217 			while (*p && *ptr < 255 && ptr + 1 + *ptr < txt+sizeof(txt))
640*4904Srs200217 				{
641*4904Srs200217 				if      (p[0] != '\\' || p[1] == 0)                       { ptr[++*ptr] = *p;           p+=1; }
642*4904Srs200217 				else if (p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3])) { ptr[++*ptr] = HexPair(p+2); p+=4; }
643*4904Srs200217 				else                                                      { ptr[++*ptr] = p[1];         p+=2; }
644*4904Srs200217 				}
645*4904Srs200217 			ptr += 1 + *ptr;
646*4904Srs200217 			}
647*4904Srs200217 		ShowTXTRecord(ptr-txt, txt);
648*4904Srs200217 		printf("\n");
649*4904Srs200217 		}
650*4904Srs200217 
651*4904Srs200217 	return(DNSServiceRegister(sdRef, /* kDNSServiceFlagsAllowRemoteQuery */ 0, opinterface, nam, typ, dom, host, registerPort.NotAnInteger, (uint16_t) (ptr-txt), txt, reg_reply, NULL));
652*4904Srs200217 	}
653*4904Srs200217 
main(int argc,char ** argv)654*4904Srs200217 int main(int argc, char **argv)
655*4904Srs200217 	{
656*4904Srs200217 	DNSServiceErrorType err;
657*4904Srs200217 	char *dom;
658*4904Srs200217 	int optind;
659*4904Srs200217 
660*4904Srs200217 	// Extract the program name from argv[0], which by convention contains the path to this executable.
661*4904Srs200217 	// Note that this is just a voluntary convention, not enforced by the kernel --
662*4904Srs200217 	// the process calling exec() can pass bogus data in argv[0] if it chooses to.
663*4904Srs200217 	const char *a0 = strrchr(argv[0], kFilePathSep) + 1;
664*4904Srs200217 	if (a0 == (const char *)1) a0 = argv[0];
665*4904Srs200217 
666*4904Srs200217 	if (argc > 1 && !strcmp(argv[1], "-lo"))
667*4904Srs200217 		{
668*4904Srs200217 		argc--;
669*4904Srs200217 		argv++;
670*4904Srs200217 		opinterface = kDNSServiceInterfaceIndexLocalOnly;
671*4904Srs200217 		printf("Using LocalOnly\n");
672*4904Srs200217 		}
673*4904Srs200217 
674*4904Srs200217 	if (argc > 2 && !strcmp(argv[1], "-i") && atoi(argv[2]))
675*4904Srs200217 		{
676*4904Srs200217 		opinterface = atoi(argv[2]);
677*4904Srs200217 		argc -= 2;
678*4904Srs200217 		argv += 2;
679*4904Srs200217 		printf("Using interface %d\n", opinterface);
680*4904Srs200217 		}
681*4904Srs200217 
682*4904Srs200217 	if (argc < 2) goto Fail;        // Minimum command line is the command name and one argument
683*4904Srs200217 	operation = getfirstoption( argc, argv, "EFBLRPQCAUNTMI", &optind);
684*4904Srs200217 	if (operation == -1) goto Fail;
685*4904Srs200217 
686*4904Srs200217 	switch (operation)
687*4904Srs200217 		{
688*4904Srs200217 		case 'E':	printf("Looking for recommended registration domains:\n");
689*4904Srs200217 					err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsRegistrationDomains, opinterface, enum_reply, NULL);
690*4904Srs200217 					break;
691*4904Srs200217 
692*4904Srs200217 		case 'F':	printf("Looking for recommended browsing domains:\n");
693*4904Srs200217 					err = DNSServiceEnumerateDomains(&client, kDNSServiceFlagsBrowseDomains, opinterface, enum_reply, NULL);
694*4904Srs200217 					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
695*4904Srs200217 					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
696*4904Srs200217 					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
697*4904Srs200217 					//enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
698*4904Srs200217 					break;
699*4904Srs200217 
700*4904Srs200217 		case 'B':	if (argc < optind+1) goto Fail;
701*4904Srs200217 					dom = (argc < optind+2) ? "" : argv[optind+1];
702*4904Srs200217 					if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;   // We allow '.' on the command line as a synonym for empty string
703*4904Srs200217 					printf("Browsing for %s%s%s\n", argv[optind+0], dom[0] ? "." : "", dom);
704*4904Srs200217 					err = DNSServiceBrowse(&client, 0, opinterface, argv[optind+0], dom, browse_reply, NULL);
705*4904Srs200217 					break;
706*4904Srs200217 
707*4904Srs200217 		case 'L':	if (argc < optind+2) goto Fail;
708*4904Srs200217 					dom = (argc < optind+3) ? "local" : argv[optind+2];
709*4904Srs200217 					if (dom[0] == '.' && dom[1] == 0) dom = "local";   // We allow '.' on the command line as a synonym for "local"
710*4904Srs200217 					printf("Lookup %s.%s.%s\n", argv[optind+0], argv[optind+1], dom);
711*4904Srs200217 					err = DNSServiceResolve(&client, 0, opinterface, argv[optind+0], argv[optind+1], dom, (DNSServiceResolveReply)resolve_reply, NULL);
712*4904Srs200217 					break;
713*4904Srs200217 
714*4904Srs200217 		case 'R':	if (argc < optind+4) goto Fail;
715*4904Srs200217 					err = RegisterService(&client, argv[optind+0], argv[optind+1], argv[optind+2], NULL, argv[optind+3], argc-(optind+4), argv+(optind+4));
716*4904Srs200217 					break;
717*4904Srs200217 
718*4904Srs200217 		case 'P':	if (argc < optind+6) goto Fail;
719*4904Srs200217 					err = RegisterProxyAddressRecord(&client2, argv[optind+4], argv[optind+5]);
720*4904Srs200217 					if (err) break;
721*4904Srs200217 					err = RegisterService(&client, argv[optind+0], argv[optind+1], argv[optind+2], argv[optind+4], argv[optind+3], argc-(optind+6), argv+(optind+6));
722*4904Srs200217 					break;
723*4904Srs200217 
724*4904Srs200217 		case 'Q':
725*4904Srs200217 		case 'C':	{
726*4904Srs200217 					uint16_t rrtype, rrclass;
727*4904Srs200217 					DNSServiceFlags flags = kDNSServiceFlagsReturnCNAME;
728*4904Srs200217 					if (argc < optind+1) goto Fail;
729*4904Srs200217 					rrtype = (argc <= optind+1) ? kDNSServiceType_A  : GetRRType(argv[optind+1]);
730*4904Srs200217 					rrclass = (argc <= optind+2) ? kDNSServiceClass_IN : atoi(argv[optind+2]);
731*4904Srs200217 					if (rrtype == kDNSServiceType_TXT || rrtype == kDNSServiceType_PTR) flags |= kDNSServiceFlagsLongLivedQuery;
732*4904Srs200217 					err = DNSServiceQueryRecord(&client, flags, opinterface, argv[optind+0], rrtype, rrclass, qr_reply, NULL);
733*4904Srs200217 					break;
734*4904Srs200217 					}
735*4904Srs200217 
736*4904Srs200217 		case 'A':
737*4904Srs200217 		case 'U':
738*4904Srs200217 		case 'N':	{
739*4904Srs200217 					Opaque16 registerPort = { { 0x12, 0x34 } };
740*4904Srs200217 					static const char TXT[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
741*4904Srs200217 					printf("Registering Service Test._testupdate._tcp.local.\n");
742*4904Srs200217 					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testupdate._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT)-1, TXT, reg_reply, NULL);
743*4904Srs200217 					break;
744*4904Srs200217 					}
745*4904Srs200217 
746*4904Srs200217 		case 'T':	{
747*4904Srs200217 					Opaque16 registerPort = { { 0x23, 0x45 } };
748*4904Srs200217 					char TXT[1024];
749*4904Srs200217 					unsigned int i;
750*4904Srs200217 					for (i=0; i<sizeof(TXT); i++)
751*4904Srs200217 						if ((i & 0x1F) == 0) TXT[i] = 0x1F; else TXT[i] = 'A' + (i >> 5);
752*4904Srs200217 					printf("Registering Service Test._testlargetxt._tcp.local.\n");
753*4904Srs200217 					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testlargetxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT), TXT, reg_reply, NULL);
754*4904Srs200217 					break;
755*4904Srs200217 					}
756*4904Srs200217 
757*4904Srs200217 		case 'M':	{
758*4904Srs200217 					pid_t pid = getpid();
759*4904Srs200217 					Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
760*4904Srs200217 					static const char TXT1[] = "\xC" "First String"  "\xD" "Second String" "\xC" "Third String";
761*4904Srs200217 					static const char TXT2[] = "\xD" "Fourth String" "\xC" "Fifth String"  "\xC" "Sixth String";
762*4904Srs200217 					printf("Registering Service Test._testdualtxt._tcp.local.\n");
763*4904Srs200217 					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testdualtxt._tcp.", "", NULL, registerPort.NotAnInteger, sizeof(TXT1)-1, TXT1, reg_reply, NULL);
764*4904Srs200217 					if (!err) err = DNSServiceAddRecord(client, &record, 0, kDNSServiceType_TXT, sizeof(TXT2)-1, TXT2, 0);
765*4904Srs200217 					break;
766*4904Srs200217 					}
767*4904Srs200217 
768*4904Srs200217 		case 'I':	{
769*4904Srs200217 					pid_t pid = getpid();
770*4904Srs200217 					Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
771*4904Srs200217 					static const char TXT[] = "\x09" "Test Data";
772*4904Srs200217 					printf("Registering Service Test._testtxt._tcp.local.\n");
773*4904Srs200217 					err = DNSServiceRegister(&client, 0, opinterface, "Test", "_testtxt._tcp.", "", NULL, registerPort.NotAnInteger, 0, NULL, reg_reply, NULL);
774*4904Srs200217 					if (!err) err = DNSServiceUpdateRecord(client, NULL, 0, sizeof(TXT)-1, TXT, 0);
775*4904Srs200217 					break;
776*4904Srs200217 					}
777*4904Srs200217 
778*4904Srs200217 		default: goto Fail;
779*4904Srs200217 		}
780*4904Srs200217 
781*4904Srs200217 	if (!client || err != kDNSServiceErr_NoError) { fprintf(stderr, "DNSService call failed %ld\n", (long int)err); return (-1); }
782*4904Srs200217 	HandleEvents();
783*4904Srs200217 
784*4904Srs200217 	// Be sure to deallocate the DNSServiceRef when you're finished
785*4904Srs200217 	if (client ) DNSServiceRefDeallocate(client );
786*4904Srs200217 	if (client2) DNSServiceRefDeallocate(client2);
787*4904Srs200217 	return 0;
788*4904Srs200217 
789*4904Srs200217 Fail:
790*4904Srs200217 	fprintf(stderr, "%s -E                  (Enumerate recommended registration domains)\n", a0);
791*4904Srs200217 	fprintf(stderr, "%s -F                      (Enumerate recommended browsing domains)\n", a0);
792*4904Srs200217 	fprintf(stderr, "%s -B        <Type> <Domain>        (Browse for services instances)\n", a0);
793*4904Srs200217 	fprintf(stderr, "%s -L <Name> <Type> <Domain>           (Look up a service instance)\n", a0);
794*4904Srs200217 	fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", a0);
795*4904Srs200217 	fprintf(stderr, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...]  (Proxy)\n", a0);
796*4904Srs200217 	fprintf(stderr, "%s -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)\n", a0);
797*4904Srs200217 	fprintf(stderr, "%s -C <FQDN> <rrtype> <rrclass>   (Query; reconfirming each result)\n", a0);
798*4904Srs200217 	fprintf(stderr, "%s -A                      (Test Adding/Updating/Deleting a record)\n", a0);
799*4904Srs200217 	fprintf(stderr, "%s -U                                  (Test updating a TXT record)\n", a0);
800*4904Srs200217 	fprintf(stderr, "%s -N                             (Test adding a large NULL record)\n", a0);
801*4904Srs200217 	fprintf(stderr, "%s -T                            (Test creating a large TXT record)\n", a0);
802*4904Srs200217 	fprintf(stderr, "%s -M      (Test creating a registration with multiple TXT records)\n", a0);
803*4904Srs200217 	fprintf(stderr, "%s -I   (Test registering and then immediately updating TXT record)\n", a0);
804*4904Srs200217 	return 0;
805*4904Srs200217 	}
806