]> git.saurik.com Git - apple/mdnsresponder.git/commitdiff
mDNSResponder-22.tar.gz mac-os-x-1021 mac-os-x-1022 mac-os-x-1023 v22
authorApple <opensource@apple.com>
Fri, 13 Sep 2002 19:11:51 +0000 (19:11 +0000)
committerApple <opensource@apple.com>
Fri, 13 Sep 2002 19:11:51 +0000 (19:11 +0000)
15 files changed:
CFSocket.c [new file with mode: 0644]
DNSServiceDiscoveryDefines.h [new file with mode: 0644]
DNSServiceDiscoveryReply.defs [new file with mode: 0644]
DNSServiceDiscoveryRequest.defs [new file with mode: 0644]
SamplemDNSClient.c [new file with mode: 0644]
daemon.c [new file with mode: 0644]
mDNSCore/mDNS.c [new file with mode: 0755]
mDNSCore/mDNSClientAPI.h [new file with mode: 0755]
mDNSCore/mDNSDebug.h [new file with mode: 0755]
mDNSCore/mDNSPlatformEnvironment.h [new file with mode: 0755]
mDNSCore/mDNSPlatformFunctions.h [new file with mode: 0755]
mDNSCore/mDNSsprintf.c [new file with mode: 0755]
mDNSCore/mDNSsprintf.h [new file with mode: 0755]
mDNSCore/mDNSvsprintf.h [new file with mode: 0755]
mDNSResponder.pbproj/project.pbxproj [new file with mode: 0644]

diff --git a/CFSocket.c b/CFSocket.c
new file mode 100644 (file)
index 0000000..12b463a
--- /dev/null
@@ -0,0 +1,845 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in
+ * and are subject to the Apple Public Source License Version 1.1
+ * (the "License").  You may not use this file except in compliance
+ * with the License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+
+// ***************************************************************************
+// mDNS-CFSocket.c:
+// Supporting routines to run mDNS on a CFRunLoop platform
+// ***************************************************************************
+
+// Open Transport 2.7.x on Mac OS 9 used to send Multicast DNS queries to UDP port 53,
+// before the Multicast DNS port was changed to 5353. For this reason, the mDNSResponder
+// in earlier versions of Mac OS X 10.2 Jaguar used to set mDNS_AllowPort53 to 1 to allow
+// it to also listen and answer queries on UDP port 53. Now that Transport 2.8 (included in
+// the Classic subsystem of Mac OS X 10.2 Jaguar) has been corrected to issue Multicast DNS
+// queries on UDP port 5353, this backwards-compatibility legacy support is no longer needed.
+#define mDNS_AllowPort53 1
+
+// Normally mDNSResponder is advertising local services on all active interfaces.
+// However, should you wish to build a query-only mDNS client, setting mDNS_AdvertiseLocalAddresses
+// to zero will cause CFSocket.c to not set the Advertise flag in its mDNS_RegisterInterface calls.
+int mDNS_AdvertiseLocalAddresses = 1;
+
+#include "mDNSClientAPI.h"           // Defines the interface provided to the client layer above
+#include "mDNSPlatformFunctions.h"   // Defines the interface to the supporting layer below
+#include "mDNSPlatformEnvironment.h" // Defines the specific types needed to run mDNS on this platform
+#include "mDNSvsprintf.h"            // Used to implement debugf_();
+
+#include <stdio.h>
+#include <stdarg.h>                  // For va_list support
+#include <net/if.h>
+#include <net/if_dl.h>
+#include <sys/uio.h>
+#include <sys/param.h>
+#include <sys/socket.h>
+
+// Code contributed by Dave Heller:
+// Define RUN_ON_PUMA_WITHOUT_IFADDRS to compile code that will
+// work on Mac OS X 10.1, which does not have the getifaddrs call.
+#define RUN_ON_PUMA_WITHOUT_IFADDRS 0
+
+#if RUN_ON_PUMA_WITHOUT_IFADDRS
+
+#include <sys/ioctl.h>
+#include <sys/sockio.h>
+#define ifaddrs ifa_info
+#ifndef        ifa_broadaddr
+#define        ifa_broadaddr   ifa_dstaddr     /* broadcast address interface */
+#endif
+#include <sys/cdefs.h>
+
+#else
+
+#include <ifaddrs.h>
+
+#endif
+
+#include <IOKit/IOKitLib.h>
+#include <IOKit/IOMessage.h>
+
+// ***************************************************************************
+// Structures
+
+typedef struct NetworkInterfaceInfo2_struct NetworkInterfaceInfo2;
+struct NetworkInterfaceInfo2_struct
+       {
+       NetworkInterfaceInfo ifinfo;
+       mDNS *m;
+       char *ifa_name;
+       NetworkInterfaceInfo2 *alias;
+       int socket;
+       CFSocketRef cfsocket;
+#if mDNS_AllowPort53
+       int socket53;
+       CFSocketRef cfsocket53;
+#endif
+       };
+
+// ***************************************************************************
+// Functions
+
+mDNSexport void debugf_(const char *format, ...)
+       {
+       unsigned char buffer[512];
+       va_list ptr;
+       va_start(ptr,format);
+       buffer[mDNS_vsprintf((char *)buffer, format, ptr)] = 0;
+       va_end(ptr);
+       fprintf(stderr, "%s\n", buffer);
+       fflush(stderr);
+       }
+
+mDNSexport mStatus mDNSPlatformSendUDP(const mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
+       mDNSIPAddr src, mDNSIPPort srcport, mDNSIPAddr dst, mDNSIPPort dstport)
+       {
+       NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2 *)(m->HostInterfaces);
+       struct sockaddr_in to;
+       to.sin_family      = AF_INET;
+       to.sin_port        = dstport.NotAnInteger;
+       to.sin_addr.s_addr = dst.    NotAnInteger;
+
+       if (src.NotAnInteger == 0) debugf("mDNSPlatformSendUDP ERROR! Cannot send from zero source address");
+
+       while (info)
+               {
+               if (info->ifinfo.ip.NotAnInteger == src.NotAnInteger)
+                       {
+                       int s, err;
+                       if      (srcport.NotAnInteger == MulticastDNSPort.NotAnInteger) s = info->socket;
+#if mDNS_AllowPort53
+                       else if (srcport.NotAnInteger == UnicastDNSPort.NotAnInteger  ) s = info->socket53;
+#endif
+                       else { debugf("Source port %d not allowed", (mDNSu16)srcport.b[0]<<8 | srcport.b[1]); return(-1); }
+                       err = sendto(s, msg, (UInt8*)end - (UInt8*)msg, 0, (struct sockaddr *)&to, sizeof(to));
+                       if (err < 0) { perror("mDNSPlatformSendUDP sendto"); return(err); }
+                       }
+               info = (NetworkInterfaceInfo2 *)(info->ifinfo.next);
+               }
+
+       return(mStatus_NoError);
+       }
+
+static ssize_t myrecvfrom(const int s, void *const buffer, const size_t max,
+       struct sockaddr *const from, size_t *const fromlen, struct in_addr *dstaddr, char ifname[128])
+       {
+       struct iovec databuffers = { (char *)buffer, max };
+       struct msghdr   msg;
+       ssize_t         n;
+       struct cmsghdr *cmPtr;
+       char            ancillary[1024];
+
+       // Set up the message
+       msg.msg_name       = (caddr_t)from;
+       msg.msg_namelen    = *fromlen;
+       msg.msg_iov        = &databuffers;
+       msg.msg_iovlen     = 1;
+       msg.msg_control    = (caddr_t)&ancillary;
+       msg.msg_controllen = sizeof(ancillary);
+       msg.msg_flags      = 0;
+       
+       // Receive the data
+       n = recvmsg(s, &msg, 0);
+       if (n<0 || msg.msg_controllen < sizeof(struct cmsghdr) || (msg.msg_flags & MSG_CTRUNC))
+               { perror("recvmsg"); return(n); }
+       
+       *fromlen = msg.msg_namelen;
+       
+       // Parse each option out of the ancillary data.
+       for (cmPtr = CMSG_FIRSTHDR(&msg); cmPtr; cmPtr = CMSG_NXTHDR(&msg, cmPtr))
+               {
+               // debugf("myrecvfrom cmsg_level %d cmsg_type %d", cmPtr->cmsg_level, cmPtr->cmsg_type);
+               if (cmPtr->cmsg_level == IPPROTO_IP && cmPtr->cmsg_type == IP_RECVDSTADDR)
+                       *dstaddr = *(struct in_addr *)CMSG_DATA(cmPtr);
+               if (cmPtr->cmsg_level == IPPROTO_IP && cmPtr->cmsg_type == IP_RECVIF)
+                       {
+                       struct sockaddr_dl *sdl = (struct sockaddr_dl *)CMSG_DATA(cmPtr);
+                       if (sdl->sdl_nlen < sizeof(ifname))
+                               {
+                               mDNSPlatformMemCopy(sdl->sdl_data, ifname, sdl->sdl_nlen);
+                               ifname[sdl->sdl_nlen] = 0;
+                               // debugf("IP_RECVIF sdl_index %d, sdl_data %s len %d", sdl->sdl_index, ifname, sdl->sdl_nlen);
+                               }
+                       }
+               }
+
+       return(n);
+       }
+
+mDNSlocal void myCFSocketCallBack(CFSocketRef s, CFSocketCallBackType type, CFDataRef address, const void *data, void *context)
+       {
+       mDNSIPAddr senderaddr, destaddr;
+       mDNSIPPort senderport;
+       NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2 *)context;
+       mDNS *const m = info->m;
+       DNSMessage packet;
+       struct in_addr to;
+       struct sockaddr_in from;
+       size_t fromlen = sizeof(from);
+       char packetifname[128] = "";
+       int err;
+       
+       (void)address;  // Parameter not used
+       (void)data;             // Parameter not used
+       
+       if (type != kCFSocketReadCallBack) debugf("myCFSocketCallBack: Why is type not kCFSocketReadCallBack?");
+#if mDNS_AllowPort53
+       if (s == info->cfsocket53)
+               err = myrecvfrom(info->socket53, &packet, sizeof(packet), (struct sockaddr *)&from, &fromlen, &to, packetifname);
+       else
+#endif
+       err = myrecvfrom(info->socket, &packet, sizeof(packet), (struct sockaddr *)&from, &fromlen, &to, packetifname);
+
+       if (err < 0) { debugf("myCFSocketCallBack recvfrom error %d", err); return; }
+
+       senderaddr.NotAnInteger = from.sin_addr.s_addr;
+       senderport.NotAnInteger = from.sin_port;
+       destaddr.NotAnInteger   = to.s_addr;
+
+       // Even though we indicated a specific interface in the IP_ADD_MEMBERSHIP call, a weirdness of the
+       // sockets API means that even though this socket has only officially joined the multicast group
+       // on one specific interface, the kernel will still deliver multicast packets to it no matter which
+       // interface they arrive on. According to the official Unix Powers That Be, this is Not A Bug.
+       // To work around this weirdness, we use the IP_RECVIF option to find the name of the interface
+       // on which the packet arrived, and ignore the packet if it really arrived on some other interface.
+       if (strcmp(info->ifa_name, packetifname))
+               {
+               verbosedebugf("myCFSocketCallBack got a packet from %.4a to %.4a on interface %.4a/%s (Ignored -- really arrived on interface %s)",
+                       &senderaddr, &destaddr, &info->ifinfo.ip, info->ifa_name, packetifname);
+               return;
+               }
+       else
+               verbosedebugf("myCFSocketCallBack got a packet from %.4a to %.4a on interface %.4a/%s",
+                       &senderaddr, &destaddr, &info->ifinfo.ip, info->ifa_name);
+
+       if (err < sizeof(DNSMessageHeader)) { debugf("myCFSocketCallBack packet length (%d) too short", err); return; }
+       
+#if mDNS_AllowPort53
+       if (s == info->cfsocket53)
+               mDNSCoreReceive(m, &packet, (unsigned char*)&packet + err, senderaddr, senderport, destaddr, UnicastDNSPort, info->ifinfo.ip);
+       else
+#endif
+       mDNSCoreReceive(m, &packet, (unsigned char*)&packet + err, senderaddr, senderport, destaddr, MulticastDNSPort, info->ifinfo.ip);
+       }
+
+mDNSlocal void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
+       {
+       (void)timer;    // Parameter not used
+       mDNSCoreTask((mDNS *const)info);
+       }
+
+// This gets the text of the field currently labelled "Computer Name" in the Sharing Prefs Control Panel
+mDNSlocal void GetUserSpecifiedFriendlyComputerName(domainlabel *const namelabel)
+       {
+       CFStringEncoding encoding = kCFStringEncodingUTF8;
+       CFStringRef cfs = SCDynamicStoreCopyComputerName(NULL, &encoding);
+       if (cfs)
+               {
+               CFStringGetPascalString(cfs, namelabel->c, sizeof(*namelabel), kCFStringEncodingUTF8);
+               CFRelease(cfs);
+               }
+       }
+
+// This gets the text of the field currently labelled "Rendezvous Name" in the Sharing Prefs Control Panel
+mDNSlocal void GetUserSpecifiedRFC1034ComputerName(domainlabel *const namelabel)
+       {
+       CFStringRef cfs = SCDynamicStoreCopyLocalHostName(NULL);
+       if (cfs)
+               {
+               CFStringGetPascalString(cfs, namelabel->c, sizeof(*namelabel), kCFStringEncodingUTF8);
+               CFRelease(cfs);
+               }
+       }
+
+mDNSlocal mStatus SetupSocket(struct sockaddr_in *ifa_addr, mDNSIPPort port, int *s, CFSocketRef *c, CFSocketContext *context)
+       {
+       mStatus err;
+       const int on = 1;
+       const int twofivefive = 255;
+       struct ip_mreq imr;
+       struct sockaddr_in listening_sockaddr;
+       CFRunLoopSourceRef rls;
+       
+       // Open the socket...
+       *s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
+       *c = NULL;
+       if (*s < 0) { perror("socket"); return(*s); }
+       
+       // ... with a shared UDP port
+       err = setsockopt(*s, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
+       if (err < 0) { perror("setsockopt - SO_REUSEPORT"); return(err); }
+
+       // We want to receive destination addresses
+       err = setsockopt(*s, IPPROTO_IP, IP_RECVDSTADDR, &on, sizeof(on));
+       if (err < 0) { perror("setsockopt - IP_RECVDSTADDR"); return(err); }
+       
+       // We want to receive interface identifiers
+       err = setsockopt(*s, IPPROTO_IP, IP_RECVIF, &on, sizeof(on));
+       if (err < 0) { perror("setsockopt - IP_RECVIF"); return(err); }
+       
+       // Add multicast group membership on this interface
+       imr.imr_multiaddr.s_addr = AllDNSLinkGroup.NotAnInteger;
+       imr.imr_interface        = ifa_addr->sin_addr;
+       err = setsockopt(*s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(struct ip_mreq));      
+       if (err < 0) { perror("setsockopt - IP_ADD_MEMBERSHIP"); return(err); }
+
+       // Specify outgoing interface too
+       err = setsockopt(*s, IPPROTO_IP, IP_MULTICAST_IF, &ifa_addr->sin_addr, sizeof(ifa_addr->sin_addr));
+       if (err < 0) { perror("setsockopt - IP_MULTICAST_IF"); return(err); }
+
+       // Send unicast packets with TTL 255
+       err = setsockopt(*s, IPPROTO_IP, IP_TTL, &twofivefive, sizeof(twofivefive));
+       if (err < 0) { perror("setsockopt - IP_TTL"); return(err); }
+
+       // And multicast packets with TTL 255 too
+       err = setsockopt(*s, IPPROTO_IP, IP_MULTICAST_TTL, &twofivefive, sizeof(twofivefive));
+       if (err < 0) { perror("setsockopt - IP_MULTICAST_TTL"); return(err); }
+
+       // And start listening for packets
+       listening_sockaddr.sin_family      = AF_INET;
+       listening_sockaddr.sin_port        = port.NotAnInteger;
+       listening_sockaddr.sin_addr.s_addr = 0; // Want to receive multicasts AND unicasts on this socket
+       err = bind(*s, (struct sockaddr *) &listening_sockaddr, sizeof(listening_sockaddr));
+       if (err)
+               {
+               if (port.NotAnInteger == UnicastDNSPort.NotAnInteger) err = 0;
+               else perror("bind");
+               return(err);
+               }
+
+       *c = CFSocketCreateWithNative(kCFAllocatorDefault, *s, kCFSocketReadCallBack, myCFSocketCallBack, context);
+       rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, *c, 0);
+       CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
+       CFRelease(rls);
+       
+       return(err);
+       }
+
+#if 0
+mDNSlocal NetworkInterfaceInfo2 *SearchForInterfaceByAddr(mDNS *const m, mDNSIPAddr ip)
+       {
+       NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2*)(m->HostInterfaces);
+       while (info)
+               {
+               if (info->ifinfo.ip.NotAnInteger == ip.NotAnInteger) return(info);
+               info = (NetworkInterfaceInfo2 *)(info->ifinfo.next);
+               }
+       return(NULL);
+       }
+#endif
+
+mDNSlocal NetworkInterfaceInfo2 *SearchForInterfaceByName(mDNS *const m, char *ifname)
+       {
+       NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2*)(m->HostInterfaces);
+       while (info)
+               {
+               if (!strcmp(info->ifa_name, ifname)) return(info);
+               info = (NetworkInterfaceInfo2 *)(info->ifinfo.next);
+               }
+       return(NULL);
+       }
+
+#if RUN_ON_PUMA_WITHOUT_IFADDRS
+
+/* Our own header for the programs that need interface configuration info.
+   Include this file, instead of "unp.h". */
+
+#define        IFA_NAME        16                      /* same as IFNAMSIZ in <net/if.h> */
+#define        IFA_HADDR        8                      /* allow for 64-bit EUI-64 in future */
+
+struct ifa_info {
+  char    ifa_name[IFA_NAME];  /* interface name, null terminated */
+  u_char  ifa_haddr[IFA_HADDR];        /* hardware address */
+  u_short ifa_hlen;                            /* #bytes in hardware address: 0, 6, 8 */
+  short   ifa_flags;                   /* IFF_xxx constants from <net/if.h> */
+  short   ifa_myflags;                 /* our own IFI_xxx flags */
+  struct sockaddr  *ifa_addr;  /* primary address */
+  struct sockaddr  *ifa_brdaddr;/* broadcast address */
+  struct sockaddr  *ifa_dstaddr;/* destination address */
+  struct ifa_info  *ifa_next;  /* next of these structures */
+};
+
+#define        IFI_ALIAS       1                       /* ifa_addr is an alias */
+
+                                       /* function prototypes */
+struct ifa_info        *get_ifa_info(int, int);
+struct ifa_info        *Get_ifa_info(int, int);
+void                    free_ifa_info(struct ifa_info *);
+
+#define HAVE_SOCKADDR_SA_LEN   1
+
+struct ifa_info *
+get_ifa_info(int family, int doaliases)
+{
+       struct ifa_info         *ifi, *ifihead, **ifipnext;
+       int                                     sockfd, len, lastlen, flags, myflags;
+       char                            *ptr, *buf, lastname[IFNAMSIZ], *cptr;
+       struct ifconf           ifc;
+       struct ifreq            *ifr, ifrcopy;
+       struct sockaddr_in      *sinptr;
+
+       sockfd = socket(AF_INET, SOCK_DGRAM, 0);
+
+       lastlen = 0;
+       len = 100 * sizeof(struct ifreq);       /* initial buffer size guess */
+       for ( ; ; ) {
+               buf = (char *) malloc(len);
+               ifc.ifc_len = len;
+               ifc.ifc_buf = buf;
+               if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
+                       if (errno != EINVAL || lastlen != 0)
+                               debugf("ioctl error");
+               } else {
+                       if (ifc.ifc_len == lastlen)
+                               break;          /* success, len has not changed */
+                       lastlen = ifc.ifc_len;
+               }
+               len += 10 * sizeof(struct ifreq);       /* increment */
+               free(buf);
+       }
+       ifihead = NULL;
+       ifipnext = &ifihead;
+       lastname[0] = 0;
+/* end get_ifa_info1 */
+
+/* include get_ifa_info2 */
+       for (ptr = buf; ptr < buf + ifc.ifc_len; ) {
+               ifr = (struct ifreq *) ptr;
+
+#ifdef HAVE_SOCKADDR_SA_LEN
+               len = MAX(sizeof(struct sockaddr), ifr->ifr_addr.sa_len);
+#else
+               switch (ifr->ifr_addr.sa_family) {
+#ifdef IPV6
+               case AF_INET6:  
+                       len = sizeof(struct sockaddr_in6);
+                       break;
+#endif
+               case AF_INET:   
+               default:        
+                       len = sizeof(struct sockaddr);
+                       break;
+               }
+#endif /* HAVE_SOCKADDR_SA_LEN */
+               ptr += sizeof(ifr->ifr_name) + len;     /* for next one in buffer */
+
+               if (ifr->ifr_addr.sa_family != family)
+                       continue;       /* ignore if not desired address family */
+
+               myflags = 0;
+               if ( (cptr = strchr(ifr->ifr_name, ':')) != NULL)
+                       *cptr = 0;              /* replace colon will null */
+               if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) {
+                       if (doaliases == 0)
+                               continue;       /* already processed this interface */
+                       myflags = IFI_ALIAS;
+               }
+               memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
+
+               ifrcopy = *ifr;
+               ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
+               flags = ifrcopy.ifr_flags;
+               if ((flags & IFF_UP) == 0)
+                       continue;       /* ignore if interface not up */
+
+               ifi = (struct ifa_info *) calloc(1, sizeof(struct ifa_info));
+               *ifipnext = ifi;                        /* prev points to this new one */
+               ifipnext = &ifi->ifa_next;      /* pointer to next one goes here */
+
+               ifi->ifa_flags = flags;         /* IFF_xxx values */
+               ifi->ifa_myflags = myflags;     /* IFI_xxx values */
+               memcpy(ifi->ifa_name, ifr->ifr_name, IFA_NAME);
+               ifi->ifa_name[IFA_NAME-1] = '\0';
+/* end get_ifa_info2 */
+/* include get_ifa_info3 */
+               switch (ifr->ifr_addr.sa_family) {
+               case AF_INET:
+                       sinptr = (struct sockaddr_in *) &ifr->ifr_addr;
+                       if (ifi->ifa_addr == NULL) {
+                               ifi->ifa_addr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr_in));
+                               memcpy(ifi->ifa_addr, sinptr, sizeof(struct sockaddr_in));
+
+#ifdef SIOCGIFBRDADDR
+                               if (flags & IFF_BROADCAST) {
+                                       ioctl(sockfd, SIOCGIFBRDADDR, &ifrcopy);
+                                       sinptr = (struct sockaddr_in *) &ifrcopy.ifr_broadaddr;
+                                       ifi->ifa_brdaddr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr_in));
+                                       memcpy(ifi->ifa_brdaddr, sinptr, sizeof(struct sockaddr_in));
+                               }
+#endif
+
+#ifdef SIOCGIFDSTADDR
+                               if (flags & IFF_POINTOPOINT) {
+                                       ioctl(sockfd, SIOCGIFDSTADDR, &ifrcopy);
+                                       sinptr = (struct sockaddr_in *) &ifrcopy.ifr_dstaddr;
+                                       ifi->ifa_dstaddr = (struct sockaddr *) calloc(1, sizeof(struct sockaddr_in));
+                                       memcpy(ifi->ifa_dstaddr, sinptr, sizeof(struct sockaddr_in));
+                               }
+#endif
+                       }
+                       break;
+
+               default:
+                       break;
+               }
+       }
+       free(buf);
+       return(ifihead);        /* pointer to first structure in linked list */
+}
+/* end get_ifa_info3 */
+
+/* include free_ifa_info */
+mDNSlocal void freeifaddrs(struct ifa_info *ifihead)
+{
+       struct ifa_info *ifi, *ifinext;
+
+       for (ifi = ifihead; ifi != NULL; ifi = ifinext) {
+               if (ifi->ifa_addr != NULL)
+                       free(ifi->ifa_addr);
+               if (ifi->ifa_brdaddr != NULL)
+                       free(ifi->ifa_brdaddr);
+               if (ifi->ifa_dstaddr != NULL)
+                       free(ifi->ifa_dstaddr);
+               ifinext = ifi->ifa_next;        /* can't fetch ifa_next after free() */
+               free(ifi);                                      /* the ifa_info{} itself */
+       }
+}
+/* end free_ifa_info */
+
+struct ifa_info *
+Get_ifa_info(int family, int doaliases)
+{
+       struct ifa_info *ifi;
+
+       if ( (ifi = get_ifa_info(family, doaliases)) == NULL)
+               debugf("get_ifa_info error");
+       return(ifi);
+}
+
+mDNSlocal int getifaddrs(struct ifa_info **ifalist)
+       {
+       *ifalist = get_ifa_info(PF_INET, false);
+       if( ifalist == nil )
+               return -1;
+       else
+               return(0);
+       }
+
+#endif
+
+mDNSlocal mStatus SetupInterface(mDNS *const m, NetworkInterfaceInfo2 *info, struct ifaddrs *ifa)
+       {
+       mStatus err = 0;
+       struct sockaddr_in *ifa_addr = (struct sockaddr_in *)ifa->ifa_addr;
+       CFSocketContext myCFSocketContext = { 0, info, NULL, NULL, NULL };
+
+       info->ifinfo.ip.NotAnInteger = ifa_addr->sin_addr.s_addr;
+       info->ifinfo.Advertise       = mDNS_AdvertiseLocalAddresses;
+       info->m         = m;
+       info->ifa_name  = (char *)mallocL("NetworkInterfaceInfo2 name", strlen(ifa->ifa_name) + 1);
+       if (!info->ifa_name) return(-1);
+       strcpy(info->ifa_name, ifa->ifa_name);
+       info->alias     = SearchForInterfaceByName(m, ifa->ifa_name);
+       info->socket    = 0;
+       info->cfsocket  = 0;
+#if mDNS_AllowPort53
+       info->socket53   = 0;
+       info->cfsocket53 = 0;
+#endif
+
+       mDNS_RegisterInterface(m, &info->ifinfo);
+
+       if (info->alias)
+               debugf("SetupInterface: %s Flags %04X %.4a is an alias of %.4a",
+                       ifa->ifa_name, ifa->ifa_flags, &info->ifinfo.ip, &info->alias->ifinfo.ip);
+
+#if mDNS_AllowPort53
+       err = SetupSocket(ifa_addr, UnicastDNSPort,   &info->socket53, &info->cfsocket53, &myCFSocketContext);
+#endif
+       if (!err)
+               err = SetupSocket(ifa_addr, MulticastDNSPort, &info->socket, &info->cfsocket, &myCFSocketContext);
+
+       debugf("SetupInterface: %s Flags %04X %.4a Registered",
+               ifa->ifa_name, ifa->ifa_flags, &info->ifinfo.ip);
+
+       return(err);
+       }
+
+mDNSlocal void ClearInterfaceList(mDNS *const m)
+       {
+       while (m->HostInterfaces)
+               {
+               NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2*)(m->HostInterfaces);
+               mDNS_DeregisterInterface(m, &info->ifinfo);
+               if (info->ifa_name  ) freeL("NetworkInterfaceInfo2 name", info->ifa_name);
+               if (info->socket > 0) shutdown(info->socket, 2);
+               if (info->cfsocket) { CFSocketInvalidate(info->cfsocket); CFRelease(info->cfsocket); }
+#if mDNS_AllowPort53
+               if (info->socket53 > 0) shutdown(info->socket53, 2);
+               if (info->cfsocket53) { CFSocketInvalidate(info->cfsocket53); CFRelease(info->cfsocket53); }
+#endif
+               freeL("NetworkInterfaceInfo2", info);
+               }
+       }
+
+mDNSlocal mStatus SetupInterfaceList(mDNS *const m)
+       {
+       struct ifaddrs *ifalist;
+       int err = getifaddrs(&ifalist);
+       struct ifaddrs *ifa = ifalist;
+       struct ifaddrs *theLoopback = NULL;
+       if (err) return(err);
+
+       // Set up the nice label
+       m->nicelabel.c[0] = 0;
+       GetUserSpecifiedFriendlyComputerName(&m->nicelabel);
+       if (m->nicelabel.c[0] == 0) ConvertCStringToDomainLabel("Macintosh", &m->nicelabel);
+
+       // Set up the RFC 1034-compliant label
+       m->hostlabel.c[0] = 0;
+       GetUserSpecifiedRFC1034ComputerName(&m->hostlabel);
+       if (m->hostlabel.c[0] == 0) ConvertCStringToDomainLabel("Macintosh", &m->hostlabel);
+
+       mDNS_GenerateFQDN(m);
+
+       while (ifa)
+               {
+#if 0
+               if (ifa->ifa_addr->sa_family != AF_INET)
+                       debugf("SetupInterface: %s Flags %04X Family %d not AF_INET",
+                               ifa->ifa_name, ifa->ifa_flags, ifa->ifa_addr->sa_family);
+               if (!(ifa->ifa_flags & IFF_UP))
+                       debugf("SetupInterface: %s Flags %04X Interface not IFF_UP", ifa->ifa_name, ifa->ifa_flags);
+               if (ifa->ifa_flags & IFF_LOOPBACK)
+                       debugf("SetupInterface: %s Flags %04X Interface IFF_LOOPBACK", ifa->ifa_name, ifa->ifa_flags);
+               if (ifa->ifa_flags & IFF_POINTOPOINT)
+                       debugf("SetupInterface: %s Flags %04X Interface IFF_POINTOPOINT", ifa->ifa_name, ifa->ifa_flags);
+#endif
+               if (ifa->ifa_addr->sa_family == AF_INET && (ifa->ifa_flags & IFF_UP) &&
+                       !(ifa->ifa_flags & IFF_POINTOPOINT))
+                       {
+                       if (ifa->ifa_flags & IFF_LOOPBACK)
+                               theLoopback = ifa;
+                       else
+                               {
+                               NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2 *)mallocL("NetworkInterfaceInfo2", sizeof(*info));
+                               if (!info) debugf("SetupInterfaceList: Out of Memory!");
+                               else SetupInterface(m, info, ifa);
+                               }
+                       }
+               ifa = ifa->ifa_next;
+               }
+
+       if (!m->HostInterfaces && theLoopback)
+               {
+               NetworkInterfaceInfo2 *info = (NetworkInterfaceInfo2 *)mallocL("NetworkInterfaceInfo2", sizeof(*info));
+               if (!info) debugf("SetupInterfaceList: (theLoopback) Out of Memory!");
+               else SetupInterface(m, info, theLoopback);
+               }
+
+       freeifaddrs(ifalist);
+       return(err);
+       }
+
+mDNSlocal void NetworkChanged(SCDynamicStoreRef store, CFArrayRef changedKeys, void *context)
+       {
+       mDNS *const m = (mDNS *const)context;
+       debugf("***   Network Configuration Change   ***");
+       (void)store;            // Parameter not used
+       (void)changedKeys;      // Parameter not used
+       ClearInterfaceList(m);
+       SetupInterfaceList(m);
+       mDNSCoreSleep(m, false);
+       }
+
+mDNSlocal mStatus WatchForNetworkChanges(mDNS *const m)
+       {
+       mStatus err = -1;
+       SCDynamicStoreContext context = { 0, m, NULL, NULL, NULL };
+       SCDynamicStoreRef     store    = SCDynamicStoreCreate(NULL, CFSTR("mDNSResponder"), NetworkChanged, &context);
+       CFStringRef           key1     = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetIPv4);
+       CFStringRef           key2     = SCDynamicStoreKeyCreateComputerName(NULL);
+       CFStringRef           key3     = SCDynamicStoreKeyCreateHostNames(NULL);
+       CFStringRef           pattern  = SCDynamicStoreKeyCreateNetworkServiceEntity(NULL, kSCDynamicStoreDomainState, kSCCompAnyRegex, kSCEntNetIPv4);
+       CFMutableArrayRef     keys     = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
+       CFMutableArrayRef     patterns = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
+
+       if (!store) { fprintf(stderr, "SCDynamicStoreCreate failed: %s\n", SCErrorString(SCError())); goto error; }
+       if (!key1 || !key2 || !key3 || !keys || !pattern || !patterns) goto error;
+
+       CFArrayAppendValue(keys, key1);
+       CFArrayAppendValue(keys, key2);
+       CFArrayAppendValue(keys, key3);
+       CFArrayAppendValue(patterns, pattern);
+       if (!SCDynamicStoreSetNotificationKeys(store, keys, patterns))
+               { fprintf(stderr, "SCDynamicStoreSetNotificationKeys failed: %s\n", SCErrorString(SCError())); goto error; }
+
+       m->p->StoreRLS = SCDynamicStoreCreateRunLoopSource(NULL, store, 0);
+       if (!m->p->StoreRLS) { fprintf(stderr, "SCDynamicStoreCreateRunLoopSource failed: %s\n", SCErrorString(SCError())); goto error; }
+
+       CFRunLoopAddSource(CFRunLoopGetCurrent(), m->p->StoreRLS, kCFRunLoopDefaultMode);
+       m->p->Store = store;
+       err = 0;
+       goto exit;
+
+error:
+       if (store)    CFRelease(store);
+
+exit:
+       if (key1)     CFRelease(key1);
+       if (key2)     CFRelease(key2);
+       if (key3)     CFRelease(key3);
+       if (pattern)  CFRelease(pattern);
+       if (keys)     CFRelease(keys);
+       if (patterns) CFRelease(patterns);
+       
+       return(err);
+       }
+
+mDNSlocal void PowerChanged(void *refcon, io_service_t service, natural_t messageType, void *messageArgument)
+       {
+       mDNS *const m = (mDNS *const)refcon;
+       (void)service;          // Parameter not used
+       switch(messageType)
+               {
+               case kIOMessageCanSystemPowerOff:     debugf("PowerChanged kIOMessageCanSystemPowerOff (no action)");               break; // E0000240
+               case kIOMessageSystemWillPowerOff:    debugf("PowerChanged kIOMessageSystemWillPowerOff"); mDNSCoreSleep(m, true);  break; // E0000250
+               case kIOMessageSystemWillNotPowerOff: debugf("PowerChanged kIOMessageSystemWillNotPowerOff (no action)");           break; // E0000260
+               case kIOMessageCanSystemSleep:        debugf("PowerChanged kIOMessageCanSystemSleep (no action)");                  break; // E0000270
+               case kIOMessageSystemWillSleep:       debugf("PowerChanged kIOMessageSystemWillSleep");    mDNSCoreSleep(m, true);  break; // E0000280
+               case kIOMessageSystemWillNotSleep:    debugf("PowerChanged kIOMessageSystemWillNotSleep (no action)");              break; // E0000290
+               case kIOMessageSystemHasPoweredOn:    debugf("PowerChanged kIOMessageSystemHasPoweredOn"); mDNSCoreSleep(m, false); break; // E0000300
+               default:                              debugf("PowerChanged unknown message %X", messageType);                       break;
+               }
+       IOAllowPowerChange(m->p->PowerConnection, (long)messageArgument);
+       }
+
+mDNSlocal mStatus WatchForPowerChanges(mDNS *const m)
+       {
+       IONotificationPortRef thePortRef;
+       m->p->PowerConnection = IORegisterForSystemPower(m, &thePortRef, PowerChanged, &m->p->PowerNotifier);
+       if (m->p->PowerConnection)
+               {
+               m->p->PowerRLS = IONotificationPortGetRunLoopSource(thePortRef);
+               CFRunLoopAddSource(CFRunLoopGetCurrent(), m->p->PowerRLS, kCFRunLoopDefaultMode);
+               return(mStatus_NoError);
+               }
+       return(-1);
+       }
+
+mDNSlocal mStatus mDNSPlatformInit_setup(mDNS *const m)
+       {
+       mStatus err;
+
+       CFRunLoopTimerContext myCFRunLoopTimerContext = { 0, m, NULL, NULL, NULL };
+       
+       // Note: Every CFRunLoopTimer has to be created with an initial fire time, and a repeat interval, or it becomes
+       // a one-shot timer and you can't use CFRunLoopTimerSetNextFireDate(timer, when) to schedule subsequent firings.
+       // Here we create it with an initial fire time ten seconds from now, and a repeat interval of ten seconds,
+       // knowing that we'll reschedule it using CFRunLoopTimerSetNextFireDate(timer, when) long before that happens.
+       m->p->CFTimer = CFRunLoopTimerCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent() + 10.0, 10.0, 0, 1,
+                                                                                       myCFRunLoopTimerCallBack, &myCFRunLoopTimerContext);
+       CFRunLoopAddTimer(CFRunLoopGetCurrent(), m->p->CFTimer, kCFRunLoopDefaultMode);
+
+       SetupInterfaceList(m);
+
+       err = WatchForNetworkChanges(m);
+       if (err) return(err);
+       
+       err = WatchForPowerChanges(m);
+       return(err);
+       }
+
+mDNSexport mStatus mDNSPlatformInit(mDNS *const m)
+       {
+       mStatus result = mDNSPlatformInit_setup(m);
+       // We don't do asynchronous initialization on OS X, so by the time we get here the setup will already
+       // have succeeded or failed -- so if it succeeded, we should just call mDNSCoreInitComplete() immediately
+       if (result == mStatus_NoError) mDNSCoreInitComplete(m, mStatus_NoError);
+       return(result);
+       }
+
+mDNSexport void mDNSPlatformClose(mDNS *const m)
+       {
+       if (m->p->PowerConnection)
+               {
+               CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m->p->PowerRLS, kCFRunLoopDefaultMode);
+               CFRunLoopSourceInvalidate(m->p->PowerRLS);
+               CFRelease(m->p->PowerRLS);
+               IODeregisterForSystemPower(&m->p->PowerNotifier);
+               m->p->PowerConnection = NULL;
+               m->p->PowerNotifier   = NULL;
+               m->p->PowerRLS        = NULL;
+               }
+       
+       if (m->p->Store)
+               {
+               CFRunLoopRemoveSource(CFRunLoopGetCurrent(), m->p->StoreRLS, kCFRunLoopDefaultMode);
+               CFRunLoopSourceInvalidate(m->p->StoreRLS);
+               CFRelease(m->p->StoreRLS);
+               CFRelease(m->p->Store);
+               m->p->Store    = NULL;
+               m->p->StoreRLS = NULL;
+               }
+       
+       ClearInterfaceList(m);
+       
+       if (m->p->CFTimer)
+               {
+               CFRunLoopTimerInvalidate(m->p->CFTimer);
+               CFRelease(m->p->CFTimer);
+               m->p->CFTimer = NULL;
+               }
+       }
+
+// To Do: Find out how to implement a proper modular time function in CF
+mDNSexport void mDNSPlatformScheduleTask(const mDNS *const m, SInt32 NextTaskTime)
+       {
+       if (m->p->CFTimer)
+               {
+               CFAbsoluteTime ticks    = (CFAbsoluteTime)(NextTaskTime - mDNSPlatformTimeNow());
+               CFAbsoluteTime interval = ticks / (CFAbsoluteTime)mDNSPlatformOneSecond;
+               CFRunLoopTimerSetNextFireDate(m->p->CFTimer, CFAbsoluteTimeGetCurrent() + interval);
+               }
+       }
+
+// Locking is a no-op here, because we're CFRunLoop-based, so we can never interrupt ourselves
+mDNSexport void    mDNSPlatformLock   (const mDNS *const m) { (void)m; }
+mDNSexport void    mDNSPlatformUnlock (const mDNS *const m) { (void)m; }
+mDNSexport void    mDNSPlatformStrCopy(const void *src,       void *dst)             { strcpy((char *)dst, (char *)src); }
+mDNSexport UInt32  mDNSPlatformStrLen (const void *src)                              { return(strlen((char*)src)); }
+mDNSexport void    mDNSPlatformMemCopy(const void *src,       void *dst, UInt32 len) { memcpy(dst, src, len); }
+mDNSexport Boolean mDNSPlatformMemSame(const void *src, const void *dst, UInt32 len) { return(memcmp(dst, src, len) == 0); }
+mDNSexport void    mDNSPlatformMemZero(                       void *dst, UInt32 len) { bzero(dst, len); }
+
+mDNSexport SInt32  mDNSPlatformTimeNow()
+       {
+       struct timeval tp;
+       gettimeofday(&tp, NULL);
+       // tp.tv_sec is seconds since 1st January 1970 (GMT, with no adjustment for daylight savings time)
+       // tp.tv_usec is microseconds since the start of this second (i.e. values 0 to 999999)
+       // We use the lower 22 bits of tp.tv_sec for the top 22 bits of our result
+       // and we multiply tp.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).
+       return( (tp.tv_sec << 10) | (tp.tv_usec * 16 / 15625) );
+       }
+
+mDNSexport SInt32  mDNSPlatformOneSecond = 1024;
diff --git a/DNSServiceDiscoveryDefines.h b/DNSServiceDiscoveryDefines.h
new file mode 100644 (file)
index 0000000..1c8e8ea
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+
+#include <DNSServiceDiscovery/DNSServiceDiscoveryDefines.h>
+
diff --git a/DNSServiceDiscoveryReply.defs b/DNSServiceDiscoveryReply.defs
new file mode 100644 (file)
index 0000000..c08e86f
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+ #import "/AppleInternal/Developer/Headers/DNSServiceDiscovery/DNSServiceDiscoveryReply.defs"
\ No newline at end of file
diff --git a/DNSServiceDiscoveryRequest.defs b/DNSServiceDiscoveryRequest.defs
new file mode 100644 (file)
index 0000000..fc17bd3
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+ #import "/AppleInternal/Developer/Headers/DNSServiceDiscovery/DNSServiceDiscoveryRequest.defs"
\ No newline at end of file
diff --git a/SamplemDNSClient.c b/SamplemDNSClient.c
new file mode 100644 (file)
index 0000000..8f14f2d
--- /dev/null
@@ -0,0 +1,329 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+
+/*
+ * 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.)
+ */
+
+#include <libc.h>
+#include <arpa/nameser.h>
+#include <CoreFoundation/CoreFoundation.h>
+#include <DNSServiceDiscovery/DNSServiceDiscovery.h>
+
+//*************************************************************************************************************
+// Globals
+
+typedef union { unsigned char b[2]; unsigned short NotAnInteger; } Opaque16;
+
+static char operation;
+static dns_service_discovery_ref client = NULL;
+static char addtest = 0;
+static DNSRecordReference record;
+static char myhinfo9[11] = "\003Mac\006OS 9.2";
+static char myhinfoX[ 9] = "\003Mac\004OS X";
+static char updatetest[2] = "\001A";
+static char bigNULL[4096];
+
+//*************************************************************************************************************
+// Supporting Utility Functions
+//
+// This code takes care of:
+// 1. Extracting the mach_port_t from the dns_service_discovery_ref
+// 2. Making a CFMachPortRef from it
+// 3. Making a CFRunLoopSourceRef from that
+// 4. Adding that source to the current RunLoop
+// 5. and passing the resulting messages back to DNSServiceDiscovery_handleReply() for processing
+//
+// Code that's not based around a CFRunLoop will need its own mechanism to receive Mach messages
+// from the mDNSResponder daemon and pass them to the DNSServiceDiscovery_handleReply() routine.
+// (There is no way to automate this, because it varies depending on the application's existing
+// event handling model.)
+
+static void MyHandleMachMessage(CFMachPortRef port, void *msg, CFIndex size, void *info)
+       {
+       DNSServiceDiscovery_handleReply(msg);
+       }
+
+static int AddDNSServiceClientToRunLoop(dns_service_discovery_ref client)
+    {
+       mach_port_t port = DNSServiceDiscoveryMachPort(client);
+    if (!port)
+        return(-1);
+    else
+        {
+        CFMachPortContext  context    = { 0, 0, NULL, NULL, NULL };
+        Boolean            shouldFreeInfo;
+        CFMachPortRef      cfMachPort = CFMachPortCreateWithPort(kCFAllocatorDefault, port, MyHandleMachMessage, &context, &shouldFreeInfo);
+        CFRunLoopSourceRef rls        = CFMachPortCreateRunLoopSource(NULL, cfMachPort, 0);
+        CFRunLoopAddSource(CFRunLoopGetCurrent(), rls, kCFRunLoopDefaultMode);
+        CFRelease(rls);
+        return(0);
+        }
+    }
+
+//*************************************************************************************************************
+// Sample callback functions for each of the operation types
+
+#define DomainMsg(X) ((X) == DNSServiceDomainEnumerationReplyAddDomain        ? "Added"     :          \
+                      (X) == DNSServiceDomainEnumerationReplyAddDomainDefault ? "(Default)" :          \
+                      (X) == DNSServiceDomainEnumerationReplyRemoveDomain     ? "Removed"   : "Unknown")
+
+static void regdom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
+    DNSServiceDiscoveryReplyFlags flags, void *context)
+       {
+       printf("Recommended Registration Domain %s %s", replyDomain, DomainMsg(resultType));
+       if (flags) printf(" Flags: %X", flags);
+       printf("\n");
+       }
+
+static void browsedom_reply(DNSServiceDomainEnumerationReplyResultType resultType, const char *replyDomain,
+    DNSServiceDiscoveryReplyFlags flags, void *context)
+       {
+       printf("Recommended Browsing Domain %s %s", replyDomain, DomainMsg(resultType));
+       if (flags) printf(" Flags: %X", flags);
+       printf("\n");
+       }
+
+static void browse_reply(DNSServiceBrowserReplyResultType resultType,
+    const char *replyName, const char *replyType, const char *replyDomain, DNSServiceDiscoveryReplyFlags flags, void *context)
+       {
+       char *op = (resultType == DNSServiceBrowserReplyAddInstance) ? "Found" : "Removed";
+       printf("Service \"%s\", type \"%s\", domain \"%s\" %s", replyName, replyType, replyDomain, op);
+       if (flags) printf(" Flags: %X", flags);
+       printf("\n");
+       }
+
+static void resolve_reply(struct sockaddr *interface, struct sockaddr *address, const char *txtRecord, DNSServiceDiscoveryReplyFlags flags, void *context)
+       {
+       if (address->sa_family != AF_INET)
+               printf("Unknown address family %d\n", address->sa_family);
+       else
+               {
+               struct sockaddr_in *ip = (struct sockaddr_in *)address;
+               union { uint32_t l; u_char b[4]; } addr = { ip->sin_addr.s_addr };
+               union { uint16_t s; u_char b[2]; } port = { ip->sin_port };
+               uint16_t PortAsNumber = ((uint16_t)port.b[0]) << 8 | port.b[1];
+        const char *src = txtRecord;
+               printf("Service can be reached at %d.%d.%d.%d:%u", addr.b[0], addr.b[1], addr.b[2], addr.b[3], PortAsNumber);
+        while (*src)
+            {
+            char txtInfo[256];
+            char *dst = txtInfo;
+            const char *const lim = &txtInfo[sizeof(txtInfo)];
+            while (*src && *src != 1 && dst < lim-1) *dst++ = *src++;
+            *dst++ = 0;
+            printf(" TXT \"%s\"", txtInfo);
+            if (*src == 1) src++;
+            }
+               if (flags) printf(" Flags: %X", flags);
+               printf("\n");
+               }
+       }
+
+static void myCFRunLoopTimerCallBack(CFRunLoopTimerRef timer, void *info)
+       {
+       (void)timer;    // Parameter not used
+       (void)info;             // Parameter not used
+    
+    switch (operation)
+        {
+        case 'A':
+            {
+            switch (addtest)
+                {
+                case 0: printf("Adding Test HINFO record\n");
+                        record = DNSServiceRegistrationAddRecord(client, T_HINFO, sizeof(myhinfo9), &myhinfo9[0], 120);
+                        addtest = 1;
+                        break;
+                case 1: printf("Updating Test HINFO record\n");
+                        DNSServiceRegistrationUpdateRecord(client, record, sizeof(myhinfoX), &myhinfoX[0], 120);
+                        addtest = 2;
+                        break;
+                case 2: printf("Removing Test HINFO record\n");
+                        DNSServiceRegistrationRemoveRecord(client, record);
+                        addtest = 0;
+                        break;
+                }
+            }
+            break;
+
+        case 'U':
+            {
+            if (updatetest[1] != 'Z') updatetest[1]++;
+            else                      updatetest[1] = 'A';
+            printf("Updating Test TXT record to %c\n", updatetest[1]);
+            DNSServiceRegistrationUpdateRecord(client, 0, sizeof(updatetest), &updatetest[0], 120);
+            }
+            break;
+
+        case 'N':
+            {
+            printf("Adding big NULL record\n");
+            DNSServiceRegistrationAddRecord(client, T_NULL, sizeof(bigNULL), &bigNULL[0], 120);
+            CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
+            }
+            break;
+        }
+    }
+
+static void reg_reply(DNSServiceRegistrationReplyErrorType errorCode, void *context)
+       {
+    printf("Got a reply from the server: ");
+    switch (errorCode)
+        {
+        case kDNSServiceDiscoveryNoError:      printf("Name now registered and active\n"); break;
+        case kDNSServiceDiscoveryNameConflict: printf("Name in use, please choose another\n"); exit(-1);
+        default:                               printf("Error %d\n", errorCode); return;
+        }
+
+    if (operation == 'A' || operation == 'U' || operation == 'N')
+        {
+        CFRunLoopTimerContext myCFRunLoopTimerContext = { 0, 0, NULL, NULL, NULL };
+        CFRunLoopTimerRef timer = CFRunLoopTimerCreate(kCFAllocatorDefault,
+            CFAbsoluteTimeGetCurrent() + 5.0, 5.0, 0, 1,       // Next fire time, periodic interval, flags, and order
+                                myCFRunLoopTimerCallBack, &myCFRunLoopTimerContext);
+        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopDefaultMode);
+        }
+       }
+
+//*************************************************************************************************************
+// The main test function
+
+int main(int argc, char **argv)
+       {
+       char *dom;
+
+       if (argc < 2) goto Fail;                // Minimum command line is the command name and one argument
+    operation = getopt(argc, (char * const *)argv, "EFBLRAUNTM");
+       if (operation == -1) goto Fail;
+
+    switch (operation)
+        {
+        case 'E':      printf("Looking for recommended registration domains:\n");
+                    client = DNSServiceDomainEnumerationCreate(1, regdom_reply, nil);
+                    break;
+
+        case 'F':      printf("Looking for recommended browsing domains:\n");
+                    client = DNSServiceDomainEnumerationCreate(0, browsedom_reply, nil);
+                    break;
+
+        case 'B':      if (argc < optind+1) goto Fail;
+                    dom = (argc < optind+2) ? "" : argv[optind+1];
+                    if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;      // We allow '.' on the command line as a synonym for empty string
+                    printf("Browsing for %s%s\n", argv[optind+0], dom);
+                    client = DNSServiceBrowserCreate(argv[optind+0], dom, browse_reply, nil);
+                    break;
+
+        case 'L':      if (argc < optind+2) goto Fail;
+                    dom = (argc < optind+3) ? "" : argv[optind+2];
+                    if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;      // We allow '.' on the command line as a synonym for empty string
+                    printf("Lookup %s.%s%s\n", argv[optind+0], argv[optind+1], dom);
+                    client = DNSServiceResolverResolve(argv[optind+0], argv[optind+1], dom, resolve_reply, nil);
+                    break;
+
+        case 'R':      if (argc < optind+4) goto Fail;
+                    {
+                    char *nam = argv[optind+0];
+                    char *typ = argv[optind+1];
+                    char *dom = argv[optind+2];
+                    uint16_t PortAsNumber = atoi(argv[optind+3]);
+                    Opaque16 registerPort = { { PortAsNumber >> 8, PortAsNumber & 0xFF } };
+                    char *txt = (argc > optind+4) ? argv[optind+4] : "";
+                    if (nam[0] == '.' && nam[1] == 0) nam[0] = 0;      // We allow '.' on the command line as a synonym for empty string
+                    if (dom[0] == '.' && dom[1] == 0) dom[0] = 0;      // We allow '.' on the command line as a synonym for empty string
+                    printf("Registering Service %s.%s%s port %s %s\n", nam, typ, dom, argv[optind+3], txt);
+                    client = DNSServiceRegistrationCreate(nam, typ, dom, registerPort.NotAnInteger, txt, reg_reply, nil);
+                    break;
+                    }
+
+        case 'A':
+        case 'U':
+        case 'N':      {
+                    Opaque16 registerPort = { { 0x12, 0x34 } };
+                    static const char TXT[] = "First String\001Second String\001Third String";
+                    printf("Registering Service Test._testupdate._tcp.local.\n");
+                    client = DNSServiceRegistrationCreate("Test", "_testupdate._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
+                    break;
+                    }
+
+        case 'T':      {
+                    Opaque16 registerPort = { { 0x23, 0x45 } };
+                    char TXT[512];
+                    int i;
+                    for (i=0; i<sizeof(TXT)-1; i++)
+                        if ((i & 0x1F) == 0x1F) TXT[i] = 1; else TXT[i] = 'A' + (i >> 5);
+                    TXT[i] = 0;
+                    printf("Registering Service Test._testlargetxt._tcp.local.\n");
+                    client = DNSServiceRegistrationCreate("Test", "_testlargetxt._tcp.", "", registerPort.NotAnInteger, TXT, reg_reply, nil);
+                    break;
+                    }
+
+        case 'M':      {
+                    Opaque16 registerPort = { { 0x23, 0x45 } };
+                    static const char TXT1[] = "First String\001Second String\001Third String";
+                    static const char TXT2[] = "\x0D" "Fourth String" "\x0C" "Fifth String" "\x0C" "Sixth String";
+                    printf("Registering Service Test._testdualtxt._tcp.local.\n");
+                    client = DNSServiceRegistrationCreate("Test", "_testdualtxt._tcp.", "", registerPort.NotAnInteger, TXT1, reg_reply, nil);
+                    record = DNSServiceRegistrationAddRecord(client, T_TXT, sizeof(TXT2), TXT2, 120);
+                    break;
+                    }
+
+        default: goto Exit;
+        }
+
+    if (!client) { fprintf(stderr, "DNSService call failed\n"); return (-1); }
+    if (AddDNSServiceClientToRunLoop(client) != 0) { fprintf(stderr, "AddDNSServiceClientToRunLoop failed\n"); return (-1); }
+    printf("Talking to DNS SD Daemon at Mach port %d\n", DNSServiceDiscoveryMachPort(client));
+       CFRunLoopRun();
+    
+    // Be sure to deallocate the dns_service_discovery_ref when you're finished
+    // Note: What other cleanup has to be done here?
+    // We should probably invalidate, remove and release our CFRunLoopSourceRef?
+    DNSServiceDiscoveryDeallocate(client);
+    
+Exit:
+       return 0;
+
+Fail:
+       fprintf(stderr, "%s -E             (Enumerate recommended registration domains)\n", argv[0]);
+       fprintf(stderr, "%s -F                 (Enumerate recommended browsing domains)\n", argv[0]);
+       fprintf(stderr, "%s -B        <Type> <Domain>   (Browse for services instances)\n", argv[0]);
+       fprintf(stderr, "%s -L <Name> <Type> <Domain>      (Look up a service instance)\n", argv[0]);
+       fprintf(stderr, "%s -R <Name> <Type> <Domain> <Port> <TXT> (Register a service)\n", argv[0]);
+       fprintf(stderr, "%s -A                 (Test Adding/Updating/Deleting a record)\n", argv[0]);
+       fprintf(stderr, "%s -U                             (Test updating a TXT record)\n", argv[0]);
+       fprintf(stderr, "%s -N                        (Test adding a large NULL record)\n", argv[0]);
+       fprintf(stderr, "%s -T                       (Test creating a large TXT record)\n", argv[0]);
+       fprintf(stderr, "%s -M (Test creating a registration with multiple TXT records)\n", argv[0]);
+       return 0;
+       }
diff --git a/daemon.c b/daemon.c
new file mode 100644 (file)
index 0000000..c012ab1
--- /dev/null
+++ b/daemon.c
@@ -0,0 +1,1121 @@
+/*
+ * Copyright (c) 2002 Apple Computer, Inc. All rights reserved.
+ *
+ * @APPLE_LICENSE_HEADER_START@
+ *
+ * The contents of this file constitute Original Code as defined in and
+ * are subject to the Apple Public Source License Version 1.1 (the
+ * "License").  You may not use this file except in compliance with the
+ * License.  Please obtain a copy of the License at
+ * http://www.apple.com/publicsource and read it before using this file.
+ *
+ * This Original Code and all software distributed under the License are
+ * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
+ * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
+ * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
+ * License for the specific language governing rights and limitations
+ * under the License.
+ *
+ * @APPLE_LICENSE_HEADER_END@
+ */
+
+/*
+ * 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.)
+ */
+
+#include <mach/mach.h>
+#include <mach/mach_error.h>
+#include <servers/bootstrap.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include "DNSServiceDiscoveryRequestServer.h"
+#include "DNSServiceDiscoveryReply.h"
+
+#include "mDNSClientAPI.h"                             // Defines the interface to the client layer above
+#include "mDNSPlatformEnvironment.h"   // Defines the specific types needed to run mDNS on this platform
+#include "mDNSsprintf.h"
+#include "mDNSvsprintf.h"                              // Used to implement LogErrorMessage();
+
+#include <DNSServiceDiscovery/DNSServiceDiscovery.h>
+
+//*************************************************************************************************************
+// Globals
+
+static mDNS mDNSStorage;
+static mDNS_PlatformSupport PlatformStorage;
+#define RR_CACHE_SIZE 500
+static ResourceRecord rrcachestorage[RR_CACHE_SIZE];
+static const char PID_FILE[] = "/var/run/mDNSResponder.pid";
+
+static const char kmDNSBootstrapName[] = "com.apple.mDNSResponder";
+static mach_port_t client_death_port = MACH_PORT_NULL;
+static mach_port_t exit_m_port       = MACH_PORT_NULL;
+static mach_port_t server_priv_port  = MACH_PORT_NULL;
+static CFRunLoopTimerRef DeliverInstanceTimer;
+
+// mDNS Mach Message Timeout, in milliseconds.
+// We need this to be short enough that we don't deadlock the mDNSResponder if a client
+// fails to service its mach message queue, but long enough to give a well-written
+// client a chance to service its mach message queue without getting cut off.
+// Empirically, 50ms seems to work, so we set the timeout to 250ms to give
+// even extra-slow clients a fair chance before we cut them off.
+#define MDNS_MM_TIMEOUT 250
+
+static int restarting_via_mach_init = 0;
+
+#if DEBUGBREAKS
+static int debug_mode = 1;
+#else
+static int debug_mode = 0;
+#endif
+
+//*************************************************************************************************************
+// Active client list structures
+
+typedef struct DNSServiceDomainEnumeration_struct DNSServiceDomainEnumeration;
+struct DNSServiceDomainEnumeration_struct
+       {
+       DNSServiceDomainEnumeration *next;
+       mach_port_t ClientMachPort;
+       DNSQuestion dom;        // Question asking for domains
+       DNSQuestion def;        // Question asking for default domain
+       };
+
+typedef struct DNSServiceBrowser_struct DNSServiceBrowser;
+struct DNSServiceBrowser_struct
+       {
+       DNSServiceBrowser *next;
+       mach_port_t ClientMachPort;
+       DNSQuestion q;
+       int resultType;         // Set to -1 if no outstanding reply
+       char name[256], type[256], dom[256];
+       };
+
+typedef struct DNSServiceResolver_struct DNSServiceResolver;
+struct DNSServiceResolver_struct
+       {
+       DNSServiceResolver *next;
+       mach_port_t ClientMachPort;
+       ServiceInfoQuery q;
+       ServiceInfo      i;
+       };
+
+typedef struct DNSServiceRegistration_struct DNSServiceRegistration;
+struct DNSServiceRegistration_struct
+       {
+       DNSServiceRegistration *next;
+       mach_port_t ClientMachPort;
+       mDNSBool autoname;
+       ServiceRecordSet s;
+       // Don't add any fields after ServiceRecordSet.
+       // This is where the implicit extra space goes if we allocate an oversized ServiceRecordSet object
+       };
+
+static DNSServiceDomainEnumeration *DNSServiceDomainEnumerationList = NULL;
+static DNSServiceBrowser           *DNSServiceBrowserList           = NULL;
+static DNSServiceResolver          *DNSServiceResolverList          = NULL;
+static DNSServiceRegistration      *DNSServiceRegistrationList      = NULL;
+
+//*************************************************************************************************************
+// General Utility Functions
+
+void LogErrorMessage(const char *format, ...)
+       {
+       unsigned char buffer[512];
+       va_list ptr;
+       va_start(ptr,format);
+       buffer[mDNS_vsprintf((char *)buffer, format, ptr)] = 0;
+       va_end(ptr);
+       openlog("mDNSResponder", LOG_CONS | LOG_PERROR | LOG_PID, LOG_DAEMON);
+       fprintf(stderr, "%s\n", buffer);
+       syslog(LOG_ERR, "%s", buffer);
+       closelog();
+       fflush(stderr);
+       }
+
+#if MACOSX_MDNS_MALLOC_DEBUGGING
+
+char _malloc_options[] = "AXZ";
+
+static void validatelists(mDNS *const m)
+       {
+       DNSServiceDomainEnumeration *e;
+       DNSServiceBrowser           *b;
+       DNSServiceResolver          *l;
+       DNSServiceRegistration      *r;
+       ResourceRecord              *rr;
+
+       for (e = DNSServiceDomainEnumerationList; e; e=e->next)
+               if (e->ClientMachPort == 0)
+                       LogErrorMessage("!!!! DNSServiceDomainEnumerationList %X is garbage !!!!", e);
+
+       for (b = DNSServiceBrowserList; b; b=b->next)
+               if (b->ClientMachPort == 0)
+                       LogErrorMessage("!!!! DNSServiceBrowserList %X is garbage !!!!", b);
+
+       for (l = DNSServiceResolverList; l; l=l->next)
+               if (l->ClientMachPort == 0)
+                       LogErrorMessage("!!!! DNSServiceResolverList %X is garbage !!!!", l);
+
+       for (r = DNSServiceRegistrationList; r; r=r->next)
+               if (r->ClientMachPort == 0)
+                       LogErrorMessage("!!!! DNSServiceRegistrationList %X is garbage !!!!", r);
+
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               if (rr->RecordType == 0)
+                       LogErrorMessage("!!!! ResourceRecords %X list is garbage !!!!");
+       }
+
+void *mallocL(char *msg, unsigned int size)
+       {
+       unsigned long *mem = malloc(size+8);
+       if (!mem)
+               { LogErrorMessage("malloc(%s:%d) failed", msg, size); return(NULL); }
+       else
+               {
+               LogErrorMessage("malloc(%s:%d) = %X", msg, size, &mem[2]);
+               mem[0] = 0xDEADBEEF;
+               mem[1] = size;
+               bzero(&mem[2], size);
+               validatelists(&mDNSStorage);
+               return(&mem[2]);
+               }
+       }
+
+void freeL(char *msg, void *x)
+       {
+       if (!x)
+               LogErrorMessage("free(%s@NULL)!", msg);
+       else
+               {
+               unsigned long *mem = ((unsigned long *)x) - 2;
+               if (mem[0] != 0xDEADBEEF)
+                       { LogErrorMessage("free(%s@%X) !!!! NOT ALLOCATED !!!!", msg, &mem[2]); return; }
+               if (mem[1] > 8000)
+                       { LogErrorMessage("free(%s:%d@%X) too big!", msg, mem[1], &mem[2]); return; }
+               LogErrorMessage("free(%s:%d@%X)", msg, mem[1], &mem[2]);
+               bzero(mem, mem[1]+8);
+               validatelists(&mDNSStorage);
+               free(mem);
+               }
+       }
+
+#endif
+
+//*************************************************************************************************************
+// Client Death Detection
+
+mDNSlocal void AbortClient(mach_port_t ClientMachPort)
+       {
+       DNSServiceDomainEnumeration **e = &DNSServiceDomainEnumerationList;
+       DNSServiceBrowser           **b = &DNSServiceBrowserList;
+       DNSServiceResolver          **l = &DNSServiceResolverList;
+       DNSServiceRegistration      **r = &DNSServiceRegistrationList;
+
+       while (*e && (*e)->ClientMachPort != ClientMachPort) e = &(*e)->next;
+       if (*e)
+               {
+               DNSServiceDomainEnumeration *x = *e;
+               *e = (*e)->next;
+               debugf("Aborting DNSServiceDomainEnumeration %d", ClientMachPort);
+               mDNS_StopGetDomains(&mDNSStorage, &x->dom);
+               mDNS_StopGetDomains(&mDNSStorage, &x->def);
+               freeL("DNSServiceDomainEnumeration", x);
+               return;
+               }
+
+       while (*b && (*b)->ClientMachPort != ClientMachPort) b = &(*b)->next;
+       if (*b)
+               {
+               DNSServiceBrowser *x = *b;
+               *b = (*b)->next;
+               debugf("Aborting DNSServiceBrowser %d", ClientMachPort);
+               mDNS_StopBrowse(&mDNSStorage, &x->q);
+               freeL("DNSServiceBrowser", x);
+               return;
+               }
+
+       while (*l && (*l)->ClientMachPort != ClientMachPort) l = &(*l)->next;
+       if (*l)
+               {
+               DNSServiceResolver *x = *l;
+               *l = (*l)->next;
+               debugf("Aborting DNSServiceResolver %d", ClientMachPort);
+               mDNS_StopResolveService(&mDNSStorage, &x->q);
+               freeL("DNSServiceResolver", x);
+               return;
+               }
+
+       while (*r && (*r)->ClientMachPort != ClientMachPort) r = &(*r)->next;
+       if (*r)
+               {
+               DNSServiceRegistration *x = *r;
+               *r = (*r)->next;
+               mDNS_DeregisterService(&mDNSStorage, &x->s);
+               // Note that we don't do the "free(x);" here -- wait for the mStatus_MemFree message
+               return;
+               }
+       }
+
+mDNSlocal void AbortBlockedClient(mach_port_t c, char *m)
+       {
+       DNSServiceDomainEnumeration **e = &DNSServiceDomainEnumerationList;
+       DNSServiceBrowser           **b = &DNSServiceBrowserList;
+       DNSServiceResolver          **l = &DNSServiceResolverList;
+       DNSServiceRegistration      **r = &DNSServiceRegistrationList;
+       while (*e && (*e)->ClientMachPort != c) e = &(*e)->next;
+       while (*b && (*b)->ClientMachPort != c) b = &(*b)->next;
+       while (*l && (*l)->ClientMachPort != c) l = &(*l)->next;
+       while (*r && (*r)->ClientMachPort != c) r = &(*r)->next;
+       if      (*e) LogErrorMessage("%5d: DomainEnumeration(%##s) stopped accepting Mach messages (%s)", c, &e[0]->dom.name, m);
+       else if (*b) LogErrorMessage("%5d: Browser(%##s) stopped accepting Mach messages (%s)",      c, &b[0]->q.name, m);
+       else if (*l) LogErrorMessage("%5d: Resolver(%##s) stopped accepting Mach messages (%s)",     c, &l[0]->i.name, m);
+       else if (*r) LogErrorMessage("%5d: Registration(%##s) stopped accepting Mach messages (%s)", c, &r[0]->s.RR_SRV.name, m);
+       else         LogErrorMessage("%5d (%s) stopped accepting Mach messages, but no record of client can be found!", c, m);
+
+       AbortClient(c);
+       }
+
+mDNSlocal void ClientDeathCallback(CFMachPortRef unusedport, void *voidmsg, CFIndex size, void *info)
+       {
+       mach_msg_header_t *msg = (mach_msg_header_t *)voidmsg;
+       if (msg->msgh_id == MACH_NOTIFY_DEAD_NAME)
+               {
+               const mach_dead_name_notification_t *const deathMessage = (mach_dead_name_notification_t *)msg;
+               AbortClient(deathMessage->not_port);
+
+               /* Deallocate the send right that came in the dead name notification */
+               mach_port_destroy( mach_task_self(), deathMessage->not_port );
+               }
+       }
+
+mDNSlocal void EnableDeathNotificationForClient(mach_port_t ClientMachPort)
+       {
+       mach_port_t prev;
+       kern_return_t r = mach_port_request_notification(mach_task_self(), ClientMachPort, MACH_NOTIFY_DEAD_NAME, 0,
+                                                                                                        client_death_port, MACH_MSG_TYPE_MAKE_SEND_ONCE, &prev);
+       // If the port already died while we were thinking about it, then abort the operation right away
+       if (r != KERN_SUCCESS)
+               {
+               if (ClientMachPort != (mach_port_t)-1)
+                       LogErrorMessage("Client %5d died before we could enable death notification", ClientMachPort);
+               AbortClient(ClientMachPort);
+               }
+       }
+
+//*************************************************************************************************************
+// Domain Enumeration
+
+mDNSlocal void FoundDomain(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
+       {
+       kern_return_t status;
+       #pragma unused(m)
+       char buffer[256];
+       DNSServiceDomainEnumerationReplyResultType rt;
+       DNSServiceDomainEnumeration *x = (DNSServiceDomainEnumeration *)question->Context;
+
+       debugf("FoundDomain: %##s PTR %##s", answer->name.c, answer->rdata->u.name.c);
+       if (answer->rrtype != kDNSType_PTR) return;
+       if (!x) { debugf("FoundDomain: DNSServiceDomainEnumeration is NULL"); return; }
+
+       if (answer->rrremainingttl > 0)
+               {
+               if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyAddDomain;
+               else                     rt = DNSServiceDomainEnumerationReplyAddDomainDefault;
+               }
+       else
+               {
+               if (question == &x->dom) rt = DNSServiceDomainEnumerationReplyRemoveDomain;
+               else return;
+               }
+
+       ConvertDomainNameToCString(&answer->rdata->u.name, buffer);
+       status = DNSServiceDomainEnumerationReply_rpc(x->ClientMachPort, rt, buffer, 0, MDNS_MM_TIMEOUT);
+       if (status == MACH_SEND_TIMED_OUT)
+               AbortBlockedClient(x->ClientMachPort, "enumeration");
+       }
+
+mDNSexport kern_return_t provide_DNSServiceDomainEnumerationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
+       int regDom)
+       {
+       kern_return_t status;
+       mStatus err;
+
+       mDNS_DomainType dt1 = regDom ? mDNS_DomainTypeRegistration        : mDNS_DomainTypeBrowse;
+       mDNS_DomainType dt2 = regDom ? mDNS_DomainTypeRegistrationDefault : mDNS_DomainTypeBrowseDefault;
+       const DNSServiceDomainEnumerationReplyResultType rt = DNSServiceDomainEnumerationReplyAddDomainDefault;
+       DNSServiceDomainEnumeration *x = mallocL("DNSServiceDomainEnumeration", sizeof(*x));
+       if (!x) { debugf("provide_DNSServiceDomainEnumerationCreate_rpc: No memory!"); return(mStatus_NoMemoryErr); }
+       x->ClientMachPort = client;
+       x->next = DNSServiceDomainEnumerationList;
+       DNSServiceDomainEnumerationList = x;
+       
+       debugf("Client %d: Enumerate %s Domains", client, regDom ? "Registration" : "Browsing");
+       // We always give local. as the initial default browse domain, and then look for more
+       status = DNSServiceDomainEnumerationReply_rpc(x->ClientMachPort, rt, "local.", 0, MDNS_MM_TIMEOUT);
+       if (status == MACH_SEND_TIMED_OUT)
+               {
+               AbortBlockedClient(x->ClientMachPort, "local enumeration");
+               return(mStatus_UnknownErr);
+               }
+
+       err           = mDNS_GetDomains(&mDNSStorage, &x->dom, dt1, zeroIPAddr, FoundDomain, x);
+       if (!err) err = mDNS_GetDomains(&mDNSStorage, &x->def, dt2, zeroIPAddr, FoundDomain, x);
+
+       if (err) AbortClient(client);
+       else EnableDeathNotificationForClient(client);
+
+       if (err) debugf("provide_DNSServiceDomainEnumerationCreate_rpc: mDNS_GetDomains error %d", err);
+       return(err);
+       }
+
+//*************************************************************************************************************
+// Browse for services
+
+mDNSlocal void DeliverInstance(DNSServiceBrowser *x, DNSServiceDiscoveryReplyFlags flags)
+       {
+       kern_return_t status;
+       debugf("DNSServiceBrowserReply_rpc sending reply for %s (%s)", x->name,
+               (flags & DNSServiceDiscoverReplyFlagsMoreComing) ? "more coming" : "last in batch");
+       status = DNSServiceBrowserReply_rpc(x->ClientMachPort, x->resultType, x->name, x->type, x->dom, flags, MDNS_MM_TIMEOUT);
+       x->resultType = -1;
+       if (status == MACH_SEND_TIMED_OUT)
+               AbortBlockedClient(x->ClientMachPort, "browse");
+       }
+
+mDNSlocal void DeliverInstanceTimerCallBack(CFRunLoopTimerRef timer, void *info)
+       {
+       DNSServiceBrowser *b = DNSServiceBrowserList;
+       (void)timer;    // Parameter not used
+
+       while (b)
+               {
+               // NOTE: Need to advance b to the next element BEFORE we call DeliverInstance(), because in the
+               // event that the client Mach queue overflows, DeliverInstance() will call AbortBlockedClient()
+               // and that will cause the DNSServiceBrowser object's memory to be freed before it returns
+               DNSServiceBrowser *x = b;
+               b = b->next;
+               if (x->resultType != -1)
+                       DeliverInstance(x, 0);
+               }
+       }
+
+mDNSlocal void FoundInstance(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
+       {
+       DNSServiceBrowser *x = (DNSServiceBrowser *)question->Context;
+       domainlabel name;
+       domainname type, domain;
+       
+       if (answer->rrtype != kDNSType_PTR)
+               {
+               debugf("FoundInstance: Should not be called with rrtype %d (not a PTR record)", answer->rrtype);
+               return;
+               }
+       
+       if (!DeconstructServiceName(&answer->rdata->u.name, &name, &type, &domain))
+               {
+               debugf("FoundInstance: %##s PTR %##s is not valid NIAS service pointer", &answer->name, &answer->rdata->u.name);
+               return;
+               }
+
+       if (x->resultType != -1) DeliverInstance(x, DNSServiceDiscoverReplyFlagsMoreComing);
+
+       debugf("FoundInstance: %##s", answer->rdata->u.name.c);
+       ConvertDomainLabelToCString_unescaped(&name, x->name);
+       ConvertDomainNameToCString(&type, x->type);
+       ConvertDomainNameToCString(&domain, x->dom);
+       if (answer->rrremainingttl)
+                x->resultType = DNSServiceBrowserReplyAddInstance;
+       else x->resultType = DNSServiceBrowserReplyRemoveInstance;
+
+       // We schedule this timer 1/10 second in the future because CFRunLoop doesn't respect
+       // the relative priority between CFSocket and CFRunLoopTimer, and continues to call
+       // the timer callback even though there are packets waiting to be processed.
+       CFRunLoopTimerSetNextFireDate(DeliverInstanceTimer, CFAbsoluteTimeGetCurrent() + 0.1);
+       }
+
+mDNSexport kern_return_t provide_DNSServiceBrowserCreate_rpc(mach_port_t unusedserver, mach_port_t client,
+       DNSCString regtype, DNSCString domain)
+       {
+       mStatus err;
+       domainname t, d;
+       DNSServiceBrowser *x = mallocL("DNSServiceBrowser", sizeof(*x));
+       if (!x) { debugf("provide_DNSServiceBrowserCreate_rpc: No memory!"); return(mStatus_NoMemoryErr); }
+       x->ClientMachPort = client;
+       x->resultType = -1;
+       x->next = DNSServiceBrowserList;
+       DNSServiceBrowserList = x;
+
+       ConvertCStringToDomainName(regtype, &t);
+       ConvertCStringToDomainName(*domain ? domain : "local.", &d);
+
+       debugf("Client %d: provide_DNSServiceBrowserCreate_rpc", client);
+       debugf("Client %d: Browse for Services: %##s%##s", client, &t, &d);
+       err = mDNS_StartBrowse(&mDNSStorage, &x->q, &t, &d, zeroIPAddr, FoundInstance, x);
+
+       if (err) AbortClient(client);
+       else EnableDeathNotificationForClient(client);
+
+       if (err) debugf("provide_DNSServiceBrowserCreate_rpc: mDNS_StartBrowse error %d", err);
+       return(err);
+       }
+
+//*************************************************************************************************************
+// Resolve Service Info
+
+mDNSlocal void FoundInstanceInfo(mDNS *const m, ServiceInfoQuery *query)
+       {
+       kern_return_t status;
+       DNSServiceResolver *x = (DNSServiceResolver *)query->Context;
+       struct sockaddr_in interface;
+       struct sockaddr_in address;
+       char cstring[1024];
+       int i, pstrlen = query->info->TXTinfo[0];
+
+       //debugf("FoundInstanceInfo %.4a %.4a %##s", &query->info->InterfaceAddr, &query->info->ip, &query->info->name);
+
+       if (query->info->TXTlen > sizeof(cstring)) return;
+
+       bzero(&interface, sizeof(interface));
+       bzero(&address,   sizeof(address));
+
+       interface.sin_len         = sizeof(interface);
+       interface.sin_family      = AF_INET;
+       interface.sin_port        = 0;
+       interface.sin_addr.s_addr = query->info->InterfaceAddr.NotAnInteger;
+       
+       address.sin_len           = sizeof(address);
+       address.sin_family        = AF_INET;
+       address.sin_port          = query->info->port.NotAnInteger;
+       address.sin_addr.s_addr   = query->info->ip.NotAnInteger;
+
+       // The OS X DNSServiceResolverResolve() API is defined using a C-string,
+       // but the mDNS_StartResolveService() call actually returns a packed block of P-strings.
+       // Hence we have to convert the P-string(s) to a C-string before returning the result to the client.
+       // ASCII-1 characters are used in the C-string as boundary markers,
+       // to indicate the boundaries between the original constituent P-strings.
+       for (i=1; i<query->info->TXTlen; i++)
+               {
+               if (--pstrlen >= 0)
+                       cstring[i-1] = query->info->TXTinfo[i];
+               else
+                       {
+                       cstring[i-1] = 1;
+                       pstrlen = query->info->TXTinfo[i];
+                       }
+               }
+       cstring[i-1] = 0;               // Put the terminating NULL on the end
+       
+       status = DNSServiceResolverReply_rpc(x->ClientMachPort,
+               (char*)&interface, (char*)&address, cstring, 0, MDNS_MM_TIMEOUT);
+       if (status == MACH_SEND_TIMED_OUT)
+               AbortBlockedClient(x->ClientMachPort, "resolve");
+       }
+
+mDNSexport kern_return_t provide_DNSServiceResolverResolve_rpc(mach_port_t unusedserver, mach_port_t client,
+       DNSCString name, DNSCString regtype, DNSCString domain)
+       {
+       mStatus err;
+       domainlabel n;
+       domainname t, d;
+       DNSServiceResolver *x = mallocL("DNSServiceResolver", sizeof(*x));
+       if (!x) { debugf("provide_DNSServiceResolverResolve_rpc: No memory!"); return(mStatus_NoMemoryErr); }
+       x->ClientMachPort = client;
+       x->next = DNSServiceResolverList;
+       DNSServiceResolverList = x;
+
+       ConvertCStringToDomainLabel(name, &n);
+       ConvertCStringToDomainName(regtype, &t);
+       ConvertCStringToDomainName(*domain ? domain : "local.", &d);
+       ConstructServiceName(&x->i.name, &n, &t, &d);
+       x->i.InterfaceAddr = zeroIPAddr;
+
+       debugf("Client %d: provide_DNSServiceResolverResolve_rpc", client);
+       debugf("Client %d: Resolve Service: %##s", client, &x->i.name);
+       err = mDNS_StartResolveService(&mDNSStorage, &x->q, &x->i, FoundInstanceInfo, x);
+
+       if (err) AbortClient(client);
+       else EnableDeathNotificationForClient(client);
+
+       if (err) debugf("provide_DNSServiceResolverResolve_rpc: mDNS_StartResolveService error %d", err);
+       return(err);
+       }
+
+//*************************************************************************************************************
+// Registration
+
+mDNSlocal void FreeDNSServiceRegistration(DNSServiceRegistration *x)
+       {
+       while (x->s.Extras)
+               {
+               ExtraResourceRecord *extras = x->s.Extras;
+               x->s.Extras = x->s.Extras->next;
+               if (extras->r.rdata != &extras->r.rdatastorage)
+                       freeL("Extra RData", extras->r.rdata);
+               freeL("ExtraResourceRecord", extras);
+               }
+
+       if (x->s.RR_TXT.rdata != &x->s.RR_TXT.rdatastorage)
+                       freeL("TXT RData", x->s.RR_TXT.rdata);
+
+       freeL("DNSServiceRegistration", x);
+       }
+
+mDNSlocal void RegCallback(mDNS *const m, ServiceRecordSet *const sr, mStatus result)
+       {
+       DNSServiceRegistration *x = (DNSServiceRegistration*)sr->Context;
+
+       switch (result)
+               {
+               case mStatus_NoError:      debugf("RegCallback: %##s Name Registered",   sr->RR_SRV.name.c); break;
+               case mStatus_NameConflict: debugf("RegCallback: %##s Name Conflict",     sr->RR_SRV.name.c); break;
+               case mStatus_MemFree:      debugf("RegCallback: %##s Memory Free",       sr->RR_SRV.name.c); break;
+               default:                   debugf("RegCallback: %##s Unknown Result %d", sr->RR_SRV.name.c, result); break;
+               }
+
+       if (result == mStatus_NoError)
+               {
+               kern_return_t status = DNSServiceRegistrationReply_rpc(x->ClientMachPort, result, MDNS_MM_TIMEOUT);
+               if (status == MACH_SEND_TIMED_OUT)
+                       AbortBlockedClient(x->ClientMachPort, "registration success");
+               }
+
+       if (result == mStatus_NameConflict)
+               {
+               // Note: By the time we get the mStatus_NameConflict message, the service is already deregistered
+               // and the memory is free, so we don't have to wait for an mStatus_MemFree message as well.
+               if (x->autoname)
+                       mDNS_RenameAndReregisterService(m, sr);
+               else
+                       {
+                       kern_return_t status;
+                       // AbortClient unlinks our DNSServiceRegistration from the list so we can safely free it
+                       AbortClient(x->ClientMachPort);
+                       status = DNSServiceRegistrationReply_rpc(x->ClientMachPort, result, MDNS_MM_TIMEOUT);
+                       if (status == MACH_SEND_TIMED_OUT)
+                               AbortBlockedClient(x->ClientMachPort, "registration conflict"); // Yes, this IS safe :-)
+                       FreeDNSServiceRegistration(x);
+                       }
+               }
+
+       if (result == mStatus_MemFree)
+               {
+               DNSServiceRegistration **r = &DNSServiceRegistrationList;
+               while (*r && *r != x) r = &(*r)->next;
+               if (*r)
+                       {
+                       debugf("RegCallback: %##s Still in DNSServiceRegistration list; removing now", sr->RR_SRV.name.c);
+                       *r = (*r)->next;
+                       }
+               debugf("RegCallback: Freeing DNSServiceRegistration %##s %d", sr->RR_SRV.name.c, x->ClientMachPort);
+               FreeDNSServiceRegistration(x);
+               }
+       }
+
+mDNSlocal void CheckForDuplicateRegistrations(DNSServiceRegistration *x, domainlabel *n, domainname *t, domainname *d)
+       {
+       char name[256];
+       int count = 0;
+       ResourceRecord *rr;
+       domainname srvname;
+       ConstructServiceName(&srvname, n, t, d);
+       mDNS_sprintf(name, "%##s", &srvname);
+
+       for (rr = mDNSStorage.ResourceRecords; rr; rr=rr->next)
+               if (rr->rrtype == kDNSType_SRV && SameDomainName(&rr->name, &srvname))
+                       count++;
+
+       if (count)
+               {
+               debugf("Client %5d   registering Service Record Set \"%##s\"; WARNING! now have %d instances",
+                       x->ClientMachPort, &srvname, count+1);
+               LogErrorMessage("%5d: WARNING! Bogus client application has now registered %d identical instances of service %##s",
+                       x->ClientMachPort, count+1, &srvname);
+               }
+       }
+
+mDNSexport kern_return_t provide_DNSServiceRegistrationCreate_rpc(mach_port_t unusedserver, mach_port_t client,
+       DNSCString name, DNSCString regtype, DNSCString domain, int notAnIntPort, DNSCString txtRecord)
+       {
+       mStatus err;
+       domainlabel n;
+       domainname t, d;
+       mDNSIPPort port;
+       unsigned char txtinfo[1024] = "";
+       int data_len = 0;
+       int size = sizeof(RDataBody);
+       unsigned char *pstring = &txtinfo[data_len];
+       char *ptr = txtRecord;
+       DNSServiceRegistration *x;
+
+       // The OS X DNSServiceRegistrationCreate() API is defined using a C-string,
+       // but the mDNS_RegisterService() call actually requires a packed block of P-strings.
+       // Hence we have to convert the C-string to a P-string.
+       // ASCII-1 characters are allowed in the C-string as boundary markers,
+       // so that a single C-string can be used to represent one or more P-strings.
+       while (*ptr)
+               {
+               if (++data_len >= sizeof(txtinfo)) return(mStatus_BadParamErr);
+               if (*ptr == 1)          // If this is our boundary marker, start a new P-string
+                       {
+                       pstring = &txtinfo[data_len];
+                       pstring[0] = 0;
+                       ptr++;
+                       }
+               else
+                       {
+                       if (pstring[0] == 255) return(mStatus_BadParamErr);
+                       pstring[++pstring[0]] = *ptr++;
+                       }
+               }
+
+       data_len++;
+       if (size < data_len)
+               size = data_len;
+
+       x = mallocL("DNSServiceRegistration", sizeof(*x) - sizeof(RDataBody) + size);
+       if (!x) { debugf("provide_DNSServiceRegistrationCreate_rpc: No memory!"); return(mStatus_NoMemoryErr); }
+       x->ClientMachPort = client;
+       x->next = DNSServiceRegistrationList;
+       DNSServiceRegistrationList = x;
+
+       x->autoname = (*name == 0);
+       if (x->autoname) n = mDNSStorage.nicelabel;
+       else ConvertCStringToDomainLabel(name, &n);
+       ConvertCStringToDomainName(regtype, &t);
+       ConvertCStringToDomainName(*domain ? domain : "local.", &d);
+       port.NotAnInteger = notAnIntPort;
+
+       debugf("Client %d: provide_DNSServiceRegistrationCreate_rpc", client);
+       debugf("Client %d: Register Service: %#s.%##s%##s %d %.30s",
+               client, &n, &t, &d, (int)port.b[0] << 8 | port.b[1], txtRecord);
+       CheckForDuplicateRegistrations(x, &n, &t, &d);
+       err = mDNS_RegisterService(&mDNSStorage, &x->s, &n, &t, &d, mDNSNULL, port, txtinfo, data_len, RegCallback, x);
+
+       if (err) AbortClient(client);
+       else EnableDeathNotificationForClient(client);
+
+       if (err) debugf("provide_DNSServiceRegistrationCreate_rpc: mDNS_RegisterService error %d", err);
+       else debugf("Made Service Record Set for %##s", &x->s.RR_SRV.name);
+
+       return(err);
+       }
+
+mDNSexport kern_return_t provide_DNSServiceRegistrationAddRecord_rpc(mach_port_t unusedserver, mach_port_t client,
+       int type, const char *data, mach_msg_type_number_t data_len, uint32_t ttl, natural_t *reference)
+       {
+       mStatus err;
+       DNSServiceRegistration *x = DNSServiceRegistrationList;
+       ExtraResourceRecord *extra;
+       int size = sizeof(RDataBody);
+       if (size < data_len)
+               size = data_len;
+       
+       // Find this registered service
+       while (x && x->ClientMachPort != client) x = x->next;
+       if (!x)
+               {
+               debugf("provide_DNSServiceRegistrationAddRecord_rpc bad client %X", client);
+               return(mStatus_BadReferenceErr);
+               }
+
+       // Allocate storage for our new record
+       extra = mallocL("ExtraResourceRecord", sizeof(*extra) - sizeof(RDataBody) + size);
+       if (!extra) return(mStatus_NoMemoryErr);
+
+       // Fill in type, length, and data
+       extra->r.rrtype = type;
+       extra->r.rdatastorage.MaxRDLength = size;
+       extra->r.rdatastorage.RDLength    = data_len;
+       memcpy(&extra->r.rdatastorage.u.data, data, data_len);
+       
+       // And register it
+       err = mDNS_AddRecordToService(&mDNSStorage, &x->s, extra, &extra->r.rdatastorage, ttl);
+       *reference = (natural_t)extra;
+       debugf("Received a request to add the record of type: %d length: %d; returned reference %X",
+               type, data_len, *reference);
+       return(err);
+       }
+
+mDNSlocal void UpdateCallback(mDNS *const m, ResourceRecord *const rr, RData *OldRData)
+       {
+       if (OldRData != &rr->rdatastorage)
+               freeL("Old RData", OldRData);
+       }
+
+mDNSexport kern_return_t provide_DNSServiceRegistrationUpdateRecord_rpc(mach_port_t unusedserver, mach_port_t client,
+       natural_t reference, const char *data, mach_msg_type_number_t data_len, uint32_t ttl)
+       {
+       mStatus err;
+       DNSServiceRegistration *x = DNSServiceRegistrationList;
+       ResourceRecord *rr;
+       RData *newrdata;
+       int size = sizeof(RDataBody);
+       if (size < data_len)
+               size = data_len;
+
+       // Find this registered service
+       while (x && x->ClientMachPort != client) x = x->next;
+       if (!x)
+               {
+               debugf("provide_DNSServiceRegistrationUpdateRecord_rpc bad client %X", client);
+               return(mStatus_BadReferenceErr);
+               }
+       
+       // Find the record we're updating
+       if (!reference) // NULL reference means update the primary TXT record
+               rr = &x->s.RR_TXT;
+       else                    // Else, scan our list to make sure we're updating a valid record that was previously added
+               {
+               ExtraResourceRecord *e = x->s.Extras;
+               while (e && e != (ExtraResourceRecord*)reference) e = e->next;
+               if (!e)
+                       {
+                       debugf("provide_DNSServiceRegistrationUpdateRecord_rpc failed to find record %X", reference);
+                       return(mStatus_BadReferenceErr);
+                       }
+               rr = &e->r;
+               }
+
+       // Allocate storage for our new data
+       newrdata = mallocL("RData", sizeof(*newrdata) - sizeof(RDataBody) + size);
+       if (!newrdata) return(mStatus_NoMemoryErr);
+
+       // Fill in new length, and data
+       newrdata->MaxRDLength = size;
+       newrdata->RDLength    = data_len;
+       memcpy(&newrdata->u, data, data_len);
+       
+       // And update our record
+       err = mDNS_Update(&mDNSStorage, rr, ttl, newrdata, UpdateCallback);
+       if (err)
+               {
+               debugf("Received a request to update the record of length: %d for reference: %X; failed %d",
+                       data_len, reference, err);
+               return(err);
+               }
+
+       debugf("Received a request to update the record of length: %d for reference: %X", data_len, reference);
+       return(err);
+       }
+
+mDNSexport kern_return_t provide_DNSServiceRegistrationRemoveRecord_rpc(mach_port_t unusedserver, mach_port_t client,
+       natural_t reference)
+       {
+       mStatus err;
+       DNSServiceRegistration *x = DNSServiceRegistrationList;
+       ExtraResourceRecord *extra = (ExtraResourceRecord*)reference;
+       
+       // Find this registered service
+       while (x && x->ClientMachPort != client) x = x->next;
+       if (!x)
+               {
+               LogErrorMessage("DNSServiceRegistrationRemoveRecord Client %5d not found", client);
+               debugf("provide_DNSServiceRegistrationRemoveRecord_rpc bad client %X", client);
+               return(mStatus_BadReferenceErr);
+               }
+
+       err = mDNS_RemoveRecordFromService(&mDNSStorage, &x->s, extra);
+       if (err)
+               {
+               LogErrorMessage("DNSServiceRegistrationRemoveRecord Client %5d does not have record %X", client, extra);
+               debugf("Received a request to remove the record of reference: %X (failed %d)", extra, err);
+               return(err);
+               }
+
+       debugf("Received a request to remove the record of reference: %X", extra);
+       if (extra->r.rdata != &extra->r.rdatastorage)
+               freeL("Extra RData", extra->r.rdata);
+       freeL("ExtraResourceRecord", extra);
+       return(err);
+       }
+
+//*************************************************************************************************************
+// Support Code
+
+mDNSlocal void DNSserverCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
+       {
+       mig_reply_error_t *request = msg;
+       mig_reply_error_t *reply;
+       mach_msg_return_t mr;
+       int               options;
+
+       /* allocate a reply buffer */
+       reply = CFAllocatorAllocate(NULL, provide_DNSServiceDiscoveryRequest_subsystem.maxsize, 0);
+
+       /* call the MiG server routine */
+       (void) DNSServiceDiscoveryRequest_server(&request->Head, &reply->Head);
+
+       if (!(reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX) && (reply->RetCode != KERN_SUCCESS))
+               {
+        if (reply->RetCode == MIG_NO_REPLY)
+                       {
+            /*
+             * This return code is a little tricky -- it appears that the
+             * demux routine found an error of some sort, but since that
+             * error would not normally get returned either to the local
+             * user or the remote one, we pretend it's ok.
+             */
+            CFAllocatorDeallocate(NULL, reply);
+            return;
+                       }
+
+        /*
+         * destroy any out-of-line data in the request buffer but don't destroy
+         * the reply port right (since we need that to send an error message).
+         */
+        request->Head.msgh_remote_port = MACH_PORT_NULL;
+        mach_msg_destroy(&request->Head);
+               }
+
+    if (reply->Head.msgh_remote_port == MACH_PORT_NULL)
+               {
+        /* no reply port, so destroy the reply */
+        if (reply->Head.msgh_bits & MACH_MSGH_BITS_COMPLEX)
+            mach_msg_destroy(&reply->Head);
+        CFAllocatorDeallocate(NULL, reply);
+        return;
+               }
+
+    /*
+     * send reply.
+     *
+     * We don't want to block indefinitely because the client
+     * isn't receiving messages from the reply port.
+     * If we have a send-once right for the reply port, then
+     * this isn't a concern because the send won't block.
+     * If we have a send right, we need to use MACH_SEND_TIMEOUT.
+     * To avoid falling off the kernel's fast RPC path unnecessarily,
+     * we only supply MACH_SEND_TIMEOUT when absolutely necessary.
+     */
+
+    options = MACH_SEND_MSG;
+    if (MACH_MSGH_BITS_REMOTE(reply->Head.msgh_bits) == MACH_MSG_TYPE_MOVE_SEND_ONCE)
+        options |= MACH_SEND_TIMEOUT;
+
+    mr = mach_msg(&reply->Head,                /* msg */
+                     options,                  /* option */
+                     reply->Head.msgh_size,    /* send_size */
+                     0,                        /* rcv_size */
+                     MACH_PORT_NULL,           /* rcv_name */
+                     MACH_MSG_TIMEOUT_NONE,    /* timeout */
+                     MACH_PORT_NULL);          /* notify */
+
+    /* Has a message error occurred? */
+    switch (mr)
+               {
+        case MACH_SEND_INVALID_DEST:
+        case MACH_SEND_TIMED_OUT:
+            /* the reply can't be delivered, so destroy it */
+            mach_msg_destroy(&reply->Head);
+            break;
+
+        default :
+            /* Includes success case.  */
+            break;
+               }
+
+    CFAllocatorDeallocate(NULL, reply);
+       }
+
+mDNSlocal kern_return_t registerBootstrapService()
+       {
+       kern_return_t status;
+       mach_port_t service_send_port, service_rcv_port;
+
+       debugf("Registering Bootstrap Service");
+
+       /*
+        * See if our service name is already registered and if we have privilege to check in.
+        */
+       status = bootstrap_check_in(bootstrap_port, (char*)kmDNSBootstrapName, &service_rcv_port);
+       if (status == KERN_SUCCESS)
+               {
+               /*
+                * If so, we must be a followup instance of an already defined server.  In that case,
+                * the bootstrap port we inherited from our parent is the server's privilege port, so set
+                * that in case we have to unregister later (which requires the privilege port).
+                */
+               server_priv_port = bootstrap_port;
+               restarting_via_mach_init = TRUE;
+               }
+       else if (status == BOOTSTRAP_UNKNOWN_SERVICE)
+               {
+               status = bootstrap_create_server(bootstrap_port, "/usr/sbin/mDNSResponder", getuid(),
+                       FALSE /* relaunch immediately, not on demand */, &server_priv_port);
+               if (status != KERN_SUCCESS) return status;
+
+               status = bootstrap_create_service(server_priv_port, (char*)kmDNSBootstrapName, &service_send_port);
+               if (status != KERN_SUCCESS)
+                       {
+                       mach_port_deallocate(mach_task_self(), server_priv_port);
+                       return status;
+                       }
+
+               status = bootstrap_check_in(server_priv_port, (char*)kmDNSBootstrapName, &service_rcv_port);
+               if (status != KERN_SUCCESS)
+                       {
+                       mach_port_deallocate(mach_task_self(), server_priv_port);
+                       mach_port_deallocate(mach_task_self(), service_send_port);
+                       return status;
+                       }
+               assert(service_send_port == service_rcv_port);
+               }
+
+       /*
+        * We have no intention of responding to requests on the service port.  We are not otherwise
+        * a Mach port-based service.  We are just using this mechanism for relaunch facilities.
+        * So, we can dispose of all the rights we have for the service port.  We don't destroy the
+        * send right for the server's privileged bootstrap port - in case we have to unregister later.
+        */
+       mach_port_destroy(mach_task_self(), service_rcv_port);
+       return status;
+       }
+
+mDNSlocal kern_return_t destroyBootstrapService()
+       {
+       debugf("Destroying Bootstrap Service");
+       return bootstrap_register(server_priv_port, (char*)kmDNSBootstrapName, MACH_PORT_NULL);
+       }
+
+mDNSlocal void ExitCallback(CFMachPortRef port, void *msg, CFIndex size, void *info)
+       {
+       debugf("ExitCallback: destroyBootstrapService");
+       if (!debug_mode)
+               destroyBootstrapService();
+
+       debugf("ExitCallback: Aborting MIG clients");
+       while (DNSServiceDomainEnumerationList) AbortClient(DNSServiceDomainEnumerationList->ClientMachPort);
+       while (DNSServiceBrowserList)           AbortClient(DNSServiceBrowserList->ClientMachPort);
+       while (DNSServiceResolverList)          AbortClient(DNSServiceResolverList->ClientMachPort);
+       while (DNSServiceRegistrationList)      AbortClient(DNSServiceRegistrationList->ClientMachPort);
+
+       debugf("ExitCallback: mDNS_Close");
+       mDNS_Close(&mDNSStorage);
+       exit(0);
+       }
+
+mDNSlocal kern_return_t start(const char *bundleName, const char *bundleDir)
+       {
+       mStatus            err;
+       CFRunLoopTimerContext myCFRunLoopTimerContext = { 0, &mDNSStorage, NULL, NULL, NULL };
+       CFMachPortRef      d_port = CFMachPortCreate(NULL, ClientDeathCallback, NULL, NULL);
+       CFMachPortRef      s_port = CFMachPortCreate(NULL, DNSserverCallback, NULL, NULL);
+       CFMachPortRef      e_port = CFMachPortCreate(NULL, ExitCallback, NULL, NULL);
+       mach_port_t        m_port = CFMachPortGetPort(s_port);
+       kern_return_t      status = bootstrap_register(bootstrap_port, DNS_SERVICE_DISCOVERY_SERVER, m_port);
+       CFRunLoopSourceRef d_rls  = CFMachPortCreateRunLoopSource(NULL, d_port, 0);
+       CFRunLoopSourceRef s_rls  = CFMachPortCreateRunLoopSource(NULL, s_port, 0);
+       CFRunLoopSourceRef e_rls  = CFMachPortCreateRunLoopSource(NULL, e_port, 0);
+       
+       if (status)
+               {
+               if (status == 1103)
+                       LogErrorMessage("Bootstrap_register failed(): A copy of the daemon is apparently already running");
+               else
+                       LogErrorMessage("Bootstrap_register failed(): %s %d", mach_error_string(status), status);
+               return(status);
+               }
+
+       // Note: Every CFRunLoopTimer has to be created with an initial fire time, and a repeat interval, or it becomes
+       // a one-shot timer and you can't use CFRunLoopTimerSetNextFireDate(timer, when) to schedule subsequent firings.
+       // Here we create it with an initial fire time 24 hours from now, and a repeat interval of 24 hours, with
+       // the intention that we'll actually reschedule it using CFRunLoopTimerSetNextFireDate(timer, when) as necessary.
+       DeliverInstanceTimer = CFRunLoopTimerCreate(kCFAllocatorDefault,
+                                                       CFAbsoluteTimeGetCurrent() + 24.0*60.0*60.0, 24.0*60.0*60.0,
+                                                       0, // no flags
+                                                       9, // low priority execution (after all packets, etc., have been handled).
+                                                       DeliverInstanceTimerCallBack, &myCFRunLoopTimerContext);
+       if (!DeliverInstanceTimer) return(-1);
+       CFRunLoopAddTimer(CFRunLoopGetCurrent(), DeliverInstanceTimer, kCFRunLoopDefaultMode);
+       
+       err = mDNS_Init(&mDNSStorage, &PlatformStorage, rrcachestorage, RR_CACHE_SIZE, NULL, NULL);
+       if (err) { LogErrorMessage("Daemon start: mDNS_Init failed %ld", err); return(err); }
+
+       client_death_port = CFMachPortGetPort(d_port);
+       exit_m_port = CFMachPortGetPort(e_port);
+
+       CFRunLoopAddSource(CFRunLoopGetCurrent(), d_rls, kCFRunLoopDefaultMode);
+       CFRunLoopAddSource(CFRunLoopGetCurrent(), s_rls, kCFRunLoopDefaultMode);
+       CFRunLoopAddSource(CFRunLoopGetCurrent(), e_rls, kCFRunLoopDefaultMode);
+       CFRelease(d_rls);
+       CFRelease(s_rls);
+       CFRelease(e_rls);
+       if (debug_mode) printf("Service registered with Mach Port %d\n", m_port);
+
+       return(err);
+       }
+
+mDNSlocal void HandleSIG(int signal)
+       {
+       debugf("");
+       debugf("HandleSIG");
+       
+       // Send a mach_msg to ourselves (since that is signal safe) telling us to cleanup and exit
+       mach_msg_return_t msg_result;
+       mach_msg_header_t header;
+
+       header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_MAKE_SEND, 0);
+       header.msgh_remote_port = exit_m_port;
+       header.msgh_local_port = MACH_PORT_NULL;
+       header.msgh_size = sizeof(header);
+       header.msgh_id = 0;
+
+       msg_result = mach_msg_send(&header);
+       }
+
+mDNSexport int main(int argc, char **argv)
+       {
+       int i;
+       kern_return_t status;
+       FILE *fp;
+
+       for (i=1; i<argc; i++)
+               {
+               if (!strcmp(argv[i], "-d")) debug_mode = 1;
+               }
+
+       signal(SIGINT, HandleSIG);      // SIGINT is what you get for a Ctrl-C
+       signal(SIGTERM, HandleSIG);
+
+       // Register the server with mach_init for automatic restart only during debug mode
+    if (!debug_mode)
+               registerBootstrapService();
+
+       if (!debug_mode && !restarting_via_mach_init)
+               exit(0); /* mach_init will restart us immediately as a daemon */
+
+       fp = fopen(PID_FILE, "w");
+       if (fp != NULL)
+               {
+               fprintf(fp, "%d\n", getpid());
+               fclose(fp);
+               }
+       
+       LogErrorMessage("mDNSResponder (%s %s) starting", __DATE__, __TIME__);
+       status = start(NULL, NULL);
+
+       if (status == 0)
+               {
+               CFRunLoopRun();
+               LogErrorMessage("CFRunLoopRun Exiting. This is bad.");
+               mDNS_Close(&mDNSStorage);
+               }
+
+       destroyBootstrapService();
+
+       return(status);
+       }
diff --git a/mDNSCore/mDNS.c b/mDNSCore/mDNS.c
new file mode 100755 (executable)
index 0000000..fc678e0
--- /dev/null
@@ -0,0 +1,3890 @@
+// ***************************************************************************
+// mDNS.c
+// This file defines all of mDNS, including
+// mDNS Service Discovery, mDNS Responder, and mDNS Searcher.
+//
+// This code is completely 100% portable C. It does not depend on any external header files
+// from outside the mDNS project -- all the types it expects to find are defined right here.
+//
+// The previous point is very important: This file does not depend on any external
+// header files. It should complile on *any* platform that has a C compiler, without
+// making *any* assumptions about availability of so-called "standard" C functions,
+// routines, or types (which may or may not be present on any given platform).
+// ***************************************************************************
+
+/*
+ * 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.)
+ */
+
+#include "mDNSClientAPI.h"                             // Defines the interface provided to the client layer above
+#include "mDNSPlatformFunctions.h"             // Defines the interface required of the supporting layer below
+#include "mDNSsprintf.h"
+
+#if(defined(_MSC_VER))
+       // Disable warnings about Microsoft Visual Studio/C++ not understanding "pragma unused"
+    #pragma warning( disable:4068 )
+#endif
+
+// ***************************************************************************
+#if 0
+#pragma mark - DNS Protocol Constants
+#endif
+
+typedef enum
+       {
+       kDNSFlag0_QR_Mask     = 0x80,           // Query or response?
+       kDNSFlag0_QR_Query    = 0x00,
+       kDNSFlag0_QR_Response = 0x80,
+       
+       kDNSFlag0_OP_Mask     = 0x78,           // Operation type
+       kDNSFlag0_OP_StdQuery = 0x00,
+       kDNSFlag0_OP_Iquery   = 0x08,
+       kDNSFlag0_OP_Status   = 0x10,
+       kDNSFlag0_OP_Unused3  = 0x18,
+       kDNSFlag0_OP_Notify   = 0x20,
+       kDNSFlag0_OP_Update   = 0x28,
+       
+       kDNSFlag0_QROP_Mask   = kDNSFlag0_QR_Mask | kDNSFlag0_OP_Mask,
+       
+       kDNSFlag0_AA          = 0x04,           // Authoritative Answer?
+       kDNSFlag0_TC          = 0x02,           // Truncated?
+       kDNSFlag0_RD          = 0x01,           // Recursion Desired?
+       kDNSFlag1_RA          = 0x80,           // Recursion Available?
+       
+       kDNSFlag1_Zero        = 0x40,           // Reserved; must be zero
+       kDNSFlag1_AD          = 0x20,           // Authentic Data [RFC 2535]
+       kDNSFlag1_CD          = 0x10,           // Checking Disabled [RFC 2535]
+
+       kDNSFlag1_RC          = 0x0F,           // Response code
+       kDNSFlag1_RC_NoErr    = 0x00,
+       kDNSFlag1_RC_FmtErr   = 0x01,
+       kDNSFlag1_RC_SrvErr   = 0x02,
+       kDNSFlag1_RC_NXDomain = 0x03,
+       kDNSFlag1_RC_NotImpl  = 0x04,
+       kDNSFlag1_RC_Refused  = 0x05,
+       kDNSFlag1_RC_YXDomain = 0x06,
+       kDNSFlag1_RC_YXRRSet  = 0x07,
+       kDNSFlag1_RC_NXRRSet  = 0x08,
+       kDNSFlag1_RC_NotAuth  = 0x09,
+       kDNSFlag1_RC_NotZone  = 0x0A
+       } DNS_Flags;
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - Program Constants
+#endif
+
+mDNSexport const ResourceRecord zeroRR = { 0 };
+mDNSexport const mDNSIPPort zeroIPPort = { { 0 } };
+mDNSexport const mDNSIPAddr zeroIPAddr = { { 0 } };
+mDNSexport const mDNSIPAddr onesIPAddr = { { 255, 255, 255, 255 } };
+
+#define UnicastDNSPortAsNumber 53
+#define MulticastDNSPortAsNumber 5353
+mDNSexport const mDNSIPPort UnicastDNSPort     = { { UnicastDNSPortAsNumber   >> 8, UnicastDNSPortAsNumber   & 0xFF } };
+mDNSexport const mDNSIPPort MulticastDNSPort   = { { MulticastDNSPortAsNumber >> 8, MulticastDNSPortAsNumber & 0xFF } };
+mDNSexport const mDNSIPAddr AllDNSLinkGroup  = { { 224,   0,   0, 251 } };
+mDNSexport const mDNSIPAddr AllDNSAdminGroup = { { 239, 255, 255, 251 } };
+
+static const mDNSOpaque16 zeroID = { { 0, 0 } };
+static const mDNSOpaque16 QueryFlags    = { { kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery,                0 } };
+static const mDNSOpaque16 ResponseFlags = { { kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery | kDNSFlag0_AA, 0 } };
+#define zeroDomainNamePtr ((domainname*)"")
+
+static const char *const mDNS_DomainTypeNames[] =
+       {
+       "_browse._mdns._udp.local.",
+       "_default._browse._mdns._udp.local.",
+       "_register._mdns._udp.local.",
+       "_default._register._mdns._udp.local."
+       };
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - General Utility Functions
+#endif
+
+#if DEBUGBREAKS
+mDNSlocal char *DNSTypeName(mDNSu16 rrtype)
+       {
+       switch (rrtype)
+               {
+               case kDNSType_A:        return("Address");
+               case kDNSType_CNAME:return("CNAME");
+               case kDNSType_PTR:      return("PTR");
+               case kDNSType_TXT:  return("TXT");
+               case kDNSType_SRV:      return("SRV");
+               default:                        {
+                                                       static char buffer[16];
+                                                       mDNS_sprintf(buffer, "(%d)", rrtype);
+                                                       return(buffer);
+                                                       }
+               }
+       }
+#endif
+
+mDNSlocal mDNSu32 mDNSRandom(mDNSu32 max)
+       {
+       static mDNSu32 seed = 1;
+       mDNSu32 mask = 1;
+       while (mask < max) mask = (mask << 1) | 1;
+       do seed = seed * 21 + 1; while ((seed & mask) > max);
+       return (seed & mask);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - Domain Name Utility Functions
+#endif
+
+// Returns length of a domain name INCLUDING the byte for the final null label
+// i.e. for the root label "." it returns one
+// For the FQDN "com." it returns 5 (length, three data bytes, final zero)
+mDNSexport mDNSu32 DomainNameLength(const domainname *const name)
+       {
+       const mDNSu8 *src = name->c;
+       while (*src)
+               {
+               if (*src > MAX_DOMAIN_LABEL) return(MAX_DOMAIN_NAME+1);
+               src += 1 + *src;
+               if (src - name->c >= MAX_DOMAIN_NAME) return(MAX_DOMAIN_NAME+1);
+               }
+       return((mDNSu32)(src - name->c + 1));
+       }
+
+mDNSlocal mDNSBool SameDomainLabel(const mDNSu8 *a, const mDNSu8 *b)
+       {
+       int i;
+       const int len = *a++;
+
+       if (len > MAX_DOMAIN_LABEL)
+               { debugf("Malformed label (too long)"); return(mDNSfalse); }
+
+       if (len != *b++) return(mDNSfalse);
+       for (i=0; i<len; i++)
+               {
+               mDNSu8 ac = *a++;
+               mDNSu8 bc = *b++;
+               if (ac >= 'A' && ac <= 'Z') ac += 'a' - 'A';
+               if (bc >= 'A' && bc <= 'Z') bc += 'a' - 'A';
+               if (ac != bc) return(mDNSfalse);
+               }
+       return(mDNStrue);
+       }
+
+mDNSexport mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2)
+       {
+       const mDNSu8 *      a   = d1->c;
+       const mDNSu8 *      b   = d2->c;
+       const mDNSu8 *const max = d1->c + MAX_DOMAIN_NAME;                      // Maximum that's valid
+
+       while (*a || *b)
+               {
+               if (a + 1 + *a >= max)
+                       { debugf("Malformed domain name (more than 255 characters)"); return(mDNSfalse); }
+               if (!SameDomainLabel(a, b)) return(mDNSfalse);
+               a += 1 + *a;
+               b += 1 + *b;
+               }
+       
+       return(mDNStrue);
+       }
+
+// CompressedDomainNameLength returns the length of a domain name INCLUDING the byte
+// for the final null label i.e. for the root label "." it returns one.
+// E.g. for the FQDN "foo.com." it returns 9
+// (length, three data bytes, length, three more data bytes, final zero).
+// In the case where a parent domain name is provided, and the given name is a child
+// of that parent, CompressedDomainNameLength returns the length of the prefix portion
+// of the child name, plus TWO bytes for the compression pointer.
+// E.g. for the name "foo.com." with parent "com.", it returns 6
+// (length, three data bytes, two-byte compression pointer).
+mDNSlocal mDNSu32 CompressedDomainNameLength(const domainname *const name, const domainname *parent)
+       {
+       const mDNSu8 *src = name->c;
+       if (parent && parent->c[0] == 0) parent = mDNSNULL;
+       while (*src)
+               {
+               if (*src > MAX_DOMAIN_LABEL) return(MAX_DOMAIN_NAME+1);
+               if (parent && SameDomainName((domainname *)src, parent)) return((mDNSu32)(src - name->c + 2));
+               src += 1 + *src;
+               if (src - name->c >= MAX_DOMAIN_NAME) return(MAX_DOMAIN_NAME+1);
+               }
+       return((mDNSu32)(src - name->c + 1));
+       }
+
+mDNSexport void AppendDomainLabelToName(domainname *const name, const domainlabel *const label)
+       {
+       int i;
+       mDNSu8 *ptr = name->c + DomainNameLength(name) - 1;
+       const mDNSu8 *const lim = name->c + MAX_DOMAIN_NAME;
+       if (ptr + 1 + label->c[0] + 1 >= lim) return;
+       for (i=0; i<=label->c[0]; i++) *ptr++ = label->c[i];
+       *ptr++ = 0;                                                                             // Put the null root label on the end
+       }
+
+// AppendStringLabelToName appends a single label to an existing (possibly empty) domainname.
+// The C string contains the label as-is, with no escaping, etc.
+// Any dots in the name are literal dots, not label separators
+mDNSexport void AppendStringLabelToName(domainname *const name, const char *cstr)
+       {
+       mDNSu8 *lengthbyte;
+       mDNSu8 *ptr = name->c + DomainNameLength(name) - 1;
+       const mDNSu8 *lim = name->c + MAX_DOMAIN_NAME - 1;
+       if (lim > ptr + MAX_DOMAIN_LABEL + 1)
+               lim = ptr + MAX_DOMAIN_LABEL + 1;
+       lengthbyte = ptr++;
+       while (*cstr && ptr < lim) *ptr++ = (mDNSu8)*cstr++;
+       *lengthbyte = (mDNSu8)(ptr - lengthbyte - 1);
+       *ptr++ = 0;                                                                             // Put the null root label on the end
+       }
+
+mDNSexport void AppendDomainNameToName(domainname *const name, const domainname *const append)
+       {
+       int i;
+       mDNSu8 *ptr = name->c + DomainNameLength(name) - 1;
+       const mDNSu8 *src = append->c;
+       const mDNSu8 *const lim = name->c + MAX_DOMAIN_NAME;
+       while(src[0])
+               {
+               if (ptr + 1 + src[0] + 1 >= lim) return;
+               for (i=0; i<=src[0]; i++) *ptr++ = src[i];
+               *ptr = 0;       // Put the null root label on the end
+               src += i;
+               }
+       }
+
+// AppendStringNameToName appends zero or more labels to an existing (possibly empty) domainname.
+// The C string contains the labels separated by dots, but otherwise as-is, with no escaping, etc.
+mDNSexport void AppendStringNameToName(domainname *const name, const char *cstr)
+       {
+       mDNSu8 *ptr = name->c + DomainNameLength(name) - 1;                     // Find end of current name
+       const mDNSu8 *const lim = name->c + MAX_DOMAIN_NAME - 1;                // Find limit of how much we can add
+       while (*cstr)
+               {
+               mDNSu8 *const lengthbyte = ptr++;
+               const mDNSu8 *const lim2 = ptr + MAX_DOMAIN_LABEL;
+               const mDNSu8 *const lim3 = (lim < lim2) ? lim : lim2;
+               while (*cstr && *cstr != '.' && ptr < lim3) *ptr++ = (mDNSu8)*cstr++;
+               *lengthbyte = (mDNSu8)(ptr - lengthbyte - 1);
+               if (*cstr == '.') cstr++;
+               }
+       
+       *ptr++ = 0;                                                                             // Put the null root label on the end
+       }
+
+//#define IsThreeDigit(X) (IsDigit((X)[1]) && IsDigit((X)[2]) && IsDigit((X)[3]))
+//#define ValidEscape(X) (X)[0] == '\\' && ((X)[1] == '\\' || (X)[1] == '\\' || IsThreeDigit(X))
+
+#define mdnsIsLetter(X) (((X) >= 'A' && (X) <= 'Z') || ((X) >= 'a' && (X) <= 'z'))
+#define mdnsIsDigit(X) (((X) >= '0' && (X) <= '9'))
+#define mdnsValidHostChar(X, notfirst, notlast) (mdnsIsLetter(X) || \
+       ((notfirst) && (mdnsIsDigit(X) || ((notlast) && (X) == '-'))) )
+
+mDNSexport void ConvertCStringToDomainLabel(const char *src, domainlabel *label)
+       {
+       mDNSu8       *      ptr   = label->c + 1;                                       // Where we're putting it
+       const mDNSu8 *const limit = ptr + MAX_DOMAIN_LABEL;                     // The maximum we can put
+       while (*src && ptr < limit)                                                                     // While we have characters in the label...
+               {
+               mDNSu8 c = (mDNSu8)*src++;                                                              // Read the character
+               if (c == '\\')                                                                                  // If escape character, check next character
+                       {
+                       if (*src == '\\' || *src == '.')                                        // If a second escape, or a dot,
+                               c = (mDNSu8)*src++;                                                             // just use the second character
+                       else if (mdnsIsDigit(src[0]) && mdnsIsDigit(src[1]) && mdnsIsDigit(src[2]))
+                               {                                                                                               // else, if three decimal digits,
+                               int v0 = src[0] - '0';                                                  // then interpret as three-digit decimal
+                               int v1 = src[1] - '0';
+                               int v2 = src[2] - '0';
+                               int val = v0 * 100 + v1 * 10 + v2;
+                               if (val <= 255) { c = (mDNSu8)val; src += 3; }  // If valid value, use it
+                               }
+                       }
+               *ptr++ = c;                                                                                             // Write the character
+               }
+       label->c[0] = (mDNSu8)(ptr - label->c - 1);
+       }
+
+mDNSexport mDNSu8 *ConvertCStringToDomainName(const char *const cstr, domainname *name)
+       {
+       const mDNSu8 *src         = (const mDNSu8 *)cstr;                                       // C string we're reading
+       mDNSu8       *ptr         = name->c;                                                            // Where we're putting it
+       const mDNSu8 *const limit = ptr + MAX_DOMAIN_NAME;                              // The maximum we can put
+
+       while (*src && ptr < limit)                                                                             // While more characters, and space to put them...
+               {
+               mDNSu8 *lengthbyte = ptr++;                                                                     // Record where the length is going to go
+               while (*src && *src != '.' && ptr < limit)                                      // While we have characters in the label...
+                       {
+                       mDNSu8 c = *src++;                                                                              // Read the character
+                       if (c == '\\')                                                                                  // If escape character, check next character
+                               {
+                               if (*src == '\\' || *src == '.')                                        // If a second escape, or a dot,
+                                       c = *src++;                                                                             // just use the second character
+                               else if (mdnsIsDigit(src[0]) && mdnsIsDigit(src[1]) && mdnsIsDigit(src[2]))
+                                       {                                                                                               // else, if three decimal digits,
+                                       int v0 = src[0] - '0';                                          // then interpret as three-digit decimal
+                                       int v1 = src[1] - '0';
+                                       int v2 = src[2] - '0';
+                                       int val = v0 * 100 + v1 * 10 + v2;
+                                       if (val <= 255) { c = (mDNSu8)val; src += 3; }  // If valid value, use it
+                                       }
+                               }
+                       *ptr++ = c;                                                                                             // Write the character
+                       }
+               if (*src) src++;                                                                                        // Skip over the trailing dot (if present)
+               if (ptr - lengthbyte - 1 > MAX_DOMAIN_LABEL) return(mDNSNULL);  // If illegal label, abort
+               *lengthbyte = (mDNSu8)(ptr - lengthbyte - 1);
+               }
+
+       if (ptr < limit)                                                                                                // If we didn't run out of space
+               {
+               *ptr++ = 0;                                                                                                     // Put the final root label
+               return(ptr);                                                                                            // and return
+               }
+
+       return(mDNSNULL);
+       }
+
+//#define convertCstringtodomainname(C,D)        convertCstringtodomainname_withescape((C), (D), -1)
+//#define convertescapedCstringtodomainname(C,D) convertCstringtodomainname_withescape((C), (D), '\\')
+
+mDNSexport char *ConvertDomainLabelToCString_withescape(const domainlabel *const label, char *ptr, char esc)
+       {
+       const mDNSu8 *      src = label->c;                                                     // Domain label we're reading
+       const mDNSu8        len = *src++;                                                       // Read length of this (non-null) label
+       const mDNSu8 *const end = src + len;                                                    // Work out where the label ends
+       if (len > MAX_DOMAIN_LABEL) return(mDNSNULL);                                   // If illegal label, abort
+       while (src < end)                                                                                       // While we have characters in the label
+               {
+               mDNSu8 c = *src++;
+               if (esc)
+                       {
+                       if (c == '.')                                                                           // If character is a dot,
+                               *ptr++ = esc;                                                                   // Output escape character
+                       else if (c <= ' ')                                                                      // If non-printing ascii,
+                               {                                                                                               // Output decimal escape sequence
+                               *ptr++ = esc;
+                               *ptr++ = (char) ('0' + (c / 100)     );
+                               *ptr++ = (char) ('0' + (c /  10) % 10);
+                               c      = (mDNSu8)('0' + (c      ) % 10);
+                               }
+                       }
+               *ptr++ = (char)c;                                                                               // Copy the character
+               }
+       *ptr = 0;                                                                                                       // Null-terminate the string
+       return(ptr);                                                                                            // and return
+       }
+
+// Note, to guarantee that there will be no possible overrun, cstr must be at least 1005 bytes
+// The longest legal domain name is 255 bytes, in the form of three 64-byte labels, one 62-byte label,
+// and the null root label.
+// If every label character has to be escaped as a four-byte escape sequence, the maximum textual
+// ascii display of this is 63*4 + 63*4 + 63*4 + 61*4 = 1000 label characters,
+// plus four dots and the null at the end of the C string = 1005
+mDNSexport char *ConvertDomainNameToCString_withescape(const domainname *const name, char *ptr, char esc)
+       {
+       const mDNSu8 *src         = name->c;                                                            // Domain name we're reading
+       const mDNSu8 *const max   = name->c + MAX_DOMAIN_NAME;                  // Maximum that's valid
+       
+       if (*src == 0) *ptr++ = '.';                                                                    // Special case: For root, just write a dot
+
+       while (*src)                                                                                                    // While more characters in the domain name
+               {
+               if (src + 1 + *src >= max) return(mDNSNULL);
+               ptr = ConvertDomainLabelToCString_withescape((const domainlabel *)src, ptr, esc);
+               if (!ptr) return(mDNSNULL);
+               src += 1 + *src;
+               *ptr++ = '.';                                                                                           // Write the dot after the label
+               }
+
+       *ptr++ = 0;                                                                                                             // Null-terminate the string
+       return(ptr);                                                                                                    // and return
+       }
+
+// RFC 1034 rules:
+// Host names must start with a letter, end with a letter or digit,
+// and have as interior characters only letters, digits, and hyphen.
+
+mDNSexport void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel)
+       {
+       const mDNSu8 *      src  = &UTF8Name[1];
+       const mDNSu8 *const end  = &UTF8Name[1] + UTF8Name[0];
+             mDNSu8 *      ptr  = &hostlabel->c[1];
+       const mDNSu8 *const lim  = &hostlabel->c[1] + MAX_DOMAIN_LABEL;
+       while (src < end)
+               {
+               // Delete apostrophes from source name
+               if (src[0] == '\'') { src++; continue; }                // Standard straight single quote
+               if (src + 2 < end && src[0] == 0xE2 && src[1] == 0x80 && src[2] == 0x99)
+                       { src += 3; continue; } // Unicode curly apostrophe
+               if (ptr < lim)
+                       {
+                       if (mdnsValidHostChar(*src, (ptr > &hostlabel->c[1]), (src < end-1))) *ptr++ = *src;
+                       else if (ptr > &hostlabel->c[1] && ptr[-1] != '-') *ptr++ = '-';
+                       }
+               src++;
+               }
+       while (ptr > &hostlabel->c[1] && ptr[-1] == '-') ptr--; // Truncate trailing '-' marks
+       hostlabel->c[0] = (mDNSu8)(ptr - &hostlabel->c[1]);
+       }
+
+mDNSexport mDNSu8 *ConstructServiceName(domainname *const fqdn,
+       const domainlabel *const name, const domainname *const type, const domainname *const domain)
+       {
+       int i, len;
+       mDNSu8 *dst = fqdn->c;
+       mDNSu8 *max = fqdn->c + MAX_DOMAIN_NAME;
+       const mDNSu8 *src;
+
+       if (name)
+               {
+               src = name->c;                                                                  // Put the service name into the domain name
+               len = *src;
+               if (len >= 0x40) { debugf("ConstructServiceName: service name too long"); return(0); }
+               for (i=0; i<=len; i++) *dst++ = *src++;
+               }
+       
+       src = type->c;                                                                          // Put the service type into the domain name
+       len = *src;
+       if (len == 0 || len >= 0x40)  { debugf("ConstructServiceName: Invalid service name"); return(0); }
+       if (dst + 1 + len + 1 >= max) { debugf("ConstructServiceName: service type too long"); return(0); }
+       for (i=0; i<=len; i++) *dst++ = *src++;
+
+       len = *src;
+       if (len == 0 || len >= 0x40)  { debugf("ConstructServiceName: Invalid service name"); return(0); }
+       if (dst + 1 + len + 1 >= max) { debugf("ConstructServiceName: service type too long"); return(0); }
+       for (i=0; i<=len; i++) *dst++ = *src++;
+       
+       if (*src) { debugf("ConstructServiceName: Service type must have only two labels"); return(0); }
+
+       src = domain->c;                                                                        // Put the service domain into the domain name
+       while (*src)
+               {
+               len = *src;
+               if (dst + 1 + len + 1 >= max)
+                       { debugf("ConstructServiceName: service domain too long"); return(0); }
+               for (i=0; i<=len; i++) *dst++ = *src++;
+               }
+       
+       *dst++ = 0;             // Put the null root label on the end
+       return(dst);
+       }
+
+mDNSexport mDNSBool DeconstructServiceName(const domainname *const fqdn,
+       domainlabel *const name, domainname *const type, domainname *const domain)
+       {
+       int i, len;
+       const mDNSu8 *src = fqdn->c;
+       const mDNSu8 *max = fqdn->c + MAX_DOMAIN_NAME;
+       mDNSu8 *dst;
+       
+       dst = name->c;                                                                          // Extract the service name from the domain name
+       len = *src;
+       if (len >= 0x40) { debugf("DeconstructServiceName: service name too long"); return(mDNSfalse); }
+       for (i=0; i<=len; i++) *dst++ = *src++;
+       
+       dst = type->c;                                                                          // Extract the service type from the domain name
+       len = *src;
+       if (len >= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse); }
+       for (i=0; i<=len; i++) *dst++ = *src++;
+
+       len = *src;
+       if (len >= 0x40) { debugf("DeconstructServiceName: service type too long"); return(mDNSfalse); }
+       for (i=0; i<=len; i++) *dst++ = *src++;
+       *dst++ = 0;             // Put the null root label on the end of the service type
+
+       dst = domain->c;                                                                        // Extract the service domain from the domain name
+       while (*src)
+               {
+               len = *src;
+               if (len >= 0x40)
+                       { debugf("DeconstructServiceName: service domain label too long"); return(mDNSfalse); }
+               if (src + 1 + len + 1 >= max)
+                       { debugf("DeconstructServiceName: service domain too long"); return(mDNSfalse); }
+               for (i=0; i<=len; i++) *dst++ = *src++;
+               }
+       *dst++ = 0;             // Put the null root label on the end
+       
+       return(mDNStrue);
+       }
+
+mDNSlocal void IncrementLabelSuffix(domainlabel *name, mDNSBool RichText)
+       {
+       long val = 0, multiplier = 1, divisor = 1, digits = 1;
+
+       // Get any existing numerical suffix off the name
+       while (mdnsIsDigit(name->c[name->c[0]]))
+               { val += (name->c[name->c[0]] - '0') * multiplier; multiplier *= 10; name->c[0]--; }
+       
+       // If existing suffix, increment it, else start by renaming "Foo" as "Foo2"
+       if (multiplier > 1 && val < 999999) val++; else val = 2;
+
+       // Can only add spaces to rich text names, not RFC 1034 names
+       if (RichText && name->c[name->c[0]] != ' ' && name->c[0] < MAX_DOMAIN_LABEL)
+               name->c[++name->c[0]] = ' ';
+       
+       while (val >= divisor * 10)
+               { divisor *= 10; digits++; }
+
+       if (name->c[0] > (mDNSu8)(MAX_DOMAIN_LABEL - digits))
+               name->c[0] = (mDNSu8)(MAX_DOMAIN_LABEL - digits);
+       
+       while (divisor)
+               {
+               name->c[++name->c[0]] = (mDNSu8)('0' + val / divisor);
+               val     %= divisor;
+               divisor /= 10;
+               }
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - Resource Record Utility Functions
+#endif
+
+#define ResourceRecordIsValidAnswer(RR) ( ((RR)->             RecordType & kDNSRecordTypeActiveMask)  && \
+               ((RR)->Additional1 == mDNSNULL || ((RR)->Additional1->RecordType & kDNSRecordTypeActiveMask)) && \
+               ((RR)->Additional2 == mDNSNULL || ((RR)->Additional2->RecordType & kDNSRecordTypeActiveMask)) && \
+               ((RR)->DependentOn == mDNSNULL || ((RR)->DependentOn->RecordType & kDNSRecordTypeActiveMask))  )
+
+#define ResourceRecordIsValidInterfaceAnswer(RR, I) \
+       (ResourceRecordIsValidAnswer(RR) && \
+       ((RR)->InterfaceAddr.NotAnInteger == 0 || (RR)->InterfaceAddr.NotAnInteger == (I).NotAnInteger))
+
+#define DefaultProbeCountForTypeUnique ((mDNSu8)3)
+
+#define DefaultAnnounceCountForTypeShared ((mDNSu8)10)
+#define DefaultAnnounceCountForTypeUnique ((mDNSu8)2)
+
+#define DefaultAnnounceCountForRecordType(X)   ((X) == kDNSRecordTypeShared   ? DefaultAnnounceCountForTypeShared : \
+                                                                                               (X) == kDNSRecordTypeUnique   ? DefaultAnnounceCountForTypeUnique : \
+                                                                                               (X) == kDNSRecordTypeVerified ? DefaultAnnounceCountForTypeUnique : (mDNSu8)0)
+
+#define DefaultSendIntervalForRecordType(X)    ((X) == kDNSRecordTypeShared   ? mDNSPlatformOneSecond   : \
+                                                                                               (X) == kDNSRecordTypeUnique   ? mDNSPlatformOneSecond/4 : \
+                                                                                               (X) == kDNSRecordTypeVerified ? mDNSPlatformOneSecond/4 : 0)
+
+#define TimeToAnnounceThisRecord(RR,time) ((RR)->AnnounceCount && time - (RR)->NextSendTime >= 0)
+#define TimeToSendThisRecord(RR,time) \
+       ((TimeToAnnounceThisRecord(RR,time) || (RR)->SendPriority) && ResourceRecordIsValidAnswer(RR))
+
+mDNSlocal mDNSBool SameRData(const mDNSu16 rrtype, const RData *const r1, const RData *const r2)
+       {
+       if (r1->RDLength != r2->RDLength) return(mDNSfalse);
+       switch(rrtype)
+               {
+               case kDNSType_CNAME:// Same as PTR
+               case kDNSType_PTR:      return(SameDomainName(&r1->u.name, &r2->u.name));
+
+               case kDNSType_SRV:      return( r1->u.srv.priority          == r2->u.srv.priority          &&
+                                                                       r1->u.srv.weight            == r2->u.srv.weight            &&
+                                                                       r1->u.srv.port.NotAnInteger == r2->u.srv.port.NotAnInteger &&
+                                                                       SameDomainName(&r1->u.srv.target, &r2->u.srv.target));
+
+               default:                        return(mDNSPlatformMemSame(r1->u.data, r2->u.data, r1->RDLength));
+               }
+       }
+
+mDNSlocal mDNSBool ResourceRecordAnswersQuestion(const ResourceRecord *const rr, const DNSQuestion *const q)
+       {
+       if (rr->InterfaceAddr.NotAnInteger &&
+               q ->InterfaceAddr.NotAnInteger &&
+               rr->InterfaceAddr.NotAnInteger != q->InterfaceAddr.NotAnInteger) return(mDNSfalse);
+
+       // RR type CNAME matches any query type. QTYPE ANY matches any RR type. QCLASS ANY matches any RR class.
+       if (rr->rrtype != kDNSType_CNAME && rr->rrtype  != q->rrtype  && q->rrtype  != kDNSQType_ANY ) return(mDNSfalse);
+       if (                                rr->rrclass != q->rrclass && q->rrclass != kDNSQClass_ANY) return(mDNSfalse);
+       return(SameDomainName(&rr->name, &q->name));
+       }
+
+// SameResourceRecordSignature returns true if two resources records have the same interface, name, type, and class.
+// -- i.e. if they would both be given in response to the same question.
+// (TTL and rdata may differ)
+mDNSlocal mDNSBool SameResourceRecordSignature(const ResourceRecord *const r1, const ResourceRecord *const r2)
+       {
+       if (!r1) { debugf("SameResourceRecordSignature ERROR: r1 is NULL"); return(mDNSfalse); }
+       if (!r2) { debugf("SameResourceRecordSignature ERROR: r2 is NULL"); return(mDNSfalse); }
+       if (r1->InterfaceAddr.NotAnInteger &&
+               r2->InterfaceAddr.NotAnInteger &&
+               r1->InterfaceAddr.NotAnInteger != r2->InterfaceAddr.NotAnInteger) return(mDNSfalse);
+       return (r1->rrtype == r2->rrtype && r1->rrclass == r2->rrclass && SameDomainName(&r1->name, &r2->name));
+       }
+
+// SameResourceRecordSignatureAnyInterface returns true if two resources records have the same name, type, and class.
+// (InterfaceAddr, TTL and rdata may differ)
+mDNSlocal mDNSBool SameResourceRecordSignatureAnyInterface(const ResourceRecord *const r1, const ResourceRecord *const r2)
+       {
+       if (!r1) { debugf("SameResourceRecordSignatureAnyInterface ERROR: r1 is NULL"); return(mDNSfalse); }
+       if (!r2) { debugf("SameResourceRecordSignatureAnyInterface ERROR: r2 is NULL"); return(mDNSfalse); }
+       return (r1->rrtype == r2->rrtype && r1->rrclass == r2->rrclass && SameDomainName(&r1->name, &r2->name));
+       }
+
+// IdenticalResourceRecord returns true if two resources records have
+// the same interface, name, type, class, and identical rdata (TTL may differ)
+mDNSlocal mDNSBool IdenticalResourceRecord(const ResourceRecord *const r1, const ResourceRecord *const r2)
+       {
+       if (!SameResourceRecordSignature(r1, r2)) return(mDNSfalse);
+       return(SameRData(r1->rrtype, r1->rdata, r2->rdata));
+       }
+
+// IdenticalResourceRecordAnyInterface returns true if two resources records have
+// the same name, type, class, and identical rdata (InterfaceAddr and TTL may differ)
+mDNSlocal mDNSBool IdenticalResourceRecordAnyInterface(const ResourceRecord *const r1, const ResourceRecord *const r2)
+       {
+       if (!SameResourceRecordSignatureAnyInterface(r1, r2)) return(mDNSfalse);
+       return(SameRData(r1->rrtype, r1->rdata, r2->rdata));
+       }
+
+// ResourceRecord *ds is the ResourceRecord from the duplicate suppression section of the query
+// This is the information that the requester believes to be correct
+// ResourceRecord *rr is the answer we are proposing to give, if not suppressed
+// This is the information that we believe to be correct
+mDNSlocal mDNSBool SuppressDuplicate(const ResourceRecord *const ds, const ResourceRecord *const rr)
+       {
+       // If RR signature is different, or data is different, then don't suppress
+       if (!IdenticalResourceRecord(ds,rr)) return(mDNSfalse);
+       
+       // If the requester's indicated TTL is less than half the real TTL,
+       // we need to give our answer before the requester's copy expires.
+       // If the requester's indicated TTL is at least half the real TTL,
+       // then we can suppress our answer this time.
+       // If the requester's indicated TTL is greater than the TTL we believe,
+       // then that's okay, and we don't need to do anything about it.
+       // (If two responders on the network are offering the same information,
+       // that's okay, and if they are offering the information with different TTLs,
+       // the one offering the lower TTL should defer to the one offering the higher TTL.)
+       return(ds->rroriginalttl >= rr->rroriginalttl / 2);
+       }
+
+mDNSlocal mDNSu32 GetRDLength(const ResourceRecord *const rr, mDNSBool estimate)
+       {
+       const domainname *const name = estimate ? &rr->name : mDNSNULL;
+       switch (rr->rrtype)
+               {
+               case kDNSType_A:        return(sizeof(rr->rdata->u.ip)); break;
+               case kDNSType_CNAME:// Same as PTR
+               case kDNSType_PTR:      return(CompressedDomainNameLength(&rr->rdata->u.name, name));
+               case kDNSType_TXT:  return(rr->rdata->RDLength); // TXT is not self-describing, so have to just trust rdlength
+               case kDNSType_SRV:      return(6 + CompressedDomainNameLength(&rr->rdata->u.srv.target, name));
+               default:                        debugf("Warning! Don't know how to get length of resource type %d", rr->rrtype);
+                                                       return(rr->rdata->RDLength);
+               }
+       }
+
+// rr is a ResourceRecord in our cache
+// (kDNSRecordTypePacketAnswer/kDNSRecordTypePacketAdditional/kDNSRecordTypePacketUniqueAns/kDNSRecordTypePacketUniqueAdd)
+mDNSlocal DNSQuestion *CacheRRActive(const mDNS *const m, ResourceRecord *rr)
+       {
+       DNSQuestion *q;
+       for (q = m->ActiveQuestions; q; q=q->next)              // Scan our list of questions
+               if (!q->DuplicateOf && ResourceRecordAnswersQuestion(rr, q))
+                       return(q);
+       return(mDNSNULL);
+       }
+
+mDNSlocal void SetTargetToHostName(const mDNS *const m, ResourceRecord *const rr)
+       {
+       switch (rr->rrtype)
+               {
+               case kDNSType_CNAME:// Same as PTR
+               case kDNSType_PTR:      rr->rdata->u.name       = m->hostname1; break;
+               case kDNSType_SRV:      rr->rdata->u.srv.target = m->hostname1; break;
+               default: debugf("SetTargetToHostName: Dont' know how to set the target of rrtype %d", rr->rrtype); break;
+               }
+       rr->rdata->RDLength = GetRDLength(rr, mDNSfalse);
+       rr->rdestimate      = GetRDLength(rr, mDNStrue);
+       
+       // If we're in the middle of probing this record, we need to start again,
+       // because changing its rdata may change the outcome of the tie-breaker.
+       if (rr->RecordType == kDNSRecordTypeUnique) rr->ProbeCount = DefaultProbeCountForTypeUnique;
+       }
+
+mDNSlocal void UpdateHostNameTargets(const mDNS *const m)
+       {
+       ResourceRecord *rr;
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               if (rr->HostTarget)
+                       SetTargetToHostName(m, rr);
+       }
+
+mDNSlocal mStatus mDNS_Register_internal(mDNS *const m, ResourceRecord *const rr, const mDNSs32 timenow)
+       {
+       ResourceRecord **p = &m->ResourceRecords;
+       while (*p && *p != rr) p=&(*p)->next;
+       if (*p)
+               {
+               debugf("Error! Tried to register a ResourceRecord that's already in the list");
+               return(mStatus_AlreadyRegistered);
+               }
+
+       if (rr->DependentOn)
+               {
+               if (rr->RecordType == kDNSRecordTypeUnique)
+                       rr->RecordType =  kDNSRecordTypeVerified;
+               else
+                       {
+                       debugf("mDNS_Register_internal: ERROR! %##s: rr->DependentOn && RecordType != kDNSRecordTypeUnique",
+                               rr->name.c);
+                       return(mStatus_Invalid);
+                       }
+               if (rr->DependentOn->RecordType != kDNSRecordTypeUnique && rr->DependentOn->RecordType != kDNSRecordTypeVerified)
+                       {
+                       debugf("mDNS_Register_internal: ERROR! %##s: rr->DependentOn->RecordType bad type %X",
+                               rr->name.c, rr->DependentOn->RecordType);
+                       return(mStatus_Invalid);
+                       }
+               }
+
+       rr->next = mDNSNULL;
+
+       // Field Group 1: Persistent metadata for Authoritative Records
+//     rr->Additional1       = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
+//     rr->Additional2       = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
+//     rr->DependentOn       = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
+//     rr->RRSet             = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
+//     rr->Callback          = already set in mDNS_SetupResourceRecord
+//     rr->Context           = already set in mDNS_SetupResourceRecord
+//     rr->RecordType        = already set in mDNS_SetupResourceRecord
+//     rr->HostTarget        = set to mDNSNULL in mDNS_SetupResourceRecord; may be overridden by client
+
+       // Field Group 2: Transient state for Authoritative Records
+       rr->Acknowledged      = mDNSfalse;
+       rr->ProbeCount        = (rr->RecordType == kDNSRecordTypeUnique) ? DefaultProbeCountForTypeUnique : (mDNSu8)0;
+       rr->AnnounceCount     = DefaultAnnounceCountForRecordType(rr->RecordType);
+       rr->IncludeInProbe    = mDNSfalse;
+       rr->SendPriority      = 0;
+       rr->Requester         = zeroIPAddr;
+       rr->NextResponse      = mDNSNULL;
+       rr->NR_AnswerTo       = mDNSNULL;
+       rr->NR_AdditionalTo   = mDNSNULL;
+       rr->LastSendTime      = timenow - mDNSPlatformOneSecond;
+       rr->NextSendTime      = timenow;
+       if (rr->RecordType == kDNSRecordTypeUnique && m->SuppressProbes) rr->NextSendTime = m->SuppressProbes;
+       rr->NextSendInterval  = DefaultSendIntervalForRecordType(rr->RecordType);
+       rr->NewRData          = mDNSNULL;
+       rr->UpdateCallback    = mDNSNULL;
+
+       // Field Group 3: Transient state for Cache Records
+       rr->NextDupSuppress   = mDNSNULL;       // Not strictly relevant for a local record
+       rr->TimeRcvd          = 0;                      // Not strictly relevant for a local record
+       rr->LastUsed          = 0;                      // Not strictly relevant for a local record
+       rr->UseCount          = 0;                      // Not strictly relevant for a local record
+       rr->UnansweredQueries = 0;                      // Not strictly relevant for a local record
+       rr->Active            = mDNSfalse;      // Not strictly relevant for a local record
+       rr->NewData           = mDNSfalse;      // Not strictly relevant for a local record
+
+       // Field Group 4: The actual information pertaining to this resource record
+//     rr->interface         = already set in mDNS_SetupResourceRecord
+//     rr->name.c            = MUST be set by client
+//     rr->rrtype            = already set in mDNS_SetupResourceRecord
+//     rr->rrclass           = already set in mDNS_SetupResourceRecord
+//     rr->rroriginalttl     = already set in mDNS_SetupResourceRecord
+//     rr->rrremainingttl    = already set in mDNS_SetupResourceRecord
+
+       if (rr->HostTarget)
+               SetTargetToHostName(m, rr);     // This also sets rdlength and rdestimate for us
+       else
+               {
+               rr->rdata->RDLength = GetRDLength(rr, mDNSfalse);
+               rr->rdestimate      = GetRDLength(rr, mDNStrue);
+               }
+//     rr->rdata             = MUST be set by client
+
+       *p = rr;
+       return(mStatus_NoError);
+       }
+
+// mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
+// mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
+// mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
+typedef enum { mDNS_Dereg_normal, mDNS_Dereg_conflict, mDNS_Dereg_repeat } mDNS_Dereg_type;
+
+// NOTE: mDNS_Deregister_internal can call a user callback, which may change the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void mDNS_Deregister_internal(mDNS *const m, ResourceRecord *const rr, const mDNSs32 timenow, mDNS_Dereg_type drt)
+       {
+       mDNSu8 RecordType = rr->RecordType;
+       // If this is a shared record and we've announced it at least once,
+       // we need to retract that announcement before we delete the record
+       if (RecordType == kDNSRecordTypeShared && rr->AnnounceCount < DefaultAnnounceCountForTypeShared)
+               {
+               debugf("mDNS_Deregister_internal: Sending deregister for %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+               rr->RecordType     = kDNSRecordTypeDeregistering;
+               rr->rroriginalttl  = 0;
+               rr->rrremainingttl = 0;
+               }
+       else
+               {
+               // Find this record in our list of active records
+               ResourceRecord **p = &m->ResourceRecords;
+               while (*p && *p != rr) p=&(*p)->next;
+
+               if (*p) *p = rr->next;
+               else
+                       {
+                       // No need to give an error message if we already know this is a potentially repeated deregistration
+                       if (drt != mDNS_Dereg_repeat)
+                               debugf("mDNS_Deregister_internal: Record %##s (%s) not found in list", rr->name.c, DNSTypeName(rr->rrtype));
+                       return;
+                       }
+               // If someone is about to look at this, bump the pointer forward
+               if (m->CurrentRecord == rr) m->CurrentRecord = rr->next;
+               rr->next = mDNSNULL;
+
+               if      (RecordType == kDNSRecordTypeUnregistered)
+                       debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeUnregistered", rr->name.c, DNSTypeName(rr->rrtype));
+               else if (RecordType == kDNSRecordTypeDeregistering)
+                       debugf("mDNS_Deregister_internal: Record %##s (%s) already marked kDNSRecordTypeDeregistering", rr->name.c, DNSTypeName(rr->rrtype));
+               else
+                       {
+                       debugf("mDNS_Deregister_internal: Deleting record for %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+                       rr->RecordType = kDNSRecordTypeUnregistered;
+                       }
+
+               if ((drt == mDNS_Dereg_conflict || drt == mDNS_Dereg_repeat) && RecordType == kDNSRecordTypeShared)
+                       debugf("mDNS_Deregister_internal: Cannot have a conflict on a shared record! %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+
+               // If we have an update queued up which never executed, give the client a chance to free that memory
+               if (rr->NewRData)
+                       {
+                       RData *n = rr->NewRData;
+                       rr->NewRData = mDNSNULL;        // Clear the NewRData pointer ...
+                       if (rr->UpdateCallback) rr->UpdateCallback(m, rr, n); // ...and let the client free this memory, if necessary
+                       }
+               
+               if (RecordType == kDNSRecordTypeShared && rr->Callback)
+                       rr->Callback(m, rr, mStatus_MemFree);
+               else if (drt == mDNS_Dereg_conflict)
+                       {
+                       m->SuppressProbes = timenow + mDNSPlatformOneSecond;
+                       if (m->SuppressProbes == 0) m->SuppressProbes = 1;
+                       if (rr->Callback) rr->Callback(m, rr, mStatus_NameConflict);
+                       }
+               }
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark -
+#pragma mark - DNS Message Creation Functions
+#endif
+
+mDNSlocal void InitializeDNSMessage(DNSMessageHeader *h, mDNSOpaque16 id, mDNSOpaque16 flags)
+       {
+       h->id             = id;
+       h->flags          = flags;
+       h->numQuestions   = 0;
+       h->numAnswers     = 0;
+       h->numAuthorities = 0;
+       h->numAdditionals = 0;
+       }
+
+mDNSlocal const mDNSu8 *FindCompressionPointer(const mDNSu8 *const base, const mDNSu8 *const end, const mDNSu8 *const domname)
+       {
+       const mDNSu8 *result = end - *domname - 1;
+
+       if (*domname == 0) return(mDNSNULL);    // There's no point trying to match just the root label
+       
+       // This loop examines each possible starting position in packet, starting end of the packet and working backwards
+       while (result >= base)
+               {
+               // If the length byte and first character of the label match, then check further to see
+               // if this location in the packet will yield a useful name compression pointer.
+               if (result[0] == domname[0] && result[1] == domname[1])
+                       {
+                       const mDNSu8 *name = domname;
+                       const mDNSu8 *targ = result;
+                       while (targ + *name < end)
+                               {
+                               // First see if this label matches
+                               int i;
+                               const mDNSu8 *pointertarget;
+                               for (i=0; i <= *name; i++) if (targ[i] != name[i]) break;
+                               if (i <= *name) break;                                                  // If label did not match, bail out
+                               targ += 1 + *name;                                                              // Else, did match, so advance target pointer
+                               name += 1 + *name;                                                              // and proceed to check next label
+                               if (*name == 0 && *targ == 0) return(result);   // If no more labels, we found a match!
+                               if (*name == 0) break;                                                  // If no more labels to match, we failed, so bail out
+
+                               // The label matched, so now follow the pointer (if appropriate) and then see if the next label matches
+                               if (targ[0] < 0x40) continue;                                   // If length value, continue to check next label
+                               if (targ[0] < 0xC0) break;                                              // If 40-BF, not valid
+                               if (targ+1 >= end) break;                                               // Second byte not present!
+                               pointertarget = base + (((mDNSu16)(targ[0] & 0x3F)) << 8) + targ[1];
+                               if (targ < pointertarget) break;                                // Pointertarget must point *backwards* in the packet
+                               if (pointertarget[0] >= 0x40) break;                    // Pointertarget must point to a valid length byte
+                               targ = pointertarget;
+                               }
+                       }
+               result--;       // We failed to match at this search position, so back up the tentative result pointer and try again
+               }
+       return(mDNSNULL);
+       }
+
+// Put a string of dot-separated labels as length-prefixed labels
+// domainname is a fully-qualified name (i.e. assumed to be ending in a dot, even if it doesn't)
+// msg points to the message we're building (pass mDNSNULL if we don't want to use compression pointers)
+// end points to the end of the message so far
+// ptr points to where we want to put the name
+// limit points to one byte past the end of the buffer that we must not overrun
+// domainname is the name to put
+mDNSlocal mDNSu8 *putDomainNameAsLabels(const DNSMessage *const msg,
+       mDNSu8 *ptr, const mDNSu8 *const limit, const domainname *const name)
+       {
+       const mDNSu8 *const base        = (const mDNSu8 *const)msg;
+       const mDNSu8 *      np          = name->c;
+       const mDNSu8 *const max         = name->c + MAX_DOMAIN_NAME;    // Maximum that's valid
+       const mDNSu8 *      pointer     = mDNSNULL;
+       const mDNSu8 *const searchlimit = ptr;
+
+       while (*np && ptr < limit-1)            // While we've got characters in the name, and space to write them in the message...
+               {
+               if (np + 1 + *np >= max)
+                       { debugf("Malformed domain name (more than 255 characters)"); return(mDNSNULL); }
+
+               if (base) pointer = FindCompressionPointer(base, searchlimit, np);
+               if (pointer)                                    // Use a compression pointer if we can
+                       {
+                       mDNSu16 offset = (mDNSu16)(pointer - base);
+                       *ptr++ = (mDNSu8)(0xC0 | (offset >> 8));
+                       *ptr++ = (mDNSu8)(        offset      );
+                       return(ptr);
+                       }
+               else                                                    // Else copy one label and try again
+                       {
+                       int i;
+                       mDNSu8 len = *np++;
+                       if (ptr + 1 + len >= limit) return(mDNSNULL);
+                       *ptr++ = len;
+                       for (i=0; i<len; i++) *ptr++ = *np++;
+                       }
+               }
+
+       if (ptr < limit)                                                                                                // If we didn't run out of space
+               {
+               *ptr++ = 0;                                                                                                     // Put the final root label
+               return(ptr);                                                                                            // and return
+               }
+
+       return(mDNSNULL);
+       }
+
+mDNSlocal mDNSu8 *putRData(const DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit,
+       const mDNSu16 rrtype, const RData *const rdata)
+       {
+       switch (rrtype)
+               {
+               case kDNSType_A:        if (rdata->RDLength != 4)
+                                                               {
+                                                               debugf("putRData: Illegal length %d for kDNSType_A", rdata->RDLength);
+                                                               return(mDNSNULL);
+                                                               }
+                                                       if (ptr + 4 > limit) return(mDNSNULL);
+                                                       *ptr++ = rdata->u.ip.b[0];
+                                                       *ptr++ = rdata->u.ip.b[1];
+                                                       *ptr++ = rdata->u.ip.b[2];
+                                                       *ptr++ = rdata->u.ip.b[3];
+                                                       return(ptr);
+
+               case kDNSType_CNAME:// Same as PTR
+               case kDNSType_PTR:      return(putDomainNameAsLabels(msg, ptr, limit, &rdata->u.name));
+
+               case kDNSType_TXT:  if (ptr + rdata->RDLength > limit) return(mDNSNULL);
+                                                       mDNSPlatformMemCopy(rdata->u.data, ptr, rdata->RDLength);
+                                                       return(ptr + rdata->RDLength);
+
+               case kDNSType_SRV:      if (ptr + 6 > limit) return(mDNSNULL);
+                                                       *ptr++ = (mDNSu8)(rdata->u.srv.priority >> 8);
+                                                       *ptr++ = (mDNSu8)(rdata->u.srv.priority     );
+                                                       *ptr++ = (mDNSu8)(rdata->u.srv.weight   >> 8);
+                                                       *ptr++ = (mDNSu8)(rdata->u.srv.weight       );
+                                                       *ptr++ = rdata->u.srv.port.b[0];
+                                                       *ptr++ = rdata->u.srv.port.b[1];
+                                                       return(putDomainNameAsLabels(msg, ptr, limit, &rdata->u.srv.target));
+
+               default:                        if (ptr + rdata->RDLength > limit) return(mDNSNULL);
+                                                       debugf("putRData: Warning! Writing resource type %d as raw data", rrtype);
+                                                       mDNSPlatformMemCopy(rdata->u.data, ptr, rdata->RDLength);
+                                                       return(ptr + rdata->RDLength);
+               }
+       }
+
+// Put a domain name, type, class, ttl, length, and type-specific data
+// domainname is a fully-qualified name
+// Only pass the "m" and "timenow" parameters in cases where the LastSendTime is to be updated,
+// and the kDNSClass_UniqueRRSet bit set
+mDNSlocal mDNSu8 *putResourceRecord(DNSMessage *const msg, mDNSu8 *ptr,
+       mDNSu16 *count, ResourceRecord *rr, mDNS *const m, const mDNSs32 timenow)
+       {
+       mDNSu8 *endofrdata;
+       mDNSu32 actualLength;
+       const mDNSu8 *limit = msg->data + AbsoluteMaxDNSMessageData;
+       
+       // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
+       // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
+       if (msg->h.numAnswers || msg->h.numAuthorities || msg->h.numAdditionals)
+               limit = msg->data + NormalMaxDNSMessageData;
+
+       if (rr->RecordType == kDNSRecordTypeUnregistered)
+               {
+               debugf("putResourceRecord ERROR! Attempt to put kDNSRecordTypeUnregistered");
+               return(ptr);
+               }
+
+       ptr = putDomainNameAsLabels(msg, ptr, limit, &rr->name);
+       if (!ptr || ptr + 10 >= limit) return(mDNSNULL);        // If we're out-of-space, return mDNSNULL
+       ptr[0] = (mDNSu8)(rr->rrtype  >> 8);
+       ptr[1] = (mDNSu8)(rr->rrtype      );
+       ptr[2] = (mDNSu8)(rr->rrclass >> 8);
+       ptr[3] = (mDNSu8)(rr->rrclass     );
+       ptr[4] = (mDNSu8)(rr->rrremainingttl >> 24);
+       ptr[5] = (mDNSu8)(rr->rrremainingttl >> 16);
+       ptr[6] = (mDNSu8)(rr->rrremainingttl >>  8);
+       ptr[7] = (mDNSu8)(rr->rrremainingttl      );
+       endofrdata = putRData(msg, ptr+10, limit, rr->rrtype, rr->rdata);
+       if (!endofrdata) { debugf("Ran out of space in putResourceRecord!"); return(mDNSNULL); }
+
+       // Go back and fill in the actual number of data bytes we wrote
+       // (actualLength can be less than rdlength when domain name compression is used)
+       actualLength = (mDNSu32)(endofrdata - ptr - 10);
+       ptr[8] = (mDNSu8)(actualLength >> 8);
+       ptr[9] = (mDNSu8)(actualLength     );
+
+       if (m)                                                                                                          // If the 'm' parameter was passed in...
+               {
+               rr->LastSendTime = timenow;                                                             // ... then update LastSendTime
+               if (rr->RecordType & kDNSRecordTypeUniqueMask)                  // If it is supposed to be unique
+                       {
+                       const ResourceRecord *a = mDNSNULL;
+                       // If we find a member of the same RRSet (same name/type/class)
+                       // that hasn't been updated within the last quarter second, don't set the bit
+                       for (a = m->ResourceRecords; a; a=a->next)
+                               if (SameResourceRecordSignatureAnyInterface(rr, a))
+                                       if (timenow - a->LastSendTime > mDNSPlatformOneSecond/4)
+                                               break;
+                       if (a == mDNSNULL)
+                               ptr[2] |= kDNSClass_UniqueRRSet >> 8;
+                       }
+               }
+
+       (*count)++;
+       return(endofrdata);
+       }
+
+#if 0
+mDNSlocal mDNSu8 *putEmptyResourceRecord(DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit,
+       mDNSu16 *count, const ResourceRecord *rr)
+       {
+       ptr = putDomainNameAsLabels(msg, ptr, limit, &rr->name);
+       if (!ptr || ptr + 10 > limit) return(mDNSNULL);         // If we're out-of-space, return mDNSNULL
+       ptr[0] = (mDNSu8)(rr->rrtype  >> 8);                            // Put type
+       ptr[1] = (mDNSu8)(rr->rrtype      );
+       ptr[2] = (mDNSu8)(rr->rrclass >> 8);                            // Put class
+       ptr[3] = (mDNSu8)(rr->rrclass     );
+       ptr[4] = ptr[5] = ptr[6] = ptr[7] = 0;                          // TTL is zero
+       ptr[8] = ptr[9] = 0;                                                            // RDATA length is zero
+       (*count)++;
+       return(ptr + 10);
+       }
+#endif
+
+mDNSlocal mDNSu8 *putQuestion(DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit,
+                                                       const domainname *const name, mDNSu16 rrtype, mDNSu16 rrclass)
+       {
+       ptr = putDomainNameAsLabels(msg, ptr, limit, name);
+       if (!ptr || ptr+4 >= limit) return(mDNSNULL);                   // If we're out-of-space, return mDNSNULL
+       ptr[0] = (mDNSu8)(rrtype  >> 8);
+       ptr[1] = (mDNSu8)(rrtype      );
+       ptr[2] = (mDNSu8)(rrclass >> 8);
+       ptr[3] = (mDNSu8)(rrclass     );
+       msg->h.numQuestions++;
+       return(ptr+4);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - DNS Message Parsing Functions
+#endif
+
+mDNSlocal const mDNSu8 *skipDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end)
+       {
+       mDNSu32 total = 0;
+
+       if (ptr < (mDNSu8*)msg || ptr >= end)
+               { debugf("skipDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL); }
+
+       while (1)                                               // Read sequence of labels
+               {
+               const mDNSu8 len = *ptr++;      // Read length of this label
+               if (len == 0) return(ptr);      // If length is zero, that means this name is complete
+               switch (len & 0xC0)
+                       {
+                       case 0x00:      if (ptr + len >= end)                                   // Remember: expect at least one more byte for the root label
+                                                       { debugf("skipDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL); }
+                                               if (total + 1 + len >= MAX_DOMAIN_NAME) // Remember: expect at least one more byte for the root label
+                                                       { debugf("skipDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL); }
+                                               ptr += len;
+                                               total += 1 + len;
+                                               break;
+
+                       case 0x40:      debugf("skipDomainName: Extended EDNS0 label types 0x%X not supported", len); return(mDNSNULL);
+                       case 0x80:      debugf("skipDomainName: Illegal label length 0x%X", len); return(mDNSNULL);
+                       case 0xC0:      return(ptr+1);
+                       }
+               }
+       }
+
+// Routine to fetch an FQDN from the DNS message, following compression pointers if necessary.
+mDNSlocal const mDNSu8 *getDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end,
+       domainname *const name)
+       {
+       const mDNSu8 *nextbyte = mDNSNULL;                                      // Record where we got to before we started following pointers
+       mDNSu8       *np = name->c;                                                     // Name pointer
+       const mDNSu8 *const limit = np + MAX_DOMAIN_NAME;       // Limit so we don't overrun buffer
+
+       if (ptr < (mDNSu8*)msg || ptr >= end)
+               { debugf("getDomainName: Illegal ptr not within packet boundaries"); return(mDNSNULL); }
+
+       *np = 0;                                                // Tentatively place the root label here (may be overwritten if we have more labels)
+
+       while (1)                                               // Read sequence of labels
+               {
+               const mDNSu8 len = *ptr++;      // Read length of this label
+               if (len == 0) break;            // If length is zero, that means this name is complete
+               switch (len & 0xC0)
+                       {
+                       int i;
+                       mDNSu16 offset;
+
+                       case 0x00:      if (ptr + len >= end)           // Remember: expect at least one more byte for the root label
+                                                       { debugf("getDomainName: Malformed domain name (overruns packet end)"); return(mDNSNULL); }
+                                               if (np + 1 + len >= limit)      // Remember: expect at least one more byte for the root label
+                                                       { debugf("getDomainName: Malformed domain name (more than 255 characters)"); return(mDNSNULL); }
+                                               *np++ = len;
+                                               for (i=0; i<len; i++) *np++ = *ptr++;
+                                               *np = 0;        // Tentatively place the root label here (may be overwritten if we have more labels)
+                                               break;
+
+                       case 0x40:      debugf("getDomainName: Extended EDNS0 label types 0x%X not supported in name %##s", len, name->c);
+                                               return(mDNSNULL);
+
+                       case 0x80:      debugf("getDomainName: Illegal label length 0x%X in domain name %##s", len, name->c); return(mDNSNULL);
+
+                       case 0xC0:      offset = (mDNSu16)((((mDNSu16)(len & 0x3F)) << 8) | *ptr++);
+                                               if (!nextbyte) nextbyte = ptr;  // Record where we got to before we started following pointers
+                                               ptr = (mDNSu8 *)msg + offset;
+                                               if (ptr < (mDNSu8*)msg || ptr >= end)
+                                                       { debugf("getDomainName: Illegal compression pointer not within packet boundaries"); return(mDNSNULL); }
+                                               if (*ptr & 0xC0)
+                                                       { debugf("getDomainName: Compression pointer must point to real label"); return(mDNSNULL); }
+                                               break;
+                       }
+               }
+       
+       if (nextbyte) return(nextbyte);
+       else return(ptr);
+       }
+
+mDNSlocal const mDNSu8 *skipResourceRecord(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end)
+       {
+       mDNSu16 pktrdlength;
+
+       ptr = skipDomainName(msg, ptr, end);
+       if (!ptr) { debugf("skipResourceRecord: Malformed RR name"); return(mDNSNULL); }
+       
+       if (ptr + 10 > end) { debugf("skipResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL); }
+       pktrdlength = (mDNSu16)((mDNSu16)ptr[8] <<  8 | ptr[9]);
+       ptr += 10;
+       if (ptr + pktrdlength > end) { debugf("skipResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL); }
+
+       return(ptr + pktrdlength);
+       }
+
+mDNSlocal const mDNSu8 *getResourceRecord(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end,
+       const mDNSIPAddr InterfaceAddr, const mDNSs32 timenow, mDNSu8 RecordType, ResourceRecord *rr, RData *RDataStorage)
+       {
+       mDNSu16 pktrdlength;
+
+       rr->next              = mDNSNULL;
+       
+       // Field Group 1: Persistent metadata for Authoritative Records
+       rr->Additional1       = mDNSNULL;
+       rr->Additional2       = mDNSNULL;
+       rr->DependentOn       = mDNSNULL;
+       rr->RRSet             = mDNSNULL;
+       rr->Callback          = mDNSNULL;
+       rr->Context           = mDNSNULL;
+       rr->RecordType        = RecordType;
+       rr->HostTarget        = mDNSfalse;
+
+       // Field Group 2: Transient state for Authoritative Records
+       rr->Acknowledged      = mDNSfalse;
+       rr->ProbeCount        = 0;
+       rr->AnnounceCount     = 0;
+       rr->IncludeInProbe    = mDNSfalse;
+       rr->SendPriority      = 0;
+       rr->Requester         = zeroIPAddr;
+       rr->NextResponse      = mDNSNULL;
+       rr->NR_AnswerTo       = mDNSNULL;
+       rr->NR_AdditionalTo   = mDNSNULL;
+       rr->LastSendTime      = 0;
+       rr->NextSendTime      = 0;
+       rr->NextSendInterval  = 0;
+       rr->NewRData          = mDNSNULL;
+       rr->UpdateCallback    = mDNSNULL;
+
+       // Field Group 3: Transient state for Cache Records
+       rr->NextDupSuppress   = mDNSNULL;
+       rr->TimeRcvd          = timenow;
+       rr->LastUsed          = timenow;
+       rr->UseCount          = 0;
+       rr->UnansweredQueries = 0;
+       rr->Active            = mDNSfalse;
+       rr->NewData           = mDNStrue;
+
+       // Field Group 4: The actual information pertaining to this resource record
+       rr->InterfaceAddr     = InterfaceAddr;
+       ptr = getDomainName(msg, ptr, end, &rr->name);
+       if (!ptr) { debugf("getResourceRecord: Malformed RR name"); return(mDNSNULL); }
+
+       if (ptr + 10 > end) { debugf("getResourceRecord: Malformed RR -- no type/class/ttl/len!"); return(mDNSNULL); }
+       
+       rr->rrtype            = (mDNSu16)((mDNSu16)ptr[0] <<  8 | ptr[1]);
+       rr->rrclass           = (mDNSu16)((mDNSu16)ptr[2] <<  8 | ptr[3]) & kDNSQClass_Mask;
+       rr->rroriginalttl     = (mDNSu32)((mDNSu32)ptr[4] << 24 | (mDNSu32)ptr[5] << 16 | (mDNSu32)ptr[6] << 8 | ptr[7]);
+       if (rr->rroriginalttl > 0x70000000UL / mDNSPlatformOneSecond)
+               rr->rroriginalttl = 0x70000000UL / mDNSPlatformOneSecond;
+       rr->rrremainingttl    = 0;
+       pktrdlength           = (mDNSu16)((mDNSu16)ptr[8] <<  8 | ptr[9]);
+       if (ptr[2] & (kDNSClass_UniqueRRSet >> 8))
+               rr->RecordType |= kDNSRecordTypeUniqueMask;
+       ptr += 10;
+       if (ptr + pktrdlength > end) { debugf("getResourceRecord: RDATA exceeds end of packet"); return(mDNSNULL); }
+
+       if (RDataStorage)
+               rr->rdata = RDataStorage;
+       else
+               {
+               rr->rdata = &rr->rdatastorage;
+               rr->rdata->MaxRDLength = sizeof(RDataBody);
+               }
+
+       switch (rr->rrtype)
+               {
+               case kDNSType_A:        rr->rdata->u.ip.b[0] = ptr[0];
+                                                       rr->rdata->u.ip.b[1] = ptr[1];
+                                                       rr->rdata->u.ip.b[2] = ptr[2];
+                                                       rr->rdata->u.ip.b[3] = ptr[3];
+                                                       break;
+
+               case kDNSType_CNAME:// CNAME is same as PTR
+               case kDNSType_PTR:      if (!getDomainName(msg, ptr, end, &rr->rdata->u.name))
+                                                               { debugf("getResourceRecord: Malformed CNAME/PTR RDATA name"); return(mDNSNULL); }
+                                                       //debugf("%##s PTR %##s rdlen %d", rr->name.c, rr->rdata->u.name.c, pktrdlength);
+                                                       break;
+
+               case kDNSType_TXT:  if (pktrdlength > rr->rdata->MaxRDLength)
+                                                               {
+                                                               debugf("getResourceRecord: TXT rdata size (%d) exceeds storage (%d)",
+                                                                       pktrdlength, rr->rdata->MaxRDLength);
+                                                               return(mDNSNULL);
+                                                               }
+                                                       rr->rdata->RDLength = pktrdlength;
+                                                       mDNSPlatformMemCopy(ptr, rr->rdata->u.data, pktrdlength);
+                                                       break;
+
+               case kDNSType_SRV:      rr->rdata->u.srv.priority = (mDNSu16)((mDNSu16)ptr[0] <<  8 | ptr[1]);
+                                                       rr->rdata->u.srv.weight   = (mDNSu16)((mDNSu16)ptr[2] <<  8 | ptr[3]);
+                                                       rr->rdata->u.srv.port.b[0] = ptr[4];
+                                                       rr->rdata->u.srv.port.b[1] = ptr[5];
+                                                       if (!getDomainName(msg, ptr+6, end, &rr->rdata->u.srv.target))
+                                                               { debugf("getResourceRecord: Malformed SRV RDATA name"); return(mDNSNULL); }
+                                                       //debugf("%##s SRV %##s rdlen %d", rr->name.c, rr->rdata->u.srv.target.c, pktrdlength);
+                                                       break;
+
+               default:                        if (pktrdlength > rr->rdata->MaxRDLength)
+                                                               {
+                                                               debugf("getResourceRecord: rdata %d size (%d) exceeds storage (%d)",
+                                                                       rr->rrtype, pktrdlength, rr->rdata->MaxRDLength);
+                                                               return(mDNSNULL);
+                                                               }
+                                                       debugf("getResourceRecord: Warning! Reading resource type %d as opaque data", rr->rrtype);
+                                                       // Note: Just because we don't understand the record type, that doesn't
+                                                       // mean we fail. The DNS protocol specifies rdlength, so we can
+                                                       // safely skip over unknown records and ignore them.
+                                                       // We also grab a binary copy of the rdata anyway, since the caller
+                                                       // might know how to interpret it even if we don't.
+                                                       rr->rdata->RDLength = pktrdlength;
+                                                       mDNSPlatformMemCopy(ptr, rr->rdata->u.data, pktrdlength);
+                                                       break;
+               }
+
+       rr->rdata->RDLength   = GetRDLength(rr, mDNSfalse);
+       rr->rdestimate        = GetRDLength(rr, mDNStrue);
+       return(ptr + pktrdlength);
+       }
+
+mDNSlocal const mDNSu8 *skipQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end)
+       {
+       ptr = skipDomainName(msg, ptr, end);
+       if (!ptr) { debugf("skipQuestion: Malformed domain name in DNS question section"); return(mDNSNULL); }
+       if (ptr+4 > end) { debugf("skipQuestion: Malformed DNS question section -- no query type and class!"); return(mDNSNULL); }
+       return(ptr+4);
+       }
+
+mDNSlocal const mDNSu8 *getQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end, const mDNSIPAddr InterfaceAddr,
+       DNSQuestion *question)
+       {
+       question->InterfaceAddr = InterfaceAddr;
+       ptr = getDomainName(msg, ptr, end, &question->name);
+       if (!ptr) { debugf("Malformed domain name in DNS question section"); return(mDNSNULL); }
+       if (ptr+4 > end) { debugf("Malformed DNS question section -- no query type and class!"); return(mDNSNULL); }
+       
+       question->rrtype  = (mDNSu16)((mDNSu16)ptr[0] << 8 | ptr[1]);                   // Get type
+       question->rrclass = (mDNSu16)((mDNSu16)ptr[2] << 8 | ptr[3]);                   // and class
+       return(ptr+4);
+       }
+
+mDNSlocal const mDNSu8 *LocateAnswers(const DNSMessage *const msg, const mDNSu8 *const end)
+       {
+       int i;
+       const mDNSu8 *ptr = msg->data;
+       for (i = 0; i < msg->h.numQuestions && ptr; i++) ptr = skipQuestion(msg, ptr, end);
+       return(ptr);
+       }
+
+mDNSlocal const mDNSu8 *LocateAuthorities(const DNSMessage *const msg, const mDNSu8 *const end)
+       {
+       int i;
+       const mDNSu8 *ptr = LocateAnswers(msg, end);
+       for (i = 0; i < msg->h.numAnswers && ptr; i++) ptr = skipResourceRecord(msg, ptr, end);
+       return(ptr);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark -
+#pragma mark - Packet Sending Functions
+#endif
+
+mDNSlocal mStatus mDNSSendDNSMessage(const mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
+       mDNSIPAddr src, mDNSIPPort srcport, mDNSIPAddr dst, mDNSIPPort dstport)
+       {
+       mStatus status;
+       mDNSu16 numQuestions   = msg->h.numQuestions;
+       mDNSu16 numAnswers     = msg->h.numAnswers;
+       mDNSu16 numAuthorities = msg->h.numAuthorities;
+       mDNSu16 numAdditionals = msg->h.numAdditionals;
+       
+       // Put all the integer values in IETF byte-order (MSB first, LSB second)
+       mDNSu8 *ptr = (mDNSu8 *)&msg->h.numQuestions;
+       *ptr++ = (mDNSu8)(numQuestions   >> 8);
+       *ptr++ = (mDNSu8)(numQuestions       );
+       *ptr++ = (mDNSu8)(numAnswers     >> 8);
+       *ptr++ = (mDNSu8)(numAnswers         );
+       *ptr++ = (mDNSu8)(numAuthorities >> 8);
+       *ptr++ = (mDNSu8)(numAuthorities     );
+       *ptr++ = (mDNSu8)(numAdditionals >> 8);
+       *ptr++ = (mDNSu8)(numAdditionals     );
+       
+       // Send the packet on the wire
+       status = mDNSPlatformSendUDP(m, msg, end, src, srcport, dst, dstport);
+       
+       // Put all the integer values back the way they were before we return
+       msg->h.numQuestions   = numQuestions;
+       msg->h.numAnswers     = numAnswers;
+       msg->h.numAuthorities = numAuthorities;
+       msg->h.numAdditionals = numAdditionals;
+
+       return(status);
+       }
+
+mDNSlocal mDNSBool HaveResponses(const mDNS *const m, const mDNSs32 timenow)
+       {
+       ResourceRecord *rr;
+       if (m->SleepState)
+               {
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       if (rr->RecordType == kDNSRecordTypeShared && rr->rrremainingttl == 0)
+                               return(mDNStrue);
+               }
+       else
+               {
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       {
+                       if (rr->RecordType == kDNSRecordTypeDeregistering)
+                               return(mDNStrue);
+       
+                       if (rr->AnnounceCount && ResourceRecordIsValidAnswer(rr) && timenow - rr->NextSendTime >= 0)
+                               return(mDNStrue);
+       
+                       if (rr->SendPriority >= kDNSSendPriorityAnswer && ResourceRecordIsValidAnswer(rr))
+                               return(mDNStrue);
+                       }
+               }
+       return(mDNSfalse);
+       }
+
+// NOTE: DiscardDeregistrations calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void DiscardDeregistrations(mDNS *const m, mDNSs32 timenow)
+       {
+       if (m->CurrentRecord) debugf("DiscardDeregistrations ERROR m->CurrentRecord already set");
+       m->CurrentRecord = m->ResourceRecords;
+       
+       while (m->CurrentRecord)
+               {
+               ResourceRecord *rr = m->CurrentRecord;
+               m->CurrentRecord = rr->next;
+               if (rr->RecordType == kDNSRecordTypeDeregistering)
+                       {
+                       rr->RecordType    = kDNSRecordTypeShared;
+                       rr->AnnounceCount = DefaultAnnounceCountForTypeShared;
+                       mDNS_Deregister_internal(m, rr, timenow, mDNS_Dereg_normal);
+                       }
+               }
+       }
+
+// This routine sends as many records as it can fit in a single DNS Response Message, in order of priority.
+// If there are any deregistrations, announcements, or answers that don't fit, they are left in the work list for next time.
+// If there are any additionals that don't fit, they are discarded -- they were optional anyway.
+// NOTE: BuildResponse calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal mDNSu8 *BuildResponse(mDNS *const m,
+       DNSMessage *const response, mDNSu8 *responseptr, const mDNSIPAddr InterfaceAddr, const mDNSs32 timenow)
+       {
+       ResourceRecord *rr;
+       mDNSu8 *newptr;
+       int numDereg    = 0;
+       int numAnnounce = 0;
+       int numAnswer   = 0;
+
+       if (m->CurrentRecord) debugf("BuildResponse ERROR m->CurrentRecord already set");
+       m->CurrentRecord = m->ResourceRecords;
+       
+       // If we're sleeping, only send deregistrations
+       if (m->SleepState)
+               {
+               while (m->CurrentRecord)
+                       {
+                       ResourceRecord *rr = m->CurrentRecord;
+                       m->CurrentRecord = rr->next;
+                       if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                               rr->RecordType == kDNSRecordTypeShared && rr->rrremainingttl == 0 &&
+                               (newptr = putResourceRecord(response, responseptr, &response->h.numAnswers, rr, mDNSNULL, 0)))
+                               {
+                               numDereg++;
+                               responseptr = newptr;
+                               rr->rrremainingttl = rr->rroriginalttl;
+                               }
+                       }
+               }
+       else
+               {
+               // 1. Look for deregistrations we need to send
+               while (m->CurrentRecord)
+                       {
+                       ResourceRecord *rr = m->CurrentRecord;
+                       m->CurrentRecord = rr->next;
+                       if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger)
+                               {
+                               if (rr->NewRData)                                                               // If we have new data for this record
+                                       {
+                                       RData *OldRData = rr->rdata;
+                                       if (ResourceRecordIsValidAnswer(rr))            // First see if we have to de-register the old data
+                                               {
+                                               rr->rrremainingttl = 0;                                 // Clear rroriginalttl before putting record
+                                               newptr = putResourceRecord(response, responseptr, &response->h.numAnswers, rr, mDNSNULL, 0);
+                                               if (newptr)
+                                                       {
+                                                       numDereg++;
+                                                       responseptr = newptr;
+                                                       }
+                                               rr->rrremainingttl = rr->rroriginalttl; // Now restore rroriginalttl
+                                               }
+                                       rr->rdata = rr->NewRData;       // Update our rdata
+                                       rr->NewRData = mDNSNULL;        // Clear the NewRData pointer ...
+                                       if (rr->UpdateCallback) rr->UpdateCallback(m, rr, OldRData);    // ... and let the client know
+                                       }
+                               if (rr->RecordType == kDNSRecordTypeDeregistering &&
+                                       (newptr = putResourceRecord(response, responseptr, &response->h.numAnswers, rr, mDNSNULL, 0)))
+                                       {
+                                       numDereg++;
+                                       responseptr = newptr;
+                                       rr->RecordType    = kDNSRecordTypeShared;
+                                       rr->AnnounceCount = DefaultAnnounceCountForTypeShared;
+                                       mDNS_Deregister_internal(m, rr, timenow, mDNS_Dereg_normal);
+                                       }
+                               }
+                       }
+       
+               // 2. Look for announcements we are due to send in the next second
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       {
+                       if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                               rr->AnnounceCount && ResourceRecordIsValidAnswer(rr) &&
+                               timenow + mDNSPlatformOneSecond - rr->NextSendTime >= 0)
+                                       {
+                                       newptr = putResourceRecord(response, responseptr, &response->h.numAnswers, rr, m, timenow);
+                                       if (newptr)
+                                               {
+                                               numAnnounce++;
+                                               responseptr = newptr;
+                                               }
+                                       // If we were able to put the record, then update the state variables
+                                       // If we were unable to put the record because it is too large to fit, even though
+                                       // there are no other answers in the packet, then pretend we succeeded anyway,
+                                       // or we'll end up in an infinite loop trying to send a record that will never fit
+                                       if (response->h.numAnswers == 0) debugf("BuildResponse announcements failed");
+                                       if (newptr || response->h.numAnswers == 0)
+                                               {
+                                               rr->SendPriority      = 0;
+                                               rr->Requester         = zeroIPAddr;
+                                               rr->AnnounceCount--;
+                                               rr->NextSendTime     += rr->NextSendInterval;
+                                               if (rr->NextSendTime - (timenow + rr->NextSendInterval/2) < 0)
+                                                       rr->NextSendTime = (timenow + rr->NextSendInterval/2);
+                                               rr->NextSendInterval *= 2;
+                                               }
+                                       }
+                       }
+       
+               // 3. Look for answers we need to send
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                               rr->SendPriority >= kDNSSendPriorityAnswer && ResourceRecordIsValidAnswer(rr))
+                                       {
+                                       newptr = putResourceRecord(response, responseptr, &response->h.numAnswers, rr, m, timenow);
+                                       if (newptr)
+                                               {
+                                               numAnswer++;
+                                               responseptr = newptr;
+                                               }
+                                       // If we were able to put the record, then update the state variables
+                                       // If we were unable to put the record because it is too large to fit, even though
+                                       // there are no other answers in the packet then pretend we succeeded anyway,
+                                       // or we'll end up in an infinite loop trying to send a record that will never fit
+                                       if (response->h.numAnswers == 0) debugf("BuildResponse answers failed");
+                                       if (newptr || response->h.numAnswers == 0)
+                                               {
+                                               rr->SendPriority = 0;
+                                               rr->Requester    = zeroIPAddr;
+                                               }
+                                       }
+       
+               // 4. Add additionals, if there's space
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                               rr->SendPriority == kDNSSendPriorityAdditional)
+                               {
+                               if (ResourceRecordIsValidAnswer(rr) &&
+                                       (newptr = putResourceRecord(response, responseptr, &response->h.numAdditionals, rr, m, timenow)))
+                                               responseptr = newptr;
+                               rr->SendPriority = 0;   // Clear SendPriority anyway, even if we didn't put the additional in the packet
+                               rr->Requester    = zeroIPAddr;
+                               }
+               }
+
+       if (numDereg || numAnnounce || numAnswer || response->h.numAdditionals)
+               verbosedebugf("BuildResponse Built %d Deregistration%s, %d Announcement%s, %d Answer%s, %d Additional%s",
+                       numDereg,                   numDereg                   == 1 ? "" : "s",
+                       numAnnounce,                numAnnounce                == 1 ? "" : "s",
+                       numAnswer,                  numAnswer                  == 1 ? "" : "s",
+                       response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
+
+       return(responseptr);
+       }
+
+mDNSlocal void SendResponses(mDNS *const m, const mDNSs32 timenow)
+       {
+       DNSMessage response;
+       DNSMessageHeader baseheader;
+       mDNSu8 *baselimit, *responseptr;
+       NetworkInterfaceInfo *intf;
+       ResourceRecord *rr, *r2;
+
+       // Run through our list of records,
+       // and if there's a record which is supposed to be unique that we're proposing to give as an answer,
+       // then make sure that the whole RRSet with that name/type/class is also marked for answering.
+       // Otherwise, if we set the kDNSClass_UniqueRRSet bit on a record, then other RRSet members
+       // that have not been sent recently will get flushed out of client caches.
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               if (rr->RecordType & kDNSRecordTypeUniqueMask)
+                       if (TimeToSendThisRecord(rr,timenow))
+                               for (r2 = m->ResourceRecords; r2; r2=r2->next)
+                                       if (r2 != rr && timenow - r2->LastSendTime > mDNSPlatformOneSecond/4)
+                                               if (SameResourceRecordSignatureAnyInterface(rr, r2))
+                                                       r2->SendPriority = kDNSSendPriorityAnswer;
+
+       // First build the generic part of the message
+       InitializeDNSMessage(&response.h, zeroID, ResponseFlags);
+       baselimit = BuildResponse(m, &response, response.data, zeroIPAddr, timenow);
+       baseheader = response.h;
+
+       for (intf = m->HostInterfaces; intf; intf = intf->next)
+               {
+               // Restore the header to the counts for the generic records
+               response.h = baseheader;
+               // Now add any records specific to this interface
+               responseptr = BuildResponse(m, &response, baselimit, intf->ip, timenow);
+               if (response.h.numAnswers > 0)  // We *never* send a packet with only additionals in it
+                       {
+                       mDNSSendDNSMessage(m, &response, responseptr, intf->ip, MulticastDNSPort, AllDNSLinkGroup, MulticastDNSPort);
+                       debugf("SendResponses Sent %d Answer%s, %d Additional%s on %.4a",
+                               response.h.numAnswers,     response.h.numAnswers     == 1 ? "" : "s",
+                               response.h.numAdditionals, response.h.numAdditionals == 1 ? "" : "s", &intf->ip);
+                       }
+               }
+       }
+
+#define TimeToSendThisQuestion(Q,time) (!(Q)->DuplicateOf && time - (Q)->NextQTime >= 0)
+
+mDNSlocal mDNSBool HaveQueries(const mDNS *const m, const mDNSs32 timenow)
+       {
+       ResourceRecord *rr;
+       DNSQuestion *q;
+
+       // 1. See if we've got any cache records in danger of expiring
+       for (rr = m->rrcache; rr; rr=rr->next)
+               if (rr->UnansweredQueries < 2)
+                       {
+                       mDNSs32 onetenth = ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond) / 10;
+                       mDNSs32 t0 = rr->TimeRcvd + (mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond;
+                       mDNSs32 t1 = t0 - onetenth;
+                       mDNSs32 t2 = t1 - onetenth;
+
+                       if (timenow - t1 >= 0 || (rr->UnansweredQueries < 1 && timenow - t2 >= 0))
+                               {
+                               DNSQuestion *q = CacheRRActive(m, rr);
+                               if (q) q->NextQTime = timenow;
+                               }
+                       }
+       
+       // 2. Scan our list of questions to see if it's time to send any of them
+       for (q = m->ActiveQuestions; q; q=q->next)
+               if (TimeToSendThisQuestion(q, timenow))
+                       return(mDNStrue);
+
+       // 3. Scan our list of Resource Records to see if we need to send any probe questions
+       for (rr = m->ResourceRecords; rr; rr=rr->next)          // Scan our list of records
+               if (rr->RecordType == kDNSRecordTypeUnique && timenow - rr->NextSendTime >= 0)
+                       return(mDNStrue);
+
+       return(mDNSfalse);
+       }
+
+// BuildProbe puts a probe question into a DNS Query packet and if successful, updates the value of queryptr.
+// It also sets the record's IncludeInProbe flag so that we know to add an Update Record too
+// and updates the forcast for the size of the duplicate suppression (answer) section.
+// NOTE: BuildProbe can call a user callback, which may change the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void BuildProbe(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr,
+       ResourceRecord *rr, mDNSu32 *answerforecast, const mDNSs32 timenow)
+       {
+       if (rr->ProbeCount == 0)
+               {
+               rr->RecordType    = kDNSRecordTypeVerified;
+               rr->AnnounceCount = DefaultAnnounceCountForRecordType(rr->RecordType);
+               debugf("Probing for %##s (%s) complete", rr->name.c, DNSTypeName(rr->rrtype));
+               if (!rr->Acknowledged && rr->Callback)  
+                       { rr->Acknowledged = mDNStrue; rr->Callback(m, rr, mStatus_NoError); }
+               }
+       else
+               {
+               const mDNSu8 *const limit = query->data + ((query->h.numQuestions) ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
+               mDNSu8 *newptr = putQuestion(query, *queryptr, limit, &rr->name, kDNSQType_ANY, rr->rrclass);
+               // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
+               mDNSu32 forecast = *answerforecast + 12 + rr->rdestimate;
+               if (newptr && newptr + forecast < limit)
+                       {
+                       *queryptr       = newptr;
+                       *answerforecast = forecast;
+                       rr->ProbeCount--;               // Only decrement ProbeCount if we successfully added the record to the packet
+                       rr->IncludeInProbe = mDNStrue;
+                       rr->NextSendTime = timenow + rr->NextSendInterval;
+                       }
+               else
+                       {
+                       debugf("BuildProbe retracting Question %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+                       query->h.numQuestions--;
+                       }
+               }
+       }
+
+#define MaxQuestionInterval         (3600 * mDNSPlatformOneSecond)
+#define GetNextQInterval(X)         (((X)*2) <= MaxQuestionInterval ? ((X)*2) : MaxQuestionInterval)
+#define GetNextSendTime(T,EARLIEST) (((T) - (EARLIEST) >= 0) ? (T) : (EARLIEST) )
+
+// BuildQuestion puts a question into a DNS Query packet and if successful, updates the value of queryptr.
+// It also appends to the list of duplicate suppression records that need to be included,
+// and updates the forcast for the size of the duplicate suppression (answer) section.
+mDNSlocal void BuildQuestion(mDNS *const m, DNSMessage *query, mDNSu8 **queryptr, DNSQuestion *q,
+       ResourceRecord ***dups_ptr, mDNSu32 *answerforecast, const mDNSs32 timenow)
+       {
+       const mDNSu8 *const limit = query->data + (query->h.numQuestions ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData);
+       mDNSu8 *newptr = putQuestion(query, *queryptr, limit, &q->name, q->rrtype, q->rrclass);
+       if (!newptr)
+               debugf("BuildQuestion: No more space for queries");
+       else
+               {
+               mDNSu32 forecast = *answerforecast;
+               ResourceRecord *rr;
+               ResourceRecord **d = *dups_ptr;
+               mDNSs32 nst = timenow + q->NextQInterval;
+
+               // If we have a resource record in our cache,
+               // which is not already in the duplicate suppression list
+               // which answers our question,
+               // then add it to the duplicate suppression list
+               for (rr=m->rrcache; rr; rr=rr->next)
+                       if (rr->NextDupSuppress == mDNSNULL && d != &rr->NextDupSuppress &&
+                               ResourceRecordAnswersQuestion(rr, q))
+                               {
+                               // Work out the latest time we should ask about this record to refresh it before it expires
+                               mDNSs32 onetenth = ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond) / 10;
+                               mDNSs32 t0 = rr->TimeRcvd + (mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond;
+                               mDNSs32 t3 = t0 - onetenth*3;
+
+                               // If we'll ask again at least twice before it expires, okay to suppress it this time
+                               if (t3 - nst >= 0)
+                                       {
+                                       *d = rr;        // Link this record into our duplicate suppression chain
+                                       d = &rr->NextDupSuppress;
+                                       // We forecast: compressed name (2) type (2) class (2) TTL (4) rdlength (2) rdata (n)
+                                       forecast += 12 + rr->rdestimate;
+                                       }
+                               else
+                                       rr->UnansweredQueries++;
+                               }
+
+               // If we're trying to put more than one question in this packet, and it doesn't fit
+               // then undo that last question and try again next time
+               if (query->h.numQuestions > 1 && newptr + forecast >= limit)
+                       {
+                       debugf("BuildQuestion retracting question %##s answerforecast %d", q->name.c, *answerforecast);
+                       query->h.numQuestions--;
+                       d = *dups_ptr;          // Go back to where we started and retract these answer records
+                       while (*d) { ResourceRecord *rr = *d; *d = mDNSNULL; d = &rr->NextDupSuppress; }
+                       }
+               else
+                       {
+                       *queryptr       = newptr;               // Update the packet pointer
+                       *answerforecast = forecast;             // Update the forecast
+                       *dups_ptr       = d;                    // Update the dup suppression pointer
+                       q->NextQTime     = nst;
+                       q->ThisQInterval = q->NextQInterval;
+                       q->NextQInterval = GetNextQInterval(q->ThisQInterval);
+                       }
+               }
+       }
+
+// How Standard Queries are generated:
+// 1. The Question Section contains the question
+// 2. The Additional Section contains answers we already know, to suppress duplicate replies
+
+// How Probe Queries are generated:
+// 1. The Question Section contains queries for the name we intend to use, with QType=ANY because
+// if some other host is already using *any* records with this name, we want to know about it.
+// 2. The Authority Section contains the proposed values we intend to use for one or more
+// of our records with that name (analogous to the Update section of DNS Update packets)
+// because if some other host is probing at the same time, we each want to know what the other is
+// planning, in order to apply the tie-breaking rule to see who gets to use the name and who doesn't.
+
+mDNSlocal mDNSu8 *BuildQueryPacketQuestions(mDNS *const m, DNSMessage *query, mDNSu8 *queryptr,
+       ResourceRecord ***dups_ptr, mDNSu32 *answerforecast,
+       const mDNSIPAddr InterfaceAddr, const mDNSs32 timenow)
+       {
+       DNSQuestion *q;
+       
+       // See which questions need to go out right now
+       for (q = m->ActiveQuestions; q; q=q->next)
+               if (q->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                       TimeToSendThisQuestion(q, timenow))
+                       BuildQuestion(m, query, &queryptr, q, dups_ptr, answerforecast, timenow);
+
+       // See which questions are more than half way to their NextSendTime, and send them too, if we have space
+       for (q = m->ActiveQuestions; q; q=q->next)
+               if (q->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                       TimeToSendThisQuestion(q, timenow + q->ThisQInterval/2))
+                       BuildQuestion(m, query, &queryptr, q, dups_ptr, answerforecast, timenow);
+
+       return(queryptr);
+       }
+
+mDNSlocal mDNSu8 *BuildQueryPacketAnswers(DNSMessage *query, mDNSu8 *queryptr,
+       ResourceRecord **dups_ptr, const mDNSs32 timenow)
+       {
+       while (*dups_ptr)
+               {
+               ResourceRecord *rr = *dups_ptr;
+               mDNSu32 timesincercvd = (mDNSu32)(timenow - rr->TimeRcvd);
+               mDNSu8 *newptr;
+               // Need to update rrremainingttl correctly before we put this cache record in the packet
+               rr->rrremainingttl = rr->rroriginalttl - timesincercvd / mDNSPlatformOneSecond;
+               newptr = putResourceRecord(query, queryptr, &query->h.numAnswers, rr, mDNSNULL, 0);
+               if (newptr)
+                       {
+                       *dups_ptr = rr->NextDupSuppress;
+                       rr->NextDupSuppress = mDNSNULL;
+                       queryptr = newptr;
+                       }
+               else
+                       {
+                       debugf("BuildQueryPacketAnswers: Put %d answers; No more space for duplicate suppression",
+                               query->h.numAnswers);
+                       query->h.flags.b[0] |= kDNSFlag0_TC;
+                       break;
+                       }
+               }
+       return(queryptr);
+       }
+
+mDNSlocal mDNSu8 *BuildQueryPacketProbes(mDNS *const m, DNSMessage *query, mDNSu8 *queryptr,
+       mDNSu32 *answerforecast, const mDNSIPAddr InterfaceAddr, const mDNSs32 timenow)
+       {
+       if (m->CurrentRecord) debugf("BuildQueryPacketProbes ERROR m->CurrentRecord already set");
+       m->CurrentRecord = m->ResourceRecords;
+       while (m->CurrentRecord)
+               {
+               ResourceRecord *rr = m->CurrentRecord;
+               m->CurrentRecord = rr->next;
+               if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger &&
+                       rr->RecordType == kDNSRecordTypeUnique && timenow - rr->NextSendTime >= 0)
+                       BuildProbe(m, query, &queryptr, rr, answerforecast, timenow);
+               }
+       return(queryptr);
+       }
+
+mDNSlocal mDNSu8 *BuildQueryPacketUpdates(mDNS *const m, DNSMessage *query, mDNSu8 *queryptr)
+       {
+       ResourceRecord *rr;
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               if (rr->IncludeInProbe)
+                       {
+                       mDNSu8 *newptr = putResourceRecord(query, queryptr, &query->h.numAuthorities, rr, mDNSNULL, 0);
+                       rr->IncludeInProbe = mDNSfalse;
+                       if (newptr)
+                               queryptr = newptr;
+                       else
+                               {
+                               debugf("BuildQueryPacketUpdates: How did we fail to have space for the Update record %##s (%s)?",
+                                       rr->name.c, DNSTypeName(rr->rrtype));
+                               break;
+                               }
+                       }
+       return(queryptr);
+       }
+
+mDNSlocal void SendQueries(mDNS *const m, const mDNSs32 timenow)
+       {
+       ResourceRecord *NextDupSuppress = mDNSNULL;
+       do
+               {
+               DNSMessage query;
+               DNSMessageHeader baseheader;
+               mDNSu8 *baselimit = query.data;
+               NetworkInterfaceInfo *intf;
+       
+               // First build the generic part of the message
+               InitializeDNSMessage(&query.h, zeroID, QueryFlags);
+               if (!NextDupSuppress)
+                       {
+                       ResourceRecord **dups = &NextDupSuppress;
+                       mDNSu32 answerforecast = 0;
+                       baselimit = BuildQueryPacketQuestions(m, &query, baselimit, &dups, &answerforecast, zeroIPAddr, timenow);
+                       baselimit = BuildQueryPacketProbes(m, &query, baselimit, &answerforecast, zeroIPAddr, timenow);
+                       }
+               baselimit = BuildQueryPacketAnswers(&query, baselimit, &NextDupSuppress, timenow);
+               baselimit = BuildQueryPacketUpdates(m, &query, baselimit);
+               baseheader = query.h;
+               
+               if (NextDupSuppress) debugf("SendQueries: NextDupSuppress still set... Will continue in next packet");
+
+               for (intf = m->HostInterfaces; intf; intf = intf->next)
+                       {
+                       ResourceRecord *NextDupSuppress2 = mDNSNULL;
+                       do
+                               {
+                               // Restore the header to the counts for the generic records
+                               mDNSu8 *queryptr = baselimit;
+                               query.h = baseheader;
+                               // Now add any records specific to this interface, if we can
+                               if (query.h.numAnswers == 0 && query.h.numAuthorities == 0 && !NextDupSuppress)
+                                       {
+                                       if (!NextDupSuppress2)
+                                               {
+                                               ResourceRecord **dups2 = &NextDupSuppress2;
+                                               mDNSu32 answerforecast2 = 0;
+                                               queryptr = BuildQueryPacketQuestions(m, &query, queryptr, &dups2, &answerforecast2, intf->ip, timenow);
+                                               queryptr = BuildQueryPacketProbes(m, &query, queryptr, &answerforecast2, intf->ip, timenow);
+                                               }
+                                       queryptr = BuildQueryPacketAnswers(&query, queryptr, &NextDupSuppress2, timenow);
+                                       queryptr = BuildQueryPacketUpdates(m, &query, queryptr);
+                                       }
+       
+                               if (queryptr > query.data)
+                                       {
+                                       mDNSSendDNSMessage(m, &query, queryptr, intf->ip, MulticastDNSPort, AllDNSLinkGroup, MulticastDNSPort);
+                                       debugf("SendQueries Sent %d Question%s %d Answer%s %d Update%s on %.4a",
+                                               query.h.numQuestions,   query.h.numQuestions   == 1 ? "" : "s",
+                                               query.h.numAnswers,     query.h.numAnswers     == 1 ? "" : "s",
+                                               query.h.numAuthorities, query.h.numAuthorities == 1 ? "" : "s", &intf->ip);
+                                       }
+                               } while (NextDupSuppress2);
+                       }
+               } while (NextDupSuppress);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - RR List Management & Task Management
+#endif
+
+// rr is a new ResourceRecord just received into our cache
+// (kDNSRecordTypePacketAnswer/kDNSRecordTypePacketAdditional/kDNSRecordTypePacketUniqueAns/kDNSRecordTypePacketUniqueAdd)
+mDNSlocal void TriggerImmediateQuestions(mDNS *const m, const ResourceRecord *const rr, const mDNSs32 timenow)
+       {
+       // If we just received a new record off the wire that we've never seen before, we want to ask our question again
+       // soon, and keep doing that repeatedly (with duplicate suppression) until we stop getting any more responses
+       mDNSs32 needquery = timenow + mDNSPlatformOneSecond;
+       DNSQuestion *q;
+       for (q = m->ActiveQuestions; q; q=q->next)              // Scan our list of questions
+               if (!q->DuplicateOf && q->NextQTime - needquery > 0 && ResourceRecordAnswersQuestion(rr, q))
+                       {
+                       q->NextQTime     = needquery;
+                       // As long as responses are still coming in, don't do the exponential backoff
+                       q->NextQInterval = q->ThisQInterval;
+                       }
+       }
+
+// NOTE: AnswerQuestionWithResourceRecord can call a user callback, which may change the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void AnswerQuestionWithResourceRecord(mDNS *const m, DNSQuestion *q, ResourceRecord *rr, const mDNSs32 timenow)
+       {
+       mDNSu32 timesincercvd = (mDNSu32)(timenow - rr->TimeRcvd);
+       if (rr->rroriginalttl <= timesincercvd / mDNSPlatformOneSecond) rr->rrremainingttl = 0;
+       else rr->rrremainingttl = rr->rroriginalttl - timesincercvd / mDNSPlatformOneSecond;
+
+#if DEBUGBREAKS
+       if (rr->rrremainingttl)
+               {
+               if (rr->rrtype == kDNSType_TXT)
+                       debugf("AnswerQuestionWithResourceRecord Add %##s TXT %#.20s remaining ttl %d",
+                               rr->name.c, rr->rdata->u.txt.c, rr->rrremainingttl);
+               else
+                       debugf("AnswerQuestionWithResourceRecord Add %##s (%s) remaining ttl %d",
+                               rr->name.c, DNSTypeName(rr->rrtype), rr->rrremainingttl);
+               }
+       else
+               {
+               if (rr->rrtype == kDNSType_TXT)
+                       debugf("AnswerQuestionWithResourceRecord Del %##s TXT %#.20s UnansweredQueries %d",
+                               rr->name.c, rr->rdata->u.txt.c, rr->UnansweredQueries);
+               else
+                       debugf("AnswerQuestionWithResourceRecord Del %##s (%s) UnansweredQueries %d",
+                               rr->name.c, DNSTypeName(rr->rrtype), rr->UnansweredQueries);
+               }
+#endif
+
+       rr->LastUsed = timenow;
+       rr->UseCount++;
+       if (q->Callback) q->Callback(m, q, rr);
+       }
+
+// AnswerLocalQuestions is called from mDNSCoreReceiveResponse,
+// and from TidyRRCache, which is called from mDNSCoreTask and from mDNSCoreReceiveResponse
+// AnswerLocalQuestions is *never* called directly as a result of a client API call
+// If new questions are created as a result of invoking client callbacks, they will be added to
+// the end of the question list, and m->NewQuestions will be set to indicate the first new question.
+// rr is a ResourceRecord in our cache
+// (kDNSRecordTypePacketAnswer/kDNSRecordTypePacketAdditional/kDNSRecordTypePacketUniqueAns/kDNSRecordTypePacketUniqueAdd)
+// NOTE: AnswerLocalQuestions calls AnswerQuestionWithResourceRecord which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void AnswerLocalQuestions(mDNS *const m, ResourceRecord *rr, const mDNSs32 timenow)
+       {
+       if (m->CurrentQuestion) debugf("AnswerLocalQuestions ERROR m->CurrentQuestion already set");
+       m->CurrentQuestion = m->ActiveQuestions;
+       while (m->CurrentQuestion && m->CurrentQuestion != m->NewQuestions)
+               {
+               DNSQuestion *q = m->CurrentQuestion;
+               m->CurrentQuestion = q->next;
+               if (ResourceRecordAnswersQuestion(rr, q))
+                       AnswerQuestionWithResourceRecord(m, q, rr, timenow);
+               }
+       m->CurrentQuestion = mDNSNULL;
+       }
+
+mDNSlocal void AnswerNewQuestion(mDNS *const m, const mDNSs32 timenow)
+       {
+       ResourceRecord *rr;
+       DNSQuestion *q = m->NewQuestions;               // Grab the question we're going to answer
+       m->NewQuestions = q->next;                              // Advance NewQuestions to the next (if any)
+
+       if (m->lock_rrcache) debugf("AnswerNewQuestion ERROR! Cache already locked!");
+       // This should be safe, because calling the client's question callback may cause the
+       // question list to be modified, but should not ever cause the rrcache list to be modified.
+       // If the client's question callback deletes the question, then m->CurrentQuestion will
+       // be advanced, and we'll exit out of the loop
+       m->lock_rrcache = 1;
+       if (m->CurrentQuestion) debugf("AnswerNewQuestion ERROR m->CurrentQuestion already set");
+       m->CurrentQuestion = q;         // Indicate which question we're answering, so we'll know if it gets deleted
+       for (rr=m->rrcache; rr && m->CurrentQuestion == q; rr=rr->next)
+               if (ResourceRecordAnswersQuestion(rr, q))
+                       AnswerQuestionWithResourceRecord(m, q, rr, timenow);
+       m->CurrentQuestion = mDNSNULL;
+       m->lock_rrcache = 0;
+       }
+
+mDNSlocal void FlushCacheRecords(mDNS *const m, mDNSIPAddr InterfaceAddr, const mDNSs32 timenow)
+       {
+       mDNSu32 count = 0;
+       ResourceRecord *rr;
+       for (rr = m->rrcache; rr; rr=rr->next)
+               {
+               if (rr->InterfaceAddr.NotAnInteger == InterfaceAddr.NotAnInteger)
+                       {
+                       // If the record's interface matches the one we're flushing,
+                       // then pretend we just received a 'goodbye' packet for this record.
+                       rr->TimeRcvd          = timenow;
+                       rr->UnansweredQueries = 0;
+                       rr->rroriginalttl     = 1;
+                       count++;
+                       }
+               }
+       
+       if (count) debugf("FlushCacheRecords Flushing %d Cache Entries on interface %.4a", count, &InterfaceAddr);
+       }
+
+// TidyRRCache
+// Throw away any cache records that have passed their TTL
+// First we prepare a list of records to delete, and pull them off the rrcache list
+// Then we go through the list of records to delete, calling the user's question callbacks if necessary
+// We do it in two phases like this to guard against the user's question callbacks modifying
+// the rrcache list while we're walking it.
+mDNSlocal void TidyRRCache(mDNS *const m, const mDNSs32 timenow)
+       {
+       mDNSu32 count = 0;
+       ResourceRecord **rr = &m->rrcache;
+       ResourceRecord *deletelist = mDNSNULL;
+       
+       if (m->lock_rrcache) { debugf("TidyRRCache ERROR! Cache already locked!"); return; }
+       m->lock_rrcache = 1;
+       
+       while (*rr)
+               {
+               mDNSu32 timesincercvd = (mDNSu32)(timenow - (*rr)->TimeRcvd);
+               if ((*rr)->rroriginalttl > timesincercvd / mDNSPlatformOneSecond)
+                       rr=&(*rr)->next;                        // If TTL is greater than time elapsed, save this record
+               else
+                       {
+                       ResourceRecord *r = *rr;        // Else,
+                       *rr = r->next;                          // detatch this record from the cache list
+                       r->next = deletelist;           // and move it onto the list of things to delete
+                       deletelist = r;
+                       count++;
+                       }
+               }
+       
+       if (count) verbosedebugf("TidyRRCache Deleting %d Expired Cache Entries", count);
+
+       m->lock_rrcache = 0;
+
+       while (deletelist)
+               {
+               ResourceRecord *r = deletelist;
+               verbosedebugf("TidyRRCache: Deleted %##s (%s)", r->name.c, DNSTypeName(r->rrtype));
+               deletelist = deletelist->next;
+               AnswerLocalQuestions(m, r, timenow);
+               r->next = m->rrcache_free;      // and move it back to the free list
+               m->rrcache_free = r;
+               m->rrcache_used--;
+               }
+       }
+
+mDNSlocal ResourceRecord *GetFreeCacheRR(mDNS *const m, const mDNSs32 timenow)
+       {
+       ResourceRecord *r = m->rrcache_free;
+
+       if (m->lock_rrcache) { debugf("GetFreeCacheRR ERROR! Cache already locked!"); return(mDNSNULL); }
+       m->lock_rrcache = 1;
+       
+       if (r)          // If there are records in the free list, take one
+               {
+               m->rrcache_free = r->next;
+               m->rrcache_used++;
+               if (m->rrcache_used >= m->rrcache_report)
+                       {
+                       debugf("RR Cache now using %d records", m->rrcache_used);
+                       m->rrcache_report *= 2;
+                       }
+               }
+       else            // Else search for a candidate to recycle
+               {
+               ResourceRecord **rr = &m->rrcache;
+               ResourceRecord **best = mDNSNULL;
+               mDNSs32 bestage = -1;
+
+               while (*rr)
+                       {
+                       mDNSs32 timesincercvd = timenow - (*rr)->TimeRcvd;
+
+                       // Records we've only just received are not candidates for deletion
+                       if (timesincercvd > 0)
+                               {
+                               // Work out a weighted age, which is the number of seconds since this record was last used,
+                               // divided by the number of times it has been used (we want to keep frequently used records longer).
+                               mDNSs32 count = (*rr)->UseCount < 100 ? 1 + (mDNSs32)(*rr)->UseCount : 100;
+                               mDNSs32 age = (timenow - (*rr)->LastUsed) / count;
+                               mDNSu8 rtype = ((*rr)->RecordType) & ~kDNSRecordTypeUniqueMask;
+                               if (rtype == kDNSRecordTypePacketAnswer) age /= 2;              // Keep answer records longer than additionals
+
+                               // Records that answer still-active questions are not candidates for deletion
+                               if (bestage < age && !CacheRRActive(m, *rr)) { best = rr; bestage = age; }
+                               }
+
+                       rr=&(*rr)->next;
+                       }
+
+               if (best)
+                       {
+                       r = *best;                                                      // Remember the record we chose
+                       *best = r->next;                                        // And detatch it from the free list
+                       }
+               }
+
+       m->lock_rrcache = 0;
+
+       if (r) mDNSPlatformMemZero(r, sizeof(*r));
+       return(r);
+       }
+
+mDNSlocal void ScheduleNextTask(const mDNS *const m)
+       {
+       const mDNSs32 timenow = mDNSPlatformTimeNow();
+       mDNSs32 nextevent = timenow + 0x78000000;
+       const char *msg = "No Event", *sign="";
+       mDNSs32 interval, fraction;
+
+       DNSQuestion *q;
+       ResourceRecord *rr;
+       
+       if (m->mDNSPlatformStatus != mStatus_NoError)
+               return;
+       
+       // 1. If sleeping, do nothing
+       if (m->SleepState)
+               {
+               debugf("ScheduleNextTask: Sleeping");
+               return;
+               }
+       
+       // 2. If we have new questions added to the list, we need to answer them from cache ASAP
+       if (m->NewQuestions)
+               {
+               nextevent = timenow;
+               msg = "New Questions";
+               }
+       else
+               {
+               // 3. Scan cache to see if any resource records are going to expire
+               for (rr = m->rrcache; rr; rr=rr->next)
+                       {
+                       mDNSs32 onetenth = ((mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond) / 10;
+                       mDNSs32 t0 = rr->TimeRcvd + (mDNSs32)rr->rroriginalttl * mDNSPlatformOneSecond;
+                       mDNSs32 t1 = t0 - onetenth;
+                       mDNSs32 t2 = t1 - onetenth;
+                       if (rr->UnansweredQueries < 1 && nextevent - t2 > 0 && CacheRRActive(m, rr))
+                               {
+                               nextevent = t2;
+                               msg = "Penultimate Query";
+                               }
+                       else if (rr->UnansweredQueries < 2 && nextevent - t1 > 0 && CacheRRActive(m, rr))
+                               {
+                               nextevent = t1;
+                               msg = "Final Expiration Query";
+                               }
+                       else if (nextevent - t0 > 0)
+                               {
+                               nextevent = t0;
+                               msg = "Cache Tidying";
+                               }
+                       }
+               
+               // 4. If we're suppressing sending right now, don't bother searching for packet generation events --
+               // but do make sure we come back at the end of the suppression time to check again
+               if (m->SuppressSending)
+                       {
+                       if (nextevent - m->SuppressSending > 0)
+                               {
+                               nextevent = m->SuppressSending;
+                               msg = "Send Suppressed Packets";
+                               }
+                       }
+               else
+                       {
+                       // 5. Scan list of active questions to see if we need to send any queries
+                       for (q = m->ActiveQuestions; q; q=q->next)
+                               if (TimeToSendThisQuestion(q, nextevent))
+                                       {
+                                       nextevent = q->NextQTime;
+                                       msg = "Send Questions";
+                                       }
+
+                       // 6. Scan list of local resource records to see if we have any
+                       // deregistrations, probes, announcements, or replies to send
+                       for (rr = m->ResourceRecords; rr; rr=rr->next)
+                               {
+                               if (rr->RecordType == kDNSRecordTypeDeregistering)
+                                       {
+                                       nextevent = timenow;
+                                       msg = "Send Deregistrations";
+                                       }
+                               else if (rr->SendPriority >= kDNSSendPriorityAnswer && ResourceRecordIsValidAnswer(rr))
+                                       {
+                                       nextevent = timenow;
+                                       msg = "Send Answers";
+                                       }
+                               else if (rr->RecordType == kDNSRecordTypeUnique && nextevent - rr->NextSendTime > 0)
+                                       {
+                                       nextevent = rr->NextSendTime;
+                                       msg = "Send Probes";
+                                       }
+                               else if (rr->AnnounceCount && nextevent - rr->NextSendTime > 0 && ResourceRecordIsValidAnswer(rr))
+                                       {
+                                       nextevent = rr->NextSendTime;
+                                       msg = "Send Announcements";
+                                       }
+                               }
+                       }
+               }
+
+       interval = nextevent - timenow;
+       if (interval < 0) { interval = -interval; sign = "-"; }
+       fraction = interval % mDNSPlatformOneSecond;
+       verbosedebugf("ScheduleNextTask: Next event: <%s> in %s%d.%03d seconds", msg, sign,
+               interval / mDNSPlatformOneSecond, fraction * 1000 / mDNSPlatformOneSecond);
+
+       mDNSPlatformScheduleTask(m, nextevent);
+       }
+
+mDNSlocal mDNSs32 mDNS_Lock(mDNS *const m)
+       {
+       mDNSPlatformLock(m);
+       ++m->mDNS_busy;
+       return(mDNSPlatformTimeNow());
+       }
+
+mDNSlocal void mDNS_Unlock(mDNS *const m)
+       {
+       // Upon unlocking, we've usually added some new work to the task list.
+       // If we don't decrement mDNS_busy to zero, then we don't have to worry about calling
+       // ScheduleNextTask(), because the last lock holder will do it for us on the way out.
+       if (--m->mDNS_busy == 0) ScheduleNextTask(m);
+       mDNSPlatformUnlock(m);
+       }
+
+mDNSexport void mDNSCoreTask(mDNS *const m)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+       verbosedebugf("mDNSCoreTask");
+       if (m->mDNS_busy > 1) debugf("mDNSCoreTask: Locking failure! mDNS already busy");
+       if (m->CurrentQuestion) debugf("mDNSCoreTask: ERROR! m->CurrentQuestion already set");
+       
+       if (m->SuppressProbes && timenow - m->SuppressProbes >= 0)
+               m->SuppressProbes = 0;
+
+       // 1. See if we can answer any of our new local questions from the cache
+       while (m->NewQuestions) AnswerNewQuestion(m, timenow);
+
+       // 2. See what packets we need to send
+       if (m->mDNSPlatformStatus != mStatus_NoError || m->SleepState)
+               {
+               // If the platform code is currently non-operational,
+               // then we'll just complete deregistrations immediately,
+               // without waiting for the goodbye packet to be sent
+               DiscardDeregistrations(m, timenow);
+               }
+       else if (m->SuppressSending == 0 || timenow - m->SuppressSending >= 0)
+               {
+               // If the platform code is ready,
+               // and we're not suppressing packet generation right now
+               // send our responses, probes, and questions
+               m->SuppressSending = 0;
+               while (HaveResponses(m, timenow)) SendResponses(m, timenow);
+               while (HaveQueries  (m, timenow)) SendQueries  (m, timenow);
+               }
+
+       if (m->rrcache_size) TidyRRCache(m, timenow);
+
+       mDNS_Unlock(m);
+       }
+
+mDNSexport void mDNSCoreSleep(mDNS *const m, mDNSBool sleepstate)
+       {
+       ResourceRecord *rr;
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+       m->SleepState = sleepstate;
+       debugf("mDNSCoreSleep: %d", sleepstate);
+
+       if (sleepstate)
+               {
+               // First mark all the records we need to deregister
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       if (rr->RecordType == kDNSRecordTypeShared && rr->AnnounceCount < DefaultAnnounceCountForTypeShared)
+                               rr->rrremainingttl = 0;
+               while (HaveResponses(m, timenow)) SendResponses(m, timenow);
+               }
+       else
+               {
+               DNSQuestion *q;
+
+               for (rr = m->ResourceRecords; rr; rr=rr->next)
+                       {
+                       if (rr->RecordType == kDNSRecordTypeVerified) rr->RecordType = kDNSRecordTypeUnique;
+                       rr->ProbeCount        = (rr->RecordType == kDNSRecordTypeUnique) ? DefaultProbeCountForTypeUnique : (mDNSu8)0;
+                       rr->AnnounceCount     = DefaultAnnounceCountForRecordType(rr->RecordType);
+                       rr->NextSendInterval  = DefaultSendIntervalForRecordType(rr->RecordType);
+                       rr->NextSendTime      = timenow;
+                       }
+               for (q = m->ActiveQuestions; q; q=q->next)              // Scan our list of questions
+                       if (!q->DuplicateOf)
+                               {
+                               q->NextQTime     = timenow;
+                               q->ThisQInterval = mDNSPlatformOneSecond;  // MUST NOT be zero for an active question
+                               q->NextQInterval = mDNSPlatformOneSecond;
+                               }
+               }
+
+       mDNS_Unlock(m);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - Packet Reception Functions
+#endif
+
+mDNSlocal mDNSBool AddRecordToResponseList(ResourceRecord **nrp,
+       ResourceRecord *rr, const mDNSu8 *answerto, ResourceRecord *additionalto)
+       {
+       if (rr->NextResponse == mDNSNULL && nrp != &rr->NextResponse)
+               {
+               *nrp = rr;
+               rr->NR_AnswerTo     = answerto;
+               rr->NR_AdditionalTo = additionalto;
+               return(mDNStrue);
+               }
+       else debugf("AddRecordToResponseList: %##s (%s) already in list", rr->name.c, DNSTypeName(rr->rrtype));
+       return(mDNSfalse);
+       }
+
+#define MustSendRecord(RR) ((RR)->NR_AnswerTo || (RR)->NR_AdditionalTo)
+
+mDNSlocal mDNSu8 *GenerateUnicastResponse(const DNSMessage *const query, const mDNSu8 *const end,
+       const mDNSIPAddr InterfaceAddr, DNSMessage *const reply, ResourceRecord  *ResponseRecords)
+       {
+       const mDNSu8    *const limit     = reply->data + sizeof(reply->data);
+       const mDNSu8    *ptr             = query->data;
+       mDNSu8          *responseptr     = reply->data;
+       ResourceRecord  *rr;
+       int i;
+
+       // Initialize the response fields so we can answer the questions
+       InitializeDNSMessage(&reply->h, query->h.id, ResponseFlags);
+
+       // ***
+       // *** 1. Write out the list of questions we are actually going to answer with this packet
+       // ***
+       for (i=0; i<query->h.numQuestions; i++)                                         // For each question...
+               {
+               DNSQuestion q;
+               ptr = getQuestion(query, ptr, end, InterfaceAddr, &q);  // get the question...
+               if (!ptr) return(mDNSNULL);
+
+               for (rr=ResponseRecords; rr; rr=rr->NextResponse)               // and search our list of proposed answers
+                       {
+                       if (rr->NR_AnswerTo == ptr)                                                     // If we're going to generate a record answering this question
+                               {                                                                                               // then put the question in the question section
+                               responseptr = putQuestion(reply, responseptr, limit, &q.name, q.rrtype, q.rrclass);
+                               if (!responseptr) { debugf("GenerateUnicastResponse: Ran out of space for questions!"); return(mDNSNULL); }
+                               break;          // break out of the ResponseRecords loop, and go on to the next question
+                               }
+                       }
+               }
+
+       if (reply->h.numQuestions == 0) { debugf("GenerateUnicastResponse: ERROR! Why no questions?"); return(mDNSNULL); }
+
+       // ***
+       // *** 2. Write answers and additionals
+       // ***
+       for (rr=ResponseRecords; rr; rr=rr->NextResponse)
+               {
+               if (MustSendRecord(rr))
+                       {
+                       if (rr->NR_AnswerTo)
+                               {
+                               mDNSu8 *p = putResourceRecord(reply, responseptr, &reply->h.numAnswers, rr, mDNSNULL, 0);
+                               if (p) responseptr = p;
+                               else { debugf("GenerateUnicastResponse: Ran out of space for answers!"); reply->h.flags.b[0] |= kDNSFlag0_TC; }
+                               }
+                       else
+                               {
+                               mDNSu8 *p = putResourceRecord(reply, responseptr, &reply->h.numAdditionals, rr, mDNSNULL, 0);
+                               if (p) responseptr = p;
+                               else debugf("GenerateUnicastResponse: No more space for additionals");
+                               }
+                       }
+               }
+       return(responseptr);
+       }
+
+// ResourceRecord *pktrr is the ResourceRecord from the response packet we've witnessed on the network
+// ResourceRecord *rr is our ResourceRecord
+// Returns 0 if there is no conflict
+// Returns +1 if there was a conflict and we won
+// Returns -1 if there was a conflict and we lost and have to rename
+mDNSlocal int CompareRData(ResourceRecord *pkt, ResourceRecord *our)
+       {
+       mDNSu8 pktdata[256], *pktptr = pktdata, *pktend;
+       mDNSu8 ourdata[256], *ourptr = ourdata, *ourend;
+       if (!pkt) { debugf("CompareRData ERROR: pkt is NULL"); return(+1); }
+       if (!our) { debugf("CompareRData ERROR: our is NULL"); return(+1); }
+
+       pktend = putRData(mDNSNULL, pktdata, pktdata + sizeof(pktdata), pkt->rrtype, pkt->rdata);
+       ourend = putRData(mDNSNULL, ourdata, ourdata + sizeof(ourdata), our->rrtype, our->rdata);
+       while (pktptr < pktend && ourptr < ourend && *pktptr == *ourptr) { pktptr++; ourptr++; }
+       if (pktptr >= pktend && ourptr >= ourend) return(0);                    // If data identical, not a conflict
+
+       if (pktptr >= pktend) return(-1);                                                               // Packet data is substring; We lost
+       if (ourptr >= ourend) return(+1);                                                               // Our data is substring; We won
+       if (*pktptr < *ourptr) return(-1);                                                              // Packet data is numerically lower; We lost
+       if (*pktptr > *ourptr) return(+1);                                                              // Our data is numerically lower; We won
+       
+       debugf("CompareRData: How did we get here?");
+       return(-1);
+       }
+
+// Find the canonical DependentOn record for this RR received in a packet.
+// The DependentOn pointer is typically used for the TXT record of service registrations
+// It indicates that there is no inherent conflict detection for the TXT record
+// -- it depends on the SRV record to resolve name conflicts
+// If we find any identical ResourceRecord in our authoritative list, then follow its DependentOn
+// pointers (if any) to make sure we return the canonical DependentOn record
+// If the record has no DependentOn, then just return that record's pointer
+// Returns NULL if we don't have any local RRs that are identical to the one from the packet
+mDNSlocal const ResourceRecord *FindDependentOn(const mDNS *const m, const ResourceRecord *const pktrr)
+       {
+       const ResourceRecord *rr;
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               {
+               if (IdenticalResourceRecordAnyInterface(rr, pktrr))
+                       {
+                       while (rr->DependentOn) rr = rr->DependentOn;
+                       return(rr);
+                       }
+               }
+       return(mDNSNULL);
+       }
+
+// Find the canonical RRSet pointer for this RR received in a packet.
+// If we find any identical ResourceRecord in our authoritative list, then follow its RRSet
+// pointers (if any) to make sure we return the canonical member of this name/type/class
+// Returns NULL if we don't have any local RRs that are identical to the one from the packet
+mDNSlocal const ResourceRecord *FindRRSet(const mDNS *const m, const ResourceRecord *const pktrr)
+       {
+       const ResourceRecord *rr;
+       for (rr = m->ResourceRecords; rr; rr=rr->next)
+               {
+               if (IdenticalResourceRecordAnyInterface(rr, pktrr))
+                       {
+                       while (rr->RRSet && rr != rr->RRSet) rr = rr->RRSet;
+                       return(rr);
+                       }
+               }
+       return(mDNSNULL);
+       }
+
+// PacketRRConflict is called when we've received an RR (pktrr) which has the same name
+// as one of our records (our) but different rdata.
+// 1. If our record is not a type that's supposed to be unique, we don't care.
+// 2a. If our record is marked as dependent on some other record for conflict detection, ignore this one.
+// 2b. If the packet rr exactly matches one of our other RRs, and *that* record's DependentOn pointer
+//     points to our record, ignore this conflict (e.g. the packet record matches one of our
+//     TXT records, and that record is marked as dependent on 'our', its SRV record).
+// 3. If we have some *other* RR that exactly matches the one from the packet, and that record and our record
+//    are members of the same RRSet, then this is not a conflict.
+mDNSlocal mDNSBool PacketRRConflict(const mDNS *const m, const ResourceRecord *const our, const ResourceRecord *const pktrr)
+       {
+       const ResourceRecord *ourset = our->RRSet ? our->RRSet : our;
+
+       // If not supposed to be unique, not a conflict
+       if (!(our->RecordType & kDNSRecordTypeUniqueMask)) return(mDNSfalse);
+
+       // If a dependent record, not a conflict
+       if (our->DependentOn || FindDependentOn(m, pktrr) == our) return(mDNSfalse);
+
+       // If the pktrr matches a member of ourset, not a conflict
+       if (FindRRSet(m, pktrr) == ourset) return(mDNSfalse);
+
+       // Okay, this is a conflict
+       return(mDNStrue);
+       }
+
+// NOTE: ResolveSimultaneousProbe calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void ResolveSimultaneousProbe(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
+       DNSQuestion *q, ResourceRecord *our, const mDNSs32 timenow)
+       {
+       int i;
+       const mDNSu8 *ptr = LocateAuthorities(query, end);
+       mDNSBool FoundUpdate = mDNSfalse;
+
+       for (i = 0; i < query->h.numAuthorities; i++)
+               {
+               ResourceRecord pktrr;
+               ptr = getResourceRecord(query, ptr, end, q->InterfaceAddr, 0, 0, &pktrr, mDNSNULL);
+               if (!ptr) break;
+               if (ResourceRecordAnswersQuestion(&pktrr, q))
+                       {
+                       FoundUpdate = mDNStrue;
+                       if (PacketRRConflict(m, our, &pktrr))
+                               {
+                               int result          = (int)pktrr.rrclass - (int)our->rrclass;
+                               if (!result) result = (int)pktrr.rrtype  - (int)our->rrtype;
+                               if (!result) result = CompareRData(&pktrr, our);
+                               switch (result)
+                                       {
+                                       case  1:        debugf("ResolveSimultaneousProbe: %##s (%s): We won",  our->name.c, DNSTypeName(our->rrtype));
+                                                               break;
+                                       case  0:        break;
+                                       case -1:        debugf("ResolveSimultaneousProbe: %##s (%s): We lost", our->name.c, DNSTypeName(our->rrtype));
+                                                               mDNS_Deregister_internal(m, our, timenow, mDNS_Dereg_conflict);
+                                                               return;
+                                       }
+                               }
+                       }
+               }
+       if (!FoundUpdate)
+               debugf("ResolveSimultaneousProbe: %##s (%s): No Update Record found", our->name.c, DNSTypeName(our->rrtype));
+       }
+
+// ProcessQuery examines a received query to see if we have any answers to give
+mDNSlocal mDNSu8 *ProcessQuery(mDNS *const m, const DNSMessage *const query, const mDNSu8 *const end,
+       const mDNSIPAddr srcaddr, const mDNSIPAddr InterfaceAddr,
+       DNSMessage *const replyunicast, mDNSBool replymulticast, const mDNSs32 timenow)
+       {
+       ResourceRecord  *ResponseRecords = mDNSNULL;
+       ResourceRecord **nrp             = &ResponseRecords;
+       mDNSBool         delayresponse   = mDNSfalse;
+       mDNSBool         answers         = mDNSfalse;
+       const mDNSu8    *ptr             = query->data;
+       mDNSu8          *responseptr     = mDNSNULL;
+       ResourceRecord  *rr, *rr2;
+       int i;
+
+       // If TC flag is set, it means we should expect additional duplicate suppression info may be coming in another packet.
+       if (query->h.flags.b[0] & kDNSFlag0_TC) delayresponse = mDNStrue;
+
+       // ***
+       // *** 1. Parse Question Section and mark potential answers
+       // ***
+       for (i=0; i<query->h.numQuestions; i++)                                         // For each question...
+               {
+               int NumAnswersForThisQuestion = 0;
+               DNSQuestion q;
+               ptr = getQuestion(query, ptr, end, InterfaceAddr, &q);  // get the question...
+               if (!ptr) goto exit;
+               
+               // Note: We use the m->CurrentRecord mechanism here because calling ResolveSimultaneousProbe
+               // can result in user callbacks which may change the record list and/or question list.
+               // Also note: we just mark potential answer records here, without trying to build the
+               // "ResponseRecords" list, because we don't want to risk user callbacks deleting records
+               //  from that list while we're in the middle of trying to build it.
+               if (m->CurrentRecord) debugf("ProcessQuery ERROR m->CurrentRecord already set");
+               m->CurrentRecord = m->ResourceRecords;
+               while (m->CurrentRecord)
+                       {
+                       rr = m->CurrentRecord;
+                       m->CurrentRecord = rr->next;
+                       if (ResourceRecordAnswersQuestion(rr, &q))
+                               {
+                               if (rr->RecordType == kDNSRecordTypeUnique)
+                                       ResolveSimultaneousProbe(m, query, end, &q, rr, timenow);
+                               else if (ResourceRecordIsValidAnswer(rr))
+                                       {
+                                       NumAnswersForThisQuestion++;
+                                       if (!rr->NR_AnswerTo) rr->NR_AnswerTo = ptr;    // Mark as potential answer
+                                       }
+                               }
+                       }
+               // If we couldn't answer this question, someone else might be able to,
+               // so use random delay on response to reduce collisions
+               if (NumAnswersForThisQuestion == 0) delayresponse = mDNStrue;
+               }
+
+       // ***
+       // *** 2. Now we can safely build the list of marked answers
+       // ***
+       for (rr = m->ResourceRecords; rr; rr=rr->next)                          // Now build our list of potential answers
+               if (rr->NR_AnswerTo)                                                                    // If we marked the record...
+                       if (AddRecordToResponseList(nrp, rr, rr->NR_AnswerTo, mDNSNULL))        // ... add it to the list
+                               {
+                               nrp = &rr->NextResponse;
+                               if (rr->RecordType == kDNSRecordTypeShared) delayresponse = mDNStrue;
+                               }
+
+       // ***
+       // *** 3. Add additional records
+       // ***
+       for (rr=ResponseRecords; rr; rr=rr->NextResponse)                       // For each record we plan to put
+               {
+               // (Note: This is an "if", not a "while". If we add a record, we'll find it again
+               // later in the "for" loop, and we will follow further "additional" links then.)
+               if (rr->Additional1 && ResourceRecordIsValidInterfaceAnswer(rr->Additional1, InterfaceAddr) &&
+                       AddRecordToResponseList(nrp, rr->Additional1, mDNSNULL, rr))
+                       nrp = &rr->Additional1->NextResponse;
+
+               if (rr->Additional2 && ResourceRecordIsValidInterfaceAnswer(rr->Additional2, InterfaceAddr) &&
+                       AddRecordToResponseList(nrp, rr->Additional2, mDNSNULL, rr))
+                       nrp = &rr->Additional2->NextResponse;
+               
+               // For SRV records, automatically add the Address record(s) for the target host
+               if (rr->rrtype == kDNSType_SRV)
+                       for (rr2=m->ResourceRecords; rr2; rr2=rr2->next)                                        // Scan list of resource records
+                               if (rr2->rrtype == kDNSType_A &&                                                                // For all records type "A" ...
+                                       ResourceRecordIsValidInterfaceAnswer(rr2, InterfaceAddr) &&     // ... which are valid for answer ...
+                                       SameDomainName(&rr->rdata->u.srv.target, &rr2->name) &&         // ... whose name is the name of the SRV target
+                                       AddRecordToResponseList(nrp, rr2, mDNSNULL, rr))
+                                       nrp = &rr2->NextResponse;
+               }
+
+       // ***
+       // *** 4. Parse Answer Section and cancel any records disallowed by duplicate suppression
+       // ***
+       for (i=0; i<query->h.numAnswers; i++)                                           // For each record in the query's answer section...
+               {
+               // Get the record...
+               ResourceRecord pktrr, *rr;
+               ptr = getResourceRecord(query, ptr, end, InterfaceAddr, timenow, kDNSRecordTypePacketAnswer, &pktrr, mDNSNULL);
+               if (!ptr) goto exit;
+
+               // See if it suppresses any of our planned answers
+               for (rr=ResponseRecords; rr; rr=rr->NextResponse)
+                       if (MustSendRecord(rr) && SuppressDuplicate(&pktrr, rr))
+                               { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
+
+               // And see if it suppresses any previously scheduled answers
+               for (rr=m->ResourceRecords; rr; rr=rr->next)
+                       {
+                       // If this record has been requested by exactly one client, and that client is
+                       // the same one sending this query, then allow inter-packet duplicate suppression
+                       if (rr->Requester.NotAnInteger && rr->Requester.NotAnInteger == srcaddr.NotAnInteger)
+                               if (SuppressDuplicate(&pktrr, rr))
+                                       {
+                                       rr->SendPriority = 0;
+                                       rr->Requester    = zeroIPAddr;
+                                       }
+                       }
+               }
+
+       // ***
+       // *** 5. Cancel any additionals that were added because of now-deleted records
+       // ***
+       for (rr=ResponseRecords; rr; rr=rr->NextResponse)
+               if (rr->NR_AdditionalTo && !MustSendRecord(rr->NR_AdditionalTo))
+                       { rr->NR_AnswerTo = mDNSNULL; rr->NR_AdditionalTo = mDNSNULL; }
+
+       // ***
+       // *** 6. Mark the send flags on the records we plan to send
+       // ***
+       for (rr=ResponseRecords; rr; rr=rr->NextResponse)
+               {
+               if (MustSendRecord(rr))
+                       {
+                       // For oversized records which we are going to send back to the requester via unicast
+                       // anyway, don't waste network bandwidth by also sending them via multicast.
+                       // This means we lose passive conflict detection for these oversized records, but
+                       // that is a reasonable tradeoff -- these large records usually have an associated
+                       // SRV record with the same name which will catch conflicts for us anyway.
+                       mDNSBool LargeRecordWithUnicastReply = (rr->rdestimate > 1024 && replyunicast);
+
+                       if (rr->NR_AnswerTo)
+                               answers = mDNStrue;
+
+                       if (replymulticast && !LargeRecordWithUnicastReply)
+                               {
+                               // If this query has additional duplicate suppression info
+                               // coming in another packet, then remember the requesting IP address
+                               if (query->h.flags.b[0] & kDNSFlag0_TC)
+                                       {
+                                       // We can only store one IP address at a time per record, so if we've already
+                                       // stored one address, set it to some special distinguished value instead
+                                       if (rr->Requester.NotAnInteger == zeroIPAddr.NotAnInteger) rr->Requester = srcaddr;
+                                       else                                                       rr->Requester = onesIPAddr;
+                                       }
+                               if (rr->NR_AnswerTo)
+                                       {
+                                       // This is a direct answer in response to one of the questions
+                                       rr->SendPriority = kDNSSendPriorityAnswer;
+                                       }
+                               else
+                                       {
+                                       // This is an additional record supporting one of our answers
+                                       if (rr->SendPriority < kDNSSendPriorityAdditional)
+                                               rr->SendPriority = kDNSSendPriorityAdditional;
+                                       }
+                               }
+                       }
+               }
+
+       // ***
+       // *** 7. If we think other machines are likely to answer these questions, set our packet suppression timer
+       // ***
+       if (delayresponse && !m->SuppressSending)
+               {
+               // Pick a random delay between 20ms and 120ms.
+               m->SuppressSending = timenow + (mDNSPlatformOneSecond*2 + (mDNSs32)mDNSRandom((mDNSu32)mDNSPlatformOneSecond*10)) / 100;
+               if (m->SuppressSending == 0) m->SuppressSending = 1;
+               }
+
+       // ***
+       // *** 8. If query is from a legacy client, generate a unicast reply too
+       // ***
+       if (answers && replyunicast)
+               responseptr = GenerateUnicastResponse(query, end, InterfaceAddr, replyunicast, ResponseRecords);
+
+exit:
+       // ***
+       // *** 9. Finally, clear our NextResponse link chain ready for use next time
+       // ***
+       while (ResponseRecords)
+               {
+               rr = ResponseRecords;
+               ResponseRecords = rr->NextResponse;
+               rr->NextResponse    = mDNSNULL;
+               rr->NR_AnswerTo     = mDNSNULL;
+               rr->NR_AdditionalTo = mDNSNULL;
+               }
+       
+       return(responseptr);
+       }
+
+mDNSlocal void mDNSCoreReceiveQuery(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
+       const mDNSIPAddr srcaddr, const mDNSIPPort srcport, const mDNSIPAddr dstaddr, mDNSIPPort dstport, const mDNSIPAddr InterfaceAddr)
+       {
+       const mDNSs32 timenow        = mDNSPlatformTimeNow();
+       DNSMessage    response;
+       const mDNSu8 *responseend    = mDNSNULL;
+       DNSMessage   *replyunicast   = mDNSNULL;
+       mDNSBool      replymulticast = mDNSfalse;
+       
+       verbosedebugf("Received Query from %.4a:%d to %.4a:%d on %.4a with %d Question%s, %d Answer%s, %d Authorit%s, %d Additional%s",
+               &srcaddr, (mDNSu16)srcport.b[0]<<8 | srcport.b[1],
+               &dstaddr, (mDNSu16)dstport.b[0]<<8 | dstport.b[1],
+               &InterfaceAddr,
+               msg->h.numQuestions,   msg->h.numQuestions   == 1 ? "" : "s",
+               msg->h.numAnswers,     msg->h.numAnswers     == 1 ? "" : "s",
+               msg->h.numAuthorities, msg->h.numAuthorities == 1 ? "y" : "ies",
+               msg->h.numAdditionals, msg->h.numAdditionals == 1 ? "" : "s");
+
+       // If this was a unicast query, or it was from an old (non-port-5353) client, then send a unicast response
+       if (dstaddr.NotAnInteger != AllDNSLinkGroup.NotAnInteger || srcport.NotAnInteger != MulticastDNSPort.NotAnInteger)
+               replyunicast = &response;
+       
+       // If this was a multicast query, then we need to send a multicast response
+       if (dstaddr.NotAnInteger == AllDNSLinkGroup.NotAnInteger) replymulticast = mDNStrue;
+       
+       responseend = ProcessQuery(m, msg, end, srcaddr, InterfaceAddr, replyunicast, replymulticast, timenow);
+       if (replyunicast && responseend)
+               {
+               mDNSSendDNSMessage(m, replyunicast, responseend, InterfaceAddr, dstport, srcaddr, srcport);
+               verbosedebugf("Unicast Response: %d Answer%s, %d Additional%s on %.4a",
+                       replyunicast->h.numAnswers,     replyunicast->h.numAnswers     == 1 ? "" : "s",
+                       replyunicast->h.numAdditionals, replyunicast->h.numAdditionals == 1 ? "" : "s", &InterfaceAddr);
+               }
+       }
+
+// NOTE: mDNSCoreReceiveResponse calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSlocal void mDNSCoreReceiveResponse(mDNS *const m,
+       const DNSMessage *const response, const mDNSu8 *end, const mDNSIPAddr dstaddr, const mDNSIPAddr InterfaceAddr)
+       {
+       int i;
+       const mDNSs32 timenow = mDNSPlatformTimeNow();
+       
+       // We ignore questions (if any) in a DNS response packet
+       const mDNSu8 *ptr = LocateAnswers(response, end);
+
+       // All records in a DNS response packet are treated as equally valid statements of truth. If we want
+       // to guard against spoof replies, then the only credible protection against that is cryptographic
+       // security, e.g. DNSSEC., not worring about which section in the spoof packet contained the record
+       int totalrecords = response->h.numAnswers + response->h.numAuthorities + response->h.numAdditionals;
+
+       verbosedebugf("Received Response addressed to %.4a on %.4a with %d Question%s, %d Answer%s, %d Authorit%s, %d Additional%s",
+               &dstaddr, &InterfaceAddr,
+               response->h.numQuestions,   response->h.numQuestions   == 1 ? "" : "s",
+               response->h.numAnswers,     response->h.numAnswers     == 1 ? "" : "s",
+               response->h.numAuthorities, response->h.numAuthorities == 1 ? "y" : "ies",
+               response->h.numAdditionals, response->h.numAdditionals == 1 ? "" : "s");
+
+       // Other mDNS devices may issue unicast queries (which we correctly answer),
+       // but we never *issue* unicast queries, so if we ever receive a unicast
+       // response then it is someone trying to spoof us, so ignore it!
+       if (dstaddr.NotAnInteger != AllDNSLinkGroup.NotAnInteger)
+               { debugf("** Ignored attempted spoof unicast mDNS response packet **"); return; }
+
+       for (i = 0; i < totalrecords && ptr && ptr < end; i++)
+               {
+               ResourceRecord pktrr;
+               mDNSu8 RecordType = (i < response->h.numAnswers) ? kDNSRecordTypePacketAnswer : kDNSRecordTypePacketAdditional;
+               ptr = getResourceRecord(response, ptr, end, InterfaceAddr, timenow, RecordType, &pktrr, mDNSNULL);
+               if (!ptr) return;
+
+               // 1. Check that this packet resource record does not conflict with any of ours
+               if (m->CurrentRecord) debugf("mDNSCoreReceiveResponse ERROR m->CurrentRecord already set");
+               m->CurrentRecord = m->ResourceRecords;
+               while (m->CurrentRecord)
+                       {
+                       ResourceRecord *rr = m->CurrentRecord;
+                       m->CurrentRecord = rr->next;
+                       if (SameResourceRecordSignature(&pktrr, rr))            // If interface, name, type and class match...
+                               {                                                                                               // ... check to see if rdata is identical
+                               if (SameRData(pktrr.rrtype, pktrr.rdata, rr->rdata))
+                                       {
+                                       // If the RR in the packet is identical to ours, just check they're not trying to lower the TTL on us
+                                       if (pktrr.rroriginalttl >= rr->rroriginalttl || m->SleepState)
+                                               rr->SendPriority = kDNSSendPriorityNone;
+                                       else
+                                               rr->SendPriority = kDNSSendPriorityAnswer;
+                                       }
+                               else
+                                       {
+                                       // else, the packet RR has different rdata -- check to see if this is a conflict
+                                       if (PacketRRConflict(m, rr, &pktrr))
+                                               {
+                                               if (rr->rrtype == kDNSType_SRV)
+                                                       {
+                                                       debugf("mDNSCoreReceiveResponse: Our Data %d %##s", rr->rdata->RDLength,   rr->rdata->u.srv.target.c);
+                                                       debugf("mDNSCoreReceiveResponse: Pkt Data %d %##s", pktrr.rdata->RDLength, pktrr.rdata->u.srv.target.c);
+                                                       }
+                                               else if (rr->rrtype == kDNSType_TXT)
+                                                       {
+                                                       debugf("mDNSCoreReceiveResponse: Our Data %d %#s", rr->rdata->RDLength,   rr->rdata->u.txt.c);
+                                                       debugf("mDNSCoreReceiveResponse: Pkt Data %d %#s", pktrr.rdata->RDLength, pktrr.rdata->u.txt.c);
+                                                       }
+                                               else if (rr->rrtype == kDNSType_A)
+                                                       {
+                                                       debugf("mDNSCoreReceiveResponse: Our Data %.4a", &rr->rdata->u.ip);
+                                                       debugf("mDNSCoreReceiveResponse: Pkt Data %.4a", &pktrr.rdata->u.ip);
+                                                       }
+                                               // If we've just whacked this record's ProbeCount, don't need to do it again
+                                               if (rr->ProbeCount <= DefaultProbeCountForTypeUnique)
+                                                       {
+                                                       if (rr->RecordType == kDNSRecordTypeVerified)
+                                                               {
+                                                               debugf("mDNSCoreReceiveResponse: Reseting to Probing: %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+                                                               // If we'd previously verified this record, put it back to probing state and try again
+                                                               rr->RecordType       = kDNSRecordTypeUnique;
+                                                               rr->ProbeCount       = DefaultProbeCountForTypeUnique + 1;
+                                                               rr->NextSendTime     = timenow;
+                                                               rr->NextSendInterval = DefaultSendIntervalForRecordType(kDNSRecordTypeUnique);
+                                                               }
+                                                       else
+                                                               {
+                                                               debugf("mDNSCoreReceiveResponse: Will rename %##s (%s)", rr->name.c, DNSTypeName(rr->rrtype));
+                                                               // If we're probing for this record (or we assumed it must be unique) we just failed
+                                                               mDNS_Deregister_internal(m, rr, timenow, mDNS_Dereg_conflict);
+                                                               }
+                                                       }
+                                               }
+                                       }
+                               }
+                       }
+
+               // 2. See if we want to add this packet resource record to our cache
+               if (m->rrcache_size)    // Only try to cache answers if we have a cache to put them in
+                       {
+                       ResourceRecord *rr;
+                       // 2a. Check if this packet resource record is already in our cache
+                       for (rr = m->rrcache; rr; rr=rr->next)
+                               {
+                               // If we found this exact resource record, refresh its TTL
+                               if (IdenticalResourceRecord(&pktrr, rr))
+                                       {
+                                       //debugf("Found RR %##s size %d already in cache", pktrr.name.c, pktrr.rdata->RDLength);
+                                       rr->TimeRcvd = timenow;
+                                       rr->UnansweredQueries = 0;
+                                       rr->NewData = mDNStrue;
+                                       // If we're deleting a record, push it out one second into the future
+                                       // to give other hosts on the network a chance to protest
+                                       if (pktrr.rroriginalttl == 0) rr->rroriginalttl = 1;
+                                       else rr->rroriginalttl = pktrr.rroriginalttl;
+                                       break;
+                                       }
+                               }
+
+                       // If packet resource record not in our cache, add it now
+                       // (unless it is just a deletion of a record we never had, in which case we don't care)
+                       if (!rr && pktrr.rroriginalttl > 0)
+                               {
+                               rr = GetFreeCacheRR(m, timenow);
+                               if (!rr) debugf("No cache space to add record for %#s", pktrr.name.c);
+                               else
+                                       {
+                                       *rr = pktrr;
+                                       rr->rdata = &rr->rdatastorage;  // For now, all cache records use local storage
+                                       rr->next = m->rrcache;
+                                       m->rrcache = rr;
+                                       if ((rr->RecordType & kDNSRecordTypeUniqueMask) == 0)
+                                               TriggerImmediateQuestions(m, rr, timenow);
+                                       //debugf("Adding RR %##s to cache (%d)", pktrr.name.c, m->rrcache_used);
+                                       AnswerLocalQuestions(m, rr, timenow);
+                                       }
+                               }
+                       }
+               }
+
+       // If we have a cache, then run through all the new records that we've just added,
+       // clear their 'NewData' flags, and if they were marked as unique in the packet,
+       // then search our cache for any records with the same name/type/class,
+       // and purge them if they are more than one second old.
+       if (m->rrcache_size)
+               {
+               ResourceRecord *rr;
+               for (rr = m->rrcache; rr; rr=rr->next)
+                       {
+                       if (rr->NewData)
+                               {
+                               rr->NewData = mDNSfalse;
+                               if (rr->RecordType & kDNSRecordTypeUniqueMask)
+                                       {
+                                       ResourceRecord *r;
+                                       for (r = m->rrcache; r; r=r->next)
+                                               if (SameResourceRecordSignature(rr, r) && timenow - r->TimeRcvd > mDNSPlatformOneSecond)
+                                                       r->rroriginalttl = 0;
+                                       }
+                               }
+                       }
+               TidyRRCache(m, timenow);
+               }
+       }
+
+mDNSexport void mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
+       mDNSIPAddr srcaddr, mDNSIPPort srcport, mDNSIPAddr dstaddr, mDNSIPPort dstport, mDNSIPAddr InterfaceAddr)
+       {
+       const mDNSu8 StdQ = kDNSFlag0_QR_Query    | kDNSFlag0_OP_StdQuery;
+       const mDNSu8 StdR = kDNSFlag0_QR_Response | kDNSFlag0_OP_StdQuery;
+       mDNSu8 QR_OP = (mDNSu8)(msg->h.flags.b[0] & kDNSFlag0_QROP_Mask);
+       
+       // Read the integer parts which are in IETF byte-order (MSB first, LSB second)
+       mDNSu8 *ptr = (mDNSu8 *)&msg->h.numQuestions;
+       msg->h.numQuestions   = (mDNSu16)((mDNSu16)ptr[0] <<  8 | ptr[1]);
+       msg->h.numAnswers     = (mDNSu16)((mDNSu16)ptr[2] <<  8 | ptr[3]);
+       msg->h.numAuthorities = (mDNSu16)((mDNSu16)ptr[4] <<  8 | ptr[5]);
+       msg->h.numAdditionals = (mDNSu16)((mDNSu16)ptr[6] <<  8 | ptr[7]);
+       
+       if (!m) { debugf("mDNSCoreReceive ERROR m is NULL"); return; }
+       
+       mDNS_Lock(m);
+       if (m->mDNS_busy > 1) debugf("mDNSCoreReceive: Locking failure! mDNS already busy");
+
+       if      (QR_OP == StdQ) mDNSCoreReceiveQuery   (m, msg, end, srcaddr, srcport, dstaddr, dstport, InterfaceAddr);
+       else if (QR_OP == StdR) mDNSCoreReceiveResponse(m, msg, end,                   dstaddr,          InterfaceAddr);
+       else debugf("Unknown DNS packet type %02X%02X (ignored)", msg->h.flags.b[0], msg->h.flags.b[1]);
+
+       // Packet reception often causes a change to the task list:
+       // 1. Inbound queries can cause us to need to send responses
+       // 2. Conflicing response packets received from other hosts can cause us to need to send defensive responses
+       // 3. Other hosts announcing deletion of shared records can cause us to need to re-assert those records
+       // 4. Response packets that answer questions may cause our client to issue new questions
+       mDNS_Unlock(m);
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark -
+#pragma mark - Searcher Functions
+#endif
+
+mDNSlocal DNSQuestion *FindDuplicateQuestion(const mDNS *const m, const DNSQuestion *const question)
+       {
+       DNSQuestion *q;
+       for (q = m->ActiveQuestions; q; q=q->next)              // Scan our list of questions
+               if (q->rrtype  == question->rrtype  &&
+                       q->rrclass == question->rrclass &&
+                       SameDomainName(&q->name, &question->name)) return(q);
+       return(mDNSNULL);
+       }
+
+// This is called after a question is deleted, in case other identical questions were being
+// suppressed as duplicates
+mDNSlocal void UpdateQuestionDuplicates(const mDNS *const m, const DNSQuestion *const question)
+       {
+       DNSQuestion *q;
+       for (q = m->ActiveQuestions; q; q=q->next)      // Scan our list of questions
+               if (q->DuplicateOf == question)                 // To see if any questions were referencing this as their duplicate
+                       {
+                       q->NextQTime     = question->NextQTime;
+                       q->ThisQInterval = question->ThisQInterval;
+                       q->NextQInterval = question->NextQInterval;
+                       q->DuplicateOf   = FindDuplicateQuestion(m, q);
+                       }
+       }
+
+mDNSlocal mStatus mDNS_StartQuery_internal(mDNS *const m, DNSQuestion *const question, const mDNSs32 timenow)
+       {
+       if (m->rrcache_size == 0)       // Can't do queries if we have no cache space allocated
+               return(mStatus_NoCache);
+       else
+               {
+               DNSQuestion **q = &m->ActiveQuestions;
+               while (*q && *q != question) q=&(*q)->next;
+
+               if (*q)
+                       {
+                       debugf("Error! Tried to add a question that's already in the active list");
+                       return(mStatus_AlreadyRegistered);
+                       }
+
+               question->next          = mDNSNULL;
+               question->NextQTime     = timenow;
+               question->ThisQInterval = mDNSPlatformOneSecond;  // MUST NOT be zero for an active question
+               question->NextQInterval = mDNSPlatformOneSecond;
+               question->DuplicateOf   = FindDuplicateQuestion(m, question);
+               *q = question;
+               
+               if (!m->NewQuestions) m->NewQuestions = question;
+
+               return(mStatus_NoError);
+               }
+       }
+
+mDNSlocal void mDNS_StopQuery_internal(mDNS *const m, DNSQuestion *const question)
+       {
+       DNSQuestion **q = &m->ActiveQuestions;
+       while (*q && *q != question) q=&(*q)->next;
+       if (*q) *q = (*q)->next;
+       else debugf("mDNS_StopQuery_internal: Question %##s (%s) not found in active list",
+               question->name.c, DNSTypeName(question->rrtype));
+
+       UpdateQuestionDuplicates(m, question);
+
+       question->next = mDNSNULL;
+       question->ThisQInterval = 0;
+       question->NextQInterval = 0;
+       
+       // If we just deleted the question that AnswerLocalQuestions() is about to look at,
+       // bump its pointer forward one question.
+       if (m->CurrentQuestion == question)
+               {
+               debugf("mDNS_StopQuery_internal: Just deleted the currently active question.");
+               m->CurrentQuestion = m->CurrentQuestion->next;
+               }
+
+       if (m->NewQuestions    == question)
+               {
+               debugf("mDNS_StopQuery_internal: Just deleted a new question that wasn't even answered yet.");
+               m->NewQuestions    = m->NewQuestions->next;
+               }
+       
+       }
+
+mDNSexport mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+       mStatus status = mDNS_StartQuery_internal(m, question, timenow);
+       mDNS_Unlock(m);
+       return(status);
+       }
+
+mDNSexport void mDNS_StopQuery(mDNS *const m, DNSQuestion *const question)
+       {
+       mDNS_Lock(m);
+       mDNS_StopQuery_internal(m, question);
+       mDNS_Unlock(m);
+       }
+
+mDNSexport mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
+       const domainname *const srv, const domainname *const domain,
+       const mDNSIPAddr InterfaceAddr, mDNSQuestionCallback *Callback, void *Context)
+       {
+       question->InterfaceAddr = InterfaceAddr;
+       question->name = *srv;
+       AppendDomainNameToName(&question->name, domain);
+       question->rrtype    = kDNSType_PTR;
+       question->rrclass   = kDNSClass_IN;
+       question->Callback  = Callback;
+       question->Context   = Context;
+       return(mDNS_StartQuery(m, question));
+       }
+
+mDNSlocal void FoundServiceInfoSRV(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
+       {
+       ServiceInfoQuery *query = (ServiceInfoQuery *)question->Context;
+       if (answer->rrremainingttl == 0) return;
+       if (answer->rrtype != kDNSType_SRV) return;
+
+       query->info->port = answer->rdata->u.srv.port;
+
+       // If this is our first answer, then set the GotSRV flag and start the address query
+       if (!query->GotSRV)
+               {
+               query->GotSRV             = mDNStrue;
+               query->qADD.name          = answer->rdata->u.srv.target;
+               mDNS_StartQuery_internal(m, &query->qADD, mDNSPlatformTimeNow());
+               }
+       // If this is not our first answer, only re-issue the address query if the target host name has changed
+       else if (!SameDomainName(&query->qADD.name, &answer->rdata->u.srv.target))
+               {
+               mDNS_StopQuery_internal(m, &query->qADD);
+               query->qADD.name          = answer->rdata->u.srv.target;
+               mDNS_StartQuery_internal(m, &query->qADD, mDNSPlatformTimeNow());
+               }
+
+       // Don't need to do ScheduleNextTask because this callback can only ever happen
+       // (a) as a result of an immediate result from the mDNS_StartQuery call, or
+       // (b) as a result of receiving a packet on the wire
+       // both of which will result in a subsequent ScheduleNextTask call of their own
+       }
+
+mDNSlocal void FoundServiceInfoTXT(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
+       {
+       ServiceInfoQuery *query = (ServiceInfoQuery *)question->Context;
+       if (answer->rrremainingttl == 0) return;
+       if (answer->rrtype != kDNSType_TXT) return;
+       if (answer->rdata->RDLength > sizeof(query->info->TXTinfo)) return;
+
+       query->GotTXT       = 1 + (query->GotTXT || query->GotADD);
+       query->info->TXTlen = answer->rdata->RDLength;
+       mDNSPlatformMemCopy(answer->rdata->u.txt.c, query->info->TXTinfo, answer->rdata->RDLength);
+
+       debugf("FoundServiceInfoTXT: %##s GotADD=%d", &query->info->name, query->GotADD);
+
+       if (query->Callback && query->GotADD)
+               query->Callback(m, query);
+       }
+
+mDNSlocal void FoundServiceInfoADD(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer)
+       {
+       ServiceInfoQuery *query = (ServiceInfoQuery *)question->Context;
+       if (answer->rrremainingttl == 0) return;
+       if (answer->rrtype != kDNSType_A) return;
+       query->GotADD = mDNStrue;
+       query->info->InterfaceAddr = answer->InterfaceAddr;
+       query->info->ip            = answer->rdata->u.ip;
+
+       debugf("FoundServiceInfoADD: %##s GotTXT=%d", &query->info->name, query->GotTXT);
+
+       // If query->GotTXT is 1 that means we already got a single TXT answer but didn't
+       // deliver it to the client at that time, so no further action is required.
+       // If query->GotTXT is 2 that means we either got more than one TXT answer,
+       // or we got a TXT answer and delivered it to the client at that time, so in either
+       // of these cases we may have lost information, so we should re-issue the TXT question.
+       if (query->GotTXT > 1)
+               {
+               mDNS_StopQuery_internal(m, &query->qTXT);
+               mDNS_StartQuery_internal(m, &query->qTXT, mDNSPlatformTimeNow());
+               }
+
+       if (query->Callback && query->GotTXT)
+               query->Callback(m, query);
+       }
+
+// On entry, the client must have set the name and InterfaceAddr fields of the ServiceInfo structure
+// If the query is not interface-specific, then InterfaceAddr may be zero
+// Each time the Callback is invoked, the remainder of the fields will have been filled in
+// In addition, InterfaceAddr will be updated to give the interface address corresponding to that reply
+mDNSexport mStatus mDNS_StartResolveService(mDNS *const m,
+       ServiceInfoQuery *query, ServiceInfo *info, ServiceInfoQueryCallback *Callback, void *Context)
+       {
+       mStatus status;
+       const mDNSs32 timenow = mDNS_Lock(m);
+       
+       query->qSRV.InterfaceAddr = info->InterfaceAddr;
+       query->qSRV.name          = info->name;
+       query->qSRV.rrtype        = kDNSType_SRV;
+       query->qSRV.rrclass       = kDNSClass_IN;
+       query->qSRV.Callback      = FoundServiceInfoSRV;
+       query->qSRV.Context       = query;
+
+       query->qTXT.InterfaceAddr = info->InterfaceAddr;
+       query->qTXT.name          = info->name;
+       query->qTXT.rrtype        = kDNSType_TXT;
+       query->qTXT.rrclass       = kDNSClass_IN;
+       query->qTXT.Callback      = FoundServiceInfoTXT;
+       query->qTXT.Context       = query;
+
+       query->qADD.InterfaceAddr = info->InterfaceAddr;
+       query->qADD.name.c[0]     = 0;
+       query->qADD.rrtype        = kDNSType_A;
+       query->qADD.rrclass       = kDNSClass_IN;
+       query->qADD.Callback      = FoundServiceInfoADD;
+       query->qADD.Context       = query;
+
+       query->GotSRV             = mDNSfalse;
+       query->GotTXT             = mDNSfalse;
+       query->GotADD             = mDNSfalse;
+
+       query->info               = info;
+       query->Callback           = Callback;
+       query->Context            = Context;
+
+//     info->name      = Must already be set up by client
+//     info->interface = Must already be set up by client
+       info->ip        = zeroIPAddr;
+       info->port      = zeroIPPort;
+       info->TXTlen    = 0;
+
+       status = mDNS_StartQuery_internal(m, &query->qSRV, timenow);
+       if (status == mStatus_NoError) status = mDNS_StartQuery_internal(m, &query->qTXT, timenow);
+       if (status != mStatus_NoError) mDNS_StopResolveService(m, query);
+
+       mDNS_Unlock(m);
+       return(status);
+       }
+
+mDNSexport void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *query)
+       {
+       mDNS_Lock(m);
+       if (query->qSRV.ThisQInterval) mDNS_StopQuery_internal(m, &query->qSRV);
+       if (query->qTXT.ThisQInterval) mDNS_StopQuery_internal(m, &query->qTXT);
+       if (query->qADD.ThisQInterval) mDNS_StopQuery_internal(m, &query->qADD);
+       mDNS_Unlock(m);
+       }
+
+mDNSexport mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNSu8 DomainType,
+       const mDNSIPAddr InterfaceAddr, mDNSQuestionCallback *Callback, void *Context)
+       {
+       question->InterfaceAddr = InterfaceAddr;
+       ConvertCStringToDomainName(mDNS_DomainTypeNames[DomainType], &question->name);
+       question->rrtype    = kDNSType_PTR;
+       question->rrclass   = kDNSClass_IN;
+       question->Callback  = Callback;
+       question->Context   = Context;
+       return(mDNS_StartQuery(m, question));
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark - Responder Functions
+#endif
+
+// Set up a ResourceRecord with sensible default values.
+// These defaults may be overwritten with new values before mDNS_Register is called
+mDNSexport void mDNS_SetupResourceRecord(ResourceRecord *rr, RData *RDataStorage, mDNSIPAddr InterfaceAddr,
+       mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, mDNSRecordCallback Callback, void *Context)
+       {
+       // Don't try to store a TTL bigger than we can represent in platform time units
+       if (ttl > 0x7FFFFFFFUL / mDNSPlatformOneSecond)
+               ttl = 0x7FFFFFFFUL / mDNSPlatformOneSecond;
+       else if (ttl == 0)              // And Zero TTL is illegal
+               ttl = 1;
+
+       // Field Group 1: Persistent metadata for Authoritative Records
+       rr->Additional1       = mDNSNULL;
+       rr->Additional2       = mDNSNULL;
+       rr->DependentOn       = mDNSNULL;
+       rr->RRSet             = mDNSNULL;
+       rr->Callback          = Callback;
+       rr->Context           = Context;
+
+       rr->RecordType        = RecordType;
+       rr->HostTarget        = mDNSfalse;
+       
+       // Field Group 2: Transient state for Authoritative Records (set in mDNS_Register_internal)
+       // Field Group 3: Transient state for Cache Records         (set in mDNS_Register_internal)
+
+       // Field Group 4: The actual information pertaining to this resource record
+       rr->InterfaceAddr     = InterfaceAddr;
+       rr->name.c[0]         = 0;              // MUST be set by client
+       rr->rrtype            = rrtype;
+       rr->rrclass           = kDNSClass_IN;
+       rr->rroriginalttl     = ttl;
+       rr->rrremainingttl    = ttl;
+//     rr->rdlength          = MUST set by client and/or in mDNS_Register_internal
+//     rr->rdestimate        = set in mDNS_Register_internal
+//     rr->rdata             = MUST be set by client
+
+       if (RDataStorage)
+               rr->rdata = RDataStorage;
+       else
+               {
+               rr->rdata = &rr->rdatastorage;
+               rr->rdata->MaxRDLength = sizeof(RDataBody);
+               }
+       }
+
+mDNSexport mStatus mDNS_Register(mDNS *const m, ResourceRecord *const rr)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+       mStatus status = mDNS_Register_internal(m, rr, timenow);
+       mDNS_Unlock(m);
+       return(status);
+       }
+
+mDNSexport mStatus mDNS_Update(mDNS *const m, ResourceRecord *const rr, mDNSu32 newttl,
+       RData *const newrdata, mDNSRecordUpdateCallback *Callback)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+       // If we already have an update queued up which has not gone through yet,
+       // give the client a chance to free that memory
+       if (rr->NewRData)
+               {
+               RData *n = rr->NewRData;
+               rr->NewRData = mDNSNULL;        // Clear the NewRData pointer ...
+               if (rr->UpdateCallback) rr->UpdateCallback(m, rr, n); // ...and let the client free this memory, if necessary
+               }
+       
+       rr->AnnounceCount    = DefaultAnnounceCountForRecordType(rr->RecordType);
+       rr->NextSendTime     = timenow;
+       if (rr->RecordType == kDNSRecordTypeUnique && m->SuppressProbes) rr->NextSendTime = m->SuppressProbes;
+       rr->NextSendInterval = DefaultSendIntervalForRecordType(rr->RecordType);
+       rr->NewRData         = newrdata;
+       rr->UpdateCallback   = Callback;
+       rr->rroriginalttl    = newttl;
+       rr->rrremainingttl   = newttl;
+       mDNS_Unlock(m);
+       return(mStatus_NoError);
+       }
+
+// NOTE: mDNS_Deregister calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSexport void mDNS_Deregister(mDNS *const m, ResourceRecord *const rr)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+       mDNS_Deregister_internal(m, rr, timenow, mDNS_Dereg_normal);
+       mDNS_Unlock(m);
+       }
+
+mDNSexport void mDNS_GenerateFQDN(mDNS *const m)
+       {
+       // Set up the Primary mDNS FQDN
+       m->hostname1.c[0] = 0;
+       AppendDomainLabelToName(&m->hostname1, &m->hostlabel);
+       AppendStringLabelToName(&m->hostname1, "local");
+
+       // Set up the Secondary mDNS FQDN
+       m->hostname2.c[0] = 0;
+       AppendDomainLabelToName(&m->hostname2, &m->hostlabel);
+       AppendStringLabelToName(&m->hostname2, "local");
+       AppendStringLabelToName(&m->hostname2, "arpa");
+
+       // Make sure that any SRV records (and the like) that reference our 
+       // host name in their rdata get updated to reference this new host name
+       UpdateHostNameTargets(m);
+       }
+
+mDNSlocal void HostNameCallback(mDNS *const m, ResourceRecord *const rr, mStatus result)
+       {
+       #pragma unused(rr)
+       switch (result)
+               {
+               case mStatus_NoError:
+                       debugf("HostNameCallback: %##s (%s) Name registered",   rr->name.c, DNSTypeName(rr->rrtype));
+                       break;
+               case mStatus_NameConflict:
+                       debugf("HostNameCallback: %##s (%s) Name conflict",     rr->name.c, DNSTypeName(rr->rrtype));
+                       break;
+               default:
+                       debugf("HostNameCallback: %##s (%s) Unknown result %d", rr->name.c, DNSTypeName(rr->rrtype), result);
+                       break;
+               }
+
+       if (result == mStatus_NameConflict)
+               {
+               NetworkInterfaceInfo *hr = mDNSNULL;
+               NetworkInterfaceInfo **p = &hr;
+               domainlabel oldlabel = m->hostlabel;
+
+               // 1. Deregister all our host sets
+               while (m->HostInterfaces)
+                       {
+                       NetworkInterfaceInfo *set = m->HostInterfaces;
+                       mDNS_DeregisterInterface(m, set);
+                       *p = set;
+                       p = &set->next;
+                       }
+               
+               // 2. Pick a new name
+               // First give the client callback a chance to pick a new name
+               if (m->Callback) m->Callback(m, mStatus_NameConflict);
+               // If the client callback didn't do it, add (or increment) an index ourselves
+               if (SameDomainLabel(m->hostlabel.c, oldlabel.c))
+                       IncrementLabelSuffix(&m->hostlabel, mDNSfalse);
+               mDNS_GenerateFQDN(m);
+               
+               // 3. Re-register all our host sets
+               while (hr)
+                       {
+                       NetworkInterfaceInfo *set = hr;
+                       hr = hr->next;
+                       mDNS_RegisterInterface(m, set);
+                       }
+               }
+       }
+
+mDNSlocal NetworkInterfaceInfo *FindFirstAdvertisedInterface(mDNS *const m)
+       {
+       NetworkInterfaceInfo *i;
+       for (i=m->HostInterfaces; i; i=i->next) if (i->Advertise) break;
+       return(i);
+       }
+
+mDNSexport mStatus mDNS_RegisterInterface(mDNS *const m, NetworkInterfaceInfo *set)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+       NetworkInterfaceInfo **p = &m->HostInterfaces;
+       
+       while (*p && *p != set) p=&(*p)->next;
+       if (*p)
+               {
+               debugf("Error! Tried to register a NetworkInterfaceInfo that's already in the list");
+               mDNS_Unlock(m);
+               return(mStatus_AlreadyRegistered);
+               }
+
+       if (set->Advertise)
+               {
+               char buffer[256];
+               NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
+               if (!primary) primary = set; // If no existing advertised interface, this new NetworkInterfaceInfo becomes our new primary
+               
+               mDNS_SetupResourceRecord(&set->RR_A1,  mDNSNULL, set->ip, kDNSType_A,   60, kDNSRecordTypeUnique,      HostNameCallback, set);
+               mDNS_SetupResourceRecord(&set->RR_A2,  mDNSNULL, set->ip, kDNSType_A,   60, kDNSRecordTypeUnique,      HostNameCallback, set);
+               mDNS_SetupResourceRecord(&set->RR_PTR, mDNSNULL, set->ip, kDNSType_PTR, 60, kDNSRecordTypeKnownUnique, mDNSNULL, mDNSNULL);
+       
+               // 1. Set up primary Address record to map from primary host name ("foo.local.") to IP address
+               set->RR_A1.name        = m->hostname1;
+               set->RR_A1.rdata->u.ip = set->ip;
+       
+               // 2. Set up secondary Address record to map from secondary host name ("foo.local.arpa.") to IP address
+               set->RR_A2.name        = m->hostname2;
+               set->RR_A2.rdata->u.ip = set->ip;
+       
+               // 3. Set up reverse-lookup PTR record to map from our address back to our primary host name
+               // Setting HostTarget tells DNS that the target of this PTR is to be automatically kept in sync if our host name changes
+               // Note: This is reverse order compared to a normal dotted-decimal IP address
+               mDNS_sprintf(buffer, "%d.%d.%d.%d.in-addr.arpa.", set->ip.b[3], set->ip.b[2], set->ip.b[1], set->ip.b[0]);
+               ConvertCStringToDomainName(buffer, &set->RR_PTR.name);
+               set->RR_PTR.HostTarget = mDNStrue;      // Tell mDNS that the target of this PTR is to be kept in sync with our host name
+       
+               set->RR_A1.RRSet = &primary->RR_A1;     // May refer to self
+               set->RR_A2.RRSet = &primary->RR_A2;     // May refer to self
+       
+               mDNS_Register_internal(m, &set->RR_A1,  timenow);
+               mDNS_Register_internal(m, &set->RR_A2,  timenow);
+               mDNS_Register_internal(m, &set->RR_PTR, timenow);
+       
+               // ... Add an HINFO record, etc.?
+               }
+
+       set->next = mDNSNULL;
+       *p = set;
+       mDNS_Unlock(m);
+       return(mStatus_NoError);
+       }
+
+mDNSlocal void mDNS_DeadvertiseInterface(mDNS *const m, NetworkInterfaceInfo *set, const mDNSs32 timenow)
+       {
+       NetworkInterfaceInfo *i;
+       // If we still have address records referring to this one, update them
+       NetworkInterfaceInfo *primary = FindFirstAdvertisedInterface(m);
+       ResourceRecord *A1 = primary ? &primary->RR_A1 : mDNSNULL;
+       ResourceRecord *A2 = primary ? &primary->RR_A2 : mDNSNULL;
+       for (i=m->HostInterfaces; i; i=i->next)
+               {
+               if (i->RR_A1.RRSet == &set->RR_A1) i->RR_A1.RRSet = A1;
+               if (i->RR_A2.RRSet == &set->RR_A2) i->RR_A2.RRSet = A2;
+               }
+
+       // Unregister these records
+       mDNS_Deregister_internal(m, &set->RR_A1,  timenow, mDNS_Dereg_normal);
+       mDNS_Deregister_internal(m, &set->RR_A2,  timenow, mDNS_Dereg_normal);
+       mDNS_Deregister_internal(m, &set->RR_PTR, timenow, mDNS_Dereg_normal);
+       }
+
+// NOTE: mDNS_DeregisterInterface calls mDNS_Deregister_internal which can call a user callback, which may change
+// the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSexport void mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set)
+       {
+       NetworkInterfaceInfo **p = &m->HostInterfaces;
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+       // Find this record in our list
+       while (*p && *p != set) p=&(*p)->next;
+       if (!*p) { debugf("mDNS_DeregisterInterface: NetworkInterfaceInfo not found in list"); return; }
+
+       // Unlink this record from our list
+       *p = (*p)->next;
+       set->next = mDNSNULL;
+
+       // Flush any cache entries we received on this interface
+       FlushCacheRecords(m, set->ip, timenow);
+
+       // If we were advertising on this interface, deregister now
+       // When doing the mDNS_Close processing, we first call mDNS_DeadvertiseInterface for each interface
+       // so by the time the platform support layer gets to call mDNS_DeregisterInterface,
+       // the address and PTR records have already been deregistered for it
+       if (set->Advertise && set->RR_A1.RecordType) mDNS_DeadvertiseInterface(m, set, timenow);
+
+       mDNS_Unlock(m);
+       }
+
+mDNSlocal void ServiceCallback(mDNS *const m, ResourceRecord *const rr, mStatus result)
+       {
+       #pragma unused(m)
+       ServiceRecordSet *sr = (ServiceRecordSet *)rr->Context;
+       switch (result)
+               {
+               case mStatus_NoError:
+                       if (rr == &sr->RR_SRV)
+                               debugf("ServiceCallback: Service RR_SRV %##s Registered", rr->name.c);
+                       else
+                               debugf("ServiceCallback: %##s (%s) ERROR Should only get mStatus_NoError callback for RR_SRV",
+                                       rr->name.c, DNSTypeName(rr->rrtype));
+                       break;
+
+               case mStatus_NameConflict:
+                       debugf("ServiceCallback: %##s (%s) Name Conflict", rr->name.c, DNSTypeName(rr->rrtype));
+                       break;
+
+               case mStatus_MemFree:
+                       if (rr == &sr->RR_PTR)
+                               debugf("ServiceCallback: Service RR_PTR %##s Memory Free", rr->name.c);
+                       else
+                               debugf("ServiceCallback: %##s (%s) ERROR Should only get mStatus_MemFree callback for RR_PTR",
+                                       rr->name.c, DNSTypeName(rr->rrtype));
+                       break;
+
+               default:
+                       debugf("ServiceCallback: %##s (%s) Unknown Result %d", rr->name.c, DNSTypeName(rr->rrtype), result);
+                       break;
+               }
+
+       // If we got a name conflict on either SRV or TXT, forcibly deregister this service, and record that we did that
+       if (result == mStatus_NameConflict) { sr->Conflict = mDNStrue; mDNS_DeregisterService(m, sr); return; }
+       
+       // If this ServiceRecordSet was forcibly deregistered, and now it's memory is ready for reuse,
+       // then we can now report the NameConflict to the client
+       if (result == mStatus_MemFree && sr->Conflict) result = mStatus_NameConflict;
+
+       if (sr->Callback) sr->Callback(m, sr, result);
+       }
+
+// Note:
+// Name is first label of domain name (any dots in the name are actual dots, not label separators)
+// Type is service type (e.g. "_printer._tcp.")
+// Domain is fully qualified domain name (i.e. ending with a null label)
+// We always register a TXT, even if it is empty (so that clients are not
+// left waiting forever looking for a nonexistent record.)
+mDNSexport mStatus mDNS_RegisterService(mDNS *const m, ServiceRecordSet *sr,
+       const domainlabel *const name, const domainname *const type, const domainname *const domain,
+       const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
+       mDNSServiceCallback Callback, void *Context)
+       {
+       mDNSs32 timenow;
+
+       sr->Callback = Callback;
+       sr->Context  = Context;
+       sr->Conflict = mDNSfalse;
+       if (host && host->c[0]) sr->Host = *host;
+       else sr->Host.c[0] = 0;
+       
+       mDNS_SetupResourceRecord(&sr->RR_PTR, mDNSNULL, zeroIPAddr, kDNSType_PTR, 24*3600, kDNSRecordTypeShared, ServiceCallback, sr);
+       mDNS_SetupResourceRecord(&sr->RR_SRV, mDNSNULL, zeroIPAddr, kDNSType_SRV, 60,      kDNSRecordTypeUnique, ServiceCallback, sr);
+       mDNS_SetupResourceRecord(&sr->RR_TXT, mDNSNULL, zeroIPAddr, kDNSType_TXT, 60,      kDNSRecordTypeUnique, ServiceCallback, sr);
+       
+       // If the client is registering an oversized TXT record,
+       // it is the client's responsibility to alloate a ServiceRecordSet structure that is large enough for it
+       if (sr->RR_TXT.rdata->MaxRDLength < txtlen)
+               sr->RR_TXT.rdata->MaxRDLength = txtlen;
+
+       if (ConstructServiceName(&sr->RR_PTR.name, mDNSNULL, type, domain) == mDNSNULL) return(mStatus_BadParamErr);
+       if (ConstructServiceName(&sr->RR_SRV.name, name,     type, domain) == mDNSNULL) return(mStatus_BadParamErr);
+       sr->RR_TXT.name = sr->RR_SRV.name;
+       
+       // 1. Set up the PTR record rdata to point to our service name
+       // We set up two additionals, so when a client asks for this PTR we automatically send the SRV and the TXT too
+       sr->RR_PTR.rdata->u.name = sr->RR_SRV.name;
+       sr->RR_PTR.Additional1 = &sr->RR_SRV;
+       sr->RR_PTR.Additional2 = &sr->RR_TXT;
+
+       // 2. Set up the SRV record rdata.
+       sr->RR_SRV.rdata->u.srv.priority = 0;
+       sr->RR_SRV.rdata->u.srv.weight   = 0;
+       sr->RR_SRV.rdata->u.srv.port     = port;
+
+       // Setting HostTarget tells DNS that the target of this SRV is to be automatically kept in sync with our host name
+       if (sr->Host.c[0]) sr->RR_SRV.rdata->u.srv.target = sr->Host;
+       else sr->RR_SRV.HostTarget = mDNStrue;
+
+       // 3. Set up the TXT record rdata,
+       // and set DependentOn because we're depending on the SRV record to find and resolve conflicts for us
+       if (txtinfo == mDNSNULL) sr->RR_TXT.rdata->RDLength = 0;
+       else if (txtinfo != sr->RR_TXT.rdata->u.txt.c)
+               {
+               sr->RR_TXT.rdata->RDLength = txtlen;
+               if (sr->RR_TXT.rdata->RDLength > sr->RR_TXT.rdata->MaxRDLength) return(mStatus_BadParamErr);
+               mDNSPlatformMemCopy(txtinfo, sr->RR_TXT.rdata->u.txt.c, txtlen);
+               }
+       sr->RR_TXT.DependentOn = &sr->RR_SRV;
+
+       // 4. We have no Extras yet
+       sr->Extras = mDNSNULL;
+
+       timenow = mDNS_Lock(m);
+       mDNS_Register_internal(m, &sr->RR_SRV, timenow);
+       mDNS_Register_internal(m, &sr->RR_TXT, timenow);
+       // We register the RR_PTR last, because we want to be sure that in the event of a forced call to
+       // mDNS_Close, the RR_PTR will be the last one to be forcibly deregistered, since that is what triggers
+       // the mStatus_MemFree callback to ServiceCallback, which in turn passes on the mStatus_MemFree back to
+       // the client callback, which is then at liberty to free the ServiceRecordSet memory at will. We need to
+       // make sure we've deregistered all our records and done any other necessary cleanup before that happens.
+       mDNS_Register_internal(m, &sr->RR_PTR, timenow);
+       mDNS_Unlock(m);
+
+       return(mStatus_NoError);
+       }
+
+mDNSexport mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl)
+       {
+       ExtraResourceRecord **e = &sr->Extras;
+       while (*e) e = &(*e)->next;
+
+       // If TTL is unspecified, make it 60 seconds, the same as the service's TXT and SRV default
+       if (ttl == 0) ttl = 60;
+
+       extra->next          = mDNSNULL;
+       mDNS_SetupResourceRecord(&extra->r, rdata, zeroIPAddr, extra->r.rrtype, ttl, kDNSRecordTypeUnique, ServiceCallback, sr);
+       extra->r.name        = sr->RR_SRV.name;
+       extra->r.DependentOn = &sr->RR_SRV;
+       
+       debugf("mDNS_AddRecordToService adding record to %##s", extra->r.name.c);
+       
+       *e = extra;
+       return(mDNS_Register(m, &extra->r));
+       }
+
+mDNSexport mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra)
+       {
+       ExtraResourceRecord **e = &sr->Extras;
+       while (*e && *e != extra) e = &(*e)->next;
+       if (!*e)
+               {
+               debugf("mDNS_RemoveRecordFromService failed to remove record from %##s", extra->r.name.c);
+               return(mStatus_BadReferenceErr);
+               }
+
+       debugf("mDNS_RemoveRecordFromService removing record from %##s", extra->r.name.c);
+       
+       *e = (*e)->next;
+       mDNS_Deregister(m, &extra->r);
+       return(mStatus_NoError);
+       }
+
+mDNSexport mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr)
+       {
+       domainlabel name;
+       domainname type, domain;
+       domainname *host = mDNSNULL;
+       ExtraResourceRecord *extras = sr->Extras;
+       mStatus err;
+
+       DeconstructServiceName(&sr->RR_SRV.name, &name, &type, &domain);
+       IncrementLabelSuffix(&name, mDNStrue);
+       debugf("Reregistering as %#s", name.c);
+       if (sr->RR_SRV.HostTarget == mDNSfalse && sr->Host.c[0]) host = &sr->Host;
+       
+       err = mDNS_RegisterService(m, sr, &name, &type, &domain,
+               host, sr->RR_SRV.rdata->u.srv.port, sr->RR_TXT.rdata->u.txt.c, sr->RR_TXT.rdata->RDLength,
+               sr->Callback, sr->Context);
+
+       while (!err && extras)
+               {
+               ExtraResourceRecord *e = extras;
+               extras = extras->next;
+               err = mDNS_AddRecordToService(m, sr, e, e->r.rdata, e->r.rroriginalttl);
+               }
+       
+       return(err);
+       }
+
+// NOTE: mDNS_DeregisterService calls mDNS_Deregister_internal which can call a user callback,
+// which may change the record list and/or question list.
+// Any code walking either list must use the CurrentQuestion and/or CurrentRecord mechanism to protect against this.
+mDNSexport void mDNS_DeregisterService(mDNS *const m, ServiceRecordSet *sr)
+       {
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+       // We use mDNS_Dereg_repeat because, in the event of a collision, some or all of
+       // these records could have already been automatically deregistered, and that's okay
+       mDNS_Deregister_internal(m, &sr->RR_SRV, timenow, mDNS_Dereg_repeat);
+       mDNS_Deregister_internal(m, &sr->RR_TXT, timenow, mDNS_Dereg_repeat);
+       while (sr->Extras)
+               {
+               ExtraResourceRecord *e = sr->Extras;
+               sr->Extras = sr->Extras->next;
+               mDNS_Deregister_internal(m, &e->r, timenow, mDNS_Dereg_repeat);
+               }
+
+       // Be sure to deregister the PTR last!
+       // Deregistering this record is what triggers the mStatus_MemFree callback to ServiceCallback,
+       // which in turn passes on the mStatus_MemFree (or mStatus_NameConflict) back to the client callback,
+       // which is then at liberty to free the ServiceRecordSet memory at will. We need to make sure
+       // we've deregistered all our records and done any other necessary cleanup before that happens.
+       mDNS_Deregister_internal(m, &sr->RR_PTR, timenow, mDNS_Dereg_normal);
+
+       mDNS_Unlock(m);
+       }
+
+mDNSexport mStatus mDNS_AdvertiseDomains(mDNS *const m, ResourceRecord *rr,
+       mDNSu8 DomainType, const mDNSIPAddr InterfaceAddr, char *domname)
+       {
+       mDNS_SetupResourceRecord(rr, mDNSNULL, InterfaceAddr, kDNSType_PTR, 24*3600, kDNSRecordTypeShared, mDNSNULL, mDNSNULL);
+       ConvertCStringToDomainName(mDNS_DomainTypeNames[DomainType], &rr->name);
+       ConvertCStringToDomainName(domname, &rr->rdata->u.name);
+       return(mDNS_Register(m, rr));
+       }
+
+// ***************************************************************************
+#if 0
+#pragma mark -
+#pragma mark -
+#pragma mark - Startup and Shutdown
+#endif
+
+mDNSexport mStatus mDNS_Init(mDNS *const m, mDNS_PlatformSupport *const p,
+       ResourceRecord *rrcachestorage, mDNSu32 rrcachesize, mDNSCallback *Callback, void *Context)
+       {
+       mStatus result;
+       mDNSu32 i;
+       
+       if (!rrcachestorage) rrcachesize = 0;
+       
+       m->p                  = p;
+       m->mDNSPlatformStatus = mStatus_Waiting;
+       m->Callback           = Callback;
+       m->Context            = Context;
+
+       m->mDNS_busy          = 0;
+
+       m->lock_rrcache       = 0;
+       m->lock_Questions     = 0;
+       m->lock_Records       = 0;
+
+       m->ActiveQuestions    = mDNSNULL;
+       m->NewQuestions       = mDNSNULL;
+       m->CurrentQuestion    = mDNSNULL;
+       m->rrcache_size       = rrcachesize;
+       m->rrcache_used       = 0;
+       m->rrcache_report     = 10;
+       m->rrcache_free       = rrcachestorage;
+       if (rrcachesize)
+               {
+               for (i=0; i<rrcachesize; i++) rrcachestorage[i].next = &rrcachestorage[i+1];
+               rrcachestorage[rrcachesize-1].next = mDNSNULL;
+               }
+       m->rrcache = mDNSNULL;
+
+       m->hostlabel.c[0]     = 0;
+       m->nicelabel.c[0]     = 0;
+       m->ResourceRecords    = mDNSNULL;
+       m->CurrentRecord      = mDNSNULL;
+       m->HostInterfaces     = mDNSNULL;
+       m->SuppressSending    = 0;
+       m->SleepState         = mDNSfalse;
+       m->NetChanged         = mDNSfalse;
+
+       result = mDNSPlatformInit(m);
+       
+       return(result);
+       }
+
+extern void mDNSCoreInitComplete(mDNS *const m, mStatus result)
+       {
+       m->mDNSPlatformStatus = result;
+       if (m->Callback) m->Callback(m, mStatus_NoError);
+       mDNS_Lock(m);   // This lock/unlock causes a ScheduleNextTask(m) to get things started
+       mDNS_Unlock(m);
+       }
+
+extern void mDNS_Close(mDNS *const m)
+       {
+       NetworkInterfaceInfo *i;
+       const mDNSs32 timenow = mDNS_Lock(m);
+
+#if DEBUGBREAKS
+       ResourceRecord *rr;
+       int rrcache_active = 0;
+       for (rr = m->rrcache; rr; rr=rr->next) if (CacheRRActive(m, rr)) rrcache_active++;
+       debugf("mDNS_Close: RR Cache now using %d records, %d active", m->rrcache_used, rrcache_active);
+#endif
+
+       m->ActiveQuestions = mDNSNULL;          // We won't be answering any more questions!
+       
+       for (i=m->HostInterfaces; i; i=i->next)
+               if (i->Advertise)
+                       mDNS_DeadvertiseInterface(m, i, timenow);
+
+       // Make sure there are nothing but deregistering records remaining in the list
+       if (m->CurrentRecord) debugf("DiscardDeregistrations ERROR m->CurrentRecord already set");
+       m->CurrentRecord = m->ResourceRecords;
+       while (m->CurrentRecord)
+               {
+               ResourceRecord *rr = m->CurrentRecord;
+               m->CurrentRecord = rr->next;
+               if (rr->RecordType != kDNSRecordTypeDeregistering)
+                       {
+                       debugf("mDNS_Close: Record type %X still in ResourceRecords list %##s", rr->RecordType, rr->name.c);
+                       mDNS_Deregister_internal(m, rr, timenow, mDNS_Dereg_normal);
+                       }
+               }
+
+       if (m->ResourceRecords) debugf("mDNS_Close: Sending final packets for deregistering records");
+       else debugf("mDNS_Close: No deregistering records remain");
+
+       // If any deregistering records remain, send their deregistration announcements before we exit
+       if (m->mDNSPlatformStatus != mStatus_NoError)
+               DiscardDeregistrations(m, timenow);
+       else
+               while (m->ResourceRecords)
+                       SendResponses(m, timenow);
+       
+       mDNS_Unlock(m);
+       debugf("mDNS_Close: mDNSPlatformClose");
+       mDNSPlatformClose(m);
+       debugf("mDNS_Close: done");
+       }
diff --git a/mDNSCore/mDNSClientAPI.h b/mDNSCore/mDNSClientAPI.h
new file mode 100755 (executable)
index 0000000..923e59f
--- /dev/null
@@ -0,0 +1,539 @@
+#pragma once
+
+#include "mDNSDebug.h"
+
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+// ***************************************************************************
+// Function scope indicators
+
+// If you see "mDNSlocal" before a function name, it means the function is not callable outside this file
+#define mDNSlocal static
+// If you see "mDNSexport" before a symbol, it means the symbol is exported for use by clients
+#define mDNSexport
+
+// ***************************************************************************
+#if 0
+#pragma mark - DNS Resource Record class and type constants
+#endif
+
+typedef enum                                           // From RFC 1035
+       {
+       kDNSClass_IN          = 1,              // Internet
+       kDNSClass_CS          = 2,              // CSNET
+       kDNSClass_CH          = 3,              // CHAOS
+       kDNSClass_HS          = 4,              // Hesiod
+       kDNSClass_NONE        = 254,    // Used in DNS UPDATE [RFC 2136]
+       kDNSQClass_ANY        = 255,    // Not a DNS class, but a DNS query class, meaning "all classes"
+       kDNSQClass_Mask       = 0x7FFF, // Multicast DNS uses the bottom 15 bits to identify the record class...
+       kDNSClass_UniqueRRSet = 0x8000  // ... and the top bit indicates that all other cached records are now invalid
+       } DNS_ClassValues;
+
+typedef enum                           // From RFC 1035
+       {
+       kDNSType_A = 1,                 //  1 Address
+       kDNSType_NS,                    //  2 Name Server
+       kDNSType_MD,                    //  3 Mail Destination
+       kDNSType_MF,                    //  4 Mail Forwarder
+       kDNSType_CNAME,                 //  5 Canonical Name
+       kDNSType_SOA,                   //  6 Start of Authority
+       kDNSType_MB,                    //  7 Mailbox
+       kDNSType_MG,                    //  8 Mail Group
+       kDNSType_MR,                    //  9 Mail Rename
+       kDNSType_NULL,                  // 10 NULL RR
+       kDNSType_WKS,                   // 11 Well-known-service
+       kDNSType_PTR,                   // 12 Domain name pointer
+       kDNSType_HINFO,                 // 13 Host information
+       kDNSType_MINFO,                 // 14 Mailbox information
+       kDNSType_MX,                    // 15 Mail Exchanger
+       kDNSType_TXT,                   // 16 Arbitrary text string
+       
+       kDNSType_SRV = 33,              // 33 Service record
+
+       kDNSQType_ANY = 255             // Not a DNS type, but a DNS query type, meaning "all types"
+       } DNS_TypeValues;
+
+// ***************************************************************************
+#if 0
+#pragma mark - Simple types
+#endif
+
+// mDNS defines its own names for these common types to simplify portability across
+// multiple platforms that may each have their own (different) names for these types.
+typedef unsigned char  mDNSBool;
+typedef   signed char  mDNSs8;
+typedef unsigned char  mDNSu8;
+typedef   signed short mDNSs16;
+typedef unsigned short mDNSu16;
+typedef   signed long  mDNSs32;
+typedef unsigned long  mDNSu32;
+
+// These types are for opaque two- and four-byte identifiers.
+// The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a register
+// for the sake of efficiency, but don't forget -- just because it is in a register doesn't mean it is an
+// integer. Operations like add, multiply, increment, decrement, etc., are undefined for opaque identifiers.
+typedef union { mDNSu8 b[2]; mDNSu16 NotAnInteger; } mDNSOpaque16;
+typedef union { mDNSu8 b[4]; mDNSu32 NotAnInteger; } mDNSOpaque32;
+
+typedef mDNSOpaque16 mDNSIPPort;               // An IP port is a two-byte opaque identifier (not an integer)
+typedef mDNSOpaque32 mDNSIPAddr;               // An IP address is a four-byte opaque identifier (not an integer)
+
+enum { mDNSfalse = 0, mDNStrue = 1 };
+
+#define mDNSNULL 0L
+
+enum
+       {
+       mStatus_Waiting           = 1,
+       mStatus_NoError           = 0,
+
+       // mDNS Error codes are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
+       mStatus_UnknownErr        = -65537,             // 0xFFFE FFFF
+       mStatus_NoSuchNameErr     = -65538,
+       mStatus_NoMemoryErr       = -65539,
+       mStatus_BadParamErr       = -65540,
+       mStatus_BadReferenceErr   = -65541,
+       mStatus_BadStateErr       = -65542,
+       mStatus_BadFlagsErr       = -65543,
+       mStatus_UnsupportedErr    = -65544,
+       mStatus_NotInitializedErr = -65545,
+       mStatus_NoCache           = -65546,
+       mStatus_AlreadyRegistered = -65547,
+       mStatus_NameConflict      = -65548,
+       mStatus_Invalid           = -65549,
+       
+       mStatus_MemFree           = -65792              // 0xFFFE FF00
+       };
+
+typedef mDNSs32 mStatus;
+
+#define MAX_DOMAIN_LABEL 63
+typedef struct { mDNSu8 c[ 64]; } domainlabel;         // One label: length byte and up to 63 characters
+#define MAX_DOMAIN_NAME 255
+typedef struct { mDNSu8 c[256]; } domainname;          // Up to 255 bytes of length-prefixed domainlabels
+typedef struct { mDNSu8 c[256]; } UTF8str255;          // Null-terminated C string
+
+// ***************************************************************************
+#if 0
+#pragma mark - Resource Record structures
+#endif
+
+// Shared Resource Records do not have to be unique
+// -- Shared Resource Records are used for NIAS service PTRs
+// -- It is okay for several hosts to have RRs with the same name but different RDATA
+// -- We use a random delay on replies to reduce collisions when all the hosts reply to the same query
+// -- These RRs typically have moderately high TTLs (e.g. one hour)
+// -- These records are announced on startup and topology changes for the benefit of passive listeners
+
+// Unique Resource Records should be unique among hosts within any given mDNS scope
+// -- The majority of Resource Records are of this type
+// -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
+// -- Replies may be sent immediately, because only one host should be replying to any particular query
+// -- These RRs typically have low TTLs (e.g. ten seconds)
+// -- On startup and after topology changes, a host issues queries to verify uniqueness
+
+// Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
+// not have to verify their uniqueness because this is already known by other means (e.g. the RR name
+// is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
+
+enum
+       {
+       kDNSRecordTypeUnregistered     = 0x00,  // Not currently in any list
+       kDNSRecordTypeDeregistering    = 0x01,  // Shared record about to announce its departure and leave the list
+
+       kDNSRecordTypeUnique           = 0x08,  // Will become a kDNSRecordTypeVerified when probing is complete
+
+       kDNSRecordTypePacketAnswer     = 0x10,  // Received in the Answer Section of a DNS Response
+       kDNSRecordTypePacketAdditional = 0x11,  // Received in the Additional Section of a DNS Response
+       kDNSRecordTypePacketUniqueAns  = 0x18,  // Received in the Answer Section of a DNS Response with kDNSQClass_CacheFlushBit set
+       kDNSRecordTypePacketUniqueAdd  = 0x19,  // Received in the Additional Section of a DNS Response with kDNSQClass_CacheFlushBit set
+
+       kDNSRecordTypeShared           = 0x20,  // Shared means record name does not have to be unique -- so use random delay on replies
+       kDNSRecordTypeVerified         = 0x28,  // Unique means mDNS should check that name is unique (and then send immediate replies)
+       kDNSRecordTypeKnownUnique      = 0x29,  // Known Unique means mDNS can assume name is unique without checking
+       
+       kDNSRecordTypeUniqueMask       = 0x08,  // Test for records that are supposed to not be shared with other hosts
+       kDNSRecordTypeRegisteredMask   = 0xF8,  // Test for records that have not had mDNS_Deregister called on them yet
+       kDNSRecordTypeActiveMask       = 0xF0   // Test for all records that have finished their probing and are now active
+       };
+
+enum
+       {
+       kDNSSendPriorityNone       = 0,         // Don't need to send this record right now
+       kDNSSendPriorityAdditional = 1,         // Send this record as an additional, if we have space in the packet
+       kDNSSendPriorityAnswer     = 2          // Need to send this record as an answer
+       };
+
+typedef struct { mDNSu16 priority; mDNSu16 weight; mDNSIPPort port; domainname target; } rdataSRV;
+
+typedef union
+       {
+       mDNSu8     data[512];   // Generic untyped data (temporarily set 512 for the benefit of iChat)
+       mDNSIPAddr ip;                  // For 'A' record
+       domainname name;                // For PTR and CNAME records
+       UTF8str255 txt;                 // For TXT record
+       rdataSRV   srv;                 // For SRV record
+       } RDataBody;
+
+typedef struct
+       {
+       mDNSu16    MaxRDLength; // Amount of storage allocated for rdata (usually sizeof(RDataBody))
+       mDNSu16    RDLength;    // Size of the rdata currently stored here
+       RDataBody  u;
+       } RData;
+
+typedef struct ResourceRecord_struct ResourceRecord;
+typedef struct ResourceRecord_struct *ResourceRecordPtr;
+
+typedef struct mDNS_struct mDNS;
+typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport;
+
+typedef void mDNSRecordCallback(mDNS *const m, ResourceRecord *const rr, mStatus result);
+typedef void mDNSRecordUpdateCallback(mDNS *const m, ResourceRecord *const rr, RData *OldRData);
+
+// Fields labelled "AR:" apply to our authoritative records
+// Fields labelled "CR:" apply to cache records
+// Fields labelled "--:" apply to both
+// (May want to make this a union later, but not now, because using the
+// same storage for two different purposes always makes debugging harder.)
+struct ResourceRecord_struct
+       {
+       ResourceRecord     *next;                       // --: Next in list
+       
+       // Field Group 1: Persistent metadata for Authoritative Records
+       ResourceRecord     *Additional1;        // AR: Recommended additional record to include in response
+       ResourceRecord     *Additional2;        // AR: Another additional
+       ResourceRecord     *DependentOn;        // AR: This record depends on another for its uniqueness checking
+       ResourceRecord     *RRSet;                      // AR: This unique record is part of an RRSet
+       mDNSRecordCallback *Callback;           // AR: Callback function to call for state changes
+       void               *Context;            // AR: Context parameter for the callback function
+       mDNSu8              RecordType;         // --: See enum above
+       mDNSu8              HostTarget;         // AR: Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
+
+       // Field Group 2: Transient state for Authoritative Records
+       mDNSu8          Acknowledged;           // AR: Set if we've given the success callback to the client
+       mDNSu8          ProbeCount;                     // AR: Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
+       mDNSu8          AnnounceCount;          // AR: Number of announcements remaining (kDNSRecordTypeShared)
+       mDNSu8          IncludeInProbe;         // AR: Set if this RR is being put into a probe right now
+       mDNSu8          SendPriority;           // AR: See enum above
+       mDNSIPAddr      Requester;                      // AR: Used for inter-packet duplicate suppression
+                                                                               //     If set, give the IP address of the last host that sent a truncated query for this record
+                                                                               //     If set to all-ones, more than one host sent such a request in the last few milliseconds
+       ResourceRecord *NextResponse;           // AR: Link to the next element in the chain of responses to generate
+       const mDNSu8   *NR_AnswerTo;            // AR: Set if this record was selected by virtue of being a direct answer to a question
+       ResourceRecord *NR_AdditionalTo;        // AR: Set if this record was selected by virtue of being additional to another
+       mDNSs32         LastSendTime;           // AR: In platform time units
+       mDNSs32         NextSendTime;           // AR: In platform time units
+       mDNSs32         NextSendInterval;       // AR: In platform time units
+       RData          *NewRData;                       // AR: Set if we are updating this record with new rdata
+       mDNSRecordUpdateCallback *UpdateCallback;
+
+       // Field Group 3: Transient state for Cache Records
+       ResourceRecord *NextDupSuppress;        // CR: Link to the next element in the chain of duplicate suppression answers to send
+       mDNSs32         TimeRcvd;                       // CR: In platform time units
+       mDNSs32         LastUsed;                       // CR: In platform time units
+       mDNSu32         UseCount;                       // CR: Number of times this RR has been used to answer a question
+       mDNSu32         UnansweredQueries;      // CR: Number of times we've issued a query for this record without getting an answer
+       mDNSBool        Active;                         // CR: Set if there is currently a question referencing this answer
+       mDNSBool        NewData;                        // CR: Set if this is a record we just received
+
+       // Field Group 4: The actual information pertaining to this resource record
+       mDNSIPAddr      InterfaceAddr;          // --: Set if this RR is specific to one interface (e.g. a linklocal address)
+                                                                               // For records received off the wire, InterfaceAddr is *always* set to the receiving interface
+                                                                               // For our authoritative records, InterfaceAddr is usually zero,
+                                                                               // except those few records that are interface-specific (e.g. linklocal address records)
+       domainname      name;                           // --: All the rest are used both in our authoritative records and in cache records
+       mDNSu16         rrtype;
+       mDNSu16         rrclass;
+       mDNSu32         rroriginalttl;          // In seconds.
+       mDNSu32         rrremainingttl;         // In seconds. Always set to correct value before calling question callback.
+       mDNSu16         rdestimate;                     // Upper bound on size of rdata after name compression
+       RData           *rdata;                         // Pointer to storage for this rdata
+       RData           rdatastorage;           // Normally the storage is right here, except for oversized records
+       };
+
+typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo;
+
+struct NetworkInterfaceInfo_struct
+       {
+       NetworkInterfaceInfo *next;
+       mDNSIPAddr     ip;
+       mDNSBool       Advertise;               // Set Advertise to false if you are only searching on this interface
+       // Standard ResourceRecords that every Responder host should have (one per active IP address)
+       ResourceRecord RR_A1;                   // 'A' (address) record for our ".local" name
+       ResourceRecord RR_A2;                   // 'A' record for our ".local.arpa" name
+       ResourceRecord RR_PTR;                  // PTR (reverse lookup) record
+       };
+
+typedef struct ExtraResourceRecord_struct ExtraResourceRecord;
+struct ExtraResourceRecord_struct
+       {
+       ExtraResourceRecord *next;
+       ResourceRecord r;
+       // Note: Add any additional fields *before* the ResourceRecord in this structure, not at the end.
+       // In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
+       // that this extra memory is available, which would result in any fields after the ResourceRecord getting smashed
+       };
+
+typedef struct ServiceRecordSet_struct ServiceRecordSet;
+typedef void mDNSServiceCallback(mDNS *const m, ServiceRecordSet *const sr, mStatus result);
+struct ServiceRecordSet_struct
+       {
+       mDNSServiceCallback *Callback;
+       void                *Context;
+       ExtraResourceRecord *Extras;    // Optional list of extra ResourceRecords attached to this service registration
+       mDNSBool             Conflict;  // Set if this record set was forcibly deregistered because of a conflict
+       domainname           Host;              // Set if this service record does not use the standard target host name
+       ResourceRecord       RR_PTR;    // e.g. _printer._tcp.local.      PTR Name._printer._tcp.local.
+       ResourceRecord       RR_SRV;    // e.g. Name._printer._tcp.local. SRV 0 0 port target
+       ResourceRecord       RR_TXT;    // e.g. Name._printer._tcp.local. TXT PrintQueueName
+       // Don't add any fields after ResourceRecord RR_TXT.
+       // This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
+       };
+
+// ***************************************************************************
+#if 0
+#pragma mark - Question structures
+#endif
+
+typedef struct DNSQuestion_struct DNSQuestion;
+typedef void mDNSQuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer);
+struct DNSQuestion_struct
+       {
+       DNSQuestion          *next;
+       mDNSs32               NextQTime;                // In platform time units
+       mDNSs32               ThisQInterval;    // In platform time units (zero for questions not in list)
+                                                                                       // ThisQInterval will be non-zero for an active question;
+                                                                                       // Zero for a cancelled or inactive question
+       mDNSs32               NextQInterval;
+       DNSQuestion          *DuplicateOf;
+       mDNSIPAddr            InterfaceAddr;    // Non-zero if you want to issue link-local queries only on a single specific IP interface
+       domainname            name;
+       mDNSu16               rrtype;
+       mDNSu16               rrclass;
+       mDNSQuestionCallback *Callback;
+       void                 *Context;
+       };
+
+typedef struct
+       {
+       domainname name;
+       mDNSIPAddr InterfaceAddr;               // Local (source) IP Interface (needed for scoped addresses such as link-local)
+       mDNSIPAddr ip;                                  // Remote (destination) IP address where this service can be accessed
+       mDNSIPPort port;                                // Port where this service can be accessed
+       mDNSu16    TXTlen;
+       mDNSu8     TXTinfo[2048];               // Additional demultiplexing information (e.g. LPR queue name)
+       } ServiceInfo;
+
+typedef struct ServiceInfoQuery_struct ServiceInfoQuery;
+typedef void ServiceInfoQueryCallback(mDNS *const m, ServiceInfoQuery *query);
+struct ServiceInfoQuery_struct
+       {
+       DNSQuestion               qSRV;
+       DNSQuestion               qTXT;
+       DNSQuestion               qADD;
+       mDNSu8                    GotSRV;
+       mDNSu8                    GotTXT;
+       mDNSu8                    GotADD;
+       ServiceInfo              *info;
+       ServiceInfoQueryCallback *Callback;
+       void                     *Context;
+       };
+
+// ***************************************************************************
+#if 0
+#pragma mark - Main mDNS object, used to hold all the mDNS state
+#endif
+
+typedef void mDNSCallback(mDNS *const m, mStatus result);
+
+struct mDNS_struct
+       {
+       mDNS_PlatformSupport *p;                // Pointer to platform-specific data of indeterminite size
+       mStatus mDNSPlatformStatus;
+       mDNSCallback *Callback;
+       void         *Context;
+
+       mDNSu32 mDNS_busy;                              // For debugging: To catch and report locking failures
+
+       mDNSu8 lock_rrcache;                    // For debugging: Set at times when these lists may not be modified
+       mDNSu8 lock_Questions;
+       mDNSu8 lock_Records;
+       mDNSu8 padding;
+
+       // These fields only required for mDNS Searcher...
+       DNSQuestion *ActiveQuestions;   // List of all active questions
+       DNSQuestion *NewQuestions;              // Fresh questions not yet answered from cache
+       DNSQuestion *CurrentQuestion;   // Next question about to be examined in AnswerLocalQuestions()
+       mDNSu32 rrcache_size;
+       mDNSu32 rrcache_used;
+       mDNSu32 rrcache_report;
+       ResourceRecord *rrcache_free;
+       ResourceRecord *rrcache;
+
+       // Fields below only required for mDNS Responder...
+       domainlabel nicelabel;                  // Rich text label encoded using canonically precomposed UTF-8
+       domainlabel hostlabel;                  // Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
+       domainname  hostname1;                  // Primary Host Name "Foo.local."
+       domainname  hostname2;                  // Secondary Host Name "Foo.local.arpa."
+       ResourceRecord *ResourceRecords;
+       ResourceRecord *CurrentRecord;  // Next ResourceRecord about to be examined
+       NetworkInterfaceInfo *HostInterfaces;
+       mDNSs32 SuppressSending;
+       mDNSs32 SuppressProbes;
+       mDNSBool SleepState;
+       mDNSBool NetChanged;
+       };
+
+// ***************************************************************************
+#if 0
+#pragma mark - Useful Static Constants
+#endif
+
+extern const ResourceRecord zeroRR;
+extern const mDNSIPPort zeroIPPort;
+extern const mDNSIPAddr zeroIPAddr;
+extern const mDNSIPAddr onesIPAddr;
+
+extern const mDNSIPPort UnicastDNSPort;
+extern const mDNSIPPort MulticastDNSPort;
+extern const mDNSIPAddr AllDNSLinkGroup;
+extern const mDNSIPAddr AllDNSAdminGroup;
+
+// ***************************************************************************
+#if 0
+#pragma mark - Main Client Functions
+#endif
+
+// Every client should call mDNS_Init, passing in storage for the mDNS object, mDNS_PlatformSupport object, and rrcache.
+// The rrcachesize parameter is the size of (i.e. number of entries in) the rrcache array passed in.
+// When mDNS has finished setting up the initComplete callback is called
+// A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
+//
+// Call mDNS_Close to tidy up before exiting
+//
+// Call mDNS_Register with a completed ResourceRecord object to register a resource record
+// If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
+// the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
+// the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
+//
+// Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a reply
+// is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
+// Call mDNS_StopQuery when no more answers are required
+//
+// The mDNS routines are intentionally not thread-safe -- adding locking operations would add overhead that may not
+// be necessary or appropriate on every platform. Instead, code in a pre-emptive environment calling any mDNS routine
+// (except mDNS_Init and mDNS_Close) is responsible for doing the necessary synchronization to ensure that mDNS code is
+// not re-entered. This includes both client software above mDNS, and the platform support code below. For example, if
+// the support code on a particular platform implements timer callbacks at interrupt time, then clients on that platform
+// need to disable interrupts or do similar concurrency control to ensure that the mDNS code is not entered by an
+// interrupt-time timer callback while in the middle of processing a client call.
+
+extern mStatus mDNS_Init      (mDNS *const m, mDNS_PlatformSupport *const p,
+                                                               ResourceRecord *rrcachestorage, mDNSu32 rrcachesize, mDNSCallback *Callback, void *Context);
+extern void    mDNS_Close     (mDNS *const m);
+extern mStatus mDNS_Register  (mDNS *const m, ResourceRecord *const rr);
+extern mStatus mDNS_Update    (mDNS *const m, ResourceRecord *const rr, mDNSu32 newttl,
+                                                               RData *const newrdata, mDNSRecordUpdateCallback *Callback);
+extern void    mDNS_Deregister(mDNS *const m, ResourceRecord *const rr);
+extern mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question);
+extern void    mDNS_StopQuery (mDNS *const m, DNSQuestion *const question);
+
+// ***************************************************************************
+#if 0
+#pragma mark - General utility and helper functions
+#endif
+
+// mDNS_RegisterHostSet is a single call to register the standard resource records associated with every host.
+// mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
+//
+// mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
+// to find the IP address, port number, and demultiplexing information for a given named service.
+// As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
+// found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
+// The client can also call mDNS_StopResolveService at any time to abort the transaction.
+//
+// mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
+// are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
+// After getting the list of domains to browse, call mDNS_StopQuery to end the search.
+// mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
+//
+// mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
+// of one or more domains that should be offered to the user as choices for where they may register their service,
+// and the default domain in which to register in the case where the user has made no selection.
+
+extern void    mDNS_SetupResourceRecord(ResourceRecord *rr, RData *RDataStorage, mDNSIPAddr InterfaceAddr,
+               mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, mDNSRecordCallback Callback, void *Context);
+
+extern void    mDNS_GenerateFQDN(mDNS *const m);
+extern mStatus mDNS_RegisterInterface  (mDNS *const m, NetworkInterfaceInfo *set);
+extern void    mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set);
+
+extern mStatus mDNS_RegisterService  (mDNS *const m, ServiceRecordSet *sr,
+               const domainlabel *const name, const domainname *const type, const domainname *const domain,
+               const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
+               mDNSServiceCallback Callback, void *Context);
+extern mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl);
+extern mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra);
+extern mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr);
+extern void    mDNS_DeregisterService(mDNS *const m, ServiceRecordSet *sr);
+
+extern mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
+                               const domainname *const srv, const domainname *const domain,
+                               const mDNSIPAddr InterfaceAddr, mDNSQuestionCallback *Callback, void *Context);
+#define        mDNS_StopBrowse mDNS_StopQuery
+
+extern mStatus mDNS_StartResolveService(mDNS *const m, ServiceInfoQuery *query, ServiceInfo *info, ServiceInfoQueryCallback *Callback, void *Context);
+extern void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *query);
+
+typedef enum
+       {
+       mDNS_DomainTypeBrowse              = 0,
+       mDNS_DomainTypeBrowseDefault       = 1,
+       mDNS_DomainTypeRegistration        = 2,
+       mDNS_DomainTypeRegistrationDefault = 3
+       } mDNS_DomainType;
+
+extern mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNSu8 DomainType, const mDNSIPAddr InterfaceAddr, mDNSQuestionCallback *Callback, void *Context);
+#define        mDNS_StopGetDomains mDNS_StopQuery
+extern mStatus mDNS_AdvertiseDomains(mDNS *const m, ResourceRecord *rr, mDNSu8 DomainType, const mDNSIPAddr InterfaceAddr, char *domname);
+#define        mDNS_StopAdvertiseDomains mDNS_Deregister
+
+// ***************************************************************************
+#if 0
+#pragma mark - DNS name utility functions
+#endif
+
+// In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
+// in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
+// work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
+// are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
+
+extern mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2);
+
+extern mDNSu32 DomainNameLength(const domainname *const name);
+extern void AppendDomainLabelToName(domainname *const name, const domainlabel *const label);
+extern void AppendStringLabelToName(domainname *const name, const char *cstr);
+extern void AppendDomainNameToName(domainname *const name, const domainname *const append);
+extern void AppendStringNameToName(domainname *const name, const char *cstr);
+
+extern void   ConvertCStringToDomainLabel(const char *src, domainlabel *label);
+extern mDNSu8 *ConvertCStringToDomainName(const char *const cstr, domainname *name);
+
+extern char *ConvertDomainLabelToCString_withescape(const domainlabel *const name, char *cstr, char esc);
+#define      ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
+#define      ConvertDomainLabelToCString(D,C)           ConvertDomainLabelToCString_withescape((D), (C), '\\')
+
+extern char *ConvertDomainNameToCString_withescape(const domainname *const name, char *cstr, char esc);
+#define      ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
+#define      ConvertDomainNameToCString(D,C)           ConvertDomainNameToCString_withescape((D), (C), '\\')
+extern void  ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel);
+
+extern mDNSu8    *ConstructServiceName(domainname *const fqdn, const domainlabel *const name, const domainname *const type, const domainname *const domain);
+extern mDNSBool DeconstructServiceName(const domainname *const fqdn, domainlabel *const name, domainname *const type, domainname *const domain);
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSCore/mDNSDebug.h b/mDNSCore/mDNSDebug.h
new file mode 100755 (executable)
index 0000000..f6e6e1e
--- /dev/null
@@ -0,0 +1,39 @@
+// Set DEBUGBREAKS to 0 to optimize debugf() calls out of the compiled code
+// Set DEBUGBREAKS to 1 to generate normal debugging messages
+// Set DEBUGBREAKS to 2 to generate verbose debugging messages
+// DEBUGBREAKS is normally set in the project options (or makefile) but can also be set here if desired
+
+//#define DEBUGBREAKS 2
+
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+#if DEBUGBREAKS
+#define debugf debugf_
+extern void debugf_(const char *format, ...);
+#else // If debug breaks are off, use a preprocessor trick to optimize those calls out of the code
+       #if( defined( __GNUC__ ) )
+               #define debugf( ARGS... )
+       #elif( defined( __MWERKS__ ) )
+               #define debugf( ... )
+       #else
+               #define debugf 1 ? ((void) 0) : (void)
+       #endif
+#endif
+
+#if DEBUGBREAKS > 1
+#define verbosedebugf debugf_
+#else
+       #if( defined( __GNUC__ ) )
+               #define verbosedebugf( ARGS... )
+       #elif( defined( __MWERKS__ ) )
+               #define verbosedebugf( ... )
+       #else
+               #define verbosedebugf 1 ? ((void) 0) : (void)
+       #endif
+#endif
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSCore/mDNSPlatformEnvironment.h b/mDNSCore/mDNSPlatformEnvironment.h
new file mode 100755 (executable)
index 0000000..1a349c7
--- /dev/null
@@ -0,0 +1,103 @@
+// mDNS-PlatformEnvironment.h needs to ensure that the necessary mDNS types are defined,
+// plus whatever additional types are needed to support a particular platform
+
+// To add support for a new target platform with its own networking APIs and types,
+// duplicate the "#elif __SOME_OTHER_OS__" section (including its two-line comment
+// at the start) and add support for the new target platform in the new section.
+
+#pragma once
+
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+// ***************************************************************************
+// Classic Mac (Open Transport) structures
+
+#if (TARGET_API_MAC_OS8 || __MACOS__)
+
+// Headers needed for code on this platform
+#include <OpenTptInternet.h>
+#include <OpenTptClient.h>
+
+typedef enum
+       {
+       mOT_Reset = 0,
+       mOT_Start,
+       mOT_ReusePort,
+       mOT_RcvDestAddr,
+       mOT_LLScope,
+       mOT_AdminScope,
+       mOT_Bind,
+       mOT_Ready
+       } mOT_State;
+
+typedef struct { TOptionHeader h; mDNSIPAddr multicastGroupAddress; mDNSIPAddr InterfaceAddress; } TIPAddMulticastOption;
+typedef struct { TOptionHeader h; UInt32 flag; } TSetBooleanOption;
+
+// TOptionBlock is a union of various types.
+// What they all have in common is that they all start with a TOptionHeader.
+typedef union  { TOptionHeader h; TIPAddMulticastOption m; TSetBooleanOption b; } TOptionBlock;
+
+struct mDNS_PlatformSupport_struct
+       {
+       EndpointRef ep;
+       UInt32 mOTstate;                                // mOT_State enum
+       TOptionBlock optBlock;
+       TOptMgmt optReq;
+       long OTTimerTask;
+       UInt32 nesting;
+
+       // Platforms that support multi-homing will want a list of HostRecordSets instead of just one
+       HostRecordSet hostset;
+       };
+
+// ***************************************************************************
+// Mac OS X structures
+
+#elif (TARGET_API_MAC_OSX || __MACOSX__)
+
+// Headers needed for code on this platform
+#include <SystemConfiguration/SystemConfiguration.h>
+#include <IOKit/pwr_mgt/IOPMLib.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+struct mDNS_PlatformSupport_struct
+       {
+       CFRunLoopTimerRef  CFTimer;
+       SCDynamicStoreRef  Store;
+       CFRunLoopSourceRef StoreRLS;
+       io_connect_t       PowerConnection;
+       io_object_t        PowerNotifier;
+       CFRunLoopSourceRef PowerRLS;
+       };
+
+// Set this symbol to 1 to do extra debug checks on malloc() and free()
+#define MACOSX_MDNS_MALLOC_DEBUGGING 0
+
+#if MACOSX_MDNS_MALLOC_DEBUGGING
+extern void *mallocL(char *msg, unsigned int size);
+extern void freeL(char *msg, void *x);
+#else
+#define mallocL(X,Y) malloc(Y)
+#define freeL(X,Y) free(Y)
+#endif
+
+// ***************************************************************************
+// Placeholder for future platforms
+
+#elif __SOME_OTHER_OS__
+
+// ***************************************************************************
+// Generic code for Unix-style platforms
+
+#else
+
+#error Other platforms need to make sure that types like UInt16 are defined
+
+#endif
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSCore/mDNSPlatformFunctions.h b/mDNSCore/mDNSPlatformFunctions.h
new file mode 100755 (executable)
index 0000000..e058894
--- /dev/null
@@ -0,0 +1,69 @@
+// ***************************************************************************
+// Support functions which must be provided by each set of specific PlatformSupport files
+
+// mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
+// When Setup is complete, the callback is called.
+// mDNSPlatformSendUDP() sends one UDP packet
+// When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
+// mDNSPlatformScheduleTask() indicates that a timer should be set,
+// and mDNSCoreTask() should be called when the timer expires
+// mDNSPlatformClose() tidies up on exit
+
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+// ***************************************************************************
+// DNS protocol message format
+
+typedef struct
+       {
+       mDNSOpaque16 id;
+       mDNSOpaque16 flags;
+       mDNSu16 numQuestions;
+       mDNSu16 numAnswers;
+       mDNSu16 numAuthorities;
+       mDNSu16 numAdditionals;
+       } DNSMessageHeader;
+
+// We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
+// However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
+#define AbsoluteMaxDNSMessageData 8960
+#define NormalMaxDNSMessageData 1460
+typedef struct
+       {
+       DNSMessageHeader h;                                             // Note: Size 12 bytes
+       mDNSu8 data[AbsoluteMaxDNSMessageData]; // 20 (IP) + 8 (UDP) + 12 (header) + 8960 (data) = 9000
+       } DNSMessage;
+
+// ***************************************************************************
+// Functions
+
+// Every platform support module must provide the following functions
+extern mStatus  mDNSPlatformInit   (mDNS *const m);
+extern void     mDNSPlatformClose  (mDNS *const m);
+extern mStatus  mDNSPlatformSendUDP(const mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end,
+       mDNSIPAddr src, mDNSIPPort srcport, mDNSIPAddr dst, mDNSIPPort dstport);
+
+extern void     mDNSPlatformScheduleTask(const mDNS *const m, mDNSs32 NextTaskTime);
+extern void     mDNSPlatformLock        (const mDNS *const m);
+extern void     mDNSPlatformUnlock      (const mDNS *const m);
+
+extern void     mDNSPlatformStrCopy(const void *src,       void *dst);
+extern mDNSu32  mDNSPlatformStrLen (const void *src);
+extern void     mDNSPlatformMemCopy(const void *src,       void *dst, mDNSu32 len);
+extern mDNSBool mDNSPlatformMemSame(const void *src, const void *dst, mDNSu32 len);
+extern void     mDNSPlatformMemZero(                       void *dst, mDNSu32 len);
+extern mDNSs32  mDNSPlatformTimeNow();
+extern mDNSs32  mDNSPlatformOneSecond;
+
+// The core mDNS code provides these functions, for the platform support code to call at appropriate times
+extern void     mDNSCoreInitComplete(mDNS *const m, mStatus result);
+extern void     mDNSCoreReceive(mDNS *const m, DNSMessage *const msg, const mDNSu8 *const end,
+                                                               mDNSIPAddr srcaddr, mDNSIPPort srcport, mDNSIPAddr dstaddr, mDNSIPPort dstport, mDNSIPAddr InterfaceAddr);
+extern void     mDNSCoreTask   (mDNS *const m);
+extern void     mDNSCoreSleep  (mDNS *const m, mDNSBool wake);
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSCore/mDNSsprintf.c b/mDNSCore/mDNSsprintf.c
new file mode 100755 (executable)
index 0000000..beaab51
--- /dev/null
@@ -0,0 +1,227 @@
+#include <stdio.h>
+#include <stdarg.h>                                                    // For va_list support
+
+#include "mDNSsprintf.h"
+#include "mDNSvsprintf.h"
+
+static const struct mDNSsprintf_format
+       {
+       unsigned                leftJustify : 1;
+       unsigned                forceSign : 1;
+       unsigned                zeroPad : 1;
+       unsigned                havePrecision : 1;
+       unsigned                hSize : 1;
+       unsigned                lSize : 1;
+       char                    altForm;
+       char                    sign;           // +, - or space
+       int                             fieldWidth;
+       int                             precision;
+       } default_format = { 0 };
+
+#define BUFLEN                 512
+
+int mDNS_vsprintf(char *sbuffer, const char *fmt, va_list arg)
+       {
+       int c, nwritten = 0;
+
+       for (c = *fmt; c; c = *++fmt)
+               {
+               int i=0, j;
+               char buf[BUFLEN], *digits;
+               char *s = &buf[BUFLEN];
+               struct mDNSsprintf_format F;
+               if (c != '%') goto copy1;
+               F = default_format;
+
+               for (;;)        //  decode flags
+                       {
+                       c = *++fmt;
+                       if      (c == '-')      F.leftJustify = 1;
+                       else if (c == '+')      F.forceSign = 1;
+                       else if (c == ' ')      F.sign = ' ';
+                       else if (c == '#')      F.altForm++;
+                       else if (c == '0')      F.zeroPad = 1;
+                       else break;
+                       }
+
+               if (c == '*')   //  decode field width
+                       {
+                       if ((F.fieldWidth = va_arg(arg, int)) < 0)
+                               {
+                               F.leftJustify = 1;
+                               F.fieldWidth = -F.fieldWidth;
+                               }
+                       c = *++fmt;
+                       }
+               else
+                       {
+                       for (; c >= '0' && c <= '9'; c = *++fmt)
+                               F.fieldWidth = (10 * F.fieldWidth) + (c - '0');
+                       }
+
+               if (c == '.')   //  decode precision
+                       {
+                       if ((c = *++fmt) == '*')
+                               { F.precision = va_arg(arg, int); c = *++fmt; }
+                       else for (; c >= '0' && c <= '9'; c = *++fmt)
+                                       F.precision = (10 * F.precision) + (c - '0');
+                       if (F.precision >= 0) F.havePrecision = 1;
+                       }
+
+               if (F.leftJustify) F.zeroPad = 0;
+
+conv:  switch (c)      //  perform appropriate conversion
+                       {
+                       unsigned long n;
+                       case 'h' :      F.hSize = 1; c = *++fmt; goto conv;
+                       case 'l' :      // fall through
+                       case 'L' :      F.lSize = 1; c = *++fmt; goto conv;
+                       case 'd' :
+                       case 'i' :      if (F.lSize) n = (unsigned long)va_arg(arg, long);
+                                               else n = (unsigned long)va_arg(arg, int);
+                                               if (F.hSize) n = (short) n;
+                                               if ((long) n < 0) { n = (unsigned long)-(long)n; F.sign = '-'; }
+                                               else if (F.forceSign) F.sign = '+';
+                                               goto decimal;
+                       case 'u' :      if (F.lSize) n = va_arg(arg, unsigned long);
+                                               else n = va_arg(arg, unsigned int);
+                                               if (F.hSize) n = (unsigned short) n;
+                                               F.sign = 0;
+                                               goto decimal;
+                       decimal:        if (!F.havePrecision)
+                                                       {
+                                                       if (F.zeroPad)
+                                                               {
+                                                               F.precision = F.fieldWidth;
+                                                               if (F.sign) --F.precision;
+                                                               }
+                                                       if (F.precision < 1) F.precision = 1;
+                                                       }
+                                               for (i = 0; n; n /= 10, i++) *--s = (char)(n % 10 + '0');
+                                               for (; i < F.precision; i++) *--s = '0';
+                                               if (F.sign) { *--s = F.sign; i++; }
+                                               break;
+
+                       case 'o' :      if (F.lSize) n = va_arg(arg, unsigned long);
+                                               else n = va_arg(arg, unsigned int);
+                                               if (F.hSize) n = (unsigned short) n;
+                                               if (!F.havePrecision)
+                                                       {
+                                                       if (F.zeroPad) F.precision = F.fieldWidth;
+                                                       if (F.precision < 1) F.precision = 1;
+                                                       }
+                                               for (i = 0; n; n /= 8, i++) *--s = (char)(n % 8 + '0');
+                                               if (F.altForm && i && *s != '0') { *--s = '0'; i++; }
+                                               for (; i < F.precision; i++) *--s = '0';
+                                               break;
+
+                       case 'a' :      {
+                                               unsigned char *a = va_arg(arg, unsigned char *);
+                                               unsigned short *w = (unsigned short *)a;
+                                               s = buf;
+                                               switch (F.precision)
+                                                       {
+                                                       case  4: i = mDNS_sprintf(s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]); break;
+                                                       case  6: i = mDNS_sprintf(s, "%02X:%02X:%02X:%02X:%02X:%02X", a[0], a[1], a[2], a[3], a[4], a[5]); break;
+                                                       case 16: i = mDNS_sprintf(s, "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X",
+                                                                                               w[0], w[1], w[2], w[3], w[4], w[5], w[6], w[7]); break;
+                                                       default: i = mDNS_sprintf(s, "%s", "ERROR: Must specify address size "
+                                                                                               "(i.e. %.4a=IPv4, %.6a=Ethernet, %.16a=IPv6) >>"); break;
+                                                       }
+                                               }
+                                               break;
+
+                       case 'p' :      F.havePrecision = F.lSize = 1;
+                                               F.precision = 8;
+                       case 'X' :      digits = "0123456789ABCDEF";
+                                               goto hexadecimal;
+                       case 'x' :      digits = "0123456789abcdef";
+                       hexadecimal:if (F.lSize) n = va_arg(arg, unsigned long);
+                                               else n = va_arg(arg, unsigned int);
+                                               if (F.hSize) n = (unsigned short) n;
+                                               if (!F.havePrecision)
+                                                       {
+                                                       if (F.zeroPad)
+                                                               {
+                                                               F.precision = F.fieldWidth;
+                                                               if (F.altForm) F.precision -= 2;
+                                                               }
+                                                       if (F.precision < 1) F.precision = 1;
+                                                       }
+                                               for (i = 0; n; n /= 16, i++) *--s = digits[n % 16];
+                                               for (; i < F.precision; i++) *--s = '0';
+                                               if (F.altForm) { *--s = (char)c; *--s = '0'; i += 2; }
+                                               break;
+
+                       case 'c' :      *--s = (char)va_arg(arg, int); i = 1; break;
+
+                       case 's' :      s = va_arg(arg, char *);
+                                               switch (F.altForm)
+                                                       {
+                                                       case 0: { char *a=s; i=0; while(*a++) i++; break; }     // C string
+                                                       case 1: i = (unsigned char) *s++; break;        // Pascal string
+                                                       case 2: {                                                                       // DNS label-sequence name
+                                                                       unsigned char *a = (unsigned char *)s;
+                                                                       s = buf;
+                                                                       if (*a == 0) *s++ = '.';        // Special case for root DNS name
+                                                                       while (*a && s + *a + 1 < &buf[BUFLEN])
+                                                                               {
+                                                                               s += mDNS_sprintf(s, "%#s.", a);
+                                                                               a += 1 + *a;
+                                                                               }
+                                                                       i = (int)(s - buf);
+                                                                       s = buf;
+                                                                       break;
+                                                                       }
+                                                       }
+                                               if (F.havePrecision && i > F.precision) i = F.precision;
+                                               break;
+
+                       case 'n' :      s = va_arg(arg, char *);
+                                               if      (F.hSize) * (short *) s = (short)nwritten;
+                                               else if (F.lSize) * (long  *) s = (long)nwritten;
+                                               else              * (int   *) s = (int)nwritten;
+                                               continue;
+
+                               //  oops - unknown conversion, abort
+
+                       case 'M': case 'N': case 'O': case 'P': case 'Q':
+                       case 'R': case 'S': case 'T': case 'U': case 'V':
+                       // (extra cases force this to be an indexed switch)
+                       default: goto done;
+
+                       case '%' :
+                       copy1    :      *sbuffer++ = (char)c; ++nwritten; continue;
+                       }
+
+                       //  pad on the left
+
+               if (i < F.fieldWidth && !F.leftJustify)
+                       do { *sbuffer++ = ' '; ++nwritten; } while (i < --F.fieldWidth);
+
+                       //  write the converted result
+
+               for (j=0; j<i; j++) *sbuffer++ = *s++;
+               nwritten += i;
+
+                       //  pad on the right
+
+               for (; i < F.fieldWidth; i++)
+                       { *sbuffer++ = ' '; ++nwritten; }
+               }
+
+done: return(nwritten);
+       }
+
+int mDNS_sprintf(char *sbuffer, const char *fmt, ...)
+{
+       int     length;
+       
+    va_list ptr;
+       va_start(ptr,fmt);
+       length = mDNS_vsprintf(sbuffer, fmt, ptr);
+       sbuffer[length] = 0;
+       va_end(ptr);
+       
+       return length;
+}
diff --git a/mDNSCore/mDNSsprintf.h b/mDNSCore/mDNSsprintf.h
new file mode 100755 (executable)
index 0000000..199048e
--- /dev/null
@@ -0,0 +1,9 @@
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+extern int mDNS_sprintf(char *sbuffer, const char *fmt, ...);
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSCore/mDNSvsprintf.h b/mDNSCore/mDNSvsprintf.h
new file mode 100755 (executable)
index 0000000..d6e9f05
--- /dev/null
@@ -0,0 +1,9 @@
+#ifdef __cplusplus
+       extern "C" {
+#endif
+
+extern int mDNS_vsprintf(char *sbuffer, const char *fmt, va_list arg);
+
+#ifdef __cplusplus
+       }
+#endif
diff --git a/mDNSResponder.pbproj/project.pbxproj b/mDNSResponder.pbproj/project.pbxproj
new file mode 100644 (file)
index 0000000..7fc8cc5
--- /dev/null
@@ -0,0 +1,531 @@
+// !$*UTF8*$!
+{
+       archiveVersion = 1;
+       classes = {
+       };
+       objectVersion = 38;
+       objects = {
+               00CA213D02786FC30CCA2C71 = {
+                       isa = PBXFrameworkReference;
+                       name = IOKit.framework;
+                       path = /System/Library/Frameworks/IOKit.framework;
+                       refType = 0;
+               };
+//000
+//001
+//002
+//003
+//004
+//010
+//011
+//012
+//013
+//014
+               014CEA490018CE3211CA2923 = {
+                       buildRules = (
+                       );
+                       buildSettings = {
+                               COPY_PHASE_STRIP = NO;
+                               OPTIMIZATION_CFLAGS = "-O0";
+                               OTHER_CFLAGS = "-D__MACOSX__ -DDEBUGBREAKS=1";
+                       };
+                       isa = PBXBuildStyle;
+                       name = Development;
+               };
+               014CEA4A0018CE3211CA2923 = {
+                       buildRules = (
+                       );
+                       buildSettings = {
+                               COPY_PHASE_STRIP = YES;
+                               OTHER_CFLAGS = "-D__MACOSX__";
+                       };
+                       isa = PBXBuildStyle;
+                       name = Deployment;
+               };
+//010
+//011
+//012
+//013
+//014
+//030
+//031
+//032
+//033
+//034
+               034768E2FF38A6DC11DB9C8B = {
+                       isa = PBXExecutableFileReference;
+                       path = mDNSResponder;
+                       refType = 3;
+               };
+//030
+//031
+//032
+//033
+//034
+//080
+//081
+//082
+//083
+//084
+               08FB7793FE84155DC02AAC07 = {
+                       buildStyles = (
+                               014CEA490018CE3211CA2923,
+                               014CEA4A0018CE3211CA2923,
+                       );
+                       isa = PBXProject;
+                       mainGroup = 08FB7794FE84155DC02AAC07;
+                       projectDirPath = "";
+                       targets = (
+                               08FB779FFE84155DC02AAC07,
+                               6575FC1C022EB76000000109,
+                       );
+               };
+               08FB7794FE84155DC02AAC07 = {
+                       children = (
+                               08FB7795FE84155DC02AAC07,
+                               6575FC1F022EB78C00000109,
+                               6575FBFE022EAFA800000109,
+                               08FB779DFE84155DC02AAC07,
+                               19C28FBDFE9D53C911CA2CBB,
+                       );
+                       isa = PBXGroup;
+                       name = mDNSResponder;
+                       refType = 4;
+               };
+               08FB7795FE84155DC02AAC07 = {
+                       children = (
+                               6575FBEC022EAF7200000109,
+                               6575FBE9022EAF5A00000109,
+                               6575FC12022EB27800000109,
+                               6575FBEB022EAF7200000109,
+                               654BE64F02B63B93000001D1,
+                               654BE65002B63B93000001D1,
+                               654BE65102B63B93000001D1,
+                               654BE65202B63B93000001D1,
+                               654BE65302B63B93000001D1,
+                               654BE65402B63B93000001D1,
+                       );
+                       isa = PBXGroup;
+                       name = "mDNS Server Sources";
+                       refType = 4;
+               };
+               08FB779DFE84155DC02AAC07 = {
+                       children = (
+                               09AB6884FE841BABC02AAC07,
+                               65713D46025A293200000109,
+                               00CA213D02786FC30CCA2C71,
+                       );
+                       isa = PBXGroup;
+                       name = "External Frameworks and Libraries";
+                       refType = 4;
+               };
+               08FB779FFE84155DC02AAC07 = {
+                       buildPhases = (
+                               08FB77A0FE84155DC02AAC07,
+                               08FB77A1FE84155DC02AAC07,
+                               08FB77A3FE84155DC02AAC07,
+                               08FB77A5FE84155DC02AAC07,
+                       );
+                       buildSettings = {
+                               FRAMEWORK_SEARCH_PATHS = "";
+                               HEADER_SEARCH_PATHS = "\"$(APPLE_INTERNAL_DEVELOPER_DIR)/Headers\"";
+                               INSTALL_PATH = /usr/sbin;
+                               LIBRARY_SEARCH_PATHS = "";
+                               OTHER_CFLAGS = "-D__MACOSX__";
+                               OTHER_LDFLAGS = "";
+                               OTHER_REZFLAGS = "";
+                               PRODUCT_NAME = mDNSResponder;
+                               REZ_EXECUTABLE = YES;
+                               SECTORDER_FLAGS = "";
+                               WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+                       };
+                       dependencies = (
+                       );
+                       isa = PBXToolTarget;
+                       name = mDNSResponder;
+                       productInstallPath = "$(HOME)/bin";
+                       productName = mDNSResponder;
+                       productReference = 034768E2FF38A6DC11DB9C8B;
+                       shouldUseHeadermap = 1;
+               };
+               08FB77A0FE84155DC02AAC07 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                               6575FC02022EAFBA00000109,
+                               654BE65502B63B93000001D1,
+                               654BE65602B63B93000001D1,
+                               654BE65702B63B93000001D1,
+                               654BE65802B63B93000001D1,
+                               654BE65902B63B93000001D1,
+                               654BE65A02B63B93000001D1,
+                       );
+                       isa = PBXHeadersBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               08FB77A1FE84155DC02AAC07 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                               6575FC0D022EB18700000109,
+                               6575FC0E022EB18700000109,
+                               6575FBEA022EAF5A00000109,
+                               6575FBED022EAF7200000109,
+                               6575FBEE022EAF7200000109,
+                               6575FC15022EB27800000109,
+                       );
+                       isa = PBXSourcesBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               08FB77A3FE84155DC02AAC07 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                               09AB6885FE841BABC02AAC07,
+                               65713D66025A293200000109,
+                               6585DD640279A3B7000001D1,
+                       );
+                       isa = PBXFrameworksBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               08FB77A5FE84155DC02AAC07 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                       );
+                       isa = PBXRezBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+//080
+//081
+//082
+//083
+//084
+//090
+//091
+//092
+//093
+//094
+               09AB6884FE841BABC02AAC07 = {
+                       isa = PBXFrameworkReference;
+                       name = CoreFoundation.framework;
+                       path = /System/Library/Frameworks/CoreFoundation.framework;
+                       refType = 0;
+               };
+               09AB6885FE841BABC02AAC07 = {
+                       fileRef = 09AB6884FE841BABC02AAC07;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+//090
+//091
+//092
+//093
+//094
+//190
+//191
+//192
+//193
+//194
+               19C28FBDFE9D53C911CA2CBB = {
+                       children = (
+                               034768E2FF38A6DC11DB9C8B,
+                               6575FC1D022EB76000000109,
+                       );
+                       isa = PBXGroup;
+                       name = Products;
+                       refType = 4;
+               };
+//190
+//191
+//192
+//193
+//194
+//650
+//651
+//652
+//653
+//654
+               654BE64F02B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSClientAPI.h;
+                       path = mDNSCore/mDNSClientAPI.h;
+                       refType = 4;
+               };
+               654BE65002B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSDebug.h;
+                       path = mDNSCore/mDNSDebug.h;
+                       refType = 4;
+               };
+               654BE65102B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSPlatformEnvironment.h;
+                       path = mDNSCore/mDNSPlatformEnvironment.h;
+                       refType = 4;
+               };
+               654BE65202B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSPlatformFunctions.h;
+                       path = mDNSCore/mDNSPlatformFunctions.h;
+                       refType = 4;
+               };
+               654BE65302B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSsprintf.h;
+                       path = mDNSCore/mDNSsprintf.h;
+                       refType = 4;
+               };
+               654BE65402B63B93000001D1 = {
+                       isa = PBXFileReference;
+                       name = mDNSvsprintf.h;
+                       path = mDNSCore/mDNSvsprintf.h;
+                       refType = 4;
+               };
+               654BE65502B63B93000001D1 = {
+                       fileRef = 654BE64F02B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               654BE65602B63B93000001D1 = {
+                       fileRef = 654BE65002B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               654BE65702B63B93000001D1 = {
+                       fileRef = 654BE65102B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               654BE65802B63B93000001D1 = {
+                       fileRef = 654BE65202B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               654BE65902B63B93000001D1 = {
+                       fileRef = 654BE65302B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               654BE65A02B63B93000001D1 = {
+                       fileRef = 654BE65402B63B93000001D1;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               65713D46025A293200000109 = {
+                       isa = PBXFrameworkReference;
+                       name = SystemConfiguration.framework;
+                       path = /System/Library/Frameworks/SystemConfiguration.framework;
+                       refType = 0;
+               };
+               65713D66025A293200000109 = {
+                       fileRef = 65713D46025A293200000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FBE9022EAF5A00000109 = {
+                       indentWidth = 4;
+                       isa = PBXFileReference;
+                       name = mDNS.c;
+                       path = mDNSCore/mDNS.c;
+                       refType = 4;
+                       tabWidth = 4;
+                       usesTabs = 1;
+               };
+               6575FBEA022EAF5A00000109 = {
+                       fileRef = 6575FBE9022EAF5A00000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FBEB022EAF7200000109 = {
+                       indentWidth = 4;
+                       isa = PBXFileReference;
+                       path = CFSocket.c;
+                       refType = 4;
+                       tabWidth = 4;
+                       usesTabs = 1;
+               };
+               6575FBEC022EAF7200000109 = {
+                       indentWidth = 4;
+                       isa = PBXFileReference;
+                       path = daemon.c;
+                       refType = 4;
+                       tabWidth = 4;
+                       usesTabs = 1;
+               };
+               6575FBED022EAF7200000109 = {
+                       fileRef = 6575FBEB022EAF7200000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FBEE022EAF7200000109 = {
+                       fileRef = 6575FBEC022EAF7200000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FBFE022EAFA800000109 = {
+                       children = (
+                               6575FBFF022EAFBA00000109,
+                               6575FC00022EAFBA00000109,
+                               6575FC01022EAFBA00000109,
+                       );
+                       isa = PBXGroup;
+                       name = "DNS Service Discovery MIG files";
+                       refType = 4;
+               };
+               6575FBFF022EAFBA00000109 = {
+                       isa = PBXFileReference;
+                       path = DNSServiceDiscoveryDefines.h;
+                       refType = 4;
+               };
+               6575FC00022EAFBA00000109 = {
+                       isa = PBXFileReference;
+                       path = DNSServiceDiscoveryReply.defs;
+                       refType = 4;
+               };
+               6575FC01022EAFBA00000109 = {
+                       isa = PBXFileReference;
+                       path = DNSServiceDiscoveryRequest.defs;
+                       refType = 4;
+               };
+               6575FC02022EAFBA00000109 = {
+                       fileRef = 6575FBFF022EAFBA00000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FC0D022EB18700000109 = {
+                       fileRef = 6575FC00022EAFBA00000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                               ATTRIBUTES = (
+                                       Client,
+                               );
+                       };
+               };
+               6575FC0E022EB18700000109 = {
+                       fileRef = 6575FC01022EAFBA00000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                               ATTRIBUTES = (
+                                       Server,
+                                       Client,
+                               );
+                       };
+               };
+               6575FC12022EB27800000109 = {
+                       isa = PBXFileReference;
+                       name = mDNSsprintf.c;
+                       path = mDNSCore/mDNSsprintf.c;
+                       refType = 4;
+               };
+               6575FC15022EB27800000109 = {
+                       fileRef = 6575FC12022EB27800000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FC18022EB76000000109 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                       );
+                       isa = PBXHeadersBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               6575FC19022EB76000000109 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                               6575FC21022EB7AA00000109,
+                       );
+                       isa = PBXSourcesBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               6575FC1A022EB76000000109 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                               6575FC24022EBA5D00000109,
+                       );
+                       isa = PBXFrameworksBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               6575FC1B022EB76000000109 = {
+                       buildActionMask = 2147483647;
+                       files = (
+                       );
+                       isa = PBXRezBuildPhase;
+                       runOnlyForDeploymentPostprocessing = 0;
+               };
+               6575FC1C022EB76000000109 = {
+                       buildPhases = (
+                               6575FC18022EB76000000109,
+                               6575FC19022EB76000000109,
+                               6575FC1A022EB76000000109,
+                               6575FC1B022EB76000000109,
+                       );
+                       buildSettings = {
+                               OTHER_CFLAGS = "";
+                               OTHER_LDFLAGS = "";
+                               OTHER_REZFLAGS = "";
+                               PRODUCT_NAME = mDNS;
+                               REZ_EXECUTABLE = YES;
+                               SECTORDER_FLAGS = "";
+                               WARNING_CFLAGS = "-Wmost -Wno-four-char-constants -Wno-unknown-pragmas";
+                       };
+                       dependencies = (
+                       );
+                       isa = PBXToolTarget;
+                       name = mDNS;
+                       productInstallPath = /usr/local/bin;
+                       productName = "Sample mDNS Client";
+                       productReference = 6575FC1D022EB76000000109;
+                       shouldUseHeadermap = 0;
+               };
+               6575FC1D022EB76000000109 = {
+                       isa = PBXExecutableFileReference;
+                       path = mDNS;
+                       refType = 3;
+               };
+               6575FC1F022EB78C00000109 = {
+                       children = (
+                               6575FC20022EB7AA00000109,
+                       );
+                       isa = PBXGroup;
+                       name = SampleMulticastDNSClient;
+                       refType = 4;
+               };
+               6575FC20022EB7AA00000109 = {
+                       indentWidth = 4;
+                       isa = PBXFileReference;
+                       path = SamplemDNSClient.c;
+                       refType = 4;
+                       tabWidth = 4;
+                       usesTabs = 0;
+               };
+               6575FC21022EB7AA00000109 = {
+                       fileRef = 6575FC20022EB7AA00000109;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6575FC24022EBA5D00000109 = {
+                       fileRef = 09AB6884FE841BABC02AAC07;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+               6585DD640279A3B7000001D1 = {
+                       fileRef = 00CA213D02786FC30CCA2C71;
+                       isa = PBXBuildFile;
+                       settings = {
+                       };
+               };
+       };
+       rootObject = 08FB7793FE84155DC02AAC07;
+}