Home | History | Annotate | Download | only in mDNSCore
      1 /* -*- Mode: C; tab-width: 4 -*-
      2  *
      3  * Copyright (c) 2002-2003 Apple Computer, Inc. All rights reserved.
      4  *
      5  * Licensed under the Apache License, Version 2.0 (the "License");
      6  * you may not use this file except in compliance with the License.
      7  * You may obtain a copy of the License at
      8  *
      9  *     http://www.apache.org/licenses/LICENSE-2.0
     10  *
     11  * Unless required by applicable law or agreed to in writing, software
     12  * distributed under the License is distributed on an "AS IS" BASIS,
     13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     14  * See the License for the specific language governing permissions and
     15  * limitations under the License.
     16 
     17    NOTE:
     18    If you're building an application that uses DNS Service Discovery
     19    this is probably NOT the header file you're looking for.
     20    In most cases you will want to use /usr/include/dns_sd.h instead.
     21 
     22    This header file defines the lowest level raw interface to mDNSCore,
     23    which is appropriate *only* on tiny embedded systems where everything
     24    runs in a single address space and memory is extremely constrained.
     25    All the APIs here are malloc-free, which means that the caller is
     26    responsible for passing in a pointer to the relevant storage that
     27    will be used in the execution of that call, and (when called with
     28    correct parameters) all the calls are guaranteed to succeed. There
     29    is never a case where a call can suffer intermittent failures because
     30    the implementation calls malloc() and sometimes malloc() returns NULL
     31    because memory is so limited that no more is available.
     32    This is primarily for devices that need to have precisely known fixed
     33    memory requirements, with absolutely no uncertainty or run-time variation,
     34    but that certainty comes at a cost of more difficult programming.
     35 
     36    For applications running on general-purpose desktop operating systems
     37    (Mac OS, Linux, Solaris, Windows, etc.) the API you should use is
     38    /usr/include/dns_sd.h, which defines the API by which multiple
     39    independent client processes communicate their DNS Service Discovery
     40    requests to a single "mdnsd" daemon running in the background.
     41 
     42    Even on platforms that don't run multiple independent processes in
     43    multiple independent address spaces, you can still use the preferred
     44    dns_sd.h APIs by linking in "dnssd_clientshim.c", which implements
     45    the standard "dns_sd.h" API calls, allocates any required storage
     46    using malloc(), and then calls through to the low-level malloc-free
     47    mDNSCore routines defined here. This has the benefit that even though
     48    you're running on a small embedded system with a single address space,
     49    you can still use the exact same client C code as you'd use on a
     50    general-purpose desktop system.
     51 
     52  */
     53 
     54 #ifndef __mDNSClientAPI_h
     55 #define __mDNSClientAPI_h
     56 
     57 /* MinGW thinks "#define interface struct" is a cute way to do ObjC
     58  * compatibility. Everything is terrible.
     59  */
     60 #ifdef _WIN32
     61 #ifndef interface
     62 #warning "MinGW no longer does weird things with 'interface'. "\
     63          "You can remove this code."
     64 #endif /* ! interface */
     65 #undef interface
     66 #endif /* _WIN32 */
     67 
     68 #if defined(EFI32) || defined(EFI64) || defined(EFIX64)
     69 // EFI doesn't have stdarg.h unless it's building with GCC.
     70 #include "Tiano.h"
     71 #if !defined(__GNUC__)
     72 #define va_list         VA_LIST
     73 #define va_start(a, b)  VA_START(a, b)
     74 #define va_end(a)       VA_END(a)
     75 #define va_arg(a, b)    VA_ARG(a, b)
     76 #endif
     77 #else
     78 #include <stdarg.h>		// stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
     79 #endif
     80 
     81 #include "mDNSDebug.h"
     82 #if APPLE_OSX_mDNSResponder
     83 #include <uuid/uuid.h>
     84 #endif
     85 
     86 #ifdef __cplusplus
     87 	extern "C" {
     88 #endif
     89 
     90 // ***************************************************************************
     91 // Function scope indicators
     92 
     93 // If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
     94 #ifndef mDNSlocal
     95 #define mDNSlocal static
     96 #endif
     97 // If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
     98 // For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
     99 // (When a C file #includes a header file, the "extern" declarations tell the compiler:
    100 // "This symbol exists -- but not necessarily in this C file.")
    101 #ifndef mDNSexport
    102 #define mDNSexport
    103 #endif
    104 
    105 // Explanation: These local/export markers are a little habit of mine for signaling the programmers' intentions.
    106 // When "mDNSlocal" is just a synonym for "static", and "mDNSexport" is a complete no-op, you could be
    107 // forgiven for asking what purpose they serve. The idea is that if you see "mDNSexport" in front of a
    108 // function definition it means the programmer intended it to be exported and callable from other files
    109 // in the project. If you see "mDNSlocal" in front of a function definition it means the programmer
    110 // intended it to be private to that file. If you see neither in front of a function definition it
    111 // means the programmer forgot (so you should work out which it is supposed to be, and fix it).
    112 // Using "mDNSlocal" instead of "static" makes it easier to do a textual searches for one or the other.
    113 // For example you can do a search for "static" to find if any functions declare any local variables as "static"
    114 // (generally a bad idea unless it's also "const", because static storage usually risks being non-thread-safe)
    115 // without the results being cluttered with hundreds of matches for functions declared static.
    116 // - Stuart Cheshire
    117 
    118 // ***************************************************************************
    119 // Structure packing macro
    120 
    121 // If we're not using GNUC, it's not fatal.
    122 // Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
    123 // In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
    124 // developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
    125 #ifndef packedstruct
    126  #if ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
    127   #define packedstruct struct __attribute__((__packed__))
    128   #define packedunion  union  __attribute__((__packed__))
    129  #else
    130   #define packedstruct struct
    131   #define packedunion  union
    132  #endif
    133 #endif
    134 
    135 // ***************************************************************************
    136 #if 0
    137 #pragma mark - DNS Resource Record class and type constants
    138 #endif
    139 
    140 typedef enum							// From RFC 1035
    141 	{
    142 	kDNSClass_IN               = 1,		// Internet
    143 	kDNSClass_CS               = 2,		// CSNET
    144 	kDNSClass_CH               = 3,		// CHAOS
    145 	kDNSClass_HS               = 4,		// Hesiod
    146 	kDNSClass_NONE             = 254,	// Used in DNS UPDATE [RFC 2136]
    147 
    148 	kDNSClass_Mask             = 0x7FFF,// Multicast DNS uses the bottom 15 bits to identify the record class...
    149 	kDNSClass_UniqueRRSet      = 0x8000,// ... and the top bit indicates that all other cached records are now invalid
    150 
    151 	kDNSQClass_ANY             = 255,	// Not a DNS class, but a DNS query class, meaning "all classes"
    152 	kDNSQClass_UnicastResponse = 0x8000	// Top bit set in a question means "unicast response acceptable"
    153 	} DNS_ClassValues;
    154 
    155 typedef enum				// From RFC 1035
    156 	{
    157 	kDNSType_A = 1,			//  1 Address
    158 	kDNSType_NS,			//  2 Name Server
    159 	kDNSType_MD,			//  3 Mail Destination
    160 	kDNSType_MF,			//  4 Mail Forwarder
    161 	kDNSType_CNAME,			//  5 Canonical Name
    162 	kDNSType_SOA,			//  6 Start of Authority
    163 	kDNSType_MB,			//  7 Mailbox
    164 	kDNSType_MG,			//  8 Mail Group
    165 	kDNSType_MR,			//  9 Mail Rename
    166 	kDNSType_NULL,			// 10 NULL RR
    167 	kDNSType_WKS,			// 11 Well-known-service
    168 	kDNSType_PTR,			// 12 Domain name pointer
    169 	kDNSType_HINFO,			// 13 Host information
    170 	kDNSType_MINFO,			// 14 Mailbox information
    171 	kDNSType_MX,			// 15 Mail Exchanger
    172 	kDNSType_TXT,			// 16 Arbitrary text string
    173 	kDNSType_RP,			// 17 Responsible person
    174 	kDNSType_AFSDB,			// 18 AFS cell database
    175 	kDNSType_X25,			// 19 X_25 calling address
    176 	kDNSType_ISDN,			// 20 ISDN calling address
    177 	kDNSType_RT,			// 21 Router
    178 	kDNSType_NSAP,			// 22 NSAP address
    179 	kDNSType_NSAP_PTR,		// 23 Reverse NSAP lookup (deprecated)
    180 	kDNSType_SIG,			// 24 Security signature
    181 	kDNSType_KEY,			// 25 Security key
    182 	kDNSType_PX,			// 26 X.400 mail mapping
    183 	kDNSType_GPOS,			// 27 Geographical position (withdrawn)
    184 	kDNSType_AAAA,			// 28 IPv6 Address
    185 	kDNSType_LOC,			// 29 Location Information
    186 	kDNSType_NXT,			// 30 Next domain (security)
    187 	kDNSType_EID,			// 31 Endpoint identifier
    188 	kDNSType_NIMLOC,		// 32 Nimrod Locator
    189 	kDNSType_SRV,			// 33 Service record
    190 	kDNSType_ATMA,			// 34 ATM Address
    191 	kDNSType_NAPTR,			// 35 Naming Authority PoinTeR
    192 	kDNSType_KX,			// 36 Key Exchange
    193 	kDNSType_CERT,			// 37 Certification record
    194 	kDNSType_A6,			// 38 IPv6 Address (deprecated)
    195 	kDNSType_DNAME,			// 39 Non-terminal DNAME (for IPv6)
    196 	kDNSType_SINK,			// 40 Kitchen sink (experimental)
    197 	kDNSType_OPT,			// 41 EDNS0 option (meta-RR)
    198 	kDNSType_APL,			// 42 Address Prefix List
    199 	kDNSType_DS,			// 43 Delegation Signer
    200 	kDNSType_SSHFP,			// 44 SSH Key Fingerprint
    201 	kDNSType_IPSECKEY,		// 45 IPSECKEY
    202 	kDNSType_RRSIG,			// 46 RRSIG
    203 	kDNSType_NSEC,			// 47 Denial of Existence
    204 	kDNSType_DNSKEY,		// 48 DNSKEY
    205 	kDNSType_DHCID,			// 49 DHCP Client Identifier
    206 	kDNSType_NSEC3,			// 50 Hashed Authenticated Denial of Existence
    207 	kDNSType_NSEC3PARAM,	// 51 Hashed Authenticated Denial of Existence
    208 
    209 	kDNSType_HIP = 55,		// 55 Host Identity Protocol
    210 
    211 	kDNSType_SPF = 99,		// 99 Sender Policy Framework for E-Mail
    212 	kDNSType_UINFO,			// 100 IANA-Reserved
    213 	kDNSType_UID,			// 101 IANA-Reserved
    214 	kDNSType_GID,			// 102 IANA-Reserved
    215 	kDNSType_UNSPEC,		// 103 IANA-Reserved
    216 
    217 	kDNSType_TKEY = 249,	// 249 Transaction key
    218 	kDNSType_TSIG,			// 250 Transaction signature
    219 	kDNSType_IXFR,			// 251 Incremental zone transfer
    220 	kDNSType_AXFR,			// 252 Transfer zone of authority
    221 	kDNSType_MAILB,			// 253 Transfer mailbox records
    222 	kDNSType_MAILA,			// 254 Transfer mail agent records
    223 	kDNSQType_ANY			// Not a DNS type, but a DNS query type, meaning "all types"
    224 	} DNS_TypeValues;
    225 
    226 // ***************************************************************************
    227 #if 0
    228 #pragma mark -
    229 #pragma mark - Simple types
    230 #endif
    231 
    232 // mDNS defines its own names for these common types to simplify portability across
    233 // multiple platforms that may each have their own (different) names for these types.
    234 typedef          int   mDNSBool;
    235 typedef   signed char  mDNSs8;
    236 typedef unsigned char  mDNSu8;
    237 typedef   signed short mDNSs16;
    238 typedef unsigned short mDNSu16;
    239 
    240 // <http://gcc.gnu.org/onlinedocs/gcc-3.3.3/cpp/Common-Predefined-Macros.html> says
    241 //   __LP64__ _LP64
    242 //   These macros are defined, with value 1, if (and only if) the compilation is
    243 //   for a target where long int and pointer both use 64-bits and int uses 32-bit.
    244 // <http://www.intel.com/software/products/compilers/clin/docs/ug/lin1077.htm> says
    245 //   Macro Name __LP64__ Value 1
    246 // A quick Google search for "defined(__LP64__)" OR "#ifdef __LP64__" gives 2590 hits and
    247 // a search for "#if __LP64__" gives only 12, so I think we'll go with the majority and use defined()
    248 #if defined(_ILP64) || defined(__ILP64__)
    249 typedef   signed int32 mDNSs32;
    250 typedef unsigned int32 mDNSu32;
    251 #elif defined(_LP64) || defined(__LP64__)
    252 typedef   signed int   mDNSs32;
    253 typedef unsigned int   mDNSu32;
    254 #else
    255 typedef   signed long  mDNSs32;
    256 typedef unsigned long  mDNSu32;
    257 //typedef   signed int mDNSs32;
    258 //typedef unsigned int mDNSu32;
    259 #endif
    260 
    261 // To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
    262 // This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
    263 // Declaring the type to be the typical generic "void *" would lack this type checking
    264 typedef struct mDNSInterfaceID_dummystruct { void *dummy; } *mDNSInterfaceID;
    265 
    266 // These types are for opaque two- and four-byte identifiers.
    267 // The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
    268 // register for the sake of efficiency, and compared for equality or inequality, but don't forget --
    269 // just because it is in a register doesn't mean it is an integer. Operations like greater than,
    270 // less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
    271 // and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
    272 // find you get code that doesn't work consistently on big-endian and little-endian machines.
    273 #if defined(_WIN32)
    274  #pragma pack(push,2)
    275 #endif
    276 typedef       union { mDNSu8 b[ 2]; mDNSu16 NotAnInteger; } mDNSOpaque16;
    277 typedef       union { mDNSu8 b[ 4]; mDNSu32 NotAnInteger; } mDNSOpaque32;
    278 typedef packedunion { mDNSu8 b[ 6]; mDNSu16 w[3]; mDNSu32 l[1]; } mDNSOpaque48;
    279 typedef       union { mDNSu8 b[ 8]; mDNSu16 w[4]; mDNSu32 l[2]; } mDNSOpaque64;
    280 typedef       union { mDNSu8 b[16]; mDNSu16 w[8]; mDNSu32 l[4]; } mDNSOpaque128;
    281 #if defined(_WIN32)
    282  #pragma pack(pop)
    283 #endif
    284 
    285 typedef mDNSOpaque16  mDNSIPPort;		// An IP port is a two-byte opaque identifier (not an integer)
    286 typedef mDNSOpaque32  mDNSv4Addr;		// An IP address is a four-byte opaque identifier (not an integer)
    287 typedef mDNSOpaque128 mDNSv6Addr;		// An IPv6 address is a 16-byte opaque identifier (not an integer)
    288 typedef mDNSOpaque48  mDNSEthAddr;		// An Ethernet address is a six-byte opaque identifier (not an integer)
    289 
    290 // Bit operations for opaque 64 bit quantity. Uses the 32 bit quantity(l[2]) to set and clear bits
    291 #define mDNSNBBY 8
    292 #define bit_set_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] |= (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
    293 #define bit_clr_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] &= ~(1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
    294 #define bit_get_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] & (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
    295 
    296 enum
    297 	{
    298 	mDNSAddrType_None    = 0,
    299 	mDNSAddrType_IPv4    = 4,
    300 	mDNSAddrType_IPv6    = 6,
    301 	mDNSAddrType_Unknown = ~0	// Special marker value used in known answer list recording
    302 	};
    303 
    304 enum
    305 	{
    306 	mDNSTransport_None = 0,
    307 	mDNSTransport_UDP  = 1,
    308 	mDNSTransport_TCP  = 2
    309 	};
    310 
    311 typedef struct
    312 	{
    313 	mDNSs32 type;
    314 	union { mDNSv6Addr v6; mDNSv4Addr v4; } ip;
    315 	} mDNSAddr;
    316 
    317 enum { mDNSfalse = 0, mDNStrue = 1 };
    318 
    319 #define mDNSNULL 0L
    320 
    321 enum
    322 	{
    323 	mStatus_Waiting           = 1,
    324 	mStatus_NoError           = 0,
    325 
    326 	// mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
    327 	// The top end of the range (FFFE FFFF) is used for error codes;
    328 	// the bottom end of the range (FFFE FF00) is used for non-error values;
    329 
    330 	// Error codes:
    331 	mStatus_UnknownErr                = -65537,		// First value: 0xFFFE FFFF
    332 	mStatus_NoSuchNameErr             = -65538,
    333 	mStatus_NoMemoryErr               = -65539,
    334 	mStatus_BadParamErr               = -65540,
    335 	mStatus_BadReferenceErr           = -65541,
    336 	mStatus_BadStateErr               = -65542,
    337 	mStatus_BadFlagsErr               = -65543,
    338 	mStatus_UnsupportedErr            = -65544,
    339 	mStatus_NotInitializedErr         = -65545,
    340 	mStatus_NoCache                   = -65546,
    341 	mStatus_AlreadyRegistered         = -65547,
    342 	mStatus_NameConflict              = -65548,
    343 	mStatus_Invalid                   = -65549,
    344 	mStatus_Firewall                  = -65550,
    345 	mStatus_Incompatible              = -65551,
    346 	mStatus_BadInterfaceErr           = -65552,
    347 	mStatus_Refused                   = -65553,
    348 	mStatus_NoSuchRecord              = -65554,
    349 	mStatus_NoAuth                    = -65555,
    350 	mStatus_NoSuchKey                 = -65556,
    351 	mStatus_NATTraversal              = -65557,
    352 	mStatus_DoubleNAT                 = -65558,
    353 	mStatus_BadTime                   = -65559,
    354 	mStatus_BadSig                    = -65560,     // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
    355 	mStatus_BadKey                    = -65561,
    356 	mStatus_TransientErr              = -65562,     // transient failures, e.g. sending packets shortly after a network transition or wake from sleep
    357 	mStatus_ServiceNotRunning         = -65563,     // Background daemon not running
    358 	mStatus_NATPortMappingUnsupported = -65564,     // NAT doesn't support NAT-PMP or UPnP
    359 	mStatus_NATPortMappingDisabled    = -65565,     // NAT supports NAT-PMP or UPnP but it's disabled by the administrator
    360 	mStatus_NoRouter                  = -65566,
    361 	mStatus_PollingMode               = -65567,
    362 	mStatus_Timeout                   = -65568,
    363 	// -65568 to -65786 currently unused; available for allocation
    364 
    365 	// tcp connection status
    366 	mStatus_ConnPending       = -65787,
    367 	mStatus_ConnFailed        = -65788,
    368 	mStatus_ConnEstablished   = -65789,
    369 
    370 	// Non-error values:
    371 	mStatus_GrowCache         = -65790,
    372 	mStatus_ConfigChanged     = -65791,
    373 	mStatus_MemFree           = -65792		// Last value: 0xFFFE FF00
    374 	// mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
    375 	};
    376 
    377 typedef mDNSs32 mStatus;
    378 
    379 // RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
    380 #define MAX_DOMAIN_LABEL 63
    381 typedef struct { mDNSu8 c[ 64]; } domainlabel;		// One label: length byte and up to 63 characters
    382 
    383 // RFC 1034/1035/2181 specify that a domain name (length bytes and data bytes) may be up to 255 bytes long,
    384 // plus the terminating zero at the end makes 256 bytes total in the on-the-wire format.
    385 #define MAX_DOMAIN_NAME 256
    386 typedef struct { mDNSu8 c[256]; } domainname;		// Up to 256 bytes of length-prefixed domainlabels
    387 
    388 typedef struct { mDNSu8 c[256]; } UTF8str255;		// Null-terminated C string
    389 
    390 // The longest legal textual form of a DNS name is 1009 bytes, including the C-string terminating NULL at the end.
    391 // Explanation:
    392 // When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
    393 // non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
    394 // The longest legal domain name is 256 bytes, in the form of four labels as shown below:
    395 // Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 62 data bytes, zero byte.
    396 // Each label is encoded textually as characters followed by a trailing dot.
    397 // If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
    398 // plus the C-string terminating NULL as shown below:
    399 // 63*4+1 + 63*4+1 + 63*4+1 + 62*4+1 + 1 = 1009.
    400 // Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
    401 // It is for domain names, where dots are used as label separators, that proper escaping is vital.
    402 #define MAX_ESCAPED_DOMAIN_LABEL 254
    403 #define MAX_ESCAPED_DOMAIN_NAME 1009
    404 
    405 // MAX_REVERSE_MAPPING_NAME
    406 // For IPv4: "123.123.123.123.in-addr.arpa."  30 bytes including terminating NUL
    407 // For IPv6: "x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.x.ip6.arpa."  74 bytes including terminating NUL
    408 
    409 #define MAX_REVERSE_MAPPING_NAME_V4 30
    410 #define MAX_REVERSE_MAPPING_NAME_V6 74
    411 #define MAX_REVERSE_MAPPING_NAME    74
    412 
    413 // Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
    414 // For records containing a hostname (in the name on the left, or in the rdata on the right),
    415 // like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
    416 // them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
    417 
    418 #define kStandardTTL (3600UL * 100 / 80)
    419 #define kHostNameTTL 120UL
    420 
    421 // Some applications want to register their SRV records with a lower ttl so that in case the server
    422 // using a dynamic port number restarts, the clients will not have stale information for more than
    423 // 10 seconds
    424 
    425 #define kHostNameSmallTTL 10UL
    426 
    427 
    428 // Multicast DNS uses announcements (gratuitous responses) to update peer caches.
    429 // This means it is feasible to use relatively larger TTL values than we might otherwise
    430 // use, because we have a cache coherency protocol to keep the peer caches up to date.
    431 // With Unicast DNS, once an authoritative server gives a record with a certain TTL value to a client
    432 // or caching server, that client or caching server is entitled to hold onto the record until its TTL
    433 // expires, and has no obligation to contact the authoritative server again until that time arrives.
    434 // This means that whereas Multicast DNS can use announcements to pre-emptively update stale data
    435 // before it would otherwise have expired, standard Unicast DNS (not using LLQs) has no equivalent
    436 // mechanism, and TTL expiry is the *only* mechanism by which stale data gets deleted. Because of this,
    437 // we currently limit the TTL to ten seconds in such cases where no dynamic cache updating is possible.
    438 #define kStaticCacheTTL 10
    439 
    440 #define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
    441 
    442 typedef struct AuthRecord_struct AuthRecord;
    443 typedef struct ServiceRecordSet_struct ServiceRecordSet;
    444 typedef struct CacheRecord_struct CacheRecord;
    445 typedef struct CacheGroup_struct CacheGroup;
    446 typedef struct AuthGroup_struct AuthGroup;
    447 typedef struct DNSQuestion_struct DNSQuestion;
    448 typedef struct ZoneData_struct ZoneData;
    449 typedef struct mDNS_struct mDNS;
    450 typedef struct mDNS_PlatformSupport_struct mDNS_PlatformSupport;
    451 typedef struct NATTraversalInfo_struct NATTraversalInfo;
    452 
    453 // Structure to abstract away the differences between TCP/SSL sockets, and one for UDP sockets
    454 // The actual definition of these structures appear in the appropriate platform support code
    455 typedef struct TCPSocket_struct TCPSocket;
    456 typedef struct UDPSocket_struct UDPSocket;
    457 
    458 // ***************************************************************************
    459 #if 0
    460 #pragma mark -
    461 #pragma mark - DNS Message structures
    462 #endif
    463 
    464 #define mDNS_numZones   numQuestions
    465 #define mDNS_numPrereqs numAnswers
    466 #define mDNS_numUpdates numAuthorities
    467 
    468 typedef packedstruct
    469 	{
    470 	mDNSOpaque16 id;
    471 	mDNSOpaque16 flags;
    472 	mDNSu16 numQuestions;
    473 	mDNSu16 numAnswers;
    474 	mDNSu16 numAuthorities;
    475 	mDNSu16 numAdditionals;
    476 	} DNSMessageHeader;
    477 
    478 // We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
    479 // However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
    480 // 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
    481 #define AbsoluteMaxDNSMessageData 8940
    482 #define NormalMaxDNSMessageData 1440
    483 typedef packedstruct
    484 	{
    485 	DNSMessageHeader h;						// Note: Size 12 bytes
    486 	mDNSu8 data[AbsoluteMaxDNSMessageData];	// 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
    487 	} DNSMessage;
    488 
    489 typedef struct tcpInfo_t
    490 	{
    491 	mDNS             *m;
    492 	TCPSocket        *sock;
    493 	DNSMessage        request;
    494 	int               requestLen;
    495 	DNSQuestion      *question;   // For queries
    496 	AuthRecord       *rr;         // For record updates
    497 	mDNSAddr          Addr;
    498 	mDNSIPPort        Port;
    499 	mDNSIPPort        SrcPort;
    500 	DNSMessage       *reply;
    501 	mDNSu16           replylen;
    502 	unsigned long     nread;
    503 	int               numReplies;
    504 	} tcpInfo_t;
    505 
    506 // ***************************************************************************
    507 #if 0
    508 #pragma mark -
    509 #pragma mark - Other Packet Format Structures
    510 #endif
    511 
    512 typedef packedstruct
    513 	{
    514 	mDNSEthAddr  dst;
    515 	mDNSEthAddr  src;
    516 	mDNSOpaque16 ethertype;
    517 	} EthernetHeader;		// 14 bytes
    518 
    519 typedef packedstruct
    520 	{
    521 	mDNSOpaque16 hrd;
    522 	mDNSOpaque16 pro;
    523 	mDNSu8       hln;
    524 	mDNSu8       pln;
    525 	mDNSOpaque16 op;
    526 	mDNSEthAddr  sha;
    527 	mDNSv4Addr   spa;
    528 	mDNSEthAddr  tha;
    529 	mDNSv4Addr   tpa;
    530 	} ARP_EthIP;			// 28 bytes
    531 
    532 typedef packedstruct
    533 	{
    534 	mDNSu8       vlen;
    535 	mDNSu8       tos;
    536 	mDNSu16      totlen;
    537 	mDNSOpaque16 id;
    538 	mDNSOpaque16 flagsfrags;
    539 	mDNSu8       ttl;
    540 	mDNSu8       protocol;	// Payload type: 0x06 = TCP, 0x11 = UDP
    541 	mDNSu16      checksum;
    542 	mDNSv4Addr   src;
    543 	mDNSv4Addr   dst;
    544 	} IPv4Header;			// 20 bytes
    545 
    546 typedef packedstruct
    547 	{
    548 	mDNSu32      vcf;		// Version, Traffic Class, Flow Label
    549 	mDNSu16      len;		// Payload Length
    550 	mDNSu8       pro;		// Type of next header: 0x06 = TCP, 0x11 = UDP, 0x3A = ICMPv6
    551 	mDNSu8       ttl;		// Hop Limit
    552 	mDNSv6Addr   src;
    553 	mDNSv6Addr   dst;
    554 	} IPv6Header;			// 40 bytes
    555 
    556 typedef packedstruct
    557 	{
    558 	mDNSv6Addr   src;
    559 	mDNSv6Addr   dst;
    560 	mDNSOpaque32 len;
    561 	mDNSOpaque32 pro;
    562 	} IPv6PseudoHeader;		// 40 bytes
    563 
    564 typedef union
    565 	{
    566 	mDNSu8       bytes[20];
    567 	ARP_EthIP    arp;
    568 	IPv4Header   v4;
    569 	IPv6Header   v6;
    570 	} NetworkLayerPacket;
    571 
    572 typedef packedstruct
    573 	{
    574 	mDNSIPPort   src;
    575 	mDNSIPPort   dst;
    576 	mDNSu32      seq;
    577 	mDNSu32      ack;
    578 	mDNSu8       offset;
    579 	mDNSu8       flags;
    580 	mDNSu16      window;
    581 	mDNSu16      checksum;
    582 	mDNSu16      urgent;
    583 	} TCPHeader;			// 20 bytes; IP protocol type 0x06
    584 
    585 typedef packedstruct
    586 	{
    587 	mDNSIPPort   src;
    588 	mDNSIPPort   dst;
    589 	mDNSu16      len;		// Length including UDP header (i.e. minimum value is 8 bytes)
    590 	mDNSu16      checksum;
    591 	} UDPHeader;			// 8 bytes; IP protocol type 0x11
    592 
    593 typedef packedstruct
    594 	{
    595 	mDNSu8       type;		// 0x87 == Neighbor Solicitation, 0x88 == Neighbor Advertisement
    596 	mDNSu8       code;
    597 	mDNSu16      checksum;
    598 	mDNSu32      flags_res;	// R/S/O flags and reserved bits
    599 	mDNSv6Addr   target;
    600 	// Typically 8 bytes of options are also present
    601 	} IPv6NDP;				// 24 bytes or more; IP protocol type 0x3A
    602 
    603 #define NDP_Sol 0x87
    604 #define NDP_Adv 0x88
    605 
    606 #define NDP_Router    0x80
    607 #define NDP_Solicited 0x40
    608 #define NDP_Override  0x20
    609 
    610 #define NDP_SrcLL 1
    611 #define NDP_TgtLL 2
    612 
    613 typedef union
    614 	{
    615 	mDNSu8       bytes[20];
    616 	TCPHeader    tcp;
    617 	UDPHeader    udp;
    618 	IPv6NDP      ndp;
    619 	} TransportLayerPacket;
    620 
    621 typedef packedstruct
    622 	{
    623 	mDNSOpaque64 InitiatorCookie;
    624 	mDNSOpaque64 ResponderCookie;
    625 	mDNSu8       NextPayload;
    626 	mDNSu8       Version;
    627 	mDNSu8       ExchangeType;
    628 	mDNSu8       Flags;
    629 	mDNSOpaque32 MessageID;
    630 	mDNSu32      Length;
    631 	} IKEHeader;			// 28 bytes
    632 
    633 // ***************************************************************************
    634 #if 0
    635 #pragma mark -
    636 #pragma mark - Resource Record structures
    637 #endif
    638 
    639 // Authoritative Resource Records:
    640 // There are four basic types: Shared, Advisory, Unique, Known Unique
    641 
    642 // * Shared Resource Records do not have to be unique
    643 // -- Shared Resource Records are used for DNS-SD service PTRs
    644 // -- It is okay for several hosts to have RRs with the same name but different RDATA
    645 // -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
    646 // -- These RRs typically have moderately high TTLs (e.g. one hour)
    647 // -- These records are announced on startup and topology changes for the benefit of passive listeners
    648 // -- These records send a goodbye packet when deregistering
    649 //
    650 // * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
    651 //
    652 // * Unique Resource Records should be unique among hosts within any given mDNS scope
    653 // -- The majority of Resource Records are of this type
    654 // -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
    655 // -- Responses may be sent immediately, because only one host should be responding to any particular query
    656 // -- These RRs typically have low TTLs (e.g. a few minutes)
    657 // -- On startup and after topology changes, a host issues queries to verify uniqueness
    658 
    659 // * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
    660 // not have to verify their uniqueness because this is already known by other means (e.g. the RR name
    661 // is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
    662 
    663 // Summary of properties of different record types:
    664 // Probe?    Does this record type send probes before announcing?
    665 // Conflict? Does this record type react if we observe an apparent conflict?
    666 // Goodbye?  Does this record type send a goodbye packet on departure?
    667 //
    668 //               Probe? Conflict? Goodbye? Notes
    669 // Unregistered                            Should not appear in any list (sanity check value)
    670 // Shared         No      No       Yes     e.g. Service PTR record
    671 // Deregistering  No      No       Yes     Shared record about to announce its departure and leave the list
    672 // Advisory       No      No       No
    673 // Unique         Yes     Yes      No      Record intended to be unique -- will probe to verify
    674 // Verified       Yes     Yes      No      Record has completed probing, and is verified unique
    675 // KnownUnique    No      Yes      No      Record is assumed by other means to be unique
    676 
    677 // Valid lifecycle of a record:
    678 // Unregistered ->                   Shared      -> Deregistering -(goodbye)-> Unregistered
    679 // Unregistered ->                   Advisory                               -> Unregistered
    680 // Unregistered -> Unique -(probe)-> Verified                               -> Unregistered
    681 // Unregistered ->                   KnownUnique                            -> Unregistered
    682 
    683 // Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
    684 // is one of a particular set of types simply by performing the appropriate bitwise masking operation.
    685 
    686 // Cache Resource Records (received from the network):
    687 // There are four basic types: Answer, Unique Answer, Additional, Unique Additional
    688 // Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
    689 // Bit 6 (value 0x40) is set for answer records; clear for authority/additional records
    690 // Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
    691 
    692 enum
    693 	{
    694 	kDNSRecordTypeUnregistered     = 0x00,	// Not currently in any list
    695 	kDNSRecordTypeDeregistering    = 0x01,	// Shared record about to announce its departure and leave the list
    696 
    697 	kDNSRecordTypeUnique           = 0x02,	// Will become a kDNSRecordTypeVerified when probing is complete
    698 
    699 	kDNSRecordTypeAdvisory         = 0x04,	// Like Shared, but no goodbye packet
    700 	kDNSRecordTypeShared           = 0x08,	// Shared means record name does not have to be unique -- use random delay on responses
    701 
    702 	kDNSRecordTypeVerified         = 0x10,	// Unique means mDNS should check that name is unique (and then send immediate responses)
    703 	kDNSRecordTypeKnownUnique      = 0x20,	// Known Unique means mDNS can assume name is unique without checking
    704 	                                        // For Dynamic Update records, Known Unique means the record must already exist on the server.
    705 	kDNSRecordTypeUniqueMask       = (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique),
    706 	kDNSRecordTypeActiveSharedMask = (kDNSRecordTypeAdvisory         | kDNSRecordTypeShared),
    707 	kDNSRecordTypeActiveUniqueMask = (kDNSRecordTypeVerified         | kDNSRecordTypeKnownUnique),
    708 	kDNSRecordTypeActiveMask       = (kDNSRecordTypeActiveSharedMask | kDNSRecordTypeActiveUniqueMask),
    709 
    710 	kDNSRecordTypePacketAdd        = 0x80,	// Received in the Additional  Section of a DNS Response
    711 	kDNSRecordTypePacketAddUnique  = 0x90,	// Received in the Additional  Section of a DNS Response with kDNSClass_UniqueRRSet set
    712 	kDNSRecordTypePacketAuth       = 0xA0,	// Received in the Authorities Section of a DNS Response
    713 	kDNSRecordTypePacketAuthUnique = 0xB0,	// Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
    714 	kDNSRecordTypePacketAns        = 0xC0,	// Received in the Answer      Section of a DNS Response
    715 	kDNSRecordTypePacketAnsUnique  = 0xD0,	// Received in the Answer      Section of a DNS Response with kDNSClass_UniqueRRSet set
    716 
    717 	kDNSRecordTypePacketNegative   = 0xF0,	// Pseudo-RR generated to cache non-existence results like NXDomain
    718 
    719 	kDNSRecordTypePacketUniqueMask = 0x10	// True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique, kDNSRecordTypePacketNegative
    720 	};
    721 
    722 typedef packedstruct { mDNSu16 priority; mDNSu16 weight; mDNSIPPort port; domainname target;   } rdataSRV;
    723 typedef packedstruct { mDNSu16 preference;                                domainname exchange; } rdataMX;
    724 typedef packedstruct { domainname mbox; domainname txt;                                        } rdataRP;
    725 typedef packedstruct { mDNSu16 preference; domainname map822; domainname mapx400;              } rdataPX;
    726 
    727 typedef packedstruct
    728 	{
    729 	domainname mname;
    730 	domainname rname;
    731 	mDNSs32 serial;		// Modular counter; increases when zone changes
    732 	mDNSu32 refresh;	// Time in seconds that a slave waits after successful replication of the database before it attempts replication again
    733 	mDNSu32 retry;		// Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
    734 	mDNSu32 expire;		// Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
    735 	mDNSu32 min;		// Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
    736 	} rdataSOA;
    737 
    738 // EDNS Option Code registrations are recorded in the "DNS EDNS0 Options" section of
    739 // <http://www.iana.org/assignments/dns-parameters>
    740 
    741 #define kDNSOpt_LLQ   1
    742 #define kDNSOpt_Lease 2
    743 #define kDNSOpt_NSID  3
    744 #define kDNSOpt_Owner 4
    745 
    746 typedef struct
    747 	{
    748 	mDNSu16      vers;
    749 	mDNSu16      llqOp;
    750 	mDNSu16      err;	// Or UDP reply port, in setup request
    751 	// Note: In the in-memory form, there's typically a two-byte space here, so that the following 64-bit id is word-aligned
    752 	mDNSOpaque64 id;
    753 	mDNSu32      llqlease;
    754 	} LLQOptData;
    755 
    756 typedef struct
    757 	{
    758 	mDNSu8       vers;		// Version number of this Owner OPT record
    759 	mDNSs8       seq;		// Sleep/wake epoch
    760 	mDNSEthAddr  HMAC;		// Host's primary identifier (e.g. MAC of on-board Ethernet)
    761 	mDNSEthAddr  IMAC;		// Interface's MAC address (if different to primary MAC)
    762 	mDNSOpaque48 password;	// Optional password
    763 	} OwnerOptData;
    764 
    765 // Note: rdataOPT format may be repeated an arbitrary number of times in a single resource record
    766 typedef packedstruct
    767 	{
    768 	mDNSu16 opt;
    769 	mDNSu16 optlen;
    770 	union { LLQOptData llq; mDNSu32 updatelease; OwnerOptData owner; } u;
    771 	} rdataOPT;
    772 
    773 // Space needed to put OPT records into a packet:
    774 // Header      11 bytes (name 1, type 2, class 2, TTL 4, length 2)
    775 // LLQ rdata   18 bytes (opt 2, len 2, vers 2, op 2, err 2, id 8, lease 4)
    776 // Lease rdata  8 bytes (opt 2, len 2, lease 4)
    777 // Owner rdata 12-24    (opt 2, len 2, owner 8-20)
    778 
    779 #define DNSOpt_Header_Space                 11
    780 #define DNSOpt_LLQData_Space               (4 + 2 + 2 + 2 + 8 + 4)
    781 #define DNSOpt_LeaseData_Space             (4 + 4)
    782 #define DNSOpt_OwnerData_ID_Space          (4 + 2 + 6)
    783 #define DNSOpt_OwnerData_ID_Wake_Space     (4 + 2 + 6 + 6)
    784 #define DNSOpt_OwnerData_ID_Wake_PW4_Space (4 + 2 + 6 + 6 + 4)
    785 #define DNSOpt_OwnerData_ID_Wake_PW6_Space (4 + 2 + 6 + 6 + 6)
    786 
    787 #define ValidOwnerLength(X) (	(X) == DNSOpt_OwnerData_ID_Space          - 4 || \
    788 								(X) == DNSOpt_OwnerData_ID_Wake_Space     - 4 || \
    789 								(X) == DNSOpt_OwnerData_ID_Wake_PW4_Space - 4 || \
    790 								(X) == DNSOpt_OwnerData_ID_Wake_PW6_Space - 4    )
    791 
    792 #define DNSOpt_Owner_Space(A,B) (mDNSSameEthAddress((A),(B)) ? DNSOpt_OwnerData_ID_Space : DNSOpt_OwnerData_ID_Wake_Space)
    793 
    794 #define DNSOpt_Data_Space(O) (                                  \
    795 	(O)->opt == kDNSOpt_LLQ   ? DNSOpt_LLQData_Space   :        \
    796 	(O)->opt == kDNSOpt_Lease ? DNSOpt_LeaseData_Space :        \
    797 	(O)->opt == kDNSOpt_Owner ? DNSOpt_Owner_Space(&(O)->u.owner.HMAC, &(O)->u.owner.IMAC) : 0x10000)
    798 
    799 // A maximal NSEC record is:
    800 //   256 bytes domainname 'nextname'
    801 // + 256 * 34 = 8704 bytes of bitmap data
    802 // = 8960 bytes total
    803 // For now we only support NSEC records encoding DNS types 0-255 and ignore the nextname (we always set it to be the same as the rrname),
    804 // which gives us a fixed in-memory size of 32 bytes (256 bits)
    805 typedef struct
    806 	{
    807 	mDNSu8 bitmap[32];
    808 	} rdataNSEC;
    809 
    810 // StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
    811 // MaximumRDSize is 8K the absolute maximum we support (at least for now)
    812 #define StandardAuthRDSize 264
    813 #define MaximumRDSize 8192
    814 
    815 // InlineCacheRDSize is 68
    816 // Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
    817 // Records received from the network with rdata larger than this have additional storage allocated for the rdata
    818 // A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
    819 // 1461 records in cache
    820 // 292 were one-byte TXT records
    821 // 136 were four-byte A records
    822 // 184 were sixteen-byte AAAA records
    823 // 780 were various PTR, TXT and SRV records from 12-64 bytes
    824 // Only 69 records had rdata bigger than 64 bytes
    825 // Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
    826 // have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
    827 #define InlineCacheRDSize 68
    828 
    829 // On 64-bit, the pointers in a CacheRecord are bigger, and that creates 8 bytes more space for the name in a CacheGroup
    830 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
    831 	#if defined(_ILP64) || defined(__ILP64__) || defined(_LP64) || defined(__LP64__) || defined(_WIN64)
    832 	#define InlineCacheGroupNameSize 160
    833 	#else
    834 	#define InlineCacheGroupNameSize 148
    835 	#endif
    836 #else
    837 	#if defined(_ILP64) || defined(__ILP64__) || defined(_LP64) || defined(__LP64__) || defined(_WIN64)
    838 	#define InlineCacheGroupNameSize 144
    839 	#else
    840 	#define InlineCacheGroupNameSize 132
    841 	#endif
    842 #endif
    843 
    844 // The RDataBody union defines the common rdata types that fit into our 264-byte limit
    845 typedef union
    846 	{
    847 	mDNSu8      data[StandardAuthRDSize];
    848 	mDNSv4Addr  ipv4;		// For 'A' record
    849 	domainname  name;		// For PTR, NS, CNAME, DNAME
    850 	UTF8str255  txt;
    851 	rdataMX     mx;
    852 	mDNSv6Addr  ipv6;		// For 'AAAA' record
    853 	rdataSRV    srv;
    854 	rdataOPT    opt[2];		// For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
    855 	rdataNSEC   nsec;
    856 	} RDataBody;
    857 
    858 // The RDataBody2 union is the same as above, except it includes fields for the larger types like soa, rp, px
    859 typedef union
    860 	{
    861 	mDNSu8      data[StandardAuthRDSize];
    862 	mDNSv4Addr  ipv4;		// For 'A' record
    863 	domainname  name;		// For PTR, NS, CNAME, DNAME
    864 	rdataSOA    soa;		// This is large; not included in the normal RDataBody definition
    865 	UTF8str255  txt;
    866 	rdataMX     mx;
    867 	rdataRP     rp;			// This is large; not included in the normal RDataBody definition
    868 	rdataPX     px;			// This is large; not included in the normal RDataBody definition
    869 	mDNSv6Addr  ipv6;		// For 'AAAA' record
    870 	rdataSRV    srv;
    871 	rdataOPT    opt[2];		// For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
    872 	rdataNSEC   nsec;
    873 	} RDataBody2;
    874 
    875 typedef struct
    876 	{
    877 	mDNSu16    MaxRDLength;	// Amount of storage allocated for rdata (usually sizeof(RDataBody))
    878 	mDNSu16    padding;		// So that RDataBody is aligned on 32-bit boundary
    879 	RDataBody  u;
    880 	} RData;
    881 
    882 // sizeofRDataHeader should be 4 bytes
    883 #define sizeofRDataHeader (sizeof(RData) - sizeof(RDataBody))
    884 
    885 // RData_small is a smaller version of the RData object, used for inline data storage embedded in a CacheRecord_struct
    886 typedef struct
    887 	{
    888 	mDNSu16    MaxRDLength;	// Storage allocated for data (may be greater than InlineCacheRDSize if additional storage follows this object)
    889 	mDNSu16    padding;		// So that data is aligned on 32-bit boundary
    890 	mDNSu8     data[InlineCacheRDSize];
    891 	} RData_small;
    892 
    893 // Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
    894 typedef void mDNSRecordCallback(mDNS *const m, AuthRecord *const rr, mStatus result);
    895 
    896 // Note:
    897 // Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
    898 // The intent of this callback is to allow the client to free memory, if necessary.
    899 // The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
    900 typedef void mDNSRecordUpdateCallback(mDNS *const m, AuthRecord *const rr, RData *OldRData, mDNSu16 OldRDLen);
    901 
    902 // ***************************************************************************
    903 #if 0
    904 #pragma mark -
    905 #pragma mark - NAT Traversal structures and constants
    906 #endif
    907 
    908 #define NATMAP_MAX_RETRY_INTERVAL    ((mDNSPlatformOneSecond * 60) * 15)    // Max retry interval is 15 minutes
    909 #define NATMAP_MIN_RETRY_INTERVAL     (mDNSPlatformOneSecond * 2)           // Min retry interval is 2 seconds
    910 #define NATMAP_INIT_RETRY             (mDNSPlatformOneSecond / 4)           // start at 250ms w/ exponential decay
    911 #define NATMAP_DEFAULT_LEASE          (60 * 60 * 2)                         // 2 hour lease life in seconds
    912 #define NATMAP_VERS 0
    913 
    914 typedef enum
    915 	{
    916 	NATOp_AddrRequest    = 0,
    917 	NATOp_MapUDP         = 1,
    918 	NATOp_MapTCP         = 2,
    919 
    920 	NATOp_AddrResponse   = 0x80 | 0,
    921 	NATOp_MapUDPResponse = 0x80 | 1,
    922 	NATOp_MapTCPResponse = 0x80 | 2,
    923 	} NATOp_t;
    924 
    925 enum
    926 	{
    927 	NATErr_None    = 0,
    928 	NATErr_Vers    = 1,
    929 	NATErr_Refused = 2,
    930 	NATErr_NetFail = 3,
    931 	NATErr_Res     = 4,
    932 	NATErr_Opcode  = 5
    933 	};
    934 
    935 typedef mDNSu16 NATErr_t;
    936 
    937 typedef packedstruct
    938 	{
    939 	mDNSu8 vers;
    940 	mDNSu8 opcode;
    941 	} NATAddrRequest;
    942 
    943 typedef packedstruct
    944 	{
    945 	mDNSu8     vers;
    946 	mDNSu8     opcode;
    947 	mDNSu16    err;
    948 	mDNSu32    upseconds;		// Time since last NAT engine reboot, in seconds
    949 	mDNSv4Addr ExtAddr;
    950 	} NATAddrReply;
    951 
    952 typedef packedstruct
    953 	{
    954 	mDNSu8 vers;
    955 	mDNSu8 opcode;
    956 	mDNSOpaque16 unused;
    957 	mDNSIPPort intport;
    958 	mDNSIPPort extport;
    959 	mDNSu32    NATReq_lease;
    960 	} NATPortMapRequest;
    961 
    962 typedef packedstruct
    963 	{
    964 	mDNSu8     vers;
    965 	mDNSu8     opcode;
    966 	mDNSu16    err;
    967 	mDNSu32    upseconds;		// Time since last NAT engine reboot, in seconds
    968 	mDNSIPPort intport;
    969 	mDNSIPPort extport;
    970 	mDNSu32    NATRep_lease;
    971 	} NATPortMapReply;
    972 
    973 typedef enum
    974 	{
    975 	LNTDiscoveryOp      = 1,
    976 	LNTExternalAddrOp   = 2,
    977 	LNTPortMapOp        = 3,
    978 	LNTPortMapDeleteOp  = 4
    979 	} LNTOp_t;
    980 
    981 #define LNT_MAXBUFSIZE 8192
    982 typedef struct tcpLNTInfo_struct tcpLNTInfo;
    983 struct tcpLNTInfo_struct
    984 	{
    985 	tcpLNTInfo       *next;
    986 	mDNS             *m;
    987 	NATTraversalInfo *parentNATInfo;	// pointer back to the parent NATTraversalInfo
    988 	TCPSocket        *sock;
    989 	LNTOp_t           op;				// operation performed using this connection
    990 	mDNSAddr          Address;			// router address
    991 	mDNSIPPort        Port;				// router port
    992 	mDNSu8           *Request;			// xml request to router
    993 	int               requestLen;
    994 	mDNSu8           *Reply;			// xml reply from router
    995 	int               replyLen;
    996 	unsigned long     nread;			// number of bytes read so far
    997 	int               retries;			// number of times we've tried to do this port mapping
    998 	};
    999 
   1000 typedef void (*NATTraversalClientCallback)(mDNS *m, NATTraversalInfo *n);
   1001 
   1002 // if m->timenow <  ExpiryTime then we have an active mapping, and we'll renew halfway to expiry
   1003 // if m->timenow >= ExpiryTime then our mapping has expired, and we're trying to create one
   1004 
   1005 struct NATTraversalInfo_struct
   1006 	{
   1007 	// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
   1008 	NATTraversalInfo           *next;
   1009 
   1010 	mDNSs32                     ExpiryTime;			// Time this mapping expires, or zero if no mapping
   1011 	mDNSs32                     retryInterval;		// Current interval, between last packet we sent and the next one
   1012 	mDNSs32                     retryPortMap;		// If Protocol is nonzero, time to send our next mapping packet
   1013 	mStatus                     NewResult;			// New error code; will be copied to Result just prior to invoking callback
   1014 
   1015 #ifdef _LEGACY_NAT_TRAVERSAL_
   1016 	tcpLNTInfo                  tcpInfo;			// Legacy NAT traversal (UPnP) TCP connection
   1017 #endif
   1018 
   1019 	// Result fields: When the callback is invoked these fields contain the answers the client is looking for
   1020 	// When the callback is invoked ExternalPort is *usually* set to be the same the same as RequestedPort, except:
   1021 	// (a) When we're behind a NAT gateway with port mapping disabled, ExternalPort is reported as zero to
   1022 	//     indicate that we don't currently have a working mapping (but RequestedPort retains the external port
   1023 	//     we'd like to get, the next time we meet an accomodating NAT gateway willing to give us one).
   1024 	// (b) When we have a routable non-RFC1918 address, we don't *need* a port mapping, so ExternalPort
   1025 	//     is reported as the same as our InternalPort, since that is effectively our externally-visible port too.
   1026 	//     Again, RequestedPort retains the external port we'd like to get the next time we find ourself behind a NAT gateway.
   1027 	// To improve stability of port mappings, RequestedPort is updated any time we get a successful
   1028 	// mapping response from the NAT-PMP or UPnP gateway. For example, if we ask for port 80, and
   1029 	// get assigned port 81, then thereafter we'll contine asking for port 81.
   1030 	mDNSInterfaceID             InterfaceID;
   1031 	mDNSv4Addr                  ExternalAddress;	// Initially set to onesIPv4Addr, until first callback
   1032 	mDNSIPPort                  ExternalPort;
   1033 	mDNSu32                     Lifetime;
   1034 	mStatus                     Result;
   1035 
   1036 	// Client API fields: The client must set up these fields *before* making any NAT traversal API calls
   1037 	mDNSu8                      Protocol;			// NATOp_MapUDP or NATOp_MapTCP, or zero if just requesting the external IP address
   1038 	mDNSIPPort                  IntPort;			// Client's internal port number (doesn't change)
   1039 	mDNSIPPort                  RequestedPort;		// Requested external port; may be updated with actual value assigned by gateway
   1040 	mDNSu32                     NATLease;			// Requested lifetime in seconds (doesn't change)
   1041 	NATTraversalClientCallback  clientCallback;
   1042 	void                       *clientContext;
   1043 	};
   1044 
   1045 enum
   1046 	{
   1047 	DNSServer_Untested = 0,
   1048 	DNSServer_Passed   = 1,
   1049 	DNSServer_Failed   = 2,
   1050 	DNSServer_Disabled = 3
   1051 	};
   1052 
   1053 enum
   1054 	{
   1055 	DNSServer_FlagDelete = 1,
   1056 	DNSServer_FlagNew    = 2
   1057 	};
   1058 
   1059 enum
   1060 	{
   1061 	McastResolver_FlagDelete = 1,
   1062 	McastResolver_FlagNew    = 2
   1063 	};
   1064 
   1065 typedef struct McastResolver
   1066 	{
   1067 	struct McastResolver *next;
   1068 	mDNSInterfaceID interface;
   1069 	mDNSu32         flags;		// Set when we're planning to delete this from the list
   1070 	domainname      domain;
   1071 	mDNSu32         timeout;	// timeout value for questions
   1072 	} McastResolver;
   1073 
   1074 typedef struct DNSServer
   1075 	{
   1076 	struct DNSServer *next;
   1077 	mDNSInterfaceID interface;	// For specialized uses; we can have DNS servers reachable over specific interfaces
   1078 	mDNSAddr        addr;
   1079 	mDNSIPPort      port;
   1080 	mDNSOpaque16    testid;
   1081 	mDNSu32         flags;		// Set when we're planning to delete this from the list
   1082 	mDNSu32         teststate;	// Have we sent bug-detection query to this server?
   1083 	mDNSs32         lasttest;	// Time we sent last bug-detection query to this server
   1084 	domainname      domain;		// name->server matching for "split dns"
   1085 	mDNSs32			penaltyTime; // amount of time this server is penalized
   1086 	mDNSBool		scoped;		// interface should be matched against question only
   1087 								// if scoped is set
   1088 	mDNSu32			timeout;	// timeout value for questions
   1089 	} DNSServer;
   1090 
   1091 typedef struct							// Size is 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
   1092 	{
   1093 	mDNSu8           RecordType;		// See enum above
   1094 	mDNSu16          rrtype;
   1095 	mDNSu16          rrclass;
   1096 	mDNSu32          rroriginalttl;		// In seconds
   1097 	mDNSu16          rdlength;			// Size of the raw rdata, in bytes, in the on-the-wire format
   1098 										// (In-memory storage may be larger, for structures containing 'holes', like SOA,
   1099 										// or smaller, for NSEC where we don't bother storing the nextname field)
   1100 	mDNSu16          rdestimate;		// Upper bound on on-the-wire size of rdata after name compression
   1101 	mDNSu32          namehash;			// Name-based (i.e. case-insensitive) hash of name
   1102 	mDNSu32          rdatahash;			// For rdata containing domain name (e.g. PTR, SRV, CNAME etc.), case-insensitive name hash
   1103 										// else, for all other rdata, 32-bit hash of the raw rdata
   1104 										// Note: This requirement is important. Various routines like AddAdditionalsToResponseList(),
   1105 										// ReconfirmAntecedents(), etc., use rdatahash as a pre-flight check to see
   1106 										// whether it's worth doing a full SameDomainName() call. If the rdatahash
   1107 										// is not a correct case-insensitive name hash, they'll get false negatives.
   1108 
   1109 	// Grouping pointers together at the end of the structure improves the memory layout efficiency
   1110 	mDNSInterfaceID  InterfaceID;		// Set if this RR is specific to one interface
   1111 										// For records received off the wire, InterfaceID is *always* set to the receiving interface
   1112 										// For our authoritative records, InterfaceID is usually zero, except for those few records
   1113 										// that are interface-specific (e.g. address records, especially linklocal addresses)
   1114 	const domainname *name;
   1115 	RData           *rdata;				// Pointer to storage for this rdata
   1116 	DNSServer       *rDNSServer;		// Unicast DNS server authoritative for this entry;null for multicast
   1117 	} ResourceRecord;
   1118 
   1119 // Unless otherwise noted, states may apply to either independent record registrations or service registrations
   1120 typedef enum
   1121 	{
   1122 	regState_Zero              = 0,
   1123 	regState_Pending           = 1,     // update sent, reply not received
   1124 	regState_Registered        = 2,     // update sent, reply received
   1125 	regState_DeregPending      = 3,     // dereg sent, reply not received
   1126 	regState_Unregistered      = 4,     // not in any list
   1127 	regState_Refresh           = 5,     // outstanding refresh (or target change) message
   1128 	regState_NATMap            = 6,     // establishing NAT port mapping
   1129 	regState_UpdatePending     = 7,     // update in flight as result of mDNS_Update call
   1130 	regState_NoTarget          = 8,     // SRV Record registration pending registration of hostname
   1131 	regState_NATError          = 9     // unable to complete NAT traversal
   1132 	} regState_t;
   1133 
   1134 enum
   1135 	{
   1136 	Target_Manual = 0,
   1137 	Target_AutoHost = 1,
   1138 	Target_AutoHostAndNATMAP = 2
   1139 	};
   1140 
   1141 typedef enum
   1142 	{
   1143 	mergeState_Zero = 0,
   1144 	mergeState_DontMerge = 1  // Set on fatal error conditions to disable merging
   1145 	} mergeState_t;
   1146 
   1147 struct AuthGroup_struct				// Header object for a list of AuthRecords with the same name
   1148 	{
   1149 	AuthGroup      *next;				// Next AuthGroup object in this hash table bucket
   1150 	mDNSu32         namehash;			// Name-based (i.e. case insensitive) hash of name
   1151 	AuthRecord     *members;			// List of CacheRecords with this same name
   1152 	AuthRecord    **rrauth_tail;		// Tail end of that list
   1153 	domainname     *name;				// Common name for all AuthRecords in this list
   1154 	AuthRecord     *NewLocalOnlyRecords;
   1155 	// Size to here is 20 bytes when compiling 32-bit; 40 bytes when compiling 64-bit
   1156 	mDNSu8          namestorage[InlineCacheGroupNameSize];
   1157 	};
   1158 
   1159 #define AUTH_HASH_SLOTS 499
   1160 #define FORALL_AUTHRECORDS(SLOT,AG,AR)                           	\
   1161 	for ((SLOT) = 0; (SLOT) < AUTH_HASH_SLOTS; (SLOT)++)         	\
   1162 		for ((AG)=m->rrauth.rrauth_hash[(SLOT)]; (AG); (AG)=(AG)->next) \
   1163 			for ((AR) = (AG)->members; (AR); (AR)=(AR)->next)
   1164 
   1165 typedef union AuthEntity_union AuthEntity;
   1166 union AuthEntity_union { AuthEntity *next; AuthGroup ag; };
   1167 typedef struct {
   1168 	mDNSu32 rrauth_size;				// Total number of available auth entries
   1169 	mDNSu32 rrauth_totalused;			// Number of auth entries currently occupied
   1170 	mDNSu32 rrauth_report;
   1171 	mDNSu8  rrauth_lock;				// For debugging: Set at times when these lists may not be modified
   1172 	AuthEntity *rrauth_free;
   1173 	AuthGroup *rrauth_hash[AUTH_HASH_SLOTS];
   1174 }AuthHash;
   1175 
   1176 // AuthRecordAny includes mDNSInterface_Any and interface specific auth records (anything
   1177 // other than P2P or LocalOnly)
   1178 typedef enum
   1179 	{
   1180 	AuthRecordAny, 				// registered for *Any, NOT including P2P interfaces
   1181 	AuthRecordAnyIncludeP2P, 	// registered for *Any, including P2P interfaces
   1182 	AuthRecordLocalOnly,
   1183 	AuthRecordP2P				// discovered over D2D/P2P framework
   1184 	} AuthRecType;
   1185 
   1186 struct AuthRecord_struct
   1187 	{
   1188 	// For examples of how to set up this structure for use in mDNS_Register(),
   1189 	// see mDNS_AdvertiseInterface() or mDNS_RegisterService().
   1190 	// Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
   1191 	// mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
   1192 
   1193 	AuthRecord     *next;				// Next in list; first element of structure for efficiency reasons
   1194 	// Field Group 1: Common ResourceRecord fields
   1195 	ResourceRecord  resrec;				// 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
   1196 
   1197 	// Field Group 2: Persistent metadata for Authoritative Records
   1198 	AuthRecord     *Additional1;		// Recommended additional record to include in response (e.g. SRV for PTR record)
   1199 	AuthRecord     *Additional2;		// Another additional (e.g. TXT for PTR record)
   1200 	AuthRecord     *DependentOn;		// This record depends on another for its uniqueness checking
   1201 	AuthRecord     *RRSet;				// This unique record is part of an RRSet
   1202 	mDNSRecordCallback *RecordCallback;	// Callback function to call for state changes, and to free memory asynchronously on deregistration
   1203 	void           *RecordContext;		// Context parameter for the callback function
   1204 	mDNSu8          AutoTarget;			// Set if the target of this record (PTR, CNAME, SRV, etc.) is our host name
   1205 	mDNSu8          AllowRemoteQuery;	// Set if we allow hosts not on the local link to query this record
   1206 	mDNSu8          ForceMCast;			// Set by client to advertise solely via multicast, even for apparently unicast names
   1207 
   1208 	OwnerOptData    WakeUp;				// WakeUp.HMAC.l[0] nonzero indicates that this is a Sleep Proxy record
   1209 	mDNSAddr        AddressProxy;		// For reverse-mapping Sleep Proxy PTR records, address in question
   1210 	mDNSs32         TimeRcvd;			// In platform time units
   1211 	mDNSs32         TimeExpire;			// In platform time units
   1212 	AuthRecType     ARType;             // LocalOnly, P2P or Normal ?
   1213 
   1214 	// Field Group 3: Transient state for Authoritative Records
   1215 	mDNSu8          Acknowledged;		// Set if we've given the success callback to the client
   1216 	mDNSu8          ProbeCount;			// Number of probes remaining before this record is valid (kDNSRecordTypeUnique)
   1217 	mDNSu8          AnnounceCount;		// Number of announcements remaining (kDNSRecordTypeShared)
   1218 	mDNSu8          RequireGoodbye;		// Set if this RR has been announced on the wire and will require a goodbye packet
   1219 	mDNSu8          AnsweredLocalQ;		// Set if this AuthRecord has been delivered to any local question (LocalOnly or mDNSInterface_Any)
   1220 	mDNSu8          IncludeInProbe;		// Set if this RR is being put into a probe right now
   1221 	mDNSu8          ImmedUnicast;		// Set if we may send our response directly via unicast to the requester
   1222 	mDNSInterfaceID SendNSECNow;		// Set if we need to generate associated NSEC data for this rrname
   1223 	mDNSInterfaceID ImmedAnswer;		// Someone on this interface issued a query we need to answer (all-ones for all interfaces)
   1224 #if MDNS_LOG_ANSWER_SUPPRESSION_TIMES
   1225 	mDNSs32         ImmedAnswerMarkTime;
   1226 #endif
   1227 	mDNSInterfaceID ImmedAdditional;	// Hint that we might want to also send this record, just to be helpful
   1228 	mDNSInterfaceID SendRNow;			// The interface this query is being sent on right now
   1229 	mDNSv4Addr      v4Requester;		// Recent v4 query for this record, or all-ones if more than one recent query
   1230 	mDNSv6Addr      v6Requester;		// Recent v6 query for this record, or all-ones if more than one recent query
   1231 	AuthRecord     *NextResponse;		// Link to the next element in the chain of responses to generate
   1232 	const mDNSu8   *NR_AnswerTo;		// Set if this record was selected by virtue of being a direct answer to a question
   1233 	AuthRecord     *NR_AdditionalTo;	// Set if this record was selected by virtue of being additional to another
   1234 	mDNSs32         ThisAPInterval;		// In platform time units: Current interval for announce/probe
   1235 	mDNSs32         LastAPTime;			// In platform time units: Last time we sent announcement/probe
   1236 	mDNSs32         LastMCTime;			// Last time we multicast this record (used to guard against packet-storm attacks)
   1237 	mDNSInterfaceID LastMCInterface;	// Interface this record was multicast on at the time LastMCTime was recorded
   1238 	RData          *NewRData;			// Set if we are updating this record with new rdata
   1239 	mDNSu16         newrdlength;		// ... and the length of the new RData
   1240 	mDNSRecordUpdateCallback *UpdateCallback;
   1241 	mDNSu32         UpdateCredits;		// Token-bucket rate limiting of excessive updates
   1242 	mDNSs32         NextUpdateCredit;	// Time next token is added to bucket
   1243 	mDNSs32         UpdateBlocked;		// Set if update delaying is in effect
   1244 
   1245 	// Field Group 4: Transient uDNS state for Authoritative Records
   1246 	regState_t   state;			// Maybe combine this with resrec.RecordType state? Right now it's ambiguous and confusing.
   1247 								// e.g. rr->resrec.RecordType can be kDNSRecordTypeUnregistered,
   1248 								// and rr->state can be regState_Unregistered
   1249 								// What if we find one of those statements is true and the other false? What does that mean?
   1250 	mDNSBool     uselease;		// dynamic update contains (should contain) lease option
   1251 	mDNSs32      expire;		// In platform time units: expiration of lease (-1 for static)
   1252 	mDNSBool     Private;		// If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
   1253 	mDNSOpaque16 updateid;		// Identifier to match update request and response -- also used when transferring records to Sleep Proxy
   1254 	const domainname *zone;		// the zone that is updated
   1255 	ZoneData  *nta;
   1256 	struct tcpInfo_t *tcp;
   1257 	NATTraversalInfo  NATinfo;
   1258 	mDNSBool SRVChanged;       // temporarily deregistered service because its SRV target or port changed
   1259 	mergeState_t  mState;      // Unicast Record Registrations merge state
   1260 	mDNSu8		  refreshCount; // Number of refreshes to the server
   1261 	mStatus		  updateError;  // Record update resulted in Error ?
   1262 
   1263 	// uDNS_UpdateRecord support fields
   1264 	// Do we really need all these in *addition* to NewRData and newrdlength above?
   1265 	void *UpdateContext;	// Context parameter for the update callback function
   1266 	mDNSu16 OrigRDLen;		// previously registered, being deleted
   1267 	mDNSu16 InFlightRDLen;	// currently being registered
   1268 	mDNSu16 QueuedRDLen;	// pending operation (re-transmitting if necessary) THEN register the queued update
   1269 	RData *OrigRData;
   1270 	RData *InFlightRData;
   1271 	RData *QueuedRData;
   1272 
   1273 	// Field Group 5: Large data objects go at the end
   1274 	domainname      namestorage;
   1275 	RData           rdatastorage;		// Normally the storage is right here, except for oversized records
   1276 	// rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
   1277 	// are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
   1278 	// DO NOT ADD ANY MORE FIELDS HERE
   1279 	};
   1280 
   1281 // IsLocalDomain alone is not sufficient to determine that a record is mDNS or uDNS. By default domain names within
   1282 // the "local" pseudo-TLD (and within the IPv4 and IPv6 link-local reverse mapping domains) are automatically treated
   1283 // as mDNS records, but it is also possible to force any record (even those not within one of the inherently local
   1284 // domains) to be handled as an mDNS record by setting the ForceMCast flag, or by setting a non-zero InterfaceID.
   1285 // For example, the reverse-mapping PTR record created in AdvertiseInterface sets the ForceMCast flag, since it points to
   1286 // a dot-local hostname, and therefore it would make no sense to register this record with a wide-area Unicast DNS server.
   1287 // The same applies to Sleep Proxy records, which we will answer for when queried via mDNS, but we never want to try
   1288 // to register them with a wide-area Unicast DNS server -- and we probably don't have the required credentials anyway.
   1289 // Currently we have no concept of a wide-area uDNS record scoped to a particular interface, so if the InterfaceID is
   1290 // nonzero we treat this the same as ForceMCast.
   1291 // Note: Question_uDNS(Q) is used in *only* one place -- on entry to mDNS_StartQuery_internal, to decide whether to set TargetQID.
   1292 // Everywhere else in the code, the determination of whether a question is unicast is made by checking to see if TargetQID is nonzero.
   1293 #define AuthRecord_uDNS(R) ((R)->resrec.InterfaceID == mDNSInterface_Any && !(R)->ForceMCast && !IsLocalDomain((R)->resrec.name))
   1294 #define Question_uDNS(Q)   ((Q)->InterfaceID == mDNSInterface_Unicast || \
   1295 	((Q)->InterfaceID != mDNSInterface_LocalOnly && (Q)->InterfaceID != mDNSInterface_P2P && !(Q)->ForceMCast && !IsLocalDomain(&(Q)->qname)))
   1296 
   1297 #define RRLocalOnly(rr) ((rr)->ARType == AuthRecordLocalOnly || (rr)->ARType == AuthRecordP2P)
   1298 
   1299 #define RRAny(rr) ((rr)->ARType == AuthRecordAny || (rr)->ARType == AuthRecordAnyIncludeP2P)
   1300 
   1301 // Question (A or AAAA) that is suppressed currently because IPv4 or IPv6 address
   1302 // is not available locally for A or AAAA question respectively
   1303 #define QuerySuppressed(Q) ((Q)->SuppressUnusable && (Q)->SuppressQuery)
   1304 
   1305 #define PrivateQuery(Q) ((Q)->AuthInfo && (Q)->AuthInfo->AutoTunnel)
   1306 
   1307 // Normally we always lookup the cache and /etc/hosts before sending the query on the wire. For single label
   1308 // queries (A and AAAA) that are unqualified (indicated by AppendSearchDomains), we want to append search
   1309 // domains before we try them as such
   1310 #define ApplySearchDomainsFirst(q) ((q)->AppendSearchDomains && (CountLabels(&((q)->qname))) == 1)
   1311 
   1312 // Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
   1313 typedef struct ARListElem
   1314 	{
   1315 	struct ARListElem *next;
   1316 	AuthRecord ar;          // Note: Must be last element of structure, to accomodate oversized AuthRecords
   1317 	} ARListElem;
   1318 
   1319 struct CacheGroup_struct				// Header object for a list of CacheRecords with the same name
   1320 	{
   1321 	CacheGroup     *next;				// Next CacheGroup object in this hash table bucket
   1322 	mDNSu32         namehash;			// Name-based (i.e. case insensitive) hash of name
   1323 	CacheRecord    *members;			// List of CacheRecords with this same name
   1324 	CacheRecord   **rrcache_tail;		// Tail end of that list
   1325 	domainname     *name;				// Common name for all CacheRecords in this list
   1326 	// Size to here is 20 bytes when compiling 32-bit; 40 bytes when compiling 64-bit
   1327 	mDNSu8          namestorage[InlineCacheGroupNameSize];
   1328 	};
   1329 
   1330 
   1331 struct CacheRecord_struct
   1332 	{
   1333 	CacheRecord    *next;				// Next in list; first element of structure for efficiency reasons
   1334 	ResourceRecord  resrec;				// 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit
   1335 
   1336 	// Transient state for Cache Records
   1337 	CacheRecord    *NextInKAList;		// Link to the next element in the chain of known answers to send
   1338 	mDNSs32         TimeRcvd;			// In platform time units
   1339 	mDNSs32         DelayDelivery;		// Set if we want to defer delivery of this answer to local clients
   1340 	mDNSs32         NextRequiredQuery;	// In platform time units
   1341 	mDNSs32         LastUsed;			// In platform time units
   1342 	DNSQuestion    *CRActiveQuestion;	// Points to an active question referencing this answer. Can never point to a NewQuestion.
   1343 	mDNSu32         UnansweredQueries;	// Number of times we've issued a query for this record without getting an answer
   1344 	mDNSs32         LastUnansweredTime;	// In platform time units; last time we incremented UnansweredQueries
   1345 #if ENABLE_MULTI_PACKET_QUERY_SNOOPING
   1346 	mDNSu32         MPUnansweredQ;		// Multi-packet query handling: Number of times we've seen a query for this record
   1347 	mDNSs32         MPLastUnansweredQT;	// Multi-packet query handling: Last time we incremented MPUnansweredQ
   1348 	mDNSu32         MPUnansweredKA;		// Multi-packet query handling: Number of times we've seen this record in a KA list
   1349 	mDNSBool        MPExpectingKA;		// Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
   1350 #endif
   1351 	CacheRecord    *NextInCFList;		// Set if this is in the list of records we just received with the cache flush bit set
   1352 	// Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit
   1353 	RData_small     smallrdatastorage;	// Storage for small records is right here (4 bytes header + 68 bytes data = 72 bytes)
   1354 	};
   1355 
   1356 // Storage sufficient to hold either a CacheGroup header or a CacheRecord
   1357 // -- for best efficiency (to avoid wasted unused storage) they should be the same size
   1358 typedef union CacheEntity_union CacheEntity;
   1359 union CacheEntity_union { CacheEntity *next; CacheGroup cg; CacheRecord cr; };
   1360 
   1361 typedef struct
   1362 	{
   1363 	CacheRecord r;
   1364 	mDNSu8 _extradata[MaximumRDSize-InlineCacheRDSize];		// Glue on the necessary number of extra bytes
   1365 	domainname namestorage;									// Needs to go *after* the extra rdata bytes
   1366 	} LargeCacheRecord;
   1367 
   1368 typedef struct HostnameInfo
   1369 	{
   1370 	struct HostnameInfo *next;
   1371 	NATTraversalInfo natinfo;
   1372 	domainname fqdn;
   1373 	AuthRecord arv4;                          // registered IPv4 address record
   1374 	AuthRecord arv6;                          // registered IPv6 address record
   1375 	mDNSRecordCallback *StatusCallback;       // callback to deliver success or error code to client layer
   1376 	const void *StatusContext;                // Client Context
   1377 	} HostnameInfo;
   1378 
   1379 typedef struct ExtraResourceRecord_struct ExtraResourceRecord;
   1380 struct ExtraResourceRecord_struct
   1381 	{
   1382 	ExtraResourceRecord *next;
   1383 	mDNSu32 ClientID;  // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
   1384 	AuthRecord r;
   1385 	// Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
   1386 	// In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
   1387 	// that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
   1388 	};
   1389 
   1390 // Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
   1391 typedef void mDNSServiceCallback(mDNS *const m, ServiceRecordSet *const sr, mStatus result);
   1392 
   1393 // A ServiceRecordSet has no special meaning to the core code of the Multicast DNS protocol engine;
   1394 // it is just a convenience structure to group together the records that make up a standard service
   1395 // registration so that they can be allocted and deallocted together as a single memory object.
   1396 // It contains its own ServiceCallback+ServiceContext to report aggregate results up to the next layer of software above.
   1397 // It also contains:
   1398 //  * the basic PTR/SRV/TXT triplet used to represent any DNS-SD service
   1399 //  * the "_services" PTR record for service enumeration
   1400 //  * the optional list of SubType PTR records
   1401 //  * the optional list of additional records attached to the service set (e.g. iChat pictures)
   1402 
   1403 struct ServiceRecordSet_struct
   1404 	{
   1405 	// These internal state fields are used internally by mDNSCore; the client layer needn't be concerned with them.
   1406 	// No fields need to be set up by the client prior to calling mDNS_RegisterService();
   1407 	// all required data is passed as parameters to that function.
   1408 	mDNSServiceCallback *ServiceCallback;
   1409 	void                *ServiceContext;
   1410 	mDNSBool             Conflict;	// Set if this record set was forcibly deregistered because of a conflict
   1411 
   1412 	ExtraResourceRecord *Extras;	// Optional list of extra AuthRecords attached to this service registration
   1413 	mDNSu32              NumSubTypes;
   1414 	AuthRecord          *SubTypes;
   1415 	AuthRecord           RR_ADV;	// e.g. _services._dns-sd._udp.local. PTR _printer._tcp.local.
   1416 	AuthRecord           RR_PTR;	// e.g. _printer._tcp.local.        PTR Name._printer._tcp.local.
   1417 	AuthRecord           RR_SRV;	// e.g. Name._printer._tcp.local.   SRV 0 0 port target
   1418 	AuthRecord           RR_TXT;	// e.g. Name._printer._tcp.local.   TXT PrintQueueName
   1419 	// Don't add any fields after AuthRecord RR_TXT.
   1420 	// This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
   1421 	};
   1422 
   1423 // ***************************************************************************
   1424 #if 0
   1425 #pragma mark -
   1426 #pragma mark - Question structures
   1427 #endif
   1428 
   1429 // We record the last eight instances of each duplicate query
   1430 // This gives us v4/v6 on each of Ethernet, AirPort and Firewire, and two free slots "for future expansion"
   1431 // If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
   1432 // Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
   1433 #define DupSuppressInfoSize 8
   1434 
   1435 typedef struct
   1436 	{
   1437 	mDNSs32               Time;
   1438 	mDNSInterfaceID       InterfaceID;
   1439 	mDNSs32               Type;				// v4 or v6?
   1440 	} DupSuppressInfo;
   1441 
   1442 typedef enum
   1443 	{
   1444 	LLQ_InitialRequest    = 1,
   1445 	LLQ_SecondaryRequest  = 2,
   1446 	LLQ_Established       = 3,
   1447 	LLQ_Poll              = 4
   1448 	} LLQ_State;
   1449 
   1450 // LLQ constants
   1451 #define kLLQ_Vers      1
   1452 #define kLLQ_DefLease  7200 // 2 hours
   1453 #define kLLQ_MAX_TRIES 3    // retry an operation 3 times max
   1454 #define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
   1455 // LLQ Operation Codes
   1456 #define kLLQOp_Setup     1
   1457 #define kLLQOp_Refresh   2
   1458 #define kLLQOp_Event     3
   1459 
   1460 // LLQ Errror Codes
   1461 enum
   1462 	{
   1463 	LLQErr_NoError    = 0,
   1464 	LLQErr_ServFull   = 1,
   1465 	LLQErr_Static     = 2,
   1466 	LLQErr_FormErr    = 3,
   1467 	LLQErr_NoSuchLLQ  = 4,
   1468 	LLQErr_BadVers    = 5,
   1469 	LLQErr_UnknownErr = 6
   1470 	};
   1471 
   1472 enum { NoAnswer_Normal = 0, NoAnswer_Suspended = 1, NoAnswer_Fail = 2 };
   1473 
   1474 #define HMAC_LEN    64
   1475 #define HMAC_IPAD   0x36
   1476 #define HMAC_OPAD   0x5c
   1477 #define MD5_LEN     16
   1478 
   1479 #define AutoTunnelUnregistered(X) (                                              \
   1480 	(X)->AutoTunnelHostRecord.resrec.RecordType == kDNSRecordTypeUnregistered && \
   1481 	(X)->AutoTunnelDeviceInfo.resrec.RecordType == kDNSRecordTypeUnregistered && \
   1482 	(X)->AutoTunnelService.   resrec.RecordType == kDNSRecordTypeUnregistered && \
   1483 	(X)->AutoTunnel6Record.   resrec.RecordType == kDNSRecordTypeUnregistered    )
   1484 
   1485 // Internal data structure to maintain authentication information
   1486 typedef struct DomainAuthInfo
   1487 	{
   1488 	struct DomainAuthInfo *next;
   1489 	mDNSs32          deltime;				// If we're planning to delete this DomainAuthInfo, the time we want it deleted
   1490 	const char*      AutoTunnel;            // If NULL, this is not an AutoTunnel DAI. Otherwise, this is prepended to the IPSec identifier
   1491 	AuthRecord       AutoTunnelHostRecord;	// User-visible hostname; used as SRV target for AutoTunnel services
   1492 	AuthRecord       AutoTunnelTarget;		// Opaque hostname of tunnel endpoint; used as SRV target for AutoTunnelService record
   1493 	AuthRecord       AutoTunnelDeviceInfo;	// Device info of tunnel endpoint
   1494 	AuthRecord       AutoTunnelService;		// Service record (possibly NAT-Mapped) of IKE daemon implementing tunnel endpoint
   1495 	AuthRecord       AutoTunnel6Record;     // AutoTunnel AAAA Record obtained from Connectivityd
   1496 	NATTraversalInfo AutoTunnelNAT;
   1497 	domainname       domain;
   1498 	domainname       keyname;
   1499 	domainname       hostname;
   1500 	mDNSIPPort       port;
   1501 	char             b64keydata[32];
   1502 	mDNSu8           keydata_ipad[HMAC_LEN];	// padded key for inner hash rounds
   1503 	mDNSu8           keydata_opad[HMAC_LEN];	// padded key for outer hash rounds
   1504 	} DomainAuthInfo;
   1505 
   1506 // Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
   1507 typedef enum { QC_rmv = 0, QC_add = 1, QC_addnocache = 2 } QC_result;
   1508 typedef void mDNSQuestionCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord);
   1509 
   1510 #define NextQSendTime(Q)  ((Q)->LastQTime + (Q)->ThisQInterval)
   1511 #define ActiveQuestion(Q) ((Q)->ThisQInterval > 0 && !(Q)->DuplicateOf)
   1512 #define TimeToSendThisQuestion(Q,time) (ActiveQuestion(Q) && (time) - NextQSendTime(Q) >= 0)
   1513 
   1514 struct DNSQuestion_struct
   1515 	{
   1516 	// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
   1517 	DNSQuestion          *next;
   1518 	mDNSu32               qnamehash;
   1519 	mDNSs32               DelayAnswering;	// Set if we want to defer answering this question until the cache settles
   1520 	mDNSs32               LastQTime;		// Last scheduled transmission of this Q on *all* applicable interfaces
   1521 	mDNSs32               ThisQInterval;	// LastQTime + ThisQInterval is the next scheduled transmission of this Q
   1522 											// ThisQInterval > 0 for an active question;
   1523 											// ThisQInterval = 0 for a suspended question that's still in the list
   1524 											// ThisQInterval = -1 for a cancelled question (should not still be in list)
   1525 	mDNSs32               ExpectUnicastResp;// Set when we send a query with the kDNSQClass_UnicastResponse bit set
   1526 	mDNSs32               LastAnswerPktNum;	// The sequence number of the last response packet containing an answer to this Q
   1527 	mDNSu32               RecentAnswerPkts;	// Number of answers since the last time we sent this query
   1528 	mDNSu32               CurrentAnswers;	// Number of records currently in the cache that answer this question
   1529 	mDNSu32               LargeAnswers;		// Number of answers with rdata > 1024 bytes
   1530 	mDNSu32               UniqueAnswers;	// Number of answers received with kDNSClass_UniqueRRSet bit set
   1531 	mDNSInterfaceID       FlappingInterface1;// Set when an interface goes away, to flag if remove events are delivered for this Q
   1532 	mDNSInterfaceID       FlappingInterface2;// Set when an interface goes away, to flag if remove events are delivered for this Q
   1533 	DomainAuthInfo       *AuthInfo;			// Non-NULL if query is currently being done using Private DNS
   1534 	DNSQuestion          *DuplicateOf;
   1535 	DNSQuestion          *NextInDQList;
   1536 	DupSuppressInfo       DupSuppress[DupSuppressInfoSize];
   1537 	mDNSInterfaceID       SendQNow;			// The interface this query is being sent on right now
   1538 	mDNSBool              SendOnAll;		// Set if we're sending this question on all active interfaces
   1539 	mDNSu32               RequestUnicast;	// Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
   1540 	mDNSs32               LastQTxTime;		// Last time this Q was sent on one (but not necessarily all) interfaces
   1541 	mDNSu32               CNAMEReferrals;	// Count of how many CNAME redirections we've done
   1542 	mDNSBool              SuppressQuery;    // This query should be suppressed and not sent on the wire
   1543 	mDNSu8                LOAddressAnswers; // Number of answers from the local only auth records that are
   1544 		                                    // answering A, AAAA and CNAME (/etc/hosts)
   1545 	mDNSu8                WakeOnResolveCount; // Number of wakes that should be sent on resolve
   1546 	mDNSs32               StopTime;			// Time this question should be stopped by giving them a negative answer
   1547 
   1548 	// Wide Area fields. These are used internally by the uDNS core
   1549 	UDPSocket            *LocalSocket;
   1550 	mDNSBool             deliverAddEvents;  // Change in DNSSserver requiring to deliver ADD events
   1551 	DNSServer            *qDNSServer;		// Caching server for this query (in the absence of an SRV saying otherwise)
   1552 	mDNSOpaque64          validDNSServers;  // Valid DNSServers for this question
   1553 	mDNSu16              noServerResponse;  // At least one server did not respond.
   1554 	mDNSu16              triedAllServersOnce; // Tried all DNS servers once
   1555 	mDNSu8               unansweredQueries;// The number of unanswered queries to this server
   1556 
   1557 	ZoneData             *nta;				// Used for getting zone data for private or LLQ query
   1558 	mDNSAddr              servAddr;			// Address and port learned from _dns-llq, _dns-llq-tls or _dns-query-tls SRV query
   1559 	mDNSIPPort            servPort;
   1560 	struct tcpInfo_t *tcp;
   1561 	mDNSIPPort            tcpSrcPort;		// Local Port TCP packet received on;need this as tcp struct is disposed
   1562 											// by tcpCallback before calling into mDNSCoreReceive
   1563 	mDNSu8                NoAnswer;			// Set if we want to suppress answers until tunnel setup has completed
   1564 
   1565 	// LLQ-specific fields. These fields are only meaningful when LongLived flag is set
   1566 	LLQ_State             state;
   1567 	mDNSu32               ReqLease;			// seconds (relative)
   1568 	mDNSs32               expire;			// ticks (absolute)
   1569 	mDNSs16               ntries;           // for UDP: the number of packets sent for this LLQ state
   1570 	                                       // for TCP: there is some ambiguity in the use of this variable, but in general, it is
   1571 	                                       //          the number of TCP/TLS connection attempts for this LLQ state, or
   1572 	                                       //          the number of packets sent for this TCP/TLS connection
   1573 	mDNSOpaque64          id;
   1574 
   1575 	// Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
   1576 	mDNSInterfaceID       InterfaceID;		// Non-zero if you want to issue queries only on a single specific IP interface
   1577 	mDNSAddr              Target;			// Non-zero if you want to direct queries to a specific unicast target address
   1578 	mDNSIPPort            TargetPort;		// Must be set if Target is set
   1579 	mDNSOpaque16          TargetQID;		// Must be set if Target is set
   1580 	domainname            qname;
   1581 	mDNSu16               qtype;
   1582 	mDNSu16               qclass;
   1583 	mDNSBool              LongLived;        // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
   1584 	mDNSBool              ExpectUnique;		// Set by client if it's expecting unique RR(s) for this question, not shared RRs
   1585 	mDNSBool              ForceMCast;		// Set by client to force mDNS query, even for apparently uDNS names
   1586 	mDNSBool              ReturnIntermed;	// Set by client to request callbacks for intermediate CNAME/NXDOMAIN results
   1587 	mDNSBool              SuppressUnusable; // Set by client to suppress unusable queries to be sent on the wire
   1588 	mDNSBool              RetryWithSearchDomains;	// Retry with search domains if there is no entry in the cache or AuthRecords
   1589 	mDNSu8                TimeoutQuestion; // Timeout this question if there is no reply in configured time
   1590 	mDNSu8                WakeOnResolve; // Send wakeup on resolve
   1591 	mDNSs8                SearchListIndex;  // Index into SearchList; Used by the client layer but not touched by core
   1592 	mDNSs8                AppendSearchDomains; // Search domains can be appended for this query
   1593 	mDNSs8                AppendLocalSearchDomains; // Search domains ending in .local can be appended for this query
   1594 	domainname           *qnameOrig;       // Copy of the original question name if it is not fully qualified
   1595 	mDNSQuestionCallback *QuestionCallback;
   1596 	void                 *QuestionContext;
   1597 	};
   1598 
   1599 typedef struct
   1600 	{
   1601 	// Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
   1602 	// When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
   1603 	domainname      name;
   1604 	mDNSInterfaceID InterfaceID;		// ID of the interface the response was received on
   1605 	mDNSAddr        ip;					// Remote (destination) IP address where this service can be accessed
   1606 	mDNSIPPort      port;				// Port where this service can be accessed
   1607 	mDNSu16         TXTlen;
   1608 	mDNSu8          TXTinfo[2048];		// Additional demultiplexing information (e.g. LPR queue name)
   1609 	} ServiceInfo;
   1610 
   1611 // Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
   1612 typedef struct ServiceInfoQuery_struct ServiceInfoQuery;
   1613 typedef void mDNSServiceInfoQueryCallback(mDNS *const m, ServiceInfoQuery *query);
   1614 struct ServiceInfoQuery_struct
   1615 	{
   1616 	// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
   1617 	// No fields need to be set up by the client prior to calling mDNS_StartResolveService();
   1618 	// all required data is passed as parameters to that function.
   1619 	// The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
   1620 	// and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
   1621 	// dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
   1622 	DNSQuestion                   qSRV;
   1623 	DNSQuestion                   qTXT;
   1624 	DNSQuestion                   qAv4;
   1625 	DNSQuestion                   qAv6;
   1626 	mDNSu8                        GotSRV;
   1627 	mDNSu8                        GotTXT;
   1628 	mDNSu8                        GotADD;
   1629 	mDNSu32                       Answers;
   1630 	ServiceInfo                  *info;
   1631 	mDNSServiceInfoQueryCallback *ServiceInfoQueryCallback;
   1632 	void                         *ServiceInfoQueryContext;
   1633 	};
   1634 
   1635 typedef enum { ZoneServiceUpdate, ZoneServiceQuery, ZoneServiceLLQ } ZoneService;
   1636 
   1637 typedef void ZoneDataCallback(mDNS *const m, mStatus err, const ZoneData *result);
   1638 
   1639 struct ZoneData_struct
   1640 	{
   1641 	domainname       ChildName;			// Name for which we're trying to find the responsible server
   1642 	ZoneService      ZoneService;		// Which service we're seeking for this zone (update, query, or LLQ)
   1643 	domainname       *CurrentSOA;		// Points to somewhere within ChildName
   1644 	domainname       ZoneName;			// Discovered result: Left-hand-side of SOA record
   1645 	mDNSu16          ZoneClass;			// Discovered result: DNS Class from SOA record
   1646 	domainname       Host;				// Discovered result: Target host from SRV record
   1647 	mDNSIPPort       Port;				// Discovered result: Update port, query port, or LLQ port from SRV record
   1648 	mDNSAddr         Addr;				// Discovered result: Address of Target host from SRV record
   1649 	mDNSBool         ZonePrivate;		// Discovered result: Does zone require encrypted queries?
   1650 	ZoneDataCallback *ZoneDataCallback;	// Caller-specified function to be called upon completion
   1651 	void             *ZoneDataContext;
   1652 	DNSQuestion      question;			// Storage for any active question
   1653 	};
   1654 
   1655 extern ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *callbackInfo);
   1656 extern void CancelGetZoneData(mDNS *const m, ZoneData *nta);
   1657 extern mDNSBool IsGetZoneDataQuestion(DNSQuestion *q);
   1658 
   1659 typedef struct DNameListElem
   1660 	{
   1661 	struct DNameListElem *next;
   1662 	mDNSu32 uid;
   1663 	domainname name;
   1664 	} DNameListElem;
   1665 
   1666 #if APPLE_OSX_mDNSResponder
   1667 // Different states that we go through locating the peer
   1668 #define TC_STATE_AAAA_PEER			0x000000001		/* Peer's BTMM IPv6 address */
   1669 #define TC_STATE_AAAA_PEER_RELAY	0x000000002		/* Peer's IPv6 Relay address */
   1670 #define TC_STATE_SRV_PEER			0x000000003		/* Peer's SRV Record corresponding to IPv4 address */
   1671 #define TC_STATE_ADDR_PEER			0x000000004		/* Peer's IPv4 address */
   1672 
   1673 typedef struct ClientTunnel
   1674 	{
   1675 	struct ClientTunnel *next;
   1676 	const char *prefix;
   1677 	domainname dstname;
   1678 	mDNSBool   MarkedForDeletion;
   1679 	mDNSv6Addr loc_inner;
   1680 	mDNSv4Addr loc_outer;
   1681 	mDNSv6Addr loc_outer6;
   1682 	mDNSv6Addr rmt_inner;
   1683 	mDNSv4Addr rmt_outer;
   1684 	mDNSv6Addr rmt_outer6;
   1685 	mDNSIPPort rmt_outer_port;
   1686 	mDNSu16	tc_state;
   1687 	DNSQuestion q;
   1688 	} ClientTunnel;
   1689 #endif
   1690 
   1691 // ***************************************************************************
   1692 #if 0
   1693 #pragma mark -
   1694 #pragma mark - NetworkInterfaceInfo_struct
   1695 #endif
   1696 
   1697 typedef struct NetworkInterfaceInfo_struct NetworkInterfaceInfo;
   1698 
   1699 // A NetworkInterfaceInfo_struct serves two purposes:
   1700 // 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
   1701 // 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
   1702 //    Since there may be multiple IP addresses on a single physical interface,
   1703 //    there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
   1704 //    In this case, to avoid sending the same packet n times, when there's more than one
   1705 //    struct with the same InterfaceID, mDNSCore picks one member of the set to be the
   1706 //    active representative of the set; all others have the 'InterfaceActive' flag unset.
   1707 
   1708 struct NetworkInterfaceInfo_struct
   1709 	{
   1710 	// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
   1711 	NetworkInterfaceInfo *next;
   1712 
   1713 	mDNSu8          InterfaceActive;	// Set if interface is sending & receiving packets (see comment above)
   1714 	mDNSu8          IPv4Available;		// If InterfaceActive, set if v4 available on this InterfaceID
   1715 	mDNSu8          IPv6Available;		// If InterfaceActive, set if v6 available on this InterfaceID
   1716 
   1717 	DNSQuestion     NetWakeBrowse;
   1718 	DNSQuestion     NetWakeResolve[3];	// For fault-tolerance, we try up to three Sleep Proxies
   1719 	mDNSAddr        SPSAddr[3];
   1720 	mDNSIPPort      SPSPort[3];
   1721 	mDNSs32         NextSPSAttempt;		// -1 if we're not currently attempting to register with any Sleep Proxy
   1722 	mDNSs32         NextSPSAttemptTime;
   1723 
   1724 	// Standard AuthRecords that every Responder host should have (one per active IP address)
   1725 	AuthRecord RR_A;					// 'A' or 'AAAA' (address) record for our ".local" name
   1726 	AuthRecord RR_PTR;					// PTR (reverse lookup) record
   1727 	AuthRecord RR_HINFO;
   1728 
   1729 	// Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
   1730 	mDNSInterfaceID InterfaceID;		// Identifies physical interface; MUST NOT be 0, -1, or -2
   1731 	mDNSAddr        ip;					// The IPv4 or IPv6 address to advertise
   1732 	mDNSAddr        mask;
   1733 	mDNSEthAddr     MAC;
   1734 	char            ifname[64];			// Windows uses a GUID string for the interface name, which doesn't fit in 16 bytes
   1735 	mDNSu8          Advertise;			// False if you are only searching on this interface
   1736 	mDNSu8          McastTxRx;			// Send/Receive multicast on this { InterfaceID, address family } ?
   1737 	mDNSu8          NetWake;			// Set if Wake-On-Magic-Packet is enabled on this interface
   1738 	mDNSu8          Loopback;			// Set if this is the loopback interface
   1739 	};
   1740 
   1741 #define SLE_DELETE              0x00000001
   1742 #define SLE_WAB_QUERY_STARTED   0x00000002
   1743 
   1744 typedef struct SearchListElem
   1745 	{
   1746 	struct SearchListElem *next;
   1747 	domainname domain;
   1748 	int flag;
   1749 	mDNSInterfaceID InterfaceID;
   1750 	DNSQuestion BrowseQ;
   1751 	DNSQuestion DefBrowseQ;
   1752 	DNSQuestion AutomaticBrowseQ;
   1753 	DNSQuestion RegisterQ;
   1754 	DNSQuestion DefRegisterQ;
   1755 	int	numCfAnswers;
   1756 	ARListElem *AuthRecs;
   1757 	} SearchListElem;
   1758 
   1759 // For domain enumeration and automatic browsing
   1760 // This is the user's DNS search list.
   1761 // In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
   1762 // to discover recommended domains for domain enumeration (browse, default browse, registration,
   1763 // default registration) and possibly one or more recommended automatic browsing domains.
   1764 extern SearchListElem *SearchList;		// This really ought to be part of mDNS_struct -- SC
   1765 
   1766 // ***************************************************************************
   1767 #if 0
   1768 #pragma mark -
   1769 #pragma mark - Main mDNS object, used to hold all the mDNS state
   1770 #endif
   1771 
   1772 typedef void mDNSCallback(mDNS *const m, mStatus result);
   1773 
   1774 #define CACHE_HASH_SLOTS 499
   1775 
   1776 enum		// Bit flags -- i.e. values should be 1, 2, 4, 8, etc.
   1777 	{
   1778 	mDNS_KnownBug_LimitedIPv6       = 1,
   1779 	mDNS_KnownBug_LossySyslog       = 2		// <rdar://problem/6561888>
   1780 	};
   1781 
   1782 enum
   1783 	{
   1784 	SleepState_Awake = 0,
   1785 	SleepState_Transferring = 1,
   1786 	SleepState_Sleeping = 2
   1787 	};
   1788 
   1789 struct mDNS_struct
   1790 	{
   1791 	// Internal state fields. These hold the main internal state of mDNSCore;
   1792 	// the client layer needn't be concerned with them.
   1793 	// No fields need to be set up by the client prior to calling mDNS_Init();
   1794 	// all required data is passed as parameters to that function.
   1795 
   1796 	mDNS_PlatformSupport *p;			// Pointer to platform-specific data of indeterminite size
   1797 	mDNSu32  KnownBugs;
   1798 	mDNSBool CanReceiveUnicastOn5353;
   1799 	mDNSBool AdvertiseLocalAddresses;
   1800 	mDNSBool DivertMulticastAdvertisements; // from interfaces that do not advertise local addresses to local-only
   1801 	mStatus mDNSPlatformStatus;
   1802 	mDNSIPPort UnicastPort4;
   1803 	mDNSIPPort UnicastPort6;
   1804 	mDNSEthAddr PrimaryMAC;				// Used as unique host ID
   1805 	mDNSCallback *MainCallback;
   1806 	void         *MainContext;
   1807 
   1808 	// For debugging: To catch and report locking failures
   1809 	mDNSu32 mDNS_busy;					// Incremented between mDNS_Lock/mDNS_Unlock section
   1810 	mDNSu32 mDNS_reentrancy;			// Incremented when calling a client callback
   1811 	mDNSu8  lock_rrcache;				// For debugging: Set at times when these lists may not be modified
   1812 	mDNSu8  lock_Questions;
   1813 	mDNSu8  lock_Records;
   1814 #ifndef MaxMsg
   1815 	#define MaxMsg 160
   1816 #endif
   1817 	char MsgBuffer[MaxMsg];				// Temp storage used while building error log messages
   1818 
   1819 	// Task Scheduling variables
   1820 	mDNSs32  timenow_adjust;			// Correction applied if we ever discover time went backwards
   1821 	mDNSs32  timenow;					// The time that this particular activation of the mDNS code started
   1822 	mDNSs32  timenow_last;				// The time the last time we ran
   1823 	mDNSs32  NextScheduledEvent;		// Derived from values below
   1824 	mDNSs32  ShutdownTime;				// Set when we're shutting down; allows us to skip some unnecessary steps
   1825 	mDNSs32  SuppressSending;			// Don't send local-link mDNS packets during this time
   1826 	mDNSs32  NextCacheCheck;			// Next time to refresh cache record before it expires
   1827 	mDNSs32  NextScheduledQuery;		// Next time to send query in its exponential backoff sequence
   1828 	mDNSs32  NextScheduledProbe;		// Next time to probe for new authoritative record
   1829 	mDNSs32  NextScheduledResponse;		// Next time to send authoritative record(s) in responses
   1830 	mDNSs32  NextScheduledNATOp;		// Next time to send NAT-traversal packets
   1831 	mDNSs32  NextScheduledSPS;			// Next time to purge expiring Sleep Proxy records
   1832 	mDNSs32  RandomQueryDelay;			// For de-synchronization of query packets on the wire
   1833 	mDNSu32  RandomReconfirmDelay;		// For de-synchronization of reconfirmation queries on the wire
   1834 	mDNSs32  PktNum;					// Unique sequence number assigned to each received packet
   1835 	mDNSu8   LocalRemoveEvents;			// Set if we may need to deliver remove events for local-only questions and/or local-only records
   1836 	mDNSu8   SleepState;				// Set if we're sleeping
   1837 	mDNSu8   SleepSeqNum;				// "Epoch number" of our current period of wakefulness
   1838 	mDNSu8   SystemWakeOnLANEnabled;	// Set if we want to register with a Sleep Proxy before going to sleep
   1839 	mDNSu8   SentSleepProxyRegistration;// Set if we registered (or tried to register) with a Sleep Proxy
   1840 	mDNSu8   SystemSleepOnlyIfWakeOnLAN;// Set if we may only sleep if we managed to register with a Sleep Proxy
   1841 	mDNSs32  AnnounceOwner;				// After waking from sleep, include OWNER option in packets until this time
   1842 	mDNSs32  DelaySleep;				// To inhibit re-sleeping too quickly right after wake
   1843 	mDNSs32  SleepLimit;				// Time window to allow deregistrations, etc.,
   1844 										// during which underying platform layer should inhibit system sleep
   1845 	mDNSs32  NextScheduledSPRetry;		// Time next sleep proxy registration action is required.
   1846 										// Only valid if SleepLimit is nonzero and DelaySleep is zero.
   1847 
   1848 	mDNSs32 NextScheduledStopTime;      // Next time to stop a question
   1849 
   1850 	// These fields only required for mDNS Searcher...
   1851 	DNSQuestion *Questions;				// List of all registered questions, active and inactive
   1852 	DNSQuestion *NewQuestions;			// Fresh questions not yet answered from cache
   1853 	DNSQuestion *CurrentQuestion;		// Next question about to be examined in AnswerLocalQuestions()
   1854 	DNSQuestion *LocalOnlyQuestions;	// Questions with InterfaceID set to mDNSInterface_LocalOnly or mDNSInterface_P2P
   1855 	DNSQuestion *NewLocalOnlyQuestions;	// Fresh local-only or P2P questions not yet answered
   1856 	DNSQuestion *RestartQuestion;		// Questions that are being restarted (stop followed by start)
   1857 	mDNSu32 rrcache_size;				// Total number of available cache entries
   1858 	mDNSu32 rrcache_totalused;			// Number of cache entries currently occupied
   1859 	mDNSu32 rrcache_active;				// Number of cache entries currently occupied by records that answer active questions
   1860 	mDNSu32 rrcache_report;
   1861 	CacheEntity *rrcache_free;
   1862 	CacheGroup *rrcache_hash[CACHE_HASH_SLOTS];
   1863 	mDNSs32  rrcache_nextcheck[CACHE_HASH_SLOTS];
   1864 
   1865 	AuthHash rrauth;
   1866 
   1867 	// Fields below only required for mDNS Responder...
   1868 	domainlabel nicelabel;				// Rich text label encoded using canonically precomposed UTF-8
   1869 	domainlabel hostlabel;				// Conforms to RFC 1034 "letter-digit-hyphen" ARPANET host name rules
   1870 	domainname  MulticastHostname;		// Fully Qualified "dot-local" Host Name, e.g. "Foo.local."
   1871 	UTF8str255  HIHardware;
   1872 	UTF8str255  HISoftware;
   1873 	AuthRecord  DeviceInfo;
   1874 	AuthRecord *ResourceRecords;
   1875 	AuthRecord *DuplicateRecords;		// Records currently 'on hold' because they are duplicates of existing records
   1876 	AuthRecord *NewLocalRecords;		// Fresh AuthRecords (public) not yet delivered to our local-only questions
   1877 	AuthRecord *CurrentRecord;			// Next AuthRecord about to be examined
   1878 	mDNSBool    NewLocalOnlyRecords;	// Fresh AuthRecords (local only) not yet delivered to our local questions
   1879 	NetworkInterfaceInfo *HostInterfaces;
   1880 	mDNSs32 ProbeFailTime;
   1881 	mDNSu32 NumFailedProbes;
   1882 	mDNSs32 SuppressProbes;
   1883 
   1884 	// Unicast-specific data
   1885 	mDNSs32           NextuDNSEvent;		// uDNS next event
   1886 	mDNSs32           NextSRVUpdate;        // Time to perform delayed update
   1887 
   1888 	DNSServer        *DNSServers;           // list of DNS servers
   1889 	McastResolver    *McastResolvers;       // list of Mcast Resolvers
   1890 
   1891 	mDNSAddr          Router;
   1892 	mDNSAddr          AdvertisedV4;         // IPv4 address pointed to by hostname
   1893 	mDNSAddr          AdvertisedV6;         // IPv6 address pointed to by hostname
   1894 
   1895 	DomainAuthInfo   *AuthInfoList;         // list of domains requiring authentication for updates
   1896 
   1897 	DNSQuestion       ReverseMap;           // Reverse-map query to find static hostname for service target
   1898 	DNSQuestion       AutomaticBrowseDomainQ;
   1899 	domainname        StaticHostname;       // Current answer to reverse-map query
   1900 	domainname        FQDN;
   1901 	HostnameInfo     *Hostnames;            // List of registered hostnames + hostname metadata
   1902 	mDNSv6Addr        AutoTunnelHostAddr;	// IPv6 address advertised for AutoTunnel services on this machine
   1903 	mDNSBool          AutoTunnelHostAddrActive;
   1904 	// AutoTunnel Relay address has two distinct uses
   1905 	// AutoTunnelRelayAddrIn: If non-zero, it means that this host can be reached (inbound connection) through the relay
   1906 	// AutoTunnelRelayAddrOut: If non-zero, it means that this host can use the relay to reach (outbound connection) the
   1907 	// other hosts through the relay
   1908 	mDNSv6Addr        AutoTunnelRelayAddrIn;
   1909 	mDNSv6Addr        AutoTunnelRelayAddrOut;
   1910 	domainlabel       AutoTunnelLabel;		// Used to construct hostname for *IPv4* address of tunnel endpoints
   1911 
   1912 	mDNSBool          StartWABQueries;		// Start WAB queries for the purpose of domain enumeration
   1913 	mDNSBool          RegisterAutoTunnel6;
   1914 
   1915 	// NAT-Traversal fields
   1916 	NATTraversalInfo  LLQNAT;					// Single shared NAT Traversal to receive inbound LLQ notifications
   1917 	NATTraversalInfo *NATTraversals;
   1918 	NATTraversalInfo *CurrentNATTraversal;
   1919 	mDNSs32           retryIntervalGetAddr;		// delta between time sent and retry
   1920 	mDNSs32           retryGetAddr;				// absolute time when we retry
   1921 	mDNSv4Addr        ExternalAddress;
   1922 
   1923 	UDPSocket        *NATMcastRecvskt;			// For receiving NAT-PMP AddrReply multicasts from router on port 5350
   1924 	mDNSu32           LastNATupseconds;			// NAT engine uptime in seconds, from most recent NAT packet
   1925 	mDNSs32           LastNATReplyLocalTime;	// Local time in ticks when most recent NAT packet was received
   1926 	mDNSu16           LastNATMapResultCode;		// Most recent error code for mappings
   1927 
   1928 	tcpLNTInfo        tcpAddrInfo;				// legacy NAT traversal TCP connection info for external address
   1929 	tcpLNTInfo        tcpDeviceInfo;			// legacy NAT traversal TCP connection info for device info
   1930 	tcpLNTInfo       *tcpInfoUnmapList;			// list of pending unmap requests
   1931 	mDNSInterfaceID   UPnPInterfaceID;
   1932 	UDPSocket        *SSDPSocket;               // For SSDP request/response
   1933 	mDNSBool          SSDPWANPPPConnection;     // whether we should send the SSDP query for WANIPConnection or WANPPPConnection
   1934 	mDNSIPPort        UPnPRouterPort;			// port we send discovery messages to
   1935 	mDNSIPPort        UPnPSOAPPort;				// port we send SOAP messages to
   1936 	mDNSu8           *UPnPRouterURL;			// router's URL string
   1937 	mDNSBool          UPnPWANPPPConnection;     // whether we're using WANIPConnection or WANPPPConnection
   1938 	mDNSu8           *UPnPSOAPURL;				// router's SOAP control URL string
   1939 	mDNSu8           *UPnPRouterAddressString;	// holds both the router's address and port
   1940 	mDNSu8           *UPnPSOAPAddressString;	// holds both address and port for SOAP messages
   1941 
   1942 	// Sleep Proxy Server fields
   1943 	mDNSu8            SPSType;					// 0 = off, 10-99 encodes desirability metric
   1944 	mDNSu8            SPSPortability;			// 10-99
   1945 	mDNSu8            SPSMarginalPower;			// 10-99
   1946 	mDNSu8            SPSTotalPower;			// 10-99
   1947 	mDNSu8            SPSState;					// 0 = off, 1 = running, 2 = shutting down, 3 = suspended during sleep
   1948 	mDNSInterfaceID   SPSProxyListChanged;
   1949 	UDPSocket        *SPSSocket;
   1950 	ServiceRecordSet  SPSRecords;
   1951 	mDNSQuestionCallback *SPSBrowseCallback;    // So the platform layer can do something useful with SPS browse results
   1952 	int               ProxyRecords;				// Total number of records we're holding as proxy
   1953 	#define           MAX_PROXY_RECORDS 10000	/* DOS protection: 400 machines at 25 records each */
   1954 
   1955 #if APPLE_OSX_mDNSResponder
   1956 	ClientTunnel     *TunnelClients;
   1957 	uuid_t           asl_uuid;					// uuid for ASL logging
   1958 	void		    *WCF;
   1959 #endif
   1960 
   1961 	// Fixed storage, to avoid creating large objects on the stack
   1962 	// The imsg is declared as a union with a pointer type to enforce CPU-appropriate alignment
   1963 	union { DNSMessage m; void *p; } imsg;  // Incoming message received from wire
   1964 	DNSMessage        omsg;                 // Outgoing message we're building
   1965 	LargeCacheRecord  rec;                  // Resource Record extracted from received message
   1966 	};
   1967 
   1968 #define FORALL_CACHERECORDS(SLOT,CG,CR)                           \
   1969 	for ((SLOT) = 0; (SLOT) < CACHE_HASH_SLOTS; (SLOT)++)         \
   1970 		for ((CG)=m->rrcache_hash[(SLOT)]; (CG); (CG)=(CG)->next) \
   1971 			for ((CR) = (CG)->members; (CR); (CR)=(CR)->next)
   1972 
   1973 // ***************************************************************************
   1974 #if 0
   1975 #pragma mark -
   1976 #pragma mark - Useful Static Constants
   1977 #endif
   1978 
   1979 extern const mDNSInterfaceID mDNSInterface_Any;				// Zero
   1980 extern const mDNSInterfaceID mDNSInterface_LocalOnly;		// Special value
   1981 extern const mDNSInterfaceID mDNSInterface_Unicast;			// Special value
   1982 extern const mDNSInterfaceID mDNSInterfaceMark;				// Special value
   1983 extern const mDNSInterfaceID mDNSInterface_P2P;				// Special value
   1984 
   1985 extern const mDNSIPPort   DiscardPort;
   1986 extern const mDNSIPPort   SSHPort;
   1987 extern const mDNSIPPort   UnicastDNSPort;
   1988 extern const mDNSIPPort   SSDPPort;
   1989 extern const mDNSIPPort   IPSECPort;
   1990 extern const mDNSIPPort   NSIPCPort;
   1991 extern const mDNSIPPort   NATPMPAnnouncementPort;
   1992 extern const mDNSIPPort   NATPMPPort;
   1993 extern const mDNSIPPort   DNSEXTPort;
   1994 extern const mDNSIPPort   MulticastDNSPort;
   1995 extern const mDNSIPPort   LoopbackIPCPort;
   1996 extern const mDNSIPPort   PrivateDNSPort;
   1997 
   1998 extern const OwnerOptData    zeroOwner;
   1999 
   2000 extern const mDNSIPPort      zeroIPPort;
   2001 extern const mDNSv4Addr      zerov4Addr;
   2002 extern const mDNSv6Addr      zerov6Addr;
   2003 extern const mDNSEthAddr     zeroEthAddr;
   2004 extern const mDNSv4Addr      onesIPv4Addr;
   2005 extern const mDNSv6Addr      onesIPv6Addr;
   2006 extern const mDNSEthAddr     onesEthAddr;
   2007 extern const mDNSAddr        zeroAddr;
   2008 
   2009 extern const mDNSv4Addr   AllDNSAdminGroup;
   2010 extern const mDNSv4Addr   AllHosts_v4;
   2011 extern const mDNSv6Addr   AllHosts_v6;
   2012 extern const mDNSv6Addr   NDP_prefix;
   2013 extern const mDNSEthAddr  AllHosts_v6_Eth;
   2014 extern const mDNSAddr     AllDNSLinkGroup_v4;
   2015 extern const mDNSAddr     AllDNSLinkGroup_v6;
   2016 
   2017 extern const mDNSOpaque16 zeroID;
   2018 extern const mDNSOpaque16 onesID;
   2019 extern const mDNSOpaque16 QueryFlags;
   2020 extern const mDNSOpaque16 uQueryFlags;
   2021 extern const mDNSOpaque16 ResponseFlags;
   2022 extern const mDNSOpaque16 UpdateReqFlags;
   2023 extern const mDNSOpaque16 UpdateRespFlags;
   2024 
   2025 extern const mDNSOpaque64 zeroOpaque64;
   2026 
   2027 extern mDNSBool StrictUnicastOrdering;
   2028 extern mDNSu8 NumUnicastDNSServers;
   2029 
   2030 #define localdomain           (*(const domainname *)"\x5" "local")
   2031 #define DeviceInfoName        (*(const domainname *)"\xC" "_device-info" "\x4" "_tcp")
   2032 #define SleepProxyServiceType (*(const domainname *)"\xC" "_sleep-proxy" "\x4" "_udp")
   2033 
   2034 // ***************************************************************************
   2035 #if 0
   2036 #pragma mark -
   2037 #pragma mark - Inline functions
   2038 #endif
   2039 
   2040 #if (defined(_MSC_VER))
   2041 	#define mDNSinline static __inline
   2042 #elif ((__GNUC__ > 2) || ((__GNUC__ == 2) && (__GNUC_MINOR__ >= 9)))
   2043 	#define mDNSinline static inline
   2044 #endif
   2045 
   2046 // If we're not doing inline functions, then this header needs to have the extern declarations
   2047 #if !defined(mDNSinline)
   2048 extern mDNSs32      NonZeroTime(mDNSs32 t);
   2049 extern mDNSu16      mDNSVal16(mDNSOpaque16 x);
   2050 extern mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v);
   2051 #endif
   2052 
   2053 // If we're compiling the particular C file that instantiates our inlines, then we
   2054 // define "mDNSinline" (to empty string) so that we generate code in the following section
   2055 #if (!defined(mDNSinline) && mDNS_InstantiateInlines)
   2056 #define mDNSinline
   2057 #endif
   2058 
   2059 #ifdef mDNSinline
   2060 
   2061 mDNSinline mDNSs32 NonZeroTime(mDNSs32 t) { if (t) return(t); else return(1); }
   2062 
   2063 mDNSinline mDNSu16 mDNSVal16(mDNSOpaque16 x) { return((mDNSu16)((mDNSu16)x.b[0] <<  8 | (mDNSu16)x.b[1])); }
   2064 
   2065 mDNSinline mDNSOpaque16 mDNSOpaque16fromIntVal(mDNSu16 v)
   2066 	{
   2067 	mDNSOpaque16 x;
   2068 	x.b[0] = (mDNSu8)(v >> 8);
   2069 	x.b[1] = (mDNSu8)(v & 0xFF);
   2070 	return(x);
   2071 	}
   2072 
   2073 #endif
   2074 
   2075 // ***************************************************************************
   2076 #if 0
   2077 #pragma mark -
   2078 #pragma mark - Main Client Functions
   2079 #endif
   2080 
   2081 // Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
   2082 //
   2083 // Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
   2084 // Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
   2085 // need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
   2086 // The rrcachestorage parameter is the address of memory for the resource record cache, and
   2087 // the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
   2088 // (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
   2089 // OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
   2090 // mStatus_GrowCache message if it needs more.
   2091 //
   2092 // Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
   2093 // create the correct address records for all the hosts interfaces. If you plan to advertise
   2094 // services being offered by the local machine, this is almost always what you want.
   2095 // There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
   2096 // 1. A client-only device, that browses for services but doesn't advertise any of its own.
   2097 // 2. A proxy-registration service, that advertises services being offered by other machines, and takes
   2098 //    the appropriate steps to manually create the correct address records for those other machines.
   2099 // In principle, a proxy-like registration service could manually create address records for its own machine too,
   2100 // but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
   2101 //
   2102 // Note that a client-only device that wishes to prohibit multicast advertisements (e.g. from
   2103 // higher-layer API calls) must also set DivertMulticastAdvertisements in the mDNS structure and
   2104 // advertise local address(es) on a loopback interface.
   2105 //
   2106 // When mDNS has finished setting up the client's callback is called
   2107 // A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
   2108 //
   2109 // Call mDNS_StartExit to tidy up before exiting
   2110 // Because exiting may be an asynchronous process (e.g. if unicast records need to be deregistered)
   2111 // client layer may choose to wait until mDNS_ExitNow() returns true before calling mDNS_FinalExit().
   2112 //
   2113 // Call mDNS_Register with a completed AuthRecord object to register a resource record
   2114 // If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
   2115 // the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
   2116 // the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
   2117 // Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
   2118 // the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
   2119 //
   2120 // Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
   2121 // is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
   2122 // Call mDNS_StopQuery when no more answers are required
   2123 //
   2124 // Care should be taken on multi-threaded or interrupt-driven environments.
   2125 // The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
   2126 // each platform layer needs to implement these appropriately for its respective platform.
   2127 // For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
   2128 // mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
   2129 // code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
   2130 
   2131 extern mStatus mDNS_Init      (mDNS *const m, mDNS_PlatformSupport *const p,
   2132 								CacheEntity *rrcachestorage, mDNSu32 rrcachesize,
   2133 								mDNSBool AdvertiseLocalAddresses,
   2134 								mDNSCallback *Callback, void *Context);
   2135 // See notes above on use of NoCache/ZeroCacheSize
   2136 #define mDNS_Init_NoCache                     mDNSNULL
   2137 #define mDNS_Init_ZeroCacheSize               0
   2138 // See notes above on use of Advertise/DontAdvertiseLocalAddresses
   2139 #define mDNS_Init_AdvertiseLocalAddresses     mDNStrue
   2140 #define mDNS_Init_DontAdvertiseLocalAddresses mDNSfalse
   2141 #define mDNS_Init_NoInitCallback              mDNSNULL
   2142 #define mDNS_Init_NoInitCallbackContext       mDNSNULL
   2143 
   2144 extern void    mDNS_ConfigChanged(mDNS *const m);
   2145 extern void    mDNS_GrowCache (mDNS *const m, CacheEntity *storage, mDNSu32 numrecords);
   2146 extern void    mDNS_GrowAuth (mDNS *const m, AuthEntity *storage, mDNSu32 numrecords);
   2147 extern void    mDNS_StartExit (mDNS *const m);
   2148 extern void    mDNS_FinalExit (mDNS *const m);
   2149 #define mDNS_Close(m) do { mDNS_StartExit(m); mDNS_FinalExit(m); } while(0)
   2150 #define mDNS_ExitNow(m, now) ((now) - (m)->ShutdownTime >= 0 || (!(m)->ResourceRecords))
   2151 
   2152 extern mDNSs32 mDNS_Execute   (mDNS *const m);
   2153 
   2154 extern mStatus mDNS_Register  (mDNS *const m, AuthRecord *const rr);
   2155 extern mStatus mDNS_Update    (mDNS *const m, AuthRecord *const rr, mDNSu32 newttl,
   2156 								const mDNSu16 newrdlength, RData *const newrdata, mDNSRecordUpdateCallback *Callback);
   2157 extern mStatus mDNS_Deregister(mDNS *const m, AuthRecord *const rr);
   2158 
   2159 extern mStatus mDNS_StartQuery(mDNS *const m, DNSQuestion *const question);
   2160 extern mStatus mDNS_StopQuery (mDNS *const m, DNSQuestion *const question);
   2161 extern mStatus mDNS_StopQueryWithRemoves(mDNS *const m, DNSQuestion *const question);
   2162 extern mStatus mDNS_Reconfirm (mDNS *const m, CacheRecord *const cacherr);
   2163 extern mStatus mDNS_ReconfirmByValue(mDNS *const m, ResourceRecord *const rr);
   2164 extern void    mDNS_PurgeCacheResourceRecord(mDNS *const m, CacheRecord *rr);
   2165 extern mDNSs32 mDNS_TimeNow(const mDNS *const m);
   2166 
   2167 extern mStatus mDNS_StartNATOperation(mDNS *const m, NATTraversalInfo *traversal);
   2168 extern mStatus mDNS_StopNATOperation(mDNS *const m, NATTraversalInfo *traversal);
   2169 extern mStatus mDNS_StopNATOperation_internal(mDNS *m, NATTraversalInfo *traversal);
   2170 
   2171 extern DomainAuthInfo *GetAuthInfoForName(mDNS *m, const domainname *const name);
   2172 
   2173 extern void    mDNS_UpdateAllowSleep(mDNS *const m);
   2174 
   2175 // ***************************************************************************
   2176 #if 0
   2177 #pragma mark -
   2178 #pragma mark - Platform support functions that are accessible to the client layer too
   2179 #endif
   2180 
   2181 extern mDNSs32  mDNSPlatformOneSecond;
   2182 
   2183 // ***************************************************************************
   2184 #if 0
   2185 #pragma mark -
   2186 #pragma mark - General utility and helper functions
   2187 #endif
   2188 
   2189 // mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
   2190 // mDNS_Dereg_rapid is used to send one goodbye instead of three, when we want the memory available for reuse sooner
   2191 // mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
   2192 // mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
   2193 typedef enum { mDNS_Dereg_normal, mDNS_Dereg_rapid, mDNS_Dereg_conflict, mDNS_Dereg_repeat } mDNS_Dereg_type;
   2194 
   2195 // mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
   2196 //
   2197 // mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
   2198 // to find the IP address, port number, and demultiplexing information for a given named service.
   2199 // As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
   2200 // found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
   2201 // The client can also call mDNS_StopResolveService at any time to abort the transaction.
   2202 //
   2203 // mDNS_AddRecordToService adds an additional record to a Service Record Set.  This record may be deregistered
   2204 // via mDNS_RemoveRecordFromService, or by deregistering the service.  mDNS_RemoveRecordFromService is passed a
   2205 // callback to free the memory associated with the extra RR when it is safe to do so.  The ExtraResourceRecord
   2206 // object can be found in the record's context pointer.
   2207 
   2208 // mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
   2209 // are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
   2210 // After getting the list of domains to browse, call mDNS_StopQuery to end the search.
   2211 // mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
   2212 //
   2213 // mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
   2214 // of one or more domains that should be offered to the user as choices for where they may register their service,
   2215 // and the default domain in which to register in the case where the user has made no selection.
   2216 
   2217 extern void    mDNS_SetupResourceRecord(AuthRecord *rr, RData *RDataStorage, mDNSInterfaceID InterfaceID,
   2218                mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, AuthRecType artype, mDNSRecordCallback Callback, void *Context);
   2219 
   2220 // mDNS_RegisterService() flags parameter bit definitions
   2221 enum
   2222 	{
   2223 		regFlagIncludeP2P	= 0x1,	// include P2P interfaces when using mDNSInterface_Any
   2224 		regFlagKnownUnique	= 0x2	// client guarantees that SRV and TXT record names are unique
   2225 	};
   2226 
   2227 extern mStatus mDNS_RegisterService  (mDNS *const m, ServiceRecordSet *sr,
   2228                const domainlabel *const name, const domainname *const type, const domainname *const domain,
   2229                const domainname *const host, mDNSIPPort port, const mDNSu8 txtinfo[], mDNSu16 txtlen,
   2230                AuthRecord *SubTypes, mDNSu32 NumSubTypes,
   2231                mDNSInterfaceID InterfaceID, mDNSServiceCallback Callback, void *Context, mDNSu32 flags);
   2232 extern mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl,  mDNSu32 includeP2P);
   2233 extern mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, mDNSRecordCallback MemFreeCallback, void *Context);
   2234 extern mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname);
   2235 extern mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt);
   2236 #define mDNS_DeregisterService(M,S) mDNS_DeregisterService_drt((M), (S), mDNS_Dereg_normal)
   2237 
   2238 extern mStatus mDNS_RegisterNoSuchService(mDNS *const m, AuthRecord *const rr,
   2239                const domainlabel *const name, const domainname *const type, const domainname *const domain,
   2240                const domainname *const host,
   2241                const mDNSInterfaceID InterfaceID, mDNSRecordCallback Callback, void *Context, mDNSBool includeP2P);
   2242 #define        mDNS_DeregisterNoSuchService mDNS_Deregister
   2243 
   2244 extern void mDNS_SetupQuestion(DNSQuestion *const q, const mDNSInterfaceID InterfaceID, const domainname *const name,
   2245                const mDNSu16 qtype, mDNSQuestionCallback *const callback, void *const context);
   2246 
   2247 extern mStatus mDNS_StartBrowse(mDNS *const m, DNSQuestion *const question,
   2248                const domainname *const srv, const domainname *const domain,
   2249                const mDNSInterfaceID InterfaceID, mDNSBool ForceMCast, mDNSQuestionCallback *Callback, void *Context);
   2250 #define        mDNS_StopBrowse mDNS_StopQuery
   2251 
   2252 extern mStatus mDNS_StartResolveService(mDNS *const m, ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context);
   2253 extern void    mDNS_StopResolveService (mDNS *const m, ServiceInfoQuery *query);
   2254 
   2255 typedef enum
   2256 	{
   2257 	mDNS_DomainTypeBrowse              = 0,
   2258 	mDNS_DomainTypeBrowseDefault       = 1,
   2259 	mDNS_DomainTypeBrowseAutomatic     = 2,
   2260 	mDNS_DomainTypeRegistration        = 3,
   2261 	mDNS_DomainTypeRegistrationDefault = 4,
   2262 
   2263 	mDNS_DomainTypeMax = 4
   2264 	} mDNS_DomainType;
   2265 
   2266 extern const char *const mDNS_DomainTypeNames[];
   2267 
   2268 extern mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
   2269 								const mDNSInterfaceID InterfaceID, mDNSQuestionCallback *Callback, void *Context);
   2270 #define        mDNS_StopGetDomains mDNS_StopQuery
   2271 extern mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname);
   2272 #define        mDNS_StopAdvertiseDomains mDNS_Deregister
   2273 
   2274 extern mDNSOpaque16 mDNS_NewMessageID(mDNS *const m);
   2275 extern mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr);
   2276 
   2277 extern DNSServer *GetServerForName(mDNS *m, const domainname *name, mDNSInterfaceID InterfaceID);
   2278 extern DNSServer *GetServerForQuestion(mDNS *m, DNSQuestion *question);
   2279 extern mDNSu32 SetValidDNSServers(mDNS *m, DNSQuestion *question);
   2280 
   2281 // ***************************************************************************
   2282 #if 0
   2283 #pragma mark -
   2284 #pragma mark - DNS name utility functions
   2285 #endif
   2286 
   2287 // In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
   2288 // in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
   2289 // work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
   2290 // are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
   2291 
   2292 // Assignment
   2293 // A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
   2294 // because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
   2295 // This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
   2296 #define AssignDomainName(DST, SRC) do { mDNSu16 len__ = DomainNameLength((SRC)); \
   2297 	if (len__ <= MAX_DOMAIN_NAME) mDNSPlatformMemCopy((DST)->c, (SRC)->c, len__); else (DST)->c[0] = 0; } while(0)
   2298 
   2299 // Comparison functions
   2300 #define SameDomainLabelCS(A,B) ((A)[0] == (B)[0] && mDNSPlatformMemSame((A)+1, (B)+1, (A)[0]))
   2301 extern mDNSBool SameDomainLabel(const mDNSu8 *a, const mDNSu8 *b);
   2302 extern mDNSBool SameDomainName(const domainname *const d1, const domainname *const d2);
   2303 extern mDNSBool SameDomainNameCS(const domainname *const d1, const domainname *const d2);
   2304 typedef mDNSBool DomainNameComparisonFn(const domainname *const d1, const domainname *const d2);
   2305 extern mDNSBool IsLocalDomain(const domainname *d);     // returns true for domains that by default should be looked up using link-local multicast
   2306 
   2307 #define StripFirstLabel(X) ((const domainname *)&(X)->c[(X)->c[0] ? 1 + (X)->c[0] : 0])
   2308 
   2309 #define FirstLabel(X)  ((const domainlabel *)(X))
   2310 #define SecondLabel(X) ((const domainlabel *)StripFirstLabel(X))
   2311 #define ThirdLabel(X)  ((const domainlabel *)StripFirstLabel(StripFirstLabel(X)))
   2312 
   2313 extern const mDNSu8 *LastLabel(const domainname *d);
   2314 
   2315 // Get total length of domain name, in native DNS format, including terminal root label
   2316 //   (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
   2317 extern mDNSu16  DomainNameLengthLimit(const domainname *const name, const mDNSu8 *limit);
   2318 #define DomainNameLength(name) DomainNameLengthLimit((name), (name)->c + MAX_DOMAIN_NAME)
   2319 
   2320 // Append functions to append one or more labels to an existing native format domain name:
   2321 //   AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
   2322 //   AppendDNSNameString      adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
   2323 //   AppendDomainLabel        adds a single label from a native format domainlabel
   2324 //   AppendDomainName         adds zero or more labels from a native format domainname
   2325 extern mDNSu8  *AppendLiteralLabelString(domainname *const name, const char *cstr);
   2326 extern mDNSu8  *AppendDNSNameString     (domainname *const name, const char *cstr);
   2327 extern mDNSu8  *AppendDomainLabel       (domainname *const name, const domainlabel *const label);
   2328 extern mDNSu8  *AppendDomainName        (domainname *const name, const domainname *const append);
   2329 
   2330 // Convert from null-terminated string to native DNS format:
   2331 //   The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
   2332 //   The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
   2333 //     dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
   2334 //     backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
   2335 extern mDNSBool MakeDomainLabelFromLiteralString(domainlabel *const label, const char *cstr);
   2336 extern mDNSu8  *MakeDomainNameFromDNSNameString (domainname  *const name,  const char *cstr);
   2337 
   2338 // Convert native format domainlabel or domainname back to C string format
   2339 // IMPORTANT:
   2340 // When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
   2341 // to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
   2342 // where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
   2343 // Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1009) bytes long.
   2344 // See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
   2345 extern char    *ConvertDomainLabelToCString_withescape(const domainlabel *const name, char *cstr, char esc);
   2346 #define         ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
   2347 #define         ConvertDomainLabelToCString(D,C)           ConvertDomainLabelToCString_withescape((D), (C), '\\')
   2348 extern char    *ConvertDomainNameToCString_withescape(const domainname *const name, char *cstr, char esc);
   2349 #define         ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
   2350 #define         ConvertDomainNameToCString(D,C)           ConvertDomainNameToCString_withescape((D), (C), '\\')
   2351 
   2352 extern void     ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel);
   2353 
   2354 extern mDNSu8  *ConstructServiceName(domainname *const fqdn, const domainlabel *name, const domainname *type, const domainname *const domain);
   2355 extern mDNSBool DeconstructServiceName(const domainname *const fqdn, domainlabel *const name, domainname *const type, domainname *const domain);
   2356 
   2357 // Note: Some old functions have been replaced by more sensibly-named versions.
   2358 // You can uncomment the hash-defines below if you don't want to have to change your source code right away.
   2359 // When updating your code, note that (unlike the old versions) *all* the new routines take the target object
   2360 // as their first parameter.
   2361 //#define ConvertCStringToDomainName(SRC,DST)  MakeDomainNameFromDNSNameString((DST),(SRC))
   2362 //#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
   2363 //#define AppendStringLabelToName(DST,SRC)     AppendLiteralLabelString((DST),(SRC))
   2364 //#define AppendStringNameToName(DST,SRC)      AppendDNSNameString((DST),(SRC))
   2365 //#define AppendDomainLabelToName(DST,SRC)     AppendDomainLabel((DST),(SRC))
   2366 //#define AppendDomainNameToName(DST,SRC)      AppendDomainName((DST),(SRC))
   2367 
   2368 // ***************************************************************************
   2369 #if 0
   2370 #pragma mark -
   2371 #pragma mark - Other utility functions and macros
   2372 #endif
   2373 
   2374 // mDNS_vsnprintf/snprintf return the number of characters written, excluding the final terminating null.
   2375 // The output is always null-terminated: for example, if the output turns out to be exactly buflen long,
   2376 // then the output will be truncated by one character to allow space for the terminating null.
   2377 // Unlike standard C vsnprintf/snprintf, they return the number of characters *actually* written,
   2378 // not the number of characters that *would* have been printed were buflen unlimited.
   2379 extern mDNSu32 mDNS_vsnprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, va_list arg);
   2380 extern mDNSu32 mDNS_snprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
   2381 extern mDNSu32 NumCacheRecordsForInterfaceID(const mDNS *const m, mDNSInterfaceID id);
   2382 extern char *DNSTypeName(mDNSu16 rrtype);
   2383 extern char *GetRRDisplayString_rdb(const ResourceRecord *const rr, const RDataBody *const rd1, char *const buffer);
   2384 #define RRDisplayString(m, rr) GetRRDisplayString_rdb(rr, &(rr)->rdata->u, (m)->MsgBuffer)
   2385 #define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
   2386 #define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
   2387 extern mDNSBool mDNSSameAddress(const mDNSAddr *ip1, const mDNSAddr *ip2);
   2388 extern void IncrementLabelSuffix(domainlabel *name, mDNSBool RichText);
   2389 extern mDNSBool mDNSv4AddrIsRFC1918(mDNSv4Addr *addr);  // returns true for RFC1918 private addresses
   2390 #define mDNSAddrIsRFC1918(X) ((X)->type == mDNSAddrType_IPv4 && mDNSv4AddrIsRFC1918(&(X)->ip.v4))
   2391 
   2392 #define mDNSSameIPPort(A,B)      ((A).NotAnInteger == (B).NotAnInteger)
   2393 #define mDNSSameOpaque16(A,B)    ((A).NotAnInteger == (B).NotAnInteger)
   2394 #define mDNSSameOpaque32(A,B)    ((A).NotAnInteger == (B).NotAnInteger)
   2395 #define mDNSSameOpaque64(A,B)    ((A)->l[0] == (B)->l[0] && (A)->l[1] == (B)->l[1])
   2396 
   2397 #define mDNSSameIPv4Address(A,B) ((A).NotAnInteger == (B).NotAnInteger)
   2398 #define mDNSSameIPv6Address(A,B) ((A).l[0] == (B).l[0] && (A).l[1] == (B).l[1] && (A).l[2] == (B).l[2] && (A).l[3] == (B).l[3])
   2399 #define mDNSSameEthAddress(A,B)  ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
   2400 
   2401 #define mDNSIPPortIsZero(A)      ((A).NotAnInteger                            == 0)
   2402 #define mDNSOpaque16IsZero(A)    ((A).NotAnInteger                            == 0)
   2403 #define mDNSOpaque64IsZero(A)    (((A)->l[0] | (A)->l[1]                    ) == 0)
   2404 #define mDNSIPv4AddressIsZero(A) ((A).NotAnInteger                            == 0)
   2405 #define mDNSIPv6AddressIsZero(A) (((A).l[0] | (A).l[1] | (A).l[2] | (A).l[3]) == 0)
   2406 #define mDNSEthAddressIsZero(A)  (((A).w[0] | (A).w[1] | (A).w[2]           ) == 0)
   2407 
   2408 #define mDNSIPv4AddressIsOnes(A) ((A).NotAnInteger == 0xFFFFFFFF)
   2409 #define mDNSIPv6AddressIsOnes(A) (((A).l[0] & (A).l[1] & (A).l[2] & (A).l[3]) == 0xFFFFFFFF)
   2410 
   2411 #define mDNSAddressIsAllDNSLinkGroup(X) (                                                            \
   2412 	((X)->type == mDNSAddrType_IPv4 && mDNSSameIPv4Address((X)->ip.v4, AllDNSLinkGroup_v4.ip.v4)) || \
   2413 	((X)->type == mDNSAddrType_IPv6 && mDNSSameIPv6Address((X)->ip.v6, AllDNSLinkGroup_v6.ip.v6))    )
   2414 
   2415 #define mDNSAddressIsZero(X) (                                                \
   2416 	((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsZero((X)->ip.v4))  || \
   2417 	((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsZero((X)->ip.v6))     )
   2418 
   2419 #define mDNSAddressIsValidNonZero(X) (                                        \
   2420 	((X)->type == mDNSAddrType_IPv4 && !mDNSIPv4AddressIsZero((X)->ip.v4)) || \
   2421 	((X)->type == mDNSAddrType_IPv6 && !mDNSIPv6AddressIsZero((X)->ip.v6))    )
   2422 
   2423 #define mDNSAddressIsOnes(X) (                                                \
   2424 	((X)->type == mDNSAddrType_IPv4 && mDNSIPv4AddressIsOnes((X)->ip.v4))  || \
   2425 	((X)->type == mDNSAddrType_IPv6 && mDNSIPv6AddressIsOnes((X)->ip.v6))     )
   2426 
   2427 #define mDNSAddressIsValid(X) (                                                                                             \
   2428 	((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) :          \
   2429 	((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
   2430 
   2431 #define mDNSv4AddressIsLinkLocal(X) ((X)->b[0] ==  169 &&  (X)->b[1]         ==  254)
   2432 #define mDNSv6AddressIsLinkLocal(X) ((X)->b[0] == 0xFE && ((X)->b[1] & 0xC0) == 0x80)
   2433 
   2434 #define mDNSAddressIsLinkLocal(X)  (                                                    \
   2435 	((X)->type == mDNSAddrType_IPv4) ? mDNSv4AddressIsLinkLocal(&(X)->ip.v4) :          \
   2436 	((X)->type == mDNSAddrType_IPv6) ? mDNSv6AddressIsLinkLocal(&(X)->ip.v6) : mDNSfalse)
   2437 
   2438 #define mDNSv4AddressIsLoopback(X) ((X)->b[0] == 127 && (X)->b[1] == 0 && (X)->b[2] == 0 && (X)->b[3] == 1)
   2439 #define mDNSv6AddressIsLoopback(X) ((((X)->l[0] | (X)->l[1] | (X)->l[2]) == 0) && ((X)->b[12] == 0 && (X)->b[13] == 0 && (X)->b[14] == 0 && (X)->b[15] == 1))
   2440 
   2441 // ***************************************************************************
   2442 #if 0
   2443 #pragma mark -
   2444 #pragma mark - Authentication Support
   2445 #endif
   2446 
   2447 // Unicast DNS and Dynamic Update specific Client Calls
   2448 //
   2449 // mDNS_SetSecretForDomain tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
   2450 // when dynamically updating a given zone (and its subdomains).  The key used in authentication must be in
   2451 // domain name format.  The shared secret must be a null-terminated base64 encoded string.  A minimum size of
   2452 // 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485.
   2453 // Calling this routine multiple times for a zone replaces previously entered values.  Call with a NULL key
   2454 // to disable authentication for the zone.  A non-NULL autoTunnelPrefix means this is an AutoTunnel domain,
   2455 // and the value is prepended to the IPSec identifier (used for key lookup)
   2456 
   2457 extern mStatus mDNS_SetSecretForDomain(mDNS *m, DomainAuthInfo *info,
   2458 	const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port, const char *autoTunnelPrefix);
   2459 
   2460 extern void RecreateNATMappings(mDNS *const m);
   2461 
   2462 // Hostname/Unicast Interface Configuration
   2463 
   2464 // All hostnames advertised point to one IPv4 address and/or one IPv6 address, set via SetPrimaryInterfaceInfo.  Invoking this routine
   2465 // updates all existing hostnames to point to the new address.
   2466 
   2467 // A hostname is added via AddDynDNSHostName, which points to the primary interface's v4 and/or v6 addresss
   2468 
   2469 // The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
   2470 // Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
   2471 
   2472 // Host domains added prior to specification of the primary interface address and computer name will be deferred until
   2473 // these values are initialized.
   2474 
   2475 // DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer.
   2476 // For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
   2477 // a domain may be associated with a DNS server.  For standard configurations, specify the root label (".") or NULL.
   2478 
   2479 extern void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext);
   2480 extern void mDNS_RemoveDynDNSHostName(mDNS *m, const domainname *fqdn);
   2481 extern void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr,  const mDNSAddr *v6addr, const mDNSAddr *router);
   2482 extern DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, const mDNSAddr *addr, const mDNSIPPort port, mDNSBool scoped, mDNSu32 timeout);
   2483 extern void PenalizeDNSServer(mDNS *const m, DNSQuestion *q);
   2484 extern void mDNS_AddSearchDomain(const domainname *const domain, mDNSInterfaceID InterfaceID);
   2485 
   2486 extern McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout);
   2487 
   2488 // We use ((void *)0) here instead of mDNSNULL to avoid compile warnings on gcc 4.2
   2489 #define mDNS_AddSearchDomain_CString(X, I) \
   2490 	do { domainname d__; if (((X) != (void*)0) && MakeDomainNameFromDNSNameString(&d__, (X)) && d__.c[0]) mDNS_AddSearchDomain(&d__, I); } while(0)
   2491 
   2492 // Routines called by the core, exported by DNSDigest.c
   2493 
   2494 // Convert an arbitrary base64 encoded key key into an HMAC key (stored in AuthInfo struct)
   2495 extern mDNSs32 DNSDigest_ConstructHMACKeyfromBase64(DomainAuthInfo *info, const char *b64key);
   2496 
   2497 // sign a DNS message.  The message must be complete, with all values in network byte order.  end points to the end
   2498 // of the message, and is modified by this routine.  numAdditionals is a pointer to the number of additional
   2499 // records in HOST byte order, which is incremented upon successful completion of this routine.  The function returns
   2500 // the new end pointer on success, and NULL on failure.
   2501 extern void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode);
   2502 
   2503 #define SwapDNSHeaderBytes(M) do { \
   2504     (M)->h.numQuestions   = (mDNSu16)((mDNSu8 *)&(M)->h.numQuestions  )[0] << 8 | ((mDNSu8 *)&(M)->h.numQuestions  )[1]; \
   2505     (M)->h.numAnswers     = (mDNSu16)((mDNSu8 *)&(M)->h.numAnswers    )[0] << 8 | ((mDNSu8 *)&(M)->h.numAnswers    )[1]; \
   2506     (M)->h.numAuthorities = (mDNSu16)((mDNSu8 *)&(M)->h.numAuthorities)[0] << 8 | ((mDNSu8 *)&(M)->h.numAuthorities)[1]; \
   2507     (M)->h.numAdditionals = (mDNSu16)((mDNSu8 *)&(M)->h.numAdditionals)[0] << 8 | ((mDNSu8 *)&(M)->h.numAdditionals)[1]; \
   2508     } while (0)
   2509 
   2510 #define DNSDigest_SignMessageHostByteOrder(M,E,INFO) \
   2511 	do { SwapDNSHeaderBytes(M); DNSDigest_SignMessage((M), (E), (INFO), 0); SwapDNSHeaderBytes(M); } while (0)
   2512 
   2513 // verify a DNS message.  The message must be complete, with all values in network byte order.  end points to the
   2514 // end of the record.  tsig is a pointer to the resource record that contains the TSIG OPT record.  info is
   2515 // the matching key to use for verifying the message.  This function expects that the additionals member
   2516 // of the DNS message header has already had one subtracted from it.
   2517 extern mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord *tsig, DomainAuthInfo *info, mDNSu16 *rcode, mDNSu16 *tcode);
   2518 
   2519 // ***************************************************************************
   2520 #if 0
   2521 #pragma mark -
   2522 #pragma mark - PlatformSupport interface
   2523 #endif
   2524 
   2525 // This section defines the interface to the Platform Support layer.
   2526 // Normal client code should not use any of types defined here, or directly call any of the functions defined here.
   2527 // The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
   2528 // For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
   2529 
   2530 // Every platform support module must provide the following functions.
   2531 // mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
   2532 // When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
   2533 // mDNSPlatformSendUDP() sends one UDP packet
   2534 // When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
   2535 // mDNSPlatformClose() tidies up on exit
   2536 //
   2537 // Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
   2538 // If your target platform has a well-defined specialized application, and you know that all the records it uses
   2539 // are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
   2540 // NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 68. If you need to handle records
   2541 // a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
   2542 // can raise the value of this constant to a suitable value (at the expense of increased memory usage).
   2543 //
   2544 // USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
   2545 // Generally speaking:
   2546 // Code that's protected by the main mDNS lock should just use the m->timenow value
   2547 // Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
   2548 // In certain cases there may be reasons why it's necessary to get the time without taking the lock first
   2549 // (e.g. inside the routines that are doing the locking and unlocking, where a call to get the lock would result in a
   2550 // recursive loop); in these cases use mDNS_TimeNow_NoLock(m) to get mDNSPlatformRawTime with the proper correction factor added.
   2551 //
   2552 // mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
   2553 
   2554 extern mStatus  mDNSPlatformInit        (mDNS *const m);
   2555 extern void     mDNSPlatformClose       (mDNS *const m);
   2556 extern mStatus  mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
   2557 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst, mDNSIPPort dstport);
   2558 
   2559 extern void     mDNSPlatformLock        (const mDNS *const m);
   2560 extern void     mDNSPlatformUnlock      (const mDNS *const m);
   2561 
   2562 mDNSexport void     mDNSPlatformStrCopy(      void *dst, const void *src);
   2563 mDNSexport mDNSu32  mDNSPlatformStrLCopy(     void *dst, const void *src, mDNSu32 dstlen);
   2564 mDNSexport mDNSu32  mDNSPlatformStrLen (                 const void *src);
   2565 extern void     mDNSPlatformMemCopy     (      void *dst, const void *src, mDNSu32 len);
   2566 extern mDNSBool mDNSPlatformMemSame     (const void *dst, const void *src, mDNSu32 len);
   2567 extern void     mDNSPlatformMemZero     (      void *dst,                  mDNSu32 len);
   2568 #if APPLE_OSX_mDNSResponder && MACOSX_MDNS_MALLOC_DEBUGGING
   2569 #define         mDNSPlatformMemAllocate(X) mallocL(#X, X)
   2570 #else
   2571 extern void *   mDNSPlatformMemAllocate (mDNSu32 len);
   2572 #endif
   2573 extern void     mDNSPlatformMemFree     (void *mem);
   2574 
   2575 // If the platform doesn't have a strong PRNG, we define a naive multiply-and-add based on a seed
   2576 // from the platform layer.  Long-term, we should embed an arc4 implementation, but the strength
   2577 // will still depend on the randomness of the seed.
   2578 #if !defined(_PLATFORM_HAS_STRONG_PRNG_) && (_BUILDING_XCODE_PROJECT_ || defined(_WIN32))
   2579 #define _PLATFORM_HAS_STRONG_PRNG_ 1
   2580 #endif
   2581 #if _PLATFORM_HAS_STRONG_PRNG_
   2582 extern mDNSu32  mDNSPlatformRandomNumber(void);
   2583 #else
   2584 extern mDNSu32  mDNSPlatformRandomSeed  (void);
   2585 #endif // _PLATFORM_HAS_STRONG_PRNG_
   2586 
   2587 extern mStatus  mDNSPlatformTimeInit    (void);
   2588 extern mDNSs32  mDNSPlatformRawTime     (void);
   2589 extern mDNSs32  mDNSPlatformUTC         (void);
   2590 #define mDNS_TimeNow_NoLock(m) (mDNSPlatformRawTime() + (m)->timenow_adjust)
   2591 
   2592 #if MDNS_DEBUGMSGS
   2593 extern void	mDNSPlatformWriteDebugMsg(const char *msg);
   2594 #endif
   2595 extern void	mDNSPlatformWriteLogMsg(const char *ident, const char *msg, mDNSLogLevel_t loglevel);
   2596 
   2597 #if APPLE_OSX_mDNSResponder
   2598 // Utility function for ASL logging
   2599 mDNSexport void mDNSASLLog(uuid_t *uuid, const char *subdomain, const char *result, const char *signature, const char *fmt, ...);
   2600 #endif
   2601 
   2602 // Platform support modules should provide the following functions to map between opaque interface IDs
   2603 // and interface indexes in order to support the DNS-SD API. If your target platform does not support
   2604 // multiple interfaces and/or does not support the DNS-SD API, these functions can be empty.
   2605 extern mDNSInterfaceID mDNSPlatformInterfaceIDfromInterfaceIndex(mDNS *const m, mDNSu32 ifindex);
   2606 extern mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange);
   2607 
   2608 // Every platform support module must provide the following functions if it is to support unicast DNS
   2609 // and Dynamic Update.
   2610 // All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
   2611 // mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
   2612 // main event loop.  The return value indicates whether the connection succeeded, failed, or is pending
   2613 // (i.e. the call would block.)  On return, the descriptor parameter is set to point to the connected socket.
   2614 // The TCPConnectionCallback is subsequently invoked when the connection
   2615 // completes (in which case the ConnectionEstablished parameter is true), or data is available for
   2616 // reading on the socket (indicated by the ConnectionEstablished parameter being false.)  If the connection
   2617 // asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
   2618 // returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP.  (This allows for platforms
   2619 // with limited asynchronous error detection capabilities.)  PlatformReadTCP and PlatformWriteTCP must
   2620 // return the number of bytes read/written, 0 if the call would block, and -1 if an error.  PlatformReadTCP
   2621 // should set the closed argument if the socket has been closed.
   2622 // PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
   2623 // event loop.  CloseConnectin may be called at any time, including in a ConnectionCallback.
   2624 
   2625 typedef enum
   2626 	{
   2627 	kTCPSocketFlags_Zero   = 0,
   2628 	kTCPSocketFlags_UseTLS = (1 << 0)
   2629 	} TCPSocketFlags;
   2630 
   2631 typedef void (*TCPConnectionCallback)(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err);
   2632 extern TCPSocket *mDNSPlatformTCPSocket(mDNS *const m, TCPSocketFlags flags, mDNSIPPort *port);	// creates a TCP socket
   2633 extern TCPSocket *mDNSPlatformTCPAccept(TCPSocketFlags flags, int sd);
   2634 extern int        mDNSPlatformTCPGetFD(TCPSocket *sock);
   2635 extern mStatus    mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname,
   2636 										mDNSInterfaceID InterfaceID, TCPConnectionCallback callback, void *context);
   2637 extern void       mDNSPlatformTCPCloseConnection(TCPSocket *sock);
   2638 extern long       mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool *closed);
   2639 extern long       mDNSPlatformWriteTCP(TCPSocket *sock, const char *msg, unsigned long len);
   2640 extern UDPSocket *mDNSPlatformUDPSocket(mDNS *const m, const mDNSIPPort requestedport);
   2641 extern void       mDNSPlatformUDPClose(UDPSocket *sock);
   2642 extern void       mDNSPlatformReceiveBPF_fd(mDNS *const m, int fd);
   2643 extern void       mDNSPlatformUpdateProxyList(mDNS *const m, const mDNSInterfaceID InterfaceID);
   2644 extern void       mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID);
   2645 extern void       mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID);
   2646 extern void       mDNSPlatformSourceAddrForDest(mDNSAddr *const src, const mDNSAddr *const dst);
   2647 
   2648 // mDNSPlatformTLSSetupCerts/mDNSPlatformTLSTearDownCerts used by dnsextd
   2649 extern mStatus    mDNSPlatformTLSSetupCerts(void);
   2650 extern void       mDNSPlatformTLSTearDownCerts(void);
   2651 
   2652 // Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
   2653 // in browse/registration calls must implement these routines to get the "default" browse/registration list.
   2654 
   2655 extern void       mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains, DNameListElem **BrowseDomains);
   2656 extern mStatus    mDNSPlatformGetPrimaryInterface(mDNS *const m, mDNSAddr *v4, mDNSAddr *v6, mDNSAddr *router);
   2657 extern void       mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status);
   2658 
   2659 extern void       mDNSPlatformSetAllowSleep(mDNS *const m, mDNSBool allowSleep, const char *reason);
   2660 extern void       mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration);
   2661 extern mDNSBool   mDNSPlatformValidRecordForInterface(AuthRecord *rr, const NetworkInterfaceInfo *intf);
   2662 
   2663 #ifdef _LEGACY_NAT_TRAVERSAL_
   2664 // Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
   2665 extern void     LNT_SendDiscoveryMsg(mDNS *m);
   2666 extern void     LNT_ConfigureRouterInfo(mDNS *m, const mDNSInterfaceID InterfaceID, const mDNSu8 *const data, const mDNSu16 len);
   2667 extern mStatus  LNT_GetExternalAddress(mDNS *m);
   2668 extern mStatus  LNT_MapPort(mDNS *m, NATTraversalInfo *n);
   2669 extern mStatus  LNT_UnmapPort(mDNS *m, NATTraversalInfo *n);
   2670 extern void     LNT_ClearState(mDNS *const m);
   2671 #endif // _LEGACY_NAT_TRAVERSAL_
   2672 
   2673 // The core mDNS code provides these functions, for the platform support code to call at appropriate times
   2674 //
   2675 // mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
   2676 // and then again on each subsequent change of the host name.
   2677 //
   2678 // mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
   2679 // physical and/or logical interfaces are available for sending and receiving packets.
   2680 // Typically it is called on startup for each available interface, but register/deregister may be
   2681 // called again later, on multiple occasions, to inform the core of interface configuration changes.
   2682 // If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
   2683 // resource records that should be associated with every publicised IP address/interface:
   2684 // -- Name-to-address records (A/AAAA)
   2685 // -- Address-to-name records (PTR)
   2686 // -- Host information (HINFO)
   2687 // IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
   2688 // mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
   2689 // see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
   2690 // Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
   2691 //
   2692 // mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
   2693 // available domain name servers for unicast queries/updates.  RegisterDNS() should be called once for
   2694 // each name server, typically at startup, or when a new name server becomes available.  DeregiterDNS()
   2695 // must be called whenever a registered name server becomes unavailable.  DeregisterDNSList deregisters
   2696 // all registered servers.  mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
   2697 //
   2698 // mDNSCoreInitComplete() is called when the platform support layer is finished.
   2699 // Typically this is at the end of mDNSPlatformInit(), but may be later
   2700 // (on platforms like OT that allow asynchronous initialization of the networking stack).
   2701 //
   2702 // mDNSCoreReceive() is called when a UDP packet is received
   2703 //
   2704 // mDNSCoreMachineSleep() is called when the machine sleeps or wakes
   2705 // (This refers to heavyweight laptop-style sleep/wake that disables network access,
   2706 // not lightweight second-by-second CPU power management modes.)
   2707 
   2708 extern void     mDNS_SetFQDN(mDNS *const m);
   2709 extern void     mDNS_ActivateNetWake_internal  (mDNS *const m, NetworkInterfaceInfo *set);
   2710 extern void     mDNS_DeactivateNetWake_internal(mDNS *const m, NetworkInterfaceInfo *set);
   2711 extern mStatus  mDNS_RegisterInterface  (mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping);
   2712 extern void     mDNS_DeregisterInterface(mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping);
   2713 extern void     mDNSCoreInitComplete(mDNS *const m, mStatus result);
   2714 extern void     mDNSCoreReceive(mDNS *const m, void *const msg, const mDNSu8 *const end,
   2715 								const mDNSAddr *const srcaddr, const mDNSIPPort srcport,
   2716 								const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID);
   2717 extern void		mDNSCoreRestartQueries(mDNS *const m);
   2718 typedef void    (*FlushCache)(mDNS *const m);
   2719 typedef void    (*CallbackBeforeStartQuery)(mDNS *const m, void *context);
   2720 extern void		mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
   2721 											  CallbackBeforeStartQuery beforeQueryStart, void *context);
   2722 extern mDNSBool mDNSCoreHaveAdvertisedMulticastServices(mDNS *const m);
   2723 extern void     mDNSCoreMachineSleep(mDNS *const m, mDNSBool wake);
   2724 extern mDNSBool mDNSCoreReadyForSleep(mDNS *m, mDNSs32 now);
   2725 extern mDNSs32  mDNSCoreIntervalToNextWake(mDNS *const m, mDNSs32 now);
   2726 
   2727 extern void     mDNSCoreReceiveRawPacket  (mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID);
   2728 
   2729 extern mDNSBool mDNSAddrIsDNSMulticast(const mDNSAddr *ip);
   2730 
   2731 extern CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay);
   2732 extern void ScheduleNextCacheCheckTime(mDNS *const m, const mDNSu32 slot, const mDNSs32 event);
   2733 extern void GrantCacheExtensions(mDNS *const m, DNSQuestion *q, mDNSu32 lease);
   2734 extern void MakeNegativeCacheRecord(mDNS *const m, CacheRecord *const cr,
   2735 	const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds,
   2736 	mDNSInterfaceID InterfaceID, DNSServer *dnsserver);
   2737 extern void CompleteDeregistration(mDNS *const m, AuthRecord *rr);
   2738 extern void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord);
   2739 extern char *InterfaceNameForID(mDNS *const m, const mDNSInterfaceID InterfaceID);
   2740 extern void DNSServerChangeForQuestion(mDNS *const m, DNSQuestion *q, DNSServer *newServer);
   2741 extern void ActivateUnicastRegistration(mDNS *const m, AuthRecord *const rr);
   2742 extern void CheckSuppressUnusableQuestions(mDNS *const m);
   2743 extern void RetrySearchDomainQuestions(mDNS *const m);
   2744 
   2745 // Used only in logging to restrict the number of /etc/hosts entries printed
   2746 extern void FreeEtcHosts(mDNS *const m, AuthRecord *const rr, mStatus result);
   2747 // exported for using the hash for /etc/hosts AuthRecords
   2748 extern AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name);
   2749 extern AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr);
   2750 extern AuthGroup *InsertAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr);
   2751 extern AuthGroup *RemoveAuthRecord(mDNS *const m, AuthHash *r, AuthRecord *rr);
   2752 
   2753 // For now this AutoTunnel stuff is specific to Mac OS X.
   2754 // In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
   2755 #if APPLE_OSX_mDNSResponder
   2756 extern void AutoTunnelCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord);
   2757 extern void AddNewClientTunnel(mDNS *const m, DNSQuestion *const q);
   2758 extern void SetupLocalAutoTunnelInterface_internal(mDNS *const m, mDNSBool servicesStarting);
   2759 extern void UpdateAutoTunnelDomainStatuses(const mDNS *const m);
   2760 extern mStatus ActivateLocalProxy(mDNS *const m, char *ifname);
   2761 extern void RemoveAutoTunnel6Record(mDNS *const m);
   2762 extern mDNSBool RecordReadyForSleep(mDNS *const m, AuthRecord *rr);
   2763 #endif
   2764 
   2765 // ***************************************************************************
   2766 #if 0
   2767 #pragma mark -
   2768 #pragma mark - Sleep Proxy
   2769 #endif
   2770 
   2771 // Sleep Proxy Server Property Encoding
   2772 //
   2773 // Sleep Proxy Servers are advertised using a structured service name, consisting of four
   2774 // metrics followed by a human-readable name. The metrics assist clients in deciding which
   2775 // Sleep Proxy Server(s) to use when multiple are available on the network. Each metric
   2776 // is a two-digit decimal number in the range 10-99. Lower metrics are generally better.
   2777 //
   2778 //   AA-BB-CC-DD Name
   2779 //
   2780 // Metrics:
   2781 //
   2782 // AA = Intent
   2783 // BB = Portability
   2784 // CC = Marginal Power
   2785 // DD = Total Power
   2786 //
   2787 //
   2788 // ** Intent Metric **
   2789 //
   2790 // 20 = Dedicated Sleep Proxy Server -- a device, permanently powered on,
   2791 //      installed for the express purpose of providing Sleep Proxy Service.
   2792 //
   2793 // 30 = Primary Network Infrastructure Hardware -- a router, DHCP server, NAT gateway,
   2794 //      or similar permanently installed device which is permanently powered on.
   2795 //      This is hardware designed for the express purpose of being network
   2796 //      infrastructure, and for most home users is typically a single point
   2797 //      of failure for the local network -- e.g. most home users only have
   2798 //      a single NAT gateway / DHCP server. Even though in principle the
   2799 //      hardware might technically be capable of running different software,
   2800 //      a typical user is unlikely to do that. e.g. AirPort base station.
   2801 //
   2802 // 40 = Primary Network Infrastructure Software -- a general-purpose computer
   2803 //      (e.g. Mac, Windows, Linux, etc.) which is currently running DHCP server
   2804 //      or NAT gateway software, but the user could choose to turn that off
   2805 //      fairly easily. e.g. iMac running Internet Sharing
   2806 //
   2807 // 50 = Secondary Network Infrastructure Hardware -- like primary infrastructure
   2808 //      hardware, except not a single point of failure for the entire local network.
   2809 //      For example, an AirPort base station in bridge mode. This may have clients
   2810 //      associated with it, and if it goes away those clients will be inconvenienced,
   2811 //      but unlike the NAT gateway / DHCP server, the entire local network is not
   2812 //      dependent on it.
   2813 //
   2814 // 60 = Secondary Network Infrastructure Software -- like 50, but in a general-
   2815 //      purpose CPU.
   2816 //
   2817 // 70 = Incidentally Available Hardware -- a device which has no power switch
   2818 //      and is generally left powered on all the time. Even though it is not a
   2819 //      part of what we conventionally consider network infrastructure (router,
   2820 //      DHCP, NAT, DNS, etc.), and the rest of the network can operate fine
   2821 //      without it, since it's available and unlikely to be turned off, it is a
   2822 //      reasonable candidate for providing Sleep Proxy Service e.g. Apple TV,
   2823 //      or an AirPort base station in client mode, associated with an existing
   2824 //      wireless network (e.g. AirPort Express connected to a music system, or
   2825 //      being used to share a USB printer).
   2826 //
   2827 // 80 = Incidentally Available Software -- a general-purpose computer which
   2828 //      happens at this time to be set to "never sleep", and as such could be
   2829 //      useful as a Sleep Proxy Server, but has not been intentionally provided
   2830 //      for this purpose. Of all the Intent Metric categories this is the
   2831 //      one most likely to be shut down or put to sleep without warning.
   2832 //      However, if nothing else is availalable, it may be better than nothing.
   2833 //      e.g. Office computer in the workplace which has been set to "never sleep"
   2834 //
   2835 //
   2836 // ** Portability Metric **
   2837 //
   2838 // Inversely related to mass of device, on the basis that, all other things
   2839 // being equal, heavier devices are less likely to be moved than lighter devices.
   2840 // E.g. A MacBook running Internet Sharing is probably more likely to be
   2841 // put to sleep and taken away than a Mac Pro running Internet Sharing.
   2842 // The Portability Metric is a logarithmic decibel scale, computed by taking the
   2843 // (approximate) mass of the device in milligrammes, taking the base 10 logarithm
   2844 // of that, multiplying by 10, and subtracting the result from 100:
   2845 //
   2846 //   Portability Metric = 100 - (log10(mg) * 10)
   2847 //
   2848 // The Portability Metric is not necessarily computed literally from the actual
   2849 // mass of the device; the intent is just that lower numbers indicate more
   2850 // permanent devices, and higher numbers indicate devices more likely to be
   2851 // removed from the network, e.g., in order of increasing portability:
   2852 //
   2853 // Mac Pro < iMac < Laptop < iPhone
   2854 //
   2855 // Example values:
   2856 //
   2857 // 10 = 1 metric tonne
   2858 // 40 = 1kg
   2859 // 70 = 1g
   2860 // 90 = 10mg
   2861 //
   2862 //
   2863 // ** Marginal Power and Total Power Metrics **
   2864 //
   2865 // The Marginal Power Metric is the power difference between sleeping and staying awake
   2866 // to be a Sleep Proxy Server.
   2867 //
   2868 // The Total Power Metric is the total power consumption when being Sleep Proxy Server.
   2869 //
   2870 // The Power Metrics use a logarithmic decibel scale, computed as ten times the
   2871 // base 10 logarithm of the (approximate) power in microwatts:
   2872 //
   2873 //   Power Metric = log10(uW) * 10
   2874 //
   2875 // Higher values indicate higher power consumption. Example values:
   2876 //
   2877 // 10 =  10 uW
   2878 // 20 = 100 uW
   2879 // 30 =   1 mW
   2880 // 60 =   1 W
   2881 // 90 =   1 kW
   2882 
   2883 typedef enum
   2884 	{
   2885 	mDNSSleepProxyMetric_Dedicated          = 20,
   2886 	mDNSSleepProxyMetric_PrimaryHardware    = 30,
   2887 	mDNSSleepProxyMetric_PrimarySoftware    = 40,
   2888 	mDNSSleepProxyMetric_SecondaryHardware  = 50,
   2889 	mDNSSleepProxyMetric_SecondarySoftware  = 60,
   2890 	mDNSSleepProxyMetric_IncidentalHardware = 70,
   2891 	mDNSSleepProxyMetric_IncidentalSoftware = 80
   2892 	} mDNSSleepProxyMetric;
   2893 
   2894 extern void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower);
   2895 #define mDNSCoreBeSleepProxyServer(M,S,P,MP,TP) \
   2896 	do { mDNS_Lock(m); mDNSCoreBeSleepProxyServer_internal((M),(S),(P),(MP),(TP)); mDNS_Unlock(m); } while(0)
   2897 
   2898 extern void FindSPSInCache(mDNS *const m, const DNSQuestion *const q, const CacheRecord *sps[3]);
   2899 #define PrototypeSPSName(X) ((X)[0] >= 11 && (X)[3] == '-' && (X)[ 4] == '9' && (X)[ 5] == '9' && \
   2900                                              (X)[6] == '-' && (X)[ 7] == '9' && (X)[ 8] == '9' && \
   2901                                              (X)[9] == '-' && (X)[10] == '9' && (X)[11] == '9'    )
   2902 #define ValidSPSName(X) ((X)[0] >= 5 && mDNSIsDigit((X)[1]) && mDNSIsDigit((X)[2]) && mDNSIsDigit((X)[4]) && mDNSIsDigit((X)[5]))
   2903 #define SPSMetric(X) (!ValidSPSName(X) || PrototypeSPSName(X) ? 1000000 : \
   2904 	((X)[1]-'0') * 100000 + ((X)[2]-'0') * 10000 + ((X)[4]-'0') * 1000 + ((X)[5]-'0') * 100 + ((X)[7]-'0') * 10 + ((X)[8]-'0'))
   2905 
   2906 // ***************************************************************************
   2907 #if 0
   2908 #pragma mark -
   2909 #pragma mark - Compile-Time assertion checks
   2910 #endif
   2911 
   2912 // Some C compiler cleverness. We can make the compiler check certain things for
   2913 // us, and report compile-time errors if anything is wrong. The usual way to do
   2914 // this would be to use a run-time "if" statement, but then you don't find out
   2915 // what's wrong until you run the software. This way, if the assertion condition
   2916 // is false, the array size is negative, and the complier complains immediately.
   2917 
   2918 struct CompileTimeAssertionChecks_mDNS
   2919 	{
   2920 	// Check that the compiler generated our on-the-wire packet format structure definitions
   2921 	// properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
   2922 	char assert0[(sizeof(rdataSRV)         == 262                          ) ? 1 : -1];
   2923 	char assert1[(sizeof(DNSMessageHeader) ==  12                          ) ? 1 : -1];
   2924 	char assert2[(sizeof(DNSMessage)       ==  12+AbsoluteMaxDNSMessageData) ? 1 : -1];
   2925 	char assert3[(sizeof(mDNSs8)           ==   1                          ) ? 1 : -1];
   2926 	char assert4[(sizeof(mDNSu8)           ==   1                          ) ? 1 : -1];
   2927 	char assert5[(sizeof(mDNSs16)          ==   2                          ) ? 1 : -1];
   2928 	char assert6[(sizeof(mDNSu16)          ==   2                          ) ? 1 : -1];
   2929 	char assert7[(sizeof(mDNSs32)          ==   4                          ) ? 1 : -1];
   2930 	char assert8[(sizeof(mDNSu32)          ==   4                          ) ? 1 : -1];
   2931 	char assert9[(sizeof(mDNSOpaque16)     ==   2                          ) ? 1 : -1];
   2932 	char assertA[(sizeof(mDNSOpaque32)     ==   4                          ) ? 1 : -1];
   2933 	char assertB[(sizeof(mDNSOpaque128)    ==  16                          ) ? 1 : -1];
   2934 	char assertC[(sizeof(CacheRecord  )    ==  sizeof(CacheGroup)          ) ? 1 : -1];
   2935 	char assertD[(sizeof(int)              >=  4                           ) ? 1 : -1];
   2936 	char assertE[(StandardAuthRDSize       >=  256                         ) ? 1 : -1];
   2937 	char assertF[(sizeof(EthernetHeader)   ==   14                         ) ? 1 : -1];
   2938 	char assertG[(sizeof(ARP_EthIP     )   ==   28                         ) ? 1 : -1];
   2939 	char assertH[(sizeof(IPv4Header    )   ==   20                         ) ? 1 : -1];
   2940 	char assertI[(sizeof(IPv6Header    )   ==   40                         ) ? 1 : -1];
   2941 	char assertJ[(sizeof(IPv6NDP       )   ==   24                         ) ? 1 : -1];
   2942 	char assertK[(sizeof(UDPHeader     )   ==    8                         ) ? 1 : -1];
   2943 	char assertL[(sizeof(IKEHeader     )   ==   28                         ) ? 1 : -1];
   2944 	char assertM[(sizeof(TCPHeader     )   ==   20                         ) ? 1 : -1];
   2945 
   2946 	// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
   2947 	// other overly-large structures instead of having a pointer to them, can inadvertently
   2948 	// cause structure sizes (and therefore memory usage) to balloon unreasonably.
   2949 	char sizecheck_RDataBody           [(sizeof(RDataBody)            ==   264) ? 1 : -1];
   2950 	char sizecheck_ResourceRecord      [(sizeof(ResourceRecord)       <=    64) ? 1 : -1];
   2951 	char sizecheck_AuthRecord          [(sizeof(AuthRecord)           <=  1208) ? 1 : -1];
   2952 	char sizecheck_CacheRecord         [(sizeof(CacheRecord)          <=   184) ? 1 : -1];
   2953 	char sizecheck_CacheGroup          [(sizeof(CacheGroup)           <=   184) ? 1 : -1];
   2954 	char sizecheck_DNSQuestion         [(sizeof(DNSQuestion)          <=   786) ? 1 : -1];
   2955 	char sizecheck_ZoneData            [(sizeof(ZoneData)             <=  1624) ? 1 : -1];
   2956 	char sizecheck_NATTraversalInfo    [(sizeof(NATTraversalInfo)     <=   192) ? 1 : -1];
   2957 	char sizecheck_HostnameInfo        [(sizeof(HostnameInfo)         <=  3050) ? 1 : -1];
   2958 	char sizecheck_DNSServer           [(sizeof(DNSServer)            <=   320) ? 1 : -1];
   2959 	char sizecheck_NetworkInterfaceInfo[(sizeof(NetworkInterfaceInfo) <=  6850) ? 1 : -1];
   2960 	char sizecheck_ServiceRecordSet    [(sizeof(ServiceRecordSet)     <=  5500) ? 1 : -1];
   2961 	char sizecheck_DomainAuthInfo      [(sizeof(DomainAuthInfo)       <=  7808) ? 1 : -1];
   2962 	char sizecheck_ServiceInfoQuery    [(sizeof(ServiceInfoQuery)     <=  3200) ? 1 : -1];
   2963 #if APPLE_OSX_mDNSResponder
   2964 	char sizecheck_ClientTunnel        [(sizeof(ClientTunnel)         <=  1148) ? 1 : -1];
   2965 #endif
   2966 	};
   2967 
   2968 // ***************************************************************************
   2969 
   2970 #ifdef __cplusplus
   2971 	}
   2972 #endif
   2973 
   2974 #endif
   2975