-
Notifications
You must be signed in to change notification settings - Fork 231
/
Lookup.java
635 lines (579 loc) · 18 KB
/
Lookup.java
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// Copyright (c) 2002-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
* The Lookup object issues queries to caching DNS servers. The input consists of a name, an
* optional type, and an optional class. Caching is enabled by default and used when possible to
* reduce the number of DNS requests. A Resolver, which defaults to an ExtendedResolver initialized
* with the resolvers located by the ResolverConfig class, performs the queries. A search path of
* domain suffixes is used to resolve relative names, and is also determined by the ResolverConfig
* class.
*
* <p>A Lookup object may be reused, but should not be used by multiple threads.
*
* @see Cache
* @see Resolver
* @see ResolverConfig
* @author Brian Wellington
*/
@Slf4j
public final class Lookup {
private static Resolver defaultResolver;
private static List<Name> defaultSearchPath;
private static Map<Integer, Cache> defaultCaches;
private static int defaultNdots;
private Resolver resolver;
private List<Name> searchPath;
private Cache cache;
private boolean temporary_cache;
private int credibility;
private Name name;
private int type;
private int dclass;
private int iterations;
private boolean foundAlias;
private boolean done;
private boolean doneCurrent;
private List<Name> aliases;
private Record[] answers;
private int result;
private String error;
private boolean nxdomain;
private boolean badresponse;
private String badresponse_error;
private boolean networkerror;
private boolean timedout;
private boolean nametoolong;
private boolean referral;
private static final Name[] noAliases = new Name[0];
/** The lookup was successful. */
public static final int SUCCESSFUL = 0;
/** The lookup failed due to a data or server error. Repeating the lookup would not be helpful. */
public static final int UNRECOVERABLE = 1;
/** The lookup failed due to a network error. Repeating the lookup may be helpful. */
public static final int TRY_AGAIN = 2;
/** The host does not exist. */
public static final int HOST_NOT_FOUND = 3;
/** The host exists, but has no records associated with the queried type. */
public static final int TYPE_NOT_FOUND = 4;
public static synchronized void refreshDefault() {
defaultResolver = new ExtendedResolver();
defaultSearchPath = ResolverConfig.getCurrentConfig().searchPath();
defaultCaches = new HashMap<>();
defaultNdots = ResolverConfig.getCurrentConfig().ndots();
}
static {
refreshDefault();
}
/**
* Gets the Resolver that will be used as the default by future Lookups.
*
* @return The default resolver.
*/
public static synchronized Resolver getDefaultResolver() {
return defaultResolver;
}
/**
* Sets the default Resolver to be used as the default by future Lookups.
*
* @param resolver The default resolver.
*/
public static synchronized void setDefaultResolver(Resolver resolver) {
defaultResolver = resolver;
}
/**
* Gets the Cache that will be used as the default for the specified class by future Lookups.
*
* @param dclass The class whose cache is being retrieved.
* @return The default cache for the specified class.
*/
public static synchronized Cache getDefaultCache(int dclass) {
DClass.check(dclass);
Cache c = defaultCaches.get(dclass);
if (c == null) {
c = new Cache(dclass);
defaultCaches.put(dclass, c);
}
return c;
}
/**
* Sets the Cache to be used as the default for the specified class by future Lookups.
*
* @param cache The default cache for the specified class.
* @param dclass The class whose cache is being set.
*/
public static synchronized void setDefaultCache(Cache cache, int dclass) {
DClass.check(dclass);
defaultCaches.put(dclass, cache);
}
/**
* Gets the search path that will be used as the default by future Lookups.
*
* @return The default search path.
*/
public static synchronized List<Name> getDefaultSearchPath() {
return defaultSearchPath;
}
/**
* Sets the search path to be used as the default by future Lookups.
*
* @param domains The default search path.
*/
public static synchronized void setDefaultSearchPath(List<Name> domains) {
defaultSearchPath = domains;
}
/**
* Sets the search path that will be used as the default by future Lookups.
*
* @param domains The default search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public static synchronized void setDefaultSearchPath(String[] domains) throws TextParseException {
if (domains == null) {
defaultSearchPath = null;
return;
}
List<Name> newdomains = new ArrayList<>(domains.length);
for (String domain : domains) {
newdomains.add(Name.fromString(domain, Name.root));
}
defaultSearchPath = newdomains;
}
/**
* Sets a custom logger that will be used to log the send and received packets.
*
* @param logger The logger
*/
public static synchronized void setPacketLogger(PacketLogger logger) {
Client.setPacketLogger(logger);
}
private void reset() {
iterations = 0;
foundAlias = false;
done = false;
doneCurrent = false;
aliases = null;
answers = null;
result = -1;
error = null;
nxdomain = false;
badresponse = false;
badresponse_error = null;
networkerror = false;
timedout = false;
nametoolong = false;
referral = false;
if (temporary_cache) {
cache.clearCache();
}
}
/**
* Create a Lookup object that will find records of the given name, type, and class. The lookup
* will use the default cache, resolver, and search path, and look for records that are reasonably
* credible.
*
* @param name The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see Cache
* @see Resolver
* @see Credibility
* @see Name
* @see Type
* @see DClass
*/
public Lookup(Name name, int type, int dclass) {
Type.check(type);
DClass.check(dclass);
if (!Type.isRR(type) && type != Type.ANY) {
throw new IllegalArgumentException("Cannot query for meta-types other than ANY");
}
this.name = name;
this.type = type;
this.dclass = dclass;
synchronized (Lookup.class) {
this.resolver = getDefaultResolver();
this.searchPath = getDefaultSearchPath();
this.cache = getDefaultCache(dclass);
}
this.credibility = Credibility.NORMAL;
this.result = -1;
}
/**
* Create a Lookup object that will find records of the given name and type in the IN class.
*
* @param name The name of the desired records
* @param type The type of the desired records
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public Lookup(Name name, int type) {
this(name, type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name in the IN class.
*
* @param name The name of the desired records
* @see #Lookup(Name,int,int)
*/
public Lookup(Name name) {
this(name, Type.A, DClass.IN);
}
/**
* Create a Lookup object that will find records of the given name, type, and class.
*
* @param name The name of the desired records
* @param type The type of the desired records
* @param dclass The class of the desired records
* @throws TextParseException The name is not a valid DNS name
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public Lookup(String name, int type, int dclass) throws TextParseException {
this(Name.fromString(name), type, dclass);
}
/**
* Create a Lookup object that will find records of the given name and type in the IN class.
*
* @param name The name of the desired records
* @param type The type of the desired records
* @throws TextParseException The name is not a valid DNS name
* @throws IllegalArgumentException The type is a meta type other than ANY.
* @see #Lookup(Name,int,int)
*/
public Lookup(String name, int type) throws TextParseException {
this(Name.fromString(name), type, DClass.IN);
}
/**
* Create a Lookup object that will find records of type A at the given name in the IN class.
*
* @param name The name of the desired records
* @throws TextParseException The name is not a valid DNS name
* @see #Lookup(Name,int,int)
*/
public Lookup(String name) throws TextParseException {
this(Name.fromString(name), Type.A, DClass.IN);
}
/**
* Sets the resolver to use when performing this lookup. This overrides the default value.
*
* @param resolver The resolver to use.
*/
public void setResolver(Resolver resolver) {
this.resolver = resolver;
}
/**
* Sets the search path to use when performing this lookup. This overrides the default value.
*
* @param domains An array of names containing the search path.
*/
public void setSearchPath(List<Name> domains) {
this.searchPath = domains;
}
/**
* Sets the search path to use when performing this lookup. This overrides the default value.
*
* @param domains An array of names containing the search path.
* @throws TextParseException A name in the array is not a valid DNS name.
*/
public void setSearchPath(String[] domains) throws TextParseException {
if (domains == null) {
this.searchPath = null;
return;
}
List<Name> newdomains = new ArrayList<>(domains.length);
for (String domain : domains) {
newdomains.add(Name.fromString(domain, Name.root));
}
this.searchPath = newdomains;
}
/**
* Sets the cache to use when performing this lookup. This overrides the default value. If the
* results of this lookup should not be permanently cached, null can be provided here.
*
* @param cache The cache to use.
*/
public void setCache(Cache cache) {
if (cache == null) {
this.cache = new Cache(dclass);
this.temporary_cache = true;
} else {
this.cache = cache;
this.temporary_cache = false;
}
}
/**
* Sets ndots to use when performing this lookup, overriding the default value. Specifically, this
* refers to the number of "dots" which, if present in a name, indicate that a lookup for the
* absolute name should be attempted before appending any search path elements.
*
* @param ndots The ndots value to use, which must be greater than or equal to 0.
*/
public static void setNdots(int ndots) {
if (ndots < 0) {
throw new IllegalArgumentException("Illegal ndots value: " + ndots);
}
defaultNdots = ndots;
}
/**
* Sets the minimum credibility level that will be accepted when performing the lookup. This
* defaults to Credibility.NORMAL.
*
* @param credibility The minimum credibility level.
*/
public void setCredibility(int credibility) {
this.credibility = credibility;
}
private void follow(Name name, Name oldname) {
foundAlias = true;
badresponse = false;
networkerror = false;
timedout = false;
nxdomain = false;
referral = false;
iterations++;
if (iterations >= 10 || name.equals(oldname)) {
result = UNRECOVERABLE;
error = "CNAME loop";
done = true;
return;
}
if (aliases == null) {
aliases = new ArrayList<>();
}
aliases.add(oldname);
lookup(name);
}
private void processResponse(Name name, SetResponse response) {
if (response.isSuccessful()) {
List<RRset<?>> rrsets = response.answers();
List<Record> l = new ArrayList<>();
for (RRset<?> set : rrsets) {
l.addAll(set.rrs());
}
result = SUCCESSFUL;
answers = l.toArray(new Record[0]);
done = true;
} else if (response.isNXDOMAIN()) {
nxdomain = true;
doneCurrent = true;
if (iterations > 0) {
result = HOST_NOT_FOUND;
done = true;
}
} else if (response.isNXRRSET()) {
result = TYPE_NOT_FOUND;
answers = null;
done = true;
} else if (response.isCNAME()) {
CNAMERecord cname = response.getCNAME();
follow(cname.getTarget(), name);
} else if (response.isDNAME()) {
DNAMERecord dname = response.getDNAME();
try {
follow(name.fromDNAME(dname), name);
} catch (NameTooLongException e) {
result = UNRECOVERABLE;
error = "Invalid DNAME target";
done = true;
}
} else if (response.isDelegation()) {
// We shouldn't get a referral. Ignore it.
referral = true;
}
}
private void lookup(Name current) {
SetResponse sr = cache.lookupRecords(current, type, credibility);
log.debug("lookup {} {}, cache answer: {}", current, Type.string(type), sr);
processResponse(current, sr);
if (done || doneCurrent) {
return;
}
Record question = Record.newRecord(current, type, dclass);
Message query = Message.newQuery(question);
Message response;
try {
response = resolver.send(query);
} catch (IOException e) {
log.debug("Lookup failed using resolver {}", resolver, e);
// A network error occurred. Press on.
if (e instanceof InterruptedIOException) {
timedout = true;
} else {
networkerror = true;
}
return;
}
int rcode = response.getHeader().getRcode();
if (rcode != Rcode.NOERROR && rcode != Rcode.NXDOMAIN) {
// The server we contacted is broken or otherwise unhelpful.
// Press on.
badresponse = true;
badresponse_error = Rcode.string(rcode);
return;
}
if (!query.getQuestion().equals(response.getQuestion())) {
// The answer doesn't match the question. That's not good.
badresponse = true;
badresponse_error = "response does not match query";
return;
}
sr = cache.addMessage(response);
if (sr == null) {
sr = cache.lookupRecords(current, type, credibility);
}
log.debug("Queried {} {}: {}", current, Type.string(type), sr);
processResponse(current, sr);
}
private void resolve(Name current, Name suffix) {
doneCurrent = false;
Name tname;
if (suffix == null) {
tname = current;
} else {
try {
tname = Name.concatenate(current, suffix);
} catch (NameTooLongException e) {
nametoolong = true;
return;
}
}
lookup(tname);
}
/**
* Performs the lookup, using the specified Cache, Resolver, and search path.
*
* @return The answers, or null if none are found.
*/
public Record[] run() {
if (done) {
reset();
}
if (name.isAbsolute()) {
resolve(name, null);
} else if (searchPath == null) {
resolve(name, Name.root);
} else {
if (name.labels() > defaultNdots) {
resolve(name, Name.root);
}
if (done) {
return answers;
}
for (Name value : searchPath) {
resolve(name, value);
if (done) {
return answers;
} else if (foundAlias) {
break;
}
}
}
if (!done) {
if (badresponse) {
result = TRY_AGAIN;
error = badresponse_error;
done = true;
} else if (timedout) {
result = TRY_AGAIN;
error = "timed out";
done = true;
} else if (networkerror) {
result = TRY_AGAIN;
error = "network error";
done = true;
} else if (nxdomain) {
result = HOST_NOT_FOUND;
done = true;
} else if (referral) {
result = UNRECOVERABLE;
error = "referral";
done = true;
} else if (nametoolong) {
result = UNRECOVERABLE;
error = "name too long";
done = true;
}
}
return answers;
}
private void checkDone() {
if (done && result != -1) {
return;
}
StringBuilder sb = new StringBuilder("Lookup of " + name + " ");
if (dclass != DClass.IN) {
sb.append(DClass.string(dclass)).append(" ");
}
sb.append(Type.string(type)).append(" isn't done");
throw new IllegalStateException(sb.toString());
}
/**
* Returns the answers from the lookup.
*
* @return The answers, or null if none are found.
* @throws IllegalStateException The lookup has not completed.
*/
public Record[] getAnswers() {
checkDone();
return answers;
}
/**
* Returns all known aliases for this name. Whenever a CNAME/DNAME is followed, an alias is added
* to this array. The last element in this array will be the owner name for records in the answer,
* if there are any.
*
* @return The aliases.
* @throws IllegalStateException The lookup has not completed.
*/
public Name[] getAliases() {
checkDone();
if (aliases == null) {
return noAliases;
}
return aliases.toArray(new Name[0]);
}
/**
* Returns the result code of the lookup.
*
* @return The result code, which can be SUCCESSFUL, UNRECOVERABLE, TRY_AGAIN, HOST_NOT_FOUND, or
* TYPE_NOT_FOUND.
* @throws IllegalStateException The lookup has not completed.
*/
public int getResult() {
checkDone();
return result;
}
/**
* Returns an error string describing the result code of this lookup.
*
* @return A string, which may either directly correspond the result code or be more specific.
* @throws IllegalStateException The lookup has not completed.
*/
public String getErrorString() {
checkDone();
if (error != null) {
return error;
}
switch (result) {
case SUCCESSFUL:
return "successful";
case UNRECOVERABLE:
return "unrecoverable error";
case TRY_AGAIN:
return "try again";
case HOST_NOT_FOUND:
return "host not found";
case TYPE_NOT_FOUND:
return "type not found";
}
throw new IllegalStateException("unknown result");
}
}