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