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