/* -*- Mode: C; tab-width: 4 -*-
*
* Copyright (c) 2002-2015 Apple Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
NOTE:
If you're building an application that uses DNS Service Discovery
this is probably NOT the header file you're looking for.
This header file defines the lowest level raw interface to mDNSCore,
which is appropriate *only* on tiny embedded systems where everything
runs in a single address space and memory is extremely constrained.
All the APIs here are malloc-free, which means that the caller is
responsible for passing in a pointer to the relevant storage that
will be used in the execution of that call, and (when called with
correct parameters) all the calls are guaranteed to succeed. There
is never a case where a call can suffer intermittent failures because
the implementation calls malloc() and sometimes malloc() returns NULL
because memory is so limited that no more is available.
This is primarily for devices that need to have precisely known fixed
memory requirements, with absolutely no uncertainty or run-time variation,
but that certainty comes at a cost of more difficult programming.
For applications running on general-purpose desktop operating systems
(Mac OS, Linux, Solaris, Windows, etc.) the API you should use is
independent client processes communicate their DNS Service Discovery
requests to a single "mdnsd" daemon running in the background.
Even on platforms that don't run multiple independent processes in
multiple independent address spaces, you can still use the preferred
dns_sd.h APIs by linking in "dnssd_clientshim.c", which implements
the standard "dns_sd.h" API calls, allocates any required storage
using malloc(), and then calls through to the low-level malloc-free
mDNSCore routines defined here. This has the benefit that even though
you're running on a small embedded system with a single address space,
you can still use the exact same client C code as you'd use on a
general-purpose desktop system.
*/
#ifndef __mDNSEmbeddedAPI_h
#define __mDNSEmbeddedAPI_h
// EFI doesn't have stdarg.h unless it's building with GCC.
#include "Tiano.h"
#if !defined(__GNUC__)
#endif
#else
#include <stdarg.h> // stdarg.h is required for for va_list support for the mDNS_vsnprintf declaration
#endif
#include "mDNSDebug.h"
#include <TargetConditionals.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
// ***************************************************************************
// Feature removal compile options & limited resource targets
// The following compile options are responsible for removing certain features from mDNSCore to reduce the
// memory footprint for use in embedded systems with limited resources.
// UNICAST_DISABLED - disables unicast DNS functionality, including Wide Area Bonjour
// ANONYMOUS_DISABLED - disables anonymous functionality
// DNSSEC_DISABLED - disables DNSSEC functionality
// SPC_DISABLED - disables Bonjour Sleep Proxy client
// IDLESLEEPCONTROL_DISABLED - disables sleep control for Bonjour Sleep Proxy clients
// In order to disable the above features pass the option to your compiler, e.g. -D UNICAST_DISABLED
// Additionally, the LIMITED_RESOURCES_TARGET compile option will reduce the maximum DNS message sizes.
#ifdef LIMITED_RESOURCES_TARGET
// Don't support jumbo frames
// 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
// StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
#endif
// ***************************************************************************
// Function scope indicators
// If you see "mDNSlocal" before a function name in a C file, it means the function is not callable outside this file
#ifndef mDNSlocal
#define mDNSlocal static
#endif
// If you see "mDNSexport" before a symbol in a C file, it means the symbol is exported for use by clients
// For every "mDNSexport" in a C file, there needs to be a corresponding "extern" declaration in some header file
// (When a C file #includes a header file, the "extern" declarations tell the compiler:
// "This symbol exists -- but not necessarily in this C file.")
#ifndef mDNSexport
#define mDNSexport
#endif
// Explanation: These local/export markers are a little habit of mine for signaling the programmers' intentions.
// When "mDNSlocal" is just a synonym for "static", and "mDNSexport" is a complete no-op, you could be
// forgiven for asking what purpose they serve. The idea is that if you see "mDNSexport" in front of a
// function definition it means the programmer intended it to be exported and callable from other files
// in the project. If you see "mDNSlocal" in front of a function definition it means the programmer
// intended it to be private to that file. If you see neither in front of a function definition it
// means the programmer forgot (so you should work out which it is supposed to be, and fix it).
// Using "mDNSlocal" instead of "static" makes it easier to do a textual searches for one or the other.
// For example you can do a search for "static" to find if any functions declare any local variables as "static"
// (generally a bad idea unless it's also "const", because static storage usually risks being non-thread-safe)
// without the results being cluttered with hundreds of matches for functions declared static.
// - Stuart Cheshire
// ***************************************************************************
// Structure packing macro
// If we're not using GNUC, it's not fatal.
// Most compilers naturally pack the on-the-wire structures correctly anyway, so a plain "struct" is usually fine.
// In the event that structures are not packed correctly, mDNS_Init() will detect this and report an error, so the
// developer will know what's wrong, and can investigate what needs to be done on that compiler to provide proper packing.
#ifndef packedstruct
#else
#define packedstruct struct
#define packedunion union
#endif
#endif
// ***************************************************************************
#if 0
#endif
typedef enum // From RFC 1035
{
kDNSClass_UniqueRRSet = 0x8000, // ... and the top bit indicates that all other cached records are now invalid
kDNSQClass_UnicastResponse = 0x8000 // Top bit set in a question means "unicast response acceptable"
typedef enum // From RFC 1035
{
// ***************************************************************************
#if 0
#pragma mark -
#endif
// mDNS defines its own names for these common types to simplify portability across
// multiple platforms that may each have their own (different) names for these types.
typedef unsigned char mDNSBool;
typedef signed char mDNSs8;
typedef unsigned char mDNSu8;
typedef signed short mDNSs16;
typedef unsigned short mDNSu16;
// It can be safely assumed that int is 32bits on the platform
#else
typedef signed int mDNSs32;
typedef unsigned int mDNSu32;
#endif
// To enforce useful type checking, we make mDNSInterfaceID be a pointer to a dummy struct
// This way, mDNSInterfaceIDs can be assigned, and compared with each other, but not with other types
// Declaring the type to be the typical generic "void *" would lack this type checking
// These types are for opaque two- and four-byte identifiers.
// The "NotAnInteger" fields of the unions allow the value to be conveniently passed around in a
// register for the sake of efficiency, and compared for equality or inequality, but don't forget --
// just because it is in a register doesn't mean it is an integer. Operations like greater than,
// less than, add, multiply, increment, decrement, etc., are undefined for opaque identifiers,
// and if you make the mistake of trying to do those using the NotAnInteger field, then you'll
// find you get code that doesn't work consistently on big-endian and little-endian machines.
#if defined(_WIN32)
#pragma pack(1)
#endif
#if defined(_WIN32)
#pragma pack()
#endif
typedef mDNSOpaque128 mDNSv6Addr; // An IPv6 address is a 16-byte opaque identifier (not an integer)
typedef mDNSOpaque48 mDNSEthAddr; // An Ethernet address is a six-byte opaque identifier (not an integer)
// Bit operations for opaque 64 bit quantity. Uses the 32 bit quantity(l[2]) to set and clear bits
#define bit_set_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] |= (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
#define bit_clr_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] &= ~(1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
#define bit_get_opaque64(op64, index) (op64.l[((index))/(sizeof(mDNSu32) * mDNSNBBY)] & (1 << ((index) % (sizeof(mDNSu32) * mDNSNBBY))))
enum
{
mDNSAddrType_None = 0,
};
enum
{
mDNSTransport_None = 0,
};
typedef struct
{
} mDNSAddr;
#define mDNSNULL 0L
enum
{
mStatus_NoError = 0,
// mDNS return values are in the range FFFE FF00 (-65792) to FFFE FFFF (-65537)
// The top end of the range (FFFE FFFF) is used for error codes;
// the bottom end of the range (FFFE FF00) is used for non-error values;
// Error codes:
mStatus_BadSig = -65560, // while we define this per RFC 2845, BIND 9 returns Refused for bad/missing signatures
mStatus_TransientErr = -65562, // transient failures, e.g. sending packets shortly after a network transition or wake from sleep
mStatus_NATPortMappingDisabled = -65565, // NAT supports PCP, NAT-PMP or UPnP, but it's disabled by the administrator
// -65568 to -65786 currently unused; available for allocation
// tcp connection status
// Non-error values:
// mStatus_MemFree is the last legal mDNS error code, at the end of the range allocated for mDNS
};
// RFC 1034/1035 specify that a domain label consists of a length byte plus up to 63 characters
// RFC 1034/1035/2181 specify that a domain name (length bytes and data bytes) may be up to 255 bytes long,
// plus the terminating zero at the end makes 256 bytes total in the on-the-wire format.
// The longest legal textual form of a DNS name is 1009 bytes, including the C-string terminating NULL at the end.
// Explanation:
// When a native domainname object is converted to printable textual form using ConvertDomainNameToCString(),
// non-printing characters are represented in the conventional DNS way, as '\ddd', where ddd is a three-digit decimal number.
// The longest legal domain name is 256 bytes, in the form of four labels as shown below:
// Length byte, 63 data bytes, length byte, 63 data bytes, length byte, 63 data bytes, length byte, 62 data bytes, zero byte.
// Each label is encoded textually as characters followed by a trailing dot.
// If every character has to be represented as a four-byte escape sequence, then this makes the maximum textual form four labels
// plus the C-string terminating NULL as shown below:
// 63*4+1 + 63*4+1 + 63*4+1 + 62*4+1 + 1 = 1009.
// Note that MAX_ESCAPED_DOMAIN_LABEL is not normally used: If you're only decoding a single label, escaping is usually not required.
// It is for domain names, where dots are used as label separators, that proper escaping is vital.
// MAX_REVERSE_MAPPING_NAME
// For IPv4: "123.123.123.123.in-addr.arpa." 30 bytes including terminating NUL
// 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
// Most records have a TTL of 75 minutes, so that their 80% cache-renewal query occurs once per hour.
// For records containing a hostname (in the name on the left, or in the rdata on the right),
// like A, AAAA, reverse-mapping PTR, and SRV, we use a two-minute TTL by default, because we don't want
// them to hang around for too long in the cache if the host in question crashes or otherwise goes away.
// Some applications want to register their SRV records with a lower ttl so that in case the server
// using a dynamic port number restarts, the clients will not have stale information for more than
// 10 seconds
// Multicast DNS uses announcements (gratuitous responses) to update peer caches.
// This means it is feasible to use relatively larger TTL values than we might otherwise
// use, because we have a cache coherency protocol to keep the peer caches up to date.
// With Unicast DNS, once an authoritative server gives a record with a certain TTL value to a client
// or caching server, that client or caching server is entitled to hold onto the record until its TTL
// expires, and has no obligation to contact the authoritative server again until that time arrives.
// This means that whereas Multicast DNS can use announcements to pre-emptively update stale data
// before it would otherwise have expired, standard Unicast DNS (not using LLQs) has no equivalent
// mechanism, and TTL expiry is the *only* mechanism by which stale data gets deleted. Because of this,
// we currently limit the TTL to ten seconds in such cases where no dynamic cache updating is possible.
#define DefaultTTLforRRType(X) (((X) == kDNSType_A || (X) == kDNSType_AAAA || (X) == kDNSType_SRV) ? kHostNameTTL : kStandardTTL)
#define mDNS_KeepaliveRecord(rr) ((rr)->rrtype == kDNSType_NULL && SameDomainLabel(SecondLabel((rr)->name)->c, (mDNSu8 *)"\x0A_keepalive"))
// Number of times keepalives are sent if no ACK is received before waking up the system
// this is analogous to net.inet.tcp.keepcnt
// The frequency at which keepalives are retried if no ACK is received
// The actual definition of these structures appear in the appropriate platform support code
// ***************************************************************************
#if 0
#pragma mark -
#endif
typedef packedstruct
{
// We can send and receive packets up to 9000 bytes (Ethernet Jumbo Frame size, if that ever becomes widely used)
// However, in the normal case we try to limit packets to 1500 bytes so that we don't get IP fragmentation on standard Ethernet
// 40 (IPv6 header) + 8 (UDP header) + 12 (DNS message header) + 1440 (DNS message body) = 1500 total
#ifndef AbsoluteMaxDNSMessageData
#endif
typedef packedstruct
{
DNSMessageHeader h; // Note: Size 12 bytes
mDNSu8 data[AbsoluteMaxDNSMessageData]; // 40 (IPv6) + 8 (UDP) + 12 (DNS header) + 8940 (data) = 9000
} DNSMessage;
typedef struct tcpInfo_t
{
mDNS *m;
int requestLen;
unsigned long nread;
int numReplies;
} tcpInfo_t;
// ***************************************************************************
#if 0
#pragma mark -
#endif
typedef packedstruct
{
} EthernetHeader; // 14 bytes
typedef packedstruct
{
} ARP_EthIP; // 28 bytes
typedef packedstruct
{
} IPv4Header; // 20 bytes
typedef packedstruct
{
} IPv6Header; // 40 bytes
typedef packedstruct
{
} IPv6PseudoHeader; // 40 bytes
typedef union
{
typedef packedstruct
{
} TCPHeader; // 20 bytes; IP protocol type 0x06
typedef struct
{
} mDNSTCPInfo;
typedef packedstruct
{
} UDPHeader; // 8 bytes; IP protocol type 0x11
typedef packedstruct
{
// Typically 8 bytes of options are also present
} IPv6NDP; // 24 bytes or more; IP protocol type 0x3A
typedef struct
{
typedef union
{
typedef packedstruct
{
} IKEHeader; // 28 bytes
// ***************************************************************************
#if 0
#pragma mark -
#endif
// Authoritative Resource Records:
// There are four basic types: Shared, Advisory, Unique, Known Unique
// * Shared Resource Records do not have to be unique
// -- Shared Resource Records are used for DNS-SD service PTRs
// -- It is okay for several hosts to have RRs with the same name but different RDATA
// -- We use a random delay on responses to reduce collisions when all the hosts respond to the same query
// -- These RRs typically have moderately high TTLs (e.g. one hour)
// -- These records are announced on startup and topology changes for the benefit of passive listeners
// -- These records send a goodbye packet when deregistering
//
// * Advisory Resource Records are like Shared Resource Records, except they don't send a goodbye packet
//
// * Unique Resource Records should be unique among hosts within any given mDNS scope
// -- The majority of Resource Records are of this type
// -- If two entities on the network have RRs with the same name but different RDATA, this is a conflict
// -- Responses may be sent immediately, because only one host should be responding to any particular query
// -- These RRs typically have low TTLs (e.g. a few minutes)
// -- On startup and after topology changes, a host issues queries to verify uniqueness
// * Known Unique Resource Records are treated like Unique Resource Records, except that mDNS does
// not have to verify their uniqueness because this is already known by other means (e.g. the RR name
// is derived from the host's IP or Ethernet address, which is already known to be a unique identifier).
// Summary of properties of different record types:
// Probe? Does this record type send probes before announcing?
// Conflict? Does this record type react if we observe an apparent conflict?
// Goodbye? Does this record type send a goodbye packet on departure?
//
// Probe? Conflict? Goodbye? Notes
// Unregistered Should not appear in any list (sanity check value)
// Shared No No Yes e.g. Service PTR record
// Deregistering No No Yes Shared record about to announce its departure and leave the list
// Advisory No No No
// Unique Yes Yes No Record intended to be unique -- will probe to verify
// Verified Yes Yes No Record has completed probing, and is verified unique
// KnownUnique No Yes No Record is assumed by other means to be unique
// Valid lifecycle of a record:
// Unregistered -> Shared -> Deregistering -(goodbye)-> Unregistered
// Unregistered -> Advisory -> Unregistered
// Unregistered -> Unique -(probe)-> Verified -> Unregistered
// Unregistered -> KnownUnique -> Unregistered
// Each Authoritative kDNSRecordType has only one bit set. This makes it easy to quickly see if a record
// is one of a particular set of types simply by performing the appropriate bitwise masking operation.
// Cache Resource Records (received from the network):
// There are four basic types: Answer, Unique Answer, Additional, Unique Additional
// Bit 7 (the top bit) of kDNSRecordType is always set for Cache Resource Records; always clear for Authoritative Resource Records
// Bit 6 (value 0x40) is set for answer records; clear for authority/additional records
// Bit 5 (value 0x20) is set for records received with the kDNSClass_UniqueRRSet
enum
{
kDNSRecordTypeDeregistering = 0x01, // Shared record about to announce its departure and leave the list
kDNSRecordTypeShared = 0x08, // Shared means record name does not have to be unique -- use random delay on responses
kDNSRecordTypeVerified = 0x10, // Unique means mDNS should check that name is unique (and then send immediate responses)
kDNSRecordTypeKnownUnique = 0x20, // Known Unique means mDNS can assume name is unique without checking
// For Dynamic Update records, Known Unique means the record must already exist on the server.
kDNSRecordTypeUniqueMask = (kDNSRecordTypeUnique | kDNSRecordTypeVerified | kDNSRecordTypeKnownUnique),
kDNSRecordTypePacketAddUnique = 0x90, // Received in the Additional Section of a DNS Response with kDNSClass_UniqueRRSet set
kDNSRecordTypePacketAuthUnique = 0xB0, // Received in the Authorities Section of a DNS Response with kDNSClass_UniqueRRSet set
kDNSRecordTypePacketAnsUnique = 0xD0, // Received in the Answer Section of a DNS Response with kDNSClass_UniqueRRSet set
kDNSRecordTypePacketNegative = 0xF0, // Pseudo-RR generated to cache non-existence results like NXDomain
kDNSRecordTypePacketUniqueMask = 0x10 // True for PacketAddUnique, PacketAnsUnique, PacketAuthUnique, kDNSRecordTypePacketNegative
};
typedef packedstruct { mDNSu16 priority; mDNSu16 weight; mDNSIPPort port; domainname target; } rdataSRV;
typedef packedstruct
{
mDNSu32 refresh; // Time in seconds that a slave waits after successful replication of the database before it attempts replication again
mDNSu32 retry; // Time in seconds that a slave waits after an unsuccessful replication attempt before it attempts replication again
mDNSu32 expire; // Time in seconds that a slave holds on to old data while replication attempts remain unsuccessful
mDNSu32 min; // Nominally the minimum record TTL for this zone, in seconds; also used for negative caching.
} rdataSOA;
// Algorithm used for RRSIG, DS and DNS KEY
// alg - same as in RRSIG, DNS KEY or DS.
// RFC 4034 defines SHA1
// RFC 4509 defines SHA256
// Note: NSEC3 also uses 1 for SHA1 and hence we will reuse for now till a new
// value is assigned.
//
// We need support for base64 and base32 encoding for displaying KEY, NSEC3
// To make this platform agnostic, we define two types which the platform
// needs to support
typedef packedstruct
{
} rdataDS;
typedef struct TrustAnchor
{
int digestLen;
} TrustAnchor;
//size of rdataRRSIG excluding signerName and signature (which are variable fields)
typedef packedstruct
{
// mDNSu8 *signature
} rdataRRSig;
// RFC 4034: For DNS Key RR
// flags - the valid value for DNSSEC is 256 (Zone signing key - ZSK) and 257 (Secure Entry Point) which also
// includes the ZSK bit
//
// proto - the only valid value for protocol is 3 (See RFC 4034)
// DNSSEC_RSA_SHA1_ALG
typedef packedstruct
{
} rdataDNSKey;
typedef packedstruct
{
// hashLength, nxt, bitmap
} rdataNSEC3;
// In the multicast usage of NSEC3, we know the actual size of RData
// 4 bytes : HashAlg, Flags,Iterations
// 5 bytes : Salt Length 1 byte, Salt 4 bytes
// 21 bytes : HashLength 1 byte, Hash 20 bytes
// 34 bytes : Window number, Bitmap length, Type bit map to include the first 256 types
// Base32 encoding takes 5 bytes of the input and encodes as 8 bytes of output.
// For example, SHA-1 hash of 20 bytes will be encoded as 20/5 * 8 = 32 base32
// bytes. For a max domain name size of 255 bytes of base32 encoding : (255/8)*5
// is the max hash length possible.
// In NSEC3, the names are hashed and stored in the first label and hence cannot exceed label
// size.
// We define it here instead of dnssec.h so that these values can be used
// in files without bringing in all of dnssec.h unnecessarily.
typedef enum
{
} DNSSECStatus;
#define DNSSECRecordType(rrtype) (((rrtype) == kDNSType_RRSIG) || ((rrtype) == kDNSType_NSEC) || ((rrtype) == kDNSType_DNSKEY) || ((rrtype) == kDNSType_DS) || \
((rrtype) == kDNSType_NSEC3))
typedef enum
{
} Platform_t;
// EDNS Option Code registrations are recorded in the "DNS EDNS0 Options" section of
typedef struct
{
// Note: In the in-memory form, there's typically a two-byte space here, so that the following 64-bit id is word-aligned
} LLQOptData;
typedef struct
{
} OwnerOptData;
typedef struct
{
// Note: rdataOPT format may be repeated an arbitrary number of times in a single resource record
typedef packedstruct
{
} rdataOPT;
// Space needed to put OPT records into a packet:
// Header 11 bytes (name 1, type 2, class 2, TTL 4, length 2)
// LLQ rdata 18 bytes (opt 2, len 2, vers 2, op 2, err 2, id 8, lease 4)
// Lease rdata 8 bytes (opt 2, len 2, lease 4)
// Owner rdata 12-24 bytes (opt 2, len 2, owner 8-20)
// Trace rdata 9 bytes (opt 2, len 2, platf 1, mDNSv 4)
(X) == DNSOpt_OwnerData_ID_Wake_Space - 4 || \
(X) == DNSOpt_OwnerData_ID_Wake_PW4_Space - 4 || \
(X) == DNSOpt_OwnerData_ID_Wake_PW6_Space - 4 )
#define DNSOpt_Owner_Space(A,B) (mDNSSameEthAddress((A),(B)) ? DNSOpt_OwnerData_ID_Space : DNSOpt_OwnerData_ID_Wake_Space)
#define DNSOpt_Data_Space(O) ( \
// NSEC record is defined in RFC 4034.
// 16 bit RRTYPE space is split into 256 windows and each window has 256 bits (32 bytes).
// If we create a structure for NSEC, it's size would be:
//
// 256 bytes domainname 'nextname'
// + 256 * 34 = 8704 bytes of bitmap data
// = 8960 bytes total
//
// This would be a waste, as types about 256 are not very common. But it would be odd, if we receive
// a type above 256 (.US zone had TYPE65534 when this code was written) and not able to handle it.
// Hence, we handle any size by not fixing a strucure in place. The following is just a placeholder
// and never used anywhere.
//
typedef struct
{
domainname *next; //placeholders are uncommented because C89 in Windows requires that a struct has at least a member.
} rdataNSEC;
// StandardAuthRDSize is 264 (256+8), which is large enough to hold a maximum-sized SRV record (6 + 256 bytes)
// MaximumRDSize is 8K the absolute maximum we support (at least for now)
#ifndef MaximumRDSize
#endif
// InlineCacheRDSize is 68
// Records received from the network with rdata this size or less have their rdata stored right in the CacheRecord object
// Records received from the network with rdata larger than this have additional storage allocated for the rdata
// A quick unscientific sample from a busy network at Apple with lots of machines revealed this:
// 1461 records in cache
// 292 were one-byte TXT records
// 136 were four-byte A records
// 184 were sixteen-byte AAAA records
// 780 were various PTR, TXT and SRV records from 12-64 bytes
// Only 69 records had rdata bigger than 64 bytes
// Note that since CacheRecord object and a CacheGroup object are allocated out of the same pool, it's sensible to
// have them both be the same size. Making one smaller without making the other smaller won't actually save any memory.
// The RDataBody union defines the common rdata types that fit into our 264-byte limit
typedef union
{
rdataOPT opt[2]; // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
} RDataBody;
// The RDataBody2 union is the same as above, except it includes fields for the larger types like soa, rp, px
typedef union
{
rdataOPT opt[2]; // For EDNS0 OPT record; RDataBody may contain multiple variable-length rdataOPT objects packed together
} RDataBody2;
typedef struct
{
RDataBody u;
} RData;
// sizeofRDataHeader should be 4 bytes
// RData_small is a smaller version of the RData object, used for inline data storage embedded in a CacheRecord_struct
typedef struct
{
mDNSu16 MaxRDLength; // Storage allocated for data (may be greater than InlineCacheRDSize if additional storage follows this object)
} RData_small;
// Note: Within an mDNSRecordCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
// Note:
// Restrictions: An mDNSRecordUpdateCallback may not make any mDNS API calls.
// The intent of this callback is to allow the client to free memory, if necessary.
// The internal data structures of the mDNS code may not be in a state where mDNS API calls may be made safely.
typedef void mDNSRecordUpdateCallback (mDNS *const m, AuthRecord *const rr, RData *OldRData, mDNSu16 OldRDLen);
// ***************************************************************************
#if 0
#pragma mark -
#endif
#define NATMAP_MAX_RETRY_INTERVAL ((mDNSPlatformOneSecond * 60) * 15) // Max retry interval is 15 minutes
#define NATMAP_VERS 0
typedef enum
{
NATOp_AddrRequest = 0,
} NATOp_t;
enum
{
NATErr_None = 0,
};
typedef packedstruct
{
typedef packedstruct
{
} NATAddrReply;
typedef packedstruct
{
typedef packedstruct
{
// PCP Support for IPv4 mappings
typedef enum
{
PCPOp_Announce = 0,
} PCPOp_t;
typedef enum
{
PCPProto_All = 0,
} PCPProto_t;
typedef enum
{
PCPResult_Success = 0,
} PCPResult_t;
typedef packedstruct
{
typedef packedstruct
{
} PCPMapReply;
// LNT Support
typedef enum
{
} LNTOp_t;
struct tcpLNTInfo_struct
{
mDNS *m;
int requestLen;
int replyLen;
};
// if m->timenow < ExpiryTime then we have an active mapping, and we'll renew halfway to expiry
// if m->timenow >= ExpiryTime then our mapping has expired, and we're trying to create one
typedef enum
{
NATTProtocolNone = 0,
} NATTProtocol;
struct NATTraversalInfo_struct
{
// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
NATTProtocol lastSuccessfulProtocol; // To send correct deletion request & update non-PCP external address operations
// we receive another NAT-PMP "Unsupported Version" packet
#ifdef _LEGACY_NAT_TRAVERSAL_
#endif
// Result fields: When the callback is invoked these fields contain the answers the client is looking for
// When the callback is invoked ExternalPort is *usually* set to be the same the same as RequestedPort, except:
// (a) When we're behind a NAT gateway with port mapping disabled, ExternalPort is reported as zero to
// indicate that we don't currently have a working mapping (but RequestedPort retains the external port
// we'd like to get, the next time we meet an accomodating NAT gateway willing to give us one).
// (b) When we have a routable non-RFC1918 address, we don't *need* a port mapping, so ExternalPort
// is reported as the same as our InternalPort, since that is effectively our externally-visible port too.
// Again, RequestedPort retains the external port we'd like to get the next time we find ourself behind a NAT gateway.
// To improve stability of port mappings, RequestedPort is updated any time we get a successful
// mapping response from the PCP, NAT-PMP or UPnP gateway. For example, if we ask for port 80, and
// get assigned port 81, then thereafter we'll contine asking for port 81.
// Client API fields: The client must set up these fields *before* making any NAT traversal API calls
mDNSu8 Protocol; // NATOp_MapUDP or NATOp_MapTCP, or zero if just requesting the external IP address
mDNSIPPort RequestedPort; // Requested external port; may be updated with actual value assigned by gateway
void *clientContext;
};
// ***************************************************************************
#if 0
#pragma mark -
#endif
enum
{
DNSServer_Untested = 0,
};
enum
{
#endif
};
enum
{
};
typedef struct McastResolver
{
// scoped values for DNSServer matching
enum
{
// have a matching serviceID
};
// Note: DNSSECAware is set if we are able to get a valid response to
// a DNSSEC question. In some cases it is possible that the proxy
// strips the EDNS0 option and we just get a plain response with no
// signatures. But we still mark DNSSECAware in that case. As DNSSECAware
// is only used to determine whether DNSSEC_VALIDATION_SECURE_OPTIONAL
// should be turned off or not, it is sufficient that we are getting
// responses back.
typedef struct DNSServer
{
// sent with DO option.
} DNSServer;
typedef struct
{
int AnonDataLen;
struct ResourceRecord_struct
{
// (In-memory storage may be larger, for structures containing 'holes', like SOA)
mDNSu32 rdatahash; // For rdata containing domain name (e.g. PTR, SRV, CNAME etc.), case-insensitive name hash
// else, for all other rdata, 32-bit hash of the raw rdata
// Note: This requirement is important. Various routines like AddAdditionalsToResponseList(),
// ReconfirmAntecedents(), etc., use rdatahash as a pre-flight check to see
// whether it's worth doing a full SameDomainName() call. If the rdatahash
// is not a correct case-insensitive name hash, they'll get false negatives.
// Grouping pointers together at the end of the structure improves the memory layout efficiency
// For records received off the wire, InterfaceID is *always* set to the receiving interface
// For our authoritative records, InterfaceID is usually zero, except for those few records
// that are interface-specific (e.g. address records, especially linklocal addresses)
};
// Unless otherwise noted, states may apply to either independent record registrations or service registrations
typedef enum
{
regState_Zero = 0,
} regState_t;
enum
{
Target_Manual = 0,
};
typedef enum
{
mergeState_Zero = 0,
} mergeState_t;
{
};
#ifndef AUTH_HASH_SLOTS
#endif
typedef struct {
}AuthHash;
// AuthRecordAny includes mDNSInterface_Any and interface specific auth records.
typedef enum
{
} AuthRecType;
typedef enum
{
struct AuthRecord_struct
{
// For examples of how to set up this structure for use in mDNS_Register(),
// see mDNS_AdvertiseInterface() or mDNS_RegisterService().
// Basically, resrec and persistent metadata need to be set up before calling mDNS_Register().
// mDNS_SetupResourceRecord() is avaliable as a helper routine to set up most fields to sensible default values for you
// Field Group 1: Common ResourceRecord fields
ResourceRecord resrec; // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
// Field Group 2: Persistent metadata for Authoritative Records
AuthRecord *Additional1; // Recommended additional record to include in response (e.g. SRV for PTR record)
mDNSRecordCallback *RecordCallback; // Callback function to call for state changes, and to free memory asynchronously on deregistration
mDNSu8 ForceMCast; // Set by client to advertise solely via multicast, even for apparently unicast names
// Field Group 3: Transient state for Authoritative Records
mDNSu8 RequireGoodbye; // Set if this RR has been announced on the wire and will require a goodbye packet
mDNSu8 AnsweredLocalQ; // Set if this AuthRecord has been delivered to any local question (LocalOnly or mDNSInterface_Any)
mDNSInterfaceID ImmedAnswer; // Someone on this interface issued a query we need to answer (all-ones for all interfaces)
#endif
mDNSInterfaceID ImmedAdditional; // Hint that we might want to also send this record, just to be helpful
mDNSv4Addr v4Requester; // Recent v4 query for this record, or all-ones if more than one recent query
mDNSv6Addr v6Requester; // Recent v6 query for this record, or all-ones if more than one recent query
const mDNSu8 *NR_AnswerTo; // Set if this record was selected by virtue of being a direct answer to a question
AuthRecord *NR_AdditionalTo; // Set if this record was selected by virtue of being additional to another
mDNSs32 LastMCTime; // Last time we multicast this record (used to guard against packet-storm attacks)
mDNSInterfaceID LastMCInterface; // Interface this record was multicast on at the time LastMCTime was recorded
// Field Group 4: Transient uDNS state for Authoritative Records
regState_t state; // Maybe combine this with resrec.RecordType state? Right now it's ambiguous and confusing.
// e.g. rr->resrec.RecordType can be kDNSRecordTypeUnregistered,
// and rr->state can be regState_Unregistered
// What if we find one of those statements is true and the other false? What does that mean?
mDNSBool Private; // If zone is private, DNS updates may have to be encrypted to prevent eavesdropping
mDNSOpaque16 updateid; // Identifier to match update request and response -- also used when transferring records to Sleep Proxy
mDNSOpaque64 updateIntID; // Interface IDs (one bit per interface index)to which updates have been sent
// uDNS_UpdateRecord support fields
// Do we really need all these in *addition* to NewRData and newrdlength above?
mDNSu16 QueuedRDLen; // pending operation (re-transmitting if necessary) THEN register the queued update
// Field Group 5: Large data objects go at the end
// rdatastorage MUST be the last thing in the structure -- when using oversized AuthRecords, extra bytes
// are appended after the end of the AuthRecord, logically augmenting the size of the rdatastorage
// DO NOT ADD ANY MORE FIELDS HERE
};
// IsLocalDomain alone is not sufficient to determine that a record is mDNS or uDNS. By default domain names within
// the "local" pseudo-TLD (and within the IPv4 and IPv6 link-local reverse mapping domains) are automatically treated
// as mDNS records, but it is also possible to force any record (even those not within one of the inherently local
// domains) to be handled as an mDNS record by setting the ForceMCast flag, or by setting a non-zero InterfaceID.
// For example, the reverse-mapping PTR record created in AdvertiseInterface sets the ForceMCast flag, since it points to
// a dot-local hostname, and therefore it would make no sense to register this record with a wide-area Unicast DNS server.
// The same applies to Sleep Proxy records, which we will answer for when queried via mDNS, but we never want to try
// to register them with a wide-area Unicast DNS server -- and we probably don't have the required credentials anyway.
// Currently we have no concept of a wide-area uDNS record scoped to a particular interface, so if the InterfaceID is
// nonzero we treat this the same as ForceMCast.
// Note: Question_uDNS(Q) is used in *only* one place -- on entry to mDNS_StartQuery_internal, to decide whether to set TargetQID.
// Everywhere else in the code, the determination of whether a question is unicast is made by checking to see if TargetQID is nonzero.
#define AuthRecord_uDNS(R) ((R)->resrec.InterfaceID == mDNSInterface_Any && !(R)->ForceMCast && !IsLocalDomain((R)->resrec.name))
((Q)->InterfaceID != mDNSInterface_LocalOnly && (Q)->InterfaceID != mDNSInterface_P2P && !(Q)->ForceMCast && !IsLocalDomain(&(Q)->qname)))
#define RRAny(rr) ((rr)->ARType == AuthRecordAny || (rr)->ARType == AuthRecordAnyIncludeP2P || (rr)->ARType == AuthRecordAnyIncludeAWDL || (rr)->ARType == AuthRecordAnyIncludeAWDLandP2P)
// Question (A or AAAA) that is suppressed currently because IPv4 or IPv6 address
// is not available locally for A or AAAA question respectively. Also, if the
// query is disallowed for the "pid" that we are sending on behalf of, suppress it.
// Normally we always lookup the cache and /etc/hosts before sending the query on the wire. For single label
// queries (A and AAAA) that are unqualified (indicated by AppendSearchDomains), we want to append search
// domains before we try them as such
// Wrapper struct for Auth Records for higher-level code that cannot use the AuthRecord's ->next pointer field
typedef struct ARListElem
{
} ARListElem;
struct CacheRecord_struct
{
ResourceRecord resrec; // 36 bytes when compiling for 32-bit; 48 when compiling for 64-bit (now 44/64)
// Transient state for Cache Records
DNSQuestion *CRActiveQuestion; // Points to an active question referencing this answer. Can never point to a NewQuestion.
mDNSu8 UnansweredQueries; // Number of times we've issued a query for this record without getting an answer
mDNSu32 MPUnansweredQ; // Multi-packet query handling: Number of times we've seen a query for this record
mDNSu32 MPUnansweredKA; // Multi-packet query handling: Number of times we've seen this record in a KA list
mDNSBool MPExpectingKA; // Multi-packet query handling: Set when we increment MPUnansweredQ; allows one KA
#endif
CacheRecord *NextInCFList; // Set if this is in the list of records we just received with the cache flush bit set
// Size to here is 76 bytes when compiling 32-bit; 104 bytes when compiling 64-bit (now 160 bytes for 64-bit)
RData_small smallrdatastorage; // Storage for small records is right here (4 bytes header + 68 bytes data = 72 bytes)
};
// Should match the CacheGroup_struct members, except namestorage[]. Only used to calculate
// the size of the namestorage array in CacheGroup_struct so that sizeof(CacheGroup) == sizeof(CacheRecord)
struct CacheGroup_base
{
};
{
mDNSu8 namestorage[sizeof(CacheRecord) - sizeof(struct CacheGroup_base)]; // match sizeof(CacheRecord)
};
// Storage sufficient to hold either a CacheGroup header or a CacheRecord
// -- for best efficiency (to avoid wasted unused storage) they should be the same size
typedef struct
{
CacheRecord r;
typedef struct HostnameInfo
{
} HostnameInfo;
struct ExtraResourceRecord_struct
{
mDNSu32 ClientID; // Opaque ID field to be used by client to map an AddRecord call to a set of Extra records
AuthRecord r;
// Note: Add any additional fields *before* the AuthRecord in this structure, not at the end.
// In some cases clients can allocate larger chunks of memory and set r->rdata->MaxRDLength to indicate
// that this extra memory is available, which would result in any fields after the AuthRecord getting smashed
};
// Note: Within an mDNSServiceCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
// A ServiceRecordSet has no special meaning to the core code of the Multicast DNS protocol engine;
// it is just a convenience structure to group together the records that make up a standard service
// registration so that they can be allocted and deallocted together as a single memory object.
// It contains its own ServiceCallback+ServiceContext to report aggregate results up to the next layer of software above.
// It also contains:
// * the "_services" PTR record for service enumeration
// * the optional list of SubType PTR records
// * the optional list of additional records attached to the service set (e.g. iChat pictures)
struct ServiceRecordSet_struct
{
// These internal state fields are used internally by mDNSCore; the client layer needn't be concerned with them.
// No fields need to be set up by the client prior to calling mDNS_RegisterService();
// all required data is passed as parameters to that function.
void *ServiceContext;
ExtraResourceRecord *Extras; // Optional list of extra AuthRecords attached to this service registration
// need to be re-registered.
// Don't add any fields after AuthRecord RR_TXT.
// This is where the implicit extra space goes if we allocate a ServiceRecordSet containing an oversized RR_TXT record
};
// ***************************************************************************
#if 0
#pragma mark -
#endif
// We record the last eight instances of each duplicate query
// This gives us v4/v6 on each of Ethernet, AirPort and Firewire, and two free slots "for future expansion"
// If the host has more active interfaces that this it is not fatal -- duplicate question suppression will degrade gracefully.
// Since we will still remember the last eight, the busiest interfaces will still get the effective duplicate question suppression.
typedef struct
{
typedef enum
{
} LLQ_State;
// LLQ constants
#define kLLQ_INIT_RESEND 2 // resend an un-ack'd packet after 2 seconds, then double for each additional
// LLQ Operation Codes
// LLQ Errror Codes
enum
{
LLQErr_NoError = 0,
};
#define AutoTunnelUnregistered(X) ( \
// Internal data structure to maintain authentication information
typedef struct DomainAuthInfo
{
AuthRecord AutoTunnelHostRecord; // User-visible hostname; used as SRV target for AutoTunnel services
AuthRecord AutoTunnelTarget; // Opaque hostname of tunnel endpoint; used as SRV target for AutoTunnelService record
AuthRecord AutoTunnelService; // Service record (possibly NAT-Mapped) of IKE daemon implementing tunnel endpoint
// Note: Within an mDNSQuestionCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
// Note: Any value other than QC_rmv i.e., any non-zero value will result in kDNSServiceFlagsAdd to the application
// layer. These values are used within mDNSResponder and not sent across to the application. QC_addnocache is for
// delivering a response without adding to the cache. QC_forceresponse is superset of QC_addnocache where in
// addition to not entering in the cache, it also forces the negative response through.
typedef enum { QC_rmv = 0, QC_add, QC_addnocache, QC_forceresponse, QC_dnssec , QC_nodnssec, QC_suppressed } QC_result;
typedef void mDNSQuestionCallback (mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord);
// q->ValidationStatus is either DNSSECValNotRequired or DNSSECValRequired and then moves onto DNSSECValInProgress.
// When Validation is done, we mark all "DNSSECValInProgress" questions "DNSSECValDone". If we are answering
typedef enum { DNSSECValNotRequired = 0, DNSSECValRequired, DNSSECValInProgress, DNSSECValDone } DNSSECValState;
// ValidationRequired can be set to the following values:
//
// SECURE validation is set to determine whether something is secure or bogus
// INSECURE validation is set internally by dnssec code to indicate that it is currently proving something
// is insecure
// For both ValidationRequired and ValidatingResponse question, we validate DNSSEC responses.
// For ProxyQuestion with DNSSECOK, we just receive the DNSSEC records to pass them along without
// validation and if the CD bit is not set, we also validate.
#define DNSSECQuestion(q) ((q)->ValidationRequired || (q)->ValidatingResponse || ((q)->ProxyQuestion && (q)->ProxyDNSSECOK))
// ValidatingQuestion is used when we need to know whether we are validating the DNSSEC responses for a question
// Given the resource record and the question, should we follow the CNAME ?
// RFC 4122 defines it to be 16 bytes
typedef struct
{
domainname * originalQName; // Name of original A/AAAA record if this question is for a CNAME record.
} uDNSMetrics;
#endif
struct DNSQuestion_struct
{
// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
// ThisQInterval > 0 for an active question;
// ThisQInterval = 0 for a suspended question that's still in the list
// ThisQInterval = -1 for a cancelled question (should not still be in list)
mDNSs32 LastAnswerPktNum; // The sequence number of the last response packet containing an answer to this Q
// set the next question interval to MaxQuestionInterval
mDNSInterfaceID FlappingInterface1; // Set when an interface goes away, to flag if remove events are delivered for this Q
mDNSInterfaceID FlappingInterface2; // Set when an interface goes away, to flag if remove events are delivered for this Q
// because a cached answer needs to be refreshed.
mDNSu32 RequestUnicast; // Non-zero if we want to send query with kDNSQClass_UnicastResponse bit set
// DNSSEC fields
// ValidationRequired question
void *DNSSECAuthInfo;
// Wide Area fields. These are used internally by the uDNS core (Unicast)
mDNSAddr servAddr; // Address and port learned from _dns-llq, _dns-llq-tls or _dns-query-tls SRV query
// by tcpCallback before calling into mDNSCoreReceive
// LLQ-specific fields. These fields are only meaningful when LongLived flag is set
// for TCP: there is some ambiguity in the use of this variable, but in general, it is
// DNS Proxy fields
// till we populate in the cache
// Client API fields: The client must set up these fields *before* calling mDNS_StartQuery()
mDNSInterfaceID InterfaceID; // Non-zero if you want to issue queries only on a single specific IP interface
mDNSBool LongLived; // Set by client for calls to mDNS_StartQuery to indicate LLQs to unicast layer.
mDNSBool ExpectUnique; // Set by client if it's expecting unique RR(s) for this question, not shared RRs
mDNSBool ReturnIntermed; // Set by client to request callbacks for intermediate CNAME/NXDOMAIN results
mDNSu8 RetryWithSearchDomains; // Retry with search domains if there is no entry in the cache or AuthRecords
mDNSu8 uuid[UUID_SIZE]; // Unique ID of the client that is requesting the question (valid only if pid is zero)
void *QuestionContext;
#endif
};
typedef struct
{
// Client API fields: The client must set up name and InterfaceID *before* calling mDNS_StartResolveService()
// When the callback is invoked, ip, port, TXTlen and TXTinfo will have been filled in with the results learned from the network.
} ServiceInfo;
// Note: Within an mDNSServiceInfoQueryCallback mDNS all API calls are legal except mDNS_Init(), mDNS_Exit(), mDNS_Execute()
struct ServiceInfoQuery_struct
{
// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
// No fields need to be set up by the client prior to calling mDNS_StartResolveService();
// all required data is passed as parameters to that function.
// The ServiceInfoQuery structure memory is working storage for mDNSCore to discover the requested information
// and place it in the ServiceInfo structure. After the client has called mDNS_StopResolveService(), it may
// dispose of the ServiceInfoQuery structure while retaining the results in the ServiceInfo structure.
void *ServiceInfoQueryContext;
};
struct ZoneData_struct
{
void *ZoneDataContext;
};
extern ZoneData *StartGetZoneData(mDNS *const m, const domainname *const name, const ZoneService target, ZoneDataCallback callback, void *callbackInfo);
typedef struct DNameListElem
{
// Different states that we go through locating the peer
typedef struct ClientTunnel
{
DNSQuestion q;
} ClientTunnel;
#endif
// ***************************************************************************
#if 0
#pragma mark -
#pragma mark - NetworkInterfaceInfo_struct
#endif
// A NetworkInterfaceInfo_struct serves two purposes:
// 1. It holds the address, PTR and HINFO records to advertise a given IP address on a given physical interface
// 2. It tells mDNSCore which physical interfaces are available; each physical interface has its own unique InterfaceID.
// Since there may be multiple IP addresses on a single physical interface,
// there may be multiple NetworkInterfaceInfo_structs with the same InterfaceID.
// In this case, to avoid sending the same packet n times, when there's more than one
// struct with the same InterfaceID, mDNSCore picks one member of the set to be the
// active representative of the set; all others have the 'InterfaceActive' flag unset.
struct NetworkInterfaceInfo_struct
{
// Internal state fields. These are used internally by mDNSCore; the client layer needn't be concerned with them.
// Standard AuthRecords that every Responder host should have (one per active IP address)
// Client API fields: The client must set up these fields *before* calling mDNS_RegisterInterface()
char ifname[64]; // Windows uses a GUID string for the interface name, which doesn't fit in 16 bytes
// address records
// to Bonjour queries. Generally true for an interface.
};
typedef struct SearchListElem
{
int flag;
int numCfAnswers;
// For domain enumeration and automatic browsing
// This is the user's DNS search list.
// In each of these domains we search for our special pointer records (lb._dns-sd._udp.<domain>, etc.)
// to discover recommended domains for domain enumeration (browse, default browse, registration,
// default registration) and possibly one or more recommended automatic browsing domains.
// ***************************************************************************
#if 0
#pragma mark -
#endif
#ifndef CACHE_HASH_SLOTS
#endif
enum
{
SleepState_Awake = 0,
};
typedef enum
{
typedef enum
{
typedef struct
{
typedef struct
{
extern void LogMDNSStatistics(mDNS *const m);
struct mDNS_struct
{
// Internal state fields. These hold the main internal state of mDNSCore;
// the client layer needn't be concerned with them.
// No fields need to be set up by the client prior to calling mDNS_Init();
// all required data is passed as parameters to that function.
mDNS_PlatformSupport *p; // Pointer to platform-specific data of indeterminite size
mDNSBool DivertMulticastAdvertisements; // from interfaces that do not advertise local addresses to local-only
void *MainContext;
// For debugging: To catch and report locking failures
#ifndef MaxMsg
#endif
// Task Scheduling variables
mDNSu8 LocalRemoveEvents; // Set if we may need to deliver remove events for local-only questions and/or local-only records
mDNSu8 SystemWakeOnLANEnabled; // Set if we want to register with a Sleep Proxy before going to sleep
mDNSu8 SentSleepProxyRegistration; // Set if we registered (or tried to register) with a Sleep Proxy
mDNSu8 SystemSleepOnlyIfWakeOnLAN; // Set if we may only sleep if we managed to register with a Sleep Proxy
// during which underying platform layer should inhibit system sleep
// Only valid if SleepLimit is nonzero and DelaySleep is zero.
// These fields only required for mDNS Searcher...
DNSQuestion *LocalOnlyQuestions; // Questions with InterfaceID set to mDNSInterface_LocalOnly or mDNSInterface_P2P
mDNSu32 rrcache_active; // Number of cache entries currently occupied by records that answer active questions
// Fields below only required for mDNS Responder...
AuthRecord *DuplicateRecords; // Records currently 'on hold' because they are duplicates of existing records
AuthRecord *NewLocalRecords; // Fresh AuthRecords (public) not yet delivered to our local-only questions
mDNSBool NewLocalOnlyRecords; // Fresh AuthRecords (local only) not yet delivered to our local questions
// Unicast-specific data
mDNSu32 WABLBrowseQueriesCount; // Number of legacy WAB Browse domain enumeration queries (lb) callers
mDNSu32 WABRegQueriesCount; // Number of WAB Registration domain enumeration queries (r, dr) callers
// NAT-Traversal fields
mDNSs32 retryIntervalGetAddr; // delta between time sent and retry for NAT-PMP & UPnP/IGD external address request
mDNSs32 retryGetAddr; // absolute time when we retry for NAT-PMP & UPnP/IGD external address request
UDPSocket *NATMcastRecvskt; // For receiving PCP & NAT-PMP announcement multicasts from router on port 5350
mDNSBool SSDPWANPPPConnection; // whether we should send the SSDP query for WANIPConnection or WANPPPConnection
// Sleep Proxy client fields
AuthRecord *SPSRRSet; // To help the client keep track of the records registered with the sleep proxy
// Sleep Proxy Server fields
#ifndef SPC_DISABLED
#endif
mDNSQuestionCallback *SPSBrowseCallback; // So the platform layer can do something useful with SPS browse results
void *WCF;
#endif
// DNS Proxy fields
int notifyToken;
int uds_listener_skt; // Listening socket for incoming UDS clients. This should not be here -- it's private to uds_daemon.c and nothing to do with mDNSCore -- SC
mDNSu32 NumAllInterfaceRecords; // Right now we count *all* multicast records here. Later we may want to change to count interface-specific records separately. (This count includes records on the DuplicateRecords list too.)
mDNSu32 NumAllInterfaceQuestions; // Right now we count *all* multicast questions here. Later we may want to change to count interface-specific questions separately.
// Fixed storage, to avoid creating large objects on the stack
// The imsg is declared as a union with a pointer type to enforce CPU-appropriate alignment
};
// ***************************************************************************
#if 0
#pragma mark -
#endif
extern const mDNSIPPort DiscardPort;
extern const mDNSIPPort SSHPort;
extern const mDNSIPPort UnicastDNSPort;
extern const mDNSIPPort SSDPPort;
extern const mDNSIPPort IPSECPort;
extern const mDNSIPPort NSIPCPort;
extern const mDNSIPPort NATPMPAnnouncementPort;
extern const mDNSIPPort NATPMPPort;
extern const mDNSIPPort DNSEXTPort;
extern const mDNSIPPort MulticastDNSPort;
extern const mDNSIPPort LoopbackIPCPort;
extern const mDNSIPPort PrivateDNSPort;
extern const OwnerOptData zeroOwner;
extern const mDNSIPPort zeroIPPort;
extern const mDNSv4Addr zerov4Addr;
extern const mDNSv6Addr zerov6Addr;
extern const mDNSEthAddr zeroEthAddr;
extern const mDNSv4Addr onesIPv4Addr;
extern const mDNSv6Addr onesIPv6Addr;
extern const mDNSEthAddr onesEthAddr;
extern const mDNSv4Addr AllDNSAdminGroup;
extern const mDNSv4Addr AllHosts_v4;
extern const mDNSv6Addr AllHosts_v6;
extern const mDNSv6Addr NDP_prefix;
extern const mDNSEthAddr AllHosts_v6_Eth;
extern const mDNSAddr AllDNSLinkGroup_v4;
extern const mDNSAddr AllDNSLinkGroup_v6;
extern const mDNSOpaque16 zeroID;
extern const mDNSOpaque16 onesID;
extern const mDNSOpaque16 QueryFlags;
extern const mDNSOpaque16 uQueryFlags;
extern const mDNSOpaque16 DNSSecQFlags;
extern const mDNSOpaque16 ResponseFlags;
extern const mDNSOpaque16 UpdateReqFlags;
extern const mDNSOpaque16 UpdateRespFlags;
extern const mDNSOpaque64 zeroOpaque64;
extern mDNSBool StrictUnicastOrdering;
extern mDNSu8 NumUnicastDNSServers;
extern mDNSu8 NumUnreachableDNSServers;
#endif
// ***************************************************************************
#if 0
#pragma mark -
#endif
#if (defined(_MSC_VER))
#define mDNSinline static inline
#else
#define mDNSinline static inline
#endif
// If we're not doing inline functions, then this header needs to have the extern declarations
#if !defined(mDNSinline)
#endif
// If we're compiling the particular C file that instantiates our inlines, then we
// define "mDNSinline" (to empty string) so that we generate code in the following section
#if (!defined(mDNSinline) && mDNS_InstantiateInlines)
#define mDNSinline
#endif
#ifdef mDNSinline
mDNSinline mDNSu16 mDNSVal16(mDNSOpaque16 x) { return((mDNSu16)((mDNSu16)x.b[0] << 8 | (mDNSu16)x.b[1])); }
{
mDNSOpaque16 x;
x.b[0] = (mDNSu8)(v >> 8);
return(x);
}
#endif
// ***************************************************************************
#if 0
#pragma mark -
#endif
// Every client should call mDNS_Init, passing in storage for the mDNS object and the mDNS_PlatformSupport object.
//
// Clients that are only advertising services should use mDNS_Init_NoCache and mDNS_Init_ZeroCacheSize.
// Clients that plan to perform queries (mDNS_StartQuery, mDNS_StartBrowse, mDNS_StartResolveService, etc.)
// need to provide storage for the resource record cache, or the query calls will return 'mStatus_NoCache'.
// The rrcachestorage parameter is the address of memory for the resource record cache, and
// the rrcachesize parameter is the number of entries in the CacheRecord array passed in.
// (i.e. the size of the cache memory needs to be sizeof(CacheRecord) * rrcachesize).
// OS X 10.3 Panther uses an initial cache size of 64 entries, and then mDNSCore sends an
// mStatus_GrowCache message if it needs more.
//
// Most clients should use mDNS_Init_AdvertiseLocalAddresses. This causes mDNSCore to automatically
// create the correct address records for all the hosts interfaces. If you plan to advertise
// services being offered by the local machine, this is almost always what you want.
// There are two cases where you might use mDNS_Init_DontAdvertiseLocalAddresses:
// 1. A client-only device, that browses for services but doesn't advertise any of its own.
// 2. A proxy-registration service, that advertises services being offered by other machines, and takes
// the appropriate steps to manually create the correct address records for those other machines.
// In principle, a proxy-like registration service could manually create address records for its own machine too,
// but this would be pointless extra effort when using mDNS_Init_AdvertiseLocalAddresses does that for you.
//
// Note that a client-only device that wishes to prohibit multicast advertisements (e.g. from
// higher-layer API calls) must also set DivertMulticastAdvertisements in the mDNS structure and
// advertise local address(es) on a loopback interface.
//
// When mDNS has finished setting up the client's callback is called
// A client can also spin and poll the mDNSPlatformStatus field to see when it changes from mStatus_Waiting to mStatus_NoError
//
// Call mDNS_StartExit to tidy up before exiting
// Because exiting may be an asynchronous process (e.g. if unicast records need to be deregistered)
// client layer may choose to wait until mDNS_ExitNow() returns true before calling mDNS_FinalExit().
//
// Call mDNS_Register with a completed AuthRecord object to register a resource record
// If the resource record type is kDNSRecordTypeUnique (or kDNSknownunique) then if a conflicting resource record is discovered,
// the resource record's mDNSRecordCallback will be called with error code mStatus_NameConflict. The callback should deregister
// the record, and may then try registering the record again after picking a new name (e.g. by automatically appending a number).
// Following deregistration, the RecordCallback will be called with result mStatus_MemFree to signal that it is safe to deallocate
// the record's storage (memory must be freed asynchronously to allow for goodbye packets and dynamic update deregistration).
//
// Call mDNS_StartQuery to initiate a query. mDNS will proceed to issue Multicast DNS query packets, and any time a response
// is received containing a record which matches the question, the DNSQuestion's mDNSAnswerCallback function will be called
// Call mDNS_StopQuery when no more answers are required
//
// Care should be taken on multi-threaded or interrupt-driven environments.
// The main mDNS routines call mDNSPlatformLock() on entry and mDNSPlatformUnlock() on exit;
// each platform layer needs to implement these appropriately for its respective platform.
// For example, if the support code on a particular platform implements timer callbacks at interrupt time, then
// mDNSPlatformLock/Unlock need to disable interrupts or do similar concurrency control to ensure that the mDNS
// code is not entered by an interrupt-time timer callback while in the middle of processing a client call.
// See notes above on use of NoCache/ZeroCacheSize
#define mDNS_Init_ZeroCacheSize 0
// See notes above on use of Advertise/DontAdvertiseLocalAddresses
extern void mDNS_ConfigChanged(mDNS *const m);
extern void mDNS_StartExit (mDNS *const m);
extern void mDNS_FinalExit (mDNS *const m);
extern void mDNS_UpdateAllowSleep(mDNS *const m);
// ***************************************************************************
#if 0
#pragma mark -
#endif
extern mDNSs32 mDNSPlatformOneSecond;
// ***************************************************************************
#if 0
#pragma mark -
#endif
// mDNS_Dereg_normal is used for most calls to mDNS_Deregister_internal
// mDNS_Dereg_rapid is used to send one goodbye instead of three, when we want the memory available for reuse sooner
// mDNS_Dereg_conflict is used to indicate that this record is being forcibly deregistered because of a conflict
// mDNS_Dereg_repeat is used when cleaning up, for records that may have already been forcibly deregistered
typedef enum { mDNS_Dereg_normal, mDNS_Dereg_rapid, mDNS_Dereg_conflict, mDNS_Dereg_repeat } mDNS_Dereg_type;
// mDNS_RegisterService is a single call to register the set of resource records associated with a given named service.
//
// mDNS_StartResolveService is single call which is equivalent to multiple calls to mDNS_StartQuery,
// to find the IP address, port number, and demultiplexing information for a given named service.
// As with mDNS_StartQuery, it executes asynchronously, and calls the ServiceInfoQueryCallback when the answer is
// found. After the service is resolved, the client should call mDNS_StopResolveService to complete the transaction.
// The client can also call mDNS_StopResolveService at any time to abort the transaction.
//
// mDNS_AddRecordToService adds an additional record to a Service Record Set. This record may be deregistered
// via mDNS_RemoveRecordFromService, or by deregistering the service. mDNS_RemoveRecordFromService is passed a
// callback to free the memory associated with the extra RR when it is safe to do so. The ExtraResourceRecord
// object can be found in the record's context pointer.
// mDNS_GetBrowseDomains is a special case of the mDNS_StartQuery call, where the resulting answers
// are a list of PTR records indicating (in the rdata) domains that are recommended for browsing.
// After getting the list of domains to browse, call mDNS_StopQuery to end the search.
// mDNS_GetDefaultBrowseDomain returns the name of the domain that should be highlighted by default.
//
// mDNS_GetRegistrationDomains and mDNS_GetDefaultRegistrationDomain are the equivalent calls to get the list
// of one or more domains that should be offered to the user as choices for where they may register their service,
// and the default domain in which to register in the case where the user has made no selection.
extern void mDNS_SetupResourceRecord(AuthRecord *rr, RData *RDataStorage, mDNSInterfaceID InterfaceID,
mDNSu16 rrtype, mDNSu32 ttl, mDNSu8 RecordType, AuthRecType artype, mDNSRecordCallback Callback, void *Context);
// mDNS_RegisterService() flags parameter bit definitions.
// Note these are only defined to transfer the corresponding DNSServiceFlags settings into mDNSCore routines,
// since code in mDNSCore does not include the DNSServiceFlags definitions in dns_sd.h.
enum
{
};
extern mStatus mDNS_AddRecordToService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, RData *rdata, mDNSu32 ttl, mDNSu32 flags);
extern mStatus mDNS_RemoveRecordFromService(mDNS *const m, ServiceRecordSet *sr, ExtraResourceRecord *extra, mDNSRecordCallback MemFreeCallback, void *Context);
extern mStatus mDNS_RenameAndReregisterService(mDNS *const m, ServiceRecordSet *const sr, const domainlabel *newname);
extern mStatus mDNS_DeregisterService_drt(mDNS *const m, ServiceRecordSet *sr, mDNS_Dereg_type drt);
const domainname *const host,
extern void mDNS_SetupQuestion(DNSQuestion *const q, const mDNSInterfaceID InterfaceID, const domainname *const name,
extern mStatus mDNS_StartResolveService(mDNS *const m, ServiceInfoQuery *query, ServiceInfo *info, mDNSServiceInfoQueryCallback *Callback, void *Context);
typedef enum
{
extern const char *const mDNS_DomainTypeNames[];
extern mStatus mDNS_GetDomains(mDNS *const m, DNSQuestion *const question, mDNS_DomainType DomainType, const domainname *dom,
extern mStatus mDNS_AdvertiseDomains(mDNS *const m, AuthRecord *rr, mDNS_DomainType DomainType, const mDNSInterfaceID InterfaceID, char *domname);
extern mDNSBool mDNS_AddressIsLocalSubnet(mDNS *const m, const mDNSInterfaceID InterfaceID, const mDNSAddr *addr);
// ***************************************************************************
#if 0
#pragma mark -
#endif
// In order to expose the full capabilities of the DNS protocol (which allows any arbitrary eight-bit values
// in domain name labels, including unlikely characters like ascii nulls and even dots) all the mDNS APIs
// work with DNS's native length-prefixed strings. For convenience in C, the following utility functions
// are provided for converting between C's null-terminated strings and DNS's length-prefixed strings.
// Assignment
// A simple C structure assignment of a domainname can cause a protection fault by accessing unmapped memory,
// because that object is defined to be 256 bytes long, but not all domainname objects are truly the full size.
// This macro uses mDNSPlatformMemCopy() to make sure it only touches the actual bytes that are valid.
if (len__ <= MAX_DOMAIN_NAME) mDNSPlatformMemCopy((DST)->c, (SRC)->c, len__);else (DST)->c[0] = 0;} while(0)
// Comparison functions
extern mDNSBool IsLocalDomain(const domainname *d); // returns true for domains that by default should be looked up using link-local multicast
// Get total length of domain name, in native DNS format, including terminal root label
// (e.g. length of "com." is 5 (length byte, three data bytes, final zero)
// Append functions to append one or more labels to an existing native format domain name:
// AppendLiteralLabelString adds a single label from a literal C string, with no escape character interpretation.
// AppendDNSNameString adds zero or more labels from a C string using conventional DNS dots-and-escaping interpretation
// AppendDomainLabel adds a single label from a native format domainlabel
// AppendDomainName adds zero or more labels from a native format domainname
// Convert from null-terminated string to native DNS format:
// The DomainLabel form makes a single label from a literal C string, with no escape character interpretation.
// The DomainName form makes native format domain name from a C string using conventional DNS interpretation:
// dots separate labels, and within each label, '\.' represents a literal dot, '\\' represents a literal
// backslash and backslash with three decimal digits (e.g. \000) represents an arbitrary byte value.
// Convert native format domainlabel or domainname back to C string format
// IMPORTANT:
// When using ConvertDomainLabelToCString, the target buffer must be MAX_ESCAPED_DOMAIN_LABEL (254) bytes long
// to guarantee there will be no buffer overrun. It is only safe to use a buffer shorter than this in rare cases
// where the label is known to be constrained somehow (for example, if the label is known to be either "_tcp" or "_udp").
// Similarly, when using ConvertDomainNameToCString, the target buffer must be MAX_ESCAPED_DOMAIN_NAME (1009) bytes long.
// See definitions of MAX_ESCAPED_DOMAIN_LABEL and MAX_ESCAPED_DOMAIN_NAME for more detailed explanation.
extern char *ConvertDomainLabelToCString_withescape(const domainlabel *const name, char *cstr, char esc);
#define ConvertDomainLabelToCString_unescaped(D,C) ConvertDomainLabelToCString_withescape((D), (C), 0)
extern char *ConvertDomainNameToCString_withescape(const domainname *const name, char *cstr, char esc);
#define ConvertDomainNameToCString_unescaped(D,C) ConvertDomainNameToCString_withescape((D), (C), 0)
extern void ConvertUTF8PstringToRFC1034HostLabel(const mDNSu8 UTF8Name[], domainlabel *const hostlabel);
extern mDNSu8 *ConstructServiceName(domainname *const fqdn, const domainlabel *name, const domainname *type, const domainname *const domain);
extern mDNSBool DeconstructServiceName(const domainname *const fqdn, domainlabel *const name, domainname *const type, domainname *const domain);
// Note: Some old functions have been replaced by more sensibly-named versions.
// You can uncomment the hash-defines below if you don't want to have to change your source code right away.
// When updating your code, note that (unlike the old versions) *all* the new routines take the target object
// as their first parameter.
//#define ConvertCStringToDomainName(SRC,DST) MakeDomainNameFromDNSNameString((DST),(SRC))
//#define ConvertCStringToDomainLabel(SRC,DST) MakeDomainLabelFromLiteralString((DST),(SRC))
//#define AppendStringLabelToName(DST,SRC) AppendLiteralLabelString((DST),(SRC))
//#define AppendStringNameToName(DST,SRC) AppendDNSNameString((DST),(SRC))
//#define AppendDomainLabelToName(DST,SRC) AppendDomainLabel((DST),(SRC))
//#define AppendDomainNameToName(DST,SRC) AppendDomainName((DST),(SRC))
// ***************************************************************************
#if 0
#pragma mark -
#endif
// mDNS_vsnprintf/snprintf return the number of characters written, excluding the final terminating null.
// The output is always null-terminated: for example, if the output turns out to be exactly buflen long,
// then the output will be truncated by one character to allow space for the terminating null.
// not the number of characters that *would* have been printed were buflen unlimited.
extern mDNSu32 mDNS_snprintf(char *sbuffer, mDNSu32 buflen, const char *fmt, ...) IS_A_PRINTF_STYLE_FUNCTION(3,4);
extern char *GetRRDisplayString_rdb(const ResourceRecord *const rr, const RDataBody *const rd1, char *const buffer);
#define ARDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
#define CRDisplayString(m, rr) GetRRDisplayString_rdb(&(rr)->resrec, &(rr)->resrec.rdata->u, (m)->MsgBuffer)
extern mDNSBool mDNSv4AddrIsRFC1918(const mDNSv4Addr * const addr); // returns true for RFC1918 private addresses
// For PCP
#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])
#define mDNSSameEthAddress(A,B) ((A)->w[0] == (B)->w[0] && (A)->w[1] == (B)->w[1] && (A)->w[2] == (B)->w[2])
#define mDNSAddressIsAllDNSLinkGroup(X) ( \
#define mDNSAddressIsZero(X) ( \
#define mDNSAddressIsValidNonZero(X) ( \
#define mDNSAddressIsOnes(X) ( \
#define mDNSAddressIsValid(X) ( \
((X)->type == mDNSAddrType_IPv4) ? !(mDNSIPv4AddressIsZero((X)->ip.v4) || mDNSIPv4AddressIsOnes((X)->ip.v4)) : \
((X)->type == mDNSAddrType_IPv6) ? !(mDNSIPv6AddressIsZero((X)->ip.v6) || mDNSIPv6AddressIsOnes((X)->ip.v6)) : mDNSfalse)
#define mDNSAddressIsLinkLocal(X) ( \
#define mDNSv4AddressIsLoopback(X) ((X)->b[0] == 127 && (X)->b[1] == 0 && (X)->b[2] == 0 && (X)->b[3] == 1)
#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))
#define mDNSAddressIsLoopback(X) ( \
// ***************************************************************************
#if 0
#pragma mark -
#endif
// Unicast DNS and Dynamic Update specific Client Calls
//
// mDNS_SetSecretForDomain tells the core to authenticate (via TSIG with an HMAC_MD5 hash of the shared secret)
// when dynamically updating a given zone (and its subdomains). The key used in authentication must be in
// domain name format. The shared secret must be a null-terminated base64 encoded string. A minimum size of
// 16 bytes (128 bits) is recommended for an MD5 hash as per RFC 2485.
// Calling this routine multiple times for a zone replaces previously entered values. Call with a NULL key
// to disable authentication for the zone. A non-NULL autoTunnelPrefix means this is an AutoTunnel domain,
// and the value is prepended to the IPSec identifier (used for key lookup)
const domainname *domain, const domainname *keyname, const char *b64keydata, const domainname *hostname, mDNSIPPort *port, mDNSBool autoTunnel);
// All hostnames advertised point to one IPv4 address and/or one IPv6 address, set via SetPrimaryInterfaceInfo. Invoking this routine
// updates all existing hostnames to point to the new address.
// A hostname is added via AddDynDNSHostName, which points to the primary interface's v4 and/or v6 addresss
// The status callback is invoked to convey success or failure codes - the callback should not modify the AuthRecord or free memory.
// Added hostnames may be removed (deregistered) via mDNS_RemoveDynDNSHostName.
// Host domains added prior to specification of the primary interface address and computer name will be deferred until
// these values are initialized.
// DNS servers used to resolve unicast queries are specified by mDNS_AddDNSServer.
// For "split" DNS configurations, in which queries for different domains are sent to different servers (e.g. VPN and external),
// a domain may be associated with a DNS server. For standard configurations, specify the root label (".") or NULL.
extern void mDNS_AddDynDNSHostName(mDNS *m, const domainname *fqdn, mDNSRecordCallback *StatusCallback, const void *StatusContext);
extern void mDNS_SetPrimaryInterfaceInfo(mDNS *m, const mDNSAddr *v4addr, const mDNSAddr *v6addr, const mDNSAddr *router);
extern DNSServer *mDNS_AddDNSServer(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSs32 serviceID, const mDNSAddr *addr,
const mDNSIPPort port, mDNSu32 scoped, mDNSu32 timeout, mDNSBool cellIntf, mDNSu16 resGroupID, mDNSBool reqA,
extern McastResolver *mDNS_AddMcastResolver(mDNS *const m, const domainname *d, const mDNSInterfaceID interface, mDNSu32 timeout);
// We use ((void *)0) here instead of mDNSNULL to avoid compile warnings on gcc 4.2
#define mDNS_AddSearchDomain_CString(X, I) \
do { domainname d__; if (((X) != (void*)0) && MakeDomainNameFromDNSNameString(&d__, (X)) && d__.c[0]) mDNS_AddSearchDomain(&d__, I);} while(0)
// Routines called by the core, exported by DNSDigest.c
// Convert an arbitrary base64 encoded key key into an HMAC key (stored in AuthInfo struct)
// sign a DNS message. The message must be complete, with all values in network byte order. end points to the end
// of the message, and is modified by this routine. numAdditionals is a pointer to the number of additional
// records in HOST byte order, which is incremented upon successful completion of this routine. The function returns
// the new end pointer on success, and NULL on failure.
extern void DNSDigest_SignMessage(DNSMessage *msg, mDNSu8 **end, DomainAuthInfo *info, mDNSu16 tcode);
#define SwapDNSHeaderBytes(M) do { \
(M)->h.numQuestions = (mDNSu16)((mDNSu8 *)&(M)->h.numQuestions )[0] << 8 | ((mDNSu8 *)&(M)->h.numQuestions )[1]; \
(M)->h.numAnswers = (mDNSu16)((mDNSu8 *)&(M)->h.numAnswers )[0] << 8 | ((mDNSu8 *)&(M)->h.numAnswers )[1]; \
(M)->h.numAuthorities = (mDNSu16)((mDNSu8 *)&(M)->h.numAuthorities)[0] << 8 | ((mDNSu8 *)&(M)->h.numAuthorities)[1]; \
(M)->h.numAdditionals = (mDNSu16)((mDNSu8 *)&(M)->h.numAdditionals)[0] << 8 | ((mDNSu8 *)&(M)->h.numAdditionals)[1]; \
} while (0)
do { SwapDNSHeaderBytes(M); DNSDigest_SignMessage((M), (E), (INFO), 0); SwapDNSHeaderBytes(M); } while (0)
// verify a DNS message. The message must be complete, with all values in network byte order. end points to the
// end of the record. tsig is a pointer to the resource record that contains the TSIG OPT record. info is
// the matching key to use for verifying the message. This function expects that the additionals member
// of the DNS message header has already had one subtracted from it.
extern mDNSBool DNSDigest_VerifyMessage(DNSMessage *msg, mDNSu8 *end, LargeCacheRecord *tsig, DomainAuthInfo *info, mDNSu16 *rcode, mDNSu16 *tcode);
// ***************************************************************************
#if 0
#pragma mark -
#endif
// This section defines the interface to the Platform Support layer.
// Normal client code should not use any of types defined here, or directly call any of the functions defined here.
// The definitions are placed here because sometimes clients do use these calls indirectly, via other supported client operations.
// For example, AssignDomainName is a macro defined using mDNSPlatformMemCopy()
// Every platform support module must provide the following functions.
// mDNSPlatformInit() typically opens a communication endpoint, and starts listening for mDNS packets.
// When Setup is complete, the platform support layer calls mDNSCoreInitComplete().
// mDNSPlatformSendUDP() sends one UDP packet
// When a packet is received, the PlatformSupport code calls mDNSCoreReceive()
// mDNSPlatformClose() tidies up on exit
//
// Note: mDNSPlatformMemAllocate/mDNSPlatformMemFree are only required for handling oversized resource records and unicast DNS.
// If your target platform has a well-defined specialized application, and you know that all the records it uses
// are InlineCacheRDSize or less, then you can just make a simple mDNSPlatformMemAllocate() stub that always returns
// NULL. InlineCacheRDSize is a compile-time constant, which is set by default to 68. If you need to handle records
// a little larger than this and you don't want to have to implement run-time allocation and freeing, then you
// can raise the value of this constant to a suitable value (at the expense of increased memory usage).
//
// USE CAUTION WHEN CALLING mDNSPlatformRawTime: The m->timenow_adjust correction factor needs to be added
// Generally speaking:
// Code that's protected by the main mDNS lock should just use the m->timenow value
// Code outside the main mDNS lock should use mDNS_TimeNow(m) to get properly adjusted time
// In certain cases there may be reasons why it's necessary to get the time without taking the lock first
// (e.g. inside the routines that are doing the locking and unlocking, where a call to get the lock would result in a
// recursive loop); in these cases use mDNS_TimeNow_NoLock(m) to get mDNSPlatformRawTime with the proper correction factor added.
//
// mDNSPlatformUTC returns the time, in seconds, since Jan 1st 1970 UTC and is required for generating TSIG records
extern void mDNSPlatformClose (mDNS *const m);
extern mStatus mDNSPlatformSendUDP(const mDNS *const m, const void *const msg, const mDNSu8 *const end,
extern void mDNSPlatformLock (const mDNS *const m);
extern void mDNSPlatformUnlock (const mDNS *const m);
extern void mDNSPlatformQsort (void *base, int nel, int width, int (*compar)(const void *, const void *));
#else
#endif
extern void mDNSPlatformMemFree (void *mem);
// If the platform doesn't have a strong PRNG, we define a naive multiply-and-add based on a seed
// from the platform layer. Long-term, we should embed an arc4 implementation, but the strength
// will still depend on the randomness of the seed.
#endif
extern mDNSu32 mDNSPlatformRandomNumber(void);
#else
extern mDNSu32 mDNSPlatformRandomSeed (void);
#endif // _PLATFORM_HAS_STRONG_PRNG_
extern mStatus mDNSPlatformTimeInit (void);
extern mDNSs32 mDNSPlatformRawTime (void);
extern mDNSs32 mDNSPlatformUTC (void);
#if MDNS_DEBUGMSGS
extern void mDNSPlatformWriteDebugMsg(const char *msg);
#endif
// Utility function for ASL logging
mDNSexport void mDNSASLLog(uuid_t *uuid, const char *subdomain, const char *result, const char *signature, const char *fmt, ...);
// Log unicast and multicast traffic statistics once a day. Also used for DNSSEC statistics.
extern void mDNSLogStatistics(mDNS *const m);
#endif // APPLE_OSX_mDNSResponder
// Platform support modules should provide the following functions to map between opaque interface IDs
// and interface indexes in order to support the DNS-SD API. If your target platform does not support
extern mDNSu32 mDNSPlatformInterfaceIndexfromInterfaceID(mDNS *const m, mDNSInterfaceID id, mDNSBool suppressNetworkChange);
// Every platform support module must provide the following functions if it is to support unicast DNS
// and Dynamic Update.
// All TCP socket operations implemented by the platform layer MUST NOT BLOCK.
// mDNSPlatformTCPConnect initiates a TCP connection with a peer, adding the socket descriptor to the
// main event loop. The return value indicates whether the connection succeeded, failed, or is pending
// (i.e. the call would block.) On return, the descriptor parameter is set to point to the connected socket.
// The TCPConnectionCallback is subsequently invoked when the connection
// completes (in which case the ConnectionEstablished parameter is true), or data is available for
// reading on the socket (indicated by the ConnectionEstablished parameter being false.) If the connection
// asynchronously fails, the TCPConnectionCallback should be invoked as usual, with the error being
// returned in subsequent calls to PlatformReadTCP or PlatformWriteTCP. (This allows for platforms
// with limited asynchronous error detection capabilities.) PlatformReadTCP and PlatformWriteTCP must
// return the number of bytes read/written, 0 if the call would block, and -1 if an error. PlatformReadTCP
// should set the closed argument if the socket has been closed.
// PlatformTCPCloseConnection must close the connection to the peer and remove the descriptor from the
// event loop. CloseConnectin may be called at any time, including in a ConnectionCallback.
typedef enum
{
kTCPSocketFlags_Zero = 0,
typedef void (*TCPConnectionCallback)(TCPSocket *sock, void *context, mDNSBool ConnectionEstablished, mStatus err);
extern TCPSocket *mDNSPlatformTCPSocket(mDNS *const m, TCPSocketFlags flags, mDNSIPPort *port, mDNSBool useBackgroundTrafficClass); // creates a TCP socket
extern mStatus mDNSPlatformTCPConnect(TCPSocket *sock, const mDNSAddr *dst, mDNSOpaque16 dstport, domainname *hostname,
extern long mDNSPlatformReadTCP(TCPSocket *sock, void *buf, unsigned long buflen, mDNSBool *closed);
extern void mDNSPlatformSendRawPacket(const void *const msg, const mDNSu8 *const end, mDNSInterfaceID InterfaceID);
extern void mDNSPlatformSetLocalAddressCacheEntry(mDNS *const m, const mDNSAddr *const tpa, const mDNSEthAddr *const tha, mDNSInterfaceID InterfaceID);
extern void mDNSPlatformSendKeepalive(mDNSAddr *sadd, mDNSAddr *dadd, mDNSIPPort *lport, mDNSIPPort *rport, mDNSu32 seq, mDNSu32 ack, mDNSu16 win);
extern mStatus mDNSPlatformRetrieveTCPInfo(mDNS *const m, mDNSAddr *laddr, mDNSIPPort *lport, mDNSAddr *raddr, mDNSIPPort *rport, mDNSTCPInfo *mti);
extern mStatus mDNSPlatformClearSPSMACAddr(void);
// mDNSPlatformTLSSetupCerts/mDNSPlatformTLSTearDownCerts used by dnsextd
extern mStatus mDNSPlatformTLSSetupCerts(void);
extern void mDNSPlatformTLSTearDownCerts(void);
// Platforms that support unicast browsing and dynamic update registration for clients who do not specify a domain
// in browse/registration calls must implement these routines to get the "default" browse/registration list.
extern mDNSBool mDNSPlatformSetDNSConfig(mDNS *const m, mDNSBool setservers, mDNSBool setsearch, domainname *const fqdn, DNameListElem **RegDomains,
extern mStatus mDNSPlatformGetPrimaryInterface(mDNS *const m, mDNSAddr *v4, mDNSAddr *v6, mDNSAddr *router);
extern void mDNSPlatformDynDNSHostNameStatusChanged(const domainname *const dname, const mStatus status);
extern void mDNSPlatformSendWakeupPacket(mDNS *const m, mDNSInterfaceID InterfaceID, char *EthAddr, char *IPAddr, int iteration);
extern mDNSBool mDNSPlatformValidRecordForQuestion(const ResourceRecord *const rr, const DNSQuestion *const q);
extern mDNSBool mDNSPlatformValidRecordForInterface(AuthRecord *rr, const NetworkInterfaceInfo *intf);
extern mDNSBool mDNSPlatformValidQuestionForInterface(DNSQuestion *q, const NetworkInterfaceInfo *intf);
#ifdef _LEGACY_NAT_TRAVERSAL_
// Support for legacy NAT traversal protocols, implemented by the platform layer and callable by the core.
extern void LNT_SendDiscoveryMsg(mDNS *m);
extern void LNT_ConfigureRouterInfo(mDNS *m, const mDNSInterfaceID InterfaceID, const mDNSu8 *const data, const mDNSu16 len);
extern void LNT_ClearState(mDNS *const m);
#endif // _LEGACY_NAT_TRAVERSAL_
// The core mDNS code provides these functions, for the platform support code to call at appropriate times
//
// mDNS_SetFQDN() is called once on startup (typically from mDNSPlatformInit())
// and then again on each subsequent change of the host name.
//
// mDNS_RegisterInterface() is used by the platform support layer to inform mDNSCore of what
// Typically it is called on startup for each available interface, but register/deregister may be
// called again later, on multiple occasions, to inform the core of interface configuration changes.
// If set->Advertise is set non-zero, then mDNS_RegisterInterface() also registers the standard
// -- Address-to-name records (PTR)
// -- Host information (HINFO)
// IMPORTANT: The specified mDNSInterfaceID MUST NOT be 0, -1, or -2; these values have special meaning
// mDNS_RegisterInterface does not result in the registration of global hostnames via dynamic update -
// see mDNS_SetPrimaryInterfaceInfo, mDNS_AddDynDNSHostName, etc. for this purpose.
// Note that the set may be deallocated immediately after it is deregistered via mDNS_DeegisterInterface.
//
// mDNS_RegisterDNS() is used by the platform support layer to provide the core with the addresses of
// available domain name servers for unicast queries/updates. RegisterDNS() should be called once for
// each name server, typically at startup, or when a new name server becomes available. DeregiterDNS()
// must be called whenever a registered name server becomes unavailable. DeregisterDNSList deregisters
// all registered servers. mDNS_DNSRegistered() returns true if one or more servers are registered in the core.
//
// mDNSCoreInitComplete() is called when the platform support layer is finished.
// Typically this is at the end of mDNSPlatformInit(), but may be later
// (on platforms like OT that allow asynchronous initialization of the networking stack).
//
// mDNSCoreReceive() is called when a UDP packet is received
//
// mDNSCoreMachineSleep() is called when the machine sleeps or wakes
// not lightweight second-by-second CPU power management modes.)
extern void mDNS_SetFQDN(mDNS *const m);
extern mStatus mDNS_RegisterInterface (mDNS *const m, NetworkInterfaceInfo *set, mDNSBool flapping);
extern void mDNSCoreRestartQueries(mDNS *const m);
extern void mDNSCoreRestartAddressQueries(mDNS *const m, mDNSBool SearchDomainsChanged, FlushCache flushCacheRecords,
extern void mDNSCoreReceiveRawPacket (mDNS *const m, const mDNSu8 *const p, const mDNSu8 *const end, const mDNSInterfaceID InterfaceID);
extern CacheRecord *CreateNewCacheEntry(mDNS *const m, const mDNSu32 slot, CacheGroup *cg, mDNSs32 delay, mDNSBool Add, const mDNSAddr *sourceAddress);
extern CacheGroup *CacheGroupForName(const mDNS *const m, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name);
const domainname *const name, const mDNSu32 namehash, const mDNSu16 rrtype, const mDNSu16 rrclass, mDNSu32 ttl_seconds,
extern void AnswerCurrentQuestionWithResourceRecord(mDNS *const m, CacheRecord *const rr, const QC_result AddRecord);
extern void CheckSuppressUnusableQuestions(mDNS *const m);
extern void RetrySearchDomainQuestions(mDNS *const m);
extern mStatus UpdateKeepaliveRData(mDNS *const m, AuthRecord *rr, NetworkInterfaceInfo *const intf, mDNSBool updateMac, char *ethAddr);
extern AuthGroup *AuthGroupForName(AuthHash *r, const mDNSu32 slot, const mDNSu32 namehash, const domainname *const name);
extern AuthGroup *AuthGroupForRecord(AuthHash *r, const mDNSu32 slot, const ResourceRecord *const rr);
// For now this AutoTunnel stuff is specific to Mac OS X.
// In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
extern void AutoTunnelCallback(mDNS *const m, DNSQuestion *question, const ResourceRecord *const answer, QC_result AddRecord);
extern void UpdateAutoTunnelDomainStatuses(const mDNS *const m);
extern void RemoveAutoTunnel6Record(mDNS *const m);
// For now this LocalSleepProxy stuff is specific to Mac OS X.
// In the future, if there's demand, we may see if we can abstract it out cleanly into the platform layer
extern mStatus ActivateLocalProxy(mDNS *const m, NetworkInterfaceInfo *const intf, mDNSBool *keepaliveOnly);
#endif
typedef void ProxyCallback (mDNS *const m, void *socket, void *const msg, const mDNSu8 *const end, const mDNSAddr *const srcaddr,
const mDNSIPPort srcport, const mDNSAddr *dstaddr, const mDNSIPPort dstport, const mDNSInterfaceID InterfaceID, void *context);
extern void mDNSPlatformInitDNSProxySkts(mDNS *const m, ProxyCallback *UDPCallback, ProxyCallback *TCPCallback);
extern void mDNSPlatformCloseDNSProxySkts(mDNS *const m);
extern void mDNSPlatformDisposeProxyContext(void *context);
extern mDNSu8 *DNSProxySetAttributes(DNSQuestion *q, DNSMessageHeader *h, DNSMessage *msg, mDNSu8 *start, mDNSu8 *limit);
// Sleep Assertions are specific to Mac OS X
#endif
extern mDNSs32 mDNSPlatformGetPID(void);
// ***************************************************************************
#if 0
#pragma mark -
#endif
// Sleep Proxy Server Property Encoding
//
// Sleep Proxy Servers are advertised using a structured service name, consisting of four
// metrics followed by a human-readable name. The metrics assist clients in deciding which
// Sleep Proxy Server(s) to use when multiple are available on the network. Each metric
// is a two-digit decimal number in the range 10-99. Lower metrics are generally better.
//
// AA-BB-CC-DD.FF Name
//
// Metrics:
//
// AA = Intent
// BB = Portability
// CC = Marginal Power
// DD = Total Power
// FF = Features Supported (Currently TCP Keepalive only)
//
//
// ** Intent Metric **
//
// 20 = Dedicated Sleep Proxy Server -- a device, permanently powered on,
// installed for the express purpose of providing Sleep Proxy Service.
//
// 30 = Primary Network Infrastructure Hardware -- a router, DHCP server, NAT gateway,
// or similar permanently installed device which is permanently powered on.
// This is hardware designed for the express purpose of being network
// infrastructure, and for most home users is typically a single point
// of failure for the local network -- e.g. most home users only have
// a single NAT gateway / DHCP server. Even though in principle the
// hardware might technically be capable of running different software,
// a typical user is unlikely to do that. e.g. AirPort base station.
//
// 40 = Primary Network Infrastructure Software -- a general-purpose computer
// (e.g. Mac, Windows, Linux, etc.) which is currently running DHCP server
// or NAT gateway software, but the user could choose to turn that off
// fairly easily. e.g. iMac running Internet Sharing
//
// 50 = Secondary Network Infrastructure Hardware -- like primary infrastructure
// hardware, except not a single point of failure for the entire local network.
// For example, an AirPort base station in bridge mode. This may have clients
// associated with it, and if it goes away those clients will be inconvenienced,
// but unlike the NAT gateway / DHCP server, the entire local network is not
// dependent on it.
//
// 60 = Secondary Network Infrastructure Software -- like 50, but in a general-
// purpose CPU.
//
// 70 = Incidentally Available Hardware -- a device which has no power switch
// and is generally left powered on all the time. Even though it is not a
// part of what we conventionally consider network infrastructure (router,
// DHCP, NAT, DNS, etc.), and the rest of the network can operate fine
// without it, since it's available and unlikely to be turned off, it is a
// reasonable candidate for providing Sleep Proxy Service e.g. Apple TV,
// or an AirPort base station in client mode, associated with an existing
// wireless network (e.g. AirPort Express connected to a music system, or
// being used to share a USB printer).
//
// 80 = Incidentally Available Software -- a general-purpose computer which
// happens at this time to be set to "never sleep", and as such could be
// useful as a Sleep Proxy Server, but has not been intentionally provided
// for this purpose. Of all the Intent Metric categories this is the
// one most likely to be shut down or put to sleep without warning.
// However, if nothing else is availalable, it may be better than nothing.
// e.g. Office computer in the workplace which has been set to "never sleep"
//
//
// ** Portability Metric **
//
// Inversely related to mass of device, on the basis that, all other things
// being equal, heavier devices are less likely to be moved than lighter devices.
// E.g. A MacBook running Internet Sharing is probably more likely to be
// put to sleep and taken away than a Mac Pro running Internet Sharing.
// The Portability Metric is a logarithmic decibel scale, computed by taking the
// (approximate) mass of the device in milligrammes, taking the base 10 logarithm
// of that, multiplying by 10, and subtracting the result from 100:
//
// Portability Metric = 100 - (log10(mg) * 10)
//
// The Portability Metric is not necessarily computed literally from the actual
// mass of the device; the intent is just that lower numbers indicate more
// permanent devices, and higher numbers indicate devices more likely to be
// removed from the network, e.g., in order of increasing portability:
//
// Mac Pro < iMac < Laptop < iPhone
//
// Example values:
//
// 10 = 1 metric tonne
// 40 = 1kg
// 70 = 1g
// 90 = 10mg
//
//
// ** Marginal Power and Total Power Metrics **
//
// The Marginal Power Metric is the power difference between sleeping and staying awake
// to be a Sleep Proxy Server.
//
// The Total Power Metric is the total power consumption when being Sleep Proxy Server.
//
// The Power Metrics use a logarithmic decibel scale, computed as ten times the
// base 10 logarithm of the (approximate) power in microwatts:
//
// Power Metric = log10(uW) * 10
//
// Higher values indicate higher power consumption. Example values:
//
// 10 = 10 uW
// 20 = 100 uW
// 30 = 1 mW
// 60 = 1 W
// 90 = 1 kW
typedef enum
{
typedef enum
{
extern void mDNSCoreBeSleepProxyServer_internal(mDNS *const m, mDNSu8 sps, mDNSu8 port, mDNSu8 marginalpower, mDNSu8 totpower, mDNSu8 features);
do { mDNS_Lock(m); mDNSCoreBeSleepProxyServer_internal((M),(S),(P),(MP),(TP),(F)); mDNS_Unlock(m); } while(0)
(X)[6] == '-' && (X)[ 7] == '9' && (X)[ 8] == '9' && \
(X)[9] == '-' && (X)[10] == '9' && (X)[11] == '9' )
#define ValidSPSName(X) ((X)[0] >= 5 && mDNSIsDigit((X)[1]) && mDNSIsDigit((X)[2]) && mDNSIsDigit((X)[4]) && mDNSIsDigit((X)[5]))
((X)[1]-'0') * 100000 + ((X)[2]-'0') * 10000 + ((X)[4]-'0') * 1000 + ((X)[5]-'0') * 100 + ((X)[7]-'0') * 10 + ((X)[8]-'0'))
#define LocalSPSMetric(X) ( (X)->SPSType * 10000 + (X)->SPSPortability * 100 + (X)->SPSMarginalPower)
typedef struct MD5state_st
{
mDNSu32 A,B,C,D;
int num;
} MD5_CTX;
// ***************************************************************************
#if 0
#pragma mark -
#endif
// Some C compiler cleverness. We can make the compiler check certain things for
// us, and report compile-time errors if anything is wrong. The usual way to do
// this would be to use a run-time "if" statement, but then you don't find out
// what's wrong until you run the software. This way, if the assertion condition
// is false, the array size is negative, and the complier complains immediately.
{
// Check that the compiler generated our on-the-wire packet format structure definitions
// properly packed, without adding padding bytes to align fields on 32-bit or 64-bit boundaries.
// Check our structures are reasonable sizes. Including overly-large buffers, or embedding
// other overly-large structures instead of having a pointer to them, can inadvertently
// cause structure sizes (and therefore memory usage) to balloon unreasonably.
#endif
};
// Routine to initialize device-info TXT record contents
#endif
// ***************************************************************************
#ifdef __cplusplus
}
#endif
#endif