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