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