]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/SamplemDNSClient.c
mDNSResponder-161.1.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / SamplemDNSClient.c
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
4 *
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
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
16 *
17 * Formatting notes:
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.)
29
30 Change History (most recent first):
31
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
35
36 Revision 1.52 2007/03/06 22:45:52 cheshire
37
38 <rdar://problem/4138615> argv buffer overflow issues
39
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")
43
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)
47
48 Revision 1.49 2007/01/04 21:54:49 cheshire
49 Fix compile warnings related to the deprecated Mach-based API
50
51 Revision 1.48 2006/08/14 23:24:39 cheshire
52 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
53
54 Revision 1.47 2006/01/10 02:29:22 cheshire
55 <rdar://problem/4403861> Cosmetic IPv6 address display problem in mDNS test tool
56
57 */
58
59 #include <libc.h>
60 #define BIND_8_COMPAT
61 #include <arpa/nameser.h>
62 #include <arpa/inet.h>
63 #include <net/if.h>
64 #include <CoreFoundation/CoreFoundation.h>
65
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
73
74 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
75
76 //*************************************************************************************************************
77 // Globals
78
79 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
80
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];
90
91 //*************************************************************************************************************
92 // Supporting Utility Functions
93 //
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
100 //
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.)
105
106 static void MyHandleMachMessage(CFMachPortRef port, void *msg, CFIndex size, void *info)
107 {
108 (void)port; // Unused
109 (void)size; // Unused
110 (void)info; // Unused
111 DNSServiceDiscovery_handleReply(msg);
112 }
113
114 static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref client)
115 {
116 mach_port_t port = DNSServiceDiscoveryMachPort(client);
117 if (!port)
118 return(-1);
119 else
120 {
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);
126 CFRelease(rls);
127 return(0);
128 }
129 }
130
131 //*************************************************************************************************************
132 // Sample callback functions for each of the operation types
133
134 static void printtimestamp(void)
135 {
136 struct timeval tv;
137 struct tm tm;
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);
141 }
142
143 #define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain ? "Added" : \
144 (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" : \
145 (X) == DNSServiceDomainEnumerationReplyRemoveDomain ? "Removed" : "Unknown")
146
147 static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
148 DNSServiceDiscoveryReplyFlags flags, void *context)
149 {
150 (void)context; // Unused
151 printtimestamp();
152 printf("Recommended Registration Domain %s %s", replyDomain, DomainMsg(resultType));
153 if (flags) printf(" Flags: %X", flags);
154 printf("\n");
155 }
156
157 static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
158 DNSServiceDiscoveryReplyFlags flags, void *context)
159 {
160 (void)context; // Unused
161 printtimestamp();
162 printf("Recommended Browsing Domain %s %s", replyDomain, DomainMsg(resultType));
163 if (flags) printf(" Flags: %X", flags);
164 printf("\n");
165 }
166
167 static void browse_reply(DNSServiceBrowserReplyResultType resultType,
168 const char *replyName, const char *replyType, const char *replyDomain, DNSServiceDiscoveryReplyFlags flags, void *context)
169 {
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");
173 printtimestamp();
174 printf("%s%6X %-24s %-24s %s\n", op, flags, replyDomain, replyType, replyName);
175 }
176
177 static void resolve_reply(struct sockaddr *interface, struct sockaddr *address, const char *txtRecord, DNSServiceDiscoveryReplyFlags flags, void *context)
178 {
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);
183 else
184 {
185 const char *src = txtRecord;
186 printtimestamp();
187
188 if (address->sa_family == AF_INET)
189 {
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];
194 char ipstring[16];
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);
197 }
198 else if (address->sa_family == AF_INET6)
199 {
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];
204 char ipstring[40];
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);
211 }
212 if (flags) printf(" Flags: %X", flags);
213 if (*src)
214 {
215 char txtInfo[64]; // Display at most first 64 characters of TXT record
216 char *dst = txtInfo;
217 const char *const lim = &txtInfo[sizeof(txtInfo)];
218 while (*src && dst < lim-1)
219 {
220 if (*src == '\\') *dst++ = '\\'; // '\' displays as "\\"
221 if (*src >= ' ') *dst++ = *src++; // Display normal characters as-is
222 else
223 {
224 *dst++ = '\\'; // Display a backslash
225 if (*src == 1) *dst++ = ' '; // String boundary displayed as "\ "
226 else // Other chararacters displayed as "\0xHH"
227 {
228 static const char hexchars[16] = "0123456789ABCDEF";
229 *dst++ = '0';
230 *dst++ = 'x';
231 *dst++ = hexchars[*src >> 4];
232 *dst++ = hexchars[*src & 0xF];
233 }
234 src++;
235 }
236 }
237 *dst++ = 0;
238 printf(" TXT %s", txtInfo);
239 }
240 printf("\n");
241 }
242 }
243
244 static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
245 {
246 (void)timer; // Parameter not used
247 (void)info; // Parameter not used
248
249 switch (operation)
250 {
251 case 'A':
252 {
253 switch (addtest)
254 {
255 case 0: printf("Adding Test HINFO record\n");
256 record = DNSServiceRegistrationAddRecord(client, T_HINFO, sizeof(myhinfo9), &myhinfo9[0], 120);
257 addtest = 1;
258 break;
259 case 1: printf("Updating Test HINFO record\n");
260 DNSServiceRegistrationUpdateRecord(client, record, sizeof(myhinfoX), &myhinfoX[0], 120);
261 addtest = 2;
262 break;
263 case 2: printf("Removing Test HINFO record\n");
264 DNSServiceRegistrationRemoveRecord(client, record);
265 addtest = 0;
266 break;
267 }
268 }
269 break;
270
271 case 'U':
272 {
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);
279 }
280 break;
281
282 case 'N':
283 {
284 printf("Adding big NULL record\n");
285 DNSServiceRegistrationAddRecord(client, T_NULL, sizeof(bigNULL), &bigNULL[0], 120);
286 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
287 }
288 break;
289 }
290 }
291
292 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
293 {
294 (void)context; // Unused
295 printf("Got a reply from the server: ");
296 switch (errorCode)
297 {
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;
301 }
302
303 if (operation == 'A' || operation == 'U' || operation == 'N')
304 {
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);
310 }
311 }
312
313 //*************************************************************************************************************
314 // The main test function
315
316 int main(int argc, char **argv)
317 {
318 const char *progname = strrchr(argv[0], '/') ? strrchr(argv[0], '/') + 1 : argv[0];
319 char *dom;
320 setlinebuf(stdout); // Want to see lines as they appear, not block buffered
321
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;
325
326 switch (operation)
327 {
328 case 'E': printf("Looking for recommended registration domains:\n");
329 client = DNSServiceDomainEnumerationCreate(1, regdom_reply, nil);
330 break;
331
332 case 'F': printf("Looking for recommended browsing domains:\n");
333 client = DNSServiceDomainEnumerationCreate(0, browsedom_reply, nil);
334 break;
335
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);
341 break;
342
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);
348 break;
349
350 case 'R': if (argc < optind+4) goto Fail;
351 {
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 } };
357 char txt[2048];
358 char *ptr = txt;
359 int i;
360
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
363
364 // Copy all the TXT strings into one C string separated by ASCII-1 delimiters
365 for (i = optind+4; i < argc; i++)
366 {
367 int len = strlen(argv[i]);
368 if (len > 255 || ptr + len + 1 >= txt + sizeof(txt)) break;
369 strcpy(ptr, argv[i]);
370 ptr += len;
371 *ptr++ = 1;
372 }
373 if (ptr > txt) ptr--;
374 *ptr = 0;
375
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);
378 break;
379 }
380
381 case 'A':
382 case 'U':
383 case 'N': {
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);
388 break;
389 }
390
391 case 'T': {
392 Opaque16 registerPort = { { 0x23, 0x45 } };
393 char TXT[1000];
394 unsigned int i;
395 for (i=0; i<sizeof(TXT)-1; i++)
396 if ((i & 0x1F) == 0x1F) TXT[i] = 1; else TXT[i] = 'A' + (i >> 5);
397 TXT[i] = 0;
398 printf("Registering Service Test._testlargetxt._tcp.local.\n");
399 client = DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
400 break;
401 }
402
403 case 'M': {
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);
412 break;
413 }
414
415 case 'I': {
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);
422 break;
423 }
424
425 default: goto Exit;
426 }
427
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));
431 CFRunLoopRun();
432
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);
437
438 Exit:
439 return 0;
440
441 Fail:
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);
453 return 0;
454 }
455
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)
461
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__ ")";
465
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");