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