source: rtems-libbsd/mDNSResponder/mDNSPosix/mDNSPosix.c @ 91b858d

5-freebsd-12
Last change on this file since 91b858d was 91b858d, checked in by Sebastian Huber <sebastian.huber@…>, on Oct 16, 2018 at 9:24:10 AM

mDNSResponder: Fix use of uninitialized variables

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