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