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