]> git.saurik.com Git - apple/mdnsresponder.git/blob - mDNSCore/DNSCommon.h
mDNSResponder-878.270.2.tar.gz
[apple/mdnsresponder.git] / mDNSCore / DNSCommon.h
1 /* -*- Mode: C; tab-width: 4 -*-
2 *
3 * Copyright (c) 2002-2018 Apple Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #ifndef __DNSCOMMON_H_
19 #define __DNSCOMMON_H_
20
21 #include "mDNSEmbeddedAPI.h"
22
23 #ifdef __cplusplus
24 extern "C" {
25 #endif
26
27 //*************************************************************************************************************
28 // Macros
29
30 // Note: The C preprocessor stringify operator ('#') makes a string from its argument, without macro expansion
31 // e.g. If "version" is #define'd to be "4", then STRINGIFY_AWE(version) will return the string "version", not "4"
32 // To expand "version" to its value before making the string, use STRINGIFY(version) instead
33 #define STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s) # s
34 #define STRINGIFY(s) STRINGIFY_ARGUMENT_WITHOUT_EXPANSION(s)
35
36 // ***************************************************************************
37 #if COMPILER_LIKES_PRAGMA_MARK
38 #pragma mark - DNS Protocol Constants
39 #endif
40
41 typedef enum
42 {
43 kDNSFlag0_QR_Mask = 0x80, // Query or response?
44 kDNSFlag0_QR_Query = 0x00,
45 kDNSFlag0_QR_Response = 0x80,
46
47 kDNSFlag0_OP_Mask = 0x78, // Operation type
48 kDNSFlag0_OP_StdQuery = 0x00,
49 kDNSFlag0_OP_Subscribe = 0x06,
50 kDNSFlag0_OP_UnSubscribe = 0x07,
51 kDNSFlag0_OP_Iquery = 0x08,
52 kDNSFlag0_OP_Status = 0x10,
53 kDNSFlag0_OP_Unused3 = 0x18,
54 kDNSFlag0_OP_Notify = 0x20,
55 kDNSFlag0_OP_Update = 0x28,
56
57 kDNSFlag0_QROP_Mask = kDNSFlag0_QR_Mask | kDNSFlag0_OP_Mask,
58
59 kDNSFlag0_AA = 0x04, // Authoritative Answer?
60 kDNSFlag0_TC = 0x02, // Truncated?
61 kDNSFlag0_RD = 0x01, // Recursion Desired?
62 kDNSFlag1_RA = 0x80, // Recursion Available?
63
64 kDNSFlag1_Zero = 0x40, // Reserved; must be zero
65 kDNSFlag1_AD = 0x20, // Authentic Data [RFC 2535]
66 kDNSFlag1_CD = 0x10, // Checking Disabled [RFC 2535]
67
68 kDNSFlag1_RC_Mask = 0x0F, // Response code
69 kDNSFlag1_RC_NoErr = 0x00,
70 kDNSFlag1_RC_FormErr = 0x01,
71 kDNSFlag1_RC_ServFail = 0x02,
72 kDNSFlag1_RC_NXDomain = 0x03,
73 kDNSFlag1_RC_NotImpl = 0x04,
74 kDNSFlag1_RC_Refused = 0x05,
75 kDNSFlag1_RC_YXDomain = 0x06,
76 kDNSFlag1_RC_YXRRSet = 0x07,
77 kDNSFlag1_RC_NXRRSet = 0x08,
78 kDNSFlag1_RC_NotAuth = 0x09,
79 kDNSFlag1_RC_NotZone = 0x0A
80 } DNS_Flags;
81
82 typedef enum
83 {
84 TSIG_ErrBadSig = 16,
85 TSIG_ErrBadKey = 17,
86 TSIG_ErrBadTime = 18
87 } TSIG_ErrorCode;
88
89
90 // ***************************************************************************
91 #if COMPILER_LIKES_PRAGMA_MARK
92 #pragma mark -
93 #pragma mark - General Utility Functions
94 #endif
95
96 extern NetworkInterfaceInfo *GetFirstActiveInterface(NetworkInterfaceInfo *intf);
97 extern mDNSInterfaceID GetNextActiveInterfaceID(const NetworkInterfaceInfo *intf);
98
99 extern mDNSu32 mDNSRandom(mDNSu32 max); // Returns pseudo-random result from zero to max inclusive
100
101 extern mDNSu32 mDNS_GetNextResolverGroupID(void);
102
103 // ***************************************************************************
104 #if COMPILER_LIKES_PRAGMA_MARK
105 #pragma mark -
106 #pragma mark - Domain Name Utility Functions
107 #endif
108
109 #define mDNSSubTypeLabel "\x04_sub"
110
111 #define mDNSIsDigit(X) ((X) >= '0' && (X) <= '9')
112 #define mDNSIsUpperCase(X) ((X) >= 'A' && (X) <= 'Z')
113 #define mDNSIsLowerCase(X) ((X) >= 'a' && (X) <= 'z')
114 #define mDNSIsLetter(X) (mDNSIsUpperCase(X) || mDNSIsLowerCase(X))
115
116 // We believe we have adequate safeguards to protect against cache poisoning.
117 // In the event that someone does find a workable cache poisoning attack, we want to limit the lifetime of the poisoned entry.
118 // We set the maximum allowable TTL to one hour.
119 // With the 25% correction factor to avoid the DNS Zeno's paradox bug, that gives us an actual maximum lifetime of 75 minutes.
120
121 #define mDNSMaximumTTLSeconds (mDNSu32)3600
122
123 #define mDNSValidHostChar(X, notfirst, notlast) (mDNSIsLetter(X) || mDNSIsDigit(X) || ((notfirst) && (notlast) && (X) == '-') )
124
125 extern mDNSu16 CompressedDomainNameLength(const domainname *const name, const domainname *parent);
126 extern int CountLabels(const domainname *d);
127 extern const domainname *SkipLeadingLabels(const domainname *d, int skip);
128
129 extern mDNSu32 TruncateUTF8ToLength(mDNSu8 *string, mDNSu32 length, mDNSu32 max);
130 extern mDNSBool LabelContainsSuffix(const domainlabel *const name, const mDNSBool RichText);
131 extern mDNSu32 RemoveLabelSuffix(domainlabel *name, mDNSBool RichText);
132 extern void AppendLabelSuffix(domainlabel *const name, mDNSu32 val, const mDNSBool RichText);
133 #define ValidateDomainName(N) (DomainNameLength(N) <= MAX_DOMAIN_NAME)
134
135 // ***************************************************************************
136 #if COMPILER_LIKES_PRAGMA_MARK
137 #pragma mark -
138 #pragma mark - Resource Record Utility Functions
139 #endif
140
141 // IdenticalResourceRecord returns true if two resources records have
142 // the same name, type, class, and identical rdata (InterfaceID and TTL may differ)
143
144 // IdenticalSameNameRecord is the same, except it skips the expensive SameDomainName() check,
145 // which is at its most expensive and least useful in cases where we know in advance that the names match
146
147 // Note: The dominant use of IdenticalResourceRecord is from ProcessQuery(), handling known-answer lists. In this case
148 // it's common to have a whole bunch or records with exactly the same name (e.g. "_http._tcp.local") but different RDATA.
149 // The SameDomainName() check is expensive when the names match, and in this case *all* the names match, so we
150 // used to waste a lot of CPU time verifying that the names match, only then to find that the RDATA is different.
151 // We observed mDNSResponder spending 30% of its total CPU time on this single task alone.
152 // By swapping the checks so that we check the RDATA first, we can quickly detect when it's different
153 // (99% of the time) and then bail out before we waste time on the expensive SameDomainName() check.
154
155 #define IdenticalResourceRecord(r1,r2) ( \
156 (r1)->rrtype == (r2)->rrtype && \
157 (r1)->rrclass == (r2)->rrclass && \
158 (r1)->namehash == (r2)->namehash && \
159 (r1)->rdlength == (r2)->rdlength && \
160 (r1)->rdatahash == (r2)->rdatahash && \
161 SameRDataBody((r1), &(r2)->rdata->u, SameDomainName) && \
162 SameDomainName((r1)->name, (r2)->name))
163
164 #define IdenticalSameNameRecord(r1,r2) ( \
165 (r1)->rrtype == (r2)->rrtype && \
166 (r1)->rrclass == (r2)->rrclass && \
167 (r1)->rdlength == (r2)->rdlength && \
168 (r1)->rdatahash == (r2)->rdatahash && \
169 SameRDataBody((r1), &(r2)->rdata->u, SameDomainName))
170
171 // A given RRType answers a QuestionType if RRType is CNAME, or types match, or QuestionType is ANY,
172 // or the RRType is NSEC and positively asserts the nonexistence of the type being requested
173 #define RRTypeAnswersQuestionType(R,Q) ((R)->rrtype == kDNSType_CNAME || (R)->rrtype == (Q) || (Q) == kDNSQType_ANY || RRAssertsNonexistence((R),(Q)))
174 // Unicast NSEC records have the NSEC bit set whereas the multicast NSEC ones don't
175 #define UNICAST_NSEC(rr) ((rr)->rrtype == kDNSType_NSEC && RRAssertsExistence((rr), kDNSType_NSEC))
176
177 extern mDNSu32 RDataHashValue(const ResourceRecord *const rr);
178 extern mDNSBool SameRDataBody(const ResourceRecord *const r1, const RDataBody *const r2, DomainNameComparisonFn *samename);
179 extern mDNSBool SameNameRecordAnswersQuestion(const ResourceRecord *const rr, const DNSQuestion *const q);
180 extern mDNSBool ResourceRecordAnswersQuestion(const ResourceRecord *const rr, const DNSQuestion *const q);
181 extern mDNSBool AnyTypeRecordAnswersQuestion (const ResourceRecord *const rr, const DNSQuestion *const q);
182 extern mDNSBool ResourceRecordAnswersUnicastResponse(const ResourceRecord *const rr, const DNSQuestion *const q);
183 extern mDNSBool LocalOnlyRecordAnswersQuestion(AuthRecord *const rr, const DNSQuestion *const q);
184 extern mDNSu16 GetRDLength(const ResourceRecord *const rr, mDNSBool estimate);
185 extern mDNSBool ValidateRData(const mDNSu16 rrtype, const mDNSu16 rdlength, const RData *const rd);
186 extern mStatus DNSNameToLowerCase(domainname *d, domainname *result);
187
188 #define GetRRDomainNameTarget(RR) ( \
189 ((RR)->rrtype == kDNSType_NS || (RR)->rrtype == kDNSType_CNAME || (RR)->rrtype == kDNSType_PTR || (RR)->rrtype == kDNSType_DNAME) ? &(RR)->rdata->u.name : \
190 ((RR)->rrtype == kDNSType_MX || (RR)->rrtype == kDNSType_AFSDB || (RR)->rrtype == kDNSType_RT || (RR)->rrtype == kDNSType_KX ) ? &(RR)->rdata->u.mx.exchange : \
191 ((RR)->rrtype == kDNSType_SRV ) ? &(RR)->rdata->u.srv.target : mDNSNULL )
192
193 #define LocalRecordReady(X) ((X)->resrec.RecordType != kDNSRecordTypeUnique)
194
195 // ***************************************************************************
196 #if COMPILER_LIKES_PRAGMA_MARK
197 #pragma mark -
198 #pragma mark - DNS Message Creation Functions
199 #endif
200
201 extern void InitializeDNSMessage(DNSMessageHeader *h, mDNSOpaque16 id, mDNSOpaque16 flags);
202 extern const mDNSu8 *FindCompressionPointer(const mDNSu8 *const base, const mDNSu8 *const end, const mDNSu8 *const domname);
203 extern mDNSu8 *putDomainNameAsLabels(const DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit, const domainname *const name);
204 extern mDNSu8 *putRData(const DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit, const ResourceRecord *const rr);
205
206 // If we have a single large record to put in the packet, then we allow the packet to be up to 9K bytes,
207 // but in the normal case we try to keep the packets below 1500 to avoid IP fragmentation on standard Ethernet
208
209 #define AllowedRRSpace(msg) (((msg)->h.numAnswers || (msg)->h.numAuthorities || (msg)->h.numAdditionals) ? NormalMaxDNSMessageData : AbsoluteMaxDNSMessageData)
210
211 extern mDNSu8 *PutResourceRecordTTLWithLimit(DNSMessage *const msg, mDNSu8 *ptr, mDNSu16 *count, ResourceRecord *rr, mDNSu32 ttl, const mDNSu8 *limit);
212
213 #define PutResourceRecordTTL(msg, ptr, count, rr, ttl) \
214 PutResourceRecordTTLWithLimit((msg), (ptr), (count), (rr), (ttl), (msg)->data + AllowedRRSpace(msg))
215
216 #define PutResourceRecordTTLJumbo(msg, ptr, count, rr, ttl) \
217 PutResourceRecordTTLWithLimit((msg), (ptr), (count), (rr), (ttl), (msg)->data + AbsoluteMaxDNSMessageData)
218
219 #define PutResourceRecord(MSG, P, C, RR) PutResourceRecordTTL((MSG), (P), (C), (RR), (RR)->rroriginalttl)
220
221 // The PutRR_OS variants assume a local variable 'm', put build the packet at m->omsg,
222 // and assume local variables 'OwnerRecordSpace' & 'TraceRecordSpace' indicating how many bytes (if any) to reserve to add an OWNER/TRACER option at the end
223 #define PutRR_OS_TTL(ptr, count, rr, ttl) \
224 PutResourceRecordTTLWithLimit(&m->omsg, (ptr), (count), (rr), (ttl), m->omsg.data + AllowedRRSpace(&m->omsg) - OwnerRecordSpace - TraceRecordSpace)
225
226 #define PutRR_OS(P, C, RR) PutRR_OS_TTL((P), (C), (RR), (RR)->rroriginalttl)
227
228 extern mDNSu8 *putQuestion(DNSMessage *const msg, mDNSu8 *ptr, const mDNSu8 *const limit, const domainname *const name, mDNSu16 rrtype, mDNSu16 rrclass);
229 extern mDNSu8 *putZone(DNSMessage *const msg, mDNSu8 *ptr, mDNSu8 *limit, const domainname *zone, mDNSOpaque16 zoneClass);
230 extern mDNSu8 *putPrereqNameNotInUse(const domainname *const name, DNSMessage *const msg, mDNSu8 *const ptr, mDNSu8 *const end);
231 extern mDNSu8 *putDeletionRecord(DNSMessage *msg, mDNSu8 *ptr, ResourceRecord *rr);
232 extern mDNSu8 *putDeletionRecordWithLimit(DNSMessage *msg, mDNSu8 *ptr, ResourceRecord *rr, mDNSu8 *limit);
233 extern mDNSu8 *putDeleteRRSetWithLimit(DNSMessage *msg, mDNSu8 *ptr, const domainname *name, mDNSu16 rrtype, mDNSu8 *limit);
234 extern mDNSu8 *putDeleteAllRRSets(DNSMessage *msg, mDNSu8 *ptr, const domainname *name);
235 extern mDNSu8 *putUpdateLease(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease);
236 extern mDNSu8 *putUpdateLeaseWithLimit(DNSMessage *msg, mDNSu8 *ptr, mDNSu32 lease, mDNSu8 *limit);
237
238 extern mDNSu8 *putHINFO(const mDNS *const m, DNSMessage *const msg, mDNSu8 *ptr, DomainAuthInfo *authInfo, mDNSu8 *limit);
239 extern mDNSu8 *putDNSSECOption(DNSMessage *msg, mDNSu8 *end, mDNSu8 *limit);
240 extern int baseEncode(char *buffer, int blen, const mDNSu8 *data, int len, int encAlg);
241 extern void NSEC3Parse(const ResourceRecord *const rr, mDNSu8 **salt, int *hashLength, mDNSu8 **nxtName, int *bitmaplen, mDNSu8 **bitmap);
242
243 extern const mDNSu8 *NSEC3HashName(const domainname *name, rdataNSEC3 *nsec3, const mDNSu8 *AnonData, int AnonDataLen,
244 const mDNSu8 hash[NSEC3_MAX_HASH_LEN], int *dlen);
245
246 // ***************************************************************************
247 #if COMPILER_LIKES_PRAGMA_MARK
248 #pragma mark -
249 #pragma mark - DNS Message Parsing Functions
250 #endif
251
252 #define HashSlotFromNameHash(X) ((X) % CACHE_HASH_SLOTS)
253 extern mDNSu32 DomainNameHashValue(const domainname *const name);
254 extern void SetNewRData(ResourceRecord *const rr, RData *NewRData, mDNSu16 rdlength);
255 extern const mDNSu8 *skipDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end);
256 extern const mDNSu8 *getDomainName(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *const end,
257 domainname *const name);
258 extern const mDNSu8 *skipResourceRecord(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end);
259 extern const mDNSu8 *GetLargeResourceRecord(mDNS *const m, const DNSMessage * const msg, const mDNSu8 *ptr,
260 const mDNSu8 * end, const mDNSInterfaceID InterfaceID, mDNSu8 RecordType, LargeCacheRecord *const largecr);
261 extern mDNSBool SetRData(const DNSMessage *const msg, const mDNSu8 *ptr, const mDNSu8 *end,
262 LargeCacheRecord *const largecr, mDNSu16 rdlength);
263 extern const mDNSu8 *skipQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end);
264 extern const mDNSu8 *getQuestion(const DNSMessage *msg, const mDNSu8 *ptr, const mDNSu8 *end, const mDNSInterfaceID InterfaceID,
265 DNSQuestion *question);
266 extern const mDNSu8 *LocateAnswers(const DNSMessage *const msg, const mDNSu8 *const end);
267 extern const mDNSu8 *LocateAuthorities(const DNSMessage *const msg, const mDNSu8 *const end);
268 extern const mDNSu8 *LocateAdditionals(const DNSMessage *const msg, const mDNSu8 *const end);
269 extern const mDNSu8 *LocateOptRR(const DNSMessage *const msg, const mDNSu8 *const end, int minsize);
270 extern const rdataOPT *GetLLQOptData(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end);
271 extern mDNSBool GetPktLease(mDNS *const m, const DNSMessage *const msg, const mDNSu8 *const end, mDNSu32 *const lease);
272 extern void DumpPacket(mStatus status, mDNSBool sent, char *transport,
273 const mDNSAddr *srcaddr, mDNSIPPort srcport,
274 const mDNSAddr *dstaddr, mDNSIPPort dstport, const DNSMessage *const msg, const mDNSu8 *const end);
275 extern mDNSBool RRAssertsNonexistence(const ResourceRecord *const rr, mDNSu16 type);
276 extern mDNSBool RRAssertsExistence(const ResourceRecord *const rr, mDNSu16 type);
277 extern mDNSBool BitmapTypeCheck(mDNSu8 *bmap, int bitmaplen, mDNSu16 type);
278
279 extern mDNSu16 swap16(mDNSu16 x);
280 extern mDNSu32 swap32(mDNSu32 x);
281
282 // ***************************************************************************
283 #if COMPILER_LIKES_PRAGMA_MARK
284 #pragma mark -
285 #pragma mark - Packet Sending Functions
286 #endif
287
288 extern mStatus mDNSSendDNSMessage(mDNS *const m, DNSMessage *const msg, mDNSu8 *end,
289 mDNSInterfaceID InterfaceID, UDPSocket *src, const mDNSAddr *dst,
290 mDNSIPPort dstport, TCPSocket *sock, DomainAuthInfo *authInfo,
291 mDNSBool useBackgroundTrafficClass);
292
293 // ***************************************************************************
294 #if COMPILER_LIKES_PRAGMA_MARK
295 #pragma mark -
296 #pragma mark - RR List Management & Task Management
297 #endif
298
299 extern void ShowTaskSchedulingError(mDNS *const m);
300 extern void mDNS_Lock_(mDNS *const m, const char * const functionname);
301 extern void mDNS_Unlock_(mDNS *const m, const char * const functionname);
302
303 #if defined(_WIN32)
304 #define __func__ __FUNCTION__
305 #endif
306
307 #define mDNS_Lock(X) mDNS_Lock_((X), __func__)
308
309 #define mDNS_Unlock(X) mDNS_Unlock_((X), __func__)
310
311 #define mDNS_CheckLock(X) \
312 if ((X)->mDNS_busy != (X)->mDNS_reentrancy+1) LogMsg("%s: Lock not held! mDNS_busy (%ld) mDNS_reentrancy (%ld)", __func__, (X)->mDNS_busy, (X)->mDNS_reentrancy)
313
314 #define mDNS_DropLockBeforeCallback() do { m->mDNS_reentrancy++; \
315 if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Locking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy); \
316 } while (0)
317
318 #define mDNS_ReclaimLockAfterCallback() do { \
319 if (m->mDNS_busy != m->mDNS_reentrancy) LogMsg("%s: Unlocking Failure! mDNS_busy (%ld) != mDNS_reentrancy (%ld)", __func__, m->mDNS_busy, m->mDNS_reentrancy); \
320 m->mDNS_reentrancy--; } while (0)
321
322 #ifdef __cplusplus
323 }
324 #endif
325
326 #endif // __DNSCOMMON_H_