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