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