aboutsummaryrefslogtreecommitdiff
path: root/src/org/xbill/DNS/ZoneTransferIn.java
blob: 8a1999241a12e7f54ba8aace3a602713500c405d (plain)
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
// Copyright (c) 2003-2004 Brian Wellington (bwelling@xbill.org)
// Parts of this are derived from lib/dns/xfrin.c from BIND 9; its copyright
// notice follows.

/*
 * Copyright (C) 1999-2001  Internet Software Consortium.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM
 * DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
 * INTERNET SOFTWARE CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
 * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
 * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package org.xbill.DNS;

import java.io.*;
import java.net.*;
import java.util.*;

/**
 * An incoming DNS Zone Transfer.  To use this class, first initialize an
 * object, then call the run() method.  If run() doesn't throw an exception
 * the result will either be an IXFR-style response, an AXFR-style response,
 * or an indication that the zone is up to date.
 *
 * @author Brian Wellington
 */

public class ZoneTransferIn {

private static final int INITIALSOA	= 0;
private static final int FIRSTDATA	= 1;
private static final int IXFR_DELSOA	= 2;
private static final int IXFR_DEL	= 3;
private static final int IXFR_ADDSOA	= 4;
private static final int IXFR_ADD	= 5;
private static final int AXFR		= 6;
private static final int END		= 7;

private Name zname;
private int qtype;
private int dclass;
private long ixfr_serial;
private boolean want_fallback;
private ZoneTransferHandler handler;

private SocketAddress localAddress;
private SocketAddress address;
private TCPClient client;
private TSIG tsig;
private TSIG.StreamVerifier verifier;
private long timeout = 900 * 1000;

private int state;
private long end_serial;
private long current_serial;
private Record initialsoa;

private int rtype;

public static class Delta {
	/**
	 * All changes between two versions of a zone in an IXFR response.
	 */

	/** The starting serial number of this delta. */
	public long start;

	/** The ending serial number of this delta. */
	public long end;

	/** A list of records added between the start and end versions */
	public List adds;

	/** A list of records deleted between the start and end versions */
	public List deletes;

	private
	Delta() {
		adds = new ArrayList();
		deletes = new ArrayList();
	}
}

public static interface ZoneTransferHandler {
	/**
	 * Handles a Zone Transfer.
	 */

	/**
	 * Called when an AXFR transfer begins.
	 */
	public void startAXFR() throws ZoneTransferException;

	/**
	 * Called when an IXFR transfer begins.
	 */
	public void startIXFR() throws ZoneTransferException;

	/**
	 * Called when a series of IXFR deletions begins.
	 * @param soa The starting SOA.
	 */
	public void startIXFRDeletes(Record soa) throws ZoneTransferException;

	/**
	 * Called when a series of IXFR adds begins.
	 * @param soa The starting SOA.
	 */
	public void startIXFRAdds(Record soa) throws ZoneTransferException;

	/**
	 * Called for each content record in an AXFR.
	 * @param r The DNS record.
	 */
	public void handleRecord(Record r) throws ZoneTransferException;
};

private static class BasicHandler implements ZoneTransferHandler {
	private List axfr;
	private List ixfr;

	public void startAXFR() {
		axfr = new ArrayList();
	}

	public void startIXFR() {
		ixfr = new ArrayList();
	}

	public void startIXFRDeletes(Record soa) {
		Delta delta = new Delta();
		delta.deletes.add(soa);
		delta.start = getSOASerial(soa);
		ixfr.add(delta);
	}

	public void startIXFRAdds(Record soa) {
		Delta delta = (Delta) ixfr.get(ixfr.size() - 1);
		delta.adds.add(soa);
		delta.end = getSOASerial(soa);
	}

	public void handleRecord(Record r) {
		List list;
		if (ixfr != null) {
			Delta delta = (Delta) ixfr.get(ixfr.size() - 1);
			if (delta.adds.size() > 0)
				list = delta.adds;
			else
				list = delta.deletes;
		} else
			list = axfr;
		list.add(r);
	}
};

private
ZoneTransferIn() {}

private
ZoneTransferIn(Name zone, int xfrtype, long serial, boolean fallback,
	       SocketAddress address, TSIG key)
{
	this.address = address;
	this.tsig = key;
	if (zone.isAbsolute())
		zname = zone;
	else {
		try {
			zname = Name.concatenate(zone, Name.root);
		}
		catch (NameTooLongException e) {
			throw new IllegalArgumentException("ZoneTransferIn: " +
							   "name too long");
		}
	}
	qtype = xfrtype;
	dclass = DClass.IN;
	ixfr_serial = serial;
	want_fallback = fallback;
	state = INITIALSOA;
}

/**
 * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer).
 * @param zone The zone to transfer.
 * @param address The host/port from which to transfer the zone.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newAXFR(Name zone, SocketAddress address, TSIG key) {
	return new ZoneTransferIn(zone, Type.AXFR, 0, false, address, key);
}

/**
 * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer).
 * @param zone The zone to transfer.
 * @param host The host from which to transfer the zone.
 * @param port The port to connect to on the server, or 0 for the default.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newAXFR(Name zone, String host, int port, TSIG key)
throws UnknownHostException
{
	if (port == 0)
		port = SimpleResolver.DEFAULT_PORT;
	return newAXFR(zone, new InetSocketAddress(host, port), key);
}

/**
 * Instantiates a ZoneTransferIn object to do an AXFR (full zone transfer).
 * @param zone The zone to transfer.
 * @param host The host from which to transfer the zone.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newAXFR(Name zone, String host, TSIG key)
throws UnknownHostException
{
	return newAXFR(zone, host, 0, key);
}

/**
 * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone
 * transfer).
 * @param zone The zone to transfer.
 * @param serial The existing serial number.
 * @param fallback If true, fall back to AXFR if IXFR is not supported.
 * @param address The host/port from which to transfer the zone.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newIXFR(Name zone, long serial, boolean fallback, SocketAddress address,
	TSIG key)
{
	return new ZoneTransferIn(zone, Type.IXFR, serial, fallback, address,
				  key);
}

/**
 * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone
 * transfer).
 * @param zone The zone to transfer.
 * @param serial The existing serial number.
 * @param fallback If true, fall back to AXFR if IXFR is not supported.
 * @param host The host from which to transfer the zone.
 * @param port The port to connect to on the server, or 0 for the default.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newIXFR(Name zone, long serial, boolean fallback, String host, int port,
	TSIG key)
throws UnknownHostException
{
	if (port == 0)
		port = SimpleResolver.DEFAULT_PORT;
	return newIXFR(zone, serial, fallback,
		       new InetSocketAddress(host, port), key);
}

/**
 * Instantiates a ZoneTransferIn object to do an IXFR (incremental zone
 * transfer).
 * @param zone The zone to transfer.
 * @param serial The existing serial number.
 * @param fallback If true, fall back to AXFR if IXFR is not supported.
 * @param host The host from which to transfer the zone.
 * @param key The TSIG key used to authenticate the transfer, or null.
 * @return The ZoneTransferIn object.
 * @throws UnknownHostException The host does not exist.
 */
public static ZoneTransferIn
newIXFR(Name zone, long serial, boolean fallback, String host, TSIG key)
throws UnknownHostException
{
	return newIXFR(zone, serial, fallback, host, 0, key);
}

/**
 * Gets the name of the zone being transferred.
 */
public Name
getName() {
	return zname;
}

/**
 * Gets the type of zone transfer (either AXFR or IXFR).
 */
public int
getType() {
	return qtype;
}

/**
 * Sets a timeout on this zone transfer.  The default is 900 seconds (15
 * minutes).
 * @param secs The maximum amount of time that this zone transfer can take.
 */
public void
setTimeout(int secs) {
	if (secs < 0)
		throw new IllegalArgumentException("timeout cannot be " +
						   "negative");
	timeout = 1000L * secs;
}

/**
 * Sets an alternate DNS class for this zone transfer.
 * @param dclass The class to use instead of class IN.
 */
public void
setDClass(int dclass) {
	DClass.check(dclass);
	this.dclass = dclass;
}

/**
 * Sets the local address to bind to when sending messages.
 * @param addr The local address to send messages from.
 */
public void
setLocalAddress(SocketAddress addr) {
	this.localAddress = addr;
}

private void
openConnection() throws IOException {
	long endTime = System.currentTimeMillis() + timeout;
	client = new TCPClient(endTime);
	if (localAddress != null)
		client.bind(localAddress);
	client.connect(address);
}

private void
sendQuery() throws IOException {
	Record question = Record.newRecord(zname, qtype, dclass);

	Message query = new Message();
	query.getHeader().setOpcode(Opcode.QUERY);
	query.addRecord(question, Section.QUESTION);
	if (qtype == Type.IXFR) {
		Record soa = new SOARecord(zname, dclass, 0, Name.root,
					   Name.root, ixfr_serial,
					   0, 0, 0, 0);
		query.addRecord(soa, Section.AUTHORITY);
	}
	if (tsig != null) {
		tsig.apply(query, null);
		verifier = new TSIG.StreamVerifier(tsig, query.getTSIG());
	}
	byte [] out = query.toWire(Message.MAXLENGTH);
	client.send(out);
}

private static long
getSOASerial(Record rec) {
	SOARecord soa = (SOARecord) rec;
	return soa.getSerial();
}

private void
logxfr(String s) {
	if (Options.check("verbose"))
		System.out.println(zname + ": " + s);
}

private void
fail(String s) throws ZoneTransferException {
	throw new ZoneTransferException(s);
}

private void
fallback() throws ZoneTransferException {
	if (!want_fallback)
		fail("server doesn't support IXFR");

	logxfr("falling back to AXFR");
	qtype = Type.AXFR;
	state = INITIALSOA;
}

private void
parseRR(Record rec) throws ZoneTransferException {
	int type = rec.getType();
	Delta delta;

	switch (state) {
	case INITIALSOA:
		if (type != Type.SOA)
			fail("missing initial SOA");
		initialsoa = rec;
		// Remember the serial number in the initial SOA; we need it
		// to recognize the end of an IXFR.
		end_serial = getSOASerial(rec);
		if (qtype == Type.IXFR &&
		    Serial.compare(end_serial, ixfr_serial) <= 0)
		{
			logxfr("up to date");
			state = END;
			break;
		}
		state = FIRSTDATA;
		break;

	case FIRSTDATA:
		// If the transfer begins with 1 SOA, it's an AXFR.
		// If it begins with 2 SOAs, it's an IXFR.
		if (qtype == Type.IXFR && type == Type.SOA &&
		    getSOASerial(rec) == ixfr_serial)
		{
			rtype = Type.IXFR;
			handler.startIXFR();
			logxfr("got incremental response");
			state = IXFR_DELSOA;
		} else {
			rtype = Type.AXFR;
			handler.startAXFR();
			handler.handleRecord(initialsoa);
			logxfr("got nonincremental response");
			state = AXFR;
		}
		parseRR(rec); // Restart...
		return;

	case IXFR_DELSOA:
		handler.startIXFRDeletes(rec);
		state = IXFR_DEL;
		break;

	case IXFR_DEL:
		if (type == Type.SOA) {
			current_serial = getSOASerial(rec);
			state = IXFR_ADDSOA;
			parseRR(rec); // Restart...
			return;
		}
		handler.handleRecord(rec);
		break;

	case IXFR_ADDSOA:
		handler.startIXFRAdds(rec);
		state = IXFR_ADD;
		break;

	case IXFR_ADD:
		if (type == Type.SOA) {
			long soa_serial = getSOASerial(rec);
			if (soa_serial == end_serial) {
				state = END;
				break;
			} else if (soa_serial != current_serial) {
				fail("IXFR out of sync: expected serial " +
				     current_serial + " , got " + soa_serial);
			} else {
				state = IXFR_DELSOA;
				parseRR(rec); // Restart...
				return;
			}
		}
		handler.handleRecord(rec);
		break;

	case AXFR:
		// Old BINDs sent cross class A records for non IN classes.
		if (type == Type.A && rec.getDClass() != dclass)
			break;
		handler.handleRecord(rec);
		if (type == Type.SOA) {
			state = END;
		}
		break;

	case END:
		fail("extra data");
		break;

	default:
		fail("invalid state");
		break;
	}
}

private void
closeConnection() {
	try {
		if (client != null)
			client.cleanup();
	}
	catch (IOException e) {
	}
}

private Message
parseMessage(byte [] b) throws WireParseException {
	try {
		return new Message(b);
	}
	catch (IOException e) {
		if (e instanceof WireParseException)
			throw (WireParseException) e;
		throw new WireParseException("Error parsing message");
	}
}

private void
doxfr() throws IOException, ZoneTransferException {
	sendQuery();
	while (state != END) {
		byte [] in = client.recv();
		Message response =  parseMessage(in);
		if (response.getHeader().getRcode() == Rcode.NOERROR &&
		    verifier != null)
		{
			TSIGRecord tsigrec = response.getTSIG();

			int error = verifier.verify(response, in);
			if (error != Rcode.NOERROR)
				fail("TSIG failure");
		}

		Record [] answers = response.getSectionArray(Section.ANSWER);

		if (state == INITIALSOA) {
			int rcode = response.getRcode();
			if (rcode != Rcode.NOERROR) {
				if (qtype == Type.IXFR &&
				    rcode == Rcode.NOTIMP)
				{
					fallback();
					doxfr();
					return;
				}
				fail(Rcode.string(rcode));
			}

			Record question = response.getQuestion();
			if (question != null && question.getType() != qtype) {
				fail("invalid question section");
			}

			if (answers.length == 0 && qtype == Type.IXFR) {
				fallback();
				doxfr();
				return;
			}
		}

		for (int i = 0; i < answers.length; i++) {
			parseRR(answers[i]);
		}

		if (state == END && verifier != null &&
		    !response.isVerified())
			fail("last message must be signed");
	}
}

/**
 * Does the zone transfer.
 * @param handler The callback object that handles the zone transfer data.
 * @throws IOException The zone transfer failed to due an IO problem.
 * @throws ZoneTransferException The zone transfer failed to due a problem
 * with the zone transfer itself.
 */
public void
run(ZoneTransferHandler handler) throws IOException, ZoneTransferException {
	this.handler = handler;
	try {
		openConnection();
		doxfr();
	}
	finally {
		closeConnection();
	}
}

/**
 * Does the zone transfer.
 * @return A list, which is either an AXFR-style response (List of Records),
 * and IXFR-style response (List of Deltas), or null, which indicates that
 * an IXFR was performed and the zone is up to date.
 * @throws IOException The zone transfer failed to due an IO problem.
 * @throws ZoneTransferException The zone transfer failed to due a problem
 * with the zone transfer itself.
 */
public List
run() throws IOException, ZoneTransferException {
	BasicHandler handler = new BasicHandler();
	run(handler);
	if (handler.axfr != null)
		return handler.axfr;
	return handler.ixfr;
}

private BasicHandler
getBasicHandler() throws IllegalArgumentException {
	if (handler instanceof BasicHandler)
		return (BasicHandler) handler;
	throw new IllegalArgumentException("ZoneTransferIn used callback " +
					   "interface");
}

/**
 * Returns true if the response is an AXFR-style response (List of Records).
 * This will be true if either an IXFR was performed, an IXFR was performed
 * and the server provided a full zone transfer, or an IXFR failed and
 * fallback to AXFR occurred.
 */
public boolean
isAXFR() {
	return (rtype == Type.AXFR);
}

/**
 * Gets the AXFR-style response.
 * @throws IllegalArgumentException The transfer used the callback interface,
 * so the response was not stored.
 */
public List
getAXFR() {
	BasicHandler handler = getBasicHandler();
	return handler.axfr;
}

/**
 * Returns true if the response is an IXFR-style response (List of Deltas).
 * This will be true only if an IXFR was performed and the server provided
 * an incremental zone transfer.
 */
public boolean
isIXFR() {
	return (rtype == Type.IXFR);
}

/**
 * Gets the IXFR-style response.
 * @throws IllegalArgumentException The transfer used the callback interface,
 * so the response was not stored.
 */
public List
getIXFR() {
	BasicHandler handler = getBasicHandler();
	return handler.ixfr;
}

/**
 * Returns true if the response indicates that the zone is up to date.
 * This will be true only if an IXFR was performed.
 * @throws IllegalArgumentException The transfer used the callback interface,
 * so the response was not stored.
 */
public boolean
isCurrent() {
	BasicHandler handler = getBasicHandler();
	return (handler.axfr == null && handler.ixfr == null);
}

}