1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2008 Apple Inc. All rights reserved.
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.
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.
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.
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.
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.)
53 To build this tool, copy and paste the following into a command line:
56 gcc dns-sd.c -o dns-sd
59 gcc dns-sd.c -o dns-sd -I../mDNSShared -ldns_sd
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)
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
73 // When building mDNSResponder for Mac OS X 10.4 and earlier, /usr/lib/libSystem.dylib is built using its own private
74 // copy of dnssd_clientstub.c, which is old and doesn't have all the entry points defined in the latest version, so
75 // when we're building dns-sd.c on Mac OS X 10.4 or earlier, we automatically set TEST_NEW_CLIENTSTUB so that we'll
76 // embed a copy of the latest dnssd_clientstub.c instead of trying to link to the incomplete version in libSystem.dylib
77 #if defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 1040
78 #define TEST_NEW_CLIENTSTUB 1
82 #include <stdio.h> // For stdout, stderr
83 #include <stdlib.h> // For exit()
84 #include <string.h> // For strlen(), strcpy()
85 #include <errno.h> // For errno, EINTR
87 #include <sys/types.h> // For u_char
95 #define getpid _getpid
96 #define strcasecmp _stricmp
97 #define snprintf _snprintf
98 static const char kFilePathSep
= '\\';
99 #ifndef HeapEnableTerminationOnCorruption
100 # define HeapEnableTerminationOnCorruption (HEAP_INFORMATION_CLASS)1
102 #if !defined(IFNAMSIZ)
105 #define if_nametoindex if_nametoindex_win
106 #define if_indextoname if_indextoname_win
108 typedef PCHAR (WINAPI
* if_indextoname_funcptr_t
)(ULONG index
, PCHAR name
);
109 typedef ULONG (WINAPI
* if_nametoindex_funcptr_t
)(PCSTR name
);
111 unsigned if_nametoindex_win(const char *ifname
)
116 // Try and load the IP helper library dll
117 if ((library
= LoadLibrary(TEXT("Iphlpapi")) ) != NULL
)
119 if_nametoindex_funcptr_t if_nametoindex_funcptr
;
121 // On Vista and above there is a Posix like implementation of if_nametoindex
122 if ((if_nametoindex_funcptr
= (if_nametoindex_funcptr_t
) GetProcAddress(library
, "if_nametoindex")) != NULL
)
124 index
= if_nametoindex_funcptr(ifname
);
127 FreeLibrary(library
);
133 char * if_indextoname_win( unsigned ifindex
, char *ifname
)
138 // Try and load the IP helper library dll
139 if ((library
= LoadLibrary(TEXT("Iphlpapi")) ) != NULL
)
141 if_indextoname_funcptr_t if_indextoname_funcptr
;
143 // On Vista and above there is a Posix like implementation of if_indextoname
144 if ((if_indextoname_funcptr
= (if_indextoname_funcptr_t
) GetProcAddress(library
, "if_indextoname")) != NULL
)
146 name
= if_indextoname_funcptr(ifindex
, ifname
);
149 FreeLibrary(library
);
156 #include <unistd.h> // For getopt() and optind
157 #include <netdb.h> // For getaddrinfo()
158 #include <sys/time.h> // For struct timeval
159 #include <sys/socket.h> // For AF_INET
160 #include <netinet/in.h> // For struct sockaddr_in()
161 #include <arpa/inet.h> // For inet_addr()
162 #include <net/if.h> // For if_nametoindex()
163 static const char kFilePathSep
= '/';
166 #if (TEST_NEW_CLIENTSTUB && !defined(__APPLE_API_PRIVATE))
167 #define __APPLE_API_PRIVATE 1
172 #include "ClientCommon.h"
174 #if TEST_NEW_CLIENTSTUB
175 #include "../mDNSShared/dnssd_ipc.c"
176 #include "../mDNSShared/dnssd_clientlib.c"
177 #include "../mDNSShared/dnssd_clientstub.c"
180 // 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)
181 #if _DNS_SD_H+0 >= 116
182 #define HAS_NAT_PMP_API 1
183 #define HAS_ADDRINFO_API 1
185 #define kDNSServiceFlagsReturnIntermediates 0
188 //*************************************************************************************************************
191 typedef union { unsigned char b
[2]; unsigned short NotAnInteger
; } Opaque16
;
193 static int operation
;
194 static uint32_t opinterface
= kDNSServiceInterfaceIndexAny
;
195 static DNSServiceRef client
= NULL
;
196 static DNSServiceRef client_pa
= NULL
; // DNSServiceRef for RegisterProxyAddressRecord
197 static DNSServiceRef sc1
, sc2
, sc3
; // DNSServiceRefs for kDNSServiceFlagsShareConnection testing
199 static int num_printed
;
200 static char addtest
= 0;
201 static DNSRecordRef record
= NULL
;
202 static char myhinfoW
[14] = "\002PC\012Windows XP";
203 static char myhinfoX
[ 9] = "\003Mac\004OS X";
204 static char updatetest
[3] = "\002AA";
205 static char bigNULL
[8192]; // 8K is maximum rdata we support
207 // Note: the select() implementation on Windows (Winsock2) fails with any timeout much larger than this
208 #define LONG_TIME 100000000
210 static volatile int stopNow
= 0;
211 static volatile int timeOut
= LONG_TIME
;
213 //*************************************************************************************************************
214 // Supporting Utility Functions
216 static uint16_t GetRRType(const char *s
)
218 if (!strcasecmp(s
, "A" )) return(kDNSServiceType_A
);
219 else if (!strcasecmp(s
, "NS" )) return(kDNSServiceType_NS
);
220 else if (!strcasecmp(s
, "MD" )) return(kDNSServiceType_MD
);
221 else if (!strcasecmp(s
, "MF" )) return(kDNSServiceType_MF
);
222 else if (!strcasecmp(s
, "CNAME" )) return(kDNSServiceType_CNAME
);
223 else if (!strcasecmp(s
, "SOA" )) return(kDNSServiceType_SOA
);
224 else if (!strcasecmp(s
, "MB" )) return(kDNSServiceType_MB
);
225 else if (!strcasecmp(s
, "MG" )) return(kDNSServiceType_MG
);
226 else if (!strcasecmp(s
, "MR" )) return(kDNSServiceType_MR
);
227 else if (!strcasecmp(s
, "NULL" )) return(kDNSServiceType_NULL
);
228 else if (!strcasecmp(s
, "WKS" )) return(kDNSServiceType_WKS
);
229 else if (!strcasecmp(s
, "PTR" )) return(kDNSServiceType_PTR
);
230 else if (!strcasecmp(s
, "HINFO" )) return(kDNSServiceType_HINFO
);
231 else if (!strcasecmp(s
, "MINFO" )) return(kDNSServiceType_MINFO
);
232 else if (!strcasecmp(s
, "MX" )) return(kDNSServiceType_MX
);
233 else if (!strcasecmp(s
, "TXT" )) return(kDNSServiceType_TXT
);
234 else if (!strcasecmp(s
, "RP" )) return(kDNSServiceType_RP
);
235 else if (!strcasecmp(s
, "AFSDB" )) return(kDNSServiceType_AFSDB
);
236 else if (!strcasecmp(s
, "X25" )) return(kDNSServiceType_X25
);
237 else if (!strcasecmp(s
, "ISDN" )) return(kDNSServiceType_ISDN
);
238 else if (!strcasecmp(s
, "RT" )) return(kDNSServiceType_RT
);
239 else if (!strcasecmp(s
, "NSAP" )) return(kDNSServiceType_NSAP
);
240 else if (!strcasecmp(s
, "NSAP_PTR")) return(kDNSServiceType_NSAP_PTR
);
241 else if (!strcasecmp(s
, "SIG" )) return(kDNSServiceType_SIG
);
242 else if (!strcasecmp(s
, "KEY" )) return(kDNSServiceType_KEY
);
243 else if (!strcasecmp(s
, "PX" )) return(kDNSServiceType_PX
);
244 else if (!strcasecmp(s
, "GPOS" )) return(kDNSServiceType_GPOS
);
245 else if (!strcasecmp(s
, "AAAA" )) return(kDNSServiceType_AAAA
);
246 else if (!strcasecmp(s
, "LOC" )) return(kDNSServiceType_LOC
);
247 else if (!strcasecmp(s
, "NXT" )) return(kDNSServiceType_NXT
);
248 else if (!strcasecmp(s
, "EID" )) return(kDNSServiceType_EID
);
249 else if (!strcasecmp(s
, "NIMLOC" )) return(kDNSServiceType_NIMLOC
);
250 else if (!strcasecmp(s
, "SRV" )) return(kDNSServiceType_SRV
);
251 else if (!strcasecmp(s
, "ATMA" )) return(kDNSServiceType_ATMA
);
252 else if (!strcasecmp(s
, "NAPTR" )) return(kDNSServiceType_NAPTR
);
253 else if (!strcasecmp(s
, "KX" )) return(kDNSServiceType_KX
);
254 else if (!strcasecmp(s
, "CERT" )) return(kDNSServiceType_CERT
);
255 else if (!strcasecmp(s
, "A6" )) return(kDNSServiceType_A6
);
256 else if (!strcasecmp(s
, "DNAME" )) return(kDNSServiceType_DNAME
);
257 else if (!strcasecmp(s
, "SINK" )) return(kDNSServiceType_SINK
);
258 else if (!strcasecmp(s
, "OPT" )) return(kDNSServiceType_OPT
);
259 else if (!strcasecmp(s
, "TKEY" )) return(kDNSServiceType_TKEY
);
260 else if (!strcasecmp(s
, "TSIG" )) return(kDNSServiceType_TSIG
);
261 else if (!strcasecmp(s
, "IXFR" )) return(kDNSServiceType_IXFR
);
262 else if (!strcasecmp(s
, "AXFR" )) return(kDNSServiceType_AXFR
);
263 else if (!strcasecmp(s
, "MAILB" )) return(kDNSServiceType_MAILB
);
264 else if (!strcasecmp(s
, "MAILA" )) return(kDNSServiceType_MAILA
);
265 else if (!strcasecmp(s
, "ANY" )) return(kDNSServiceType_ANY
);
266 else return(atoi(s
));
269 #if HAS_NAT_PMP_API | HAS_ADDRINFO_API
270 static DNSServiceProtocol
GetProtocol(const char *s
)
272 if (!strcasecmp(s
, "v4" )) return(kDNSServiceProtocol_IPv4
);
273 else if (!strcasecmp(s
, "v6" )) return(kDNSServiceProtocol_IPv6
);
274 else if (!strcasecmp(s
, "v4v6" )) return(kDNSServiceProtocol_IPv4
| kDNSServiceProtocol_IPv6
);
275 else if (!strcasecmp(s
, "v6v4" )) return(kDNSServiceProtocol_IPv4
| kDNSServiceProtocol_IPv6
);
276 else if (!strcasecmp(s
, "udp" )) return(kDNSServiceProtocol_UDP
);
277 else if (!strcasecmp(s
, "tcp" )) return(kDNSServiceProtocol_TCP
);
278 else if (!strcasecmp(s
, "udptcp" )) return(kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
);
279 else if (!strcasecmp(s
, "tcpudp" )) return(kDNSServiceProtocol_UDP
| kDNSServiceProtocol_TCP
);
280 else return(atoi(s
));
284 //*************************************************************************************************************
285 // Sample callback functions for each of the operation types
287 static void printtimestamp(void)
293 time_t uct
= time(NULL
);
294 tm
= *localtime(&uct
);
295 GetLocalTime(&sysTime
);
296 ms
= sysTime
.wMilliseconds
;
299 gettimeofday(&tv
, NULL
);
300 localtime_r((time_t*)&tv
.tv_sec
, &tm
);
301 ms
= tv
.tv_usec
/1000;
303 printf("%2d:%02d:%02d.%03d ", tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, ms
);
306 #define DomainMsg(X) (((X) & kDNSServiceFlagsDefault) ? "(Default)" : \
307 ((X) & kDNSServiceFlagsAdd) ? "Added" : "Removed")
309 #define MAX_LABELS 128
311 static void DNSSD_API
enum_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
,
312 DNSServiceErrorType errorCode
, const char *replyDomain
, void *context
)
314 DNSServiceFlags partialflags
= flags
& ~(kDNSServiceFlagsMoreComing
| kDNSServiceFlagsAdd
| kDNSServiceFlagsDefault
);
315 int labels
= 0, depth
= 0, i
, initial
= 0;
317 const char *label
[MAX_LABELS
];
319 (void)sdref
; // Unused
320 (void)ifIndex
; // Unused
321 (void)context
; // Unused
323 // 1. Print the header
324 if (num_printed
++ == 0) printf("Timestamp Recommended %s domain\n", operation
== 'E' ? "Registration" : "Browsing");
327 printf("Error code %d\n", errorCode
);
328 else if (!*replyDomain
)
329 printf("Error: No reply domain\n");
332 printf("%-10s", DomainMsg(flags
));
333 printf("%-8s", (flags
& kDNSServiceFlagsMoreComing
) ? "(More)" : "");
334 if (partialflags
) printf("Flags: %4X ", partialflags
);
337 // 2. Count the labels
338 while (replyDomain
&& *replyDomain
&& labels
< MAX_LABELS
)
340 label
[labels
++] = replyDomain
;
341 replyDomain
= GetNextLabel(replyDomain
, text
);
344 // 3. Decide if we're going to clump the last two or three labels (e.g. "apple.com", or "nicta.com.au")
345 if (labels
>= 3 && replyDomain
- label
[labels
-1] <= 3 && label
[labels
-1] - label
[labels
-2] <= 4) initial
= 3;
346 else if (labels
>= 2 && replyDomain
- label
[labels
-1] <= 4) initial
= 2;
350 // 4. Print the initial one-, two- or three-label clump
351 for (i
=0; i
<initial
; i
++)
353 GetNextLabel(label
[labels
+i
], text
);
354 if (i
>0) printf(".");
359 // 5. Print the remainder of the hierarchy
360 for (depth
=0; depth
<labels
; depth
++)
363 for (i
=0; i
<=depth
; i
++) printf("- ");
364 GetNextLabel(label
[labels
-1-depth
], text
);
365 printf("> %s\n", text
);
369 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
372 static int CopyLabels(char *dst
, const char *lim
, const char **srcp
, int labels
)
374 const char *src
= *srcp
;
375 while (*src
!= '.' || --labels
> 0)
377 if (*src
== '\\') *dst
++ = *src
++; // Make sure "\." doesn't confuse us
378 if (!*src
|| dst
>= lim
) return -1;
380 if (!*src
|| dst
>= lim
) return -1;
383 *srcp
= src
+ 1; // skip over final dot
387 static void DNSSD_API
zonedata_resolve(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
388 const char *fullname
, const char *hosttarget
, uint16_t opaqueport
, uint16_t txtLen
, const unsigned char *txt
, void *context
)
390 union { uint16_t s
; u_char b
[2]; } port
= { opaqueport
};
391 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
393 const char *p
= fullname
;
394 char n
[kDNSServiceMaxDomainName
];
395 char t
[kDNSServiceMaxDomainName
];
397 const unsigned char *max
= txt
+ txtLen
;
399 (void)sdref
; // Unused
400 (void)ifIndex
; // Unused
401 (void)context
; // Unused
403 //if (!(flags & kDNSServiceFlagsAdd)) return;
404 if (errorCode
) { printf("Error code %d\n", errorCode
); return; }
406 if (CopyLabels(n
, n
+ kDNSServiceMaxDomainName
, &p
, 3)) return; // Fetch name+type
408 if (CopyLabels(t
, t
+ kDNSServiceMaxDomainName
, &p
, 1)) return; // Skip first label
409 if (CopyLabels(t
, t
+ kDNSServiceMaxDomainName
, &p
, 2)) return; // Fetch next two labels (service type)
411 if (num_printed
++ == 0)
414 printf("; To direct clients to browse a different domain, substitute that domain in place of '@'\n");
415 printf("%-47s PTR %s\n", "lb._dns-sd._udp", "@");
417 printf("; In the list of services below, the SRV records will typically reference dot-local Multicast DNS names.\n");
418 printf("; When transferring this zone file data to your unicast DNS server, you'll need to replace those dot-local\n");
419 printf("; names with the correct fully-qualified (unicast) domain name of the target host offering the service.\n");
423 printf("%-47s PTR %s\n", t
, n
);
424 printf("%-47s SRV 0 0 %d %s ; Replace with unicast FQDN of target host\n", n
, PortAsNumber
, hosttarget
);
425 printf("%-47s TXT ", n
);
429 const unsigned char *const end
= txt
+ 1 + txt
[0];
430 txt
++; // Skip over length byte
434 if (*txt
== '\\' || *txt
== '\"') printf("\\");
435 printf("%c", *txt
++);
441 DNSServiceRefDeallocate(sdref
);
444 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
447 static void DNSSD_API
zonedata_browse(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
448 const char *replyName
, const char *replyType
, const char *replyDomain
, void *context
)
450 DNSServiceRef
*newref
;
452 (void)sdref
; // Unused
453 (void)context
; // Unused
455 if (!(flags
& kDNSServiceFlagsAdd
)) return;
456 if (errorCode
) { printf("Error code %d\n", errorCode
); return; }
458 newref
= malloc(sizeof(*newref
));
460 DNSServiceResolve(newref
, kDNSServiceFlagsShareConnection
, ifIndex
, replyName
, replyType
, replyDomain
, zonedata_resolve
, newref
);
463 static void DNSSD_API
browse_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
464 const char *replyName
, const char *replyType
, const char *replyDomain
, void *context
)
466 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
467 (void)sdref
; // Unused
468 (void)context
; // Unused
469 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-25s %-25s %s\n", "Domain", "Service Type", "Instance Name");
471 if (errorCode
) printf("Error code %d\n", errorCode
);
472 else printf("%s%6X%3d %-25s %-25s %s\n", op
, flags
, ifIndex
, replyDomain
, replyType
, replyName
);
473 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
475 // To test selective cancellation of operations of shared sockets,
476 // cancel the current operation when we've got a multiple of five results
477 //if (operation == 'S' && num_printed % 5 == 0) DNSServiceRefDeallocate(sdref);
480 static void ShowTXTRecord(uint16_t txtLen
, const unsigned char *txtRecord
)
482 const unsigned char *ptr
= txtRecord
;
483 const unsigned char *max
= txtRecord
+ txtLen
;
486 const unsigned char *const end
= ptr
+ 1 + ptr
[0];
487 if (end
> max
) { printf("<< invalid data >>"); break; }
488 if (++ptr
< end
) printf(" "); // As long as string is non-empty, begin with a space
491 // We'd like the output to be shell-friendly, so that it can be copied and pasted unchanged into a "dns-sd -R" command.
492 // However, this is trickier than it seems. Enclosing a string in double quotes doesn't necessarily make it
493 // shell-safe, because shells still expand variables like $foo even when they appear inside quoted strings.
494 // Enclosing a string in single quotes is better, but when using single quotes even backslash escapes are ignored,
495 // meaning there's simply no way to represent a single quote (or apostrophe) inside a single-quoted string.
496 // The only remaining solution is not to surround the string with quotes at all, but instead to use backslash
497 // escapes to encode spaces and all other known shell metacharacters.
498 // (If we've missed any known shell metacharacters, please let us know.)
499 // In addition, non-printing ascii codes (0-31) are displayed as \xHH, using a two-digit hex value.
500 // Because '\' is itself a shell metacharacter (the shell escape character), it has to be escaped as "\\" to survive
501 // the round-trip to the shell and back. This means that a single '\' is represented here as EIGHT backslashes:
502 // The C compiler eats half of them, resulting in four appearing in the output.
503 // The shell parses those four as a pair of "\\" sequences, passing two backslashes to the "dns-sd -R" command.
504 // The "dns-sd -R" command interprets this single "\\" pair as an escaped literal backslash. Sigh.
505 if (strchr(" &;`'\"|*?~<>^()[]{}$", *ptr
)) printf("\\");
506 if (*ptr
== '\\') printf("\\\\\\\\");
507 else if (*ptr
>= ' ' ) printf("%c", *ptr
);
508 else printf("\\\\x%02X", *ptr
);
514 static void DNSSD_API
resolve_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
515 const char *fullname
, const char *hosttarget
, uint16_t opaqueport
, uint16_t txtLen
, const unsigned char *txtRecord
, void *context
)
517 union { uint16_t s
; u_char b
[2]; } port
= { opaqueport
};
518 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
520 (void)sdref
; // Unused
521 (void)ifIndex
; // Unused
522 (void)context
; // Unused
525 if (errorCode
) printf("Error code %d\n", errorCode
);
528 printf("%s can be reached at %s:%u (interface %d)", fullname
, hosttarget
, PortAsNumber
, ifIndex
);
529 if (flags
) printf(" Flags: %X", flags
);
530 // Don't show degenerate TXT records containing nothing but a single empty string
531 if (txtLen
> 1) { printf("\n"); ShowTXTRecord(txtLen
, txtRecord
); }
535 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
538 static void myTimerCallBack(void)
540 DNSServiceErrorType err
= kDNSServiceErr_Unknown
;
548 case 0: printf("Adding Test HINFO record\n");
549 err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_HINFO
, sizeof(myhinfoW
), &myhinfoW
[0], 0);
552 case 1: printf("Updating Test HINFO record\n");
553 err
= DNSServiceUpdateRecord(client
, record
, 0, sizeof(myhinfoX
), &myhinfoX
[0], 0);
556 case 2: printf("Removing Test HINFO record\n");
557 err
= DNSServiceRemoveRecord(client
, record
, 0);
566 if (updatetest
[1] != 'Z') updatetest
[1]++;
567 else updatetest
[1] = 'A';
568 updatetest
[0] = 3 - updatetest
[0];
569 updatetest
[2] = updatetest
[1];
571 printf("Updating Test TXT record to %c\n", updatetest
[1]);
572 err
= DNSServiceUpdateRecord(client
, NULL
, 0, 1+updatetest
[0], &updatetest
[0], 0);
578 printf("Adding big NULL record\n");
579 err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_NULL
, sizeof(bigNULL
), &bigNULL
[0], 0);
580 if (err
) printf("Failed: %d\n", err
); else printf("Succeeded\n");
586 if (err
!= kDNSServiceErr_NoError
)
588 fprintf(stderr
, "DNSService add/update/remove failed %ld\n", (long int)err
);
593 static void DNSSD_API
reg_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, DNSServiceErrorType errorCode
,
594 const char *name
, const char *regtype
, const char *domain
, void *context
)
596 (void)sdref
; // Unused
597 (void)flags
; // Unused
598 (void)context
; // Unused
601 printf("Got a reply for service %s.%s%s: ", name
, regtype
, domain
);
603 if (errorCode
== kDNSServiceErr_NoError
)
605 if (flags
& kDNSServiceFlagsAdd
) printf("Name now registered and active\n");
606 else printf("Name registration removed\n");
607 if (operation
== 'A' || operation
== 'U' || operation
== 'N') timeOut
= 5;
609 else if (errorCode
== kDNSServiceErr_NameConflict
)
611 printf("Name in use, please choose another\n");
615 printf("Error %d\n", errorCode
);
617 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
620 // Output the wire-format domainname pointed to by rd
621 static int snprintd(char *p
, int max
, const unsigned char **rd
)
623 const char *const buf
= p
;
624 const char *const end
= p
+ max
;
625 while (**rd
) { p
+= snprintf(p
, end
-p
, "%.*s.", **rd
, *rd
+1); *rd
+= 1 + **rd
; }
626 *rd
+= 1; // Advance over the final zero byte
630 static void DNSSD_API
qr_reply(DNSServiceRef sdref
, const DNSServiceFlags flags
, uint32_t ifIndex
, DNSServiceErrorType errorCode
,
631 const char *fullname
, uint16_t rrtype
, uint16_t rrclass
, uint16_t rdlen
, const void *rdata
, uint32_t ttl
, void *context
)
633 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
634 const unsigned char *rd
= rdata
;
635 const unsigned char *end
= (const unsigned char *) rdata
+ rdlen
;
636 char rdb
[1000] = "", *p
= rdb
;
639 (void)sdref
; // Unused
640 (void)flags
; // Unused
641 (void)ifIndex
; // Unused
643 (void)context
; // Unused
645 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-30s%4s%4s Rdata\n", "Name", "T", "C");
652 case kDNSServiceType_A
:
653 snprintf(rdb
, sizeof(rdb
), "%d.%d.%d.%d", rd
[0], rd
[1], rd
[2], rd
[3]);
656 case kDNSServiceType_NS
:
657 case kDNSServiceType_CNAME
:
658 case kDNSServiceType_PTR
:
659 case kDNSServiceType_DNAME
:
660 p
+= snprintd(p
, sizeof(rdb
), &rd
);
663 case kDNSServiceType_SOA
:
664 p
+= snprintd(p
, rdb
+ sizeof(rdb
) - p
, &rd
); // mname
665 p
+= snprintf(p
, rdb
+ sizeof(rdb
) - p
, " ");
666 p
+= snprintd(p
, rdb
+ sizeof(rdb
) - p
, &rd
); // rname
667 p
+= snprintf(p
, rdb
+ sizeof(rdb
) - p
, " Ser %d Ref %d Ret %d Exp %d Min %d",
668 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]));
671 case kDNSServiceType_AAAA
:
672 snprintf(rdb
, sizeof(rdb
), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
673 rd
[0x0], rd
[0x1], rd
[0x2], rd
[0x3], rd
[0x4], rd
[0x5], rd
[0x6], rd
[0x7],
674 rd
[0x8], rd
[0x9], rd
[0xA], rd
[0xB], rd
[0xC], rd
[0xD], rd
[0xE], rd
[0xF]);
677 case kDNSServiceType_SRV
:
678 p
+= snprintf(p
, rdb
+ sizeof(rdb
) - p
, "%d %d %d ", // priority, weight, port
679 ntohs(*(unsigned short*)rd
), ntohs(*(unsigned short*)(rd
+2)), ntohs(*(unsigned short*)(rd
+4)));
681 p
+= snprintd(p
, rdb
+ sizeof(rdb
) - p
, &rd
); // target host
684 default : snprintf(rdb
, sizeof(rdb
), "%d bytes%s", rdlen
, rdlen
? ":" : ""); unknowntype
= 1; break;
688 printf("%s%6X%3d %-30s%4d%4d %s", op
, flags
, ifIndex
, fullname
, rrtype
, rrclass
, rdb
);
689 if (unknowntype
) while (rd
< end
) printf(" %02X", *rd
++);
692 if (errorCode
== kDNSServiceErr_NoSuchRecord
) printf("No Such Record");
693 else printf("Error code %d", errorCode
);
697 if (operation
== 'C')
698 if (flags
& kDNSServiceFlagsAdd
)
699 DNSServiceReconfirmRecord(flags
, ifIndex
, fullname
, rrtype
, rrclass
, rdlen
, rdata
);
701 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
705 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
)
707 (void)sdref
; // Unused
708 (void)context
; // Unused
709 (void)flags
; // Unused
711 if (num_printed
++ == 0) printf("Timestamp if %-20s %-15s %-15s %-15s %-6s\n", "External Address", "Protocol", "Internal Port", "External Port", "TTL");
713 if (errorCode
&& errorCode
!= kDNSServiceErr_DoubleNAT
) printf("Error code %d\n", errorCode
);
716 const unsigned char *digits
= (const unsigned char *)&publicAddress
;
719 snprintf(addr
, sizeof(addr
), "%d.%d.%d.%d", digits
[0], digits
[1], digits
[2], digits
[3]);
720 printf("%-4d %-20s %-15d %-15d %-15d %-6d%s\n", ifIndex
, addr
, protocol
, ntohs(privatePort
), ntohs(publicPort
), ttl
, errorCode
== kDNSServiceErr_DoubleNAT
? " Double NAT" : "");
727 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
)
729 char *op
= (flags
& kDNSServiceFlagsAdd
) ? "Add" : "Rmv";
734 if (num_printed
++ == 0) printf("Timestamp A/R Flags if %-25s %-44s %s\n", "Hostname", "Address", "TTL");
737 if (address
&& address
->sa_family
== AF_INET
)
739 const unsigned char *b
= (const unsigned char *) &((struct sockaddr_in
*)address
)->sin_addr
;
740 snprintf(addr
, sizeof(addr
), "%d.%d.%d.%d", b
[0], b
[1], b
[2], b
[3]);
742 else if (address
&& address
->sa_family
== AF_INET6
)
744 char if_name
[IFNAMSIZ
]; // Older Linux distributions don't define IF_NAMESIZE
745 const struct sockaddr_in6
*s6
= (const struct sockaddr_in6
*)address
;
746 const unsigned char *b
= (const unsigned char * )&s6
->sin6_addr
;
747 if (!if_indextoname(s6
->sin6_scope_id
, if_name
))
748 snprintf(if_name
, sizeof(if_name
), "<%d>", s6
->sin6_scope_id
);
749 snprintf(addr
, sizeof(addr
), "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X%%%s",
750 b
[0x0], b
[0x1], b
[0x2], b
[0x3], b
[0x4], b
[0x5], b
[0x6], b
[0x7],
751 b
[0x8], b
[0x9], b
[0xA], b
[0xB], b
[0xC], b
[0xD], b
[0xE], b
[0xF], if_name
);
754 printf("%s%6X%3d %-25s %-44s %d", op
, flags
, interfaceIndex
, hostname
, addr
, ttl
);
757 if (errorCode
== kDNSServiceErr_NoSuchRecord
) printf(" No Such Record");
758 else printf(" Error code %d", errorCode
);
762 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
766 //*************************************************************************************************************
767 // The main test function
769 static void HandleEvents(void)
771 int dns_sd_fd
= client
? DNSServiceRefSockFD(client
) : -1;
772 int dns_sd_fd2
= client_pa
? DNSServiceRefSockFD(client_pa
) : -1;
773 int nfds
= dns_sd_fd
+ 1;
778 if (dns_sd_fd2
> dns_sd_fd
) nfds
= dns_sd_fd2
+ 1;
782 // 1. Set up the fd_set as usual here.
783 // This example client has no file descriptors of its own,
784 // but a real application would call FD_SET to add them to the set here
787 // 2. Add the fd for our client(s) to the fd_set
788 if (client
) FD_SET(dns_sd_fd
, &readfds
);
789 if (client_pa
) FD_SET(dns_sd_fd2
, &readfds
);
791 // 3. Set up the timeout.
795 result
= select(nfds
, &readfds
, (fd_set
*)NULL
, (fd_set
*)NULL
, &tv
);
798 DNSServiceErrorType err
= kDNSServiceErr_NoError
;
799 if (client
&& FD_ISSET(dns_sd_fd
, &readfds
)) err
= DNSServiceProcessResult(client
);
800 else if (client_pa
&& FD_ISSET(dns_sd_fd2
, &readfds
)) err
= DNSServiceProcessResult(client_pa
);
801 if (err
) { fprintf(stderr
, "DNSServiceProcessResult returned %d\n", err
); stopNow
= 1; }
803 else if (result
== 0)
807 printf("select() returned %d errno %d %s\n", result
, errno
, strerror(errno
));
808 if (errno
!= EINTR
) stopNow
= 1;
813 static int getfirstoption(int argc
, char **argv
, const char *optstr
, int *pOptInd
)
814 // Return the recognized option in optstr and the option index of the next arg.
818 for (i
=1; i
< argc
; i
++)
820 if (argv
[i
][0] == '-' && &argv
[i
][1] &&
821 NULL
!= strchr(optstr
, argv
[i
][1]))
831 int o
= getopt(argc
, (char *const *)argv
, optstr
);
837 static void DNSSD_API
MyRegisterRecordCallback(DNSServiceRef service
, DNSRecordRef rec
, const DNSServiceFlags flags
,
838 DNSServiceErrorType errorCode
, void *context
)
840 char *name
= (char *)context
;
842 (void)service
; // Unused
844 (void)flags
; // Unused
847 printf("Got a reply for record %s: ", name
);
851 case kDNSServiceErr_NoError
: printf("Name now registered and active\n"); break;
852 case kDNSServiceErr_NameConflict
: printf("Name in use, please choose another\n"); exit(-1);
853 default: printf("Error %d\n", errorCode
); break;
855 if (!(flags
& kDNSServiceFlagsMoreComing
)) fflush(stdout
);
856 // DNSServiceRemoveRecord(service, rec, 0); to test record removal
859 static unsigned long getip(const char *const name
)
861 unsigned long ip
= 0;
862 struct addrinfo hints
;
863 struct addrinfo
*addrs
= NULL
;
865 memset(&hints
, 0, sizeof(hints
));
866 hints
.ai_family
= AF_INET
;
868 if (getaddrinfo(name
, NULL
, &hints
, &addrs
) == 0)
870 ip
= ((struct sockaddr_in
*) addrs
->ai_addr
)->sin_addr
.s_addr
;
881 static DNSServiceErrorType
RegisterProxyAddressRecord(DNSServiceRef sdref
, const char *host
, const char *ip
)
883 // Call getip() after the call DNSServiceCreateConnection().
884 // On the Win32 platform, WinSock must be initialized for getip() to succeed.
885 // Any DNSService* call will initialize WinSock for us, so we make sure
886 // DNSServiceCreateConnection() is called before getip() is.
887 unsigned long addr
= getip(ip
);
888 return(DNSServiceRegisterRecord(sdref
, &record
, kDNSServiceFlagsUnique
, opinterface
, host
,
889 kDNSServiceType_A
, kDNSServiceClass_IN
, sizeof(addr
), &addr
, 240, MyRegisterRecordCallback
, (void*)host
));
890 // Note, should probably add support for creating proxy AAAA records too, one day
893 #define HexVal(X) ( ((X) >= '0' && (X) <= '9') ? ((X) - '0' ) : \
894 ((X) >= 'A' && (X) <= 'F') ? ((X) - 'A' + 10) : \
895 ((X) >= 'a' && (X) <= 'f') ? ((X) - 'a' + 10) : 0)
897 #define HexPair(P) ((HexVal((P)[0]) << 4) | HexVal((P)[1]))
899 static DNSServiceErrorType
RegisterService(DNSServiceRef
*sdref
,
900 const char *nam
, const char *typ
, const char *dom
, const char *host
, const char *port
, int argc
, char **argv
)
902 DNSServiceFlags flags
= 0;
903 uint16_t PortAsNumber
= atoi(port
);
904 Opaque16 registerPort
= { { PortAsNumber
>> 8, PortAsNumber
& 0xFF } };
905 unsigned char txt
[2048] = "";
906 unsigned char *ptr
= txt
;
909 if (nam
[0] == '.' && nam
[1] == 0) nam
= ""; // We allow '.' on the command line as a synonym for empty string
910 if (dom
[0] == '.' && dom
[1] == 0) dom
= ""; // We allow '.' on the command line as a synonym for empty string
912 printf("Registering Service %s.%s%s%s", nam
[0] ? nam
: "<<Default>>", typ
, dom
[0] ? "." : "", dom
);
913 if (host
&& *host
) printf(" host %s", host
);
914 printf(" port %s", port
);
918 for (i
= 0; i
< argc
; i
++)
920 const char *p
= argv
[i
];
922 while (*p
&& *ptr
< 255 && ptr
+ 1 + *ptr
< txt
+sizeof(txt
))
924 if (p
[0] != '\\' || p
[1] == 0) { ptr
[++*ptr
] = *p
; p
+=1; }
925 else if (p
[1] == 'x' && isxdigit(p
[2]) && isxdigit(p
[3])) { ptr
[++*ptr
] = HexPair(p
+2); p
+=4; }
926 else { ptr
[++*ptr
] = p
[1]; p
+=2; }
931 ShowTXTRecord(ptr
-txt
, txt
);
935 //flags |= kDNSServiceFlagsAllowRemoteQuery;
936 //flags |= kDNSServiceFlagsNoAutoRename;
938 return(DNSServiceRegister(sdref
, flags
, opinterface
, nam
, typ
, dom
, host
, registerPort
.NotAnInteger
, (uint16_t) (ptr
-txt
), txt
, reg_reply
, NULL
));
941 #define TypeBufferSize 80
942 static char *gettype(char *buffer
, char *typ
)
944 if (!typ
|| !*typ
|| (typ
[0] == '.' && typ
[1] == 0)) typ
= "_http._tcp";
945 if (!strchr(typ
, '.')) { snprintf(buffer
, TypeBufferSize
, "%s._tcp", typ
); typ
= buffer
; }
949 int main(int argc
, char **argv
)
951 DNSServiceErrorType err
;
952 char buffer
[TypeBufferSize
], *typ
, *dom
;
955 // Extract the program name from argv[0], which by convention contains the path to this executable.
956 // Note that this is just a voluntary convention, not enforced by the kernel --
957 // the process calling exec() can pass bogus data in argv[0] if it chooses to.
958 const char *a0
= strrchr(argv
[0], kFilePathSep
) + 1;
959 if (a0
== (const char *)1) a0
= argv
[0];
962 HeapSetInformation(NULL
, HeapEnableTerminationOnCorruption
, NULL
, 0);
965 #if TEST_NEW_CLIENTSTUB
966 printf("Using embedded copy of dnssd_clientstub instead of system library\n");
967 if (sizeof(argv
) == 8) printf("Running in 64-bit mode\n");
970 // Test code for TXTRecord functions
971 //TXTRecordRef txtRecord;
972 //TXTRecordCreate(&txtRecord, 0, NULL);
973 //TXTRecordSetValue(&txtRecord, "aaa", 1, "b");
974 //printf("%d\n", TXTRecordContainsKey(TXTRecordGetLength(&txtRecord), TXTRecordGetBytesPtr(&txtRecord), "Aaa"));
976 if (argc
> 1 && !strcmp(argv
[1], "-lo"))
980 opinterface
= kDNSServiceInterfaceIndexLocalOnly
;
981 printf("Using LocalOnly\n");
984 if (argc
> 2 && !strcmp(argv
[1], "-i"))
986 opinterface
= if_nametoindex(argv
[2]);
987 if (!opinterface
) opinterface
= atoi(argv
[2]);
988 if (!opinterface
) { fprintf(stderr
, "Unknown interface %s\n", argv
[2]); goto Fail
; }
993 if (argc
< 2) goto Fail
; // Minimum command line is the command name and one argument
994 operation
= getfirstoption(argc
, argv
, "EFBZLRPQCAUNTMISV"
1002 if (operation
== -1) goto Fail
;
1004 if (opinterface
) printf("Using interface %d\n", opinterface
);
1008 case 'E': printf("Looking for recommended registration domains:\n");
1009 err
= DNSServiceEnumerateDomains(&client
, kDNSServiceFlagsRegistrationDomains
, opinterface
, enum_reply
, NULL
);
1012 case 'F': printf("Looking for recommended browsing domains:\n");
1013 err
= DNSServiceEnumerateDomains(&client
, kDNSServiceFlagsBrowseDomains
, opinterface
, enum_reply
, NULL
);
1014 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "nicta.com.au.", NULL);
1015 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "bonjour.nicta.com.au.", NULL);
1016 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "ibm.com.", NULL);
1017 //enum_reply(client, kDNSServiceFlagsAdd, 0, 0, "dns-sd.ibm.com.", NULL);
1020 case 'B': typ
= (argc
< opi
+1) ? "" : argv
[opi
+0];
1021 dom
= (argc
< opi
+2) ? "" : argv
[opi
+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
1022 typ
= gettype(buffer
, typ
);
1023 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
1024 printf("Browsing for %s%s%s\n", typ
, dom
[0] ? "." : "", dom
);
1025 err
= DNSServiceBrowse(&client
, 0, opinterface
, typ
, dom
, browse_reply
, NULL
);
1028 case 'Z': typ
= (argc
< opi
+1) ? "" : argv
[opi
+0];
1029 dom
= (argc
< opi
+2) ? "" : argv
[opi
+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
1030 typ
= gettype(buffer
, typ
);
1031 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
1032 printf("Browsing for %s%s%s\n", typ
, dom
[0] ? "." : "", dom
);
1033 err
= DNSServiceCreateConnection(&client
);
1035 err
= DNSServiceBrowse(&sc1
, kDNSServiceFlagsShareConnection
, opinterface
, typ
, dom
, zonedata_browse
, NULL
);
1038 case 'L': if (argc
< opi
+2) goto Fail
;
1039 typ
= (argc
< opi
+2) ? "" : argv
[opi
+1];
1040 dom
= (argc
< opi
+3) ? "local" : argv
[opi
+2];
1041 typ
= gettype(buffer
, typ
);
1042 if (dom
[0] == '.' && dom
[1] == 0) dom
= "local"; // We allow '.' on the command line as a synonym for "local"
1043 printf("Lookup %s.%s.%s\n", argv
[opi
+0], typ
, dom
);
1044 err
= DNSServiceResolve(&client
, 0, opinterface
, argv
[opi
+0], typ
, dom
, resolve_reply
, NULL
);
1047 case 'R': if (argc
< opi
+4) goto Fail
;
1048 typ
= (argc
< opi
+2) ? "" : argv
[opi
+1];
1049 dom
= (argc
< opi
+3) ? "" : argv
[opi
+2];
1050 typ
= gettype(buffer
, typ
);
1051 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
1052 err
= RegisterService(&client
, argv
[opi
+0], typ
, dom
, NULL
, argv
[opi
+3], argc
-(opi
+4), argv
+(opi
+4));
1055 case 'P': if (argc
< opi
+6) goto Fail
;
1056 err
= DNSServiceCreateConnection(&client_pa
);
1057 if (err
) { fprintf(stderr
, "DNSServiceCreateConnection returned %d\n", err
); return(err
); }
1058 err
= RegisterProxyAddressRecord(client_pa
, argv
[opi
+4], argv
[opi
+5]);
1059 //err = RegisterProxyAddressRecord(client_pa, "two", argv[opi+5]);
1061 err
= RegisterService(&client
, argv
[opi
+0], gettype(buffer
, argv
[opi
+1]), argv
[opi
+2], argv
[opi
+4], argv
[opi
+3], argc
-(opi
+6), argv
+(opi
+6));
1062 //DNSServiceRemoveRecord(client_pa, record, 0);
1063 //DNSServiceRemoveRecord(client_pa, record, 0);
1068 uint16_t rrtype
, rrclass
;
1069 DNSServiceFlags flags
= kDNSServiceFlagsReturnIntermediates
;
1070 if (argc
< opi
+1) goto Fail
;
1071 rrtype
= (argc
<= opi
+1) ? kDNSServiceType_A
: GetRRType(argv
[opi
+1]);
1072 rrclass
= (argc
<= opi
+2) ? kDNSServiceClass_IN
: atoi(argv
[opi
+2]);
1073 if (rrtype
== kDNSServiceType_TXT
|| rrtype
== kDNSServiceType_PTR
) flags
|= kDNSServiceFlagsLongLivedQuery
;
1074 err
= DNSServiceQueryRecord(&client
, flags
, opinterface
, argv
[opi
+0], rrtype
, rrclass
, qr_reply
, NULL
);
1081 Opaque16 registerPort
= { { 0x12, 0x34 } };
1082 static const char TXT
[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1083 printf("Registering Service Test._testupdate._tcp.local.\n");
1084 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testupdate._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT
)-1, TXT
, reg_reply
, NULL
);
1089 Opaque16 registerPort
= { { 0x23, 0x45 } };
1092 for (i
=0; i
<sizeof(TXT
); i
++)
1093 if ((i
& 0x1F) == 0) TXT
[i
] = 0x1F; else TXT
[i
] = 'A' + (i
>> 5);
1094 printf("Registering Service Test._testlargetxt._tcp.local.\n");
1095 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testlargetxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT
), TXT
, reg_reply
, NULL
);
1100 pid_t pid
= getpid();
1101 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
1102 static const char TXT1
[] = "\xC" "First String" "\xD" "Second String" "\xC" "Third String";
1103 static const char TXT2
[] = "\xD" "Fourth String" "\xC" "Fifth String" "\xC" "Sixth String";
1104 printf("Registering Service Test._testdualtxt._tcp.local.\n");
1105 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testdualtxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, sizeof(TXT1
)-1, TXT1
, reg_reply
, NULL
);
1106 if (!err
) err
= DNSServiceAddRecord(client
, &record
, 0, kDNSServiceType_TXT
, sizeof(TXT2
)-1, TXT2
, 0);
1111 pid_t pid
= getpid();
1112 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
1113 static const char TXT
[] = "\x09" "Test Data";
1114 printf("Registering Service Test._testtxt._tcp.local.\n");
1115 err
= DNSServiceRegister(&client
, 0, opinterface
, "Test", "_testtxt._tcp.", "", NULL
, registerPort
.NotAnInteger
, 0, NULL
, reg_reply
, NULL
);
1116 if (!err
) err
= DNSServiceUpdateRecord(client
, NULL
, 0, sizeof(TXT
)-1, TXT
, 0);
1122 if (argc
== opi
) // If no arguments, just fetch IP address
1123 err
= DNSServiceNATPortMappingCreate(&client
, 0, 0, 0, 0, 0, 0, port_mapping_create_reply
, NULL
);
1124 else if (argc
>= opi
+2 && atoi(argv
[opi
+0]) == 0)
1126 DNSServiceProtocol prot
= GetProtocol(argv
[opi
+0]); // Must specify TCP or UDP
1127 uint16_t IntPortAsNumber
= atoi(argv
[opi
+1]); // Must specify internal port
1128 uint16_t ExtPortAsNumber
= (argc
< opi
+3) ? 0 : atoi(argv
[opi
+2]); // Optional desired external port
1129 uint32_t ttl
= (argc
< opi
+4) ? 0 : atoi(argv
[opi
+3]); // Optional desired lease lifetime
1130 Opaque16 intp
= { { IntPortAsNumber
>> 8, IntPortAsNumber
& 0xFF } };
1131 Opaque16 extp
= { { ExtPortAsNumber
>> 8, ExtPortAsNumber
& 0xFF } };
1132 err
= DNSServiceNATPortMappingCreate(&client
, 0, 0, prot
, intp
.NotAnInteger
, extp
.NotAnInteger
, ttl
, port_mapping_create_reply
, NULL
);
1139 #if HAS_ADDRINFO_API
1141 if (argc
!= opi
+2) goto Fail
;
1142 else err
= DNSServiceGetAddrInfo(&client
, kDNSServiceFlagsReturnIntermediates
, opinterface
, GetProtocol(argv
[opi
+0]), argv
[opi
+1], addrinfo_reply
, NULL
);
1148 Opaque16 registerPort
= { { 0x23, 0x45 } };
1149 unsigned char txtrec
[16] = "\xF" "/path=test.html";
1151 unsigned char nulrec
[4] = "1234";
1153 err
= DNSServiceCreateConnection(&client
);
1154 if (err
) { fprintf(stderr
, "DNSServiceCreateConnection failed %ld\n", (long int)err
); return (-1); }
1157 err
= DNSServiceBrowse(&sc1
, kDNSServiceFlagsShareConnection
, opinterface
, "_http._tcp", "", browse_reply
, NULL
);
1158 if (err
) { fprintf(stderr
, "DNSServiceBrowse _http._tcp failed %ld\n", (long int)err
); return (-1); }
1161 err
= DNSServiceBrowse(&sc2
, kDNSServiceFlagsShareConnection
, opinterface
, "_ftp._tcp", "", browse_reply
, NULL
);
1162 if (err
) { fprintf(stderr
, "DNSServiceBrowse _ftp._tcp failed %ld\n", (long int)err
); return (-1); }
1165 err
= DNSServiceRegister(&sc3
, kDNSServiceFlagsShareConnection
, opinterface
, "kDNSServiceFlagsShareConnection",
1166 "_http._tcp", "local", NULL
, registerPort
.NotAnInteger
, 0, NULL
, reg_reply
, NULL
);
1167 if (err
) { fprintf(stderr
, "SharedConnection DNSServiceRegister failed %ld\n", (long int)err
); return (-1); }
1169 err
= DNSServiceUpdateRecord(sc3
, NULL
, 0, sizeof(txtrec
), txtrec
, 0);
1170 if (err
) { fprintf(stderr
, "SharedConnection DNSServiceUpdateRecord failed %ld\n", (long int)err
); return (-1); }
1172 err
= DNSServiceAddRecord(sc3
, &rec
, 0, kDNSServiceType_NULL
, sizeof(nulrec
), nulrec
, 0);
1173 if (err
) { fprintf(stderr
, "SharedConnection DNSServiceAddRecord failed %ld\n", (long int)err
); return (-1); }
1175 err
= DNSServiceRemoveRecord(sc3
, rec
, 0);
1176 if (err
) { fprintf(stderr
, "SharedConnection DNSServiceRemoveRecord failed %ld\n", (long int)err
); return (-1); }
1183 uint32_t size
= sizeof(v
);
1184 err
= DNSServiceGetProperty(kDNSServiceProperty_DaemonVersion
, &v
, &size
);
1185 if (err
) fprintf(stderr
, "DNSServiceGetProperty failed %ld\n", (long int)err
);
1186 else printf("Currently running daemon (system service) is version %d.%d\n", v
/ 10000, v
/ 100 % 100);
1193 if (!client
|| err
!= kDNSServiceErr_NoError
) { fprintf(stderr
, "DNSService call failed %ld\n", (long int)err
); return (-1); }
1196 // Be sure to deallocate the DNSServiceRef when you're finished
1197 if (client
) DNSServiceRefDeallocate(client
);
1198 if (client_pa
) DNSServiceRefDeallocate(client_pa
);
1202 fprintf(stderr
, "%s -E (Enumerate recommended registration domains)\n", a0
);
1203 fprintf(stderr
, "%s -F (Enumerate recommended browsing domains)\n", a0
);
1204 fprintf(stderr
, "%s -B <Type> <Domain> (Browse for services instances)\n", a0
);
1205 fprintf(stderr
, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", a0
);
1206 fprintf(stderr
, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", a0
);
1207 fprintf(stderr
, "%s -P <Name> <Type> <Domain> <Port> <Host> <IP> [<TXT>...] (Proxy)\n", a0
);
1208 fprintf(stderr
, "%s -Z <Type> <Domain> (Output results in Zone File format)\n", a0
);
1209 fprintf(stderr
, "%s -Q <FQDN> <rrtype> <rrclass> (Generic query for any record type)\n", a0
);
1210 fprintf(stderr
, "%s -C <FQDN> <rrtype> <rrclass> (Query; reconfirming each result)\n", a0
);
1212 fprintf(stderr
, "%s -X udp/tcp/udptcp <IntPort> <ExtPort> <TTL> (NAT Port Mapping)\n", a0
);
1214 #if HAS_ADDRINFO_API
1215 fprintf(stderr
, "%s -G v4/v6/v4v6 <Hostname> (Get address information for hostname)\n", a0
);
1217 fprintf(stderr
, "%s -V (Get version of currently running daemon / system service)\n", a0
);
1219 fprintf(stderr
, "%s -A (Test Adding/Updating/Deleting a record)\n", a0
);
1220 fprintf(stderr
, "%s -U (Test updating a TXT record)\n", a0
);
1221 fprintf(stderr
, "%s -N (Test adding a large NULL record)\n", a0
);
1222 fprintf(stderr
, "%s -T (Test creating a large TXT record)\n", a0
);
1223 fprintf(stderr
, "%s -M (Test creating a registration with multiple TXT records)\n", a0
);
1224 fprintf(stderr
, "%s -I (Test registering and then immediately updating TXT record)\n", a0
);
1225 fprintf(stderr
, "%s -S (Test multiple operations on a shared socket)\n", a0
);
1229 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
1230 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
1231 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
1232 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
1233 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
1235 // NOT static -- otherwise the compiler may optimize it out
1236 // The "@(#) " pattern is a special prefix the "what" command looks for
1237 const char VersionString_SCCS
[] = "@(#) dns-sd " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";
1239 #if _BUILDING_XCODE_PROJECT_
1240 // If the process crashes, then this string will be magically included in the automatically-generated crash log
1241 const char *__crashreporter_info__
= VersionString_SCCS
+ 5;
1242 asm(".desc ___crashreporter_info__, 0x10");