source: rtems-libbsd/mDNSResponder/mDNSPosix/mDNSPosix.c @ 4d8f9e6

55-freebsd-126-freebsd-12
Last change on this file since 4d8f9e6 was 4d8f9e6, checked in by Sebastian Huber <sebastian.huber@…>, on 09/17/18 at 07:47:20

mDNSResponder: Honour file descriptor maximum

Dynamically allocate a big enough file descriptor set for select(). A
better solution would be to use kqueue() instead of select().

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