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