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