]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSPosix/mDNSPosix.c
mDNSResponder-66.3.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 * Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved.
7 *
8 * This file contains Original Code and/or Modifications of Original Code
9 * as defined in and that are subject to the Apple Public Source License
10 * Version 2.0 (the 'License'). You may not use this file except in
11 * compliance with the License. Please obtain a copy of the License at
12 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * file.
14 *
15 * The Original Code and all software distributed under the License are
16 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
17 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
18 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
20 * Please see the License for the specific language governing rights and
21 * limitations under the License.
22 *
23 * @APPLE_LICENSE_HEADER_END@
24 *
25 * Formatting notes:
26 * This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
27 * on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
28 * but for the sake of brevity here I will say just this: Curly braces are not syntactially
29 * part of an "if" statement; they are the beginning and ending markers of a compound statement;
30 * therefore common sense dictates that if they are part of a compound statement then they
31 * should be indented to the same level as everything else in that compound statement.
32 * Indenting curly braces at the same level as the "if" implies that curly braces are
33 * part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
34 * thinking that variables x and y are both of type "char*" -- and anyone who doesn't
35 * understand why variable y is not of type "char*" just proves the point that poor code
36 * layout leads people to unfortunate misunderstandings about how the C language really works.)
37
38 Change History (most recent first):
39
40 $Log: mDNSPosix.c,v $
41 Revision 1.46 2004/05/13 04:54:20 ksekar
42 Unified list copy/free code. Added symetric list for
43
44 Revision 1.45 2004/05/12 22:03:09 ksekar
45 Made GetSearchDomainList a true platform-layer call (declaration moved
46 from mDNSMacOSX.h to mDNSClientAPI.h), impelemted to return "local"
47 only on non-OSX platforms. Changed call to return a copy of the list
48 to avoid shared memory issues. Added a routine to free the list.
49
50 Revision 1.44 2004/04/21 02:49:11 cheshire
51 To reduce future confusion, renamed 'TxAndRx' to 'McastTxRx'
52
53 Revision 1.43 2004/04/14 23:09:29 ksekar
54 Support for TSIG signed dynamic updates.
55
56 Revision 1.42 2004/04/09 17:43:04 cheshire
57 Make sure to set the McastTxRx field so that duplicate suppression works correctly
58
59 Revision 1.41 2004/02/06 01:19:51 cheshire
60 Conditionally exclude IPv6 code unless HAVE_IPV6 is set
61
62 Revision 1.40 2004/02/05 01:00:01 rpantos
63 Fix some issues that turned up when building for FreeBSD.
64
65 Revision 1.39 2004/01/28 21:12:15 cheshire
66 Reconcile mDNSIPv6Support & HAVE_IPV6 into a single flag (HAVE_IPV6)
67
68 Revision 1.38 2004/01/27 20:15:23 cheshire
69 <rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
70
71 Revision 1.37 2004/01/24 05:12:03 cheshire
72 <rdar://problem/3534352>: Need separate socket for issuing unicast queries
73
74 Revision 1.36 2004/01/24 04:59:16 cheshire
75 Fixes so that Posix/Linux, OS9, Windows, and VxWorks targets build again
76
77 Revision 1.35 2004/01/23 21:37:08 cheshire
78 For consistency, rename multicastSocket to multicastSocket4, and multicastSocketv6 to multicastSocket6
79
80 Revision 1.34 2004/01/22 03:43:09 cheshire
81 Export constants like mDNSInterface_LocalOnly so that the client layers can use them
82
83 Revision 1.33 2004/01/21 21:54:20 cheshire
84 <rdar://problem/3448144>: Don't try to receive unicast responses if we're not the first to bind to the UDP port
85
86 Revision 1.32 2004/01/20 01:49:28 rpantos
87 Tweak error handling of last checkin a bit.
88
89 Revision 1.31 2004/01/20 01:39:27 rpantos
90 Respond to If changes by rebuilding interface list.
91
92 Revision 1.30 2003/12/11 19:40:36 cheshire
93 Fix 'destAddr.type == senderAddr.type;' that should have said 'destAddr.type = senderAddr.type;'
94
95 Revision 1.29 2003/12/11 18:53:22 cheshire
96 Fix compiler warning reported by Paul Guyot
97
98 Revision 1.28 2003/12/11 03:03:51 rpantos
99 Clean up mDNSPosix so that it builds on OS X again.
100
101 Revision 1.27 2003/12/08 20:47:02 rpantos
102 Add support for mDNSResponder on Linux.
103
104 Revision 1.26 2003/11/14 20:59:09 cheshire
105 Clients can't use AssignDomainName macro because mDNSPlatformMemCopy is defined in mDNSPlatformFunctions.h.
106 Best solution is just to combine mDNSClientAPI.h and mDNSPlatformFunctions.h into a single file.
107
108 Revision 1.25 2003/10/30 19:25:49 cheshire
109 Fix signed/unsigned warning on certain compilers
110
111 Revision 1.24 2003/08/18 23:12:23 cheshire
112 <rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformTimeNow()
113
114 Revision 1.23 2003/08/12 19:56:26 cheshire
115 Update to APSL 2.0
116
117 Revision 1.22 2003/08/06 18:46:15 cheshire
118 LogMsg() errors are serious -- always report them to stderr, regardless of debugging level
119
120 Revision 1.21 2003/08/06 18:20:51 cheshire
121 Makefile cleanup
122
123 Revision 1.20 2003/08/05 23:56:26 cheshire
124 Update code to compile with the new mDNSCoreReceive() function that requires a TTL
125 (Right now mDNSPosix.c just reports 255 -- we should fix this)
126
127 Revision 1.19 2003/07/19 03:15:16 cheshire
128 Add generic MemAllocate/MemFree prototypes to mDNSPlatformFunctions.h,
129 and add the obvious trivial implementations to each platform support layer
130
131 Revision 1.18 2003/07/14 18:11:54 cheshire
132 Fix stricter compiler warnings
133
134 Revision 1.17 2003/07/13 01:08:38 cheshire
135 There's not much point running mDNS over a point-to-point link; exclude those
136
137 Revision 1.16 2003/07/02 21:19:59 cheshire
138 <rdar://problem/3313413> Update copyright notices, etc., in source code comments
139
140 Revision 1.15 2003/06/18 05:48:41 cheshire
141 Fix warnings
142
143 Revision 1.14 2003/05/26 03:21:30 cheshire
144 Tidy up address structure naming:
145 mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
146 mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
147 mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
148
149 Revision 1.13 2003/05/26 03:01:28 cheshire
150 <rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
151
152 Revision 1.12 2003/05/21 03:49:18 cheshire
153 Fix warning
154
155 Revision 1.11 2003/05/06 00:00:50 cheshire
156 <rdar://problem/3248914> Rationalize naming of domainname manipulation functions
157
158 Revision 1.10 2003/04/25 01:45:57 cheshire
159 <rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
160
161 Revision 1.9 2003/03/20 21:10:31 cheshire
162 Fixes done at IETF 56 to make mDNSProxyResponderPosix run on Solaris
163
164 Revision 1.8 2003/03/15 04:40:38 cheshire
165 Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
166
167 Revision 1.7 2003/03/13 03:46:21 cheshire
168 Fixes to make the code build on Linux
169
170 Revision 1.6 2003/03/08 00:35:56 cheshire
171 Switched to using new "mDNS_Execute" model (see "mDNSCore/Implementer Notes.txt")
172
173 Revision 1.5 2002/12/23 22:13:31 jgraessl
174 Reviewed by: Stuart Cheshire
175 Initial IPv6 support for mDNSResponder.
176
177 Revision 1.4 2002/09/27 01:47:45 cheshire
178 Workaround for Linux 2.0 systems that don't have IP_PKTINFO
179
180 Revision 1.3 2002/09/21 20:44:53 zarzycki
181 Added APSL info
182
183 Revision 1.2 2002/09/19 21:25:36 cheshire
184 mDNS_snprintf() doesn't need to be in a separate file
185
186 Revision 1.1 2002/09/17 06:24:34 cheshire
187 First checkin
188 */
189
190 #include "mDNSClientAPI.h" // Defines the interface provided to the client layer above
191 #include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
192
193 #include <assert.h>
194 #include <stdio.h>
195 #include <stdlib.h>
196 #include <errno.h>
197 #include <string.h>
198 #include <unistd.h>
199 #include <syslog.h>
200 #include <stdarg.h>
201 #include <fcntl.h>
202 #include <sys/types.h>
203 #include <sys/time.h>
204 #include <sys/socket.h>
205 #include <sys/uio.h>
206 #include <sys/select.h>
207 #include <netinet/in.h>
208 #include <time.h> // platform support for UTC time
209
210 #if USES_NETLINK
211 #include <asm/types.h>
212 #include <linux/netlink.h>
213 #include <linux/rtnetlink.h>
214 #else // USES_NETLINK
215 #include <net/route.h>
216 #include <net/if.h>
217 #endif // USES_NETLINK
218
219 #include "mDNSUNP.h"
220 #include "GenLinkedList.h"
221
222 // ***************************************************************************
223 // Structures
224
225 // We keep a list of client-supplied event sources in PosixEventSource records
226 struct PosixEventSource
227 {
228 mDNSPosixEventCallback Callback;
229 void *Context;
230 int fd;
231 struct PosixEventSource *Next;
232 };
233 typedef struct PosixEventSource PosixEventSource;
234
235 // Context record for interface change callback
236 struct IfChangeRec
237 {
238 int NotifySD;
239 mDNS* mDNS;
240 };
241 typedef struct IfChangeRec IfChangeRec;
242
243 // Note that static data is initialized to zero in (modern) C.
244 static fd_set gEventFDs;
245 static int gMaxFD; // largest fd in gEventFDs
246 static GenLinkedList gEventSources; // linked list of PosixEventSource's
247 static sigset_t gEventSignalSet; // Signals which event loop listens for
248 static sigset_t gEventSignals; // Signals which were received while inside loop
249
250 // ***************************************************************************
251 // Globals (for debugging)
252
253 static int num_registered_interfaces = 0;
254 static int num_pkts_accepted = 0;
255 static int num_pkts_rejected = 0;
256
257 // ***************************************************************************
258 // Functions
259
260 int gMDNSPlatformPosixVerboseLevel = 0;
261
262 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
263
264 static void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
265 {
266 switch (sa->sa_family)
267 {
268 case AF_INET:
269 {
270 struct sockaddr_in* sin = (struct sockaddr_in*)sa;
271 ipAddr->type = mDNSAddrType_IPv4;
272 ipAddr->ip.v4.NotAnInteger = sin->sin_addr.s_addr;
273 if (ipPort) ipPort->NotAnInteger = sin->sin_port;
274 break;
275 }
276
277 #if HAVE_IPV6
278 case AF_INET6:
279 {
280 struct sockaddr_in6* sin6 = (struct sockaddr_in6*)sa;
281 assert(sin6->sin6_len == sizeof(*sin6));
282 ipAddr->type = mDNSAddrType_IPv6;
283 ipAddr->ip.v6 = *(mDNSv6Addr*)&sin6->sin6_addr;
284 if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
285 break;
286 }
287 #endif
288
289 default:
290 verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
291 ipAddr->type = mDNSAddrType_None;
292 if (ipPort) ipPort->NotAnInteger = 0;
293 break;
294 }
295 }
296
297 #if COMPILER_LIKES_PRAGMA_MARK
298 #pragma mark ***** Send and Receive
299 #endif
300
301 // mDNS core calls this routine when it needs to send a packet.
302 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
303 mDNSInterfaceID InterfaceID, const mDNSAddr *dst, mDNSIPPort dstPort)
304 {
305 int err = 0;
306 struct sockaddr_storage to;
307 PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
308 int sendingsocket = -1;
309
310 assert(m != NULL);
311 assert(msg != NULL);
312 assert(end != NULL);
313 assert( (((char *) end) - ((char *) msg)) > 0 );
314 assert(dstPort.NotAnInteger != 0);
315
316 if (dst->type == mDNSAddrType_IPv4)
317 {
318 struct sockaddr_in *sin = (struct sockaddr_in*)&to;
319 #ifndef NOT_HAVE_SA_LEN
320 sin->sin_len = sizeof(*sin);
321 #endif
322 sin->sin_family = AF_INET;
323 sin->sin_port = dstPort.NotAnInteger;
324 sin->sin_addr.s_addr = dst->ip.v4.NotAnInteger;
325 sendingsocket = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
326 }
327
328 #if HAVE_IPV6
329 else if (dst->type == mDNSAddrType_IPv6)
330 {
331 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
332 mDNSPlatformMemZero(sin6, sizeof(*sin6));
333 sin6->sin6_len = sizeof(*sin6);
334 sin6->sin6_family = AF_INET6;
335 sin6->sin6_port = dstPort.NotAnInteger;
336 sin6->sin6_addr = *(struct in6_addr*)&dst->ip.v6;
337 sendingsocket = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
338 }
339 #endif
340
341 if (sendingsocket >= 0)
342 err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
343
344 if (err > 0) err = 0;
345 else if (err < 0)
346 {
347 if (thisIntf)
348 verbosedebugf("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
349 errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
350 else
351 verbosedebugf("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
352 }
353
354 return PosixErrorToStatus(err);
355 }
356
357 // This routine is called when the main loop detects that data is available on a socket.
358 static void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
359 {
360 mDNSAddr senderAddr, destAddr;
361 mDNSIPPort senderPort;
362 ssize_t packetLen;
363 DNSMessage packet;
364 struct my_in_pktinfo packetInfo;
365 struct sockaddr_storage from;
366 socklen_t fromLen;
367 int flags;
368 mDNSu8 ttl;
369 mDNSBool reject;
370 const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
371
372 assert(m != NULL);
373 assert(skt >= 0);
374
375 fromLen = sizeof(from);
376 flags = 0;
377 packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
378
379 if (packetLen >= 0)
380 {
381 SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
382 SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
383
384 // If we have broken IP_RECVDSTADDR functionality (so far
385 // I've only seen this on OpenBSD) then apply a hack to
386 // convince mDNS Core that this isn't a spoof packet.
387 // Basically what we do is check to see whether the
388 // packet arrived as a multicast and, if so, set its
389 // destAddr to the mDNS address.
390 //
391 // I must admit that I could just be doing something
392 // wrong on OpenBSD and hence triggering this problem
393 // but I'm at a loss as to how.
394 //
395 // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
396 // no way to tell the destination address or interface this packet arrived on,
397 // so all we can do is just assume it's a multicast
398
399 #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
400 if ( (destAddr.NotAnInteger == 0) && (flags & MSG_MCAST) )
401 {
402 destAddr.type = senderAddr.type;
403 if (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup;
404 else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroupv6;
405 }
406 #endif
407
408 // We only accept the packet if the interface on which it came
409 // in matches the interface associated with this socket.
410 // We do this match by name or by index, depending on which
411 // information is available. recvfrom_flags sets the name
412 // to "" if the name isn't available, or the index to -1
413 // if the index is available. This accomodates the various
414 // different capabilities of our target platforms.
415
416 reject = mDNSfalse;
417 if (intf)
418 {
419 if ( packetInfo.ipi_ifname[0] != 0 ) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
420 else if ( packetInfo.ipi_ifindex != -1 ) reject = (packetInfo.ipi_ifindex != intf->index);
421
422 if (reject)
423 {
424 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d",
425 &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
426 &intf->coreIntf.ip, intf->intfName, intf->index);
427 packetLen = -1;
428 num_pkts_rejected++;
429 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
430 {
431 fprintf(stderr,
432 "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
433 num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
434 num_pkts_accepted = 0;
435 num_pkts_rejected = 0;
436 }
437 }
438 else
439 {
440 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d",
441 &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index);
442 num_pkts_accepted++;
443 }
444 }
445 }
446
447 if (packetLen >= 0 && packetLen < (ssize_t)sizeof(DNSMessageHeader))
448 {
449 debugf("SocketDataReady packet length (%d) too short", packetLen);
450 packetLen = -1;
451 }
452
453 if (packetLen >= 0)
454 mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
455 &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID, ttl);
456 }
457
458 mDNSexport mStatus mDNSPlatformTCPConnect(const mDNSAddr *dst, mDNSOpaque16 dstport, mDNSInterfaceID InterfaceID,
459 TCPConnectionCallback callback, void *context, int *descriptor)
460 {
461 (void)dst; // Unused
462 (void)dstport; // Unused
463 (void)InterfaceID; // Unused
464 (void)callback; // Unused
465 (void)context; // Unused
466 (void)descriptor; // Unused
467 return(mStatus_UnsupportedErr);
468 }
469
470 mDNSexport void mDNSPlatformTCPCloseConnection(int sd)
471 {
472 (void)sd; // Unused
473 }
474
475 mDNSexport int mDNSPlatformReadTCP(int sd, void *buf, int buflen)
476 {
477 (void)sd; // Unused
478 (void)buf; // Unused
479 (void)buflen; // Unused
480 return(0);
481 }
482
483 mDNSexport int mDNSPlatformWriteTCP(int sd, const char *msg, int len)
484 {
485 (void)sd; // Unused
486 (void)msg; // Unused
487 (void)len; // Unused
488 return(0);
489 }
490
491 #if COMPILER_LIKES_PRAGMA_MARK
492 #pragma mark ***** Get/Free Search Domain List
493 #endif
494
495 mDNSexport DNameListElem *mDNSPlatformGetSearchDomainList(void)
496 {
497 static DNameListElem tmp;
498 static mDNSBool init = mDNSfalse;
499
500 if (!init)
501 {
502 MakeDomainNameFromDNSNameString(&tmp.name, "local.");
503 tmp.next = NULL;
504 init = mDNStrue;
505 }
506 return mDNS_CopyDNameList(&tmp);
507 }
508
509 #if COMPILER_LIKES_PRAGMA_MARK
510 #pragma mark ***** Init and Term
511 #endif
512
513 // This gets the current hostname, truncating it at the first dot if necessary
514 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
515 {
516 int len = 0;
517 gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
518 while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
519 namelabel->c[0] = len;
520 }
521
522 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
523 // Other platforms can either get the information from the appropriate place,
524 // or they can alternatively just require all registering services to provide an explicit name
525 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
526 {
527 // On Unix we have no better name than the host name, so we just use that.
528 GetUserSpecifiedRFC1034ComputerName( namelabel);
529 }
530
531 // Searches the interface list looking for the named interface.
532 // Returns a pointer to if it found, or NULL otherwise.
533 static PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
534 {
535 PosixNetworkInterface *intf;
536
537 assert(m != NULL);
538 assert(intfName != NULL);
539
540 intf = (PosixNetworkInterface*)(m->HostInterfaces);
541 while ( (intf != NULL) && (strcmp(intf->intfName, intfName) != 0) )
542 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
543
544 return intf;
545 }
546
547 extern mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(const mDNS *const m, mDNSu32 index)
548 {
549 PosixNetworkInterface *intf;
550
551 assert(m != NULL);
552
553 if (index == (uint32_t)~0) return(mDNSInterface_LocalOnly);
554
555 intf = (PosixNetworkInterface*)(m->HostInterfaces);
556 while ( (intf != NULL) && (mDNSu32) intf->index != index)
557 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
558
559 return (mDNSInterfaceID) intf;
560 }
561
562 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(const mDNS *const m, mDNSInterfaceID id)
563 {
564 PosixNetworkInterface *intf;
565
566 assert(m != NULL);
567
568 if (id == mDNSInterface_LocalOnly) return((mDNSu32)~0);
569
570 intf = (PosixNetworkInterface*)(m->HostInterfaces);
571 while ( (intf != NULL) && (mDNSInterfaceID) intf != id)
572 intf = (PosixNetworkInterface *)(intf->coreIntf.next);
573
574 return intf ? intf->index : 0;
575 }
576
577 // Frees the specified PosixNetworkInterface structure. The underlying
578 // interface must have already been deregistered with the mDNS core.
579 static void FreePosixNetworkInterface(PosixNetworkInterface *intf)
580 {
581 assert(intf != NULL);
582 if (intf->intfName != NULL) free((void *)intf->intfName);
583 if (intf->multicastSocket4 != -1) assert(close(intf->multicastSocket4) == 0);
584 #if HAVE_IPV6
585 if (intf->multicastSocket6 != -1) assert(close(intf->multicastSocket6) == 0);
586 #endif
587 free(intf);
588 }
589
590 // Grab the first interface, deregister it, free it, and repeat until done.
591 static void ClearInterfaceList(mDNS *const m)
592 {
593 assert(m != NULL);
594
595 while (m->HostInterfaces)
596 {
597 PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
598 mDNS_DeregisterInterface(m, &intf->coreIntf);
599 if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
600 FreePosixNetworkInterface(intf);
601 }
602 num_registered_interfaces = 0;
603 num_pkts_accepted = 0;
604 num_pkts_rejected = 0;
605 }
606
607 // Sets up a send/receive socket.
608 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
609 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
610 static int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
611 {
612 int err = 0;
613 static const int kOn = 1;
614 static const int kIntTwoFiveFive = 255;
615 static const unsigned char kByteTwoFiveFive = 255;
616
617 (void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
618 assert(intfAddr != NULL);
619 assert(sktPtr != NULL);
620 assert(*sktPtr == -1);
621
622 // Open the socket...
623 if (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
624 #if HAVE_IPV6
625 else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
626 #endif
627 else return EINVAL;
628
629 if (*sktPtr < 0) { err = errno; perror("socket"); }
630
631 // ... with a shared UDP port, if it's for multicast receiving
632 if (err == 0 && port.NotAnInteger)
633 {
634 #if defined(SO_REUSEPORT)
635 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
636 #elif defined(SO_REUSEADDR)
637 err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
638 #else
639 #error This platform has no way to avoid address busy errors on multicast.
640 #endif
641 if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
642 }
643
644 // We want to receive destination addresses and interface identifiers.
645 if (intfAddr->sa_family == AF_INET)
646 {
647 struct ip_mreq imr;
648 struct sockaddr_in bindAddr;
649 if (err == 0)
650 {
651 #if defined(IP_PKTINFO) // Linux
652 err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
653 if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
654 #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF) // BSD and Solaris
655 #if defined(IP_RECVDSTADDR)
656 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
657 if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
658 #endif
659 #if defined(IP_RECVIF)
660 if (err == 0)
661 {
662 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
663 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
664 }
665 #endif
666 #else
667 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
668 #endif
669 }
670 #if defined(IP_RECVTTL) // Linux
671 if (err == 0)
672 {
673 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
674 if (err < 0) { err = errno; perror("setsockopt - IP_RECVTTL"); }
675 }
676 #endif
677
678 // Add multicast group membership on this interface
679 if (err == 0 && port.NotAnInteger)
680 {
681 imr.imr_multiaddr.s_addr = AllDNSLinkGroup.NotAnInteger;
682 imr.imr_interface = ((struct sockaddr_in*)intfAddr)->sin_addr;
683 err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
684 if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
685 }
686
687 // Specify outgoing interface too
688 if (err == 0 && port.NotAnInteger)
689 {
690 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
691 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
692 }
693
694 // Per the mDNS spec, send unicast packets with TTL 255
695 if (err == 0)
696 {
697 err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
698 if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
699 }
700
701 // and multicast packets with TTL 255 too
702 // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
703 if (err == 0)
704 {
705 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
706 if (err < 0 && errno == EINVAL)
707 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
708 if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
709 }
710
711 // And start listening for packets
712 if (err == 0)
713 {
714 bindAddr.sin_family = AF_INET;
715 bindAddr.sin_port = port.NotAnInteger;
716 bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
717 err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
718 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
719 }
720 } // endif (intfAddr->sa_family == AF_INET)
721
722 #if HAVE_IPV6
723 else if (intfAddr->sa_family == AF_INET6)
724 {
725 struct ipv6_mreq imr6;
726 struct sockaddr_in6 bindAddr6;
727 #if defined(IPV6_PKTINFO)
728 if (err == 0)
729 {
730 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_PKTINFO, &kOn, sizeof(kOn));
731 if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
732 }
733 #else
734 #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
735 #endif
736 #if defined(IPV6_HOPLIMIT)
737 if (err == 0)
738 {
739 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_HOPLIMIT, &kOn, sizeof(kOn));
740 if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
741 }
742 #endif
743
744 // Add multicast group membership on this interface
745 if (err == 0 && port.NotAnInteger)
746 {
747 imr6.ipv6mr_multiaddr = *(const struct in6_addr*)&AllDNSLinkGroupv6;
748 imr6.ipv6mr_interface = interfaceIndex;
749 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
750 if (err < 0)
751 {
752 err = errno;
753 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
754 perror("setsockopt - IPV6_JOIN_GROUP");
755 }
756 }
757
758 // Specify outgoing interface too
759 if (err == 0 && port.NotAnInteger)
760 {
761 u_int multicast_if = interfaceIndex;
762 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
763 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
764 }
765
766 // We want to receive only IPv6 packets on this socket.
767 // Without this option, we may get IPv4 addresses as mapped addresses.
768 if (err == 0)
769 {
770 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
771 if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
772 }
773
774 // Per the mDNS spec, send unicast packets with TTL 255
775 if (err == 0)
776 {
777 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
778 if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
779 }
780
781 // and multicast packets with TTL 255 too
782 // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
783 if (err == 0)
784 {
785 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
786 if (err < 0 && errno == EINVAL)
787 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
788 if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
789 }
790
791 // And start listening for packets
792 if (err == 0)
793 {
794 mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
795 bindAddr6.sin6_len = sizeof(bindAddr6);
796 bindAddr6.sin6_family = AF_INET6;
797 bindAddr6.sin6_port = port.NotAnInteger;
798 bindAddr6.sin6_flowinfo = 0;
799 // bindAddr6.sin6_addr.s_addr = IN6ADDR_ANY_INIT; // Want to receive multicasts AND unicasts on this socket
800 bindAddr6.sin6_scope_id = 0;
801 err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
802 if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
803 }
804 } // endif (intfAddr->sa_family == AF_INET6)
805 #endif
806
807 // Set the socket to non-blocking.
808 if (err == 0)
809 {
810 err = fcntl(*sktPtr, F_GETFL, 0);
811 if (err < 0) err = errno;
812 else
813 {
814 err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
815 if (err < 0) err = errno;
816 }
817 }
818
819 // Clean up
820 if (err != 0 && *sktPtr != -1) { assert(close(*sktPtr) == 0); *sktPtr = -1; }
821 assert( (err == 0) == (*sktPtr != -1) );
822 return err;
823 }
824
825 // Creates a PosixNetworkInterface for the interface whose IP address is
826 // intfAddr and whose name is intfName and registers it with mDNS core.
827 static int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, const char *intfName)
828 {
829 int err = 0;
830 PosixNetworkInterface *intf;
831 PosixNetworkInterface *alias = NULL;
832
833 assert(m != NULL);
834 assert(intfAddr != NULL);
835 assert(intfName != NULL);
836
837 // Allocate the interface structure itself.
838 intf = (PosixNetworkInterface*)malloc(sizeof(*intf));
839 if (intf == NULL) { assert(0); err = ENOMEM; }
840
841 // And make a copy of the intfName.
842 if (err == 0)
843 {
844 intf->intfName = strdup(intfName);
845 if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
846 }
847
848 if (err == 0)
849 {
850 // Set up the fields required by the mDNS core.
851 SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
852 intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
853 intf->coreIntf.McastTxRx = mDNStrue;
854
855 // Set up the extra fields in PosixNetworkInterface.
856 assert(intf->intfName != NULL); // intf->intfName already set up above
857 intf->index = if_nametoindex(intf->intfName);
858 intf->multicastSocket4 = -1;
859 #if HAVE_IPV6
860 intf->multicastSocket6 = -1;
861 #endif
862 alias = SearchForInterfaceByName(m, intf->intfName);
863 if (alias == NULL) alias = intf;
864 intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
865
866 if (alias != intf)
867 debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
868 }
869
870 // Set up the multicast socket
871 if (err == 0)
872 {
873 if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
874 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
875 #if HAVE_IPV6
876 else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
877 err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
878 #endif
879 }
880
881 // The interface is all ready to go, let's register it with the mDNS core.
882 if (err == 0)
883 err = mDNS_RegisterInterface(m, &intf->coreIntf);
884
885 // Clean up.
886 if (err == 0)
887 {
888 num_registered_interfaces++;
889 debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
890 if (gMDNSPlatformPosixVerboseLevel > 0)
891 fprintf(stderr, "Registered interface %s\n", intf->intfName);
892 }
893 else
894 {
895 // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
896 debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
897 if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
898 }
899
900 assert( (err == 0) == (intf != NULL) );
901
902 return err;
903 }
904
905 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
906 static int SetupInterfaceList(mDNS *const m)
907 {
908 mDNSBool foundav4 = mDNSfalse;
909 int err = 0;
910 struct ifi_info *intfList = get_ifi_info(AF_INET, mDNStrue);
911 struct ifi_info *firstLoopback = NULL;
912
913 assert(m != NULL);
914 debugf("SetupInterfaceList");
915
916 if (intfList == NULL) err = ENOENT;
917
918 #if HAVE_IPV6
919 if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
920 {
921 struct ifi_info **p = &intfList;
922 while (*p) p = &(*p)->ifi_next;
923 *p = get_ifi_info(AF_INET6, mDNStrue);
924 }
925 #endif
926
927 if (err == 0)
928 {
929 struct ifi_info *i = intfList;
930 while (i)
931 {
932 if ( ((i->ifi_addr->sa_family == AF_INET)
933 #if HAVE_IPV6
934 || (i->ifi_addr->sa_family == AF_INET6)
935 #endif
936 ) && (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT) )
937 {
938 if (i->ifi_flags & IFF_LOOPBACK)
939 {
940 if (firstLoopback == NULL)
941 firstLoopback = i;
942 }
943 else
944 {
945 if (SetupOneInterface(m, i->ifi_addr, i->ifi_name) == 0)
946 if (i->ifi_addr->sa_family == AF_INET)
947 foundav4 = mDNStrue;
948 }
949 }
950 i = i->ifi_next;
951 }
952
953 // If we found no normal interfaces but we did find a loopback interface, register the
954 // loopback interface. This allows self-discovery if no interfaces are configured.
955 // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
956 // In the interim, we skip loopback interface only if we found at least one v4 interface to use
957 // if ( (m->HostInterfaces == NULL) && (firstLoopback != NULL) )
958 if ( !foundav4 && firstLoopback )
959 (void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_name);
960 }
961
962 // Clean up.
963 if (intfList != NULL) free_ifi_info(intfList);
964 return err;
965 }
966
967 #if USES_NETLINK
968
969 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
970
971 // Open a socket that will receive interface change notifications
972 mStatus OpenIfNotifySocket( int *pFD)
973 {
974 mStatus err = mStatus_NoError;
975 struct sockaddr_nl snl;
976 int sock;
977 int ret;
978
979 sock = socket( AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
980 if (sock < 0)
981 return errno;
982
983 // Configure read to be non-blocking because inbound msg size is not known in advance
984 (void) fcntl( sock, F_SETFL, O_NONBLOCK);
985
986 /* Subscribe the socket to Link & IP addr notifications. */
987 bzero( &snl, sizeof snl);
988 snl.nl_family = AF_NETLINK;
989 snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
990 ret = bind( sock, (struct sockaddr *) &snl, sizeof snl);
991 if ( 0 == ret)
992 *pFD = sock;
993 else
994 err = errno;
995
996 return err;
997 }
998
999 #if MDNS_DEBUGMSGS
1000 static void PrintNetLinkMsg( const struct nlmsghdr *pNLMsg)
1001 {
1002 const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1003 const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1004
1005 printf( "nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
1006 pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[ pNLMsg->nlmsg_type] : kNLRtMsgTypes[ pNLMsg->nlmsg_type - RTM_BASE],
1007 pNLMsg->nlmsg_flags);
1008
1009 if ( RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
1010 {
1011 struct ifinfomsg *pIfInfo = (struct ifinfomsg*) NLMSG_DATA( pNLMsg);
1012 printf( "ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
1013 pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
1014
1015 }
1016 else if ( RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
1017 {
1018 struct ifaddrmsg *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA( pNLMsg);
1019 printf( "ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
1020 pIfAddr->ifa_index, pIfAddr->ifa_flags);
1021 }
1022 printf( "\n");
1023 }
1024 #endif
1025
1026 static uint32_t ProcessRoutingNotification( int sd)
1027 // Read through the messages on sd and if any indicate that any interface records should
1028 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1029 {
1030 ssize_t readCount;
1031 char buff[ 4096];
1032 struct nlmsghdr *pNLMsg = (struct nlmsghdr*) buff;
1033 uint32_t result = 0;
1034
1035 // The structure here is more complex than it really ought to be because,
1036 // unfortunately, there's no good way to size a buffer in advance large
1037 // enough to hold all pending data and so avoid message fragmentation.
1038 // (Note that FIONREAD is not supported on AF_NETLINK.)
1039
1040 readCount = read( sd, buff, sizeof buff);
1041 while ( 1)
1042 {
1043 // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1044 // If not, discard already-processed messages in buffer and read more data.
1045 if ( ( (char*) &pNLMsg[1] > ( buff + readCount)) || // i.e. *pNLMsg extends off end of buffer
1046 ( (char*) pNLMsg + pNLMsg->nlmsg_len > ( buff + readCount)))
1047 {
1048 if ( buff < (char*) pNLMsg) // we have space to shuffle
1049 {
1050 // discard processed data
1051 readCount -= ( (char*) pNLMsg - buff);
1052 memmove( buff, pNLMsg, readCount);
1053 pNLMsg = (struct nlmsghdr*) buff;
1054
1055 // read more data
1056 readCount += read( sd, buff + readCount, sizeof buff - readCount);
1057 continue; // spin around and revalidate with new readCount
1058 }
1059 else
1060 break; // Otherwise message does not fit in buffer
1061 }
1062
1063 #if MDNS_DEBUGMSGS
1064 PrintNetLinkMsg( pNLMsg);
1065 #endif
1066
1067 // Process the NetLink message
1068 if ( pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
1069 result |= 1 << ((struct ifinfomsg*) NLMSG_DATA( pNLMsg))->ifi_index;
1070 else if ( pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
1071 result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA( pNLMsg))->ifa_index;
1072
1073 // Advance pNLMsg to the next message in the buffer
1074 if ( ( pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
1075 {
1076 ssize_t len = readCount - ( (char*)pNLMsg - buff);
1077 pNLMsg = NLMSG_NEXT( pNLMsg, len);
1078 }
1079 else
1080 break; // all done!
1081 }
1082
1083 return result;
1084 }
1085
1086 #else // USES_NETLINK
1087
1088 // Open a socket that will receive interface change notifications
1089 mStatus OpenIfNotifySocket( int *pFD)
1090 {
1091 *pFD = socket( AF_ROUTE, SOCK_RAW, 0);
1092
1093 if ( *pFD < 0)
1094 return mStatus_UnknownErr;
1095
1096 // Configure read to be non-blocking because inbound msg size is not known in advance
1097 (void) fcntl( *pFD, F_SETFL, O_NONBLOCK);
1098
1099 return mStatus_NoError;
1100 }
1101
1102 #if MDNS_DEBUGMSGS
1103 static void PrintRoutingSocketMsg( const struct ifa_msghdr *pRSMsg)
1104 {
1105 const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1106 "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1107 "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1108
1109 int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
1110
1111 printf( "ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[ pRSMsg->ifam_type], index);
1112 }
1113 #endif
1114
1115 static uint32_t ProcessRoutingNotification( int sd)
1116 // Read through the messages on sd and if any indicate that any interface records should
1117 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1118 {
1119 ssize_t readCount;
1120 char buff[ 4096];
1121 struct ifa_msghdr *pRSMsg = (struct ifa_msghdr*) buff;
1122 uint32_t result = 0;
1123
1124 readCount = read( sd, buff, sizeof buff);
1125 if ( readCount < (ssize_t) sizeof( struct ifa_msghdr))
1126 return mStatus_UnsupportedErr; // cannot decipher message
1127
1128 #if MDNS_DEBUGMSGS
1129 PrintRoutingSocketMsg( pRSMsg);
1130 #endif
1131
1132 // Process the message
1133 if ( pRSMsg->ifam_type == RTM_NEWADDR || pRSMsg->ifam_type == RTM_DELADDR ||
1134 pRSMsg->ifam_type == RTM_IFINFO)
1135 {
1136 if ( pRSMsg->ifam_type == RTM_IFINFO)
1137 result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
1138 else
1139 result |= 1 << pRSMsg->ifam_index;
1140 }
1141
1142 return result;
1143 }
1144
1145 #endif // USES_NETLINK
1146
1147 // Called when data appears on interface change notification socket
1148 static void InterfaceChangeCallback( void *context)
1149 {
1150 IfChangeRec *pChgRec = (IfChangeRec*) context;
1151 fd_set readFDs;
1152 uint32_t changedInterfaces = 0;
1153 struct timeval zeroTimeout = { 0, 0 };
1154
1155 FD_ZERO( &readFDs);
1156 FD_SET( pChgRec->NotifySD, &readFDs);
1157
1158 do
1159 {
1160 changedInterfaces |= ProcessRoutingNotification( pChgRec->NotifySD);
1161 }
1162 while ( 0 < select( pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
1163
1164 // Currently we rebuild the entire interface list whenever any interface change is
1165 // detected. If this ever proves to be a performance issue in a multi-homed
1166 // configuration, more care should be paid to changedInterfaces.
1167 if ( changedInterfaces)
1168 mDNSPlatformPosixRefreshInterfaceList( pChgRec->mDNS);
1169 }
1170
1171 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1172 static mStatus WatchForInterfaceChange(mDNS *const m)
1173 {
1174 mStatus err;
1175 IfChangeRec *pChgRec;
1176
1177 pChgRec = (IfChangeRec*) mDNSPlatformMemAllocate( sizeof *pChgRec);
1178 if ( pChgRec == NULL)
1179 return mStatus_NoMemoryErr;
1180
1181 pChgRec->mDNS = m;
1182 err = OpenIfNotifySocket( &pChgRec->NotifySD);
1183 if ( err == 0)
1184 err = mDNSPosixAddFDToEventLoop( pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
1185
1186 return err;
1187 }
1188
1189 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1190 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1191 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1192 mDNSlocal mDNSBool mDNSPlatformInit_ReceiveUnicast(void)
1193 {
1194 int err;
1195 int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1196 struct sockaddr_in s5353;
1197 s5353.sin_family = AF_INET;
1198 s5353.sin_port = MulticastDNSPort.NotAnInteger;
1199 s5353.sin_addr.s_addr = 0;
1200 err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
1201 close(s);
1202 if (err) debugf("No unicast UDP responses");
1203 else debugf("Unicast UDP responses okay");
1204 return(err == 0);
1205 }
1206
1207 // mDNS core calls this routine to initialise the platform-specific data.
1208 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
1209 {
1210 int err = 0;
1211 struct sockaddr sa;
1212 assert(m != NULL);
1213
1214 if (mDNSPlatformInit_ReceiveUnicast()) m->CanReceiveUnicast = mDNStrue;
1215
1216 // Tell mDNS core the names of this machine.
1217
1218 // Set up the nice label
1219 m->nicelabel.c[0] = 0;
1220 GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
1221 if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Macintosh");
1222
1223 // Set up the RFC 1034-compliant label
1224 m->hostlabel.c[0] = 0;
1225 GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
1226 if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Macintosh");
1227
1228 mDNS_GenerateFQDN(m);
1229
1230 sa.sa_family = AF_INET;
1231 m->p->unicastSocket4 = -1;
1232 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
1233 #if HAVE_IPV6
1234 sa.sa_family = AF_INET6;
1235 m->p->unicastSocket6 = -1;
1236 if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
1237 #endif
1238
1239 // Tell mDNS core about the network interfaces on this machine.
1240 if (err == mStatus_NoError) err = SetupInterfaceList(m);
1241
1242 if (err == mStatus_NoError)
1243 {
1244 err = WatchForInterfaceChange(m);
1245 // Failure to observe interface changes is non-fatal.
1246 if ( err != mStatus_NoError)
1247 {
1248 fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
1249 err = mStatus_NoError;
1250 }
1251 }
1252
1253 // We don't do asynchronous initialization on the Posix platform, so by the time
1254 // we get here the setup will already have succeeded or failed. If it succeeded,
1255 // we should just call mDNSCoreInitComplete() immediately.
1256 if (err == mStatus_NoError)
1257 mDNSCoreInitComplete(m, mStatus_NoError);
1258
1259 return PosixErrorToStatus(err);
1260 }
1261
1262 // mDNS core calls this routine to clean up the platform-specific data.
1263 // In our case all we need to do is to tear down every network interface.
1264 mDNSexport void mDNSPlatformClose(mDNS *const m)
1265 {
1266 assert(m != NULL);
1267 ClearInterfaceList(m);
1268 if (m->p->unicastSocket4 != -1) assert(close(m->p->unicastSocket4) == 0);
1269 #if HAVE_IPV6
1270 if (m->p->unicastSocket6 != -1) assert(close(m->p->unicastSocket6) == 0);
1271 #endif
1272 }
1273
1274 extern mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
1275 {
1276 int err;
1277 ClearInterfaceList(m);
1278 err = SetupInterfaceList(m);
1279 return PosixErrorToStatus(err);
1280 }
1281
1282 #if COMPILER_LIKES_PRAGMA_MARK
1283 #pragma mark ***** Locking
1284 #endif
1285
1286 // On the Posix platform, locking is a no-op because we only ever enter
1287 // mDNS core on the main thread.
1288
1289 // mDNS core calls this routine when it wants to prevent
1290 // the platform from reentering mDNS core code.
1291 mDNSexport void mDNSPlatformLock (const mDNS *const m)
1292 {
1293 (void) m; // Unused
1294 }
1295
1296 // mDNS core calls this routine when it release the lock taken by
1297 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1298 mDNSexport void mDNSPlatformUnlock (const mDNS *const m)
1299 {
1300 (void) m; // Unused
1301 }
1302
1303 #if COMPILER_LIKES_PRAGMA_MARK
1304 #pragma mark ***** Strings
1305 #endif
1306
1307 // mDNS core calls this routine to copy C strings.
1308 // On the Posix platform this maps directly to the ANSI C strcpy.
1309 mDNSexport void mDNSPlatformStrCopy(const void *src, void *dst)
1310 {
1311 strcpy((char *)dst, (char *)src);
1312 }
1313
1314 // mDNS core calls this routine to get the length of a C string.
1315 // On the Posix platform this maps directly to the ANSI C strlen.
1316 mDNSexport mDNSu32 mDNSPlatformStrLen (const void *src)
1317 {
1318 return strlen((char*)src);
1319 }
1320
1321 // mDNS core calls this routine to copy memory.
1322 // On the Posix platform this maps directly to the ANSI C memcpy.
1323 mDNSexport void mDNSPlatformMemCopy(const void *src, void *dst, mDNSu32 len)
1324 {
1325 memcpy(dst, src, len);
1326 }
1327
1328 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1329 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1330 mDNSexport mDNSBool mDNSPlatformMemSame(const void *src, const void *dst, mDNSu32 len)
1331 {
1332 return memcmp(dst, src, len) == 0;
1333 }
1334
1335 // mDNS core calls this routine to clear blocks of memory.
1336 // On the Posix platform this is a simple wrapper around ANSI C memset.
1337 mDNSexport void mDNSPlatformMemZero( void *dst, mDNSu32 len)
1338 {
1339 memset(dst, 0, len);
1340 }
1341
1342 mDNSexport void * mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
1343 mDNSexport void mDNSPlatformMemFree (void *mem) { free(mem); }
1344
1345 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
1346
1347 mDNSexport mStatus mDNSPlatformTimeInit(mDNSs32 *timenow)
1348 {
1349 // No special setup is required on Posix -- we just use gettimeofday();
1350 // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1351 // We should find a better way to do this
1352 *timenow = mDNSPlatformTimeNow();
1353 return(mStatus_NoError);
1354 }
1355
1356 mDNSexport mDNSs32 mDNSPlatformTimeNow()
1357 {
1358 struct timeval tv;
1359 gettimeofday(&tv, NULL);
1360 // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1361 // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1362 // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1363 // 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.
1364 // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1365 // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1366 return( (tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625) );
1367 }
1368
1369 mDNSexport mDNSs32 mDNSPlatformUTC(void)
1370 {
1371 return time(NULL);
1372 }
1373
1374 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
1375 {
1376 if (*nfds < s + 1) *nfds = s + 1;
1377 FD_SET(s, readfds);
1378 }
1379
1380 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, struct timeval *timeout)
1381 {
1382 mDNSs32 ticks;
1383 struct timeval interval;
1384
1385 // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1386 mDNSs32 nextevent = mDNS_Execute(m);
1387
1388 // 2. Build our list of active file descriptors
1389 PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
1390 if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket4);
1391 #if HAVE_IPV6
1392 if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket6);
1393 #endif
1394 while (info)
1395 {
1396 if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket4);
1397 #if HAVE_IPV6
1398 if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket6);
1399 #endif
1400 info = (PosixNetworkInterface *)(info->coreIntf.next);
1401 }
1402
1403 // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1404 ticks = nextevent - mDNSPlatformTimeNow();
1405 if (ticks < 1) ticks = 1;
1406 interval.tv_sec = ticks >> 10; // The high 22 bits are seconds
1407 interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16; // The low 10 bits are 1024ths
1408
1409 // 4. If client's proposed timeout is more than what we want, then reduce it
1410 if (timeout->tv_sec > interval.tv_sec ||
1411 (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
1412 *timeout = interval;
1413 }
1414
1415 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
1416 {
1417 PosixNetworkInterface *info;
1418 assert(m != NULL);
1419 assert(readfds != NULL);
1420 info = (PosixNetworkInterface *)(m->HostInterfaces);
1421
1422 if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
1423 {
1424 FD_CLR(m->p->unicastSocket4, readfds);
1425 SocketDataReady(m, NULL, m->p->unicastSocket4);
1426 }
1427 #if HAVE_IPV6
1428 if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
1429 {
1430 FD_CLR(m->p->unicastSocket6, readfds);
1431 SocketDataReady(m, NULL, m->p->unicastSocket6);
1432 }
1433 #endif
1434
1435 while (info)
1436 {
1437 if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
1438 {
1439 FD_CLR(info->multicastSocket4, readfds);
1440 SocketDataReady(m, info, info->multicastSocket4);
1441 }
1442 #if HAVE_IPV6
1443 if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
1444 {
1445 FD_CLR(info->multicastSocket6, readfds);
1446 SocketDataReady(m, info, info->multicastSocket6);
1447 }
1448 #endif
1449 info = (PosixNetworkInterface *)(info->coreIntf.next);
1450 }
1451 }
1452
1453 // update gMaxFD
1454 static void DetermineMaxEventFD( void )
1455 {
1456 PosixEventSource *iSource;
1457
1458 gMaxFD = 0;
1459 for ( iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1460 if ( gMaxFD < iSource->fd)
1461 gMaxFD = iSource->fd;
1462 }
1463
1464 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1465 mStatus mDNSPosixAddFDToEventLoop( int fd, mDNSPosixEventCallback callback, void *context)
1466 {
1467 PosixEventSource *newSource;
1468
1469 if ( gEventSources.LinkOffset == 0)
1470 InitLinkedList( &gEventSources, offsetof( PosixEventSource, Next));
1471
1472 if ( fd >= (int) FD_SETSIZE || fd < 0)
1473 return mStatus_UnsupportedErr;
1474 if ( callback == NULL)
1475 return mStatus_BadParamErr;
1476
1477 newSource = (PosixEventSource*) malloc( sizeof *newSource);
1478 if ( NULL == newSource)
1479 return mStatus_NoMemoryErr;
1480
1481 newSource->Callback = callback;
1482 newSource->Context = context;
1483 newSource->fd = fd;
1484
1485 AddToTail( &gEventSources, newSource);
1486 FD_SET( fd, &gEventFDs);
1487
1488 DetermineMaxEventFD();
1489
1490 return mStatus_NoError;
1491 }
1492
1493 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1494 mStatus mDNSPosixRemoveFDFromEventLoop( int fd)
1495 {
1496 PosixEventSource *iSource;
1497
1498 for ( iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1499 {
1500 if ( fd == iSource->fd)
1501 {
1502 FD_CLR( fd, &gEventFDs);
1503 RemoveFromList( &gEventSources, iSource);
1504 free( iSource);
1505 DetermineMaxEventFD();
1506 return mStatus_NoError;
1507 }
1508 }
1509 return mStatus_NoSuchNameErr;
1510 }
1511
1512 // Simply note the received signal in gEventSignals.
1513 static void NoteSignal( int signum)
1514 {
1515 sigaddset( &gEventSignals, signum);
1516 }
1517
1518 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1519 mStatus mDNSPosixListenForSignalInEventLoop( int signum)
1520 {
1521 struct sigaction action;
1522 mStatus err;
1523
1524 bzero( &action, sizeof action); // more portable than member-wise assignment
1525 action.sa_handler = NoteSignal;
1526 err = sigaction( signum, &action, (struct sigaction*) NULL);
1527
1528 sigaddset( &gEventSignalSet, signum);
1529
1530 return err;
1531 }
1532
1533 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1534 mStatus mDNSPosixIgnoreSignalInEventLoop( int signum)
1535 {
1536 struct sigaction action;
1537 mStatus err;
1538
1539 bzero( &action, sizeof action); // more portable than member-wise assignment
1540 action.sa_handler = SIG_DFL;
1541 err = sigaction( signum, &action, (struct sigaction*) NULL);
1542
1543 sigdelset( &gEventSignalSet, signum);
1544
1545 return err;
1546 }
1547
1548 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1549 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1550 mStatus mDNSPosixRunEventLoopOnce( mDNS *m, const struct timeval *pTimeout,
1551 sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
1552 {
1553 fd_set listenFDs = gEventFDs;
1554 int fdMax = 0, numReady;
1555 struct timeval timeout = *pTimeout;
1556
1557 // Include the sockets that are listening to the wire in our select() set
1558 mDNSPosixGetFDSet( m, &fdMax, &listenFDs, &timeout); // timeout may get modified
1559 if ( fdMax < gMaxFD)
1560 fdMax = gMaxFD;
1561
1562 numReady = select( fdMax + 1, &listenFDs, (fd_set*) NULL, (fd_set*) NULL, &timeout);
1563
1564 // If any data appeared, invoke its callback
1565 if ( numReady > 0)
1566 {
1567 PosixEventSource *iSource;
1568
1569 (void) mDNSPosixProcessFDSet( m, &listenFDs); // call this first to process wire data for clients
1570
1571 for ( iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1572 {
1573 if ( FD_ISSET( iSource->fd, &listenFDs))
1574 {
1575 iSource->Callback( iSource->Context);
1576 break; // in case callback removed elements from gEventSources
1577 }
1578 }
1579 *pDataDispatched = mDNStrue;
1580 }
1581 else
1582 *pDataDispatched = mDNSfalse;
1583
1584 (void) sigprocmask( SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
1585 *pSignalsReceived = gEventSignals;
1586 sigemptyset( &gEventSignals);
1587 (void) sigprocmask( SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
1588
1589 return mStatus_NoError;
1590 }