source: trunk/minix/commands/simple/nonamed.c@ 15

Last change on this file since 15 was 9, checked in by Mattia Monga, 14 years ago

Minix 3.1.2a

File size: 58.3 KB
Line 
1/* nonamed - Not a name daemon, but plays one on TV.
2 * Author: Kees J. Bot
3 * 29 Nov 1994
4 */
5static const char version[] = "2.7";
6
7/* Use the file reading gethostent() family of functions. */
8#define sethostent _sethostent
9#define gethostent _gethostent
10#define endhostent _endhostent
11
12#define nil ((void*)0)
13#include <sys/types.h>
14#include <stdio.h>
15#include <syslog.h>
16#include <stddef.h>
17#include <stdlib.h>
18#include <unistd.h>
19#include <fcntl.h>
20#include <errno.h>
21#include <string.h>
22#include <time.h>
23#include <limits.h>
24#include <signal.h>
25#include <assert.h>
26#include <sys/stat.h>
27#include <sys/ioctl.h>
28#include <sys/asynchio.h>
29#include <net/hton.h>
30#include <net/netlib.h>
31#include <net/gen/in.h>
32#include <net/gen/inet.h>
33#include <net/gen/nameser.h>
34#include <net/gen/resolv.h>
35#include <net/gen/netdb.h>
36#include <net/gen/socket.h>
37#include <net/gen/tcp.h>
38#include <net/gen/tcp_io.h>
39#include <net/gen/udp.h>
40#include <net/gen/udp_hdr.h>
41#include <net/gen/udp_io.h>
42#include <net/gen/dhcp.h>
43
44#include <minix/paths.h>
45
46#define HTTL 3600L /* Default time to live for /etc/hosts data. */
47#define SHORT_TIMEOUT 2 /* If you expect an answer soon. */
48#define MEDIUM_TIMEOUT 4 /* Soon, but not that soon. */
49#define LONG_TIMEOUT 300 /* For stream connections to a real named. */
50#define N_IDS 256 /* Keep track of this many queries. */
51#define N_DATAMAX (4096*sizeof(char *)) /* Default response cache size. */
52#define N_NAMEDS 8 /* Max # name daemons we can keep track of. */
53#define NO_FD (-1) /* No name daemon channel here. */
54#define T_NXD ((u16_t) -1) /* A "type" signalling a nonexistent domain. */
55
56/* Can't do async I/O under standard Minix, so forget about TCP. */
57#define DO_TCP (__minix_vmd || !__minix)
58
59/* Host data, file to store our process id in, our cache, DHCP's cache. */
60static char HOSTS[]= _PATH_HOSTS;
61static char PIDFILE[]= "/usr/run/nonamed.pid";
62static char NNCACHE[]= "/usr/adm/nonamed.cache";
63static char DHCPCACHE[]= _PATH_DHCPCACHE;
64
65/* Magic string to head the cache file. */
66static char MAGIC[4]= "NND\2";
67
68#define arraysize(a) (sizeof(a) / sizeof((a)[0]))
69#define arraylimit(a) ((a) + arraysize(a))
70#define between(a, c, z) ((unsigned) ((c) - (a)) <= (unsigned) ((z) - (a)))
71
72/* The start of time and the far future. */
73#define IMMEDIATE ((time_t) 0)
74#define NEVER ((time_t) ((time_t) -1 < 0 ? LONG_MAX : ULONG_MAX))
75
76static unsigned debug; /* Debug level. */
77static time_t now; /* Current time. */
78static u32_t stale; /* Extension time for stale data. */
79static u32_t httl; /* TTL for /etc/hosts data. */
80static int reinit, done; /* Reinit config / program is done. */
81static int single; /* Run single on a nondefault interface. */
82static int localonly; /* Only accept local queries. */
83#define LOCALHOST 0x7F000001
84
85static void report(const char *label)
86{
87 fprintf(stderr, "nonamed: %s: %s\n", label, strerror(errno));
88}
89
90static void fatal(const char *label)
91{
92 report(label);
93 if (debug >= 3) { fflush(nil); abort(); }
94 exit(1);
95}
96
97static void *allocate(void *mem, size_t size)
98{
99 if ((mem= realloc(mem, size)) == nil) fatal("malloc()");
100 return mem;
101}
102
103static void deallocate(void *mem)
104{
105 free(mem);
106}
107
108static char *timegmt(time_t t)
109/* Simple "time in seconds to GMT time today" converter. */
110{
111 unsigned h, m, s;
112 static char asctime[sizeof("00:00:00")];
113
114 s= t % 60;
115 t /= 60;
116 m= t % 60;
117 t /= 60;
118 h= t % 24;
119 sprintf(asctime, "%02u:%02u:%02u", h, m, s);
120 return asctime;
121}
122
123static char *nowgmt(void)
124{
125 return timegmt(now);
126}
127
128#define PC(n) ((void) sizeof(char [sizeof(*(n)) == 1]), (char *) (n))
129#define namecpy(n1, n2) strcpy(PC(n1), PC(n2))
130#define namecat(n1, n2) strcat(PC(n1), PC(n2))
131#define namechr(n, c) ((u8_t *) strchr(PC(n), (c)))
132#define namecmp(n1, n2) strcasecmp(PC(n1), PC(n2))
133#define namencmp(n1, n2, len) strncasecmp(PC(n1), PC(n2), len)
134
135typedef struct dns { /* A DNS packet. */
136 dns_hdr_t hdr; /* DNS header. */
137 u8_t data[PACKETSZ - sizeof(dns_hdr_t)]; /* DNS data. */
138} dns_t;
139
140/* Addres of DNS packet to octet address, or vv. */
141#define dns2oct(dp) ((u8_t *) (dp))
142#define oct2dns(dp) ((dns_t *) (dp))
143
144typedef struct query { /* One cached answer to a query. */
145 struct query *less; /* Less recently used. */
146 struct query *more; /* More recently used. */
147 time_t age; /* Time it was added. */
148 time_t stale; /* Time it goes stale by TTL. */
149 u16_t usage; /* Counts of queries answered. */
150 u8_t flags; /* QF_REFRESH. */
151 size_t size; /* Size of DNS packet. */
152 dns_t dns; /* Answer to query as a DNS packet. */
153} query_t;
154
155#define QF_REFRESH 0x01 /* This stale data must be refreshed. */
156#define QU_SHIFT 1 /* To shift usage by when evicting. */
157
158/* Size of new query_t or existing query_t. */
159#define query_allocsize(dnssize) (offsetof(query_t, dns) + (dnssize))
160#define query_size(qp) query_allocsize((qp)->size)
161
162static query_t *mru, *lru; /* Most and least recently used answers. */
163static int q_refresh; /* Set when an entry needs refreshing. */
164
165static void pack16(u8_t *buf, u16_t s)
166/* Pack a 16 bit value into a byte array. */
167{
168 buf[0]= ((u8_t *) &s)[0];
169 buf[1]= ((u8_t *) &s)[1];
170}
171
172static void pack32(u8_t *buf, u32_t l)
173/* Pack a 32 bit value into a byte array. */
174{
175 buf[0]= ((u8_t *) &l)[0];
176 buf[1]= ((u8_t *) &l)[1];
177 buf[2]= ((u8_t *) &l)[2];
178 buf[3]= ((u8_t *) &l)[3];
179}
180
181static u16_t upack16(u8_t *buf)
182/* Unpack a 16 bit value from a byte array. */
183{
184 u16_t s;
185
186 ((u8_t *) &s)[0]= buf[0];
187 ((u8_t *) &s)[1]= buf[1];
188 return s;
189}
190
191static u32_t upack32(u8_t *buf)
192/* Unpack a 32 bit value from a byte array. */
193{
194 u32_t l;
195
196 ((u8_t *) &l)[0]= buf[0];
197 ((u8_t *) &l)[1]= buf[1];
198 ((u8_t *) &l)[2]= buf[2];
199 ((u8_t *) &l)[3]= buf[3];
200 return l;
201}
202
203/* Encoding of RRs: i(paddr), d(omain), l(ong), c(har), s(tring), (s)h(ort). */
204static char *encoding[] = {
205 "c*", /* anything unknown is c* */
206 "i", /* A */
207 "d", /* NS */
208 "d", /* MD */
209 "d", /* MF */
210 "d", /* CNAME */
211 "ddlllll", /* SOA */
212 "d", /* MB */
213 "d", /* MG */
214 "d", /* MR */
215 "c*", /* NULL */
216 "icc*", /* WKS */
217 "d", /* PTR */
218 "ss", /* HINFO */
219 "dd", /* MINFO */
220 "hd", /* MX */
221 "s*", /* TXT */
222};
223
224static char *itoa(char *fmt, u32_t i)
225{
226 static char output[32 + 3 * sizeof(i)];
227
228 sprintf(output, fmt, (unsigned long) i);
229 return output;
230}
231
232static char *classname(unsigned class)
233/* Class name of a resource record, for debug purposes. */
234{
235 static char *classes[] = { "IN", "CS", "CHAOS", "HS" };
236
237 if ((class - C_IN) < arraysize(classes)) return classes[class - C_IN];
238 return itoa("C_%u", class);
239}
240
241static char *typename(unsigned type)
242/* Type name of a resource record, for debug purposes. */
243{
244 static char type_A[][6] = {
245 "A", "NS", "MD", "MF", "CNAME", "SOA", "MB", "MG", "MR", "NULL",
246 "WKS", "PTR", "HINFO", "MINFO", "MX", "TXT",
247 };
248 static char type_AXFR[][6] = {
249 "AXFR", "MAILB", "MAILA", "ANY",
250 };
251 if ((type - T_A) < arraysize(type_A)) return type_A[type - T_A];
252 if ((type - T_AXFR) < arraysize(type_AXFR)) return type_AXFR[type - T_AXFR];
253 return itoa("T_%u", type);
254}
255
256static int print_qrr(dns_t *dp, size_t size, u8_t *cp0, int q)
257/* Print a query (q) or resource record (!q) from 'cp0' in a DNS packet for
258 * debug purposes. Return number of bytes skipped or -1 on error.
259 */
260{
261 u8_t name[MAXDNAME+1];
262 u8_t *cp;
263 char *ep;
264 u8_t *dlim, *rlim;
265 u16_t type, class, rdlength;
266 u32_t ttl;
267 int r;
268
269 cp= cp0;
270 dlim= dns2oct(dp) + size;
271 r= dn_expand(dns2oct(dp), dlim, cp, name, MAXDNAME);
272 if (r == -1) return -1;
273 cp += r;
274 if (cp + 2 * sizeof(u16_t) > dlim) return -1;
275 type= ntohs(upack16(cp));
276 cp += sizeof(u16_t);
277 class= ntohs(upack16(cp));
278 cp += sizeof(u16_t);
279 printf("%-25s", (char *) name);
280 if (q) {
281 /* We're just printing a query segment, stop right here. */
282 printf(" %8s", classname(class));
283 printf(" %-5s", typename(type));
284 return cp - cp0;
285 }
286 if (cp + sizeof(u32_t) + sizeof(u16_t) > dlim) return -1;
287 ttl= ntohl(upack32(cp));
288 cp += sizeof(u32_t);
289 rdlength= ntohs(upack16(cp));
290 cp += sizeof(u16_t);
291 if (cp + rdlength > dlim) return -1;
292 rlim = cp + rdlength;
293 printf(" %5lu", (unsigned long) ttl);
294 printf(" %s", classname(class));
295 printf(" %-5s", typename(type));
296 ep= type < arraysize(encoding) ? encoding[type] : encoding[0];
297 while (*ep != 0) {
298 switch (*ep++) {
299 case 'i':
300 if (cp + sizeof(u32_t) > rlim) return -1;
301 printf(" %s", inet_ntoa(upack32(cp)));
302 cp += sizeof(u32_t);
303 break;
304 case 'l':
305 if (cp + sizeof(u32_t) > rlim) return -1;
306 printf(" %ld", (long)(i32_t) ntohl(upack32(cp)));
307 cp += sizeof(u32_t);
308 break;
309 case 'd':
310 r= dn_expand(dns2oct(dp), dlim, cp, name, MAXDNAME);
311 if (r == -1) return -1;
312 printf(" %s", (char *) name);
313 cp += r;
314 break;
315 case 'c':
316 if (cp >= rlim) return -1;
317 printf(" %02X", *cp++);
318 break;
319 case 's':
320 r= *cp + 1;
321 if (cp + r > rlim) return -1;
322 printf(" \"%.*s\"", *cp, (char *) (cp + 1));
323 cp += r;
324 break;
325 case 'h':
326 if (cp + sizeof(u16_t) > rlim) return -1;
327 printf(" %u", ntohs(upack16(cp)));
328 cp += sizeof(u16_t);
329 break;
330 }
331 if (*ep == '*') ep= cp < rlim ? ep-1 : ep+1;
332 }
333 return cp - cp0;
334}
335
336static void dns_tell(int indent, dns_t *dp, size_t size)
337/* Explain a DNS packet, for debug purposes. */
338{
339 u8_t *cp;
340 int r, i;
341 unsigned count[4];
342 static char label[4][4]= { "QD:", "AN:", "NS:", "AR:" };
343 static char rcodes[][9] = {
344 "NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED"
345 };
346
347 if (size < sizeof(dns_hdr_t)) return;
348
349 printf("%*s", indent, "");
350 printf("DNS %s:", (dp->hdr.dh_flag1 & DHF_QR) ? "reply" : "query");
351 r= dp->hdr.dh_flag2 & DHF_RCODE;
352 printf(" %s", r < arraysize(rcodes) ? rcodes[r] : itoa("ERR_%lu", r));
353 if (dp->hdr.dh_flag1 & DHF_AA) printf(" AA");
354 if (dp->hdr.dh_flag1 & DHF_TC) printf(" TC");
355 if (dp->hdr.dh_flag1 & DHF_RD) printf(" RD");
356 if (dp->hdr.dh_flag2 & DHF_RA) printf(" RA");
357#ifdef DHF_AD
358 if (dp->hdr.dh_flag2 & DHF_AD) printf(" AD");
359 if (dp->hdr.dh_flag2 & DHF_CD) printf(" CD");
360#endif
361 fputc('\n', stdout);
362
363 count[0]= ntohs(dp->hdr.dh_qdcount);
364 count[1]= ntohs(dp->hdr.dh_ancount);
365 count[2]= ntohs(dp->hdr.dh_nscount);
366 count[3]= ntohs(dp->hdr.dh_arcount);
367 cp = dp->data;
368 for (i= 0; i < 4; i++) {
369 while (count[i] > 0) {
370 printf("%*s", indent, "");
371 printf(" %s ", label[i]);
372 r= print_qrr(dp, size, cp, (i == 0));
373 fputc('\n', stdout);
374 if (r == -1) return;
375 cp += r;
376 count[i]--;
377 }
378 }
379}
380
381static u32_t dns_ttl(dns_t *dp, size_t size, u32_t delta)
382/* Compute the minimum TTL of all RRs in a DNS packet and subtract delta from
383 * all TTLs. (We are actually only interested in the minimum (delta = 0) or
384 * the subtraction (delta > 0). It was easier to roll this into one routine.)
385 */
386{
387 u8_t *cp, *rdp, *dlim;
388 int r, i, hasttl, hassoa;
389 unsigned type, count[4];
390 u32_t ttl, minimum, minttl;
391 unsigned rcode;
392 u8_t name[MAXDNAME+1];
393
394 hasttl= hassoa= 0;
395 minttl= 365*24*3600L;
396 dlim= dns2oct(dp) + size;
397 if (size < sizeof(dns_hdr_t)) return 0;
398
399 rcode= dp->hdr.dh_flag2 & DHF_RCODE;
400 count[0]= ntohs(dp->hdr.dh_qdcount);
401 count[1]= ntohs(dp->hdr.dh_ancount);
402 count[2]= ntohs(dp->hdr.dh_nscount);
403 count[3]= ntohs(dp->hdr.dh_arcount);
404 cp = dp->data;
405 for (i= 0; i < 4 && cp < dlim; i++) {
406 while (count[i] > 0) {
407 r= dn_expand(dns2oct(dp), dlim, cp, name, MAXDNAME);
408 if (r == -1) break;
409 cp += r + 2 * sizeof(u16_t);
410 if (i != 0) {
411 if (cp + sizeof(u32_t) + sizeof(u16_t) > dlim) break;
412 type= upack16(cp - 2 * sizeof(u16_t));
413 ttl= ntohl(upack32(cp));
414 ttl= ttl < delta ? 0 : ttl - delta;
415 if (rcode == NXDOMAIN && i == 2 && type == HTONS(T_SOA)) {
416 rdp= cp + sizeof(u32_t) + sizeof(u16_t);
417 r= dn_expand(dns2oct(dp), dlim, rdp, name, MAXDNAME);
418 if (r == -1) break;
419 rdp += r;
420 r= dn_expand(dns2oct(dp), dlim, rdp, name, MAXDNAME);
421 if (r == -1) break;
422 rdp += r + 4 * sizeof(u32_t);
423 if (rdp + sizeof(u32_t) > dlim) break;
424 minimum= ntohl(upack32(rdp));
425 if (ttl > minimum) ttl= minimum;
426 hassoa= 1;
427 }
428 if (delta != 0) pack32(cp, htonl(ttl));
429 if (ttl < minttl) minttl= ttl;
430 hasttl= 1;
431 cp += sizeof(u32_t);
432 cp += sizeof(u16_t) + ntohs(upack16(cp));
433 }
434 count[i]--;
435 }
436 }
437 return ((rcode == NOERROR && hasttl) || (rcode == NXDOMAIN && hassoa))
438 ? minttl : 0;
439}
440
441/* Total cached query data. */
442static size_t n_datamax= N_DATAMAX;
443static size_t n_data;
444
445static query_t *extract_query(query_t *qp)
446/* Take a query out of the query cache. */
447{
448 assert(qp != nil);
449 *(qp->less != nil ? &qp->less->more : &lru) = qp->more;
450 *(qp->more != nil ? &qp->more->less : &mru) = qp->less;
451 n_data -= query_size(qp);
452 return qp;
453}
454
455static query_t *get_query(u8_t *name, unsigned type)
456/* Find a query and if so remove it from the cache and return it. */
457{
458 query_t *qp, *less;
459 u8_t qname[MAXDNAME+1];
460 int r;
461
462 for (qp= mru; qp != nil; qp= less) {
463 less= qp->less;
464 if (qp->stale <= now - stale) {
465 /* This answer has expired. */
466 deallocate(extract_query(qp));
467 } else {
468 r= dn_expand(dns2oct(&qp->dns), dns2oct(&qp->dns) + qp->size,
469 qp->dns.data, qname, MAXDNAME);
470 if (r == -1) continue;
471 if (namecmp(qname, name) == 0 && upack16(qp->dns.data+r) == type) {
472 /* Found an answer to the query. */
473 return extract_query(qp);
474 }
475 }
476 }
477 return nil;
478}
479
480static void insert_query(query_t *qp)
481/* (Re)insert a query into the cache. */
482{
483 *(qp->less != nil ? &qp->less->more : &lru) = qp;
484 *(qp->more != nil ? &qp->more->less : &mru) = qp;
485 n_data += query_size(qp);
486
487 /* Try to delete the LRU while there is too much memory in use. If
488 * its usage count is too high then it gets a second chance.
489 */
490 while (n_data > n_datamax && lru != nil) {
491 if ((lru->usage >>= QU_SHIFT) == 0 || lru->stale <= now - stale) {
492 deallocate(extract_query(lru));
493 } else {
494 lru->less= mru; /* Make list circular. */
495 mru->more= lru;
496 mru= lru; /* Move one over, making LRU the MRU. */
497 lru= lru->more;
498 lru->less= nil; /* Break the circle. */
499 mru->more= nil;
500 }
501 }
502
503 if (debug >= 2) {
504 unsigned n= 0;
505 for (qp= mru; qp != nil; qp= qp->less) n++;
506 printf("%u cached repl%s, %u bytes, sbrk(0) = %u\n",
507 n, n == 1 ? "y" : "ies",
508 (unsigned) n_data,
509 (unsigned) sbrk(0));
510 }
511}
512
513static void put_query(query_t *qp)
514/* Add a new query to the cache as the MRU. */
515{
516 qp->less= mru;
517 qp->more= nil;
518 insert_query(qp);
519}
520
521static void cache2file(void)
522/* Store the cached data into the cache file. */
523{
524 FILE *fp;
525 query_t *qp;
526 u8_t data[4+1+2+2];
527 u16_t usage;
528 char newcache[sizeof(NNCACHE) + sizeof(".new")];
529
530 if (single) return;
531
532 strcpy(newcache, NNCACHE);
533 strcat(newcache, ".new");
534
535 if ((fp= fopen(newcache, "w")) == nil) {
536 if ((errno != ENOENT && errno != EROFS) || debug >= 2) report(newcache);
537 return;
538 }
539 if (debug >= 2) printf("Writing %s:\n", newcache);
540
541 /* Magic number: */
542 fwrite(MAGIC, 1, sizeof(MAGIC), fp);
543
544 for (qp= lru; qp != nil; qp= qp->more) {
545 if (qp->stale <= now - stale) continue;
546 if (debug >= 2) {
547 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
548 qp->usage, (long) (now - qp->age), qp->flags);
549 dns_tell(2, &qp->dns, qp->size);
550 }
551 pack32(data+0, htonl(qp->age));
552 data[4]= qp->flags;
553 pack16(data+5, htons(qp->size));
554 pack16(data+7, htons(qp->usage));
555 fwrite(data, 1, sizeof(data), fp);
556 fwrite(&qp->dns, 1, qp->size, fp);
557 if (ferror(fp)) break;
558 }
559
560 if (ferror(fp) || fclose(fp) == EOF) {
561 report(newcache);
562 (void) unlink(newcache);
563 return;
564 }
565
566 if (debug >= 2) printf("mv %s %s\n", newcache, NNCACHE);
567 if (rename(newcache, NNCACHE) < 0) {
568 fprintf(stderr, "nonamed: mv %s %s: %s\n",
569 newcache, NNCACHE, strerror(errno));
570 (void) unlink(newcache);
571 }
572}
573
574static void file2cache(void)
575/* Read cached data from the cache file. */
576{
577 query_t *qp;
578 FILE *fp;
579 u8_t data[4+1+2+2];
580 size_t dlen;
581
582 if (single) return;
583
584 if ((fp= fopen(NNCACHE, "r")) == nil) {
585 if (errno != ENOENT || debug >= 2) report(NNCACHE);
586 return;
587 }
588 if (debug >= 2) printf("Reading %s:\n", NNCACHE);
589
590 /* Magic number? */
591 fread(data, 1, sizeof(MAGIC), fp);
592 if (ferror(fp) || memcmp(MAGIC, data, sizeof(MAGIC)) != 0) goto err;
593
594 for (;;) {
595 fread(data, 1, sizeof(data), fp);
596 if (feof(fp) || ferror(fp)) break;
597 dlen= ntohs(upack16(data+5));
598 qp= allocate(nil, query_allocsize(dlen));
599 qp->age= htonl(upack32(data+0));
600 qp->flags= data[4];
601 if (qp->flags & QF_REFRESH) q_refresh= 1;
602 qp->size= dlen;
603 qp->usage= htons(upack16(data+7));
604 fread(&qp->dns, 1, qp->size, fp);
605 if (feof(fp) || ferror(fp)) {
606 deallocate(qp);
607 goto err;
608 }
609 qp->stale= qp->age + dns_ttl(&qp->dns, dlen, 0);
610 if (debug >= 2) {
611 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
612 qp->usage, (long) (now - qp->age), qp->flags);
613 dns_tell(2, &qp->dns, dlen);
614 }
615 put_query(qp);
616 }
617 if (ferror(fp)) {
618 err:
619 /* The cache file did not end at EOF or is otherwise a mess. */
620 fprintf(stderr, "nonamed: %s: %s\n", NNCACHE,
621 ferror(fp) ? strerror(errno) : "Corrupt");
622 while (lru != nil) deallocate(extract_query(lru));
623 }
624 fclose(fp);
625}
626
627typedef int handler_t(void *data, int expired);
628
629/* All actions are in the form of "jobs". */
630typedef struct job {
631 struct job *next, **prev; /* To make a job queue. */
632 handler_t *handler; /* Function to handle this job. */
633 time_t timeout; /* Moment it times out. */
634 void *data; /* Data associated with the job. */
635} job_t;
636
637static job_t *queue; /* Main job queue. */
638
639static void newjob(handler_t *handler, time_t timeout, void *data)
640/* Create a new job with the given handler, timeout time and data. */
641{
642 job_t *job, **prev;
643
644 job= allocate(nil, sizeof(*job));
645 job->handler= handler;
646 job->timeout= timeout;
647 job->data= data;
648
649 for (prev= &queue; *prev != nil; prev= &(*prev)->next) {
650 if (job->timeout < (*prev)->timeout) break;
651 }
652 job->next= *prev;
653 job->prev= prev;
654 *prev= job;
655 if (job->next != nil) job->next->prev= &job->next;
656}
657
658static int execjob(job_t *job, int expired)
659/* Execute a job by calling the handler. Remove the job if it returns true,
660 * indicating that it is done. Expired is set if the job timed out. It is
661 * otherwise called to check for I/O.
662 */
663{
664 if ((*job->handler)(job->data, expired)) {
665 *job->prev= job->next;
666 if (job->next != nil) job->next->prev= job->prev;
667 deallocate(job);
668 return 1;
669 }
670 return 0;
671}
672
673static void force_expire(handler_t *handler)
674/* Force jobs to expire immediately, the named searcher for instance. */
675{
676 job_t *job, **prev= &queue;
677
678 while ((job= *prev) != nil) {
679 if (job->handler == handler && job->timeout != IMMEDIATE) {
680 *prev= job->next;
681 if (job->next != nil) job->next->prev= prev;
682 newjob(job->handler, IMMEDIATE, job->data);
683 deallocate(job);
684 } else {
685 prev= &job->next;
686 }
687 }
688}
689
690static int nxdomain(u8_t *name)
691/* True iff the two top level components in a name are repeated in the name,
692 * or if in-addr.arpa is found within a name. Such things happen often in a
693 * search for an already fully qualified local name. For instance:
694 * flotsam.cs.vu.nl.cs.vu.nl. (We don't want this at boot time.)
695 */
696{
697 u8_t *end, *top, *p;
698 size_t n;
699
700 end= namechr(name, 0);
701 top= end;
702 while (top > name && *--top != '.') {}
703 while (top > name && *--top != '.') {}
704 n= end - top;
705 p= top;
706 for (;;) {
707 if (p == name) return 0;
708 if (*--p == '.') {
709 if (namencmp(p, top, n) == 0 && p[n] == '.') return 1;
710 if (namencmp(p, ".in-addr.arpa.", 14) == 0) return 1;
711 }
712 }
713}
714
715typedef struct id2id {
716 u16_t id; /* ID of old query. */
717 u16_t port; /* Reply port. */
718 ipaddr_t ip; /* Reply address. */
719} id2id_t;
720
721static id2id_t id2id[N_IDS];
722static u16_t id_counter;
723
724static u16_t new_id(u16_t in_id, u16_t in_port, ipaddr_t in_ip)
725/* An incoming UDP query must be relabeled with a new ID before it can be
726 * send on to a real name daemon.
727 */
728{
729 id2id_t *idp;
730 u16_t id;
731
732 id= id_counter++;
733 idp= &id2id[id % N_IDS];
734 idp->id= in_id;
735 idp->port= in_port;
736 idp->ip= in_ip;
737 return htons(id);
738}
739
740static int old_id(u16_t id, u16_t *out_id, u16_t *out_port, ipaddr_t *out_ip)
741/* Translate a reply id back to the id, port, and address used in the query.
742 * Return true if the translation is possible.
743 */
744{
745 id= ntohs(id);
746 if ((u16_t) (id_counter - id) > N_IDS) {
747 /* Too old. */
748 return 0;
749 } else {
750 /* We know this one. */
751 id2id_t *idp= &id2id[id % N_IDS];
752
753 if (idp->port == 0) return 0; /* Named is trying to fool us? */
754 *out_id= idp->id;
755 *out_port= idp->port;
756 *out_ip= idp->ip;
757 idp->port= 0;
758 return 1;
759 }
760}
761
762/* IDs used to mark my own queries to name servers, must be new_id translated
763 * to make them unique "on the wire".
764 */
765#define ID_IPSELF HTONL(0) /* "I did it myself" address. */
766#define ID_PROBE HTONS(0) /* Name server probe. */
767#define ID_REFRESH HTONS(1) /* Query to refresh a cache entry. */
768
769static char *tcp_device, *udp_device; /* TCP and UDP device names. */
770static int udp_fd; /* To send or receive UDP packets. */
771static asynchio_t asyn; /* For I/O in progress. */
772static ipaddr_t my_ip; /* My IP address. */
773static u16_t my_port, named_port; /* Port numbers, normally "domain". */
774
775static ipaddr_t named[N_NAMEDS]; /* Addresses of all name servers. */
776static unsigned n_nameds; /* Number of configured name daemons. */
777static unsigned i_named; /* Index to current name server. */
778static int expect; /* Set when we expect an answer. */
779static int search_ct= -1; /* Named search count and state. */
780static int dirty; /* True when new entry put in cache. */
781
782#define current_named() (+named[i_named])
783#define searching() (search_ct > 0)
784#define start_searching() ((void) (search_ct= -1))
785#define stop_searching() ((void) (search_ct= 0))
786#define expecting() (+expect)
787#define start_expecting() ((void) (expect= 1))
788#define stop_expecting() ((void) (expect= 0))
789
790static time_t filetime(const char *file)
791/* Get the modified time of a file. */
792{
793 struct stat st;
794
795 return stat(file, &st) == 0 ? st.st_mtime : 0;
796}
797
798static void init_config(ipaddr_t ifip)
799/* Read name daemon list and other special stuff from the hosts file. */
800{
801 struct hostent *he;
802 u32_t nip, hip;
803 static time_t hosts_time, dhcp_time;
804 time_t ht, dt;
805
806 /* See if anything really changed. */
807 if (((ifip ^ HTONL(LOCALHOST)) & HTONL(0xFF000000)) == 0) ifip= my_ip;
808 ht= filetime(HOSTS);
809 dt= filetime(DHCPCACHE);
810 if (ifip == my_ip && ht == hosts_time && dt == dhcp_time) return;
811 my_ip= ifip;
812 hosts_time= ht;
813 dhcp_time= dt;
814
815 if (debug >= 2) {
816 printf("%s: I am nonamed %s at %s:%u\n",
817 nowgmt(), version, inet_ntoa(my_ip), ntohs(my_port));
818 }
819
820 httl= HTONL(HTTL);
821 stale= 0;
822 n_nameds= 0;
823
824 if (!single) {
825 sethostent(0);
826 while ((he= gethostent()) != nil) {
827 memcpy(&nip, he->h_addr, sizeof(u32_t));
828 hip= ntohl(nip);
829 if (namecmp(he->h_name, "%ttl") == 0) httl= nip;
830 if (namecmp(he->h_name, "%stale") == 0) stale= hip;
831 if (namecmp(he->h_name, "%memory") == 0) n_datamax= hip;
832 if (namecmp(he->h_name, "%nameserver") == 0) {
833 if (nip != my_ip || named_port != my_port) {
834 if (n_nameds < N_NAMEDS) named[n_nameds++]= nip;
835 }
836 }
837 }
838 endhostent();
839 }
840
841 if (n_nameds == 0) {
842 /* No name daemons found in the host file. What about DHCP? */
843 int fd;
844 dhcp_t d;
845 ssize_t r;
846 u8_t *data;
847 size_t len;
848
849 if ((fd= open(DHCPCACHE, O_RDONLY)) < 0) {
850 if (errno != ENOENT) fatal(DHCPCACHE);
851 } else {
852 while ((r= read(fd, &d, sizeof(d))) == sizeof(d)) {
853 if (d.yiaddr == my_ip) break;
854 }
855 if (r < 0) fatal(DHCPCACHE);
856 close(fd);
857
858 if (r == sizeof(d) && dhcp_gettag(&d, DHCP_TAG_DNS, &data, &len)) {
859 while (len >= sizeof(nip)) {
860 memcpy(&nip, data, sizeof(nip));
861 data += sizeof(nip);
862 len -= sizeof(nip);
863 if (nip != my_ip || named_port != my_port) {
864 if (n_nameds < N_NAMEDS) named[n_nameds++]= nip;
865 }
866 }
867 }
868 }
869 }
870 i_named= 0;
871}
872
873static handler_t job_save_cache, job_read_udp, job_find_named, job_expect_named;
874#if DO_TCP
875static handler_t job_setup_listen, job_listen, job_setup_connect, job_connect;
876static handler_t job_read_query, job_write_query;
877static handler_t job_read_reply, job_write_reply;
878#endif
879
880static int query_hosts(u8_t *qname, unsigned type, dns_t *dp, size_t *pdlen)
881/* Read the /etc/hosts file to try and answer an A or PTR query. Return
882 * true iff an answer can be found, with the answer copied to *dp.
883 */
884{
885 struct hostent *he;
886 int i, r;
887 dns_t dns;
888 u8_t *domain;
889 u8_t *cp;
890 u8_t name[MAXDNAME+1];
891 u8_t *dnvec[40];
892 unsigned ancount;
893 struct hostent localhost;
894 static char *noaliases[]= { nil };
895 static ipaddr_t localaddr= HTONL(LOCALHOST);
896 static char *localaddrlist[]= { (char *) &localaddr, nil };
897
898 if (single) return 0;
899
900 /* Assume we can answer. */
901 dns.hdr.dh_flag1= DHF_QR | DHF_AA;
902 dns.hdr.dh_flag2= DHF_RA;
903 dns.hdr.dh_qdcount= HTONS(1);
904 ancount= 0;
905 dns.hdr.dh_nscount= HTONS(0);
906 dns.hdr.dh_arcount= HTONS(0);
907
908 dnvec[0]= dns2oct(&dns);
909 dnvec[1]= nil;
910 cp= dns.data;
911 r= dn_comp(qname, cp, arraysize(dns.data), dnvec, arraylimit(dnvec));
912 if (r == -1) return 0;
913 cp += r;
914 pack16(cp, type);
915 cp += sizeof(u16_t);
916 pack16(cp, HTONS(C_IN));
917 cp += sizeof(u16_t);
918
919 /* Localhost is fixed to 127.0.0.1. */
920 localhost.h_name=
921 namencmp(qname, "localhost.", 10) == 0 ? (char *) qname : "localhost";
922 localhost.h_aliases= noaliases;
923 localhost.h_addr_list= localaddrlist;
924 he= &localhost;
925
926 sethostent(0);
927 do {
928 switch (type) {
929 case HTONS(T_A):
930 if (namecmp(qname, he->h_name) == 0) {
931 addA:
932 r= dn_comp((u8_t *) he->h_name, cp, arraylimit(dns.data) - cp,
933 dnvec, arraylimit(dnvec));
934 if (r == -1) return 0;
935 cp += r;
936 if (cp + 3 * sizeof(u16_t) + 2 * sizeof(u32_t)
937 > arraylimit(dns.data)) { r= -1; break; }
938 pack16(cp, HTONS(T_A));
939 cp += sizeof(u16_t);
940 pack16(cp, HTONS(C_IN));
941 cp += sizeof(u16_t);
942 pack32(cp, httl);
943 cp += sizeof(u32_t);
944 pack16(cp, HTONS(sizeof(u32_t)));
945 cp += sizeof(u16_t);
946 memcpy(cp, he->h_addr, sizeof(u32_t));
947 cp += sizeof(u32_t);
948 ancount++;
949 break;
950 }
951 /*FALL THROUGH*/
952 case HTONS(T_CNAME):
953 domain= namechr(he->h_name, '.');
954 for (i= 0; he->h_aliases[i] != nil; i++) {
955 namecpy(name, he->h_aliases[i]);
956 if (domain != nil && namechr(name, '.') == nil) {
957 namecat(name, domain);
958 }
959 if (namecmp(qname, name) == 0) {
960 r= dn_comp(name, cp, arraylimit(dns.data) - cp,
961 dnvec, arraylimit(dnvec));
962 if (r == -1) break;
963 cp += r;
964 if (cp + 3 * sizeof(u16_t)
965 + 1 * sizeof(u32_t) > arraylimit(dns.data)) return 0;
966 pack16(cp, HTONS(T_CNAME));
967 cp += sizeof(u16_t);
968 pack16(cp, HTONS(C_IN));
969 cp += sizeof(u16_t);
970 pack32(cp, httl);
971 cp += sizeof(u32_t);
972 /* pack16(cp, htonl(RDLENGTH)) */
973 cp += sizeof(u16_t);
974 r= dn_comp((u8_t *) he->h_name, cp,
975 arraylimit(dns.data) - cp,
976 dnvec, arraylimit(dnvec));
977 if (r == -1) break;
978 pack16(cp - sizeof(u16_t), htons(r));
979 cp += r;
980 ancount++;
981 if (type == HTONS(T_A)) goto addA; /* really wants A */
982 break;
983 }
984 }
985 break;
986 case HTONS(T_PTR):
987 if (ancount > 0) break;
988 if (he->h_name[0] == '%') break;
989 sprintf((char *) name, "%d.%d.%d.%d.in-addr.arpa",
990 ((u8_t *) he->h_addr)[3],
991 ((u8_t *) he->h_addr)[2],
992 ((u8_t *) he->h_addr)[1],
993 ((u8_t *) he->h_addr)[0]);
994 if (namecmp(qname, name) == 0) {
995 r= dn_comp(name, cp, arraylimit(dns.data) - cp,
996 dnvec, arraylimit(dnvec));
997 if (r == -1) break;
998 cp += r;
999 if (cp + 3 * sizeof(u16_t) + 1 * sizeof(u32_t)
1000 > arraylimit(dns.data)) { r= -1; break; }
1001 pack16(cp, HTONS(T_PTR));
1002 cp += sizeof(u16_t);
1003 pack16(cp, HTONS(C_IN));
1004 cp += sizeof(u16_t);
1005 pack32(cp, httl);
1006 cp += sizeof(u32_t);
1007 /* pack16(cp, htonl(RDLENGTH)) */
1008 cp += sizeof(u16_t);
1009 r= dn_comp((u8_t *) he->h_name, cp,
1010 arraylimit(dns.data) - cp, dnvec, arraylimit(dnvec));
1011 if (r == -1) return 0;
1012 pack16(cp - sizeof(u16_t), htons(r));
1013 cp += r;
1014 ancount++;
1015 }
1016 break;
1017 }
1018 } while (r != -1 && (he= gethostent()) != nil);
1019 endhostent();
1020
1021 if (r == -1 || ancount == 0) return 0;
1022
1023 dns.hdr.dh_ancount= htons(ancount);
1024 memcpy(dp, &dns, *pdlen= cp - dns2oct(&dns));
1025 return 1;
1026}
1027
1028static int query_chaos(u8_t *qname, unsigned type, dns_t *dp, size_t *pdlen)
1029/* Report my version. Can't let BIND take all the credit. :-) */
1030{
1031 int i, n, r;
1032 dns_t dns;
1033 u8_t *cp;
1034 u8_t *dnvec[40];
1035
1036 if (type != HTONS(T_TXT) || namecmp(qname, "version.bind") != 0) return 0;
1037
1038 dns.hdr.dh_flag1= DHF_QR | DHF_AA;
1039 dns.hdr.dh_flag2= DHF_RA;
1040 dns.hdr.dh_qdcount= HTONS(1);
1041 dns.hdr.dh_ancount= HTONS(1);
1042 dns.hdr.dh_nscount= HTONS(0);
1043 dns.hdr.dh_arcount= htons(n_nameds);
1044
1045 dnvec[0]= dns2oct(&dns);
1046 dnvec[1]= nil;
1047 cp= dns.data;
1048 r= dn_comp(qname, cp, arraysize(dns.data), dnvec, arraylimit(dnvec));
1049 if (r == -1) return 0;
1050 cp += r;
1051 pack16(cp, type);
1052 cp += sizeof(u16_t);
1053 pack16(cp, HTONS(C_CHAOS));
1054 cp += sizeof(u16_t);
1055
1056 r= dn_comp(qname, cp, arraylimit(dns.data) - cp, dnvec, arraylimit(dnvec));
1057 if (r == -1) return 0;
1058 cp += r;
1059 pack16(cp, HTONS(T_TXT));
1060 cp += sizeof(u16_t);
1061 pack16(cp, HTONS(C_CHAOS));
1062 cp += sizeof(u16_t);
1063 pack32(cp, HTONL(0));
1064 cp += sizeof(u32_t);
1065 /* pack16(cp, htonl(RDLENGTH)) */
1066 cp += sizeof(u16_t);
1067 sprintf((char *) cp + 1, "nonamed %s at %s:%u",
1068 version, inet_ntoa(my_ip), ntohs(my_port));
1069 r= strlen((char *) cp + 1) + 1;
1070 pack16(cp - sizeof(u16_t), htons(r));
1071 *cp= r-1;
1072 cp += r;
1073 for (n= 0, i= i_named; n < n_nameds; n++, i= (i+1) % n_nameds) {
1074 r= dn_comp((u8_t *) "%nameserver", cp, arraylimit(dns.data) - cp,
1075 dnvec, arraylimit(dnvec));
1076 if (r == -1) return 0;
1077 cp += r;
1078 if (cp + 3 * sizeof(u16_t)
1079 + 2 * sizeof(u32_t) > arraylimit(dns.data)) return 0;
1080 pack16(cp, HTONS(T_A));
1081 cp += sizeof(u16_t);
1082 pack16(cp, HTONS(C_IN));
1083 cp += sizeof(u16_t);
1084 pack32(cp, HTONL(0));
1085 cp += sizeof(u32_t);
1086 pack16(cp, HTONS(sizeof(u32_t)));
1087 cp += sizeof(u16_t);
1088 memcpy(cp, &named[i], sizeof(u32_t));
1089 cp += sizeof(u32_t);
1090 }
1091
1092 memcpy(dp, &dns, *pdlen= cp - dns2oct(&dns));
1093 return 1;
1094}
1095
1096static void cache_reply(dns_t *dp, size_t dlen)
1097/* Store a DNS packet in the cache. */
1098{
1099 int r;
1100 query_t *qp, *less, *more;
1101 unsigned usage;
1102 u16_t type;
1103 u8_t *cp;
1104 u8_t name[MAXDNAME];
1105 u32_t minttl;
1106
1107 if ((dp->hdr.dh_flag1 & (DHF_RD | DHF_TC)) != DHF_RD) return;
1108 if (dp->hdr.dh_qdcount != HTONS(1)) return;
1109 cp= dp->data;
1110 r= dn_expand(dns2oct(dp), dns2oct(dp) + dlen, cp, name, MAXDNAME);
1111 if (r == -1) return;
1112 cp += r;
1113 type= upack16(cp);
1114 cp += sizeof(u16_t);
1115 if (upack16(cp) != HTONS(C_IN)) return;
1116
1117 /* Delete old cached data, if any. Note where it is in the LRU. */
1118 if ((qp= get_query(name, type)) != nil) {
1119 less= qp->less;
1120 more= qp->more;
1121 usage= qp->usage;
1122 deallocate(qp);
1123 } else {
1124 /* Not yet in the cache. */
1125 less= mru;
1126 more= nil;
1127 usage= 1;
1128 }
1129
1130 /* Determine minimum TTL. Discard if zero, never cache zero TTLs. */
1131 if ((minttl= dns_ttl(dp, dlen, 0)) == 0) return;
1132
1133 /* Enter new reply in cache. */
1134 qp= allocate(nil, query_allocsize(dlen));
1135 qp->less= less;
1136 qp->more= more;
1137 qp->age= now;
1138 qp->flags= 0;
1139 qp->usage= usage;
1140 qp->size= dlen;
1141 memcpy(&qp->dns, dp, dlen);
1142 qp->stale= qp->age + minttl;
1143 insert_query(qp);
1144 if (debug >= 1) printf("Answer cached\n");
1145
1146 /* Save the cache soon. */
1147 if (!dirty) {
1148 dirty= 1;
1149 newjob(job_save_cache, now + LONG_TIMEOUT, nil);
1150 }
1151}
1152
1153static int job_save_cache(void *data, int expired)
1154/* Some time after the cache is changed it is written back to disk. */
1155{
1156 if (!expired) return 0;
1157 cache2file();
1158 dirty= 0;
1159}
1160
1161static int compose_reply(dns_t *dp, size_t *pdlen)
1162/* Try to compose a reply to a request in *dp using the hosts file or
1163 * cached data. Return answer in *dp with its size in *pdlen. Return true
1164 * iff an answer is given.
1165 */
1166{
1167 size_t dlen= *pdlen;
1168 int r, rd;
1169 query_t *qp;
1170 unsigned id, type, class;
1171 u8_t *cp;
1172 u8_t name[MAXDNAME];
1173
1174 cp= dp->data;
1175 r= dn_expand(dns2oct(dp), dns2oct(dp) + dlen, cp, name, MAXDNAME);
1176 if (r != -1) {
1177 cp += r;
1178 if (cp + 2 * sizeof(u16_t) > dns2oct(dp) + dlen) {
1179 r= -1;
1180 } else {
1181 type= upack16(cp);
1182 cp += sizeof(u16_t);
1183 class= upack16(cp);
1184 cp += sizeof(u16_t);
1185 }
1186 }
1187
1188 /* Remember ID and RD. */
1189 id= dp->hdr.dh_id;
1190 rd= dp->hdr.dh_flag1 & DHF_RD;
1191
1192 if (r == -1) {
1193 /* Malformed query, reply "FORMERR". */
1194 dp->hdr.dh_flag1 &= ~(DHF_TC);
1195 dp->hdr.dh_flag1 |= DHF_QR | DHF_AA;
1196 dp->hdr.dh_flag2 &= ~(DHF_UNUSED | DHF_RCODE);
1197 dp->hdr.dh_flag2 |= DHF_RA | FORMERR;
1198 } else
1199 if (class == HTONS(C_IN) && query_hosts(name, type, dp, pdlen)) {
1200 /* Answer to this query is in the hosts file. */
1201 dlen= *pdlen;
1202 } else
1203 if (class == HTONS(C_IN) && (qp= get_query(name, type)) != nil) {
1204 /* Answer to this query is present in the cache. */
1205 memcpy(dp, &qp->dns, dlen= qp->size);
1206 dp->hdr.dh_flag1 &= ~DHF_AA;
1207 (void) dns_ttl(dp, dlen, now - qp->age);
1208 if (rd) {
1209 if (qp->stale <= now) {
1210 qp->flags |= QF_REFRESH;
1211 q_refresh= 1;
1212 }
1213 qp->usage++;
1214 }
1215 put_query(qp);
1216 } else
1217 if (class == HTONS(C_CHAOS) && query_chaos(name, type, dp, pdlen)) {
1218 /* Return our version numbers. */
1219 dlen= *pdlen;
1220 } else
1221 if (n_nameds == 0 || nxdomain(name)) {
1222 /* No real name daemon present, or this name has a repeated top level
1223 * domain sequence. Reply "no such domain".
1224 */
1225 dp->hdr.dh_flag1 &= ~(DHF_TC);
1226 dp->hdr.dh_flag1 |= DHF_QR | DHF_AA;
1227 dp->hdr.dh_flag2 &= ~(DHF_UNUSED | DHF_RCODE);
1228 dp->hdr.dh_flag2 |= DHF_RA | NXDOMAIN;
1229 } else
1230 if (!rd) {
1231 /* "Recursion Desired" is off, so don't bother to relay. */
1232 dp->hdr.dh_flag1 &= ~(DHF_TC);
1233 dp->hdr.dh_flag1 |= DHF_QR;
1234 dp->hdr.dh_flag2 &= ~(DHF_UNUSED | DHF_RCODE);
1235 dp->hdr.dh_flag2 |= DHF_RA | NOERROR;
1236 } else {
1237 /* Caller needs to consult with a real name daemon. */
1238 return 0;
1239 }
1240
1241 /* Copy ID and RD back to answer. */
1242 dp->hdr.dh_id= id;
1243 dp->hdr.dh_flag1 &= ~DHF_RD;
1244 dp->hdr.dh_flag1 |= rd;
1245 *pdlen= dlen;
1246 return 1;
1247}
1248
1249typedef struct udp_dns { /* One DNS packet over UDP. */
1250 udp_io_hdr_t hdr; /* UDP header (source/destination). */
1251 dns_t dns; /* DNS packet. */
1252} udp_dns_t;
1253
1254static void refresh_cache(void)
1255/* Find a stale entry in the cache that was used to answer a query, and send
1256 * a request to a name server that should refresh this entry.
1257 */
1258{
1259 query_t *qp;
1260 unsigned type;
1261 int r;
1262 u8_t *cp;
1263 size_t dlen, ulen;
1264 u8_t qname[MAXDNAME+1];
1265 u8_t *dnvec[40];
1266 udp_dns_t udp;
1267
1268 if (!q_refresh) return;
1269 for (qp= lru; qp != nil; qp= qp->more) {
1270 if ((qp->flags & QF_REFRESH) && qp->stale > now - stale) break;
1271 }
1272 if (qp == nil) {
1273 q_refresh= 0;
1274 return;
1275 }
1276
1277 /* Found one to refresh. */
1278 qp->flags &= ~QF_REFRESH;
1279 r= dn_expand(dns2oct(&qp->dns), dns2oct(&qp->dns) + qp->size,
1280 qp->dns.data, qname, MAXDNAME);
1281 if (r == -1) return;
1282 type= upack16(qp->dns.data+r);
1283
1284 dnvec[0]= dns2oct(&udp.dns);
1285 dnvec[1]= nil;
1286 cp= udp.dns.data;
1287 r= dn_comp(qname, cp, arraysize(udp.dns.data), dnvec, arraylimit(dnvec));
1288 if (r == -1) return;
1289 cp += r;
1290 pack16(cp, type);
1291 cp += sizeof(u16_t);
1292 pack16(cp, HTONS(C_IN));
1293 cp += sizeof(u16_t);
1294 dlen= cp - dns2oct(&udp.dns);
1295
1296 udp.dns.hdr.dh_id= new_id(ID_REFRESH, my_port, ID_IPSELF);
1297 udp.dns.hdr.dh_flag1= DHF_RD;
1298 udp.dns.hdr.dh_flag2= 0;
1299 udp.dns.hdr.dh_qdcount= HTONS(1);
1300 udp.dns.hdr.dh_ancount= HTONS(0);
1301 udp.dns.hdr.dh_nscount= HTONS(0);
1302 udp.dns.hdr.dh_arcount= HTONS(0);
1303
1304 udp.hdr.uih_dst_addr= current_named();
1305 udp.hdr.uih_dst_port= named_port;
1306 udp.hdr.uih_ip_opt_len= 0;
1307 udp.hdr.uih_data_len= dlen;
1308
1309 if (debug >= 1) {
1310 printf("Refresh to %s:%u:\n",
1311 inet_ntoa(current_named()), ntohs(named_port));
1312 dns_tell(0, &udp.dns, dlen);
1313 }
1314 ulen= offsetof(udp_dns_t, dns) + dlen;
1315 if (write(udp_fd, &udp, ulen) < 0) fatal(udp_device);
1316}
1317
1318static int job_read_udp(void *data, int expired)
1319/* Read UDP queries and replies. */
1320{
1321 size_t ulen, dlen;
1322 static udp_dns_t udp;
1323 u16_t id, port;
1324 ipaddr_t ip;
1325 time_t dtime;
1326
1327 assert(!expired);
1328
1329 /* Try to read a packet. */
1330 ulen= asyn_read(&asyn, udp_fd, &udp, sizeof(udp));
1331 dlen= ulen - offsetof(udp_dns_t, dns);
1332
1333 if (ulen == -1) {
1334 if (errno == EINPROGRESS && !expired) return 0;
1335 if (errno == EIO) fatal(udp_device);
1336
1337 if (debug >= 2) {
1338 printf("%s: UDP read: %s\n", nowgmt(), strerror(errno));
1339 }
1340 } else {
1341 if (debug >= 2) {
1342 printf("%s: UDP read, %d bytes\n", nowgmt(), (int) ulen);
1343 }
1344 }
1345
1346 /* Restart this job no matter what. */
1347 newjob(job_read_udp, NEVER, nil);
1348
1349 if (ulen < (ssize_t) (sizeof(udp_io_hdr_t) + sizeof(dns_hdr_t))) return 1;
1350
1351 if (debug >= 1) {
1352 printf("%s:%u UDP ", inet_ntoa(udp.hdr.uih_src_addr),
1353 ntohs(udp.hdr.uih_src_port));
1354 dns_tell(0, &udp.dns, dlen);
1355 }
1356
1357 /* Check, and if necessary reinitialize my configuration. */
1358 init_config(udp.hdr.uih_dst_addr);
1359
1360 if (udp.dns.hdr.dh_flag1 & DHF_QR) {
1361 /* This is a remote named reply, not a query. */
1362
1363 /* Response to a query previously relayed? */
1364 if (!old_id(udp.dns.hdr.dh_id, &id, &port, &ip)) return 1;
1365
1366 if (ip == ID_IPSELF && id == ID_PROBE) {
1367 if (searching()) {
1368 /* We have found a name server! */
1369 int i;
1370
1371 /* In my list? */
1372 for (i= 0; i < n_nameds; i++) {
1373 if (named[i] == udp.hdr.uih_src_addr) {
1374 i_named= i;
1375 if (debug >= 1) {
1376 printf("Current named = %s\n",
1377 inet_ntoa(current_named()));
1378 }
1379 stop_searching();
1380 force_expire(job_find_named);
1381 }
1382 }
1383 }
1384 }
1385
1386 /* We got an answer, so stop worrying. */
1387 if (expecting()) {
1388 stop_expecting();
1389 force_expire(job_expect_named);
1390 }
1391
1392 /* Put the information in the cache. */
1393 cache_reply(&udp.dns, dlen);
1394
1395 /* Refresh a cached entry that was used when stale. */
1396 refresh_cache();
1397
1398 /* Discard reply to myself. */
1399 if (ip == ID_IPSELF) return 1;
1400
1401 /* Send the reply to the process that asked for it. */
1402 udp.dns.hdr.dh_id= id;
1403 udp.hdr.uih_dst_addr= ip;
1404 udp.hdr.uih_dst_port= port;
1405 if (debug >= 1) printf("To client %s:%u\n", inet_ntoa(ip), ntohs(port));
1406 } else {
1407 /* A query. */
1408 if (udp.dns.hdr.dh_qdcount != HTONS(1)) return 1;
1409
1410 if(localonly) {
1411 /* Check if it's a local query. */
1412 if(ntohl(udp.hdr.uih_src_addr) != LOCALHOST) {
1413 syslog(LOG_WARNING, "nonamed: dropped query from %s",
1414 inet_ntoa(udp.hdr.uih_src_addr));
1415 return 1;
1416 }
1417 }
1418
1419 /* Try to compose a reply from local data. */
1420 if (compose_reply(&udp.dns, &dlen)) {
1421 udp.hdr.uih_dst_addr= udp.hdr.uih_src_addr;
1422 udp.hdr.uih_dst_port= udp.hdr.uih_src_port;
1423 udp.hdr.uih_ip_opt_len= 0;
1424 udp.hdr.uih_data_len= dlen;
1425 ulen= offsetof(udp_dns_t, dns) + dlen;
1426
1427 /* Send an UDP DNS reply. */
1428 if (debug >= 1) {
1429 printf("%s:%u UDP ", inet_ntoa(udp.hdr.uih_dst_addr),
1430 ntohs(udp.hdr.uih_dst_port));
1431 dns_tell(0, &udp.dns, dlen);
1432 }
1433 } else {
1434 /* Let a real name daemon handle the query. */
1435 udp.dns.hdr.dh_id= new_id(udp.dns.hdr.dh_id,
1436 udp.hdr.uih_src_port, udp.hdr.uih_src_addr);
1437 udp.hdr.uih_dst_addr= current_named();
1438 udp.hdr.uih_dst_port= named_port;
1439 if (!expecting()) {
1440 start_expecting();
1441 newjob(job_expect_named, now + MEDIUM_TIMEOUT, nil);
1442 }
1443 if (debug >= 1) {
1444 printf("To named %s:%u\n",
1445 inet_ntoa(current_named()), ntohs(named_port));
1446 }
1447 }
1448 }
1449 if (write(udp_fd, &udp, ulen) < 0) fatal(udp_device);
1450 return 1;
1451}
1452
1453#if DO_TCP
1454
1455typedef struct data_cl { /* Data for connect or listen jobs. */
1456 int fd; /* Open TCP channel. */
1457 int dn_fd; /* TCP channel to the name daemon. */
1458 int retry; /* Retrying a connect? */
1459 nwio_tcpcl_t tcpcl; /* Flags. */
1460} data_cl_t;
1461
1462typedef struct data_rw { /* Data for TCP read or write jobs. */
1463 int r_fd; /* Read from this TCP channel. */
1464 int w_fd; /* And write to this TCP channel. */
1465 struct data_rw *rev; /* Optional reverse TCP channel. */
1466 u8_t *buf; /* Buffer for bytes to transfer. */
1467 ssize_t offset; /* Offset in buf to r/w at. */
1468 size_t size; /* Size of buf. */
1469} data_rw_t;
1470
1471static int job_setup_listen(void *data, int expired)
1472/* Set up a listening channel for TCP DNS queries. */
1473{
1474 data_cl_t *data_cl= data;
1475 nwio_tcpconf_t tcpconf;
1476 nwio_tcpopt_t tcpopt;
1477 int fd;
1478
1479 if (!expired) return 0;
1480 if (debug >= 2) printf("%s: Setup listen\n", nowgmt());
1481
1482 if (data_cl == nil) {
1483 if ((fd= open(tcp_device, O_RDWR)) < 0) {
1484 if (errno != EMFILE) report(tcp_device);
1485 newjob(job_setup_listen, now + SHORT_TIMEOUT, nil);
1486 return 1;
1487 }
1488
1489 tcpconf.nwtc_flags= NWTC_SHARED | NWTC_LP_SET | NWTC_UNSET_RA
1490 | NWTC_UNSET_RP;
1491 tcpconf.nwtc_locport= my_port;
1492 if (ioctl(fd, NWIOSTCPCONF, &tcpconf) == -1) fatal(tcp_device);
1493
1494 tcpopt.nwto_flags= NWTO_DEL_RST;
1495 if (ioctl(fd, NWIOSTCPOPT, &tcpopt) == -1) fatal(tcp_device);
1496
1497 data_cl= allocate(nil, sizeof(*data_cl));
1498 data_cl->fd= fd;
1499 data_cl->tcpcl.nwtcl_flags= 0;
1500 }
1501 /* And listen. */
1502 newjob(job_listen, NEVER, data_cl);
1503 return 1;
1504}
1505
1506static int job_listen(void *data, int expired)
1507/* A connection on the TCP DNS query channel. */
1508{
1509 data_cl_t *data_cl= data;
1510
1511 /* Wait for a client. */
1512 if (asyn_ioctl(&asyn, data_cl->fd, NWIOTCPLISTEN, &data_cl->tcpcl) < 0) {
1513 if (errno == EINPROGRESS) return 0;
1514 report(tcp_device);
1515
1516 /* Try again after a short time. */
1517 newjob(job_setup_listen, now + SHORT_TIMEOUT, data_cl);
1518 return 1;
1519 }
1520 if (debug >= 2) printf("%s: Listen\n", nowgmt());
1521
1522 /* Immediately resume listening. */
1523 newjob(job_setup_listen, IMMEDIATE, nil);
1524
1525 /* Set up a connect to the real name daemon. */
1526 data_cl->retry= 0;
1527 newjob(job_setup_connect, IMMEDIATE, data_cl);
1528 return 1;
1529}
1530
1531static void start_relay(int fd, int dn_fd)
1532/* Start one or two read jobs after job_setup_connect() or job_connect(). */
1533{
1534 data_rw_t *query; /* Client to DNS daemon relay. */
1535 data_rw_t *reply; /* DNS daemon to client relay. */
1536
1537 query= allocate(nil, sizeof(*query));
1538 query->r_fd= fd;
1539 query->buf= allocate(nil, sizeof(u16_t));
1540 query->offset= 0;
1541 query->size= sizeof(u16_t);
1542 if (dn_fd == NO_FD) {
1543 /* Answer mode. */
1544 query->w_fd= fd;
1545 query->rev= nil;
1546 } else {
1547 /* Relay mode. */
1548 reply= allocate(nil, sizeof(*reply));
1549 reply->r_fd= dn_fd;
1550 reply->w_fd= fd;
1551 reply->buf= allocate(nil, sizeof(u16_t));
1552 reply->offset= 0;
1553 reply->size= sizeof(u16_t);
1554 reply->rev= query;
1555 query->w_fd= dn_fd;
1556 query->rev= reply;
1557 newjob(job_read_reply, now + LONG_TIMEOUT, reply);
1558 }
1559 newjob(job_read_query, now + LONG_TIMEOUT, query);
1560}
1561
1562static void close_relay(data_rw_t *data_rw)
1563/* Close a relay channel. */
1564{
1565 if (data_rw->rev != nil) {
1566 /* Other end still active, signal EOF. */
1567 (void) ioctl(data_rw->w_fd, NWIOTCPSHUTDOWN, nil);
1568 data_rw->rev->rev= nil;
1569 } else {
1570 /* Close both ends down. */
1571 asyn_close(&asyn, data_rw->r_fd);
1572 close(data_rw->r_fd);
1573 if (data_rw->w_fd != data_rw->r_fd) {
1574 asyn_close(&asyn, data_rw->w_fd);
1575 close(data_rw->w_fd);
1576 }
1577 }
1578 deallocate(data_rw->buf);
1579 deallocate(data_rw);
1580}
1581
1582static int job_setup_connect(void *data, int expired)
1583/* Set up a connect for a TCP channel to the real name daemon. */
1584{
1585 nwio_tcpconf_t tcpconf;
1586 int dn_fd;
1587 data_cl_t *data_cl= data;
1588
1589 if (!expired) return 0;
1590 if (debug >= 2) printf("%s: Setup connect\n", nowgmt());
1591
1592 if (n_nameds == 0) {
1593 /* No name daemons to relay to, answer myself. */
1594 start_relay(data_cl->fd, NO_FD);
1595 deallocate(data_cl);
1596 return 1;
1597 }
1598
1599 if ((dn_fd= open(tcp_device, O_RDWR)) < 0) {
1600 if (errno != EMFILE) report(tcp_device);
1601 if (++data_cl->retry < 5) {
1602 /* Retry. */
1603 newjob(job_setup_connect, now + SHORT_TIMEOUT, data_cl);
1604 } else {
1605 /* Reply myself (bound to fail). */
1606 start_relay(data_cl->fd, NO_FD);
1607 deallocate(data_cl);
1608 }
1609 return 1;
1610 }
1611
1612 tcpconf.nwtc_flags= NWTC_LP_SEL | NWTC_SET_RA | NWTC_SET_RP;
1613 tcpconf.nwtc_remaddr= current_named();
1614 tcpconf.nwtc_remport= named_port;
1615 if (ioctl(dn_fd, NWIOSTCPCONF, &tcpconf) == -1) fatal(tcp_device);
1616
1617 /* And connect. */
1618 data_cl->dn_fd= dn_fd;
1619 data_cl->tcpcl.nwtcl_flags= 0;
1620 newjob(job_connect, NEVER, data_cl);
1621 return 1;
1622}
1623
1624static int job_connect(void *data, int expired)
1625/* Connect to a TCP DNS query channel. */
1626{
1627 data_cl_t *data_cl= data;
1628
1629 /* Try to connect. */
1630 if (asyn_ioctl(&asyn, data_cl->dn_fd, NWIOTCPCONN, &data_cl->tcpcl) < 0) {
1631 if (errno == EINPROGRESS) return 0;
1632 if (errno == EIO) fatal(tcp_device);
1633
1634 /* Connection refused. */
1635 if (debug >= 2) printf("%s: Connect: %s\n", nowgmt(), strerror(errno));
1636 asyn_close(&asyn, data_cl->dn_fd);
1637 close(data_cl->dn_fd);
1638 data_cl->dn_fd= NO_FD;
1639 if (++data_cl->retry < 5) {
1640 /* Search a new name daemon. */
1641 if (!searching()) {
1642 start_searching();
1643 force_expire(job_find_named);
1644 }
1645 newjob(job_setup_connect, NEVER, data_cl);
1646 return 1;
1647 }
1648 /* Reply with a failure eventually. */
1649 }
1650 if (debug >= 2) printf("%s: Connect\n", nowgmt());
1651
1652 /* Read the query from the user, send on to the name daemon, etc. */
1653 start_relay(data_cl->fd, data_cl->dn_fd);
1654 deallocate(data_cl);
1655 return 1;
1656}
1657
1658static void tcp_dns_tell(int fd, u8_t *buf)
1659/* Tell about a DNS packet on a TCP channel. */
1660{
1661 nwio_tcpconf_t tcpconf;
1662
1663 if (ioctl(fd, NWIOGTCPCONF, &tcpconf) < 0) {
1664 printf("??\?:?? TCP ");
1665 } else {
1666 printf("%s:%u TCP ", inet_ntoa(tcpconf.nwtc_remaddr),
1667 ntohs(tcpconf.nwtc_remport));
1668 }
1669 dns_tell(0, oct2dns(buf + sizeof(u16_t)), ntohs(upack16(buf)));
1670}
1671
1672static int job_read_query(void *data, int expired)
1673/* Read TCP queries from the client. */
1674{
1675 data_rw_t *data_rw= data;
1676 ssize_t count;
1677
1678 /* Try to read count bytes. */
1679 count= asyn_read(&asyn, data_rw->r_fd,
1680 data_rw->buf + data_rw->offset,
1681 data_rw->size - data_rw->offset);
1682
1683 if (count < 0) {
1684 if (errno == EINPROGRESS && !expired) return 0;
1685 if (errno == EIO) fatal(tcp_device);
1686
1687 /* Remote end is late, or an error occurred. */
1688 if (debug >= 2) {
1689 printf("%s: TCP read query: %s\n", nowgmt(), strerror(errno));
1690 }
1691 close_relay(data_rw);
1692 return 1;
1693 }
1694
1695 if (debug >= 2) {
1696 printf("%s: TCP read query, %d/%u bytes\n",
1697 nowgmt(), data_rw->offset + count, data_rw->size);
1698 }
1699 if (count == 0) {
1700 /* EOF. */
1701 close_relay(data_rw);
1702 return 1;
1703 }
1704 data_rw->offset += count;
1705 if (data_rw->offset == data_rw->size) {
1706 data_rw->size= sizeof(u16_t) + ntohs(upack16(data_rw->buf));
1707 if (data_rw->size < sizeof(u16_t)) {
1708 /* Malformed. */
1709 close_relay(data_rw);
1710 return 1;
1711 }
1712 if (data_rw->offset < data_rw->size) {
1713 /* Query not complete, read more. */
1714 data_rw->buf= allocate(data_rw->buf, data_rw->size);
1715 newjob(job_read_query, now + LONG_TIMEOUT, data_rw);
1716 return 1;
1717 }
1718 }
1719
1720 if (data_rw->size < sizeof(u16_t) + sizeof(dns_hdr_t)) {
1721 close_relay(data_rw);
1722 return 1;
1723 }
1724 if (debug >= 1) tcp_dns_tell(data_rw->r_fd, data_rw->buf);
1725
1726 /* Relay or reply. */
1727 if (data_rw->w_fd != data_rw->r_fd) {
1728 /* We have a real name daemon to do the work. */
1729 data_rw->offset= 0;
1730 newjob(job_write_query, now + LONG_TIMEOUT, data_rw);
1731 } else {
1732 /* No real name daemons or none reachable, so use the hosts file. */
1733 dns_t *dp;
1734 size_t dlen;
1735
1736 if (data_rw->size < sizeof(u16_t) + PACKETSZ) {
1737 data_rw->buf= allocate(data_rw->buf, sizeof(u16_t) + PACKETSZ);
1738 }
1739
1740 /* Build a reply packet. */
1741 dp= oct2dns(data_rw->buf + sizeof(u16_t));
1742 dlen= data_rw->size - sizeof(u16_t);
1743 if (!compose_reply(dp, &dlen)) {
1744 /* We're told to ask a name daemon, but that won't work. */
1745 close_relay(data_rw);
1746 return 1;
1747 }
1748
1749 /* Start a reply write. */
1750 pack16(data_rw->buf, htons(dlen));
1751 data_rw->size= sizeof(u16_t) + dlen;
1752 data_rw->buf= allocate(data_rw->buf, data_rw->size);
1753 data_rw->offset= 0;
1754 newjob(job_write_reply, now + LONG_TIMEOUT, data_rw);
1755 }
1756 return 1;
1757}
1758
1759static int job_write_query(void *data, int expired)
1760/* Relay a TCP query to the name daemon. */
1761{
1762 data_rw_t *data_rw= data;
1763 ssize_t count;
1764
1765 /* Try to write count bytes to the name daemon. */
1766 count= asyn_write(&asyn, data_rw->w_fd,
1767 data_rw->buf + data_rw->offset,
1768 data_rw->size - data_rw->offset);
1769
1770 if (count <= 0) {
1771 if (errno == EINPROGRESS && !expired) return 0;
1772 if (errno == EIO) fatal(tcp_device);
1773
1774 /* A write expired or failed (usually a broken connection.) */
1775 if (debug >= 2) {
1776 printf("%s: TCP write query: %s\n", nowgmt(), strerror(errno));
1777 }
1778 close_relay(data_rw);
1779 return 1;
1780 }
1781
1782 if (debug >= 2) {
1783 printf("%s: TCP write query, %d/%u bytes\n",
1784 nowgmt(), data_rw->offset + count, data_rw->size);
1785 }
1786 data_rw->offset += count;
1787 if (data_rw->offset < data_rw->size) {
1788 /* Partial write, continue. */
1789 newjob(job_write_query, now + LONG_TIMEOUT, data_rw);
1790 return 1;
1791 }
1792 if (debug >= 1) tcp_dns_tell(data_rw->w_fd, data_rw->buf);
1793
1794 /* Query fully send on, go read more queries. */
1795 data_rw->offset= 0;
1796 data_rw->size= sizeof(u16_t);
1797 newjob(job_read_query, now + LONG_TIMEOUT, data_rw);
1798 return 1;
1799}
1800
1801static int job_read_reply(void *data, int expired)
1802/* Read a TCP reply from the real name daemon. */
1803{
1804 data_rw_t *data_rw= data;
1805 ssize_t count;
1806
1807 /* Try to read count bytes. */
1808 count= asyn_read(&asyn, data_rw->r_fd,
1809 data_rw->buf + data_rw->offset,
1810 data_rw->size - data_rw->offset);
1811
1812 if (count < 0) {
1813 if (errno == EINPROGRESS && !expired) return 0;
1814 if (errno == EIO) fatal(tcp_device);
1815
1816 /* Remote end is late, or an error occurred. */
1817 if (debug >= 2) {
1818 printf("%s: TCP read reply: %s\n", nowgmt(), strerror(errno));
1819 }
1820 close_relay(data_rw);
1821 return 1;
1822 }
1823
1824 if (debug >= 2) {
1825 printf("%s: TCP read reply, %d/%u bytes\n",
1826 nowgmt(), data_rw->offset + count, data_rw->size);
1827 }
1828 if (count == 0) {
1829 /* EOF. */
1830 close_relay(data_rw);
1831 return 1;
1832 }
1833 data_rw->offset += count;
1834 if (data_rw->offset == data_rw->size) {
1835 data_rw->size= sizeof(u16_t) + ntohs(upack16(data_rw->buf));
1836 if (data_rw->size < sizeof(u16_t)) {
1837 /* Malformed. */
1838 close_relay(data_rw);
1839 return 1;
1840 }
1841 if (data_rw->offset < data_rw->size) {
1842 /* Reply not complete, read more. */
1843 data_rw->buf= allocate(data_rw->buf, data_rw->size);
1844 newjob(job_read_reply, now + LONG_TIMEOUT, data_rw);
1845 return 1;
1846 }
1847 }
1848 if (debug >= 1) tcp_dns_tell(data_rw->r_fd, data_rw->buf);
1849
1850 /* Reply fully read, send it on. */
1851 data_rw->offset= 0;
1852 newjob(job_write_reply, now + LONG_TIMEOUT, data_rw);
1853 return 1;
1854}
1855
1856static int job_write_reply(void *data, int expired)
1857/* Send a TCP reply to the client. */
1858{
1859 data_rw_t *data_rw= data;
1860 ssize_t count;
1861
1862 /* Try to write count bytes to the client. */
1863 count= asyn_write(&asyn, data_rw->w_fd,
1864 data_rw->buf + data_rw->offset,
1865 data_rw->size - data_rw->offset);
1866
1867 if (count <= 0) {
1868 if (errno == EINPROGRESS && !expired) return 0;
1869 if (errno == EIO) fatal(tcp_device);
1870
1871 /* A write expired or failed (usually a broken connection.) */
1872 if (debug >= 2) {
1873 printf("%s: TCP write reply: %s\n", nowgmt(), strerror(errno));
1874 }
1875 close_relay(data_rw);
1876 return 1;
1877 }
1878
1879 if (debug >= 2) {
1880 printf("%s: TCP write reply, %d/%u bytes\n",
1881 nowgmt(), data_rw->offset + count, data_rw->size);
1882 }
1883 data_rw->offset += count;
1884 if (data_rw->offset < data_rw->size) {
1885 /* Partial write, continue. */
1886 newjob(job_write_reply, now + LONG_TIMEOUT, data_rw);
1887 return 1;
1888 }
1889 if (debug >= 1) tcp_dns_tell(data_rw->w_fd, data_rw->buf);
1890
1891 /* Reply fully send on, go read more replies (or queries). */
1892 data_rw->offset= 0;
1893 data_rw->size= sizeof(u16_t);
1894 newjob(data_rw->w_fd != data_rw->r_fd ? job_read_reply : job_read_query,
1895 now + LONG_TIMEOUT, data_rw);
1896 return 1;
1897}
1898#else /* !DO_TCP */
1899
1900static int job_dummy(void *data, int expired)
1901{
1902 return 1;
1903}
1904#define job_setup_listen job_dummy
1905#define job_setup_connect job_dummy
1906#endif /* !DO_TCP */
1907
1908static void named_probe(ipaddr_t ip)
1909/* Send a probe to a name daemon, like 'host -r -t ns . <ip>'. */
1910{
1911 udp_dns_t udp;
1912# define dlen (offsetof(dns_t, data) + 5)
1913# define ulen (offsetof(udp_dns_t, dns) + dlen)
1914
1915 /* Send a simple DNS query that all name servers can answer easily:
1916 * "What are the name servers for the root domain?"
1917 */
1918 udp.dns.hdr.dh_id= new_id(ID_PROBE, my_port, ID_IPSELF);
1919 udp.dns.hdr.dh_flag1= 0;
1920 udp.dns.hdr.dh_flag2= 0;
1921 udp.dns.hdr.dh_qdcount= HTONS(1);
1922 udp.dns.hdr.dh_ancount= HTONS(0);
1923 udp.dns.hdr.dh_nscount= HTONS(0);
1924 udp.dns.hdr.dh_arcount= HTONS(0);
1925
1926 udp.dns.data[0] = 0; /* Null name. */
1927 pack16(udp.dns.data+1, HTONS(T_NS));
1928 pack16(udp.dns.data+3, HTONS(C_IN));
1929 if (debug >= 1) {
1930 printf("PROBE %s ", inet_ntoa(ip));
1931 dns_tell(0, &udp.dns, dlen);
1932 }
1933
1934 udp.hdr.uih_dst_addr= ip;
1935 udp.hdr.uih_dst_port= named_port;
1936 udp.hdr.uih_ip_opt_len= 0;
1937 udp.hdr.uih_data_len= dlen;
1938
1939 if (write(udp_fd, &udp, ulen) < 0) fatal(udp_device);
1940#undef dlen
1941#undef ulen
1942}
1943
1944static int job_find_named(void *data, int expired)
1945/* Look for a real name daemon to answer real DNS queries. */
1946{
1947 if (!expired) return 0;
1948 if (debug >= 2) printf("%s: Find named\n", nowgmt());
1949
1950 /* New search? */
1951 if (search_ct < 0) {
1952 search_ct= n_nameds;
1953 i_named= -1;
1954 }
1955
1956 if (--search_ct < 0) {
1957 /* Forced end of search (named response!), or end of search with
1958 * nothing found. Search again after a long time.
1959 */
1960 newjob(job_find_named,
1961 (stale > 0 || i_named > 0) ? now + LONG_TIMEOUT : NEVER, nil);
1962 force_expire(job_setup_connect);
1963 return 1;
1964 }
1965
1966 /* Send a named probe. */
1967 i_named= (i_named+1) % n_nameds;
1968 named_probe(current_named());
1969
1970 /* Schedule the next call. */
1971 newjob(job_find_named, now + SHORT_TIMEOUT, nil);
1972 return 1;
1973}
1974
1975static int job_expect_named(void *data, int expired)
1976/* The real name server is expected to answer by now. */
1977{
1978 if (!expired) return 0;
1979 if (debug >= 2) printf("%s: Expect named\n", nowgmt());
1980
1981 if (expecting() && !searching()) {
1982 /* No answer yet, start searching. */
1983 start_searching();
1984 force_expire(job_find_named);
1985 }
1986 return 1;
1987}
1988
1989static void sig_handler(int sig)
1990/* A signal forces a search for a real name daemon, etc. */
1991{
1992 switch (sig) {
1993 case SIGINT:
1994 case SIGTERM: done= 1; break;
1995 case SIGHUP: reinit= 1; break;
1996 case SIGUSR1: debug++; break;
1997 case SIGUSR2: debug= 0; break;
1998 }
1999}
2000
2001static void usage(void)
2002{
2003 fprintf(stderr, "Usage: nonamed [-qs] [-d[level]] [-p port]\n");
2004 exit(1);
2005}
2006
2007int main(int argc, char **argv)
2008{
2009 job_t *job;
2010 nwio_udpopt_t udpopt;
2011 int i;
2012 struct servent *servent;
2013 struct sigaction sa;
2014 FILE *fp;
2015 int quit= 0;
2016
2017 /* Debug output must be line buffered. */
2018 setvbuf(stdout, nil, _IOLBF, 0);
2019
2020 /* DNS service port number? */
2021 if ((servent= getservbyname("domain", nil)) == nil) {
2022 fprintf(stderr, "nonamed: \"domain\": unknown service\n");
2023 exit(1);
2024 }
2025 my_port= servent->s_port;
2026 named_port= servent->s_port;
2027
2028 i= 1;
2029 while (i < argc && argv[i][0] == '-') {
2030 char *opt= argv[i++] + 1, *end;
2031
2032 if (opt[0] == '-' && opt[1] == 0) break;
2033
2034 switch (*opt++) {
2035 case 'd': /* Debug level. */
2036 debug= 1;
2037 if (between('0', *opt, '9')) debug= strtoul(opt, &opt, 10);
2038 break;
2039 case 'p': /* Port to listen to (for testing.) */
2040 if (*opt == 0) {
2041 if (i == argc) usage();
2042 opt= argv[i++];
2043 }
2044 my_port= htons(strtoul(opt, &end, 0));
2045 if (opt == end || *end != 0) usage();
2046 opt= end;
2047 break;
2048 case 's':
2049 single= 1;
2050 break;
2051 case 'q': /* Quit after printing cache contents. */
2052 quit= 1;
2053 break;
2054 case 'L':
2055 localonly= 1;
2056 break;
2057 default:
2058 usage();
2059 }
2060 }
2061 if (i != argc) usage();
2062
2063 if (quit) {
2064 /* Oops, just having a look at the cache. */
2065 debug= 2;
2066 now= time(nil);
2067 n_datamax= -1;
2068 file2cache();
2069 return 0;
2070 }
2071
2072 /* Don't die on broken pipes, reinitialize on hangup, etc. */
2073 sa.sa_handler= SIG_IGN;
2074 sigemptyset(&sa.sa_mask);
2075 sa.sa_flags= 0;
2076 sigaction(SIGPIPE, &sa, nil);
2077 sa.sa_handler= sig_handler;
2078 sigaction(SIGINT, &sa, nil);
2079 sigaction(SIGHUP, &sa, nil);
2080 sigaction(SIGUSR1, &sa, nil);
2081 sigaction(SIGUSR2, &sa, nil);
2082 sigaction(SIGTERM, &sa, nil);
2083
2084 /* TCP and UDP device names. */
2085 if ((tcp_device= getenv("TCP_DEVICE")) == nil) tcp_device= TCP_DEVICE;
2086 if ((udp_device= getenv("UDP_DEVICE")) == nil) udp_device= UDP_DEVICE;
2087
2088 /* Open an UDP channel for incoming DNS queries. */
2089 if ((udp_fd= open(udp_device, O_RDWR)) < 0) fatal(udp_device);
2090
2091 udpopt.nwuo_flags= NWUO_EXCL | NWUO_LP_SET | NWUO_EN_LOC | NWUO_DI_BROAD
2092 | NWUO_RP_ANY | NWUO_RA_ANY | NWUO_RWDATALL | NWUO_DI_IPOPT;
2093 udpopt.nwuo_locport= my_port;
2094 if (ioctl(udp_fd, NWIOSUDPOPT, &udpopt) == -1
2095 || ioctl(udp_fd, NWIOGUDPOPT, &udpopt) == -1
2096 ) {
2097 fatal(udp_device);
2098 }
2099
2100 /* The current time is... */
2101 now= time(nil);
2102
2103 /* Read configuration and data cached by the previous nonamed. */
2104 init_config(udpopt.nwuo_locaddr);
2105 file2cache();
2106
2107 if (!single) {
2108 /* Save process id. */
2109 if ((fp= fopen(PIDFILE, "w")) != nil) {
2110 fprintf(fp, "%u\n", (unsigned) getpid());
2111 fclose(fp);
2112 }
2113 }
2114
2115 /* Jobs that start the ball rolling. */
2116 newjob(job_read_udp, NEVER, nil);
2117 newjob(job_setup_listen, IMMEDIATE, nil);
2118 newjob(job_find_named, IMMEDIATE, nil);
2119
2120 /* Open syslog. */
2121 openlog("nonamed", LOG_PID, LOG_DAEMON);
2122
2123 while (!done) {
2124 /* There is always something in the queue. */
2125 assert(queue != nil);
2126
2127 /* Any expired jobs? */
2128 while (queue->timeout <= now) {
2129 (void) execjob(queue, 1);
2130 assert(queue != nil);
2131 }
2132
2133 /* Check I/O jobs. */
2134 for (job= queue; job != nil; job= job->next) {
2135 if (execjob(job, 0)) break;
2136 }
2137
2138 if (queue->timeout != IMMEDIATE) {
2139 struct timeval tv, *tvp;
2140
2141 if (debug >= 2) printf("%s: I/O wait", nowgmt());
2142
2143 if (queue->timeout != NEVER) {
2144 tv.tv_sec= queue->timeout;
2145 tv.tv_usec= 0;
2146 tvp= &tv;
2147 if (debug >= 2) printf(" (expires %s)\n", timegmt(tv.tv_sec));
2148 } else {
2149 tvp= nil;
2150 if (debug >= 2) fputc('\n', stdout);
2151 }
2152 fflush(stdout);
2153
2154 if (asyn_wait(&asyn, 0, tvp) < 0) {
2155 if (errno != EINTR && errno != EAGAIN) fatal("fwait()");
2156 }
2157 now= time(nil);
2158 }
2159
2160 if (reinit) {
2161 /* A hangup makes us go back to square one. */
2162 reinit= 0;
2163 if (ioctl(udp_fd, NWIOGUDPOPT, &udpopt) == -1) fatal(udp_device);
2164 init_config(udpopt.nwuo_locaddr);
2165 start_searching();
2166 force_expire(job_find_named);
2167 }
2168 }
2169 cache2file();
2170 (void) unlink(PIDFILE);
2171 if (debug >= 2) printf("sbrk(0) = %u\n", (unsigned) sbrk(0));
2172 return 0;
2173}
Note: See TracBrowser for help on using the repository browser.