dns.c 13.9 KB
Newer Older
Ted Lemon's avatar
Ted Lemon committed
1
2
/* dns.c

3
   Domain Name Service subroutines. */
Ted Lemon's avatar
Ted Lemon committed
4
5
6

/*
 * Copyright (C) 1992 by Ted Lemon.
Ted Lemon's avatar
Ted Lemon committed
7
 * Copyright (c) 1997, 1998 The Internet Software Consortium.
Ted Lemon's avatar
Ted Lemon committed
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
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of The Internet Software Consortium nor the names
 *    of its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INTERNET SOFTWARE CONSORTIUM AND
 * CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE INTERNET SOFTWARE CONSORTIUM OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * This file is based on software written in 1992 by Ted Lemon for
 * a portable network boot loader.   That original code base has been
 * substantially modified for use in the Internet Software Consortium
 * DHCP suite.
 *
42
43
44
45
46
 * These later modifications were done on behalf of the Internet
 * Software Consortium by Ted Lemon <mellon@fugue.com> in cooperation
 * with Vixie Enterprises.  To learn more about the Internet Software
 * Consortium, see ``http://www.vix.com/isc''.  To learn more about
 * Vixie Enterprises, see ``http://www.vix.com''.
Ted Lemon's avatar
Ted Lemon committed
47
48
49
50
 */

#ifndef lint
static char copyright[] =
Ted Lemon's avatar
Ted Lemon committed
51
"$Id: dns.c,v 1.7 1998/03/15 20:50:53 mellon Exp $ Copyright (c) 1997 The Internet Software Consortium.  All rights reserved.\n";
Ted Lemon's avatar
Ted Lemon committed
52
53
54
55
56
#endif /* not lint */

#include "dhcpd.h"
#include "arpa/nameser.h"

57
58
59
60
61
62
int dns_protocol_initialized;
int dns_protocol_fd;

static int addlabel PROTO ((u_int8_t *, char *));
static int skipname PROTO ((u_int8_t *));
static int copy_out_name PROTO ((u_int8_t *, u_int8_t *, char *));
63
64
65
static int nslookup PROTO ((u_int8_t, char *, int, u_int16_t, u_int16_t));
static int zonelookup PROTO ((u_int8_t, char *, int, u_int16_t));
u_int16_t dns_port;
66

Ted Lemon's avatar
Ted Lemon committed
67
68
#define DNS_QUERY_HASH_SIZE	293
struct dns_query *dns_query_hash [DNS_QUERY_HASH_SIZE];
69

Ted Lemon's avatar
Ted Lemon committed
70
71
/* Initialize the DNS protocol. */

72
void dns_startup ()
Ted Lemon's avatar
Ted Lemon committed
73
{
74
	struct servent *srv;
Ted Lemon's avatar
Ted Lemon committed
75
76
77
	struct sockaddr_in from;

	/* Only initialize icmp once. */
78
79
80
	if (dns_protocol_initialized)
		error ("attempted to reinitialize dns protocol");
	dns_protocol_initialized = 1;
Ted Lemon's avatar
Ted Lemon committed
81
82

	/* Get the protocol number (should be 1). */
83
	srv = getservbyname ("domain", "tcp");
84
	if (srv)
85
86
87
		dns_port = srv -> s_port;
	else
		dns_port = htons (53);
Ted Lemon's avatar
Ted Lemon committed
88

89
	/* Get a socket for the DNS protocol. */
90
	dns_protocol_fd = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP);
91
	if (dns_protocol_fd < 0)
92
		error ("unable to create dns socket: %m");
Ted Lemon's avatar
Ted Lemon committed
93

Ted Lemon's avatar
Ted Lemon committed
94
	first_name_server ();
95

96
	add_protocol ("dns", dns_protocol_fd, dns_packet, 0);
Ted Lemon's avatar
Ted Lemon committed
97
98
99
100
101
102
103
104
105
}

/* Label manipulation stuff; see RFC1035, page 28 section 4.1.2 and
   page 30, section 4.1.4. */

/* addlabel copies a label into the specified buffer, putting the length of
   the label in the first character, the contents of the label in subsequent
   characters, and returning the length of the conglomeration. */

106
107
108
static int addlabel (buf, label)
	u_int8_t *buf;
	char *label;
Ted Lemon's avatar
Ted Lemon committed
109
{
110
111
112
	*buf = strlen (label);
	memcpy (buf + 1, label, *buf);
	return *buf + 1;
Ted Lemon's avatar
Ted Lemon committed
113
114
115
116
117
}

/* skipname skips over all of the labels in a single domain name,
   returning the length of the domain name. */

118
119
static int skipname (label)
     u_int8_t *label;
Ted Lemon's avatar
Ted Lemon committed
120
{
121
122
123
124
125
	if (*label & INDIR_MASK)
		return 2;
	if (*label == 0)
		return 1;
	return *label + 1 + skipname (label + *label + 1);
Ted Lemon's avatar
Ted Lemon committed
126
127
128
129
130
131
}

/* copy_out_name copies out the name appearing at the specified location
   into a string, stored as fields seperated by dots rather than lengths
   and labels.   The length of the label-formatted name is returned. */

132
133
134
135
static int copy_out_name (base, name, buf)
     u_int8_t *base;
     u_int8_t *name;
     char *buf;
Ted Lemon's avatar
Ted Lemon committed
136
{
137
138
139
140
141
142
143
144
145
146
147
148
	if (*name & INDIR_MASK) {
		int offset = (*name & ~INDIR_MASK) + (*name + 1);
		return copy_out_name (base, base + offset, buf);
	}
	if (!*name) {
		*buf = 0;
		return 1;
	}
	memcpy (buf, name + 1, *name);
	*(buf + *name) = '.';
	return (*name + 1
		+ copy_out_name (base, name + *name + 1, buf + *name + 1));
Ted Lemon's avatar
Ted Lemon committed
149
150
}

Ted Lemon's avatar
Ted Lemon committed
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
/* Compute a hash on the question. */

static inline u_int32_t dns_hash_question (struct dns_question *question)
{
	u_int32_t sum;
	u_int32_t remainder;
	u_int32_t *p = (u_int32_t *)question;
	u_int8_t *s;

	/* First word. */
	sum = *p++;
	s = (u_int8_t *)p;

	remainder = 0;
	while (s [0]) {
		remainder = s [0];
		if (s [1]) {
			remainder = (remainder << 8) + s [1];
			if (s [2]) {
				remainder = (remainder << 8) + s [2];
				if (s [3])
					remainder = (remainder << 8) + s [3];
				else
					goto done;
			} else
				goto done;
		} else {
		      done:
			sum += remainder;
			break;
		}
		if ((sum & 0x80000000) && (remainder & 0x80000000))
			++sum;
		sum += remainder;
		s += 4;
	}

	while (sum > DNS_QUERY_HASH_SIZE) {
		remainder = sum / DNS_QUERY_HASH_SIZE;
		sum = sum % DNS_QUERY_HASH_SIZE;
		while (remainder) {
			sum += remainder % DNS_QUERY_HASH_SIZE;
			remainder /= DNS_QUERY_HASH_SIZE;
		}
	} 

	return sum;
}

/* Find a query that matches the specified name.  If one can't be
   found, and new is nonzero, allocate one, hash it in, and save the
   question.  Otherwise, if new is nonzero, free() the question.
   Return the query if one was found or allocated. */

struct dns_query *find_dns_query (question, new)
	struct dns_question *question;
	int new;
{
	int hash = dns_hash_question (question);
	struct dns_query *q;

	for (q = dns_query_hash [hash]; q; q = q -> next) {
		if (q -> question -> type == question -> type &&
		    q -> question -> class == question -> class &&
		    !strcmp (q -> question -> data, question -> data))
			break;
	}
	if (q || !new) {
		if (new)
			free (question);
		return q;
	}

	/* Allocate and zap a new query. */
	q = (struct dns_query *)malloc (sizeof (struct dns_query));
	memset (q, 0, sizeof *q);

	/* All we need to set up is the question and the hash. */
	q -> question = question;
	q -> next = dns_query_hash [hash];
	dns_query_hash [hash] = q;
	q -> hash = hash;
	return q;
}

/* Free up all memory associated with a DNS query and remove it from the
   query hash. */

void destroy_dns_query (query)
	struct dns_query *query;
{
	struct dns_query *q;

	/* Free up attached free data. */
	if (query -> question)
		free (query -> question);
	if (query -> answer)
		free (query -> answer);
	if (query -> query)
		free (query -> query);

	/* Remove query from hash table. */
	if (dns_query_hash [query -> hash] == query)
		dns_query_hash [query -> hash] = query -> next;
	else {
		for (q = dns_query_hash [query -> hash];
		     q -> next && q -> next != query; q = q -> next)
			;
		if (q -> next)
			q -> next = query -> next;
	}

	/* Free the query structure. */
	free (query);
}

Ted Lemon's avatar
Ted Lemon committed
267
/* ns_inaddr_lookup constructs a PTR lookup query for an internet address -
Ted Lemon's avatar
Ted Lemon committed
268
269
   e.g., 1.200.9.192.in-addr.arpa.   It then passes it on to ns_query for
   completion. */
Ted Lemon's avatar
Ted Lemon committed
270

271
struct dns_query *ns_inaddr_lookup (inaddr, wakeup)
272
	struct iaddr inaddr;
273
	struct dns_wakeup *wakeup;
Ted Lemon's avatar
Ted Lemon committed
274
{
Ted Lemon's avatar
Ted Lemon committed
275
	unsigned char query [512];
276
	unsigned char *s;
277
278
279
	unsigned char *label;
	int i;
	unsigned char c;
Ted Lemon's avatar
Ted Lemon committed
280
281
282
283
284
285
	struct dns_question *question;

	/* First format the query in the internal format. */
	sprintf (query, "%d.%d.%d.%d.in-addr.arpa.",
		 inaddr.iabuf [0], inaddr.iabuf [1],
		 inaddr.iabuf [2], inaddr.iabuf [3]);
286

Ted Lemon's avatar
Ted Lemon committed
287
288
289
290
291
292
293
294
295
296
	question = (struct dns_question *)malloc (strlen (query) +
						  sizeof *question);
	if (!question)
		return (struct dns_query *)-1;
	question -> type = T_PTR;
	question -> class = C_IN;
	strcpy (question -> data, query);

	/* Now format the query for the name server. */
	s = query;
297
298

	/* Copy out the digits. */
299
300
	for (i = 3; i >= 0; --i) {
		label = s++;
Ted Lemon's avatar
Ted Lemon committed
301
302
303
		sprintf (s, "%d", inaddr.iabuf [i]);
		*label = strlen (s);
		s += *label;
Ted Lemon's avatar
Ted Lemon committed
304
	}
305
306
307
	s += addlabel (s, "in-addr");
	s += addlabel (s, "arpa");
	*s++ = 0;
Ted Lemon's avatar
Ted Lemon committed
308

309
310
311
312
313
314
315
316
	/* Set the query type. */
	putUShort (s, T_PTR);
	s += sizeof (u_int16_t);

	/* Set the query class. */
	putUShort (s, C_IN);
	s += sizeof (u_int16_t);

Ted Lemon's avatar
Ted Lemon committed
317
	return ns_query (question, query, s - query, wakeup);
318
}
Ted Lemon's avatar
Ted Lemon committed
319

Ted Lemon's avatar
Ted Lemon committed
320
321
322
323
324
325
326
327
328
329
330
/* Try to satisfy a query out of the local cache.  If no answer has
   been cached, and if there isn't already a query pending on this
   question, send it.  If the query can be immediately satisfied,
   a pointer to the dns_query structure is returned.  If the query
   can't even be made for some reason, (struct dns_query *)-1 is
   returned.  Otherwise, the null pointer is returned, indicating that
   a wakeup will be performed later when the answer comes back. */

struct dns_query *ns_query (question, formatted_query, len, wakeup)
	struct dns_question *question;
	unsigned char *formatted_query;
331
332
	int len;
	struct dns_wakeup *wakeup;
Ted Lemon's avatar
Ted Lemon committed
333
{
334
	HEADER *hdr;
335
336
	struct dns_query *query;
	unsigned char *s;
Ted Lemon's avatar
Ted Lemon committed
337
338
339
340
341
342
343
	unsigned char buf [512];

	/* If the query won't fit, don't bother setting it up. */
	if (len > 255) {
		free (question);
		return (struct dns_query *)-1;
	}
344
345
346

	/* See if there's already a query for this name, and allocate a
	   query if none exists. */
Ted Lemon's avatar
Ted Lemon committed
347
	query = find_dns_query (question, 1);
348
349

	/* If we can't allocate a query, report that the query failed. */
Ted Lemon's avatar
Ted Lemon committed
350
	if (!query)
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
		return (struct dns_query *)-1;

	/* If the query has already been answered, return it. */
	if (query -> expiry > cur_time)
		return query;

	/* The query hasn't yet been answered, so we have to wait, one
	   way or another.   Put the wakeup on the list. */
	if (wakeup) {
		wakeup -> next = query -> wakeups;
		query -> wakeups = wakeup;
	}

	/* If the query has already been sent, but we don't yet have
	   an answer, we're done. */
	if (query -> sent)
		return (struct dns_query *)0;
368

369
	/* Construct a header... */
Ted Lemon's avatar
Ted Lemon committed
370
	hdr = (HEADER *)buf;
371
	memset (hdr, 0, sizeof *hdr);
372
	hdr -> id = query -> id;
373
374
375
376
	hdr -> rd = 1;
	hdr -> opcode = QUERY;
	hdr -> qdcount = htons (1);

Ted Lemon's avatar
Ted Lemon committed
377
	/* Copy the formatted name into the buffer. */
378
	s = (unsigned char *)hdr + 1;
Ted Lemon's avatar
Ted Lemon committed
379
	memcpy (s, formatted_query, len);
380

381
382
	/* Figure out how long the whole message is */
	s += len;
Ted Lemon's avatar
Ted Lemon committed
383
384
385
386
387
388
389
390
391
	query -> len = s - buf;

	/* Save the raw query data. */
	query -> query = malloc (len);
	if (!query -> query) {
		destroy_dns_query (query);
		return (struct dns_query *)-1;
	}
	memcpy (query, buf, query -> len);
392
393
394

	/* Flag the query as having been sent. */
	query -> sent = 1;
395
396

	/* Send the query. */
397
	dns_timeout (query);
398

399
400
	/* No answer yet, obviously. */
	return (struct dns_query *)0;
Ted Lemon's avatar
Ted Lemon committed
401
402
}

403
/* Retransmit a DNS query. */
404

405
406
407
408
409
void dns_timeout (qv)
	void *qv;
{
	struct dns_query *query = qv;
	int status;
410

411
412
413
	/* Choose the server to send to. */
	if (!query -> next_server)
		query -> next_server = first_name_server ();
414

415
416
417
	/* Send the query. */
	if (query -> next_server)
		status = sendto (dns_protocol_fd,
Ted Lemon's avatar
Ted Lemon committed
418
				 query -> query, query -> len, 0,
419
420
421
422
423
				 ((struct sockaddr *)&query ->
				  next_server -> addr),
				 sizeof query -> next_server -> addr);
	else
		status = -1;
424

425
426
	/* Look for the next server... */
	query -> next_server = query -> next_server -> next;
427

428
429
430
	/* If this is our first time, backoff one second. */
	if (!query -> backoff)
		query -> backoff = 1;
431

432
433
434
	/* If the send failed, don't advance the backoff. */
	else if (status < 0)
		;
435

436
437
438
439
440
441
442
	/* If we haven't run out of servers to try, don't backoff. */
	else if (query -> next_server)
		;

	/* If we haven't backed off enough yet, back off some more. */
	else if (query -> backoff < 30)
		query -> backoff += random() % query -> backoff;
443

444
445
	/* Set up the timeout. */
	add_timeout (cur_time + query -> backoff, dns_timeout, query);
446
447
}

448
449
/* Process a reply from a name server. */

450
void dns_packet (protocol)
451
	struct protocol *protocol;
Ted Lemon's avatar
Ted Lemon committed
452
{
453
454
	HEADER *ns_header;
	struct sockaddr_in from;
455
456
	struct dns_wakeup *wakeup;
	unsigned char buf [512];
Ted Lemon's avatar
Ted Lemon committed
457
458
459
460
	union {
		unsigned char u [512];
		struct dns_question q;
	} qbuf;
461
	unsigned char *base;
462
	unsigned char *dptr, *name;
463
464
465
466
467
468
	u_int16_t type;
	u_int16_t class;
	TIME ttl;
	u_int16_t rdlength;
	int len, status;
	int i;
469
	struct dns_query *query;
470
471

	len = sizeof from;
472
	status = recvfrom (protocol -> fd, buf, sizeof buf, 0,
473
474
			  (struct sockaddr *)&from, &len);
	if (status < 0) {
475
476
477
478
479
480
481
		warn ("dns_packet: %m");
		return;
	}

	/* Response is too long? */
	if (len > 512) {
		warn ("dns_packet: dns message too long (%d)", len);
482
483
		return;
	}
Ted Lemon's avatar
Ted Lemon committed
484

485
486
	ns_header = (HEADER *)buf;
	base = (unsigned char *)(ns_header + 1);
Ted Lemon's avatar
Ted Lemon committed
487

488
489
490
491
492
493
	/* Parse the response... */
	dptr = base;

	/* If this is a response to a query from us, there should have
           been only one query. */
	if (ntohs (ns_header -> qdcount) != 1) {
Ted Lemon's avatar
Ted Lemon committed
494
495
496
		warn ("Bogus DNS answer packet from %s claims %d queries.\n",
		      inet_ntoa (from.sin_addr),
		      ntohs (ns_header -> qdcount));
497
498
		return;
	}
Ted Lemon's avatar
Ted Lemon committed
499

500
501
	/* Find the start of the name in the query. */
	name = dptr;
Ted Lemon's avatar
Ted Lemon committed
502

503
	/* Skip over the name. */
Ted Lemon's avatar
Ted Lemon committed
504
	dptr += copy_out_name (name, name, qbuf.q.data);
505
506

	/* Skip over the query type and query class. */
Ted Lemon's avatar
Ted Lemon committed
507
508
509
510
	qbuf.q.type = getUShort (dptr);
	dptr += sizeof (u_int16_t);
	qbuf.q.class = getUShort (dptr);
	dptr += sizeof (u_int16_t);
511
512

	/* See if we asked this question. */
Ted Lemon's avatar
Ted Lemon committed
513
	query = find_dns_query (&qbuf.q, 0);
514
	if (!query) {
Ted Lemon's avatar
Ted Lemon committed
515
516
warn ("got answer for question %s from DNS, which we didn't ask.",
qbuf.q.data);
517
		return;
518
	}
519

Ted Lemon's avatar
Ted Lemon committed
520
note ("got answer for question %s from DNS", qbuf.q.data);
521
522
523
524

	/* Wake up everybody who's waiting. */
	for (wakeup = query -> wakeups; wakeup; wakeup = wakeup -> next) {
		(*wakeup -> func) (query);
525
	}
Ted Lemon's avatar
Ted Lemon committed
526
}