2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
25 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
26 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
27 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
28 * therefore common sense dictates that if they are part of a compound statement then they
29 * should be indented to the same level as everything else in that compound statement.
30 * Indenting curly braces at the same level as the "if" implies that curly braces are
31 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
32 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
33 * understand why variable y is not of type "char*" just proves the point that poor code
34 * layout leads people to unfortunate misunderstandings about how the C language really works.)
36 Change History (most recent first):
38 $Log: SamplemDNSClient.c,v $
39 Revision 1.47 2006/01/10 02:29:22 cheshire
40 <rdar://problem/4403861> Cosmetic IPv6 address display problem in mDNS test tool
42 Revision 1.46 2004/11/02 01:32:34 cheshire
43 <rdar://problem/3861705> Update code so it still compiles when DNSServiceDiscovery.h is deprecated
45 Revision 1.45 2004/06/15 02:39:47 cheshire
46 When displaying error message, only show command name, not entire path
48 Revision 1.44 2004/05/28 02:20:06 cheshire
49 If we allow dot or empty string for domain when resolving a service,
50 it should be a synonym for "local"
52 Revision 1.43 2004/02/03 22:07:50 cheshire
53 <rdar://problem/3548184>: Widen columns to display non-local domains better
55 Revision 1.42 2003/12/03 11:39:17 cheshire
56 <rdar://problem/3468977> Browse output misaligned in mDNS command-line tool
57 (Also fix it to add leading space when the hours part of the time is only one digit)
59 Revision 1.41 2003/10/30 22:52:57 cheshire
60 <rdar://problem/3468977> Browse output misaligned in mDNS command-line tool
62 Revision 1.40 2003/09/26 01:07:06 cheshire
63 Added test case to test fix for <rdar://problem/3427923>
65 Revision 1.39 2003/08/18 19:05:45 cheshire
66 <rdar://problem/3382423> UpdateRecord not working right
67 Added "newrdlength" field to hold new length of updated rdata
69 Revision 1.38 2003/08/12 19:56:25 cheshire
72 Revision 1.37 2003/08/05 20:39:25 cheshire
73 <rdar://problem/3362184> mDNS buffered std out makes it impossible to use from another tool
74 Added "setlinebuf(stdout);"
76 Revision 1.36 2003/07/19 03:23:13 cheshire
77 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
79 Revision 1.35 2003/07/11 01:57:18 cheshire
80 Add checkin history header
86 #include <arpa/nameser.h>
87 #include <arpa/inet.h>
89 #include <CoreFoundation/CoreFoundation.h>
91 // We already know this tool is using the old deprecated API (that's its purpose)
92 // Since we compile with all warnings treated as errors, we have to turn off the warnings here or the project won't compile
93 #include <AvailabilityMacros.h>
94 #undef AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
95 #define AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
96 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
98 //*************************************************************************************************************
101 typedef union { unsigned char b
[2]; unsigned short NotAnInteger
; } Opaque16
;
103 static char operation
;
104 static dns_service_discovery_ref client
= NULL
;
105 static int num_printed
;
106 static char addtest
= 0;
107 static DNSRecordReference record
;
108 static char myhinfo9
[11] = "\003Mac\006OS 9.2";
109 static char myhinfoX
[ 9] = "\003Mac\004OS X";
110 static char updatetest
[3] = "\002AA";
111 static char bigNULL
[4096];
113 //*************************************************************************************************************
114 // Supporting Utility Functions
116 // This code takes care of:
117 // 1. Extracting the mach_port_t from the dns_service_discovery_ref
118 // 2. Making a CFMachPortRef from it
119 // 3. Making a CFRunLoopSourceRef from that
120 // 4. Adding that source to the current RunLoop
121 // 5. and passing the resulting messages back to DNSServiceDiscovery_handleReply() for processing
123 // Code that's not based around a CFRunLoop will need its own mechanism to receive Mach messages
124 // from the mDNSResponder daemon and pass them to the DNSServiceDiscovery_handleReply() routine.
125 // (There is no way to automate this, because it varies depending on the application's existing
126 // event handling model.)
128 static void MyHandleMachMessage(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
130 (void)port
; // Unused
131 (void)size
; // Unused
132 (void)info
; // Unused
133 DNSServiceDiscovery_handleReply(msg
);
136 static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref client
)
138 mach_port_t port
= DNSServiceDiscoveryMachPort(client
);
143 CFMachPortContext context
= { 0, 0, NULL
, NULL
, NULL
};
144 Boolean shouldFreeInfo
;
145 CFMachPortRef cfMachPort
= CFMachPortCreateWithPort(kCFAllocatorDefault
, port
, MyHandleMachMessage
, &context
, &shouldFreeInfo
);
146 CFRunLoopSourceRef rls
= CFMachPortCreateRunLoopSource(NULL
, cfMachPort
, 0);
147 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls
, kCFRunLoopDefaultMode
);
153 //*************************************************************************************************************
154 // Sample callback functions for each of the operation types
156 static void printtimestamp(void)
160 gettimeofday(&tv
, NULL
);
161 localtime_r((time_t*)&tv
.tv_sec
, &tm
);
162 printf("%2d:%02d:%02d.%03d ", tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, tv
.tv_usec
/1000);
165 #define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain ? "Added" : \
166 (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" : \
167 (X) == DNSServiceDomainEnumerationReplyRemoveDomain ? "Removed" : "Unknown")
169 static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType
, const char *replyDomain
,
170 DNSServiceDiscoveryReplyFlags flags
, void *context
)
172 (void)context
; // Unused
174 printf("Recommended Registration Domain %s %s", replyDomain
, DomainMsg(resultType
));
175 if (flags
) printf(" Flags: %X", flags
);
179 static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType
, const char *replyDomain
,
180 DNSServiceDiscoveryReplyFlags flags
, void *context
)
182 (void)context
; // Unused
184 printf("Recommended Browsing Domain %s %s", replyDomain
, DomainMsg(resultType
));
185 if (flags
) printf(" Flags: %X", flags
);
189 static void browse_reply(DNSServiceBrowserReplyResultType resultType
,
190 const char *replyName
, const char *replyType
, const char *replyDomain
, DNSServiceDiscoveryReplyFlags flags
, void *context
)
192 char *op
= (resultType
== DNSServiceBrowserReplyAddInstance
) ? "Add" : "Rmv";
193 (void)context
; // Unused
194 if (num_printed
++ == 0) printf("Timestamp A/R Flags %-24s %-24s %s\n", "Domain", "Service Type", "Instance Name");
196 printf("%s%6X %-24s %-24s %s\n", op
, flags
, replyDomain
, replyType
, replyName
);
199 static void resolve_reply(struct sockaddr
*interface
, struct sockaddr
*address
, const char *txtRecord
, DNSServiceDiscoveryReplyFlags flags
, void *context
)
201 (void)interface
; // Unused
202 (void)context
; // Unused
203 if (address
->sa_family
!= AF_INET
&& address
->sa_family
!= AF_INET6
)
204 printf("Unknown address family %d\n", address
->sa_family
);
207 const char *src
= txtRecord
;
210 if (address
->sa_family
== AF_INET
)
212 struct sockaddr_in
*ip
= (struct sockaddr_in
*)address
;
213 union { uint32_t l
; u_char b
[4]; } addr
= { ip
->sin_addr
.s_addr
};
214 union { uint16_t s
; u_char b
[2]; } port
= { ip
->sin_port
};
215 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
217 sprintf(ipstring
, "%d.%d.%d.%d", addr
.b
[0], addr
.b
[1], addr
.b
[2], addr
.b
[3]);
218 printf("Service can be reached at %-15s:%u", ipstring
, PortAsNumber
);
220 else if (address
->sa_family
== AF_INET6
)
222 struct sockaddr_in6
*ip6
= (struct sockaddr_in6
*)address
;
223 u_int8_t
*b
= ip6
->sin6_addr
.__u6_addr
.__u6_addr8
;
224 union { uint16_t s
; u_char b
[2]; } port
= { ip6
->sin6_port
};
225 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
227 char ifname
[IF_NAMESIZE
+ 1] = "";
228 sprintf(ipstring
, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
229 b
[0x0], b
[0x1], b
[0x2], b
[0x3], b
[0x4], b
[0x5], b
[0x6], b
[0x7],
230 b
[0x8], b
[0x9], b
[0xA], b
[0xB], b
[0xC], b
[0xD], b
[0xE], b
[0xF]);
231 if (ip6
->sin6_scope_id
) { ifname
[0] = '%'; if_indextoname(ip6
->sin6_scope_id
, &ifname
[1]); }
232 printf("%s%s:%u", ipstring
, ifname
, PortAsNumber
);
234 if (flags
) printf(" Flags: %X", flags
);
237 char txtInfo
[64]; // Display at most first 64 characters of TXT record
239 const char *const lim
= &txtInfo
[sizeof(txtInfo
)];
240 while (*src
&& dst
< lim
-1)
242 if (*src
== '\\') *dst
++ = '\\'; // '\' displays as "\\"
243 if (*src
>= ' ') *dst
++ = *src
++; // Display normal characters as-is
246 *dst
++ = '\\'; // Display a backslash
247 if (*src
== 1) *dst
++ = ' '; // String boundary displayed as "\ "
248 else // Other chararacters displayed as "\0xHH"
250 static const char hexchars
[16] = "0123456789ABCDEF";
253 *dst
++ = hexchars
[*src
>> 4];
254 *dst
++ = hexchars
[*src
& 0xF];
260 printf(" TXT %s", txtInfo
);
266 static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer
, void *info
)
268 (void)timer
; // Parameter not used
269 (void)info
; // Parameter not used
277 case 0: printf("Adding Test HINFO record\n");
278 record
= DNSServiceRegistrationAddRecord(client
, T_HINFO
, sizeof(myhinfo9
), &myhinfo9
[0], 120);
281 case 1: printf("Updating Test HINFO record\n");
282 DNSServiceRegistrationUpdateRecord(client
, record
, sizeof(myhinfoX
), &myhinfoX
[0], 120);
285 case 2: printf("Removing Test HINFO record\n");
286 DNSServiceRegistrationRemoveRecord(client
, record
);
295 if (updatetest
[1] != 'Z') updatetest
[1]++;
296 else updatetest
[1] = 'A';
297 updatetest
[0] = 3 - updatetest
[0];
298 updatetest
[2] = updatetest
[1];
299 printf("Updating Test TXT record to %c\n", updatetest
[1]);
300 DNSServiceRegistrationUpdateRecord(client
, 0, 1+updatetest
[0], &updatetest
[0], 120);
306 printf("Adding big NULL record\n");
307 DNSServiceRegistrationAddRecord(client
, T_NULL
, sizeof(bigNULL
), &bigNULL
[0], 120);
308 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
314 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode
, void *context
)
316 (void)context
; // Unused
317 printf("Got a reply from the server: ");
320 case kDNSServiceDiscoveryNoError
: printf("Name now registered and active\n"); break;
321 case kDNSServiceDiscoveryNameConflict
: printf("Name in use, please choose another\n"); exit(-1);
322 default: printf("Error %d\n", errorCode
); return;
325 if (operation
== 'A' || operation
== 'U' || operation
== 'N')
327 CFRunLoopTimerContext myCFRunLoopTimerContext
= { 0, 0, NULL
, NULL
, NULL
};
328 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(kCFAllocatorDefault
,
329 CFAbsoluteTimeGetCurrent() + 5.0, 5.0, 0, 1, // Next fire time, periodic interval, flags, and order
330 myCFRunLoopTimerCallBack
, &myCFRunLoopTimerContext
);
331 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
335 //*************************************************************************************************************
336 // The main test function
338 int main(int argc
, char **argv
)
340 const char *progname
= strrchr(argv
[0], '/') ? strrchr(argv
[0], '/') + 1 : argv
[0];
342 setlinebuf(stdout
); // Want to see lines as they appear, not block buffered
344 if (argc
< 2) goto Fail
; // Minimum command line is the command name and one argument
345 operation
= getopt(argc
, (char * const *)argv
, "EFBLRAUNTMI");
346 if (operation
== -1) goto Fail
;
350 case 'E': printf("Looking for recommended registration domains:\n");
351 client
= DNSServiceDomainEnumerationCreate(1, regdom_reply
, nil
);
354 case 'F': printf("Looking for recommended browsing domains:\n");
355 client
= DNSServiceDomainEnumerationCreate(0, browsedom_reply
, nil
);
358 case 'B': if (argc
< optind
+1) goto Fail
;
359 dom
= (argc
< optind
+2) ? "local" : argv
[optind
+1];
360 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
361 printf("Browsing for %s%s\n", argv
[optind
+0], dom
);
362 client
= DNSServiceBrowserCreate(argv
[optind
+0], dom
, browse_reply
, nil
);
365 case 'L': if (argc
< optind
+2) goto Fail
;
366 dom
= (argc
< optind
+3) ? "" : argv
[optind
+2];
367 if (dom
[0] == '.' && dom
[1] == 0) dom
= "local"; // We allow '.' on the command line as a synonym for "local"
368 printf("Lookup %s.%s%s\n", argv
[optind
+0], argv
[optind
+1], dom
);
369 client
= DNSServiceResolverResolve(argv
[optind
+0], argv
[optind
+1], dom
, resolve_reply
, nil
);
372 case 'R': if (argc
< optind
+4) goto Fail
;
374 char *nam
= argv
[optind
+0];
375 char *typ
= argv
[optind
+1];
376 char *dom
= argv
[optind
+2];
377 uint16_t PortAsNumber
= atoi(argv
[optind
+3]);
378 Opaque16 registerPort
= { { PortAsNumber
>> 8, PortAsNumber
& 0xFF } };
383 if (nam
[0] == '.' && nam
[1] == 0) nam
[0] = 0; // We allow '.' on the command line as a synonym for empty string
384 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
386 // Copy all the TXT strings into one C string separated by ASCII-1 delimiters
387 for (i
= optind
+4; i
< argc
; i
++)
389 strcpy(ptr
, argv
[i
]);
390 ptr
+= strlen(argv
[i
]);
393 if (ptr
> txt
) ptr
--;
396 printf("Registering Service %s.%s%s port %s %s\n", nam
, typ
, dom
, argv
[optind
+3], txt
);
397 client
= DNSServiceRegistrationCreate(nam
, typ
, dom
, registerPort
.NotAnInteger
, txt
, reg_reply
, nil
);
404 Opaque16 registerPort
= { { 0x12, 0x34 } };
405 static const char TXT
[] = "First String\001Second String\001Third String";
406 printf("Registering Service Test._testupdate._tcp.local.\n");
407 client
= DNSServiceRegistrationCreate("Test", "_testupdate._tcp.", "", registerPort
.NotAnInteger
, TXT
, reg_reply
, nil
);
412 Opaque16 registerPort
= { { 0x23, 0x45 } };
415 for (i
=0; i
<sizeof(TXT
)-1; i
++)
416 if ((i
& 0x1F) == 0x1F) TXT
[i
] = 1; else TXT
[i
] = 'A' + (i
>> 5);
418 printf("Registering Service Test._testlargetxt._tcp.local.\n");
419 client
= DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort
.NotAnInteger
, TXT
, reg_reply
, nil
);
424 pid_t pid
= getpid();
425 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
426 static const char TXT1
[] = "First String\001Second String\001Third String";
427 static const char TXT2
[] = "\x0D" "Fourth String" "\x0C" "Fifth String" "\x0C" "Sixth String";
428 printf("Registering Service Test._testdualtxt._tcp.local.\n");
429 client
= DNSServiceRegistrationCreate("", "_testdualtxt._tcp.", "", registerPort
.NotAnInteger
, TXT1
, reg_reply
, nil
);
430 // use "sizeof(TXT2)-1" because we don't wan't the C compiler's null byte on the end of the string
431 record
= DNSServiceRegistrationAddRecord(client
, T_TXT
, sizeof(TXT2
)-1, TXT2
, 120);
436 pid_t pid
= getpid();
437 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
438 static const char TXT
[] = "\x09" "Test Data";
439 printf("Registering Service Test._testtxt._tcp.local.\n");
440 client
= DNSServiceRegistrationCreate("", "_testtxt._tcp.", "", registerPort
.NotAnInteger
, "", reg_reply
, nil
);
441 if (client
) DNSServiceRegistrationUpdateRecord(client
, 0, 1+TXT
[0], &TXT
[0], 120);
448 if (!client
) { fprintf(stderr
, "DNSService call failed\n"); return (-1); }
449 if (AddDNSServiceClientToRunLoop(client
) != 0) { fprintf(stderr
, "AddDNSServiceClientToRunLoop failed\n"); return (-1); }
450 printf("Talking to DNS SD Daemon at Mach port %d\n", DNSServiceDiscoveryMachPort(client
));
453 // Be sure to deallocate the dns_service_discovery_ref when you're finished
454 // Note: What other cleanup has to be done here?
455 // We should probably invalidate, remove and release our CFRunLoopSourceRef?
456 DNSServiceDiscoveryDeallocate(client
);
462 fprintf(stderr
, "%s -E (Enumerate recommended registration domains)\n", progname
);
463 fprintf(stderr
, "%s -F (Enumerate recommended browsing domains)\n", progname
);
464 fprintf(stderr
, "%s -B <Type> <Domain> (Browse for services instances)\n", progname
);
465 fprintf(stderr
, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", progname
);
466 fprintf(stderr
, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", progname
);
467 fprintf(stderr
, "%s -A (Test Adding/Updating/Deleting a record)\n", progname
);
468 fprintf(stderr
, "%s -U (Test updating a TXT record)\n", progname
);
469 fprintf(stderr
, "%s -N (Test adding a large NULL record)\n", progname
);
470 fprintf(stderr
, "%s -T (Test creating a large TXT record)\n", progname
);
471 fprintf(stderr
, "%s -M (Test creating a registration with multiple TXT records)\n", progname
);
472 fprintf(stderr
, "%s -I (Test registering and then immediately updating TXT record)\n", progname
);