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