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