]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/mDNSPosix.c
mDNSResponder-58.tar.gz
[apple/mdnsresponder.git] / mDNSPosix / mDNSPosix.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: mDNSPosix.c,v $
39 Revision 1.24 2003/08/18 23:12:23 cheshire
40 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
41
42 Revision 1.23 2003/08/12 19:56:26 cheshire
43 Update to APSL 2.0
44
45 Revision 1.22 2003/08/06 18:46:15 cheshire
46 LogMsg() errors are serious -- always report them to stderr, regardless of debugging level
47
48 Revision 1.21 2003/08/06 18:20:51 cheshire
49 Makefile cleanup
50
51 Revision 1.20 2003/08/05 23:56:26 cheshire
52 Update code to compile with the new mDNSCoreReceive() function that requires a TTL
53 (Right now mDNSPosix.c just reports 255 -- we should fix this)
54
55 Revision 1.19 2003/07/19 03:15:16 cheshire
56 Add generic MemAllocate/MemFree prototypes to mDNSPlatformFunctions.h,
57 and add the obvious trivial implementations to each platform support layer
58
59 Revision 1.18 2003/07/14 18:11:54 cheshire
60 Fix stricter compiler warnings
61
62 Revision 1.17 2003/07/13 01:08:38 cheshire
63 There's not much point running mDNS over a point-to-point link; exclude those
64
65 Revision 1.16 2003/07/02 21:19:59 cheshire
66 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
67
68 Revision 1.15 2003/06/18 05:48:41 cheshire
69 Fix warnings
70
71 Revision 1.14 2003/05/26 03:21:30 cheshire
72 Tidy up address structure naming:
73 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
74 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
75 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
76
77 Revision 1.13 2003/05/26 03:01:28 cheshire
78 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
79
80 Revision 1.12 2003/05/21 03:49:18 cheshire
81 Fix warning
82
83 Revision 1.11 2003/05/06 00:00:50 cheshire
84 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
85
86 Revision 1.10 2003/04/25 01:45:57 cheshire
87 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
88
89 Revision 1.9 2003/03/20 21:10:31 cheshire
90 Fixes done at IETF 56 to make mDNSProxyResponderPosix run on Solaris
91
92 Revision 1.8 2003/03/15 04:40:38 cheshire
93 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
94
95 Revision 1.7 2003/03/13 03:46:21 cheshire
96 Fixes to make the code build on Linux
97
98 Revision 1.6 2003/03/08 00:35:56 cheshire
99 Switched to using new "mDNS_Execute" model (see "mDNSCore/Implementer Notes.txt")
100
101 Revision 1.5 2002/12/23 22:13:31 jgraessl
102 Reviewed by: Stuart Cheshire
103 Initial IPv6 support for mDNSResponder.
104
105 Revision 1.4 2002/09/27 01:47:45 cheshire
106 Workaround for Linux 2.0 systems that don't have IP_PKTINFO
107
108 Revision 1.3 2002/09/21 20:44:53 zarzycki
109 Added APSL info
110
111 Revision 1.2 2002/09/19 21:25:36 cheshire
112 mDNS_snprintf() doesn't need to be in a separate file
113
114 Revision 1.1 2002/09/17 06:24:34 cheshire
115 First checkin
116 */
117
118 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
119 #include "mDNSPlatformFunctions.h" // Defines the interface to the supporting layer below
120 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
121
122 #include <assert.h>
123 #include <stdio.h>
124 #include <stdlib.h>
125 #include <errno.h>
126 #include <string.h>
127 #include <unistd.h>
128 #include <fcntl.h>
129 #include <sys/types.h>
130 #include <sys/socket.h>
131 #include <sys/uio.h>
132 #include <netinet/in.h>
133
134 #include "mDNSUNP.h"
135
136 // ***************************************************************************
137 // Structures
138
139 // PosixNetworkInterface is a record extension of the core NetworkInterfaceInfo
140 // type that supports extra fields needed by the Posix platform.
141 //
142 // IMPORTANT: coreIntf must be the first field in the structure because
143 // we cast between pointers to the two different types regularly.
144
145 typedef struct PosixNetworkInterface PosixNetworkInterface;
146
147 struct PosixNetworkInterface
148 {
149 NetworkInterfaceInfo coreIntf;
150 const char * intfName;
151 PosixNetworkInterface * aliasIntf;
152 int index;
153 int multicastSocket;
154 int multicastSocketv6;
155 };
156
157 // ***************************************************************************
158 // Globals (for debugging)
159
160 static int num_registered_interfaces = 0;
161 static int num_pkts_accepted = 0;
162 static int num_pkts_rejected = 0;
163
164 // ***************************************************************************
165 // Functions
166
167 int gMDNSPlatformPosixVerboseLevel = 0;
168
169 // Note, this uses mDNS_vsnprintf instead of standard "vsnprintf", because mDNS_vsnprintf knows
170 // how to print special data types like IP addresses and length-prefixed domain names
171 mDNSexport void debugf_(const char *format, ...)
172 {
173 unsigned char buffer[512];
174 va_list ptr;
175 va_start(ptr,format);
176 buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0;
177 va_end(ptr);
178 if (gMDNSPlatformPosixVerboseLevel >= 1)
179 fprintf(stderr, "%s\n", buffer);
180 fflush(stderr);
181 }
182
183 mDNSexport void verbosedebugf_(const char *format, ...)
184 {
185 unsigned char buffer[512];
186 va_list ptr;
187 va_start(ptr,format);
188 buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0;
189 va_end(ptr);
190 if (gMDNSPlatformPosixVerboseLevel >= 2)
191 fprintf(stderr, "%s\n", buffer);
192 fflush(stderr);
193 }
194
195 mDNSexport void LogMsg(const char *format, ...)
196 {
197 unsigned char buffer[512];
198 va_list ptr;
199 va_start(ptr,format);
200 buffer[mDNS_vsnprintf((char *)buffer, sizeof(buffer), format, ptr)] = 0;
201 va_end(ptr);
202 fprintf(stderr, "%s\n", buffer);
203 fflush(stderr);
204 }
205
206 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
207
208 static void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
209 {
210 switch (sa->sa_family)
211 {
212 case AF_INET:
213 {
214 struct sockaddr_in* sin = (struct sockaddr_in*)sa;
215 ipAddr->type = mDNSAddrType_IPv4;
216 ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
217 if (ipPort) ipPort->NotAnInteger = sin->sin_port;
218 break;
219 }
220
221 #ifdef mDNSIPv6Support
222 case AF_INET6:
223 {
224 struct sockaddr_in6* sin6 = (struct sockaddr_in6*)sa;
225 assert(sin6->sin6_len == sizeof(*sin6));
226 ipAddr->type = mDNSAddrType_IPv6;
227 ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
228 if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
229 break;
230 }
231 #endif
232
233 default:
234 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
235 ipAddr->type = mDNSAddrType_None;
236 if (ipPort) ipPort->NotAnInteger = 0;
237 break;
238 }
239 }
240
241 #if COMPILER_LIKES_PRAGMA_MARK
242 #pragma mark ***** Send and Receive
243 #endif
244
245 // mDNS core calls this routine when it needs to send a packet.
246 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
247 mDNSInterfaceID InterfaceID, mDNSIPPort srcPort, const mDNSAddr *dst, mDNSIPPort dstPort)
248 {
249 int err;
250 struct sockaddr_storage to;
251 PosixNetworkInterface * thisIntf;
252
253 assert(m != NULL);
254 assert(msg != NULL);
255 assert(end != NULL);
256 assert( (((char *) end) - ((char *) msg)) > 0 );
257 assert(InterfaceID != 0); // Can't send from zero source address
258 assert(srcPort.NotAnInteger != 0); // Nor from a zero source port
259 assert(dstPort.NotAnInteger != 0); // Nor from a zero source port
260
261 if (dst->type == mDNSAddrType_IPv4)
262 {
263 struct sockaddr_in *sin = (struct sockaddr_in*)&to;
264 #ifndef NOT_HAVE_SA_LEN
265 sin->sin_len = sizeof(*sin);
266 #endif
267 sin->sin_family = AF_INET;
268 sin->sin_port = dstPort.NotAnInteger;
269 sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
270 }
271
272 #ifdef mDNSIPv6Support
273 else if (dst->type == mDNSAddrType_IPv6)
274 {
275 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
276 mDNSPlatformMemZero(sin6, sizeof(*sin6));
277 sin6->sin6_len = sizeof(*sin6);
278 sin6->sin6_family = AF_INET6;
279 sin6->sin6_port = dstPort.NotAnInteger;
280 sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
281 }
282 #endif
283
284 err = 0;
285 thisIntf = (PosixNetworkInterface *)(InterfaceID);
286 if (dst->type == mDNSAddrType_IPv4)
287 err = sendto(thisIntf->multicastSocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
288
289 #ifdef mDNSIPv6Support
290 else if (dst->type == mDNSAddrType_IPv6)
291 err = sendto(thisIntf->multicastSocketv6, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
292 #endif
293
294 if (err > 0) err = 0;
295 else if (err < 0)
296 verbosedebugf("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
297 errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
298
299 return PosixErrorToStatus(err);
300 }
301
302 // This routine is called when the main loop detects that data is available on a socket.
303 static void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
304 {
305 mDNSAddr senderAddr, destAddr;
306 mDNSIPPort senderPort;
307 ssize_t packetLen;
308 DNSMessage packet;
309 struct my_in_pktinfo packetInfo;
310 struct sockaddr_storage from;
311 socklen_t fromLen;
312 int flags;
313 mDNSBool reject;
314
315 assert(m != NULL);
316 assert(intf != NULL);
317 assert(skt >= 0);
318
319 fromLen = sizeof(from);
320 flags = 0;
321 packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo);
322
323 if (packetLen >= 0)
324 {
325 SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
326 SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
327
328 // If we have broken IP_RECVDSTADDR functionality (so far
329 // I've only seen this on OpenBSD) then apply a hack to
330 // convince mDNS Core that this isn't a spoof packet.
331 // Basically what we do is check to see whether the
332 // packet arrived as a multicast and, if so, set its
333 // destAddr to the mDNS address.
334 //
335 // I must admit that I could just be doing something
336 // wrong on OpenBSD and hence triggering this problem
337 // but I'm at a loss as to how.
338 //
339 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
340 // no way to tell the destination address or interface this packet arrived on,
341 // so all we can do is just assume it's a multicast
342
343 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
344 if ( (destAddr.NotAnInteger == 0) && (flags & MSG_MCAST) )
345 {
346 destAddr.type == senderAddr.type;
347 if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup;
348 else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroupv6;
349 }
350 #endif
351
352 // We only accept the packet if the interface on which it came
353 // in matches the interface associated with this socket.
354 // We do this match by name or by index, depending on which
355 // information is available. recvfrom_flags sets the name
356 // to "" if the name isn't available, or the index to -1
357 // if the index is available. This accomodates the various
358 // different capabilities of our target platforms.
359
360 reject = mDNSfalse;
361 if ( packetInfo.ipi_ifname[0] != 0 ) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
362 else if ( packetInfo.ipi_ifindex != -1 ) reject = (packetInfo.ipi_ifindex != intf->index);
363
364 if (reject)
365 {
366 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d",
367 &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
368 &intf->coreIntf.ip, intf->intfName, intf->index);
369 packetLen = -1;
370 num_pkts_rejected++;
371 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
372 {
373 fprintf(stderr,
374 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
375 num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
376 num_pkts_accepted = 0;
377 num_pkts_rejected = 0;
378 }
379 }
380 else
381 {
382 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d",
383 &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index);
384 num_pkts_accepted++;
385 }
386 }
387
388 if (packetLen >= 0 && packetLen < (ssize_t)sizeof(DNSMessageHeader))
389 {
390 debugf("SocketDataReady packet length (%d) too short", packetLen);
391 packetLen = -1;
392 }
393
394 if (packetLen >= 0)
395 mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
396 &senderAddr, senderPort, &destAddr, MulticastDNSPort, intf->coreIntf.InterfaceID, 255);
397 }
398
399 #if COMPILER_LIKES_PRAGMA_MARK
400 #pragma mark ***** Init and Term
401 #endif
402
403 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
404 // Other platforms can either get the information from the appropriate place,
405 // or they can alternatively just require all registering services to provide an explicit name
406 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
407 {
408 MakeDomainLabelFromLiteralString(namelabel, "Fill in Default Service Name Here");
409 }
410
411 // This gets the current hostname, truncating it at the first dot if necessary
412 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
413 {
414 int len = 0;
415 gethostname(&namelabel->c[1], MAX_DOMAIN_LABEL);
416 while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
417 namelabel->c[0] = len;
418 }
419
420 // Searches the interface list looking for the named interface.
421 // Returns a pointer to if it found, or NULL otherwise.
422 static PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
423 {
424 PosixNetworkInterface *intf;
425
426 assert(m != NULL);
427 assert(intfName != NULL);
428
429 intf = (PosixNetworkInterface*)(m->HostInterfaces);
430 while ( (intf != NULL) && (strcmp(intf->intfName, intfName) != 0) )
431 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
432
433 return intf;
434 }
435
436 // Frees the specified PosixNetworkInterface structure. The underlying
437 // interface must have already been deregistered with the mDNS core.
438 static void FreePosixNetworkInterface(PosixNetworkInterface *intf)
439 {
440 assert(intf != NULL);
441 if (intf->intfName != NULL) free((void *)intf->intfName);
442 if (intf->multicastSocket != -1) assert(close(intf->multicastSocket) == 0);
443 if (intf->multicastSocketv6 != -1) assert(close(intf->multicastSocketv6) == 0);
444 free(intf);
445 }
446
447 // Grab the first interface, deregister it, free it, and repeat until done.
448 static void ClearInterfaceList(mDNS *const m)
449 {
450 assert(m != NULL);
451
452 while (m->HostInterfaces)
453 {
454 PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
455 mDNS_DeregisterInterface(m, &intf->coreIntf);
456 if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
457 FreePosixNetworkInterface(intf);
458 }
459 num_registered_interfaces = 0;
460 num_pkts_accepted = 0;
461 num_pkts_rejected = 0;
462 }
463
464 // Sets up a multicast send/receive socket for the specified
465 // port on the interface specified by the IP addrelss intfAddr.
466 static int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
467 {
468 int err = 0;
469 static const int kOn = 1;
470 static const int kIntTwoFiveFive = 255;
471 static const unsigned char kByteTwoFiveFive = 255;
472
473 (void) interfaceIndex; // Unused
474 assert(intfAddr != NULL);
475 assert(sktPtr != NULL);
476 assert(*sktPtr == -1);
477
478 // Open the socket...
479 if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
480 #ifdef mDNSIPv6Support
481 else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
482 #endif
483 else return EINVAL;
484
485 if (*sktPtr < 0) { err = errno; perror("socket"); }
486
487 // ... with a shared UDP port
488 if (err == 0)
489 {
490 #if defined(SO_REUSEPORT)
491 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
492 #elif defined(SO_REUSEADDR)
493 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
494 #else
495 #error This platform has no way to avoid address busy errors on multicast.
496 #endif
497 if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
498 }
499
500 // We want to receive destination addresses and interface identifiers.
501 if (intfAddr->sa_family == AF_INET)
502 {
503 struct ip_mreq imr;
504 struct sockaddr_in bindAddr;
505 if (err == 0)
506 {
507 #if defined(IP_PKTINFO) // Linux
508 err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
509 if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
510 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
511 #if defined(IP_RECVDSTADDR)
512 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
513 if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
514 #endif
515 #if defined(IP_RECVIF)
516 if (err == 0)
517 {
518 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
519 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
520 }
521 #endif
522 #else
523 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
524 #endif
525 }
526
527 // Add multicast group membership on this interface
528 if (err == 0)
529 {
530 imr.imr_multiaddr.s_addr = AllDNSLinkGroup.NotAnInteger;
531 imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
532 err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
533 if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
534 }
535
536 // Specify outgoing interface too
537 if (err == 0)
538 {
539 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
540 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
541 }
542
543 // Per the mDNS spec, send unicast packets with TTL 255
544 if (err == 0)
545 {
546 err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
547 if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
548 }
549
550 // and multicast packets with TTL 255 too
551 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
552 if (err == 0)
553 {
554 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
555 if (err < 0 && errno == EINVAL)
556 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
557 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
558 }
559
560 // And start listening for packets
561 if (err == 0)
562 {
563 bindAddr.sin_family = AF_INET;
564 bindAddr.sin_port = port.NotAnInteger;
565 bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
566 err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
567 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
568 }
569 } // endif (intfAddr->sa_family == AF_INET)
570
571 #ifdef mDNSIPv6Support
572 else if (intfAddr->sa_family == AF_INET6)
573 {
574 struct ipv6_mreq imr6;
575 struct sockaddr_in6 bindAddr6;
576 if (err == 0)
577 {
578 #if defined(IPV6_PKTINFO)
579 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_PKTINFO, &kOn, sizeof(kOn));
580 if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
581 #else
582 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
583 #endif
584 }
585
586 // Add multicast group membership on this interface
587 if (err == 0)
588 {
589 imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroupv6;
590 imr6.ipv6mr_interface = interfaceIndex;
591 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
592 if (err < 0)
593 {
594 err = errno;
595 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
596 perror("setsockopt - IPV6_JOIN_GROUP");
597 }
598 }
599
600 // Specify outgoing interface too
601 if (err == 0)
602 {
603 u_int multicast_if = interfaceIndex;
604 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
605 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
606 }
607
608 // We want to receive only IPv6 packets on this socket.
609 // Without this option, we may get IPv4 addresses as mapped addresses.
610 if (err == 0)
611 {
612 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
613 if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
614 }
615
616 // Per the mDNS spec, send unicast packets with TTL 255
617 if (err == 0)
618 {
619 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
620 if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
621 }
622
623 // and multicast packets with TTL 255 too
624 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
625 if (err == 0)
626 {
627 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
628 if (err < 0 && errno == EINVAL)
629 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
630 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
631 }
632
633 // And start listening for packets
634 if (err == 0)
635 {
636 mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
637 bindAddr6.sin6_len = sizeof(bindAddr6);
638 bindAddr6.sin6_family = AF_INET6;
639 bindAddr6.sin6_port = port.NotAnInteger;
640 bindAddr6.sin6_flowinfo = 0;
641 // bindAddr6.sin6_addr.s_addr = IN6ADDR_ANY_INIT; // Want to receive multicasts AND unicasts on this socket
642 bindAddr6.sin6_scope_id = 0;
643 err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
644 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
645 }
646 } // endif (intfAddr->sa_family == AF_INET6)
647 #endif
648
649 // Set the socket to non-blocking.
650 if (err == 0)
651 {
652 err = fcntl(*sktPtr, F_GETFL, 0);
653 if (err < 0) err = errno;
654 else
655 {
656 err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
657 if (err < 0) err = errno;
658 }
659 }
660
661 // Clean up
662 if (err != 0 && *sktPtr != -1) { assert(close(*sktPtr) == 0); *sktPtr = -1; }
663 assert( (err == 0) == (*sktPtr != -1) );
664 return err;
665 }
666
667 // Creates a PosixNetworkInterface for the interface whose IP address is
668 // intfAddr and whose name is intfName and registers it with mDNS core.
669 static int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, const char *intfName)
670 {
671 int err = 0;
672 PosixNetworkInterface *intf;
673 PosixNetworkInterface *alias = NULL;
674
675 assert(m != NULL);
676 assert(intfAddr != NULL);
677 assert(intfName != NULL);
678
679 // Allocate the interface structure itself.
680 intf = malloc(sizeof(*intf));
681 if (intf == NULL) { assert(0); err = ENOMEM; }
682
683 // And make a copy of the intfName.
684 if (err == 0)
685 {
686 intf->intfName = strdup(intfName);
687 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
688 }
689
690 if (err == 0)
691 {
692 // Set up the fields required by the mDNS core.
693 SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
694 intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
695
696 // Set up the extra fields in PosixNetworkInterface.
697 assert(intf->intfName != NULL); // intf->intfName already set up above
698 intf->index = if_nametoindex(intf->intfName);
699 intf->multicastSocket = -1;
700 intf->multicastSocketv6 = -1;
701 alias = SearchForInterfaceByName(m, intf->intfName);
702 if (alias == NULL) alias = intf;
703 intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
704
705 if (alias != intf)
706 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
707 }
708
709 // Set up the multicast socket
710 if (err == 0)
711 {
712 if (alias->multicastSocket == -1 && intfAddr->sa_family == AF_INET)
713 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket);
714 #ifdef mDNSIPv6Support
715 else if (alias->multicastSocketv6 == -1 && intfAddr->sa_family == AF_INET6)
716 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocketv6);
717 #endif
718 }
719
720 // The interface is all ready to go, let's register it with the mDNS core.
721 if (err == 0)
722 err = mDNS_RegisterInterface(m, &intf->coreIntf);
723
724 // Clean up.
725 if (err == 0)
726 {
727 num_registered_interfaces++;
728 debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
729 if (gMDNSPlatformPosixVerboseLevel > 0)
730 fprintf(stderr, "Registered interface %s\n", intf->intfName);
731 }
732 else
733 {
734 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
735 debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
736 if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
737 }
738
739 assert( (err == 0) == (intf != NULL) );
740
741 return err;
742 }
743
744 static int SetupInterfaceList(mDNS *const m)
745 {
746 mDNSBool foundav4 = mDNSfalse;
747 int err = 0;
748 struct ifi_info *intfList = get_ifi_info(AF_INET, mDNStrue);
749 struct ifi_info *firstLoopback = NULL;
750
751 assert(m != NULL);
752 debugf("SetupInterfaceList");
753
754 if (intfList == NULL) err = ENOENT;
755
756 #ifdef mDNSIPv6Support
757 if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
758 {
759 struct ifi_info **p = &intfList;
760 while (*p) p = &(*p)->ifi_next;
761 *p = get_ifi_info(AF_INET6, mDNStrue);
762 }
763 #endif
764
765 if (err == 0)
766 {
767 struct ifi_info *i = intfList;
768 while (i)
769 {
770 if ( ((i->ifi_addr->sa_family == AF_INET)
771 #ifdef mDNSIPv6Support
772 || (i->ifi_addr->sa_family == AF_INET6)
773 #endif
774 ) && (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT) )
775 {
776 if (i->ifi_flags & IFF_LOOPBACK)
777 {
778 if (firstLoopback == NULL)
779 firstLoopback = i;
780 }
781 else
782 {
783 if (SetupOneInterface(m, i->ifi_addr, i->ifi_name) == 0)
784 if (i->ifi_addr->sa_family == AF_INET)
785 foundav4 = mDNStrue;
786 }
787 }
788 i = i->ifi_next;
789 }
790
791 // If we found no normal interfaces but we did find a loopback interface, register the
792 // loopback interface. This allows self-discovery if no interfaces are configured.
793 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
794 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
795 // if ( (m->HostInterfaces == NULL) && (firstLoopback != NULL) )
796 if ( !foundav4 && firstLoopback )
797 (void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_name);
798 }
799
800 // Clean up.
801 if (intfList != NULL) free_ifi_info(intfList);
802 return err;
803 }
804
805 // mDNS core calls this routine to initialise the platform-specific data.
806 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
807 {
808 int err;
809 assert(m != NULL);
810
811 // Tell mDNS core the names of this machine.
812
813 // Set up the nice label
814 m->nicelabel.c[0] = 0;
815 GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
816 if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Macintosh");
817
818 // Set up the RFC 1034-compliant label
819 m->hostlabel.c[0] = 0;
820 GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
821 if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Macintosh");
822
823 mDNS_GenerateFQDN(m);
824
825 // Tell mDNS core about the network interfaces on this machine.
826 err = SetupInterfaceList(m);
827
828 // We don't do asynchronous initialization on the Posix platform, so by the time
829 // we get here the setup will already have succeeded or failed. If it succeeded,
830 // we should just call mDNSCoreInitComplete() immediately.
831 if (err == 0)
832 mDNSCoreInitComplete(m, mStatus_NoError);
833
834 return PosixErrorToStatus(err);
835 }
836
837 // mDNS core calls this routine to clean up the platform-specific data.
838 // In our case all we need to do is to tear down every network interface.
839 mDNSexport void mDNSPlatformClose(mDNS *const m)
840 {
841 assert(m != NULL);
842 ClearInterfaceList(m);
843 }
844
845 extern mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
846 {
847 int err;
848 ClearInterfaceList(m);
849 err = SetupInterfaceList(m);
850 return PosixErrorToStatus(err);
851 }
852
853 #if COMPILER_LIKES_PRAGMA_MARK
854 #pragma mark ***** Locking
855 #endif
856
857 // On the Posix platform, locking is a no-op because we only ever enter
858 // mDNS core on the main thread.
859
860 // mDNS core calls this routine when it wants to prevent
861 // the platform from reentering mDNS core code.
862 mDNSexport void mDNSPlatformLock (const mDNS *const m)
863 {
864 (void) m; // Unused
865 }
866
867 // mDNS core calls this routine when it release the lock taken by
868 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
869 mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
870 {
871 (void) m; // Unused
872 }
873
874 #if COMPILER_LIKES_PRAGMA_MARK
875 #pragma mark ***** Strings
876 #endif
877
878 // mDNS core calls this routine to copy C strings.
879 // On the Posix platform this maps directly to the ANSI C strcpy.
880 mDNSexport void mDNSPlatformStrCopy(const void *src, void *dst)
881 {
882 strcpy((char *)dst, (char *)src);
883 }
884
885 // mDNS core calls this routine to get the length of a C string.
886 // On the Posix platform this maps directly to the ANSI C strlen.
887 mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
888 {
889 return strlen((char*)src);
890 }
891
892 // mDNS core calls this routine to copy memory.
893 // On the Posix platform this maps directly to the ANSI C memcpy.
894 mDNSexport void mDNSPlatformMemCopy(const void *src, void *dst, mDNSu32 len)
895 {
896 memcpy(dst, src, len);
897 }
898
899 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
900 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
901 mDNSexport mDNSBool mDNSPlatformMemSame(const void *src, const void *dst, mDNSu32 len)
902 {
903 return memcmp(dst, src, len) == 0;
904 }
905
906 // mDNS core calls this routine to clear blocks of memory.
907 // On the Posix platform this is a simple wrapper around ANSI C memset.
908 mDNSexport void mDNSPlatformMemZero( void *dst, mDNSu32 len)
909 {
910 memset(dst, 0, len);
911 }
912
913 mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
914 mDNSexport void mDNSPlatformMemFree (void *mem) { free(mem); }
915
916 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
917
918 mDNSexport mStatus mDNSPlatformTimeInit(mDNSs32 *timenow)
919 {
920 // No special setup is required on Posix -- we just use gettimeofday();
921 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
922 // We should find a better way to do this
923 *timenow = mDNSPlatformTimeNow();
924 return(mStatus_NoError);
925 }
926
927 mDNSexport mDNSs32 mDNSPlatformTimeNow()
928 {
929 struct timeval tv;
930 gettimeofday(&tv, NULL);
931 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
932 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
933 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
934 // and we multiply tv.tv_usec by 16 / 15625 to get a value in the range 0-1023 to go in the bottom 10 bits.
935 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
936 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
937 return( (tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625) );
938 }
939
940 mDNSexport void mDNSPosixGetFDSet(mDNS *const m, int *nfds, fd_set *readfds, struct timeval *timeout)
941 {
942 mDNSs32 ticks;
943 struct timeval interval;
944
945 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
946 mDNSs32 nextevent = mDNS_Execute(m);
947
948 // 2. Build our list of active file descriptors
949 PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
950 while (info)
951 {
952 if (info->multicastSocket != -1)
953 {
954 if (*nfds < info->multicastSocket + 1)
955 *nfds = info->multicastSocket + 1;
956 FD_SET(info->multicastSocket, readfds);
957 }
958 if (info->multicastSocketv6 != -1)
959 {
960 if (*nfds < info->multicastSocketv6 + 1)
961 *nfds = info->multicastSocketv6 + 1;
962 FD_SET(info->multicastSocketv6, readfds);
963 }
964 info = (PosixNetworkInterface *)(info->coreIntf.next);
965 }
966
967 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
968 ticks = nextevent - mDNSPlatformTimeNow();
969 if (ticks < 1) ticks = 1;
970 interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
971 interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
972
973 // 4. If client's proposed timeout is more than what we want, then reduce it
974 if (timeout->tv_sec > interval.tv_sec ||
975 (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
976 *timeout = interval;
977 }
978
979 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
980 {
981 PosixNetworkInterface *info;
982 assert(m != NULL);
983 assert(readfds != NULL);
984 info = (PosixNetworkInterface *)(m->HostInterfaces);
985 while (info)
986 {
987 if (info->multicastSocket != -1 && FD_ISSET(info->multicastSocket, readfds))
988 {
989 FD_CLR(info->multicastSocket, readfds);
990 SocketDataReady(m, info, info->multicastSocket);
991 }
992 if (info->multicastSocketv6 != -1 && FD_ISSET(info->multicastSocketv6, readfds))
993 {
994 FD_CLR(info->multicastSocketv6, readfds);
995 SocketDataReady(m, info, info->multicastSocketv6);
996 }
997 info = (PosixNetworkInterface *)(info->coreIntf.next);
998 }
999 }