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