]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/SamplemDNSClient.c
mDNSResponder-176.3.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.54 2007/11/30 23:39:55 cheshire
34 Fixed compile warning: declaration of 'client' shadows a global declaration
35
36 Revision 1.53 2007/09/18 19:09:02 cheshire
37 <rdar://problem/5489549> mDNSResponderHelper (and other binaries) missing SCCS version strings
38
39 Revision 1.52 2007/03/06 22:45:52 cheshire
40
41 <rdar://problem/4138615> argv buffer overflow issues
42
43 Revision 1.51 2007/02/13 18:56:45 cheshire
44 <rdar://problem/4993485> Mach mDNS tool inconsistent with UDS-based dns-sd tool
45 (missing domain should mean "system default(s)", not "local")
46
47 Revision 1.50 2007/01/05 08:30:47 cheshire
48 Trim excessive "$Log" checkin history from before 2006
49 (checkin history still available via "cvs log ..." of course)
50
51 Revision 1.49 2007/01/04 21:54:49 cheshire
52 Fix compile warnings related to the deprecated Mach-based API
53
54 Revision 1.48 2006/08/14 23:24:39 cheshire
55 Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
56
57 Revision 1.47 2006/01/10 02:29:22 cheshire
58 <rdar://problem/4403861> Cosmetic IPv6 address display problem in mDNS test tool
59
60 */
61
62 #include <libc.h>
63 #define BIND_8_COMPAT
64 #include <arpa/nameser.h>
65 #include <arpa/inet.h>
66 #include <net/if.h>
67 #include <CoreFoundation/CoreFoundation.h>
68
69 // We already know this tool is using the old deprecated API (that's its purpose)
70 // Since we compile with all warnings treated as errors, we have to turn off the warnings here or the project won't compile
71 #include <AvailabilityMacros.h>
72 #undef AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
73 #define AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED
74 #undef AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3
75 #define AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3
76
77 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
78
79 //*************************************************************************************************************
80 // Globals
81
82 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
83
84 static char operation;
85 static dns_service_discovery_ref client = NULL;
86 static int num_printed;
87 static char addtest = 0;
88 static DNSRecordReference record;
89 static char myhinfo9[11] = "\003Mac\006OS 9.2";
90 static char myhinfoX[ 9] = "\003Mac\004OS X";
91 static char updatetest[3] = "\002AA";
92 static char bigNULL[4096];
93
94 //*************************************************************************************************************
95 // Supporting Utility Functions
96 //
97 // This code takes care of:
98 // 1. Extracting the mach_port_t from the dns_service_discovery_ref
99 // 2. Making a CFMachPortRef from it
100 // 3. Making a CFRunLoopSourceRef from that
101 // 4. Adding that source to the current RunLoop
102 // 5. and passing the resulting messages back to DNSServiceDiscovery_handleReply() for processing
103 //
104 // Code that's not based around a CFRunLoop will need its own mechanism to receive Mach messages
105 // from the mDNSResponder daemon and pass them to the DNSServiceDiscovery_handleReply() routine.
106 // (There is no way to automate this, because it varies depending on the application's existing
107 // event handling model.)
108
109 static void MyHandleMachMessage(CFMachPortRef port, void *msg, CFIndex size, void *info)
110 {
111 (void)port; // Unused
112 (void)size; // Unused
113 (void)info; // Unused
114 DNSServiceDiscovery_handleReply(msg);
115 }
116
117 static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref c)
118 {
119 mach_port_t port = DNSServiceDiscoveryMachPort(c);
120 if (!port)
121 return(-1);
122 else
123 {
124 CFMachPortContext context = { 0, 0, NULL, NULL, NULL };
125 Boolean shouldFreeInfo;
126 CFMachPortRef cfMachPort = CFMachPortCreateWithPort(kCFAllocatorDefault, port, MyHandleMachMessage, &context, &shouldFreeInfo);
127 CFRunLoopSourceRef rls = CFMachPortCreateRunLoopSource(NULL, cfMachPort, 0);
128 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
129 CFRelease(rls);
130 return(0);
131 }
132 }
133
134 //*************************************************************************************************************
135 // Sample callback functions for each of the operation types
136
137 static void printtimestamp(void)
138 {
139 struct timeval tv;
140 struct tm tm;
141 gettimeofday(&tv, NULL);
142 localtime_r((time_t*)&tv.tv_sec, &tm);
143 printf("%2d:%02d:%02d.%03d ", tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec/1000);
144 }
145
146 #define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain ? "Added" : \
147 (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" : \
148 (X) == DNSServiceDomainEnumerationReplyRemoveDomain ? "Removed" : "Unknown")
149
150 static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
151 DNSServiceDiscoveryReplyFlags flags, void *context)
152 {
153 (void)context; // Unused
154 printtimestamp();
155 printf("Recommended Registration Domain %s %s", replyDomain, DomainMsg(resultType));
156 if (flags) printf(" Flags: %X", flags);
157 printf("\n");
158 }
159
160 static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
161 DNSServiceDiscoveryReplyFlags flags, void *context)
162 {
163 (void)context; // Unused
164 printtimestamp();
165 printf("Recommended Browsing Domain %s %s", replyDomain, DomainMsg(resultType));
166 if (flags) printf(" Flags: %X", flags);
167 printf("\n");
168 }
169
170 static void browse_reply(DNSServiceBrowserReplyResultType resultType,
171 const char *replyName, const char *replyType, const char *replyDomain, DNSServiceDiscoveryReplyFlags flags, void *context)
172 {
173 char *op = (resultType == DNSServiceBrowserReplyAddInstance) ? "Add" : "Rmv";
174 (void)context; // Unused
175 if (num_printed++ == 0) printf("Timestamp A/R Flags %-24s %-24s %s\n", "Domain", "Service Type", "Instance Name");
176 printtimestamp();
177 printf("%s%6X %-24s %-24s %s\n", op, flags, replyDomain, replyType, replyName);
178 }
179
180 static void resolve_reply(struct sockaddr *interface, struct sockaddr *address, const char *txtRecord, DNSServiceDiscoveryReplyFlags flags, void *context)
181 {
182 (void)interface; // Unused
183 (void)context; // Unused
184 if (address->sa_family != AF_INET && address->sa_family != AF_INET6)
185 printf("Unknown address family %d\n", address->sa_family);
186 else
187 {
188 const char *src = txtRecord;
189 printtimestamp();
190
191 if (address->sa_family == AF_INET)
192 {
193 struct sockaddr_in *ip = (struct sockaddr_in *)address;
194 union { uint32_t l; u_char b[4]; } addr = { ip->sin_addr.s_addr };
195 union { uint16_t s; u_char b[2]; } port = { ip->sin_port };
196 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
197 char ipstring[16];
198 sprintf(ipstring, "%d.%d.%d.%d", addr.b[0], addr.b[1], addr.b[2], addr.b[3]);
199 printf("Service can be reached at %-15s:%u", ipstring, PortAsNumber);
200 }
201 else if (address->sa_family == AF_INET6)
202 {
203 struct sockaddr_in6 *ip6 = (struct sockaddr_in6 *)address;
204 u_int8_t *b = ip6->sin6_addr.__u6_addr.__u6_addr8;
205 union { uint16_t s; u_char b[2]; } port = { ip6->sin6_port };
206 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
207 char ipstring[40];
208 char ifname[IF_NAMESIZE + 1] = "";
209 sprintf(ipstring, "%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X:%02X%02X",
210 b[0x0], b[0x1], b[0x2], b[0x3], b[0x4], b[0x5], b[0x6], b[0x7],
211 b[0x8], b[0x9], b[0xA], b[0xB], b[0xC], b[0xD], b[0xE], b[0xF]);
212 if (ip6->sin6_scope_id) { ifname[0] = '%'; if_indextoname(ip6->sin6_scope_id, &ifname[1]); }
213 printf("%s%s:%u", ipstring, ifname, PortAsNumber);
214 }
215 if (flags) printf(" Flags: %X", flags);
216 if (*src)
217 {
218 char txtInfo[64]; // Display at most first 64 characters of TXT record
219 char *dst = txtInfo;
220 const char *const lim = &txtInfo[sizeof(txtInfo)];
221 while (*src && dst < lim-1)
222 {
223 if (*src == '\\') *dst++ = '\\'; // '\' displays as "\\"
224 if (*src >= ' ') *dst++ = *src++; // Display normal characters as-is
225 else
226 {
227 *dst++ = '\\'; // Display a backslash
228 if (*src == 1) *dst++ = ' '; // String boundary displayed as "\ "
229 else // Other chararacters displayed as "\0xHH"
230 {
231 static const char hexchars[16] = "0123456789ABCDEF";
232 *dst++ = '0';
233 *dst++ = 'x';
234 *dst++ = hexchars[*src >> 4];
235 *dst++ = hexchars[*src & 0xF];
236 }
237 src++;
238 }
239 }
240 *dst++ = 0;
241 printf(" TXT %s", txtInfo);
242 }
243 printf("\n");
244 }
245 }
246
247 static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
248 {
249 (void)timer; // Parameter not used
250 (void)info; // Parameter not used
251
252 switch (operation)
253 {
254 case 'A':
255 {
256 switch (addtest)
257 {
258 case 0: printf("Adding Test HINFO record\n");
259 record = DNSServiceRegistrationAddRecord(client, T_HINFO, sizeof(myhinfo9), &myhinfo9[0], 120);
260 addtest = 1;
261 break;
262 case 1: printf("Updating Test HINFO record\n");
263 DNSServiceRegistrationUpdateRecord(client, record, sizeof(myhinfoX), &myhinfoX[0], 120);
264 addtest = 2;
265 break;
266 case 2: printf("Removing Test HINFO record\n");
267 DNSServiceRegistrationRemoveRecord(client, record);
268 addtest = 0;
269 break;
270 }
271 }
272 break;
273
274 case 'U':
275 {
276 if (updatetest[1] != 'Z') updatetest[1]++;
277 else updatetest[1] = 'A';
278 updatetest[0] = 3 - updatetest[0];
279 updatetest[2] = updatetest[1];
280 printf("Updating Test TXT record to %c\n", updatetest[1]);
281 DNSServiceRegistrationUpdateRecord(client, 0, 1+updatetest[0], &updatetest[0], 120);
282 }
283 break;
284
285 case 'N':
286 {
287 printf("Adding big NULL record\n");
288 DNSServiceRegistrationAddRecord(client, T_NULL, sizeof(bigNULL), &bigNULL[0], 120);
289 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
290 }
291 break;
292 }
293 }
294
295 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
296 {
297 (void)context; // Unused
298 printf("Got a reply from the server: ");
299 switch (errorCode)
300 {
301 case kDNSServiceDiscoveryNoError: printf("Name now registered and active\n"); break;
302 case kDNSServiceDiscoveryNameConflict: printf("Name in use, please choose another\n"); exit(-1);
303 default: printf("Error %d\n", errorCode); return;
304 }
305
306 if (operation == 'A' || operation == 'U' || operation == 'N')
307 {
308 CFRunLoopTimerContext myCFRunLoopTimerContext = { 0, 0, NULL, NULL, NULL };
309 CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
310 CFAbsoluteTimeGetCurrent() + 5.0, 5.0, 0, 1, // Next fire time, periodic interval, flags, and order
311 myCFRunLoopTimerCallBack, &myCFRunLoopTimerContext);
312 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
313 }
314 }
315
316 //*************************************************************************************************************
317 // The main test function
318
319 int main(int argc, char **argv)
320 {
321 const char *progname = strrchr(argv[0], '/') ? strrchr(argv[0], '/') + 1 : argv[0];
322 char *d;
323 setlinebuf(stdout); // Want to see lines as they appear, not block buffered
324
325 if (argc < 2) goto Fail; // Minimum command line is the command name and one argument
326 operation = getopt(argc, (char * const *)argv, "EFBLRAUNTMI");
327 if (operation == -1) goto Fail;
328
329 switch (operation)
330 {
331 case 'E': printf("Looking for recommended registration domains:\n");
332 client = DNSServiceDomainEnumerationCreate(1, regdom_reply, nil);
333 break;
334
335 case 'F': printf("Looking for recommended browsing domains:\n");
336 client = DNSServiceDomainEnumerationCreate(0, browsedom_reply, nil);
337 break;
338
339 case 'B': if (argc < optind+1) goto Fail;
340 d = (argc < optind+2) ? "" : argv[optind+1]; // Missing domain argument is the same as empty string i.e. use system default(s)
341 if (d[0] == '.' && d[1] == 0) d[0] = 0; // We allow '.' on the command line as a synonym for empty string
342 printf("Browsing for %s%s\n", argv[optind+0], d);
343 client = DNSServiceBrowserCreate(argv[optind+0], d, browse_reply, nil);
344 break;
345
346 case 'L': if (argc < optind+2) goto Fail;
347 d = (argc < optind+3) ? "" : argv[optind+2];
348 if (d[0] == '.' && d[1] == 0) d = "local"; // We allow '.' on the command line as a synonym for "local"
349 printf("Lookup %s.%s%s\n", argv[optind+0], argv[optind+1], d);
350 client = DNSServiceResolverResolve(argv[optind+0], argv[optind+1], d, resolve_reply, nil);
351 break;
352
353 case 'R': if (argc < optind+4) goto Fail;
354 {
355 char *nam = argv[optind+0];
356 char *typ = argv[optind+1];
357 char *dom = argv[optind+2];
358 uint16_t PortAsNumber = atoi(argv[optind+3]);
359 Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
360 char txt[2048];
361 char *ptr = txt;
362 int i;
363
364 if (nam[0] == '.' && nam[1] == 0) nam[0] = 0; // We allow '.' on the command line as a synonym for empty string
365 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
366
367 // Copy all the TXT strings into one C string separated by ASCII-1 delimiters
368 for (i = optind+4; i < argc; i++)
369 {
370 int len = strlen(argv[i]);
371 if (len > 255 || ptr + len + 1 >= txt + sizeof(txt)) break;
372 strcpy(ptr, argv[i]);
373 ptr += len;
374 *ptr++ = 1;
375 }
376 if (ptr > txt) ptr--;
377 *ptr = 0;
378
379 printf("Registering Service %s.%s%s port %s %s\n", nam, typ, dom, argv[optind+3], txt);
380 client = DNSServiceRegistrationCreate(nam, typ, dom, registerPort.NotAnInteger, txt, reg_reply, nil);
381 break;
382 }
383
384 case 'A':
385 case 'U':
386 case 'N': {
387 Opaque16 registerPort = { { 0x12, 0x34 } };
388 static const char TXT[] = "First String\001Second String\001Third String";
389 printf("Registering Service Test._testupdate._tcp.local.\n");
390 client = DNSServiceRegistrationCreate("Test", "_testupdate._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
391 break;
392 }
393
394 case 'T': {
395 Opaque16 registerPort = { { 0x23, 0x45 } };
396 char TXT[1000];
397 unsigned int i;
398 for (i=0; i<sizeof(TXT)-1; i++)
399 if ((i & 0x1F) == 0x1F) TXT[i] = 1; else TXT[i] = 'A' + (i >> 5);
400 TXT[i] = 0;
401 printf("Registering Service Test._testlargetxt._tcp.local.\n");
402 client = DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
403 break;
404 }
405
406 case 'M': {
407 pid_t pid = getpid();
408 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
409 static const char TXT1[] = "First String\001Second String\001Third String";
410 static const char TXT2[] = "\x0D" "Fourth String" "\x0C" "Fifth String" "\x0C" "Sixth String";
411 printf("Registering Service Test._testdualtxt._tcp.local.\n");
412 client = DNSServiceRegistrationCreate("", "_testdualtxt._tcp.", "", registerPort.NotAnInteger, TXT1, reg_reply, nil);
413 // use "sizeof(TXT2)-1" because we don't wan't the C compiler's null byte on the end of the string
414 record = DNSServiceRegistrationAddRecord(client, T_TXT, sizeof(TXT2)-1, TXT2, 120);
415 break;
416 }
417
418 case 'I': {
419 pid_t pid = getpid();
420 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
421 static const char TXT[] = "\x09" "Test Data";
422 printf("Registering Service Test._testtxt._tcp.local.\n");
423 client = DNSServiceRegistrationCreate("", "_testtxt._tcp.", "", registerPort.NotAnInteger, "", reg_reply, nil);
424 if (client) DNSServiceRegistrationUpdateRecord(client, 0, 1+TXT[0], &TXT[0], 120);
425 break;
426 }
427
428 default: goto Exit;
429 }
430
431 if (!client) { fprintf(stderr, "DNSService call failed\n"); return (-1); }
432 if (AddDNSServiceClientToRunLoop(client) != 0) { fprintf(stderr, "AddDNSServiceClientToRunLoop failed\n"); return (-1); }
433 printf("Talking to DNS SD Daemon at Mach port %d\n", DNSServiceDiscoveryMachPort(client));
434 CFRunLoopRun();
435
436 // Be sure to deallocate the dns_service_discovery_ref when you're finished
437 // Note: What other cleanup has to be done here?
438 // We should probably invalidate, remove and release our CFRunLoopSourceRef?
439 DNSServiceDiscoveryDeallocate(client);
440
441 Exit:
442 return 0;
443
444 Fail:
445 fprintf(stderr, "%s -E (Enumerate recommended registration domains)\n", progname);
446 fprintf(stderr, "%s -F (Enumerate recommended browsing domains)\n", progname);
447 fprintf(stderr, "%s -B <Type> <Domain> (Browse for services instances)\n", progname);
448 fprintf(stderr, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", progname);
449 fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", progname);
450 fprintf(stderr, "%s -A (Test Adding/Updating/Deleting a record)\n", progname);
451 fprintf(stderr, "%s -U (Test updating a TXT record)\n", progname);
452 fprintf(stderr, "%s -N (Test adding a large NULL record)\n", progname);
453 fprintf(stderr, "%s -T (Test creating a large TXT record)\n", progname);
454 fprintf(stderr, "%s -M (Test creating a registration with multiple TXT records)\n", progname);
455 fprintf(stderr, "%s -I (Test registering and then immediately updating TXT record)\n", progname);
456 return 0;
457 }
458
459 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
460 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
461 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
462 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) #s
463 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
464
465 // NOT static -- otherwise the compiler may optimize it out
466 // The "@(#) " pattern is a special prefix the "what" command looks for
467 const char VersionString_SCCS[] = "@(#) mDNS " STRINGIFY(mDNSResponderVersion) " (" __DATE__ " " __TIME__ ")";
468
469 // If the process crashes, then this string will be magically included in the automatically-generated crash log
470 const char *__crashreporter_info__ = VersionString_SCCS + 5;
471 asm(".desc ___crashreporter_info__, 0x10");