xref: /illumos-gate/usr/src/contrib/mDNSResponder/mDNSPosix/mDNSPosix.c (revision 5328fc53d11d7151861fa272e4fb0248b8f0e145)
1 /* -*- Mode: C; tab-width: 4 -*-
2  *
3  * Copyright (c) 2002-2015 Apple Inc. All rights reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #include "mDNSEmbeddedAPI.h"           // Defines the interface provided to the client layer above
20 #include "DNSCommon.h"
21 #include "mDNSPosix.h"               // Defines the specific types needed to run mDNS on this platform
22 #include "dns_sd.h"
23 #include "dnssec.h"
24 #include "nsec.h"
25 
26 #include <assert.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <unistd.h>
32 #include <syslog.h>
33 #include <stdarg.h>
34 #include <fcntl.h>
35 #include <sys/types.h>
36 #include <sys/time.h>
37 #include <sys/socket.h>
38 #include <sys/uio.h>
39 #include <sys/select.h>
40 #include <netinet/in.h>
41 #include <arpa/inet.h>
42 #include <time.h>                   // platform support for UTC time
43 
44 #if USES_NETLINK
45 #include <asm/types.h>
46 #include <linux/netlink.h>
47 #include <linux/rtnetlink.h>
48 #else // USES_NETLINK
49 #include <net/route.h>
50 #include <net/if.h>
51 #endif // USES_NETLINK
52 
53 #include "mDNSUNP.h"
54 #include "GenLinkedList.h"
55 #include "dnsproxy.h"
56 
57 // ***************************************************************************
58 // Structures
59 
60 // We keep a list of client-supplied event sources in PosixEventSource records
61 struct PosixEventSource
62 {
63     mDNSPosixEventCallback Callback;
64     void                        *Context;
65     int fd;
66     struct  PosixEventSource    *Next;
67 };
68 typedef struct PosixEventSource PosixEventSource;
69 
70 // Context record for interface change callback
71 struct IfChangeRec
72 {
73     int NotifySD;
74     mDNS *mDNS;
75 };
76 typedef struct IfChangeRec IfChangeRec;
77 
78 // Note that static data is initialized to zero in (modern) C.
79 static fd_set gEventFDs;
80 static int gMaxFD;                              // largest fd in gEventFDs
81 static GenLinkedList gEventSources;             // linked list of PosixEventSource's
82 static sigset_t gEventSignalSet;                // Signals which event loop listens for
83 static sigset_t gEventSignals;                  // Signals which were received while inside loop
84 
85 static PosixNetworkInterface *gRecentInterfaces;
86 
87 // ***************************************************************************
88 // Globals (for debugging)
89 
90 static int num_registered_interfaces = 0;
91 static int num_pkts_accepted = 0;
92 static int num_pkts_rejected = 0;
93 
94 // ***************************************************************************
95 // Functions
96 
97 int gMDNSPlatformPosixVerboseLevel = 0;
98 
99 #define PosixErrorToStatus(errNum) ((errNum) == 0 ? mStatus_NoError : mStatus_UnknownErr)
100 
101 mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
102 {
103     switch (sa->sa_family)
104     {
105     case AF_INET:
106     {
107         struct sockaddr_in *sin          = (struct sockaddr_in*)sa;
108         ipAddr->type                     = mDNSAddrType_IPv4;
109         ipAddr->ip.v4.NotAnInteger       = sin->sin_addr.s_addr;
110         if (ipPort) ipPort->NotAnInteger = sin->sin_port;
111         break;
112     }
113 
114 #if HAVE_IPV6
115     case AF_INET6:
116     {
117         struct sockaddr_in6 *sin6        = (struct sockaddr_in6*)sa;
118 #ifndef NOT_HAVE_SA_LEN
119         assert(sin6->sin6_len == sizeof(*sin6));
120 #endif
121         ipAddr->type                     = mDNSAddrType_IPv6;
122         ipAddr->ip.v6                    = *(mDNSv6Addr*)&sin6->sin6_addr;
123         if (ipPort) ipPort->NotAnInteger = sin6->sin6_port;
124         break;
125     }
126 #endif
127 
128     default:
129         verbosedebugf("SockAddrTomDNSAddr: Uknown address family %d\n", sa->sa_family);
130         ipAddr->type = mDNSAddrType_None;
131         if (ipPort) ipPort->NotAnInteger = 0;
132         break;
133     }
134 }
135 
136 #if COMPILER_LIKES_PRAGMA_MARK
137 #pragma mark ***** Send and Receive
138 #endif
139 
140 // mDNS core calls this routine when it needs to send a packet.
141 mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
142                                        mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
143                                        mDNSIPPort dstPort, mDNSBool useBackgroundTrafficClass)
144 {
145     int err = 0;
146     struct sockaddr_storage to;
147     PosixNetworkInterface * thisIntf = (PosixNetworkInterface *)(InterfaceID);
148     int sendingsocket = -1;
149 
150     (void)src;  // Will need to use this parameter once we implement mDNSPlatformUDPSocket/mDNSPlatformUDPClose
151     (void) useBackgroundTrafficClass;
152 
153     assert(m != NULL);
154     assert(msg != NULL);
155     assert(end != NULL);
156     assert((((char *) end) - ((char *) msg)) > 0);
157 
158     if (dstPort.NotAnInteger == 0)
159     {
160         LogMsg("mDNSPlatformSendUDP: Invalid argument -dstPort is set to 0");
161         return PosixErrorToStatus(EINVAL);
162     }
163     if (dst->type == mDNSAddrType_IPv4)
164     {
165         struct sockaddr_in *sin = (struct sockaddr_in*)&to;
166 #ifndef NOT_HAVE_SA_LEN
167         sin->sin_len            = sizeof(*sin);
168 #endif
169         sin->sin_family         = AF_INET;
170         sin->sin_port           = dstPort.NotAnInteger;
171         sin->sin_addr.s_addr    = dst->ip.v4.NotAnInteger;
172         sendingsocket           = thisIntf ? thisIntf->multicastSocket4 : m->p->unicastSocket4;
173     }
174 
175 #if HAVE_IPV6
176     else if (dst->type == mDNSAddrType_IPv6)
177     {
178         struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&to;
179         mDNSPlatformMemZero(sin6, sizeof(*sin6));
180 #ifndef NOT_HAVE_SA_LEN
181         sin6->sin6_len            = sizeof(*sin6);
182 #endif
183         sin6->sin6_family         = AF_INET6;
184         sin6->sin6_port           = dstPort.NotAnInteger;
185         sin6->sin6_addr           = *(struct in6_addr*)&dst->ip.v6;
186         sendingsocket             = thisIntf ? thisIntf->multicastSocket6 : m->p->unicastSocket6;
187     }
188 #endif
189 
190     if (sendingsocket >= 0)
191         err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
192 
193     if      (err > 0) err = 0;
194     else if (err < 0)
195     {
196         static int MessageCount = 0;
197         // Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
198         if (!mDNSAddressIsAllDNSLinkGroup(dst))
199             if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
200 
201 	/* dont report ENETUNREACH */
202 	if (errno == ENETUNREACH) return(mStatus_TransientErr);
203 
204         if (MessageCount < 1000)
205         {
206             MessageCount++;
207             if (thisIntf)
208                 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
209                        errno, strerror(errno), dst, &thisIntf->coreIntf.ip, thisIntf->intfName, thisIntf->index);
210             else
211                 LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a", errno, strerror(errno), dst);
212         }
213     }
214 
215     return PosixErrorToStatus(err);
216 }
217 
218 // This routine is called when the main loop detects that data is available on a socket.
219 mDNSlocal void SocketDataReady(mDNS *const m, PosixNetworkInterface *intf, int skt)
220 {
221     mDNSAddr senderAddr, destAddr;
222     mDNSIPPort senderPort;
223     ssize_t packetLen;
224     DNSMessage packet;
225     struct my_in_pktinfo packetInfo;
226     struct sockaddr_storage from;
227     socklen_t fromLen;
228     int flags;
229     mDNSu8 ttl;
230     mDNSBool reject;
231     const mDNSInterfaceID InterfaceID = intf ? intf->coreIntf.InterfaceID : NULL;
232 
233     assert(m    != NULL);
234     assert(skt  >= 0);
235 
236     fromLen = sizeof(from);
237     flags   = 0;
238     packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
239 
240     if (packetLen >= 0)
241     {
242         SockAddrTomDNSAddr((struct sockaddr*)&from, &senderAddr, &senderPort);
243         SockAddrTomDNSAddr((struct sockaddr*)&packetInfo.ipi_addr, &destAddr, NULL);
244 
245         // If we have broken IP_RECVDSTADDR functionality (so far
246         // I've only seen this on OpenBSD) then apply a hack to
247         // convince mDNS Core that this isn't a spoof packet.
248         // Basically what we do is check to see whether the
249         // packet arrived as a multicast and, if so, set its
250         // destAddr to the mDNS address.
251         //
252         // I must admit that I could just be doing something
253         // wrong on OpenBSD and hence triggering this problem
254         // but I'm at a loss as to how.
255         //
256         // If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
257         // no way to tell the destination address or interface this packet arrived on,
258         // so all we can do is just assume it's a multicast
259 
260         #if HAVE_BROKEN_RECVDSTADDR || (!defined(IP_PKTINFO) && !defined(IP_RECVDSTADDR))
261         if ((destAddr.NotAnInteger == 0) && (flags & MSG_MCAST))
262         {
263             destAddr.type = senderAddr.type;
264             if      (senderAddr.type == mDNSAddrType_IPv4) destAddr.ip.v4 = AllDNSLinkGroup_v4.ip.v4;
265             else if (senderAddr.type == mDNSAddrType_IPv6) destAddr.ip.v6 = AllDNSLinkGroup_v6.ip.v6;
266         }
267         #endif
268 
269         // We only accept the packet if the interface on which it came
270         // in matches the interface associated with this socket.
271         // We do this match by name or by index, depending on which
272         // information is available.  recvfrom_flags sets the name
273         // to "" if the name isn't available, or the index to -1
274         // if the index is available.  This accomodates the various
275         // different capabilities of our target platforms.
276 
277         reject = mDNSfalse;
278         if (!intf)
279         {
280             // Ignore multicasts accidentally delivered to our unicast receiving socket
281             if (mDNSAddrIsDNSMulticast(&destAddr)) packetLen = -1;
282         }
283         else
284         {
285             if      (packetInfo.ipi_ifname[0] != 0) reject = (strcmp(packetInfo.ipi_ifname, intf->intfName) != 0);
286             else if (packetInfo.ipi_ifindex != -1) reject = (packetInfo.ipi_ifindex != intf->index);
287 
288             if (reject)
289             {
290                 verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
291                               &senderAddr, &destAddr, packetInfo.ipi_ifname, packetInfo.ipi_ifindex,
292                               &intf->coreIntf.ip, intf->intfName, intf->index, skt);
293                 packetLen = -1;
294                 num_pkts_rejected++;
295                 if (num_pkts_rejected > (num_pkts_accepted + 1) * (num_registered_interfaces + 1) * 2)
296                 {
297                     fprintf(stderr,
298                             "*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
299                             num_pkts_accepted + num_pkts_rejected, num_pkts_accepted, num_pkts_rejected);
300                     num_pkts_accepted = 0;
301                     num_pkts_rejected = 0;
302                 }
303             }
304             else
305             {
306                 verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
307                               &senderAddr, &destAddr, &intf->coreIntf.ip, intf->intfName, intf->index, skt);
308                 num_pkts_accepted++;
309             }
310         }
311     }
312 
313     if (packetLen >= 0)
314         mDNSCoreReceive(m, &packet, (mDNSu8 *)&packet + packetLen,
315                         &senderAddr, senderPort, &destAddr, MulticastDNSPort, InterfaceID);
316 }
317 
318 mDNSexport TCPSocket *mDNSPlatformTCPSocket(TCPSocketFlags flags, mDNSIPPort * port, mDNSBool useBackgroundTrafficClass)
319 {
320     (void)flags;        // Unused
321     (void)port;         // Unused
322     (void)useBackgroundTrafficClass; // Unused
323     return NULL;
324 }
325 
326 mDNSexport TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd)
327 {
328     (void)flags;        // Unused
329     (void)sd;           // Unused
330     return NULL;
331 }
332 
333 mDNSexport int mDNSPlatformTCPGetFD(TCPSocket *sock)
334 {
335     (void)sock;         // Unused
336     return -1;
337 }
338 
339 mDNSexport mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname, mDNSInterfaceID InterfaceID,
340                                           TCPConnectionCallback callback, void *context)
341 {
342     (void)sock;         // Unused
343     (void)dst;          // Unused
344     (void)dstport;      // Unused
345     (void)hostname;     // Unused
346     (void)InterfaceID;  // Unused
347     (void)callback;     // Unused
348     (void)context;      // Unused
349     return(mStatus_UnsupportedErr);
350 }
351 
352 mDNSexport void mDNSPlatformTCPCloseConnection(TCPSocket *sock)
353 {
354     (void)sock;         // Unused
355 }
356 
357 mDNSexport long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool * closed)
358 {
359     (void)sock;         // Unused
360     (void)buf;          // Unused
361     (void)buflen;       // Unused
362     (void)closed;       // Unused
363     return 0;
364 }
365 
366 mDNSexport long mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len)
367 {
368     (void)sock;         // Unused
369     (void)msg;          // Unused
370     (void)len;          // Unused
371     return 0;
372 }
373 
374 mDNSexport UDPSocket *mDNSPlatformUDPSocket(mDNSIPPort port)
375 {
376     (void)port;         // Unused
377     return NULL;
378 }
379 
380 mDNSexport void           mDNSPlatformUDPClose(UDPSocket *sock)
381 {
382     (void)sock;         // Unused
383 }
384 
385 mDNSexport void mDNSPlatformUpdateProxyList(const mDNSInterfaceID InterfaceID)
386 {
387     (void)InterfaceID;          // Unused
388 }
389 
390 mDNSexport void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID)
391 {
392     (void)msg;          // Unused
393     (void)end;          // Unused
394     (void)InterfaceID;          // Unused
395 }
396 
397 mDNSexport void mDNSPlatformSetLocalAddressCacheEntry(const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID)
398 {
399     (void)tpa;          // Unused
400     (void)tha;          // Unused
401     (void)InterfaceID;          // Unused
402 }
403 
404 mDNSexport mStatus mDNSPlatformTLSSetupCerts(void)
405 {
406     return(mStatus_UnsupportedErr);
407 }
408 
409 mDNSexport void mDNSPlatformTLSTearDownCerts(void)
410 {
411 }
412 
413 mDNSexport void mDNSPlatformSetAllowSleep(mDNSBool allowSleep, const char *reason)
414 {
415     (void) allowSleep;
416     (void) reason;
417 }
418 
419 #if COMPILER_LIKES_PRAGMA_MARK
420 #pragma mark -
421 #pragma mark - /etc/hosts support
422 #endif
423 
424 mDNSexport void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result)
425 {
426     (void)m;  // unused
427     (void)rr;
428     (void)result;
429 }
430 
431 
432 #if COMPILER_LIKES_PRAGMA_MARK
433 #pragma mark ***** DDNS Config Platform Functions
434 #endif
435 
436 /*
437  * Stub to set or get DNS config. Even if it actually does not do anything,
438  * it has to make sure the data is zeroed properly.
439  */
440 mDNSexport mDNSBool mDNSPlatformSetDNSConfig(mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
441     DNameListElem **BrowseDomains, mDNSBool ackConfig)
442 {
443     (void) setservers;
444     if (fqdn) fqdn->c[0] = 0;
445     (void) setsearch;
446     if (RegDomains) *RegDomains = NULL;
447     if (BrowseDomains) *BrowseDomains = NULL;
448     (void) ackConfig;
449 
450     return mDNStrue;
451 }
452 
453 mDNSexport mStatus mDNSPlatformGetPrimaryInterface(mDNSAddr * v4, mDNSAddr * v6, mDNSAddr * router)
454 {
455     (void) v4;
456     (void) v6;
457     (void) router;
458 
459     return mStatus_UnsupportedErr;
460 }
461 
462 mDNSexport void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status)
463 {
464     (void) dname;
465     (void) status;
466 }
467 
468 #if COMPILER_LIKES_PRAGMA_MARK
469 #pragma mark ***** Init and Term
470 #endif
471 
472 // This gets the current hostname, truncating it at the first dot if necessary
473 mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
474 {
475     int len = 0;
476     gethostname((char *)(&namelabel->c[1]), MAX_DOMAIN_LABEL);
477     while (len < MAX_DOMAIN_LABEL && namelabel->c[len+1] && namelabel->c[len+1] != '.') len++;
478     namelabel->c[0] = len;
479 }
480 
481 // On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
482 // Other platforms can either get the information from the appropriate place,
483 // or they can alternatively just require all registering services to provide an explicit name
484 mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
485 {
486     // On Unix we have no better name than the host name, so we just use that.
487     GetUserSpecifiedRFC1034ComputerName(namelabel);
488 }
489 
490 mDNSexport int ParseDNSServers(mDNS *m, const char *filePath)
491 {
492     char line[256];
493     char nameserver[16];
494     char keyword[11];
495     int numOfServers = 0;
496     FILE *fp = fopen(filePath, "r");
497     if (fp == NULL) return -1;
498     while (fgets(line,sizeof(line),fp))
499     {
500         struct in_addr ina;
501         line[255]='\0';     // just to be safe
502         if (sscanf(line,"%10s %15s", keyword, nameserver) != 2) continue;   // it will skip whitespaces
503         if (strncasecmp(keyword,"nameserver",10)) continue;
504         if (inet_aton(nameserver, (struct in_addr *)&ina) != 0)
505         {
506             mDNSAddr DNSAddr;
507             DNSAddr.type = mDNSAddrType_IPv4;
508             DNSAddr.ip.v4.NotAnInteger = ina.s_addr;
509             mDNS_AddDNSServer(m, NULL, mDNSInterface_Any, 0, &DNSAddr, UnicastDNSPort, kScopeNone, 0, mDNSfalse, mDNSfalse, 0, mDNStrue, mDNStrue, mDNSfalse);
510             numOfServers++;
511         }
512     }
513 	fclose(fp);
514     return (numOfServers > 0) ? 0 : -1;
515 }
516 
517 // Searches the interface list looking for the named interface.
518 // Returns a pointer to if it found, or NULL otherwise.
519 mDNSlocal PosixNetworkInterface *SearchForInterfaceByName(mDNS *const m, const char *intfName)
520 {
521     PosixNetworkInterface *intf;
522 
523     assert(m != NULL);
524     assert(intfName != NULL);
525 
526     intf = (PosixNetworkInterface*)(m->HostInterfaces);
527     while ((intf != NULL) && (strcmp(intf->intfName, intfName) != 0))
528         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
529 
530     return intf;
531 }
532 
533 mDNSexport mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 index)
534 {
535     PosixNetworkInterface *intf;
536 
537     assert(m != NULL);
538 
539     if (index == kDNSServiceInterfaceIndexLocalOnly) return(mDNSInterface_LocalOnly);
540     if (index == kDNSServiceInterfaceIndexP2P      ) return(mDNSInterface_P2P);
541     if (index == kDNSServiceInterfaceIndexAny      ) return(mDNSInterface_Any);
542 
543     intf = (PosixNetworkInterface*)(m->HostInterfaces);
544     while ((intf != NULL) && (mDNSu32) intf->index != index)
545         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
546 
547     return (mDNSInterfaceID) intf;
548 }
549 
550 mDNSexport mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange)
551 {
552     PosixNetworkInterface *intf;
553     (void) suppressNetworkChange; // Unused
554 
555     assert(m != NULL);
556 
557     if (id == mDNSInterface_LocalOnly) return(kDNSServiceInterfaceIndexLocalOnly);
558     if (id == mDNSInterface_P2P      ) return(kDNSServiceInterfaceIndexP2P);
559     if (id == mDNSInterface_Any      ) return(kDNSServiceInterfaceIndexAny);
560 
561     intf = (PosixNetworkInterface*)(m->HostInterfaces);
562     while ((intf != NULL) && (mDNSInterfaceID) intf != id)
563         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
564 
565     if (intf) return intf->index;
566 
567     // If we didn't find the interface, check the RecentInterfaces list as well
568     intf = gRecentInterfaces;
569     while ((intf != NULL) && (mDNSInterfaceID) intf != id)
570         intf = (PosixNetworkInterface *)(intf->coreIntf.next);
571 
572     return intf ? intf->index : 0;
573 }
574 
575 // Frees the specified PosixNetworkInterface structure. The underlying
576 // interface must have already been deregistered with the mDNS core.
577 mDNSlocal void FreePosixNetworkInterface(PosixNetworkInterface *intf)
578 {
579     int rv;
580     assert(intf != NULL);
581     if (intf->intfName != NULL) free((void *)intf->intfName);
582     if (intf->multicastSocket4 != -1)
583     {
584         rv = close(intf->multicastSocket4);
585         assert(rv == 0);
586     }
587 #if HAVE_IPV6
588     if (intf->multicastSocket6 != -1)
589     {
590         rv = close(intf->multicastSocket6);
591         assert(rv == 0);
592     }
593 #endif
594 
595     // Move interface to the RecentInterfaces list for a minute
596     intf->LastSeen = mDNSPlatformUTC();
597     intf->coreIntf.next = &gRecentInterfaces->coreIntf;
598     gRecentInterfaces = intf;
599 }
600 
601 // Grab the first interface, deregister it, free it, and repeat until done.
602 mDNSlocal void ClearInterfaceList(mDNS *const m)
603 {
604     assert(m != NULL);
605 
606     while (m->HostInterfaces)
607     {
608         PosixNetworkInterface *intf = (PosixNetworkInterface*)(m->HostInterfaces);
609         mDNS_DeregisterInterface(m, &intf->coreIntf, NormalActivation);
610         if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
611         FreePosixNetworkInterface(intf);
612     }
613     num_registered_interfaces = 0;
614     num_pkts_accepted = 0;
615     num_pkts_rejected = 0;
616 }
617 
618 // Sets up a send/receive socket.
619 // If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
620 // If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
621 mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
622 {
623     int err = 0;
624     static const int kOn = 1;
625     static const int kIntTwoFiveFive = 255;
626     static const unsigned char kByteTwoFiveFive = 255;
627     const mDNSBool JoinMulticastGroup = (port.NotAnInteger != 0);
628 
629     (void) interfaceIndex;  // This parameter unused on plaforms that don't have IPv6
630     assert(intfAddr != NULL);
631     assert(sktPtr != NULL);
632     assert(*sktPtr == -1);
633 
634     // Open the socket...
635     if      (intfAddr->sa_family == AF_INET) *sktPtr = socket(PF_INET,  SOCK_DGRAM, IPPROTO_UDP);
636 #if HAVE_IPV6
637     else if (intfAddr->sa_family == AF_INET6) *sktPtr = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
638 #endif
639     else return EINVAL;
640 
641     if (*sktPtr < 0) { err = errno; perror((intfAddr->sa_family == AF_INET) ? "socket AF_INET" : "socket AF_INET6"); }
642 
643     // ... with a shared UDP port, if it's for multicast receiving
644     if (err == 0 && port.NotAnInteger)
645     {
646         // <rdar://problem/20946253>
647         // We test for SO_REUSEADDR first, as suggested by Jonny Törnbom from Axis Communications
648         // Linux kernel versions 3.9 introduces support for socket option
649         // SO_REUSEPORT, however this is not implemented the same as on *BSD
650         // systems. Linux version implements a "port hijacking" prevention
651         // mechanism, limiting processes wanting to bind to an already existing
652         // addr:port to have the same effective UID as the first who bound it. What
653         // this meant for us was that the daemon ran as one user and when for
654         // instance mDNSClientPosix was executed by another user, it wasn't allowed
655         // to bind to the socket. Our suggestion was to switch the order in which
656         // SO_REUSEPORT and SO_REUSEADDR was tested so that SO_REUSEADDR stays on
657         // top and SO_REUSEPORT to be used only if SO_REUSEADDR doesn't exist.
658         #if defined(SO_REUSEADDR) && !defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
659         err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEADDR, &kOn, sizeof(kOn));
660         #elif defined(SO_REUSEPORT)
661         err = setsockopt(*sktPtr, SOL_SOCKET, SO_REUSEPORT, &kOn, sizeof(kOn));
662         #else
663             #error This platform has no way to avoid address busy errors on multicast.
664         #endif
665         if (err < 0) { err = errno; perror("setsockopt - SO_REUSExxxx"); }
666 
667         // Enable inbound packets on IFEF_AWDL interface.
668         // Only done for multicast sockets, since we don't expect unicast socket operations
669         // on the IFEF_AWDL interface. Operation is a no-op for other interface types.
670         #ifdef SO_RECV_ANYIF
671         if (setsockopt(*sktPtr, SOL_SOCKET, SO_RECV_ANYIF, &kOn, sizeof(kOn)) < 0) perror("setsockopt - SO_RECV_ANYIF");
672         #endif
673     }
674 
675     // We want to receive destination addresses and interface identifiers.
676     if (intfAddr->sa_family == AF_INET)
677     {
678         struct ip_mreq imr;
679         struct sockaddr_in bindAddr;
680         if (err == 0)
681         {
682             #if defined(IP_PKTINFO)                                 // Linux
683             err = setsockopt(*sktPtr, IPPROTO_IP, IP_PKTINFO, &kOn, sizeof(kOn));
684             if (err < 0) { err = errno; perror("setsockopt - IP_PKTINFO"); }
685             #elif defined(IP_RECVDSTADDR) || defined(IP_RECVIF)     // BSD and Solaris
686                 #if defined(IP_RECVDSTADDR)
687             err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVDSTADDR, &kOn, sizeof(kOn));
688             if (err < 0) { err = errno; perror("setsockopt - IP_RECVDSTADDR"); }
689                 #endif
690                 #if defined(IP_RECVIF)
691             if (err == 0)
692             {
693                 err = setsockopt(*sktPtr, IPPROTO_IP, IP_RECVIF, &kOn, sizeof(kOn));
694                 if (err < 0) { err = errno; perror("setsockopt - IP_RECVIF"); }
695             }
696                 #endif
697             #else
698                 #warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
699             #endif
700         }
701     #if defined(IP_RECVTTL)                                 // Linux
702         if (err == 0)
703         {
704             setsockopt(*sktPtr, IPPROTO_IP, IP_RECVTTL, &kOn, sizeof(kOn));
705             // We no longer depend on being able to get the received TTL, so don't worry if the option fails
706         }
707     #endif
708 
709         // Add multicast group membership on this interface
710         if (err == 0 && JoinMulticastGroup)
711         {
712             imr.imr_multiaddr.s_addr = AllDNSLinkGroup_v4.ip.v4.NotAnInteger;
713             imr.imr_interface        = ((struct sockaddr_in*)intfAddr)->sin_addr;
714             err = setsockopt(*sktPtr, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(imr));
715             if (err < 0) { err = errno; perror("setsockopt - IP_ADD_MEMBERSHIP"); }
716         }
717 
718         // Specify outgoing interface too
719         if (err == 0 && JoinMulticastGroup)
720         {
721             err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
722             if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_IF"); }
723         }
724 
725         // Per the mDNS spec, send unicast packets with TTL 255
726         if (err == 0)
727         {
728             err = setsockopt(*sktPtr, IPPROTO_IP, IP_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
729             if (err < 0) { err = errno; perror("setsockopt - IP_TTL"); }
730         }
731 
732         // and multicast packets with TTL 255 too
733         // There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
734         if (err == 0)
735         {
736             err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
737             if (err < 0 && errno == EINVAL)
738                 err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
739             if (err < 0) { err = errno; perror("setsockopt - IP_MULTICAST_TTL"); }
740         }
741 
742         // And start listening for packets
743         if (err == 0)
744         {
745             bindAddr.sin_family      = AF_INET;
746             bindAddr.sin_port        = port.NotAnInteger;
747             bindAddr.sin_addr.s_addr = INADDR_ANY; // Want to receive multicasts AND unicasts on this socket
748             err = bind(*sktPtr, (struct sockaddr *) &bindAddr, sizeof(bindAddr));
749             if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
750         }
751     }     // endif (intfAddr->sa_family == AF_INET)
752 
753 #if HAVE_IPV6
754     else if (intfAddr->sa_family == AF_INET6)
755     {
756         struct ipv6_mreq imr6;
757         struct sockaddr_in6 bindAddr6;
758     #if defined(IPV6_RECVPKTINFO) // Solaris
759 	if (err == 0)
760 	{
761 	    err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVPKTINFO, &kOn, sizeof(kOn));
762 	    if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVPKTINFO"); }
763 	}
764     #elif defined(IPV6_PKTINFO)
765         if (err == 0)
766         {
767             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_PKTINFO, &kOn, sizeof(kOn));
768             if (err < 0) { err = errno; perror("setsockopt - IPV6_PKTINFO"); }
769         }
770     #else
771         #warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
772     #endif
773     #if defined(IPV6_RECVHOPLIMIT)
774        if (err == 0)
775        {
776            err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &kOn, sizeof(kOn));
777            if (err < 0) { err = errno; perror("setsockopt - IPV6_RECVHOPLIMIT"); }
778        }
779     #elif defined(IPV6_HOPLIMIT)
780         if (err == 0)
781         {
782             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_2292_HOPLIMIT, &kOn, sizeof(kOn));
783             if (err < 0) { err = errno; perror("setsockopt - IPV6_HOPLIMIT"); }
784         }
785     #endif
786 
787         // Add multicast group membership on this interface
788         if (err == 0 && JoinMulticastGroup)
789         {
790             imr6.ipv6mr_multiaddr       = *(const struct in6_addr*)&AllDNSLinkGroup_v6.ip.v6;
791             imr6.ipv6mr_interface       = interfaceIndex;
792             //LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
793             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_JOIN_GROUP, &imr6, sizeof(imr6));
794             if (err < 0)
795             {
796                 err = errno;
797                 verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
798                 perror("setsockopt - IPV6_JOIN_GROUP");
799             }
800         }
801 
802         // Specify outgoing interface too
803         if (err == 0 && JoinMulticastGroup)
804         {
805             u_int multicast_if = interfaceIndex;
806             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_IF, &multicast_if, sizeof(multicast_if));
807             if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_IF"); }
808         }
809 
810         // We want to receive only IPv6 packets on this socket.
811         // Without this option, we may get IPv4 addresses as mapped addresses.
812         if (err == 0)
813         {
814             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_V6ONLY, &kOn, sizeof(kOn));
815             if (err < 0) { err = errno; perror("setsockopt - IPV6_V6ONLY"); }
816         }
817 
818         // Per the mDNS spec, send unicast packets with TTL 255
819         if (err == 0)
820         {
821             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
822             if (err < 0) { err = errno; perror("setsockopt - IPV6_UNICAST_HOPS"); }
823         }
824 
825         // and multicast packets with TTL 255 too
826         // There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
827         if (err == 0)
828         {
829             err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
830             if (err < 0 && errno == EINVAL)
831                 err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
832             if (err < 0) { err = errno; perror("setsockopt - IPV6_MULTICAST_HOPS"); }
833         }
834 
835         // And start listening for packets
836         if (err == 0)
837         {
838             mDNSPlatformMemZero(&bindAddr6, sizeof(bindAddr6));
839 #ifndef NOT_HAVE_SA_LEN
840             bindAddr6.sin6_len         = sizeof(bindAddr6);
841 #endif
842             bindAddr6.sin6_family      = AF_INET6;
843             bindAddr6.sin6_port        = port.NotAnInteger;
844             bindAddr6.sin6_flowinfo    = 0;
845             bindAddr6.sin6_addr        = in6addr_any; // Want to receive multicasts AND unicasts on this socket
846             bindAddr6.sin6_scope_id    = 0;
847             err = bind(*sktPtr, (struct sockaddr *) &bindAddr6, sizeof(bindAddr6));
848             if (err < 0) { err = errno; perror("bind"); fflush(stderr); }
849         }
850     }     // endif (intfAddr->sa_family == AF_INET6)
851 #endif
852 
853     // Set the socket to non-blocking.
854     if (err == 0)
855     {
856         err = fcntl(*sktPtr, F_GETFL, 0);
857         if (err < 0) err = errno;
858         else
859         {
860             err = fcntl(*sktPtr, F_SETFL, err | O_NONBLOCK);
861             if (err < 0) err = errno;
862         }
863     }
864 
865     // Clean up
866     if (err != 0 && *sktPtr != -1)
867     {
868         int rv;
869         rv = close(*sktPtr);
870         assert(rv == 0);
871         *sktPtr = -1;
872     }
873     assert((err == 0) == (*sktPtr != -1));
874     return err;
875 }
876 
877 // Creates a PosixNetworkInterface for the interface whose IP address is
878 // intfAddr and whose name is intfName and registers it with mDNS core.
879 mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
880 {
881     int err = 0;
882     PosixNetworkInterface *intf;
883     PosixNetworkInterface *alias = NULL;
884 
885     assert(m != NULL);
886     assert(intfAddr != NULL);
887     assert(intfName != NULL);
888     assert(intfMask != NULL);
889 
890     // Allocate the interface structure itself.
891     intf = (PosixNetworkInterface*)calloc(1, sizeof(*intf));
892     if (intf == NULL) { assert(0); err = ENOMEM; }
893 
894     // And make a copy of the intfName.
895     if (err == 0)
896     {
897         intf->intfName = strdup(intfName);
898         if (intf->intfName == NULL) { assert(0); err = ENOMEM; }
899     }
900 
901     if (err == 0)
902     {
903         // Set up the fields required by the mDNS core.
904         SockAddrTomDNSAddr(intfAddr, &intf->coreIntf.ip, NULL);
905         SockAddrTomDNSAddr(intfMask, &intf->coreIntf.mask, NULL);
906 
907         //LogMsg("SetupOneInterface: %#a %#a",  &intf->coreIntf.ip,  &intf->coreIntf.mask);
908         strncpy(intf->coreIntf.ifname, intfName, sizeof(intf->coreIntf.ifname));
909         intf->coreIntf.ifname[sizeof(intf->coreIntf.ifname)-1] = 0;
910         intf->coreIntf.Advertise = m->AdvertiseLocalAddresses;
911         intf->coreIntf.McastTxRx = mDNStrue;
912 
913         // Set up the extra fields in PosixNetworkInterface.
914         assert(intf->intfName != NULL);         // intf->intfName already set up above
915         intf->index                = intfIndex;
916         intf->multicastSocket4     = -1;
917 #if HAVE_IPV6
918         intf->multicastSocket6     = -1;
919 #endif
920         alias                      = SearchForInterfaceByName(m, intf->intfName);
921         if (alias == NULL) alias   = intf;
922         intf->coreIntf.InterfaceID = (mDNSInterfaceID)alias;
923 
924         if (alias != intf)
925             debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
926     }
927 
928     // Set up the multicast socket
929     if (err == 0)
930     {
931         if (alias->multicastSocket4 == -1 && intfAddr->sa_family == AF_INET)
932             err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket4);
933 #if HAVE_IPV6
934         else if (alias->multicastSocket6 == -1 && intfAddr->sa_family == AF_INET6)
935             err = SetupSocket(intfAddr, MulticastDNSPort, intf->index, &alias->multicastSocket6);
936 #endif
937     }
938 
939     // If interface is a direct link, address record will be marked as kDNSRecordTypeKnownUnique
940     // and skip the probe phase of the probe/announce packet sequence.
941     intf->coreIntf.DirectLink = mDNSfalse;
942 #ifdef DIRECTLINK_INTERFACE_NAME
943     if (strcmp(intfName, STRINGIFY(DIRECTLINK_INTERFACE_NAME)) == 0)
944         intf->coreIntf.DirectLink = mDNStrue;
945 #endif
946     intf->coreIntf.SupportsUnicastMDNSResponse = mDNStrue;
947 
948     // The interface is all ready to go, let's register it with the mDNS core.
949     if (err == 0)
950         err = mDNS_RegisterInterface(m, &intf->coreIntf, NormalActivation);
951 
952     // Clean up.
953     if (err == 0)
954     {
955         num_registered_interfaces++;
956         debugf("SetupOneInterface: %s %#a Registered", intf->intfName, &intf->coreIntf.ip);
957         if (gMDNSPlatformPosixVerboseLevel > 0)
958             fprintf(stderr, "Registered interface %s\n", intf->intfName);
959     }
960     else
961     {
962         // Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
963         debugf("SetupOneInterface: %s %#a failed to register %d", intfName, &intf->coreIntf.ip, err);
964         if (intf) { FreePosixNetworkInterface(intf); intf = NULL; }
965     }
966 
967     assert((err == 0) == (intf != NULL));
968 
969     return err;
970 }
971 
972 // Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
973 mDNSlocal int SetupInterfaceList(mDNS *const m)
974 {
975     mDNSBool foundav4       = mDNSfalse;
976     int err            = 0;
977     struct ifi_info *intfList      = get_ifi_info(AF_INET, mDNStrue);
978     struct ifi_info *firstLoopback = NULL;
979 
980     assert(m != NULL);
981     debugf("SetupInterfaceList");
982 
983     if (intfList == NULL) err = ENOENT;
984 
985 #if HAVE_IPV6
986     if (err == 0)       /* Link the IPv6 list to the end of the IPv4 list */
987     {
988         struct ifi_info **p = &intfList;
989         while (*p) p = &(*p)->ifi_next;
990         *p = get_ifi_info(AF_INET6, mDNStrue);
991     }
992 #endif
993 
994     if (err == 0)
995     {
996         struct ifi_info *i = intfList;
997         while (i)
998         {
999             if (     ((i->ifi_addr->sa_family == AF_INET)
1000 #if HAVE_IPV6
1001                       || (i->ifi_addr->sa_family == AF_INET6)
1002 #endif
1003                       ) &&  (i->ifi_flags & IFF_UP) && !(i->ifi_flags & IFF_POINTOPOINT))
1004             {
1005                 if (i->ifi_flags & IFF_LOOPBACK)
1006                 {
1007                     if (firstLoopback == NULL)
1008                         firstLoopback = i;
1009                 }
1010                 else
1011                 {
1012                     if (SetupOneInterface(m, i->ifi_addr, i->ifi_netmask, i->ifi_name, i->ifi_index) == 0)
1013                         if (i->ifi_addr->sa_family == AF_INET)
1014                             foundav4 = mDNStrue;
1015                 }
1016             }
1017             i = i->ifi_next;
1018         }
1019 
1020         // If we found no normal interfaces but we did find a loopback interface, register the
1021         // loopback interface.  This allows self-discovery if no interfaces are configured.
1022         // Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
1023         // In the interim, we skip loopback interface only if we found at least one v4 interface to use
1024         // if ((m->HostInterfaces == NULL) && (firstLoopback != NULL))
1025         if (!foundav4 && firstLoopback)
1026             (void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_netmask, firstLoopback->ifi_name, firstLoopback->ifi_index);
1027     }
1028 
1029     // Clean up.
1030     if (intfList != NULL) free_ifi_info(intfList);
1031 
1032     // Clean up any interfaces that have been hanging around on the RecentInterfaces list for more than a minute
1033     PosixNetworkInterface **ri = &gRecentInterfaces;
1034     const mDNSs32 utc = mDNSPlatformUTC();
1035     while (*ri)
1036     {
1037         PosixNetworkInterface *pi = *ri;
1038         if (utc - pi->LastSeen < 60) ri = (PosixNetworkInterface **)&pi->coreIntf.next;
1039         else { *ri = (PosixNetworkInterface *)pi->coreIntf.next; free(pi); }
1040     }
1041 
1042     return err;
1043 }
1044 
1045 #if USES_NETLINK
1046 
1047 // See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
1048 
1049 // Open a socket that will receive interface change notifications
1050 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1051 {
1052     mStatus err = mStatus_NoError;
1053     struct sockaddr_nl snl;
1054     int sock;
1055     int ret;
1056 
1057     sock = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1058     if (sock < 0)
1059         return errno;
1060 
1061     // Configure read to be non-blocking because inbound msg size is not known in advance
1062     (void) fcntl(sock, F_SETFL, O_NONBLOCK);
1063 
1064     /* Subscribe the socket to Link & IP addr notifications. */
1065     mDNSPlatformMemZero(&snl, sizeof snl);
1066     snl.nl_family = AF_NETLINK;
1067     snl.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;
1068     ret = bind(sock, (struct sockaddr *) &snl, sizeof snl);
1069     if (0 == ret)
1070         *pFD = sock;
1071     else
1072         err = errno;
1073 
1074     return err;
1075 }
1076 
1077 #if MDNS_DEBUGMSGS
1078 mDNSlocal void      PrintNetLinkMsg(const struct nlmsghdr *pNLMsg)
1079 {
1080     const char *kNLMsgTypes[] = { "", "NLMSG_NOOP", "NLMSG_ERROR", "NLMSG_DONE", "NLMSG_OVERRUN" };
1081     const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
1082 
1083     printf("nlmsghdr len=%d, type=%s, flags=0x%x\n", pNLMsg->nlmsg_len,
1084            pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[pNLMsg->nlmsg_type] : kNLRtMsgTypes[pNLMsg->nlmsg_type - RTM_BASE],
1085            pNLMsg->nlmsg_flags);
1086 
1087     if (RTM_NEWLINK <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETLINK)
1088     {
1089         struct ifinfomsg    *pIfInfo = (struct ifinfomsg*) NLMSG_DATA(pNLMsg);
1090         printf("ifinfomsg family=%d, type=%d, index=%d, flags=0x%x, change=0x%x\n", pIfInfo->ifi_family,
1091                pIfInfo->ifi_type, pIfInfo->ifi_index, pIfInfo->ifi_flags, pIfInfo->ifi_change);
1092 
1093     }
1094     else if (RTM_NEWADDR <= pNLMsg->nlmsg_type && pNLMsg->nlmsg_type <= RTM_GETADDR)
1095     {
1096         struct ifaddrmsg    *pIfAddr = (struct ifaddrmsg*) NLMSG_DATA(pNLMsg);
1097         printf("ifaddrmsg family=%d, index=%d, flags=0x%x\n", pIfAddr->ifa_family,
1098                pIfAddr->ifa_index, pIfAddr->ifa_flags);
1099     }
1100     printf("\n");
1101 }
1102 #endif
1103 
1104 mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
1105 // Read through the messages on sd and if any indicate that any interface records should
1106 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1107 {
1108     ssize_t readCount;
1109     char buff[4096];
1110     struct nlmsghdr         *pNLMsg = (struct nlmsghdr*) buff;
1111     mDNSu32 result = 0;
1112 
1113     // The structure here is more complex than it really ought to be because,
1114     // unfortunately, there's no good way to size a buffer in advance large
1115     // enough to hold all pending data and so avoid message fragmentation.
1116     // (Note that FIONREAD is not supported on AF_NETLINK.)
1117 
1118     readCount = read(sd, buff, sizeof buff);
1119     while (1)
1120     {
1121         // Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
1122         // If not, discard already-processed messages in buffer and read more data.
1123         if (((char*) &pNLMsg[1] > (buff + readCount)) ||    // i.e. *pNLMsg extends off end of buffer
1124             ((char*) pNLMsg + pNLMsg->nlmsg_len > (buff + readCount)))
1125         {
1126             if (buff < (char*) pNLMsg)      // we have space to shuffle
1127             {
1128                 // discard processed data
1129                 readCount -= ((char*) pNLMsg - buff);
1130                 memmove(buff, pNLMsg, readCount);
1131                 pNLMsg = (struct nlmsghdr*) buff;
1132 
1133                 // read more data
1134                 readCount += read(sd, buff + readCount, sizeof buff - readCount);
1135                 continue;                   // spin around and revalidate with new readCount
1136             }
1137             else
1138                 break;  // Otherwise message does not fit in buffer
1139         }
1140 
1141 #if MDNS_DEBUGMSGS
1142         PrintNetLinkMsg(pNLMsg);
1143 #endif
1144 
1145         // Process the NetLink message
1146         if (pNLMsg->nlmsg_type == RTM_GETLINK || pNLMsg->nlmsg_type == RTM_NEWLINK)
1147             result |= 1 << ((struct ifinfomsg*) NLMSG_DATA(pNLMsg))->ifi_index;
1148         else if (pNLMsg->nlmsg_type == RTM_DELADDR || pNLMsg->nlmsg_type == RTM_NEWADDR)
1149             result |= 1 << ((struct ifaddrmsg*) NLMSG_DATA(pNLMsg))->ifa_index;
1150 
1151         // Advance pNLMsg to the next message in the buffer
1152         if ((pNLMsg->nlmsg_flags & NLM_F_MULTI) != 0 && pNLMsg->nlmsg_type != NLMSG_DONE)
1153         {
1154             ssize_t len = readCount - ((char*)pNLMsg - buff);
1155             pNLMsg = NLMSG_NEXT(pNLMsg, len);
1156         }
1157         else
1158             break;  // all done!
1159     }
1160 
1161     return result;
1162 }
1163 
1164 #else // USES_NETLINK
1165 
1166 // Open a socket that will receive interface change notifications
1167 mDNSlocal mStatus OpenIfNotifySocket(int *pFD)
1168 {
1169     *pFD = socket(AF_ROUTE, SOCK_RAW, 0);
1170 
1171     if (*pFD < 0)
1172         return mStatus_UnknownErr;
1173 
1174     // Configure read to be non-blocking because inbound msg size is not known in advance
1175     (void) fcntl(*pFD, F_SETFL, O_NONBLOCK);
1176 
1177     return mStatus_NoError;
1178 }
1179 
1180 #if MDNS_DEBUGMSGS
1181 mDNSlocal void      PrintRoutingSocketMsg(const struct ifa_msghdr *pRSMsg)
1182 {
1183     const char *kRSMsgTypes[] = { "", "RTM_ADD", "RTM_DELETE", "RTM_CHANGE", "RTM_GET", "RTM_LOSING",
1184                                   "RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
1185                                   "RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
1186 
1187     int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
1188 
1189     printf("ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[pRSMsg->ifam_type], index);
1190 }
1191 #endif
1192 
1193 mDNSlocal mDNSu32       ProcessRoutingNotification(int sd)
1194 // Read through the messages on sd and if any indicate that any interface records should
1195 // be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
1196 {
1197     ssize_t readCount;
1198     char buff[4096];
1199     struct ifa_msghdr       *pRSMsg = (struct ifa_msghdr*) buff;
1200     mDNSu32 result = 0;
1201 
1202     readCount = read(sd, buff, sizeof buff);
1203     if (readCount < (ssize_t) sizeof(struct ifa_msghdr))
1204         return mStatus_UnsupportedErr;      // cannot decipher message
1205 
1206 #if MDNS_DEBUGMSGS
1207     PrintRoutingSocketMsg(pRSMsg);
1208 #endif
1209 
1210     // Process the message
1211     switch (pRSMsg->ifam_type)
1212     {
1213     case RTM_NEWADDR:
1214     case RTM_DELADDR:
1215     case RTM_IFINFO:
1216     /*
1217      * ADD & DELETE are happening when IPv6 announces are changing,
1218      * and for some reason it will stop mdnsd to announce IPv6
1219      * addresses. So we force mdnsd to check interfaces.
1220      */
1221     case RTM_ADD:
1222     case RTM_DELETE:
1223          if (pRSMsg->ifam_type == RTM_IFINFO)
1224              result |= 1 << ((struct if_msghdr*) pRSMsg)->ifm_index;
1225          else
1226              result |= 1 << pRSMsg->ifam_index;
1227     break;
1228     }
1229 
1230     return result;
1231 }
1232 
1233 #endif // USES_NETLINK
1234 
1235 // Called when data appears on interface change notification socket
1236 mDNSlocal void InterfaceChangeCallback(int fd, short filter, void *context)
1237 {
1238     IfChangeRec     *pChgRec = (IfChangeRec*) context;
1239     fd_set readFDs;
1240     mDNSu32 changedInterfaces = 0;
1241     struct timeval zeroTimeout = { 0, 0 };
1242 
1243     (void)fd; // Unused
1244     (void)filter; // Unused
1245 
1246     FD_ZERO(&readFDs);
1247     FD_SET(pChgRec->NotifySD, &readFDs);
1248 
1249     do
1250     {
1251         changedInterfaces |= ProcessRoutingNotification(pChgRec->NotifySD);
1252     }
1253     while (0 < select(pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
1254 
1255     // Currently we rebuild the entire interface list whenever any interface change is
1256     // detected. If this ever proves to be a performance issue in a multi-homed
1257     // configuration, more care should be paid to changedInterfaces.
1258     if (changedInterfaces)
1259         mDNSPlatformPosixRefreshInterfaceList(pChgRec->mDNS);
1260 }
1261 
1262 // Register with either a Routing Socket or RtNetLink to listen for interface changes.
1263 mDNSlocal mStatus WatchForInterfaceChange(mDNS *const m)
1264 {
1265     mStatus err;
1266     IfChangeRec *pChgRec;
1267 
1268     pChgRec = (IfChangeRec*) mDNSPlatformMemAllocate(sizeof *pChgRec);
1269     if (pChgRec == NULL)
1270         return mStatus_NoMemoryErr;
1271 
1272     pChgRec->mDNS = m;
1273     err = OpenIfNotifySocket(&pChgRec->NotifySD);
1274     if (err == 0)
1275         err = mDNSPosixAddFDToEventLoop(pChgRec->NotifySD, InterfaceChangeCallback, pChgRec);
1276 
1277     return err;
1278 }
1279 
1280 // Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
1281 // If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
1282 // we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
1283 mDNSlocal mDNSBool mDNSPlatformInit_CanReceiveUnicast(void)
1284 {
1285     int err;
1286     int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
1287     struct sockaddr_in s5353;
1288     s5353.sin_family      = AF_INET;
1289     s5353.sin_port        = MulticastDNSPort.NotAnInteger;
1290     s5353.sin_addr.s_addr = 0;
1291     err = bind(s, (struct sockaddr *)&s5353, sizeof(s5353));
1292     close(s);
1293     if (err) debugf("No unicast UDP responses");
1294     else debugf("Unicast UDP responses okay");
1295     return(err == 0);
1296 }
1297 
1298 // mDNS core calls this routine to initialise the platform-specific data.
1299 mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
1300 {
1301     int err = 0;
1302     struct sockaddr sa;
1303     assert(m != NULL);
1304 
1305     if (mDNSPlatformInit_CanReceiveUnicast()) m->CanReceiveUnicastOn5353 = mDNStrue;
1306 
1307     // Tell mDNS core the names of this machine.
1308 
1309     // Set up the nice label
1310     m->nicelabel.c[0] = 0;
1311     GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
1312     if (m->nicelabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->nicelabel, "Computer");
1313 
1314     // Set up the RFC 1034-compliant label
1315     m->hostlabel.c[0] = 0;
1316     GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
1317     if (m->hostlabel.c[0] == 0) MakeDomainLabelFromLiteralString(&m->hostlabel, "Computer");
1318 
1319     mDNS_SetFQDN(m);
1320 
1321     sa.sa_family = AF_INET;
1322     m->p->unicastSocket4 = -1;
1323     if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket4);
1324 #if HAVE_IPV6
1325     sa.sa_family = AF_INET6;
1326     m->p->unicastSocket6 = -1;
1327     if (err == mStatus_NoError) err = SetupSocket(&sa, zeroIPPort, 0, &m->p->unicastSocket6);
1328 #endif
1329 
1330     // Tell mDNS core about the network interfaces on this machine.
1331     if (err == mStatus_NoError) err = SetupInterfaceList(m);
1332 
1333     // Tell mDNS core about DNS Servers
1334     mDNS_Lock(m);
1335     if (err == mStatus_NoError) ParseDNSServers(m, uDNS_SERVERS_FILE);
1336     mDNS_Unlock(m);
1337 
1338     if (err == mStatus_NoError)
1339     {
1340         err = WatchForInterfaceChange(m);
1341         // Failure to observe interface changes is non-fatal.
1342         if (err != mStatus_NoError)
1343         {
1344             fprintf(stderr, "mDNS(%d) WARNING: Unable to detect interface changes (%d).\n", getpid(), err);
1345             err = mStatus_NoError;
1346         }
1347     }
1348 
1349     // We don't do asynchronous initialization on the Posix platform, so by the time
1350     // we get here the setup will already have succeeded or failed.  If it succeeded,
1351     // we should just call mDNSCoreInitComplete() immediately.
1352     if (err == mStatus_NoError)
1353         mDNSCoreInitComplete(m, mStatus_NoError);
1354 
1355     return PosixErrorToStatus(err);
1356 }
1357 
1358 // mDNS core calls this routine to clean up the platform-specific data.
1359 // In our case all we need to do is to tear down every network interface.
1360 mDNSexport void mDNSPlatformClose(mDNS *const m)
1361 {
1362     int rv;
1363     assert(m != NULL);
1364     ClearInterfaceList(m);
1365     if (m->p->unicastSocket4 != -1)
1366     {
1367         rv = close(m->p->unicastSocket4);
1368         assert(rv == 0);
1369     }
1370 #if HAVE_IPV6
1371     if (m->p->unicastSocket6 != -1)
1372     {
1373         rv = close(m->p->unicastSocket6);
1374         assert(rv == 0);
1375     }
1376 #endif
1377 }
1378 
1379 // This is used internally by InterfaceChangeCallback.
1380 // It's also exported so that the Standalone Responder (mDNSResponderPosix)
1381 // can call it in response to a SIGHUP (mainly for debugging purposes).
1382 mDNSexport mStatus mDNSPlatformPosixRefreshInterfaceList(mDNS *const m)
1383 {
1384     int err;
1385     // This is a pretty heavyweight way to process interface changes --
1386     // destroying the entire interface list and then making fresh one from scratch.
1387     // We should make it like the OS X version, which leaves unchanged interfaces alone.
1388     ClearInterfaceList(m);
1389     err = SetupInterfaceList(m);
1390     return PosixErrorToStatus(err);
1391 }
1392 
1393 #if COMPILER_LIKES_PRAGMA_MARK
1394 #pragma mark ***** Locking
1395 #endif
1396 
1397 // On the Posix platform, locking is a no-op because we only ever enter
1398 // mDNS core on the main thread.
1399 
1400 // mDNS core calls this routine when it wants to prevent
1401 // the platform from reentering mDNS core code.
1402 mDNSexport void    mDNSPlatformLock   (const mDNS *const m)
1403 {
1404     (void) m;   // Unused
1405 }
1406 
1407 // mDNS core calls this routine when it release the lock taken by
1408 // mDNSPlatformLock and allow the platform to reenter mDNS core code.
1409 mDNSexport void    mDNSPlatformUnlock (const mDNS *const m)
1410 {
1411     (void) m;   // Unused
1412 }
1413 
1414 #if COMPILER_LIKES_PRAGMA_MARK
1415 #pragma mark ***** Strings
1416 #endif
1417 
1418 // mDNS core calls this routine to copy C strings.
1419 // On the Posix platform this maps directly to the ANSI C strcpy.
1420 mDNSexport void    mDNSPlatformStrCopy(void *dst, const void *src)
1421 {
1422     strcpy((char *)dst, (const char *)src);
1423 }
1424 
1425 mDNSexport mDNSu32  mDNSPlatformStrLCopy(void *dst, const void *src, mDNSu32 len)
1426 {
1427 #if HAVE_STRLCPY
1428     return ((mDNSu32)strlcpy((char *)dst, (const char *)src, len));
1429 #else
1430     size_t srcLen;
1431 
1432     srcLen = strlen((const char *)src);
1433     if (srcLen < len)
1434     {
1435         memcpy(dst, src, srcLen + 1);
1436     }
1437     else if (len > 0)
1438     {
1439         memcpy(dst, src, len - 1);
1440         ((char *)dst)[len - 1] = '\0';
1441     }
1442 
1443     return ((mDNSu32)srcLen);
1444 #endif
1445 }
1446 
1447 // mDNS core calls this routine to get the length of a C string.
1448 // On the Posix platform this maps directly to the ANSI C strlen.
1449 mDNSexport mDNSu32  mDNSPlatformStrLen (const void *src)
1450 {
1451     return strlen((const char*)src);
1452 }
1453 
1454 // mDNS core calls this routine to copy memory.
1455 // On the Posix platform this maps directly to the ANSI C memcpy.
1456 mDNSexport void    mDNSPlatformMemCopy(void *dst, const void *src, mDNSu32 len)
1457 {
1458     memcpy(dst, src, len);
1459 }
1460 
1461 // mDNS core calls this routine to test whether blocks of memory are byte-for-byte
1462 // identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
1463 mDNSexport mDNSBool mDNSPlatformMemSame(const void *dst, const void *src, mDNSu32 len)
1464 {
1465     return memcmp(dst, src, len) == 0;
1466 }
1467 
1468 // If the caller wants to know the exact return of memcmp, then use this instead
1469 // of mDNSPlatformMemSame
1470 mDNSexport int mDNSPlatformMemCmp(const void *dst, const void *src, mDNSu32 len)
1471 {
1472     return (memcmp(dst, src, len));
1473 }
1474 
1475 mDNSexport void mDNSPlatformQsort(void *base, int nel, int width, int (*compar)(const void *, const void *))
1476 {
1477     (void)qsort(base, nel, width, compar);
1478 }
1479 
1480 // DNSSEC stub functions
1481 mDNSexport void VerifySignature(mDNS *const m, DNSSECVerifier *dv, DNSQuestion *q)
1482 {
1483     (void)m;
1484     (void)dv;
1485     (void)q;
1486 }
1487 
1488 mDNSexport mDNSBool AddNSECSForCacheRecord(mDNS *const m, CacheRecord *crlist, CacheRecord *negcr, mDNSu8 rcode)
1489 {
1490     (void)m;
1491     (void)crlist;
1492     (void)negcr;
1493     (void)rcode;
1494     return mDNSfalse;
1495 }
1496 
1497 mDNSexport void BumpDNSSECStats(mDNS *const m, DNSSECStatsAction action, DNSSECStatsType type, mDNSu32 value)
1498 {
1499     (void)m;
1500     (void)action;
1501     (void)type;
1502     (void)value;
1503 }
1504 
1505 // Proxy stub functions
1506 mDNSexport mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *ptr, mDNSu8 *limit)
1507 {
1508     (void) q;
1509     (void) h;
1510     (void) msg;
1511     (void) ptr;
1512     (void) limit;
1513 
1514     return ptr;
1515 }
1516 
1517 mDNSexport void DNSProxyInit(mDNSu32 IpIfArr[], mDNSu32 OpIf)
1518 {
1519     (void) IpIfArr;
1520     (void) OpIf;
1521 }
1522 
1523 mDNSexport void DNSProxyTerminate(void)
1524 {
1525 }
1526 
1527 // mDNS core calls this routine to clear blocks of memory.
1528 // On the Posix platform this is a simple wrapper around ANSI C memset.
1529 mDNSexport void    mDNSPlatformMemZero(void *dst, mDNSu32 len)
1530 {
1531     memset(dst, 0, len);
1532 }
1533 
1534 mDNSexport void *  mDNSPlatformMemAllocate(mDNSu32 len) { return(malloc(len)); }
1535 mDNSexport void    mDNSPlatformMemFree    (void *mem)   { free(mem); }
1536 
1537 #if _PLATFORM_HAS_STRONG_PRNG_
1538 mDNSexport mDNSu32 mDNSPlatformRandomNumber(void)
1539 {
1540 	return(arc4random());
1541 }
1542 #else
1543 mDNSexport mDNSu32 mDNSPlatformRandomSeed(void)
1544 {
1545     struct timeval tv;
1546     gettimeofday(&tv, NULL);
1547     return(tv.tv_usec);
1548 }
1549 #endif
1550 
1551 mDNSexport mDNSs32 mDNSPlatformOneSecond = 1024;
1552 
1553 mDNSexport mStatus mDNSPlatformTimeInit(void)
1554 {
1555     // No special setup is required on Posix -- we just use gettimeofday();
1556     // This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
1557     // We should find a better way to do this
1558     return(mStatus_NoError);
1559 }
1560 
1561 mDNSexport mDNSs32  mDNSPlatformRawTime()
1562 {
1563     struct timeval tv;
1564     gettimeofday(&tv, NULL);
1565     // tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
1566     // tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
1567     // We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
1568     // 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.
1569     // This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
1570     // and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
1571     return((tv.tv_sec << 10) | (tv.tv_usec * 16 / 15625));
1572 }
1573 
1574 mDNSexport mDNSs32 mDNSPlatformUTC(void)
1575 {
1576     return time(NULL);
1577 }
1578 
1579 mDNSexport void mDNSPlatformSendWakeupPacket(mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration)
1580 {
1581     (void) InterfaceID;
1582     (void) EthAddr;
1583     (void) IPAddr;
1584     (void) iteration;
1585 }
1586 
1587 mDNSexport mDNSBool mDNSPlatformValidRecordForInterface(const AuthRecord *rr, mDNSInterfaceID InterfaceID)
1588 {
1589     (void) rr;
1590     (void) InterfaceID;
1591 
1592     return 1;
1593 }
1594 
1595 mDNSexport mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf)
1596 {
1597     (void) q;
1598     (void) intf;
1599 
1600     return 1;
1601 }
1602 
1603 // Used for debugging purposes. For now, just set the buffer to zero
1604 mDNSexport void mDNSPlatformFormatTime(unsigned long te, mDNSu8 *buf, int bufsize)
1605 {
1606     (void) te;
1607     if (bufsize) buf[0] = 0;
1608 }
1609 
1610 mDNSexport void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win)
1611 {
1612     (void) sadd;    // Unused
1613     (void) dadd;    // Unused
1614     (void) lport;   // Unused
1615     (void) rport;   // Unused
1616     (void) seq;     // Unused
1617     (void) ack;     // Unused
1618     (void) win;     // Unused
1619 }
1620 
1621 mDNSexport mStatus mDNSPlatformRetrieveTCPInfo(mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti)
1622 {
1623     (void) laddr;   // Unused
1624     (void) raddr;   // Unused
1625     (void) lport;   // Unused
1626     (void) rport;   // Unused
1627     (void) mti;     // Unused
1628 
1629     return mStatus_NoError;
1630 }
1631 
1632 mDNSexport mStatus mDNSPlatformGetRemoteMacAddr(mDNSAddr *raddr)
1633 {
1634     (void) raddr; // Unused
1635 
1636     return mStatus_NoError;
1637 }
1638 
1639 mDNSexport mStatus    mDNSPlatformStoreSPSMACAddr(mDNSAddr *spsaddr, char *ifname)
1640 {
1641     (void) spsaddr; // Unused
1642     (void) ifname;  // Unused
1643 
1644     return mStatus_NoError;
1645 }
1646 
1647 mDNSexport mStatus    mDNSPlatformClearSPSData(void)
1648 {
1649     return mStatus_NoError;
1650 }
1651 
1652 mDNSexport mStatus mDNSPlatformStoreOwnerOptRecord(char *ifname, DNSMessage *msg, int length)
1653 {
1654     (void) ifname; // Unused
1655     (void) msg;    // Unused
1656     (void) length; // Unused
1657     return mStatus_UnsupportedErr;
1658 }
1659 
1660 mDNSexport mDNSu16 mDNSPlatformGetUDPPort(UDPSocket *sock)
1661 {
1662     (void) sock; // unused
1663 
1664     return (mDNSu16)-1;
1665 }
1666 
1667 mDNSexport mDNSBool mDNSPlatformInterfaceIsD2D(mDNSInterfaceID InterfaceID)
1668 {
1669     (void) InterfaceID; // unused
1670 
1671     return mDNSfalse;
1672 }
1673 
1674 mDNSexport void mDNSPlatformSetSocktOpt(void *sock, mDNSTransport_Type transType, mDNSAddr_Type addrType, const DNSQuestion *q)
1675 {
1676     (void) sock;
1677     (void) transType;
1678     (void) addrType;
1679     (void) q;
1680 }
1681 
1682 mDNSexport mDNSs32 mDNSPlatformGetPID()
1683 {
1684     return 0;
1685 }
1686 
1687 mDNSlocal void mDNSPosixAddToFDSet(int *nfds, fd_set *readfds, int s)
1688 {
1689     if (*nfds < s + 1) *nfds = s + 1;
1690     FD_SET(s, readfds);
1691 }
1692 
1693 mDNSexport void mDNSPosixGetFDSet(mDNS *m, int *nfds, fd_set *readfds, struct timeval *timeout)
1694 {
1695     mDNSs32 ticks;
1696     struct timeval interval;
1697 
1698     // 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
1699     mDNSs32 nextevent = mDNS_Execute(m);
1700 
1701     // 2. Build our list of active file descriptors
1702     PosixNetworkInterface *info = (PosixNetworkInterface *)(m->HostInterfaces);
1703     if (m->p->unicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket4);
1704 #if HAVE_IPV6
1705     if (m->p->unicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, m->p->unicastSocket6);
1706 #endif
1707     while (info)
1708     {
1709         if (info->multicastSocket4 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket4);
1710 #if HAVE_IPV6
1711         if (info->multicastSocket6 != -1) mDNSPosixAddToFDSet(nfds, readfds, info->multicastSocket6);
1712 #endif
1713         info = (PosixNetworkInterface *)(info->coreIntf.next);
1714     }
1715 
1716     // 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
1717     ticks = nextevent - mDNS_TimeNow(m);
1718     if (ticks < 1) ticks = 1;
1719     interval.tv_sec  = ticks >> 10;                     // The high 22 bits are seconds
1720     interval.tv_usec = ((ticks & 0x3FF) * 15625) / 16;  // The low 10 bits are 1024ths
1721 
1722     // 4. If client's proposed timeout is more than what we want, then reduce it
1723     if (timeout->tv_sec > interval.tv_sec ||
1724         (timeout->tv_sec == interval.tv_sec && timeout->tv_usec > interval.tv_usec))
1725         *timeout = interval;
1726 }
1727 
1728 mDNSexport void mDNSPosixProcessFDSet(mDNS *const m, fd_set *readfds)
1729 {
1730     PosixNetworkInterface *info;
1731     assert(m       != NULL);
1732     assert(readfds != NULL);
1733     info = (PosixNetworkInterface *)(m->HostInterfaces);
1734 
1735     if (m->p->unicastSocket4 != -1 && FD_ISSET(m->p->unicastSocket4, readfds))
1736     {
1737         FD_CLR(m->p->unicastSocket4, readfds);
1738         SocketDataReady(m, NULL, m->p->unicastSocket4);
1739     }
1740 #if HAVE_IPV6
1741     if (m->p->unicastSocket6 != -1 && FD_ISSET(m->p->unicastSocket6, readfds))
1742     {
1743         FD_CLR(m->p->unicastSocket6, readfds);
1744         SocketDataReady(m, NULL, m->p->unicastSocket6);
1745     }
1746 #endif
1747 
1748     while (info)
1749     {
1750         if (info->multicastSocket4 != -1 && FD_ISSET(info->multicastSocket4, readfds))
1751         {
1752             FD_CLR(info->multicastSocket4, readfds);
1753             SocketDataReady(m, info, info->multicastSocket4);
1754         }
1755 #if HAVE_IPV6
1756         if (info->multicastSocket6 != -1 && FD_ISSET(info->multicastSocket6, readfds))
1757         {
1758             FD_CLR(info->multicastSocket6, readfds);
1759             SocketDataReady(m, info, info->multicastSocket6);
1760         }
1761 #endif
1762         info = (PosixNetworkInterface *)(info->coreIntf.next);
1763     }
1764 }
1765 
1766 // update gMaxFD
1767 mDNSlocal void  DetermineMaxEventFD(void)
1768 {
1769     PosixEventSource    *iSource;
1770 
1771     gMaxFD = 0;
1772     for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1773         if (gMaxFD < iSource->fd)
1774             gMaxFD = iSource->fd;
1775 }
1776 
1777 // Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
1778 mStatus mDNSPosixAddFDToEventLoop(int fd, mDNSPosixEventCallback callback, void *context)
1779 {
1780     PosixEventSource    *newSource;
1781 
1782     if (gEventSources.LinkOffset == 0)
1783         InitLinkedList(&gEventSources, offsetof(PosixEventSource, Next));
1784 
1785     if (fd >= (int) FD_SETSIZE || fd < 0)
1786         return mStatus_UnsupportedErr;
1787     if (callback == NULL)
1788         return mStatus_BadParamErr;
1789 
1790     newSource = (PosixEventSource*) malloc(sizeof *newSource);
1791     if (NULL == newSource)
1792         return mStatus_NoMemoryErr;
1793 
1794     newSource->Callback = callback;
1795     newSource->Context = context;
1796     newSource->fd = fd;
1797 
1798     AddToTail(&gEventSources, newSource);
1799     FD_SET(fd, &gEventFDs);
1800 
1801     DetermineMaxEventFD();
1802 
1803     return mStatus_NoError;
1804 }
1805 
1806 // Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
1807 mStatus mDNSPosixRemoveFDFromEventLoop(int fd)
1808 {
1809     PosixEventSource    *iSource;
1810 
1811     for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1812     {
1813         if (fd == iSource->fd)
1814         {
1815             FD_CLR(fd, &gEventFDs);
1816             RemoveFromList(&gEventSources, iSource);
1817             free(iSource);
1818             DetermineMaxEventFD();
1819             return mStatus_NoError;
1820         }
1821     }
1822     return mStatus_NoSuchNameErr;
1823 }
1824 
1825 // Simply note the received signal in gEventSignals.
1826 mDNSlocal void  NoteSignal(int signum)
1827 {
1828     sigaddset(&gEventSignals, signum);
1829 }
1830 
1831 // Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
1832 mStatus mDNSPosixListenForSignalInEventLoop(int signum)
1833 {
1834     struct sigaction action;
1835     mStatus err;
1836 
1837     mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
1838     action.sa_handler = NoteSignal;
1839     err = sigaction(signum, &action, (struct sigaction*) NULL);
1840 
1841     sigaddset(&gEventSignalSet, signum);
1842 
1843     return err;
1844 }
1845 
1846 // Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
1847 mStatus mDNSPosixIgnoreSignalInEventLoop(int signum)
1848 {
1849     struct sigaction action;
1850     mStatus err;
1851 
1852     mDNSPlatformMemZero(&action, sizeof action);        // more portable than member-wise assignment
1853     action.sa_handler = SIG_DFL;
1854     err = sigaction(signum, &action, (struct sigaction*) NULL);
1855 
1856     sigdelset(&gEventSignalSet, signum);
1857 
1858     return err;
1859 }
1860 
1861 // Do a single pass through the attendent event sources and dispatch any found to their callbacks.
1862 // Return as soon as internal timeout expires, or a signal we're listening for is received.
1863 mStatus mDNSPosixRunEventLoopOnce(mDNS *m, const struct timeval *pTimeout,
1864                                   sigset_t *pSignalsReceived, mDNSBool *pDataDispatched)
1865 {
1866     fd_set listenFDs = gEventFDs;
1867     int fdMax = 0, numReady;
1868     struct timeval timeout = *pTimeout;
1869 
1870     // Include the sockets that are listening to the wire in our select() set
1871     mDNSPosixGetFDSet(m, &fdMax, &listenFDs, &timeout); // timeout may get modified
1872     if (fdMax < gMaxFD)
1873         fdMax = gMaxFD;
1874 
1875     numReady = select(fdMax + 1, &listenFDs, (fd_set*) NULL, (fd_set*) NULL, &timeout);
1876 
1877     // If any data appeared, invoke its callback
1878     if (numReady > 0)
1879     {
1880         PosixEventSource    *iSource;
1881 
1882         (void) mDNSPosixProcessFDSet(m, &listenFDs);    // call this first to process wire data for clients
1883 
1884         for (iSource=(PosixEventSource*)gEventSources.Head; iSource; iSource = iSource->Next)
1885         {
1886             if (FD_ISSET(iSource->fd, &listenFDs))
1887             {
1888                 iSource->Callback(iSource->fd, 0, iSource->Context);
1889                 break;  // in case callback removed elements from gEventSources
1890             }
1891         }
1892         *pDataDispatched = mDNStrue;
1893     }
1894     else
1895         *pDataDispatched = mDNSfalse;
1896 
1897     (void) sigprocmask(SIG_BLOCK, &gEventSignalSet, (sigset_t*) NULL);
1898     *pSignalsReceived = gEventSignals;
1899     sigemptyset(&gEventSignals);
1900     (void) sigprocmask(SIG_UNBLOCK, &gEventSignalSet, (sigset_t*) NULL);
1901 
1902     return mStatus_NoError;
1903 }
1904