1 /* -*- Mode: C; tab-width: 4 -*-
3 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
18 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
19 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
20 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
21 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
22 * therefore common sense dictates that if they are part of a compound statement then they
23 * should be indented to the same level as everything else in that compound statement.
24 * Indenting curly braces at the same level as the "if" implies that curly braces are
25 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
26 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
27 * understand why variable y is not of type "char*" just proves the point that poor code
28 * layout leads people to unfortunate misunderstandings about how the C language really works.)
30 Change History (most recent first):
32 $Log: SamplemDNSClient.c,v $
33 Revision 1.53 2007/09/18 19:09:02 cheshire
34 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
36 Revision 1.52 2007/03/06 22:45:52 cheshire
38 <rdar://problem/4138615> argv buffer overflow issues
40 Revision 1.51 2007/02/13 18:56:45 cheshire
41 <rdar://problem/4993485> Mach mDNS tool inconsistent with UDS-based dns-sd tool
42 (missing domain should mean "system default(s)", not "local")
44 Revision 1.50 2007/01/05 08:30:47 cheshire
45 Trim excessive "$Log" checkin history from before 2006
46 (checkin history still available via "cvs log ..." of course)
48 Revision 1.49 2007/01/04 21:54:49 cheshire
49 Fix compile warnings related to the deprecated Mach-based API
51 Revision 1.48 2006/08/14 23:24:39 cheshire
52 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
54 Revision 1.47 2006/01/10 02:29:22 cheshire
55 <rdar://problem/4403861> Cosmetic IPv6 address display problem in mDNS test tool
61 #include <arpa/nameser.h>
62 #include <arpa/inet.h>
64 #include <CoreFoundation/CoreFoundation.h>
66 // We already know this tool is using the old deprecated API (that's its purpose)
67 // Since we compile with all warnings treated as errors, we have to turn off the warnings here or the project won't compile
68 #include <AvailabilityMacros.h>
69 #undef AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
70 #define AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
71 #undef AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3
72 #define AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3
74 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
76 //*************************************************************************************************************
79 typedef union { unsigned char b
[2]; unsigned short NotAnInteger
; } Opaque16
;
81 static char operation
;
82 static dns_service_discovery_ref client
= NULL
;
83 static int num_printed
;
84 static char addtest
= 0;
85 static DNSRecordReference record
;
86 static char myhinfo9
[11] = "\003Mac\006OS 9.2";
87 static char myhinfoX
[ 9] = "\003Mac\004OS X";
88 static char updatetest
[3] = "\002AA";
89 static char bigNULL
[4096];
91 //*************************************************************************************************************
92 // Supporting Utility Functions
94 // This code takes care of:
95 // 1. Extracting the mach_port_t from the dns_service_discovery_ref
96 // 2. Making a CFMachPortRef from it
97 // 3. Making a CFRunLoopSourceRef from that
98 // 4. Adding that source to the current RunLoop
99 // 5. and passing the resulting messages back to DNSServiceDiscovery_handleReply() for processing
101 // Code that's not based around a CFRunLoop will need its own mechanism to receive Mach messages
102 // from the mDNSResponder daemon and pass them to the DNSServiceDiscovery_handleReply() routine.
103 // (There is no way to automate this, because it varies depending on the application's existing
104 // event handling model.)
106 static void MyHandleMachMessage(CFMachPortRef port
, void *msg
, CFIndex size
, void *info
)
108 (void)port
; // Unused
109 (void)size
; // Unused
110 (void)info
; // Unused
111 DNSServiceDiscovery_handleReply(msg
);
114 static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref client
)
116 mach_port_t port
= DNSServiceDiscoveryMachPort(client
);
121 CFMachPortContext context
= { 0, 0, NULL
, NULL
, NULL
};
122 Boolean shouldFreeInfo
;
123 CFMachPortRef cfMachPort
= CFMachPortCreateWithPort(kCFAllocatorDefault
, port
, MyHandleMachMessage
, &context
, &shouldFreeInfo
);
124 CFRunLoopSourceRef rls
= CFMachPortCreateRunLoopSource(NULL
, cfMachPort
, 0);
125 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls
, kCFRunLoopDefaultMode
);
131 //*************************************************************************************************************
132 // Sample callback functions for each of the operation types
134 static void printtimestamp(void)
138 gettimeofday(&tv
, NULL
);
139 localtime_r((time_t*)&tv
.tv_sec
, &tm
);
140 printf("%2d:%02d:%02d.%03d ", tm
.tm_hour
, tm
.tm_min
, tm
.tm_sec
, tv
.tv_usec
/1000);
143 #define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain ? "Added" : \
144 (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" : \
145 (X) == DNSServiceDomainEnumerationReplyRemoveDomain ? "Removed" : "Unknown")
147 static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType
, const char *replyDomain
,
148 DNSServiceDiscoveryReplyFlags flags
, void *context
)
150 (void)context
; // Unused
152 printf("Recommended Registration Domain %s %s", replyDomain
, DomainMsg(resultType
));
153 if (flags
) printf(" Flags: %X", flags
);
157 static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType
, const char *replyDomain
,
158 DNSServiceDiscoveryReplyFlags flags
, void *context
)
160 (void)context
; // Unused
162 printf("Recommended Browsing Domain %s %s", replyDomain
, DomainMsg(resultType
));
163 if (flags
) printf(" Flags: %X", flags
);
167 static void browse_reply(DNSServiceBrowserReplyResultType resultType
,
168 const char *replyName
, const char *replyType
, const char *replyDomain
, DNSServiceDiscoveryReplyFlags flags
, void *context
)
170 char *op
= (resultType
== DNSServiceBrowserReplyAddInstance
) ? "Add" : "Rmv";
171 (void)context
; // Unused
172 if (num_printed
++ == 0) printf("Timestamp A/R Flags %-24s %-24s %s\n", "Domain", "Service Type", "Instance Name");
174 printf("%s%6X %-24s %-24s %s\n", op
, flags
, replyDomain
, replyType
, replyName
);
177 static void resolve_reply(struct sockaddr
*interface
, struct sockaddr
*address
, const char *txtRecord
, DNSServiceDiscoveryReplyFlags flags
, void *context
)
179 (void)interface
; // Unused
180 (void)context
; // Unused
181 if (address
->sa_family
!= AF_INET
&& address
->sa_family
!= AF_INET6
)
182 printf("Unknown address family %d\n", address
->sa_family
);
185 const char *src
= txtRecord
;
188 if (address
->sa_family
== AF_INET
)
190 struct sockaddr_in
*ip
= (struct sockaddr_in
*)address
;
191 union { uint32_t l
; u_char b
[4]; } addr
= { ip
->sin_addr
.s_addr
};
192 union { uint16_t s
; u_char b
[2]; } port
= { ip
->sin_port
};
193 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
195 sprintf(ipstring
, "%d.%d.%d.%d", addr
.b
[0], addr
.b
[1], addr
.b
[2], addr
.b
[3]);
196 printf("Service can be reached at %-15s:%u", ipstring
, PortAsNumber
);
198 else if (address
->sa_family
== AF_INET6
)
200 struct sockaddr_in6
*ip6
= (struct sockaddr_in6
*)address
;
201 u_int8_t
*b
= ip6
->sin6_addr
.__u6_addr
.__u6_addr8
;
202 union { uint16_t s
; u_char b
[2]; } port
= { ip6
->sin6_port
};
203 uint16_t PortAsNumber
= ((uint16_t)port
.b
[0]) << 8 | port
.b
[1];
205 char ifname
[IF_NAMESIZE
+ 1] = "";
206 sprintf(ipstring
, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
207 b
[0x0], b
[0x1], b
[0x2], b
[0x3], b
[0x4], b
[0x5], b
[0x6], b
[0x7],
208 b
[0x8], b
[0x9], b
[0xA], b
[0xB], b
[0xC], b
[0xD], b
[0xE], b
[0xF]);
209 if (ip6
->sin6_scope_id
) { ifname
[0] = '%'; if_indextoname(ip6
->sin6_scope_id
, &ifname
[1]); }
210 printf("%s%s:%u", ipstring
, ifname
, PortAsNumber
);
212 if (flags
) printf(" Flags: %X", flags
);
215 char txtInfo
[64]; // Display at most first 64 characters of TXT record
217 const char *const lim
= &txtInfo
[sizeof(txtInfo
)];
218 while (*src
&& dst
< lim
-1)
220 if (*src
== '\\') *dst
++ = '\\'; // '\' displays as "\\"
221 if (*src
>= ' ') *dst
++ = *src
++; // Display normal characters as-is
224 *dst
++ = '\\'; // Display a backslash
225 if (*src
== 1) *dst
++ = ' '; // String boundary displayed as "\ "
226 else // Other chararacters displayed as "\0xHH"
228 static const char hexchars
[16] = "0123456789ABCDEF";
231 *dst
++ = hexchars
[*src
>> 4];
232 *dst
++ = hexchars
[*src
& 0xF];
238 printf(" TXT %s", txtInfo
);
244 static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer
, void *info
)
246 (void)timer
; // Parameter not used
247 (void)info
; // Parameter not used
255 case 0: printf("Adding Test HINFO record\n");
256 record
= DNSServiceRegistrationAddRecord(client
, T_HINFO
, sizeof(myhinfo9
), &myhinfo9
[0], 120);
259 case 1: printf("Updating Test HINFO record\n");
260 DNSServiceRegistrationUpdateRecord(client
, record
, sizeof(myhinfoX
), &myhinfoX
[0], 120);
263 case 2: printf("Removing Test HINFO record\n");
264 DNSServiceRegistrationRemoveRecord(client
, record
);
273 if (updatetest
[1] != 'Z') updatetest
[1]++;
274 else updatetest
[1] = 'A';
275 updatetest
[0] = 3 - updatetest
[0];
276 updatetest
[2] = updatetest
[1];
277 printf("Updating Test TXT record to %c\n", updatetest
[1]);
278 DNSServiceRegistrationUpdateRecord(client
, 0, 1+updatetest
[0], &updatetest
[0], 120);
284 printf("Adding big NULL record\n");
285 DNSServiceRegistrationAddRecord(client
, T_NULL
, sizeof(bigNULL
), &bigNULL
[0], 120);
286 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
292 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode
, void *context
)
294 (void)context
; // Unused
295 printf("Got a reply from the server: ");
298 case kDNSServiceDiscoveryNoError
: printf("Name now registered and active\n"); break;
299 case kDNSServiceDiscoveryNameConflict
: printf("Name in use, please choose another\n"); exit(-1);
300 default: printf("Error %d\n", errorCode
); return;
303 if (operation
== 'A' || operation
== 'U' || operation
== 'N')
305 CFRunLoopTimerContext myCFRunLoopTimerContext
= { 0, 0, NULL
, NULL
, NULL
};
306 CFRunLoopTimerRef timer
= CFRunLoopTimerCreate(kCFAllocatorDefault
,
307 CFAbsoluteTimeGetCurrent() + 5.0, 5.0, 0, 1, // Next fire time, periodic interval, flags, and order
308 myCFRunLoopTimerCallBack
, &myCFRunLoopTimerContext
);
309 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer
, kCFRunLoopDefaultMode
);
313 //*************************************************************************************************************
314 // The main test function
316 int main(int argc
, char **argv
)
318 const char *progname
= strrchr(argv
[0], '/') ? strrchr(argv
[0], '/') + 1 : argv
[0];
320 setlinebuf(stdout
); // Want to see lines as they appear, not block buffered
322 if (argc
< 2) goto Fail
; // Minimum command line is the command name and one argument
323 operation
= getopt(argc
, (char * const *)argv
, "EFBLRAUNTMI");
324 if (operation
== -1) goto Fail
;
328 case 'E': printf("Looking for recommended registration domains:\n");
329 client
= DNSServiceDomainEnumerationCreate(1, regdom_reply
, nil
);
332 case 'F': printf("Looking for recommended browsing domains:\n");
333 client
= DNSServiceDomainEnumerationCreate(0, browsedom_reply
, nil
);
336 case 'B': if (argc
< optind
+1) goto Fail
;
337 dom
= (argc
< optind
+2) ? "" : argv
[optind
+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
338 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
339 printf("Browsing for %s%s\n", argv
[optind
+0], dom
);
340 client
= DNSServiceBrowserCreate(argv
[optind
+0], dom
, browse_reply
, nil
);
343 case 'L': if (argc
< optind
+2) goto Fail
;
344 dom
= (argc
< optind
+3) ? "" : argv
[optind
+2];
345 if (dom
[0] == '.' && dom
[1] == 0) dom
= "local"; // We allow '.' on the command line as a synonym for "local"
346 printf("Lookup %s.%s%s\n", argv
[optind
+0], argv
[optind
+1], dom
);
347 client
= DNSServiceResolverResolve(argv
[optind
+0], argv
[optind
+1], dom
, resolve_reply
, nil
);
350 case 'R': if (argc
< optind
+4) goto Fail
;
352 char *nam
= argv
[optind
+0];
353 char *typ
= argv
[optind
+1];
354 char *dom
= argv
[optind
+2];
355 uint16_t PortAsNumber
= atoi(argv
[optind
+3]);
356 Opaque16 registerPort
= { { PortAsNumber
>> 8, PortAsNumber
& 0xFF } };
361 if (nam
[0] == '.' && nam
[1] == 0) nam
[0] = 0; // We allow '.' on the command line as a synonym for empty string
362 if (dom
[0] == '.' && dom
[1] == 0) dom
[0] = 0; // We allow '.' on the command line as a synonym for empty string
364 // Copy all the TXT strings into one C string separated by ASCII-1 delimiters
365 for (i
= optind
+4; i
< argc
; i
++)
367 int len
= strlen(argv
[i
]);
368 if (len
> 255 || ptr
+ len
+ 1 >= txt
+ sizeof(txt
)) break;
369 strcpy(ptr
, argv
[i
]);
373 if (ptr
> txt
) ptr
--;
376 printf("Registering Service %s.%s%s port %s %s\n", nam
, typ
, dom
, argv
[optind
+3], txt
);
377 client
= DNSServiceRegistrationCreate(nam
, typ
, dom
, registerPort
.NotAnInteger
, txt
, reg_reply
, nil
);
384 Opaque16 registerPort
= { { 0x12, 0x34 } };
385 static const char TXT
[] = "First String\001Second String\001Third String";
386 printf("Registering Service Test._testupdate._tcp.local.\n");
387 client
= DNSServiceRegistrationCreate("Test", "_testupdate._tcp.", "", registerPort
.NotAnInteger
, TXT
, reg_reply
, nil
);
392 Opaque16 registerPort
= { { 0x23, 0x45 } };
395 for (i
=0; i
<sizeof(TXT
)-1; i
++)
396 if ((i
& 0x1F) == 0x1F) TXT
[i
] = 1; else TXT
[i
] = 'A' + (i
>> 5);
398 printf("Registering Service Test._testlargetxt._tcp.local.\n");
399 client
= DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort
.NotAnInteger
, TXT
, reg_reply
, nil
);
404 pid_t pid
= getpid();
405 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
406 static const char TXT1
[] = "First String\001Second String\001Third String";
407 static const char TXT2
[] = "\x0D" "Fourth String" "\x0C" "Fifth String" "\x0C" "Sixth String";
408 printf("Registering Service Test._testdualtxt._tcp.local.\n");
409 client
= DNSServiceRegistrationCreate("", "_testdualtxt._tcp.", "", registerPort
.NotAnInteger
, TXT1
, reg_reply
, nil
);
410 // use "sizeof(TXT2)-1" because we don't wan't the C compiler's null byte on the end of the string
411 record
= DNSServiceRegistrationAddRecord(client
, T_TXT
, sizeof(TXT2
)-1, TXT2
, 120);
416 pid_t pid
= getpid();
417 Opaque16 registerPort
= { { pid
>> 8, pid
& 0xFF } };
418 static const char TXT
[] = "\x09" "Test Data";
419 printf("Registering Service Test._testtxt._tcp.local.\n");
420 client
= DNSServiceRegistrationCreate("", "_testtxt._tcp.", "", registerPort
.NotAnInteger
, "", reg_reply
, nil
);
421 if (client
) DNSServiceRegistrationUpdateRecord(client
, 0, 1+TXT
[0], &TXT
[0], 120);
428 if (!client
) { fprintf(stderr
, "DNSService call failed\n"); return (-1); }
429 if (AddDNSServiceClientToRunLoop(client
) != 0) { fprintf(stderr
, "AddDNSServiceClientToRunLoop failed\n"); return (-1); }
430 printf("Talking to DNS SD Daemon at Mach port %d\n", DNSServiceDiscoveryMachPort(client
));
433 // Be sure to deallocate the dns_service_discovery_ref when you're finished
434 // Note: What other cleanup has to be done here?
435 // We should probably invalidate, remove and release our CFRunLoopSourceRef?
436 DNSServiceDiscoveryDeallocate(client
);
442 fprintf(stderr
, "%s -E (Enumerate recommended registration domains)\n", progname
);
443 fprintf(stderr
, "%s -F (Enumerate recommended browsing domains)\n", progname
);
444 fprintf(stderr
, "%s -B <Type> <Domain> (Browse for services instances)\n", progname
);
445 fprintf(stderr
, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", progname
);
446 fprintf(stderr
, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", progname
);
447 fprintf(stderr
, "%s -A (Test Adding/Updating/Deleting a record)\n", progname
);
448 fprintf(stderr
, "%s -U (Test updating a TXT record)\n", progname
);
449 fprintf(stderr
, "%s -N (Test adding a large NULL record)\n", progname
);
450 fprintf(stderr
, "%s -T (Test creating a large TXT record)\n", progname
);
451 fprintf(stderr
, "%s -M (Test creating a registration with multiple TXT records)\n", progname
);
452 fprintf(stderr
, "%s -I (Test registering and then immediately updating TXT record)\n", progname
);
456 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
457 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
458 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
459 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
460 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
462 // NOT static -- otherwise the compiler may optimize it out
463 // The "@(#) " pattern is a special prefix the "what" command looks for
464 const char VersionString_SCCS
[] = "@(#) mDNS " STRINGIFY(mDNSResponderVersion
) " (" __DATE__
" " __TIME__
")";
466 // If the process crashes, then this string will be magically included in the automatically-generated crash log
467 const char *__crashreporter_info__
= VersionString_SCCS
+ 5;
468 asm(".desc ___crashreporter_info__, 0x10");