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