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