-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResolver.php
More file actions
351 lines (305 loc) · 11.7 KB
/
Resolver.php
File metadata and controls
351 lines (305 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<?php
namespace Utopia\DNS\Zone;
use Utopia\DNS\Message;
use Utopia\DNS\Message\Record;
use Utopia\DNS\Zone;
final readonly class Resolver
{
/**
* Resolve DNS Record
* Performs a DNS lookup within the zone for the given query.
*
* Implements the DNS resolution algorithm following these steps:
* 1. Validates the query has a question section
* 2. Selects the best matching records for the query
* 3. Handles exact matches or wildcard matches appropriately
*
* Algorithm reference:
* - Flowchart: https://www.usenix.org/sites/default/files/styles/article_embedded/public/tree.png
* - Pseudocode: https://www.usenix.org/sites/default/files/styles/article_embedded/public/code.png
*
* @param Message $query The DNS query message containing the question to resolve.
* @param Zone $zone The DNS zone containing the records to resolve.
* @return Message The DNS response message with appropriate records and response code.
* Returns FORMERR if query lacks a question section.
* Returns NXDOMAIN if no matching records are found.
*/
public static function lookup(Message $query, Zone $zone): Message
{
$question = $query->questions[0] ?? null;
if ($question === null) {
return Message::response(
header: $query->header,
responseCode: Message::RCODE_FORMERR,
authoritative: true,
);
}
// Step 1: Select best matching records for the query
$records = self::selectBestRecords($query, $zone);
if (empty($records)) {
// SOA is stored separately; if querying SOA at the zone apex, return it
if ($question->type === Record::TYPE_SOA && $question->name === $zone->name) {
return self::soaApexResponse($query, $zone);
}
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NXDOMAIN,
questions: $query->questions,
authority: [$zone->soa],
authoritative: true,
);
}
$rname = $records[0]->name;
// Step 2: Check for exact match
if ($rname === $question->name) {
return self::handleExactMatch($records, $query, $zone);
}
// Step 3: Check if wildcard match
if (self::isWildcardMatch($question->name, $rname)) {
return self::handleWildcardMatch($records, $query, $zone);
}
// Should be unreachable
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NXDOMAIN,
questions: $query->questions,
authority: [$zone->soa],
authoritative: true,
);
}
/**
* Select the best matching records for a query
*
* @param Message $query
* @param Zone $zone
* @return list<Record>
*/
private static function selectBestRecords(Message $query, Zone $zone): array
{
$question = $query->questions[0] ?? throw new \RuntimeException('Not reachable');
// First, try exact match
$exactMatches = array_filter(
$zone->records,
fn ($r) => $r->name === $question->name
);
if (!empty($exactMatches)) {
return array_values($exactMatches);
}
// No exact match - try wildcard matching
// Find the closest enclosing wildcard
$wildcardRecord = self::findClosestWildcard($question->name, $zone);
if ($wildcardRecord !== null) {
// Return all records at the wildcard name
return array_values(array_filter(
$zone->records,
fn ($r) => $r->name === $wildcardRecord->name
));
}
return [];
}
/**
* Find the closest enclosing wildcard for a query name
*
* @param string $questionName
* @param Zone $zone
* @return Record|null
*/
private static function findClosestWildcard(string $questionName, Zone $zone): ?Record
{
// Generate potential wildcard names from most specific to least
// For example, for "a.b.c.example.com":
// - *.b.c.example.com
// - *.c.example.com
// - *.example.com
$parts = explode('.', $questionName);
for ($i = 1; $i < count($parts); $i++) {
$wildcardName = '*.' . implode('.', array_slice($parts, $i));
// Check if this wildcard exists in the zone
foreach ($zone->records as $record) {
if ($record->name === $wildcardName) {
return $record;
}
}
}
return null;
}
/**
* Handle exact match case (E1, E2, E3, E4 paths)
*
* @param list<Record> $records
* @param Message $query
* @param Zone $zone
* @return Message
*/
private static function handleExactMatch(array $records, Message $query, Zone $zone): Message
{
$question = $query->questions[0] ?? throw new \RuntimeException('Not reachable');
// Check if zone is authoritative for this name
$isAuthoritative = $zone->isAuthoritative($question->name);
if ($isAuthoritative) {
// SOA is stored separately in Zone; handle SOA queries at the zone apex
if ($question->type === Record::TYPE_SOA && $question->name === $zone->name) {
return self::soaApexResponse($query, $zone);
}
// Path E1: Exact match of type
$exactTypeRecords = array_filter(
$records,
fn ($r) => $r->type === $question->type
);
if (!empty($exactTypeRecords)) {
// E1: Return exact type match (randomized for load balancing)
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
answers: self::randomizeRRSet(array_values($exactTypeRecords)),
authoritative: true,
recursionAvailable: false
);
}
// Check for CNAME
$cnameRecords = array_filter($records, fn ($r) => $r->type === Record::TYPE_CNAME);
if (!empty($cnameRecords)) {
// E2: CNAME exists
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
answers: array_values($cnameRecords),
authoritative: true,
recursionAvailable: false
);
}
// E3: No matching type, no CNAME (NODATA)
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
authority: [$zone->soa],
authoritative: true,
recursionAvailable: false
);
} else {
// E4: Not authoritative - referral
// Find NS records for delegation
$nsRecords = array_filter($records, fn ($r) => $r->type === Record::TYPE_NS);
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
authority: array_values($nsRecords),
authoritative: false,
recursionAvailable: false
);
}
}
/**
* Build an authoritative SOA answer for the zone apex.
*/
private static function soaApexResponse(Message $query, Zone $zone): Message
{
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
answers: [$zone->soa],
authoritative: true,
recursionAvailable: false
);
}
/**
* Randomize RRSet order for load balancing.
*
* Per RFC 2181 Section 5, the order of resource records within an RRSet
* is not significant. By randomizing the order, we help distribute load
* across multiple servers (e.g., multiple A records for the same name).
*
* @param list<Record> $records
* @return list<Record>
*/
private static function randomizeRRSet(array $records): array
{
if (count($records) <= 1) {
return $records;
}
// RFC 2181 Section 5: Order within RRSet is not significant
// Randomization helps load balance across multiple A/AAAA records
shuffle($records);
return $records;
}
/**
* Check if a query name matches a wildcard record name
*
* @param string $queryName The query name (e.g., "sub.example.com")
* @param string $recordName The record name (e.g., "*.example.com")
* @return bool
*/
private static function isWildcardMatch(string $queryName, string $recordName): bool
{
if (!str_starts_with($recordName, '*.')) {
return false;
}
$wildcardSuffix = substr($recordName, 2); // Remove "*."
$queryParts = explode('.', $queryName);
// Build the suffix that should match
$querySuffix = implode('.', array_slice($queryParts, 1));
return $querySuffix === $wildcardSuffix;
}
/**
* Handle wildcard match case (W1, W2, W3 paths)
*
* @param list<Record> $records
* @param Message $query
* @return Message
*/
private static function handleWildcardMatch(array $records, Message $query, Zone $zone): Message
{
$question = $query->questions[0] ?? throw new \RuntimeException('Not reachable');
// W1: Exact type match in wildcard records
$exactTypeRecords = array_filter(
$records,
fn ($r) => $r->type === $question->type
);
if (!empty($exactTypeRecords)) {
// Synthesize records with the query name (randomized for load balancing)
$synthesizedRecords = array_map(
fn ($r) => $r->withName($question->name),
$exactTypeRecords
);
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
answers: self::randomizeRRSet(array_values($synthesizedRecords)),
authoritative: true,
recursionAvailable: false
);
}
// Check for CNAME
$cnameRecords = array_filter($records, fn ($r) => $r->type === Record::TYPE_CNAME);
if (!empty($cnameRecords)) {
// W2: CNAME in wildcard
$synthesizedRecords = array_map(
fn ($r) => $r->withName($question->name),
$cnameRecords
);
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
answers: array_values($synthesizedRecords),
authoritative: true,
recursionAvailable: false
);
}
// W3: No matching type in wildcard (NODATA)
return Message::response(
header: $query->header,
responseCode: Message::RCODE_NOERROR,
questions: $query->questions,
authority: [$zone->soa],
authoritative: true,
recursionAvailable: false
);
}
}