]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSMacOSX/SamplemDNSClient.c
mDNSResponder-66.3.tar.gz
[apple/mdnsresponder.git] / mDNSMacOSX / SamplemDNSClient.c
1 /*
2 * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
7 *
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 *
25 * Formatting notes:
26 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
27 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
28 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
29 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
30 * therefore common sense dictates that if they are part of a compound statement then they
31 * should be indented to the same level as everything else in that compound statement.
32 * Indenting curly braces at the same level as the "if" implies that curly braces are
33 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
34 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
35 * understand why variable y is not of type "char*" just proves the point that poor code
36 * layout leads people to unfortunate misunderstandings about how the C language really works.)
37
38 Change History (most recent first):
39
40 $Log: SamplemDNSClient.c,v $
41 Revision 1.44 2004/05/28 02:20:06 cheshire
42 If we allow dot or empty string for domain when resolving a service,
43 it should be a synonym for "local"
44
45 Revision 1.43 2004/02/03 22:07:50 cheshire
46 <rdar://problem/3548184>: Widen columns to display non-local domains better
47
48 Revision 1.42 2003/12/03 11:39:17 cheshire
49 <rdar://problem/3468977> Browse output misaligned in mDNS command-line tool
50 (Also fix it to add leading space when the hours part of the time is only one digit)
51
52 Revision 1.41 2003/10/30 22:52:57 cheshire
53 <rdar://problem/3468977> Browse output misaligned in mDNS command-line tool
54
55 Revision 1.40 2003/09/26 01:07:06 cheshire
56 Added test case to test fix for <rdar://problem/3427923>
57
58 Revision 1.39 2003/08/18 19:05:45 cheshire
59 <rdar://problem/3382423> UpdateRecord not working right
60 Added "newrdlength" field to hold new length of updated rdata
61
62 Revision 1.38 2003/08/12 19:56:25 cheshire
63 Update to APSL 2.0
64
65 Revision 1.37 2003/08/05 20:39:25 cheshire
66 <rdar://problem/3362184> mDNS buffered std out makes it impossible to use from another tool
67 Added "setlinebuf(stdout);"
68
69 Revision 1.36 2003/07/19 03:23:13 cheshire
70 <rdar://problem/2986147> mDNSResponder needs to receive and cache larger records
71
72 Revision 1.35 2003/07/11 01:57:18 cheshire
73 Add checkin history header
74
75 */
76
77 #include <libc.h>
78 #define BIND_8_COMPAT
79 #include <arpa/nameser.h>
80 #include <arpa/inet.h>
81 #include <net/if.h>
82 #include <CoreFoundation/CoreFoundation.h>
83 #include <DNSServiceDiscovery/DNSServiceDiscovery.h>
84
85 //*************************************************************************************************************
86 // Globals
87
88 typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
89
90 static char operation;
91 static dns_service_discovery_ref client = NULL;
92 static int num_printed;
93 static char addtest = 0;
94 static DNSRecordReference record;
95 static char myhinfo9[11] = "\003Mac\006OS 9.2";
96 static char myhinfoX[ 9] = "\003Mac\004OS X";
97 static char updatetest[3] = "\002AA";
98 static char bigNULL[4096];
99
100 //*************************************************************************************************************
101 // Supporting Utility Functions
102 //
103 // This code takes care of:
104 // 1. Extracting the mach_port_t from the dns_service_discovery_ref
105 // 2. Making a CFMachPortRef from it
106 // 3. Making a CFRunLoopSourceRef from that
107 // 4. Adding that source to the current RunLoop
108 // 5. and passing the resulting messages back to DNSServiceDiscovery_handleReply() for processing
109 //
110 // Code that's not based around a CFRunLoop will need its own mechanism to receive Mach messages
111 // from the mDNSResponder daemon and pass them to the DNSServiceDiscovery_handleReply() routine.
112 // (There is no way to automate this, because it varies depending on the application's existing
113 // event handling model.)
114
115 static void MyHandleMachMessage(CFMachPortRef port, void *msg, CFIndex size, void *info)
116 {
117 (void)port; // Unused
118 (void)size; // Unused
119 (void)info; // Unused
120 DNSServiceDiscovery_handleReply(msg);
121 }
122
123 static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref client)
124 {
125 mach_port_t port = DNSServiceDiscoveryMachPort(client);
126 if (!port)
127 return(-1);
128 else
129 {
130 CFMachPortContext context = { 0, 0, NULL, NULL, NULL };
131 Boolean shouldFreeInfo;
132 CFMachPortRef cfMachPort = CFMachPortCreateWithPort(kCFAllocatorDefault, port, MyHandleMachMessage, &context, &shouldFreeInfo);
133 CFRunLoopSourceRef rls = CFMachPortCreateRunLoopSource(NULL, cfMachPort, 0);
134 CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
135 CFRelease(rls);
136 return(0);
137 }
138 }
139
140 //*************************************************************************************************************
141 // Sample callback functions for each of the operation types
142
143 static void printtimestamp(void)
144 {
145 struct timeval tv;
146 struct tm tm;
147 gettimeofday(&tv, NULL);
148 localtime_r((time_t*)&tv.tv_sec, &tm);
149 printf("%2d:%02d:%02d.%03d ", tm.tm_hour, tm.tm_min, tm.tm_sec, tv.tv_usec/1000);
150 }
151
152 #define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain ? "Added" : \
153 (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" : \
154 (X) == DNSServiceDomainEnumerationReplyRemoveDomain ? "Removed" : "Unknown")
155
156 static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
157 DNSServiceDiscoveryReplyFlags flags, void *context)
158 {
159 (void)context; // Unused
160 printtimestamp();
161 printf("Recommended Registration Domain %s %s", replyDomain, DomainMsg(resultType));
162 if (flags) printf(" Flags: %X", flags);
163 printf("\n");
164 }
165
166 static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
167 DNSServiceDiscoveryReplyFlags flags, void *context)
168 {
169 (void)context; // Unused
170 printtimestamp();
171 printf("Recommended Browsing Domain %s %s", replyDomain, DomainMsg(resultType));
172 if (flags) printf(" Flags: %X", flags);
173 printf("\n");
174 }
175
176 static void browse_reply(DNSServiceBrowserReplyResultType resultType,
177 const char *replyName, const char *replyType, const char *replyDomain, DNSServiceDiscoveryReplyFlags flags, void *context)
178 {
179 char *op = (resultType == DNSServiceBrowserReplyAddInstance) ? "Add" : "Rmv";
180 (void)context; // Unused
181 if (num_printed++ == 0) printf("Timestamp A/R Flags %-24s %-24s %s\n", "Domain", "Service Type", "Instance Name");
182 printtimestamp();
183 printf("%s%6X %-24s %-24s %s\n", op, flags, replyDomain, replyType, replyName);
184 }
185
186 static void resolve_reply(struct sockaddr *interface, struct sockaddr *address, const char *txtRecord, DNSServiceDiscoveryReplyFlags flags, void *context)
187 {
188 (void)interface; // Unused
189 (void)context; // Unused
190 if (address->sa_family != AF_INET && address->sa_family != AF_INET6)
191 printf("Unknown address family %d\n", address->sa_family);
192 else
193 {
194 const char *src = txtRecord;
195 printtimestamp();
196
197 if (address->sa_family == AF_INET)
198 {
199 struct sockaddr_in *ip = (struct sockaddr_in *)address;
200 union { uint32_t l; u_char b[4]; } addr = { ip->sin_addr.s_addr };
201 union { uint16_t s; u_char b[2]; } port = { ip->sin_port };
202 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
203 char ipstring[16];
204 sprintf(ipstring, "%d.%d.%d.%d", addr.b[0], addr.b[1], addr.b[2], addr.b[3]);
205 printf("Service can be reached at %-15s:%u", ipstring, PortAsNumber);
206 }
207 else if (address->sa_family == AF_INET6)
208 {
209 struct sockaddr_in6 *ip6 = (struct sockaddr_in6 *)address;
210 u_int16_t *w = ip6->sin6_addr.__u6_addr.__u6_addr16;
211 union { uint16_t s; u_char b[2]; } port = { ip6->sin6_port };
212 uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
213 char ipstring[40];
214 char ifname[IF_NAMESIZE + 1] = "";
215 sprintf(ipstring, "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X", w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]);
216 if (ip6->sin6_scope_id) { ifname[0] = '%'; if_indextoname(ip6->sin6_scope_id, &ifname[1]); }
217 printf("%s%s:%u", ipstring, ifname, PortAsNumber);
218 }
219 if (flags) printf(" Flags: %X", flags);
220 if (*src)
221 {
222 char txtInfo[64]; // Display at most first 64 characters of TXT record
223 char *dst = txtInfo;
224 const char *const lim = &txtInfo[sizeof(txtInfo)];
225 while (*src && dst < lim-1)
226 {
227 if (*src == '\\') *dst++ = '\\'; // '\' displays as "\\"
228 if (*src >= ' ') *dst++ = *src++; // Display normal characters as-is
229 else
230 {
231 *dst++ = '\\'; // Display a backslash
232 if (*src == 1) *dst++ = ' '; // String boundary displayed as "\ "
233 else // Other chararacters displayed as "\0xHH"
234 {
235 static const char hexchars[16] = "0123456789ABCDEF";
236 *dst++ = '0';
237 *dst++ = 'x';
238 *dst++ = hexchars[*src >> 4];
239 *dst++ = hexchars[*src & 0xF];
240 }
241 src++;
242 }
243 }
244 *dst++ = 0;
245 printf(" TXT %s", txtInfo);
246 }
247 printf("\n");
248 }
249 }
250
251 static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
252 {
253 (void)timer; // Parameter not used
254 (void)info; // Parameter not used
255
256 switch (operation)
257 {
258 case 'A':
259 {
260 switch (addtest)
261 {
262 case 0: printf("Adding Test HINFO record\n");
263 record = DNSServiceRegistrationAddRecord(client, T_HINFO, sizeof(myhinfo9), &myhinfo9[0], 120);
264 addtest = 1;
265 break;
266 case 1: printf("Updating Test HINFO record\n");
267 DNSServiceRegistrationUpdateRecord(client, record, sizeof(myhinfoX), &myhinfoX[0], 120);
268 addtest = 2;
269 break;
270 case 2: printf("Removing Test HINFO record\n");
271 DNSServiceRegistrationRemoveRecord(client, record);
272 addtest = 0;
273 break;
274 }
275 }
276 break;
277
278 case 'U':
279 {
280 if (updatetest[1] != 'Z') updatetest[1]++;
281 else updatetest[1] = 'A';
282 updatetest[0] = 3 - updatetest[0];
283 updatetest[2] = updatetest[1];
284 printf("Updating Test TXT record to %c\n", updatetest[1]);
285 DNSServiceRegistrationUpdateRecord(client, 0, 1+updatetest[0], &updatetest[0], 120);
286 }
287 break;
288
289 case 'N':
290 {
291 printf("Adding big NULL record\n");
292 DNSServiceRegistrationAddRecord(client, T_NULL, sizeof(bigNULL), &bigNULL[0], 120);
293 CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
294 }
295 break;
296 }
297 }
298
299 static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
300 {
301 (void)context; // Unused
302 printf("Got a reply from the server: ");
303 switch (errorCode)
304 {
305 case kDNSServiceDiscoveryNoError: printf("Name now registered and active\n"); break;
306 case kDNSServiceDiscoveryNameConflict: printf("Name in use, please choose another\n"); exit(-1);
307 default: printf("Error %d\n", errorCode); return;
308 }
309
310 if (operation == 'A' || operation == 'U' || operation == 'N')
311 {
312 CFRunLoopTimerContext myCFRunLoopTimerContext = { 0, 0, NULL, NULL, NULL };
313 CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
314 CFAbsoluteTimeGetCurrent() + 5.0, 5.0, 0, 1, // Next fire time, periodic interval, flags, and order
315 myCFRunLoopTimerCallBack, &myCFRunLoopTimerContext);
316 CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
317 }
318 }
319
320 //*************************************************************************************************************
321 // The main test function
322
323 int main(int argc, char **argv)
324 {
325 char *dom;
326 setlinebuf(stdout); // Want to see lines as they appear, not block buffered
327
328 if (argc < 2) goto Fail; // Minimum command line is the command name and one argument
329 operation = getopt(argc, (char * const *)argv, "EFBLRAUNTMI");
330 if (operation == -1) goto Fail;
331
332 switch (operation)
333 {
334 case 'E': printf("Looking for recommended registration domains:\n");
335 client = DNSServiceDomainEnumerationCreate(1, regdom_reply, nil);
336 break;
337
338 case 'F': printf("Looking for recommended browsing domains:\n");
339 client = DNSServiceDomainEnumerationCreate(0, browsedom_reply, nil);
340 break;
341
342 case 'B': if (argc < optind+1) goto Fail;
343 dom = (argc < optind+2) ? "local" : argv[optind+1];
344 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
345 printf("Browsing for %s%s\n", argv[optind+0], dom);
346 client = DNSServiceBrowserCreate(argv[optind+0], dom, browse_reply, nil);
347 break;
348
349 case 'L': if (argc < optind+2) goto Fail;
350 dom = (argc < optind+3) ? "" : argv[optind+2];
351 if (dom[0] == '.' && dom[1] == 0) dom = "local"; // We allow '.' on the command line as a synonym for "local"
352 printf("Lookup %s.%s%s\n", argv[optind+0], argv[optind+1], dom);
353 client = DNSServiceResolverResolve(argv[optind+0], argv[optind+1], dom, resolve_reply, nil);
354 break;
355
356 case 'R': if (argc < optind+4) goto Fail;
357 {
358 char *nam = argv[optind+0];
359 char *typ = argv[optind+1];
360 char *dom = argv[optind+2];
361 uint16_t PortAsNumber = atoi(argv[optind+3]);
362 Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
363 char txt[2048];
364 char *ptr = txt;
365 int i;
366
367 if (nam[0] == '.' && nam[1] == 0) nam[0] = 0; // We allow '.' on the command line as a synonym for empty string
368 if (dom[0] == '.' && dom[1] == 0) dom[0] = 0; // We allow '.' on the command line as a synonym for empty string
369
370 // Copy all the TXT strings into one C string separated by ASCII-1 delimiters
371 for (i = optind+4; i < argc; i++)
372 {
373 strcpy(ptr, argv[i]);
374 ptr += strlen(argv[i]);
375 *ptr++ = 1;
376 }
377 if (ptr > txt) ptr--;
378 *ptr = 0;
379
380 printf("Registering Service %s.%s%s port %s %s\n", nam, typ, dom, argv[optind+3], txt);
381 client = DNSServiceRegistrationCreate(nam, typ, dom, registerPort.NotAnInteger, txt, reg_reply, nil);
382 break;
383 }
384
385 case 'A':
386 case 'U':
387 case 'N': {
388 Opaque16 registerPort = { { 0x12, 0x34 } };
389 static const char TXT[] = "First String\001Second String\001Third String";
390 printf("Registering Service Test._testupdate._tcp.local.\n");
391 client = DNSServiceRegistrationCreate("Test", "_testupdate._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
392 break;
393 }
394
395 case 'T': {
396 Opaque16 registerPort = { { 0x23, 0x45 } };
397 char TXT[1000];
398 unsigned int i;
399 for (i=0; i<sizeof(TXT)-1; i++)
400 if ((i & 0x1F) == 0x1F) TXT[i] = 1; else TXT[i] = 'A' + (i >> 5);
401 TXT[i] = 0;
402 printf("Registering Service Test._testlargetxt._tcp.local.\n");
403 client = DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
404 break;
405 }
406
407 case 'M': {
408 pid_t pid = getpid();
409 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
410 static const char TXT1[] = "First String\001Second String\001Third String";
411 static const char TXT2[] = "\x0D" "Fourth String" "\x0C" "Fifth String" "\x0C" "Sixth String";
412 printf("Registering Service Test._testdualtxt._tcp.local.\n");
413 client = DNSServiceRegistrationCreate("", "_testdualtxt._tcp.", "", registerPort.NotAnInteger, TXT1, reg_reply, nil);
414 // use "sizeof(TXT2)-1" because we don't wan't the C compiler's null byte on the end of the string
415 record = DNSServiceRegistrationAddRecord(client, T_TXT, sizeof(TXT2)-1, TXT2, 120);
416 break;
417 }
418
419 case 'I': {
420 pid_t pid = getpid();
421 Opaque16 registerPort = { { pid >> 8, pid & 0xFF } };
422 static const char TXT[] = "\x09" "Test Data";
423 printf("Registering Service Test._testtxt._tcp.local.\n");
424 client = DNSServiceRegistrationCreate("", "_testtxt._tcp.", "", registerPort.NotAnInteger, "", reg_reply, nil);
425 if (client) DNSServiceRegistrationUpdateRecord(client, 0, 1+TXT[0], &TXT[0], 120);
426 break;
427 }
428
429 default: goto Exit;
430 }
431
432 if (!client) { fprintf(stderr, "DNSService call failed\n"); return (-1); }
433 if (AddDNSServiceClientToRunLoop(client) != 0) { fprintf(stderr, "AddDNSServiceClientToRunLoop failed\n"); return (-1); }
434 printf("Talking to DNS SD Daemon at Mach port %d\n", DNSServiceDiscoveryMachPort(client));
435 CFRunLoopRun();
436
437 // Be sure to deallocate the dns_service_discovery_ref when you're finished
438 // Note: What other cleanup has to be done here?
439 // We should probably invalidate, remove and release our CFRunLoopSourceRef?
440 DNSServiceDiscoveryDeallocate(client);
441
442 Exit:
443 return 0;
444
445 Fail:
446 fprintf(stderr, "%s -E (Enumerate recommended registration domains)\n", argv[0]);
447 fprintf(stderr, "%s -F (Enumerate recommended browsing domains)\n", argv[0]);
448 fprintf(stderr, "%s -B <Type> <Domain> (Browse for services instances)\n", argv[0]);
449 fprintf(stderr, "%s -L <Name> <Type> <Domain> (Look up a service instance)\n", argv[0]);
450 fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> [<TXT>...] (Register a service)\n", argv[0]);
451 fprintf(stderr, "%s -A (Test Adding/Updating/Deleting a record)\n", argv[0]);
452 fprintf(stderr, "%s -U (Test updating a TXT record)\n", argv[0]);
453 fprintf(stderr, "%s -N (Test adding a large NULL record)\n", argv[0]);
454 fprintf(stderr, "%s -T (Test creating a large TXT record)\n", argv[0]);
455 fprintf(stderr, "%s -M (Test creating a registration with multiple TXT records)\n", argv[0]);
456 fprintf(stderr, "%s -I (Test registering and then immediately updating TXT record)\n", argv[0]);
457 return 0;
458 }