mDNSPosix.c revision 4b22b9337f359bfd063322244f5336cc7c6ffcfa
/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2002-2004 Apple Computer, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Formatting notes:
* This code follows the "Whitesmiths style" C indentation rules. Plenty of discussion
* on C indentation can be found on the web, such as <http://www.kafejo.com/komp/1tbs.htm>,
* but for the sake of brevity here I will say just this: Curly braces are not syntactially
* part of an "if" statement; they are the beginning and ending markers of a compound statement;
* therefore common sense dictates that if they are part of a compound statement then they
* should be indented to the same level as everything else in that compound statement.
* Indenting curly braces at the same level as the "if" implies that curly braces are
* part of the "if", which is false. (This is as misleading as people who write "char* x,y;"
* thinking that variables x and y are both of type "char*" -- and anyone who doesn't
* understand why variable y is not of type "char*" just proves the point that poor code
* layout leads people to unfortunate misunderstandings about how the C language really works.)
Change History (most recent first):
$Log: mDNSPosix.c,v $
Revision 1.78.2.1 2006/08/29 06:24:34 cheshire
Re-licensed mDNSResponder daemon source code under Apache License, Version 2.0
Revision 1.78 2006/06/28 09:12:22 cheshire
Added debugging message
Revision 1.77 2006/03/19 02:00:11 cheshire
<rdar://problem/4073825> Improve logic for delaying packets after repeated interface transitions
Revision 1.76 2006/01/09 19:29:16 cheshire
<rdar://problem/4403128> Cap number of "sendto failed" messages we allow mDNSResponder to log
Revision 1.75 2006/01/05 22:04:57 cheshire
<rdar://problem/4399479> Log error message when send fails with "operation not permitted"
Revision 1.74 2006/01/05 21:45:27 cheshire
<rdar://problem/4400118> Fix uninitialized structure member in IPv6 code
Revision 1.73 2005/10/11 21:31:46 cheshire
<rdar://problem/4296177> Don't depend on IP_RECVTTL succeeding (not available on all platforms)
Revision 1.72 2005/09/08 20:45:26 cheshire
Default dot-local host name should be "Computer" not "Macintosh",
since the machine this is running on is most likely NOT a Mac.
Revision 1.71 2005/02/26 01:29:12 cheshire
Ignore multicasts accidentally delivered to our unicast receiving socket
Revision 1.70 2005/02/04 00:39:59 cheshire
Move ParseDNSServers() from PosixDaemon.c to mDNSPosix.c so all Posix client layers can use it
Revision 1.69 2004/12/18 02:03:28 cheshire
Need to #include "dns_sd.h"
Revision 1.68 2004/12/18 00:51:52 cheshire
Use symbolic constant kDNSServiceInterfaceIndexLocalOnly instead of (mDNSu32) ~0
Revision 1.67 2004/12/17 23:37:48 cheshire
<rdar://problem/3485365> Guard against repeating wireless dissociation/re-association
(and other repetitive configuration changes)
Revision 1.66 2004/12/01 04:27:28 cheshire
<rdar://problem/3872803> Darwin patches for Solaris and Suse
Don't use uint32_t, etc. -- they require stdint.h, which doesn't exist on FreeBSD 4.x, Solaris, etc.
Revision 1.65 2004/11/30 22:37:01 cheshire
Update copyright dates and add "Mode: C; tab-width: 4" headers
Revision 1.64 2004/11/23 03:39:47 cheshire
Let interface name/index mapping capability live directly in JNISupport.c,
instead of having to call through to the daemon via IPC to get this information.
Revision 1.63 2004/11/12 03:16:43 rpantos
rdar://problem/3809541 Add mDNSPlatformGetInterfaceByName, mDNSPlatformGetInterfaceName
Revision 1.62 2004/10/28 03:24:42 cheshire
Rename m->CanReceiveUnicastOn as m->CanReceiveUnicastOn5353
Revision 1.61 2004/10/16 00:17:01 cheshire
<rdar://problem/3770558> Replace IP TTL 255 check with local subnet source address check
Revision 1.60 2004/09/26 23:20:36 ksekar
<rdar://problem/3813108> Allow default registrations in multiple wide-area domains
Revision 1.59 2004/09/21 21:02:55 cheshire
Set up ifname before calling mDNS_RegisterInterface()
Revision 1.58 2004/09/17 01:08:54 cheshire
Renamed mDNSClientAPI.h to mDNSEmbeddedAPI.h
The name "mDNSClientAPI.h" is misleading to new developers looking at this code. The interfaces
declared in that file are ONLY appropriate to single-address-space embedded applications.
For clients on general-purpose computers, the interfaces defined in dns_sd.h should be used.
Revision 1.57 2004/09/17 00:19:11 cheshire
For consistency with AllDNSLinkGroupv6, rename AllDNSLinkGroup to AllDNSLinkGroupv4
Revision 1.56 2004/09/17 00:15:56 cheshire
Rename mDNSPlatformInit_ReceiveUnicast to mDNSPlatformInit_CanReceiveUnicast
Revision 1.55 2004/09/16 00:24:49 cheshire
<rdar://problem/3803162> Fix unsafe use of mDNSPlatformTimeNow()
Revision 1.54 2004/09/15 23:55:00 ksekar
<rdar://problem/3800597> mDNSPosix should #include stdint.h
Revision 1.53 2004/09/14 23:42:36 cheshire
<rdar://problem/3801296> Need to seed random number generator from platform-layer data
Revision 1.52 2004/08/25 16:42:13 ksekar
Fix Posix build - change mDNS_SetFQDNs to mDNS_SetFQDN, remove unicast
hostname parameter.
Revision 1.51 2004/08/14 03:22:42 cheshire
<rdar://problem/3762579> Dynamic DNS UI <-> mDNSResponder glue
Add GetUserSpecifiedDDNSName() routine
Convert ServiceRegDomain to domainname instead of C string
Replace mDNS_GenerateFQDN/mDNS_GenerateGlobalFQDN with mDNS_SetFQDNs
Revision 1.50 2004/08/11 01:20:20 cheshire
Declare private local functions using "mDNSlocal"
Revision 1.49 2004/07/26 22:49:31 ksekar
<rdar://problem/3651409>: Feature #9516: Need support for NATPMP in client
Revision 1.48 2004/07/20 01:47:36 rpantos
NOT_HAVE_SA_LEN applies to v6, too. And use more-portable s6_addr.
Revision 1.47 2004/06/25 00:26:27 rpantos
Changes to fix the Posix build on Solaris.
Revision 1.46 2004/05/13 04:54:20 ksekar
Revision 1.45 2004/05/12 22:03:09 ksekar
Made GetSearchDomainList a true platform-layer call (declaration moved
from mDNSMacOSX.h to mDNSEmbeddedAPI.h), impelemted to return "local"
only on non-OSX platforms. Changed call to return a copy of the list
to avoid shared memory issues. Added a routine to free the list.
Revision 1.44 2004/04/21 02:49:11 cheshire
To reduce future confusion, renamed 'TxAndRx' to 'McastTxRx'
Revision 1.43 2004/04/14 23:09:29 ksekar
Support for TSIG signed dynamic updates.
Revision 1.42 2004/04/09 17:43:04 cheshire
Make sure to set the McastTxRx field so that duplicate suppression works correctly
Revision 1.41 2004/02/06 01:19:51 cheshire
Conditionally exclude IPv6 code unless HAVE_IPV6 is set
Revision 1.40 2004/02/05 01:00:01 rpantos
Fix some issues that turned up when building for FreeBSD.
Revision 1.39 2004/01/28 21:12:15 cheshire
Reconcile mDNSIPv6Support & HAVE_IPV6 into a single flag (HAVE_IPV6)
Revision 1.38 2004/01/27 20:15:23 cheshire
<rdar://problem/3541288>: Time to prune obsolete code for listening on port 53
Revision 1.37 2004/01/24 05:12:03 cheshire
<rdar://problem/3534352>: Need separate socket for issuing unicast queries
Revision 1.36 2004/01/24 04:59:16 cheshire
Revision 1.35 2004/01/23 21:37:08 cheshire
For consistency, rename multicastSocket to multicastSocket4, and multicastSocketv6 to multicastSocket6
Revision 1.34 2004/01/22 03:43:09 cheshire
Export constants like mDNSInterface_LocalOnly so that the client layers can use them
Revision 1.33 2004/01/21 21:54:20 cheshire
<rdar://problem/3448144>: Don't try to receive unicast responses if we're not the first to bind to the UDP port
Revision 1.32 2004/01/20 01:49:28 rpantos
Tweak error handling of last checkin a bit.
Revision 1.31 2004/01/20 01:39:27 rpantos
Respond to If changes by rebuilding interface list.
Revision 1.30 2003/12/11 19:40:36 cheshire
Fix 'destAddr.type == senderAddr.type;' that should have said 'destAddr.type = senderAddr.type;'
Revision 1.29 2003/12/11 18:53:22 cheshire
Fix compiler warning reported by Paul Guyot
Revision 1.28 2003/12/11 03:03:51 rpantos
Clean up mDNSPosix so that it builds on OS X again.
Revision 1.27 2003/12/08 20:47:02 rpantos
Add support for mDNSResponder on Linux.
Revision 1.26 2003/11/14 20:59:09 cheshire
Clients can't use AssignDomainName macro because mDNSPlatformMemCopy is defined in mDNSPlatformFunctions.h.
Best solution is just to combine mDNSEmbeddedAPI.h and mDNSPlatformFunctions.h into a single file.
Revision 1.25 2003/10/30 19:25:49 cheshire
Revision 1.24 2003/08/18 23:12:23 cheshire
<rdar://problem/3382647> mDNSResponder divide by zero in mDNSPlatformRawTime()
Revision 1.23 2003/08/12 19:56:26 cheshire
Update to APSL 2.0
Revision 1.22 2003/08/06 18:46:15 cheshire
LogMsg() errors are serious -- always report them to stderr, regardless of debugging level
Revision 1.21 2003/08/06 18:20:51 cheshire
Makefile cleanup
Revision 1.20 2003/08/05 23:56:26 cheshire
Update code to compile with the new mDNSCoreReceive() function that requires a TTL
(Right now mDNSPosix.c just reports 255 -- we should fix this)
Revision 1.19 2003/07/19 03:15:16 cheshire
Add generic MemAllocate/MemFree prototypes to mDNSPlatformFunctions.h,
and add the obvious trivial implementations to each platform support layer
Revision 1.18 2003/07/14 18:11:54 cheshire
Fix stricter compiler warnings
Revision 1.17 2003/07/13 01:08:38 cheshire
There's not much point running mDNS over a point-to-point link; exclude those
Revision 1.16 2003/07/02 21:19:59 cheshire
<rdar://problem/3313413> Update copyright notices, etc., in source code comments
Revision 1.15 2003/06/18 05:48:41 cheshire
Fix warnings
Revision 1.14 2003/05/26 03:21:30 cheshire
Tidy up address structure naming:
mDNSIPAddr => mDNSv4Addr (for consistency with mDNSv6Addr)
mDNSAddr.addr.ipv4 => mDNSAddr.ip.v4
mDNSAddr.addr.ipv6 => mDNSAddr.ip.v6
Revision 1.13 2003/05/26 03:01:28 cheshire
<rdar://problem/3268904> sprintf/vsprintf-style functions are unsafe; use snprintf/vsnprintf instead
Revision 1.12 2003/05/21 03:49:18 cheshire
Fix warning
Revision 1.11 2003/05/06 00:00:50 cheshire
<rdar://problem/3248914> Rationalize naming of domainname manipulation functions
Revision 1.10 2003/04/25 01:45:57 cheshire
<rdar://problem/3240002> mDNS_RegisterNoSuchService needs to include a host name
Revision 1.9 2003/03/20 21:10:31 cheshire
Fixes done at IETF 56 to make mDNSProxyResponderPosix run on Solaris
Revision 1.8 2003/03/15 04:40:38 cheshire
Change type called "mDNSOpaqueID" to the more descriptive name "mDNSInterfaceID"
Revision 1.7 2003/03/13 03:46:21 cheshire
Fixes to make the code build on Linux
Revision 1.6 2003/03/08 00:35:56 cheshire
Switched to using new "mDNS_Execute" model (see "mDNSCore/Implementer Notes.txt")
Revision 1.5 2002/12/23 22:13:31 jgraessl
Reviewed by: Stuart Cheshire
Initial IPv6 support for mDNSResponder.
Revision 1.4 2002/09/27 01:47:45 cheshire
Workaround for Linux 2.0 systems that don't have IP_PKTINFO
Revision 1.3 2002/09/21 20:44:53 zarzycki
Added APSL info
Revision 1.2 2002/09/19 21:25:36 cheshire
mDNS_snprintf() doesn't need to be in a separate file
Revision 1.1 2002/09/17 06:24:34 cheshire
First checkin
*/
#pragma ident "%Z%%M% %I% %E% SMI"
#include "mDNSEmbeddedAPI.h" // Defines the interface provided to the client layer above
#include "mDNSPosix.h" // Defines the specific types needed to run mDNS on this platform
#include "dns_sd.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <stdarg.h>
#include <fcntl.h>
#include <time.h> // platform support for UTC time
#if USES_NETLINK
#include <linux/rtnetlink.h>
#else // USES_NETLINK
#endif // USES_NETLINK
#include "mDNSUNP.h"
#include "GenLinkedList.h"
// ***************************************************************************
// Structures
// We keep a list of client-supplied event sources in PosixEventSource records
struct PosixEventSource
{
void *Context;
int fd;
struct PosixEventSource *Next;
};
typedef struct PosixEventSource PosixEventSource;
// Context record for interface change callback
struct IfChangeRec
{
int NotifySD;
};
typedef struct IfChangeRec IfChangeRec;
// Note that static data is initialized to zero in (modern) C.
static int gMaxFD; // largest fd in gEventFDs
// ***************************************************************************
// Globals (for debugging)
static int num_registered_interfaces = 0;
static int num_pkts_accepted = 0;
static int num_pkts_rejected = 0;
// ***************************************************************************
// Functions
int gMDNSPlatformPosixVerboseLevel = 0;
mDNSlocal void SockAddrTomDNSAddr(const struct sockaddr *const sa, mDNSAddr *ipAddr, mDNSIPPort *ipPort)
{
{
case AF_INET:
{
break;
}
#if HAVE_IPV6
case AF_INET6:
{
#ifndef NOT_HAVE_SA_LEN
#endif
break;
}
#endif
default:
break;
}
}
#endif
// mDNS core calls this routine when it needs to send a packet.
mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
{
int err = 0;
struct sockaddr_storage to;
int sendingsocket = -1;
{
#ifndef NOT_HAVE_SA_LEN
#endif
}
#if HAVE_IPV6
{
#ifndef NOT_HAVE_SA_LEN
#endif
}
#endif
if (sendingsocket >= 0)
err = sendto(sendingsocket, msg, (char*)end - (char*)msg, 0, (struct sockaddr *)&to, GET_SA_LEN(to));
else if (err < 0)
{
static int MessageCount = 0;
// Don't report EHOSTDOWN (i.e. ARP failure), ENETDOWN, or no route to host for unicast destinations
if (!mDNSAddressIsAllDNSLinkGroup(dst))
if (errno == EHOSTDOWN || errno == ENETDOWN || errno == EHOSTUNREACH || errno == ENETUNREACH) return(mStatus_TransientErr);
if (MessageCount < 1000)
{
MessageCount++;
if (thisIntf)
LogMsg("mDNSPlatformSendUDP got error %d (%s) sending packet to %#a on interface %#a/%s/%d",
else
}
}
return PosixErrorToStatus(err);
}
// This routine is called when the main loop detects that data is available on a socket.
{
struct my_in_pktinfo packetInfo;
struct sockaddr_storage from;
int flags;
flags = 0;
packetLen = recvfrom_flags(skt, &packet, sizeof(packet), &flags, (struct sockaddr *) &from, &fromLen, &packetInfo, &ttl);
if (packetLen >= 0)
{
// If we have broken IP_RECVDSTADDR functionality (so far
// I've only seen this on OpenBSD) then apply a hack to
// convince mDNS Core that this isn't a spoof packet.
// Basically what we do is check to see whether the
// packet arrived as a multicast and, if so, set its
// destAddr to the mDNS address.
//
// I must admit that I could just be doing something
// wrong on OpenBSD and hence triggering this problem
// but I'm at a loss as to how.
//
// If this platform doesn't have IP_PKTINFO or IP_RECVDSTADDR, then we have
// no way to tell the destination address or interface this packet arrived on,
// so all we can do is just assume it's a multicast
{
}
#endif
// We only accept the packet if the interface on which it came
// in matches the interface associated with this socket.
// We do this match by name or by index, depending on which
// information is available. recvfrom_flags sets the name
// to "" if the name isn't available, or the index to -1
// if the index is available. This accomodates the various
// different capabilities of our target platforms.
if (!intf)
{
// Ignore multicasts accidentally delivered to our unicast receiving socket
}
else
{
if (reject)
{
verbosedebugf("SocketDataReady ignored a packet from %#a to %#a on interface %s/%d expecting %#a/%s/%d/%d",
packetLen = -1;
{
"*** WARNING: Received %d packets; Accepted %d packets; Rejected %d packets because of interface mismatch\n",
num_pkts_accepted = 0;
num_pkts_rejected = 0;
}
}
else
{
verbosedebugf("SocketDataReady got a packet from %#a to %#a on interface %#a/%s/%d/%d",
}
}
}
if (packetLen >= 0)
}
mDNSexport mStatus mDNSPlatformTCPConnect(const mDNSAddr *dst, mDNSOpaque16 dstport, mDNSInterfaceID InterfaceID,
{
(void)dst; // Unused
(void)dstport; // Unused
(void)InterfaceID; // Unused
(void)callback; // Unused
(void)context; // Unused
(void)descriptor; // Unused
return(mStatus_UnsupportedErr);
}
{
(void)sd; // Unused
}
{
(void)sd; // Unused
(void)buf; // Unused
(void)buflen; // Unused
return(0);
}
{
(void)sd; // Unused
(void)msg; // Unused
(void)len; // Unused
return(0);
}
#endif
{
static DNameListElem tmp;
if (!init)
{
}
return mDNS_CopyDNameList(&tmp);
}
{
return NULL;
}
#endif
// This gets the current hostname, truncating it at the first dot if necessary
{
int len = 0;
}
// On OS X this gets the text of the field labelled "Computer Name" in the Sharing Prefs Control Panel
// Other platforms can either get the information from the appropriate place,
// or they can alternatively just require all registering services to provide an explicit name
{
// On Unix we have no better name than the host name, so we just use that.
}
{
char line[256];
char nameserver[16];
char keyword[10];
int numOfServers = 0;
{
{
numOfServers++;
}
}
return (numOfServers > 0) ? 0 : -1;
}
// Searches the interface list looking for the named interface.
// Returns a pointer to if it found, or NULL otherwise.
{
return intf;
}
{
return (mDNSInterfaceID) intf;
}
{
}
// Frees the specified PosixNetworkInterface structure. The underlying
// interface must have already been deregistered with the mDNS core.
{
#if HAVE_IPV6
#endif
}
// Grab the first interface, deregister it, free it, and repeat until done.
{
while (m->HostInterfaces)
{
if (gMDNSPlatformPosixVerboseLevel > 0) fprintf(stderr, "Deregistered interface %s\n", intf->intfName);
}
num_pkts_accepted = 0;
num_pkts_rejected = 0;
}
// If mDNSIPPort port is non-zero, then it's a multicast socket on the specified interface
// If mDNSIPPort port is zero, then it's a randomly assigned port number, used for sending unicast queries
mDNSlocal int SetupSocket(struct sockaddr *intfAddr, mDNSIPPort port, int interfaceIndex, int *sktPtr)
{
int err = 0;
static const int kOn = 1;
static const int kIntTwoFiveFive = 255;
static const unsigned char kByteTwoFiveFive = 255;
(void) interfaceIndex; // This parameter unused on plaforms that don't have IPv6
// Open the socket...
#if HAVE_IPV6
#endif
else return EINVAL;
// ... with a shared UDP port, if it's for multicast receiving
{
#if defined(SO_REUSEPORT)
#elif defined(SO_REUSEADDR)
#else
#endif
}
// We want to receive destination addresses and interface identifiers.
{
struct sockaddr_in bindAddr;
if (err == 0)
{
#if defined(IP_PKTINFO) // Linux and Solaris
#if defined(IP_RECVDSTADDR)
#endif
#if defined(IP_RECVIF)
if (err == 0)
{
}
#endif
#else
#warning This platform has no way to get the destination interface information -- will only work for single-homed hosts
#endif
}
#if defined(IP_RECVTTL) // Linux
if (err == 0)
{
// We no longer depend on being able to get the received TTL, so don't worry if the option fails
}
#endif
// Add multicast group membership on this interface
if (err == 0 && JoinMulticastGroup)
{
}
// Specify outgoing interface too
if (err == 0 && JoinMulticastGroup)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_IF, &((struct sockaddr_in*)intfAddr)->sin_addr, sizeof(struct in_addr));
}
// Per the mDNS spec, send unicast packets with TTL 255
if (err == 0)
{
}
// and multicast packets with TTL 255 too
// There's some debate as to whether IP_MULTICAST_TTL is an int or a byte so we just try both.
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IP, IP_MULTICAST_TTL, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
}
// And start listening for packets
if (err == 0)
{
}
} // endif (intfAddr->sa_family == AF_INET)
#if HAVE_IPV6
{
struct sockaddr_in6 bindAddr6;
#if defined(IPV6_RECVPKTINFO) // Solaris
if (err == 0)
{
}
#elif defined(IPV6_PKTINFO)
if (err == 0)
{
}
#else
#warning This platform has no way to get the destination interface information for IPv6 -- will only work for single-homed hosts
#endif
#if defined(IPV6_RECVHOPLIMIT) // Solaris
if (err == 0)
{
}
#elif defined(IPV6_HOPLIMIT)
if (err == 0)
{
}
#endif
// Add multicast group membership on this interface
if (err == 0 && JoinMulticastGroup)
{
//LogMsg("Joining %.16a on %d", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
if (err < 0)
{
verbosedebugf("IPV6_JOIN_GROUP %.16a on %d failed.\n", &imr6.ipv6mr_multiaddr, imr6.ipv6mr_interface);
perror("setsockopt - IPV6_JOIN_GROUP");
}
}
// Specify outgoing interface too
if (err == 0 && JoinMulticastGroup)
{
}
// We want to receive only IPv6 packets on this socket.
// Without this option, we may get IPv4 addresses as mapped addresses.
if (err == 0)
{
}
// Per the mDNS spec, send unicast packets with TTL 255
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
}
// and multicast packets with TTL 255 too
// There's some debate as to whether IPV6_MULTICAST_HOPS is an int or a byte so we just try both.
if (err == 0)
{
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kByteTwoFiveFive, sizeof(kByteTwoFiveFive));
err = setsockopt(*sktPtr, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &kIntTwoFiveFive, sizeof(kIntTwoFiveFive));
}
// And start listening for packets
if (err == 0)
{
#ifndef NOT_HAVE_SA_LEN
#endif
bindAddr6.sin6_flowinfo = 0;
bindAddr6.sin6_scope_id = 0;
}
} // endif (intfAddr->sa_family == AF_INET6)
#endif
// Set the socket to non-blocking.
if (err == 0)
{
else
{
}
}
// Clean up
return err;
}
// Creates a PosixNetworkInterface for the interface whose IP address is
// intfAddr and whose name is intfName and registers it with mDNS core.
mDNSlocal int SetupOneInterface(mDNS *const m, struct sockaddr *intfAddr, struct sockaddr *intfMask, const char *intfName, int intfIndex)
{
int err = 0;
// Allocate the interface structure itself.
// And make a copy of the intfName.
if (err == 0)
{
}
if (err == 0)
{
// Set up the fields required by the mDNS core.
//LogMsg("SetupOneInterface: %#a %#a", &intf->coreIntf.ip, &intf->coreIntf.mask);
// Set up the extra fields in PosixNetworkInterface.
#if HAVE_IPV6
#endif
debugf("SetupOneInterface: %s %#a is an alias of %#a", intfName, &intf->coreIntf.ip, &alias->coreIntf.ip);
}
// Set up the multicast socket
if (err == 0)
{
#if HAVE_IPV6
#endif
}
// The interface is all ready to go, let's register it with the mDNS core.
if (err == 0)
// Clean up.
if (err == 0)
{
if (gMDNSPlatformPosixVerboseLevel > 0)
}
else
{
// Use intfName instead of intf->intfName in the next line to avoid dereferencing NULL.
}
return err;
}
// Call get_ifi_info() to obtain a list of active interfaces and call SetupOneInterface() on each one.
{
int err = 0;
debugf("SetupInterfaceList");
#if HAVE_IPV6
if (err == 0) /* Link the IPv6 list to the end of the IPv4 list */
{
while (*p) p = &(*p)->ifi_next;
}
#endif
if (err == 0)
{
while (i)
{
#if HAVE_IPV6
#endif
{
if (i->ifi_flags & IFF_LOOPBACK)
{
if (firstLoopback == NULL)
firstLoopback = i;
}
else
{
}
}
i = i->ifi_next;
}
// If we found no normal interfaces but we did find a loopback interface, register the
// loopback interface. This allows self-discovery if no interfaces are configured.
// Temporary workaround: Multicast loopback on IPv6 interfaces appears not to work.
// In the interim, we skip loopback interface only if we found at least one v4 interface to use
// if ( (m->HostInterfaces == NULL) && (firstLoopback != NULL) )
if ( !foundav4 && firstLoopback )
(void) SetupOneInterface(m, firstLoopback->ifi_addr, firstLoopback->ifi_netmask, firstLoopback->ifi_name, firstLoopback->ifi_index);
}
// Clean up.
return err;
}
#if USES_NETLINK
// See <http://www.faqs.org/rfcs/rfc3549.html> for a description of NetLink
// Open a socket that will receive interface change notifications
{
struct sockaddr_nl snl;
int sock;
int ret;
if (sock < 0)
return errno;
// Configure read to be non-blocking because inbound msg size is not known in advance
/* Subscribe the socket to Link & IP addr notifications. */
if ( 0 == ret)
else
return err;
}
#if MDNS_DEBUGMSGS
{
const char *kNLRtMsgTypes[] = { "RTM_NEWLINK", "RTM_DELLINK", "RTM_GETLINK", "RTM_NEWADDR", "RTM_DELADDR", "RTM_GETADDR" };
pNLMsg->nlmsg_type < RTM_BASE ? kNLMsgTypes[ pNLMsg->nlmsg_type] : kNLRtMsgTypes[ pNLMsg->nlmsg_type - RTM_BASE],
{
}
{
}
printf( "\n");
}
#endif
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
char buff[ 4096];
// The structure here is more complex than it really ought to be because,
// unfortunately, there's no good way to size a buffer in advance large
// enough to hold all pending data and so avoid message fragmentation.
// (Note that FIONREAD is not supported on AF_NETLINK.)
while ( 1)
{
// Make sure we've got an entire nlmsghdr in the buffer, and payload, too.
// If not, discard already-processed messages in buffer and read more data.
{
{
// discard processed data
// read more data
continue; // spin around and revalidate with new readCount
}
else
break; // Otherwise message does not fit in buffer
}
#if MDNS_DEBUGMSGS
#endif
// Process the NetLink message
// Advance pNLMsg to the next message in the buffer
{
}
else
break; // all done!
}
return result;
}
#else // USES_NETLINK
// Open a socket that will receive interface change notifications
{
if ( *pFD < 0)
return mStatus_UnknownErr;
// Configure read to be non-blocking because inbound msg size is not known in advance
return mStatus_NoError;
}
#if MDNS_DEBUGMSGS
{
"RTM_REDIRECT", "RTM_MISS", "RTM_LOCK", "RTM_OLDADD", "RTM_OLDDEL", "RTM_RESOLVE",
"RTM_NEWADDR", "RTM_DELADDR", "RTM_IFINFO", "RTM_NEWMADDR", "RTM_DELMADDR" };
int index = pRSMsg->ifam_type == RTM_IFINFO ? ((struct if_msghdr*) pRSMsg)->ifm_index : pRSMsg->ifam_index;
printf( "ifa_msghdr len=%d, type=%s, index=%d\n", pRSMsg->ifam_msglen, kRSMsgTypes[ pRSMsg->ifam_type], index);
}
#endif
// Read through the messages on sd and if any indicate that any interface records should
// be torn down and rebuilt, return affected indices as a bitmask. Otherwise return 0.
{
char buff[ 4096];
return mStatus_UnsupportedErr; // cannot decipher message
#if MDNS_DEBUGMSGS
#endif
// Process the message
{
else
}
return result;
}
#endif // USES_NETLINK
// Called when data appears on interface change notification socket
{
mDNSu32 changedInterfaces = 0;
struct timeval zeroTimeout = { 0, 0 };
do
{
}
while ( 0 < select( pChgRec->NotifySD + 1, &readFDs, (fd_set*) NULL, (fd_set*) NULL, &zeroTimeout));
// Currently we rebuild the entire interface list whenever any interface change is
// detected. If this ever proves to be a performance issue in a multi-homed
// configuration, more care should be paid to changedInterfaces.
if ( changedInterfaces)
}
// Register with either a Routing Socket or RtNetLink to listen for interface changes.
{
return mStatus_NoMemoryErr;
if ( err == 0)
return err;
}
// Test to see if we're the first client running on UDP port 5353, by trying to bind to 5353 without using SO_REUSEPORT.
// If we fail, someone else got here first. That's not a big problem; we can share the port for multicast responses --
// we just need to be aware that we shouldn't expect to successfully receive unicast UDP responses.
{
int err;
struct sockaddr_in s5353;
close(s);
else debugf("Unicast UDP responses okay");
return(err == 0);
}
// mDNS core calls this routine to initialise the platform-specific data.
{
int err = 0;
// Tell mDNS core the names of this machine.
// Set up the nice label
m->nicelabel.c[0] = 0;
// Set up the RFC 1034-compliant label
m->hostlabel.c[0] = 0;
mDNS_SetFQDN(m);
m->p->unicastSocket4 = -1;
#if HAVE_IPV6
m->p->unicastSocket6 = -1;
#endif
// Tell mDNS core about the network interfaces on this machine.
// Tell mDNS core about DNS Servers
if (err == mStatus_NoError)
{
err = WatchForInterfaceChange(m);
// Failure to observe interface changes is non-fatal.
if ( err != mStatus_NoError)
{
}
}
// We don't do asynchronous initialization on the Posix platform, so by the time
// we get here the setup will already have succeeded or failed. If it succeeded,
// we should just call mDNSCoreInitComplete() immediately.
if (err == mStatus_NoError)
return PosixErrorToStatus(err);
}
// mDNS core calls this routine to clean up the platform-specific data.
// In our case all we need to do is to tear down every network interface.
{
#if HAVE_IPV6
#endif
}
{
int err;
err = SetupInterfaceList(m);
return PosixErrorToStatus(err);
}
#endif
// On the Posix platform, locking is a no-op because we only ever enter
// mDNS core on the main thread.
// mDNS core calls this routine when it wants to prevent
// the platform from reentering mDNS core code.
{
(void) m; // Unused
}
// mDNS core calls this routine when it release the lock taken by
// mDNSPlatformLock and allow the platform to reenter mDNS core code.
{
(void) m; // Unused
}
#endif
// mDNS core calls this routine to copy C strings.
// On the Posix platform this maps directly to the ANSI C strcpy.
{
}
// mDNS core calls this routine to get the length of a C string.
// On the Posix platform this maps directly to the ANSI C strlen.
{
}
// mDNS core calls this routine to copy memory.
// On the Posix platform this maps directly to the ANSI C memcpy.
{
}
// mDNS core calls this routine to test whether blocks of memory are byte-for-byte
// identical. On the Posix platform this is a simple wrapper around ANSI C memcmp.
{
}
// mDNS core calls this routine to clear blocks of memory.
// On the Posix platform this is a simple wrapper around ANSI C memset.
{
}
{
}
{
// No special setup is required on Posix -- we just use gettimeofday();
// This is not really safe, because gettimeofday can go backwards if the user manually changes the date or time
// We should find a better way to do this
return(mStatus_NoError);
}
{
// tv.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
// tv.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
// We use the lower 22 bits of tv.tv_sec for the top 22 bits of our result
// 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.
// This gives us a proper modular (cyclic) counter that has a resolution of roughly 1ms (actually 1/1024 second)
// and correctly cycles every 2^22 seconds (4194304 seconds = approx 48 days).
}
{
}
{
}
{
// 1. Call mDNS_Execute() to let mDNSCore do what it needs to do
// 2. Build our list of active file descriptors
#if HAVE_IPV6
#endif
while (info)
{
#if HAVE_IPV6
#endif
}
// 3. Calculate the time remaining to the next scheduled event (in struct timeval format)
// 4. If client's proposed timeout is more than what we want, then reduce it
}
{
{
}
#if HAVE_IPV6
{
}
#endif
while (info)
{
{
}
#if HAVE_IPV6
{
}
#endif
}
}
// update gMaxFD
mDNSlocal void DetermineMaxEventFD( void )
{
gMaxFD = 0;
}
// Add a file descriptor to the set that mDNSPosixRunEventLoopOnce() listens to.
{
if ( gEventSources.LinkOffset == 0)
return mStatus_UnsupportedErr;
return mStatus_BadParamErr;
return mStatus_NoMemoryErr;
return mStatus_NoError;
}
// Remove a file descriptor from the set that mDNSPosixRunEventLoopOnce() listens to.
{
{
{
return mStatus_NoError;
}
}
return mStatus_NoSuchNameErr;
}
// Simply note the received signal in gEventSignals.
{
}
// Tell the event package to listen for signal and report it in mDNSPosixRunEventLoopOnce().
{
return err;
}
// Tell the event package to stop listening for signal in mDNSPosixRunEventLoopOnce().
{
return err;
}
// Do a single pass through the attendent event sources and dispatch any found to their callbacks.
// Return as soon as internal timeout expires, or a signal we're listening for is received.
{
// Include the sockets that are listening to the wire in our select() set
// If any data appeared, invoke its callback
if ( numReady > 0)
{
{
{
break; // in case callback removed elements from gEventSources
}
}
}
else
return mStatus_NoError;
}