1 /* nonamed - Not a name daemon, but plays one on TV.
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>
27 #include <sys/ioctl.h>
28 #include <sys/asynchio.h>
30 #include <net/netlib.h>
31 #include <net/gen/in.h>
32 #include <net/gen/inet.h>
33 #include <net/gen/nameser.h>
34 #include <net/gen/resolv.h>
35 #include <net/gen/netdb.h>
36 #include <net/gen/socket.h>
37 #include <net/gen/tcp.h>
38 #include <net/gen/tcp_io.h>
39 #include <net/gen/udp.h>
40 #include <net/gen/udp_hdr.h>
41 #include <net/gen/udp_io.h>
42 #include <net/gen/dhcp.h>
44 #include <minix/paths.h>
46 #define HTTL 3600L /* Default time to live for /etc/hosts data. */
47 #define SHORT_TIMEOUT 2 /* If you expect an answer soon. */
48 #define MEDIUM_TIMEOUT 4 /* Soon, but not that soon. */
49 #define LONG_TIMEOUT 300 /* For stream connections to a real named. */
50 #define N_IDS 256 /* Keep track of this many queries. */
51 #define N_DATAMAX (4096*sizeof(char *)) /* Default response cache size. */
52 #define N_NAMEDS 8 /* Max # name daemons we can keep track of. */
53 #define NO_FD (-1) /* No name daemon channel here. */
54 #define T_NXD ((u16_t) -1) /* A "type" signalling a nonexistent domain. */
56 /* Can't do async I/O under standard Minix, so forget about TCP. */
57 #define DO_TCP (__minix_vmd || !__minix)
59 /* Host data, file to store our process id in, our cache, DHCP's cache. */
60 static char HOSTS
[]= _PATH_HOSTS
;
61 static char PIDFILE
[]= "/usr/run/nonamed.pid";
62 static char NNCACHE
[]= "/usr/adm/nonamed.cache";
63 static char DHCPCACHE
[]= _PATH_DHCPCACHE
;
65 /* Magic string to head the cache file. */
66 static char MAGIC
[4]= "NND\2";
68 #define arraysize(a) (sizeof(a) / sizeof((a)[0]))
69 #define arraylimit(a) ((a) + arraysize(a))
70 #define between(a, c, z) ((unsigned) ((c) - (a)) <= (unsigned) ((z) - (a)))
72 /* The start of time and the far future. */
73 #define IMMEDIATE ((time_t) 0)
74 #define NEVER ((time_t) ((time_t) -1 < 0 ? LONG_MAX : ULONG_MAX))
76 static unsigned debug
; /* Debug level. */
77 static time_t now
; /* Current time. */
78 static u32_t stale
; /* Extension time for stale data. */
79 static u32_t httl
; /* TTL for /etc/hosts data. */
80 static int reinit
, done
; /* Reinit config / program is done. */
81 static int single
; /* Run single on a nondefault interface. */
82 static int localonly
; /* Only accept local queries. */
83 #define LOCALHOST 0x7F000001
85 static void report(const char *label
)
87 fprintf(stderr
, "nonamed: %s: %s\n", label
, strerror(errno
));
90 static void fatal(const char *label
)
93 if (debug
>= 3) { fflush(nil
); abort(); }
97 static void *allocate(void *mem
, size_t size
)
99 if ((mem
= realloc(mem
, size
)) == nil
) fatal("malloc()");
103 static void deallocate(void *mem
)
108 static char *timegmt(time_t t
)
109 /* Simple "time in seconds to GMT time today" converter. */
112 static char asctime
[sizeof("00:00:00")];
119 sprintf(asctime
, "%02u:%02u:%02u", h
, m
, s
);
123 static char *nowgmt(void)
128 #define PC(n) ((void) sizeof(char [sizeof(*(n)) == 1]), (char *) (n))
129 #define namecpy(n1, n2) strcpy(PC(n1), PC(n2))
130 #define namecat(n1, n2) strcat(PC(n1), PC(n2))
131 #define namechr(n, c) ((u8_t *) strchr(PC(n), (c)))
132 #define namecmp(n1, n2) strcasecmp(PC(n1), PC(n2))
133 #define namencmp(n1, n2, len) strncasecmp(PC(n1), PC(n2), len)
135 typedef struct dns
{ /* A DNS packet. */
136 dns_hdr_t hdr
; /* DNS header. */
137 u8_t data
[PACKETSZ
- sizeof(dns_hdr_t
)]; /* DNS data. */
140 /* Addres of DNS packet to octet address, or vv. */
141 #define dns2oct(dp) ((u8_t *) (dp))
142 #define oct2dns(dp) ((dns_t *) (dp))
144 typedef struct query
{ /* One cached answer to a query. */
145 struct query
*less
; /* Less recently used. */
146 struct query
*more
; /* More recently used. */
147 time_t age
; /* Time it was added. */
148 time_t stale
; /* Time it goes stale by TTL. */
149 u16_t usage
; /* Counts of queries answered. */
150 u8_t flags
; /* QF_REFRESH. */
151 size_t size
; /* Size of DNS packet. */
152 dns_t dns
; /* Answer to query as a DNS packet. */
155 #define QF_REFRESH 0x01 /* This stale data must be refreshed. */
156 #define QU_SHIFT 1 /* To shift usage by when evicting. */
158 /* Size of new query_t or existing query_t. */
159 #define query_allocsize(dnssize) (offsetof(query_t, dns) + (dnssize))
160 #define query_size(qp) query_allocsize((qp)->size)
162 static query_t
*mru
, *lru
; /* Most and least recently used answers. */
163 static int q_refresh
; /* Set when an entry needs refreshing. */
165 static void pack16(u8_t
*buf
, u16_t s
)
166 /* Pack a 16 bit value into a byte array. */
168 buf
[0]= ((u8_t
*) &s
)[0];
169 buf
[1]= ((u8_t
*) &s
)[1];
172 static void pack32(u8_t
*buf
, u32_t l
)
173 /* Pack a 32 bit value into a byte array. */
175 buf
[0]= ((u8_t
*) &l
)[0];
176 buf
[1]= ((u8_t
*) &l
)[1];
177 buf
[2]= ((u8_t
*) &l
)[2];
178 buf
[3]= ((u8_t
*) &l
)[3];
181 static u16_t
upack16(u8_t
*buf
)
182 /* Unpack a 16 bit value from a byte array. */
186 ((u8_t
*) &s
)[0]= buf
[0];
187 ((u8_t
*) &s
)[1]= buf
[1];
191 static u32_t
upack32(u8_t
*buf
)
192 /* Unpack a 32 bit value from a byte array. */
196 ((u8_t
*) &l
)[0]= buf
[0];
197 ((u8_t
*) &l
)[1]= buf
[1];
198 ((u8_t
*) &l
)[2]= buf
[2];
199 ((u8_t
*) &l
)[3]= buf
[3];
203 /* Encoding of RRs: i(paddr), d(omain), l(ong), c(har), s(tring), (s)h(ort). */
204 static char *encoding
[] = {
205 "c*", /* anything unknown is c* */
224 static char *itoa(char *fmt
, u32_t i
)
226 static char output
[32 + 3 * sizeof(i
)];
228 sprintf(output
, fmt
, (unsigned long) i
);
232 static char *classname(unsigned class)
233 /* Class name of a resource record, for debug purposes. */
235 static char *classes
[] = { "IN", "CS", "CHAOS", "HS" };
237 if ((class - C_IN
) < arraysize(classes
)) return classes
[class - C_IN
];
238 return itoa("C_%u", class);
241 static char *typename(unsigned type
)
242 /* Type name of a resource record, for debug purposes. */
244 static char type_A
[][6] = {
245 "A", "NS", "MD", "MF", "CNAME", "SOA", "MB", "MG", "MR", "NULL",
246 "WKS", "PTR", "HINFO", "MINFO", "MX", "TXT",
248 static char type_AXFR
[][6] = {
249 "AXFR", "MAILB", "MAILA", "ANY",
251 if ((type
- T_A
) < arraysize(type_A
)) return type_A
[type
- T_A
];
252 if ((type
- T_AXFR
) < arraysize(type_AXFR
)) return type_AXFR
[type
- T_AXFR
];
253 return itoa("T_%u", type
);
256 static int print_qrr(dns_t
*dp
, size_t size
, u8_t
*cp0
, int q
)
257 /* Print a query (q) or resource record (!q) from 'cp0' in a DNS packet for
258 * debug purposes. Return number of bytes skipped or -1 on error.
261 u8_t name
[MAXDNAME
+1];
265 u16_t type
, class, rdlength
;
270 dlim
= dns2oct(dp
) + size
;
271 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
272 if (r
== -1) return -1;
274 if (cp
+ 2 * sizeof(u16_t
) > dlim
) return -1;
275 type
= ntohs(upack16(cp
));
277 class= ntohs(upack16(cp
));
279 printf("%-25s", (char *) name
);
281 /* We're just printing a query segment, stop right here. */
282 printf(" %8s", classname(class));
283 printf(" %-5s", typename(type
));
286 if (cp
+ sizeof(u32_t
) + sizeof(u16_t
) > dlim
) return -1;
287 ttl
= ntohl(upack32(cp
));
289 rdlength
= ntohs(upack16(cp
));
291 if (cp
+ rdlength
> dlim
) return -1;
292 rlim
= cp
+ rdlength
;
293 printf(" %5lu", (unsigned long) ttl
);
294 printf(" %s", classname(class));
295 printf(" %-5s", typename(type
));
296 ep
= type
< arraysize(encoding
) ? encoding
[type
] : encoding
[0];
300 if (cp
+ sizeof(u32_t
) > rlim
) return -1;
301 printf(" %s", inet_ntoa(upack32(cp
)));
305 if (cp
+ sizeof(u32_t
) > rlim
) return -1;
306 printf(" %ld", (long)(i32_t
) ntohl(upack32(cp
)));
310 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
311 if (r
== -1) return -1;
312 printf(" %s", (char *) name
);
316 if (cp
>= rlim
) return -1;
317 printf(" %02X", *cp
++);
321 if (cp
+ r
> rlim
) return -1;
322 printf(" \"%.*s\"", *cp
, (char *) (cp
+ 1));
326 if (cp
+ sizeof(u16_t
) > rlim
) return -1;
327 printf(" %u", ntohs(upack16(cp
)));
331 if (*ep
== '*') ep
= cp
< rlim
? ep
-1 : ep
+1;
336 static void dns_tell(int indent
, dns_t
*dp
, size_t size
)
337 /* Explain a DNS packet, for debug purposes. */
342 static char label
[4][4]= { "QD:", "AN:", "NS:", "AR:" };
343 static char rcodes
[][9] = {
344 "NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED"
347 if (size
< sizeof(dns_hdr_t
)) return;
349 printf("%*s", indent
, "");
350 printf("DNS %s:", (dp
->hdr
.dh_flag1
& DHF_QR
) ? "reply" : "query");
351 r
= dp
->hdr
.dh_flag2
& DHF_RCODE
;
352 printf(" %s", r
< arraysize(rcodes
) ? rcodes
[r
] : itoa("ERR_%lu", r
));
353 if (dp
->hdr
.dh_flag1
& DHF_AA
) printf(" AA");
354 if (dp
->hdr
.dh_flag1
& DHF_TC
) printf(" TC");
355 if (dp
->hdr
.dh_flag1
& DHF_RD
) printf(" RD");
356 if (dp
->hdr
.dh_flag2
& DHF_RA
) printf(" RA");
358 if (dp
->hdr
.dh_flag2
& DHF_AD
) printf(" AD");
359 if (dp
->hdr
.dh_flag2
& DHF_CD
) printf(" CD");
363 count
[0]= ntohs(dp
->hdr
.dh_qdcount
);
364 count
[1]= ntohs(dp
->hdr
.dh_ancount
);
365 count
[2]= ntohs(dp
->hdr
.dh_nscount
);
366 count
[3]= ntohs(dp
->hdr
.dh_arcount
);
368 for (i
= 0; i
< 4; i
++) {
369 while (count
[i
] > 0) {
370 printf("%*s", indent
, "");
371 printf(" %s ", label
[i
]);
372 r
= print_qrr(dp
, size
, cp
, (i
== 0));
381 static u32_t
dns_ttl(dns_t
*dp
, size_t size
, u32_t delta
)
382 /* Compute the minimum TTL of all RRs in a DNS packet and subtract delta from
383 * all TTLs. (We are actually only interested in the minimum (delta = 0) or
384 * the subtraction (delta > 0). It was easier to roll this into one routine.)
387 u8_t
*cp
, *rdp
, *dlim
;
388 int r
, i
, hasttl
, hassoa
;
389 unsigned type
, count
[4];
390 u32_t ttl
, minimum
, minttl
;
392 u8_t name
[MAXDNAME
+1];
395 minttl
= 365*24*3600L;
396 dlim
= dns2oct(dp
) + size
;
397 if (size
< sizeof(dns_hdr_t
)) return 0;
399 rcode
= dp
->hdr
.dh_flag2
& DHF_RCODE
;
400 count
[0]= ntohs(dp
->hdr
.dh_qdcount
);
401 count
[1]= ntohs(dp
->hdr
.dh_ancount
);
402 count
[2]= ntohs(dp
->hdr
.dh_nscount
);
403 count
[3]= ntohs(dp
->hdr
.dh_arcount
);
405 for (i
= 0; i
< 4 && cp
< dlim
; i
++) {
406 while (count
[i
] > 0) {
407 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
409 cp
+= r
+ 2 * sizeof(u16_t
);
411 if (cp
+ sizeof(u32_t
) + sizeof(u16_t
) > dlim
) break;
412 type
= upack16(cp
- 2 * sizeof(u16_t
));
413 ttl
= ntohl(upack32(cp
));
414 ttl
= ttl
< delta
? 0 : ttl
- delta
;
415 if (rcode
== NXDOMAIN
&& i
== 2 && type
== HTONS(T_SOA
)) {
416 rdp
= cp
+ sizeof(u32_t
) + sizeof(u16_t
);
417 r
= dn_expand(dns2oct(dp
), dlim
, rdp
, name
, MAXDNAME
);
420 r
= dn_expand(dns2oct(dp
), dlim
, rdp
, name
, MAXDNAME
);
422 rdp
+= r
+ 4 * sizeof(u32_t
);
423 if (rdp
+ sizeof(u32_t
) > dlim
) break;
424 minimum
= ntohl(upack32(rdp
));
425 if (ttl
> minimum
) ttl
= minimum
;
428 if (delta
!= 0) pack32(cp
, htonl(ttl
));
429 if (ttl
< minttl
) minttl
= ttl
;
432 cp
+= sizeof(u16_t
) + ntohs(upack16(cp
));
437 return ((rcode
== NOERROR
&& hasttl
) || (rcode
== NXDOMAIN
&& hassoa
))
441 /* Total cached query data. */
442 static size_t n_datamax
= N_DATAMAX
;
443 static size_t n_data
;
445 static query_t
*extract_query(query_t
*qp
)
446 /* Take a query out of the query cache. */
449 *(qp
->less
!= nil
? &qp
->less
->more
: &lru
) = qp
->more
;
450 *(qp
->more
!= nil
? &qp
->more
->less
: &mru
) = qp
->less
;
451 n_data
-= query_size(qp
);
455 static query_t
*get_query(u8_t
*name
, unsigned type
)
456 /* Find a query and if so remove it from the cache and return it. */
459 u8_t qname
[MAXDNAME
+1];
462 for (qp
= mru
; qp
!= nil
; qp
= less
) {
464 if (qp
->stale
<= now
- stale
) {
465 /* This answer has expired. */
466 deallocate(extract_query(qp
));
468 r
= dn_expand(dns2oct(&qp
->dns
), dns2oct(&qp
->dns
) + qp
->size
,
469 qp
->dns
.data
, qname
, MAXDNAME
);
470 if (r
== -1) continue;
471 if (namecmp(qname
, name
) == 0 && upack16(qp
->dns
.data
+r
) == type
) {
472 /* Found an answer to the query. */
473 return extract_query(qp
);
480 static void insert_query(query_t
*qp
)
481 /* (Re)insert a query into the cache. */
483 *(qp
->less
!= nil
? &qp
->less
->more
: &lru
) = qp
;
484 *(qp
->more
!= nil
? &qp
->more
->less
: &mru
) = qp
;
485 n_data
+= query_size(qp
);
487 /* Try to delete the LRU while there is too much memory in use. If
488 * its usage count is too high then it gets a second chance.
490 while (n_data
> n_datamax
&& lru
!= nil
) {
491 if ((lru
->usage
>>= QU_SHIFT
) == 0 || lru
->stale
<= now
- stale
) {
492 deallocate(extract_query(lru
));
494 lru
->less
= mru
; /* Make list circular. */
496 mru
= lru
; /* Move one over, making LRU the MRU. */
498 lru
->less
= nil
; /* Break the circle. */
505 for (qp
= mru
; qp
!= nil
; qp
= qp
->less
) n
++;
506 printf("%u cached repl%s, %u bytes, sbrk(0) = %u\n",
507 n
, n
== 1 ? "y" : "ies",
513 static void put_query(query_t
*qp
)
514 /* Add a new query to the cache as the MRU. */
521 static void cache2file(void)
522 /* Store the cached data into the cache file. */
528 char newcache
[sizeof(NNCACHE
) + sizeof(".new")];
532 strcpy(newcache
, NNCACHE
);
533 strcat(newcache
, ".new");
535 if ((fp
= fopen(newcache
, "w")) == nil
) {
536 if ((errno
!= ENOENT
&& errno
!= EROFS
) || debug
>= 2) report(newcache
);
539 if (debug
>= 2) printf("Writing %s:\n", newcache
);
542 fwrite(MAGIC
, 1, sizeof(MAGIC
), fp
);
544 for (qp
= lru
; qp
!= nil
; qp
= qp
->more
) {
545 if (qp
->stale
<= now
- stale
) continue;
547 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
548 qp
->usage
, (long) (now
- qp
->age
), qp
->flags
);
549 dns_tell(2, &qp
->dns
, qp
->size
);
551 pack32(data
+0, htonl(qp
->age
));
553 pack16(data
+5, htons(qp
->size
));
554 pack16(data
+7, htons(qp
->usage
));
555 fwrite(data
, 1, sizeof(data
), fp
);
556 fwrite(&qp
->dns
, 1, qp
->size
, fp
);
557 if (ferror(fp
)) break;
560 if (ferror(fp
) || fclose(fp
) == EOF
) {
562 (void) unlink(newcache
);
566 if (debug
>= 2) printf("mv %s %s\n", newcache
, NNCACHE
);
567 if (rename(newcache
, NNCACHE
) < 0) {
568 fprintf(stderr
, "nonamed: mv %s %s: %s\n",
569 newcache
, NNCACHE
, strerror(errno
));
570 (void) unlink(newcache
);
574 static void file2cache(void)
575 /* Read cached data from the cache file. */
584 if ((fp
= fopen(NNCACHE
, "r")) == nil
) {
585 if (errno
!= ENOENT
|| debug
>= 2) report(NNCACHE
);
588 if (debug
>= 2) printf("Reading %s:\n", NNCACHE
);
591 fread(data
, 1, sizeof(MAGIC
), fp
);
592 if (ferror(fp
) || memcmp(MAGIC
, data
, sizeof(MAGIC
)) != 0) goto err
;
595 fread(data
, 1, sizeof(data
), fp
);
596 if (feof(fp
) || ferror(fp
)) break;
597 dlen
= ntohs(upack16(data
+5));
598 qp
= allocate(nil
, query_allocsize(dlen
));
599 qp
->age
= htonl(upack32(data
+0));
601 if (qp
->flags
& QF_REFRESH
) q_refresh
= 1;
603 qp
->usage
= htons(upack16(data
+7));
604 fread(&qp
->dns
, 1, qp
->size
, fp
);
605 if (feof(fp
) || ferror(fp
)) {
609 qp
->stale
= qp
->age
+ dns_ttl(&qp
->dns
, dlen
, 0);
611 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
612 qp
->usage
, (long) (now
- qp
->age
), qp
->flags
);
613 dns_tell(2, &qp
->dns
, dlen
);
619 /* The cache file did not end at EOF or is otherwise a mess. */
620 fprintf(stderr
, "nonamed: %s: %s\n", NNCACHE
,
621 ferror(fp
) ? strerror(errno
) : "Corrupt");
622 while (lru
!= nil
) deallocate(extract_query(lru
));
627 typedef int handler_t(void *data
, int expired
);
629 /* All actions are in the form of "jobs". */
631 struct job
*next
, **prev
; /* To make a job queue. */
632 handler_t
*handler
; /* Function to handle this job. */
633 time_t timeout
; /* Moment it times out. */
634 void *data
; /* Data associated with the job. */
637 static job_t
*queue
; /* Main job queue. */
639 static void newjob(handler_t
*handler
, time_t timeout
, void *data
)
640 /* Create a new job with the given handler, timeout time and data. */
644 job
= allocate(nil
, sizeof(*job
));
645 job
->handler
= handler
;
646 job
->timeout
= timeout
;
649 for (prev
= &queue
; *prev
!= nil
; prev
= &(*prev
)->next
) {
650 if (job
->timeout
< (*prev
)->timeout
) break;
655 if (job
->next
!= nil
) job
->next
->prev
= &job
->next
;
658 static int execjob(job_t
*job
, int expired
)
659 /* Execute a job by calling the handler. Remove the job if it returns true,
660 * indicating that it is done. Expired is set if the job timed out. It is
661 * otherwise called to check for I/O.
664 if ((*job
->handler
)(job
->data
, expired
)) {
665 *job
->prev
= job
->next
;
666 if (job
->next
!= nil
) job
->next
->prev
= job
->prev
;
673 static void force_expire(handler_t
*handler
)
674 /* Force jobs to expire immediately, the named searcher for instance. */
676 job_t
*job
, **prev
= &queue
;
678 while ((job
= *prev
) != nil
) {
679 if (job
->handler
== handler
&& job
->timeout
!= IMMEDIATE
) {
681 if (job
->next
!= nil
) job
->next
->prev
= prev
;
682 newjob(job
->handler
, IMMEDIATE
, job
->data
);
690 static int nxdomain(u8_t
*name
)
691 /* True iff the two top level components in a name are repeated in the name,
692 * or if in-addr.arpa is found within a name. Such things happen often in a
693 * search for an already fully qualified local name. For instance:
694 * flotsam.cs.vu.nl.cs.vu.nl. (We don't want this at boot time.)
700 end
= namechr(name
, 0);
702 while (top
> name
&& *--top
!= '.') {}
703 while (top
> name
&& *--top
!= '.') {}
707 if (p
== name
) return 0;
709 if (namencmp(p
, top
, n
) == 0 && p
[n
] == '.') return 1;
710 if (namencmp(p
, ".in-addr.arpa.", 14) == 0) return 1;
715 typedef struct id2id
{
716 u16_t id
; /* ID of old query. */
717 u16_t port
; /* Reply port. */
718 ipaddr_t ip
; /* Reply address. */
721 static id2id_t id2id
[N_IDS
];
722 static u16_t id_counter
;
724 static u16_t
new_id(u16_t in_id
, u16_t in_port
, ipaddr_t in_ip
)
725 /* An incoming UDP query must be relabeled with a new ID before it can be
726 * send on to a real name daemon.
733 idp
= &id2id
[id
% N_IDS
];
740 static int old_id(u16_t id
, u16_t
*out_id
, u16_t
*out_port
, ipaddr_t
*out_ip
)
741 /* Translate a reply id back to the id, port, and address used in the query.
742 * Return true if the translation is possible.
746 if ((u16_t
) (id_counter
- id
) > N_IDS
) {
750 /* We know this one. */
751 id2id_t
*idp
= &id2id
[id
% N_IDS
];
753 if (idp
->port
== 0) return 0; /* Named is trying to fool us? */
755 *out_port
= idp
->port
;
762 /* IDs used to mark my own queries to name servers, must be new_id translated
763 * to make them unique "on the wire".
765 #define ID_IPSELF HTONL(0) /* "I did it myself" address. */
766 #define ID_PROBE HTONS(0) /* Name server probe. */
767 #define ID_REFRESH HTONS(1) /* Query to refresh a cache entry. */
769 static char *tcp_device
, *udp_device
; /* TCP and UDP device names. */
770 static int udp_fd
; /* To send or receive UDP packets. */
771 static asynchio_t asyn
; /* For I/O in progress. */
772 static ipaddr_t my_ip
; /* My IP address. */
773 static u16_t my_port
, named_port
; /* Port numbers, normally "domain". */
775 static ipaddr_t named
[N_NAMEDS
]; /* Addresses of all name servers. */
776 static unsigned n_nameds
; /* Number of configured name daemons. */
777 static unsigned i_named
; /* Index to current name server. */
778 static int expect
; /* Set when we expect an answer. */
779 static int search_ct
= -1; /* Named search count and state. */
780 static int dirty
; /* True when new entry put in cache. */
782 #define current_named() (+named[i_named])
783 #define searching() (search_ct > 0)
784 #define start_searching() ((void) (search_ct= -1))
785 #define stop_searching() ((void) (search_ct= 0))
786 #define expecting() (+expect)
787 #define start_expecting() ((void) (expect= 1))
788 #define stop_expecting() ((void) (expect= 0))
790 static time_t filetime(const char *file
)
791 /* Get the modified time of a file. */
795 return stat(file
, &st
) == 0 ? st
.st_mtime
: 0;
798 static void init_config(ipaddr_t ifip
)
799 /* Read name daemon list and other special stuff from the hosts file. */
803 static time_t hosts_time
, dhcp_time
;
806 /* See if anything really changed. */
807 if (((ifip
^ HTONL(LOCALHOST
)) & HTONL(0xFF000000)) == 0) ifip
= my_ip
;
809 dt
= filetime(DHCPCACHE
);
810 if (ifip
== my_ip
&& ht
== hosts_time
&& dt
== dhcp_time
) return;
816 printf("%s: I am nonamed %s at %s:%u\n",
817 nowgmt(), version
, inet_ntoa(my_ip
), ntohs(my_port
));
826 while ((he
= gethostent()) != nil
) {
827 memcpy(&nip
, he
->h_addr
, sizeof(u32_t
));
829 if (namecmp(he
->h_name
, "%ttl") == 0) httl
= nip
;
830 if (namecmp(he
->h_name
, "%stale") == 0) stale
= hip
;
831 if (namecmp(he
->h_name
, "%memory") == 0) n_datamax
= hip
;
832 if (namecmp(he
->h_name
, "%nameserver") == 0) {
833 if (nip
!= my_ip
|| named_port
!= my_port
) {
834 if (n_nameds
< N_NAMEDS
) named
[n_nameds
++]= nip
;
842 /* No name daemons found in the host file. What about DHCP? */
849 if ((fd
= open(DHCPCACHE
, O_RDONLY
)) < 0) {
850 if (errno
!= ENOENT
) fatal(DHCPCACHE
);
852 while ((r
= read(fd
, &d
, sizeof(d
))) == sizeof(d
)) {
853 if (d
.yiaddr
== my_ip
) break;
855 if (r
< 0) fatal(DHCPCACHE
);
858 if (r
== sizeof(d
) && dhcp_gettag(&d
, DHCP_TAG_DNS
, &data
, &len
)) {
859 while (len
>= sizeof(nip
)) {
860 memcpy(&nip
, data
, sizeof(nip
));
863 if (nip
!= my_ip
|| named_port
!= my_port
) {
864 if (n_nameds
< N_NAMEDS
) named
[n_nameds
++]= nip
;
873 static handler_t job_save_cache
, job_read_udp
, job_find_named
, job_expect_named
;
875 static handler_t job_setup_listen
, job_listen
, job_setup_connect
, job_connect
;
876 static handler_t job_read_query
, job_write_query
;
877 static handler_t job_read_reply
, job_write_reply
;
880 static int query_hosts(u8_t
*qname
, unsigned type
, dns_t
*dp
, size_t *pdlen
)
881 /* Read the /etc/hosts file to try and answer an A or PTR query. Return
882 * true iff an answer can be found, with the answer copied to *dp.
890 u8_t name
[MAXDNAME
+1];
893 struct hostent localhost
;
894 static char *noaliases
[]= { nil
};
895 static ipaddr_t localaddr
= HTONL(LOCALHOST
);
896 static char *localaddrlist
[]= { (char *) &localaddr
, nil
};
898 if (single
) return 0;
900 /* Assume we can answer. */
901 dns
.hdr
.dh_flag1
= DHF_QR
| DHF_AA
;
902 dns
.hdr
.dh_flag2
= DHF_RA
;
903 dns
.hdr
.dh_qdcount
= HTONS(1);
905 dns
.hdr
.dh_nscount
= HTONS(0);
906 dns
.hdr
.dh_arcount
= HTONS(0);
908 dnvec
[0]= dns2oct(&dns
);
911 r
= dn_comp(qname
, cp
, arraysize(dns
.data
), dnvec
, arraylimit(dnvec
));
912 if (r
== -1) return 0;
916 pack16(cp
, HTONS(C_IN
));
919 /* Localhost is fixed to 127.0.0.1. */
921 namencmp(qname
, "localhost.", 10) == 0 ? (char *) qname
: "localhost";
922 localhost
.h_aliases
= noaliases
;
923 localhost
.h_addr_list
= localaddrlist
;
930 if (namecmp(qname
, he
->h_name
) == 0) {
932 r
= dn_comp((u8_t
*) he
->h_name
, cp
, arraylimit(dns
.data
) - cp
,
933 dnvec
, arraylimit(dnvec
));
934 if (r
== -1) return 0;
936 if (cp
+ 3 * sizeof(u16_t
) + 2 * sizeof(u32_t
)
937 > arraylimit(dns
.data
)) { r
= -1; break; }
938 pack16(cp
, HTONS(T_A
));
940 pack16(cp
, HTONS(C_IN
));
944 pack16(cp
, HTONS(sizeof(u32_t
)));
946 memcpy(cp
, he
->h_addr
, sizeof(u32_t
));
953 domain
= namechr(he
->h_name
, '.');
954 for (i
= 0; he
->h_aliases
[i
] != nil
; i
++) {
955 namecpy(name
, he
->h_aliases
[i
]);
956 if (domain
!= nil
&& namechr(name
, '.') == nil
) {
957 namecat(name
, domain
);
959 if (namecmp(qname
, name
) == 0) {
960 r
= dn_comp(name
, cp
, arraylimit(dns
.data
) - cp
,
961 dnvec
, arraylimit(dnvec
));
964 if (cp
+ 3 * sizeof(u16_t
)
965 + 1 * sizeof(u32_t
) > arraylimit(dns
.data
)) return 0;
966 pack16(cp
, HTONS(T_CNAME
));
968 pack16(cp
, HTONS(C_IN
));
972 /* pack16(cp, htonl(RDLENGTH)) */
974 r
= dn_comp((u8_t
*) he
->h_name
, cp
,
975 arraylimit(dns
.data
) - cp
,
976 dnvec
, arraylimit(dnvec
));
978 pack16(cp
- sizeof(u16_t
), htons(r
));
981 if (type
== HTONS(T_A
)) goto addA
; /* really wants A */
987 if (ancount
> 0) break;
988 if (he
->h_name
[0] == '%') break;
989 sprintf((char *) name
, "%d.%d.%d.%d.in-addr.arpa",
990 ((u8_t
*) he
->h_addr
)[3],
991 ((u8_t
*) he
->h_addr
)[2],
992 ((u8_t
*) he
->h_addr
)[1],
993 ((u8_t
*) he
->h_addr
)[0]);
994 if (namecmp(qname
, name
) == 0) {
995 r
= dn_comp(name
, cp
, arraylimit(dns
.data
) - cp
,
996 dnvec
, arraylimit(dnvec
));
999 if (cp
+ 3 * sizeof(u16_t
) + 1 * sizeof(u32_t
)
1000 > arraylimit(dns
.data
)) { r
= -1; break; }
1001 pack16(cp
, HTONS(T_PTR
));
1002 cp
+= sizeof(u16_t
);
1003 pack16(cp
, HTONS(C_IN
));
1004 cp
+= sizeof(u16_t
);
1006 cp
+= sizeof(u32_t
);
1007 /* pack16(cp, htonl(RDLENGTH)) */
1008 cp
+= sizeof(u16_t
);
1009 r
= dn_comp((u8_t
*) he
->h_name
, cp
,
1010 arraylimit(dns
.data
) - cp
, dnvec
, arraylimit(dnvec
));
1011 if (r
== -1) return 0;
1012 pack16(cp
- sizeof(u16_t
), htons(r
));
1018 } while (r
!= -1 && (he
= gethostent()) != nil
);
1021 if (r
== -1 || ancount
== 0) return 0;
1023 dns
.hdr
.dh_ancount
= htons(ancount
);
1024 memcpy(dp
, &dns
, *pdlen
= cp
- dns2oct(&dns
));
1028 static int query_chaos(u8_t
*qname
, unsigned type
, dns_t
*dp
, size_t *pdlen
)
1029 /* Report my version. Can't let BIND take all the credit. :-) */
1036 if (type
!= HTONS(T_TXT
) || namecmp(qname
, "version.bind") != 0) return 0;
1038 dns
.hdr
.dh_flag1
= DHF_QR
| DHF_AA
;
1039 dns
.hdr
.dh_flag2
= DHF_RA
;
1040 dns
.hdr
.dh_qdcount
= HTONS(1);
1041 dns
.hdr
.dh_ancount
= HTONS(1);
1042 dns
.hdr
.dh_nscount
= HTONS(0);
1043 dns
.hdr
.dh_arcount
= htons(n_nameds
);
1045 dnvec
[0]= dns2oct(&dns
);
1048 r
= dn_comp(qname
, cp
, arraysize(dns
.data
), dnvec
, arraylimit(dnvec
));
1049 if (r
== -1) return 0;
1052 cp
+= sizeof(u16_t
);
1053 pack16(cp
, HTONS(C_CHAOS
));
1054 cp
+= sizeof(u16_t
);
1056 r
= dn_comp(qname
, cp
, arraylimit(dns
.data
) - cp
, dnvec
, arraylimit(dnvec
));
1057 if (r
== -1) return 0;
1059 pack16(cp
, HTONS(T_TXT
));
1060 cp
+= sizeof(u16_t
);
1061 pack16(cp
, HTONS(C_CHAOS
));
1062 cp
+= sizeof(u16_t
);
1063 pack32(cp
, HTONL(0));
1064 cp
+= sizeof(u32_t
);
1065 /* pack16(cp, htonl(RDLENGTH)) */
1066 cp
+= sizeof(u16_t
);
1067 sprintf((char *) cp
+ 1, "nonamed %s at %s:%u",
1068 version
, inet_ntoa(my_ip
), ntohs(my_port
));
1069 r
= strlen((char *) cp
+ 1) + 1;
1070 pack16(cp
- sizeof(u16_t
), htons(r
));
1073 for (n
= 0, i
= i_named
; n
< n_nameds
; n
++, i
= (i
+1) % n_nameds
) {
1074 r
= dn_comp((u8_t
*) "%nameserver", cp
, arraylimit(dns
.data
) - cp
,
1075 dnvec
, arraylimit(dnvec
));
1076 if (r
== -1) return 0;
1078 if (cp
+ 3 * sizeof(u16_t
)
1079 + 2 * sizeof(u32_t
) > arraylimit(dns
.data
)) return 0;
1080 pack16(cp
, HTONS(T_A
));
1081 cp
+= sizeof(u16_t
);
1082 pack16(cp
, HTONS(C_IN
));
1083 cp
+= sizeof(u16_t
);
1084 pack32(cp
, HTONL(0));
1085 cp
+= sizeof(u32_t
);
1086 pack16(cp
, HTONS(sizeof(u32_t
)));
1087 cp
+= sizeof(u16_t
);
1088 memcpy(cp
, &named
[i
], sizeof(u32_t
));
1089 cp
+= sizeof(u32_t
);
1092 memcpy(dp
, &dns
, *pdlen
= cp
- dns2oct(&dns
));
1096 static void cache_reply(dns_t
*dp
, size_t dlen
)
1097 /* Store a DNS packet in the cache. */
1100 query_t
*qp
, *less
, *more
;
1104 u8_t name
[MAXDNAME
];
1107 if ((dp
->hdr
.dh_flag1
& (DHF_RD
| DHF_TC
)) != DHF_RD
) return;
1108 if (dp
->hdr
.dh_qdcount
!= HTONS(1)) return;
1110 r
= dn_expand(dns2oct(dp
), dns2oct(dp
) + dlen
, cp
, name
, MAXDNAME
);
1111 if (r
== -1) return;
1114 cp
+= sizeof(u16_t
);
1115 if (upack16(cp
) != HTONS(C_IN
)) return;
1117 /* Delete old cached data, if any. Note where it is in the LRU. */
1118 if ((qp
= get_query(name
, type
)) != nil
) {
1124 /* Not yet in the cache. */
1130 /* Determine minimum TTL. Discard if zero, never cache zero TTLs. */
1131 if ((minttl
= dns_ttl(dp
, dlen
, 0)) == 0) return;
1133 /* Enter new reply in cache. */
1134 qp
= allocate(nil
, query_allocsize(dlen
));
1141 memcpy(&qp
->dns
, dp
, dlen
);
1142 qp
->stale
= qp
->age
+ minttl
;
1144 if (debug
>= 1) printf("Answer cached\n");
1146 /* Save the cache soon. */
1149 newjob(job_save_cache
, now
+ LONG_TIMEOUT
, nil
);
1153 static int job_save_cache(void *data
, int expired
)
1154 /* Some time after the cache is changed it is written back to disk. */
1156 if (!expired
) return 0;
1161 static int compose_reply(dns_t
*dp
, size_t *pdlen
)
1162 /* Try to compose a reply to a request in *dp using the hosts file or
1163 * cached data. Return answer in *dp with its size in *pdlen. Return true
1164 * iff an answer is given.
1167 size_t dlen
= *pdlen
;
1170 unsigned id
, type
, class;
1172 u8_t name
[MAXDNAME
];
1175 r
= dn_expand(dns2oct(dp
), dns2oct(dp
) + dlen
, cp
, name
, MAXDNAME
);
1178 if (cp
+ 2 * sizeof(u16_t
) > dns2oct(dp
) + dlen
) {
1182 cp
+= sizeof(u16_t
);
1184 cp
+= sizeof(u16_t
);
1188 /* Remember ID and RD. */
1190 rd
= dp
->hdr
.dh_flag1
& DHF_RD
;
1193 /* Malformed query, reply "FORMERR". */
1194 dp
->hdr
.dh_flag1
&= ~(DHF_TC
);
1195 dp
->hdr
.dh_flag1
|= DHF_QR
| DHF_AA
;
1196 dp
->hdr
.dh_flag2
&= ~(DHF_UNUSED
| DHF_RCODE
);
1197 dp
->hdr
.dh_flag2
|= DHF_RA
| FORMERR
;
1199 if (class == HTONS(C_IN
) && query_hosts(name
, type
, dp
, pdlen
)) {
1200 /* Answer to this query is in the hosts file. */
1203 if (class == HTONS(C_IN
) && (qp
= get_query(name
, type
)) != nil
) {
1204 /* Answer to this query is present in the cache. */
1205 memcpy(dp
, &qp
->dns
, dlen
= qp
->size
);
1206 dp
->hdr
.dh_flag1
&= ~DHF_AA
;
1207 (void) dns_ttl(dp
, dlen
, now
- qp
->age
);
1209 if (qp
->stale
<= now
) {
1210 qp
->flags
|= QF_REFRESH
;
1217 if (class == HTONS(C_CHAOS
) && query_chaos(name
, type
, dp
, pdlen
)) {
1218 /* Return our version numbers. */
1221 if (n_nameds
== 0 || nxdomain(name
)) {
1222 /* No real name daemon present, or this name has a repeated top level
1223 * domain sequence. Reply "no such domain".
1225 dp
->hdr
.dh_flag1
&= ~(DHF_TC
);
1226 dp
->hdr
.dh_flag1
|= DHF_QR
| DHF_AA
;
1227 dp
->hdr
.dh_flag2
&= ~(DHF_UNUSED
| DHF_RCODE
);
1228 dp
->hdr
.dh_flag2
|= DHF_RA
| NXDOMAIN
;
1231 /* "Recursion Desired" is off, so don't bother to relay. */
1232 dp
->hdr
.dh_flag1
&= ~(DHF_TC
);
1233 dp
->hdr
.dh_flag1
|= DHF_QR
;
1234 dp
->hdr
.dh_flag2
&= ~(DHF_UNUSED
| DHF_RCODE
);
1235 dp
->hdr
.dh_flag2
|= DHF_RA
| NOERROR
;
1237 /* Caller needs to consult with a real name daemon. */
1241 /* Copy ID and RD back to answer. */
1243 dp
->hdr
.dh_flag1
&= ~DHF_RD
;
1244 dp
->hdr
.dh_flag1
|= rd
;
1249 typedef struct udp_dns
{ /* One DNS packet over UDP. */
1250 udp_io_hdr_t hdr
; /* UDP header (source/destination). */
1251 dns_t dns
; /* DNS packet. */
1254 static void refresh_cache(void)
1255 /* Find a stale entry in the cache that was used to answer a query, and send
1256 * a request to a name server that should refresh this entry.
1264 u8_t qname
[MAXDNAME
+1];
1268 if (!q_refresh
) return;
1269 for (qp
= lru
; qp
!= nil
; qp
= qp
->more
) {
1270 if ((qp
->flags
& QF_REFRESH
) && qp
->stale
> now
- stale
) break;
1277 /* Found one to refresh. */
1278 qp
->flags
&= ~QF_REFRESH
;
1279 r
= dn_expand(dns2oct(&qp
->dns
), dns2oct(&qp
->dns
) + qp
->size
,
1280 qp
->dns
.data
, qname
, MAXDNAME
);
1281 if (r
== -1) return;
1282 type
= upack16(qp
->dns
.data
+r
);
1284 dnvec
[0]= dns2oct(&udp
.dns
);
1287 r
= dn_comp(qname
, cp
, arraysize(udp
.dns
.data
), dnvec
, arraylimit(dnvec
));
1288 if (r
== -1) return;
1291 cp
+= sizeof(u16_t
);
1292 pack16(cp
, HTONS(C_IN
));
1293 cp
+= sizeof(u16_t
);
1294 dlen
= cp
- dns2oct(&udp
.dns
);
1296 udp
.dns
.hdr
.dh_id
= new_id(ID_REFRESH
, my_port
, ID_IPSELF
);
1297 udp
.dns
.hdr
.dh_flag1
= DHF_RD
;
1298 udp
.dns
.hdr
.dh_flag2
= 0;
1299 udp
.dns
.hdr
.dh_qdcount
= HTONS(1);
1300 udp
.dns
.hdr
.dh_ancount
= HTONS(0);
1301 udp
.dns
.hdr
.dh_nscount
= HTONS(0);
1302 udp
.dns
.hdr
.dh_arcount
= HTONS(0);
1304 udp
.hdr
.uih_dst_addr
= current_named();
1305 udp
.hdr
.uih_dst_port
= named_port
;
1306 udp
.hdr
.uih_ip_opt_len
= 0;
1307 udp
.hdr
.uih_data_len
= dlen
;
1310 printf("Refresh to %s:%u:\n",
1311 inet_ntoa(current_named()), ntohs(named_port
));
1312 dns_tell(0, &udp
.dns
, dlen
);
1314 ulen
= offsetof(udp_dns_t
, dns
) + dlen
;
1315 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1318 static int job_read_udp(void *data
, int expired
)
1319 /* Read UDP queries and replies. */
1322 static udp_dns_t udp
;
1329 /* Try to read a packet. */
1330 ulen
= asyn_read(&asyn
, udp_fd
, &udp
, sizeof(udp
));
1331 dlen
= ulen
- offsetof(udp_dns_t
, dns
);
1334 if (errno
== EINPROGRESS
&& !expired
) return 0;
1335 if (errno
== EIO
) fatal(udp_device
);
1338 printf("%s: UDP read: %s\n", nowgmt(), strerror(errno
));
1342 printf("%s: UDP read, %d bytes\n", nowgmt(), (int) ulen
);
1346 /* Restart this job no matter what. */
1347 newjob(job_read_udp
, NEVER
, nil
);
1349 if (ulen
< (ssize_t
) (sizeof(udp_io_hdr_t
) + sizeof(dns_hdr_t
))) return 1;
1352 printf("%s:%u UDP ", inet_ntoa(udp
.hdr
.uih_src_addr
),
1353 ntohs(udp
.hdr
.uih_src_port
));
1354 dns_tell(0, &udp
.dns
, dlen
);
1357 /* Check, and if necessary reinitialize my configuration. */
1358 init_config(udp
.hdr
.uih_dst_addr
);
1360 if (udp
.dns
.hdr
.dh_flag1
& DHF_QR
) {
1361 /* This is a remote named reply, not a query. */
1363 /* Response to a query previously relayed? */
1364 if (!old_id(udp
.dns
.hdr
.dh_id
, &id
, &port
, &ip
)) return 1;
1366 if (ip
== ID_IPSELF
&& id
== ID_PROBE
) {
1368 /* We have found a name server! */
1372 for (i
= 0; i
< n_nameds
; i
++) {
1373 if (named
[i
] == udp
.hdr
.uih_src_addr
) {
1376 printf("Current named = %s\n",
1377 inet_ntoa(current_named()));
1380 force_expire(job_find_named
);
1386 /* We got an answer, so stop worrying. */
1389 force_expire(job_expect_named
);
1392 /* Put the information in the cache. */
1393 cache_reply(&udp
.dns
, dlen
);
1395 /* Refresh a cached entry that was used when stale. */
1398 /* Discard reply to myself. */
1399 if (ip
== ID_IPSELF
) return 1;
1401 /* Send the reply to the process that asked for it. */
1402 udp
.dns
.hdr
.dh_id
= id
;
1403 udp
.hdr
.uih_dst_addr
= ip
;
1404 udp
.hdr
.uih_dst_port
= port
;
1405 if (debug
>= 1) printf("To client %s:%u\n", inet_ntoa(ip
), ntohs(port
));
1408 if (udp
.dns
.hdr
.dh_qdcount
!= HTONS(1)) return 1;
1411 /* Check if it's a local query. */
1412 if(ntohl(udp
.hdr
.uih_src_addr
) != LOCALHOST
) {
1413 syslog(LOG_WARNING
, "nonamed: dropped query from %s",
1414 inet_ntoa(udp
.hdr
.uih_src_addr
));
1419 /* Try to compose a reply from local data. */
1420 if (compose_reply(&udp
.dns
, &dlen
)) {
1421 udp
.hdr
.uih_dst_addr
= udp
.hdr
.uih_src_addr
;
1422 udp
.hdr
.uih_dst_port
= udp
.hdr
.uih_src_port
;
1423 udp
.hdr
.uih_ip_opt_len
= 0;
1424 udp
.hdr
.uih_data_len
= dlen
;
1425 ulen
= offsetof(udp_dns_t
, dns
) + dlen
;
1427 /* Send an UDP DNS reply. */
1429 printf("%s:%u UDP ", inet_ntoa(udp
.hdr
.uih_dst_addr
),
1430 ntohs(udp
.hdr
.uih_dst_port
));
1431 dns_tell(0, &udp
.dns
, dlen
);
1434 /* Let a real name daemon handle the query. */
1435 udp
.dns
.hdr
.dh_id
= new_id(udp
.dns
.hdr
.dh_id
,
1436 udp
.hdr
.uih_src_port
, udp
.hdr
.uih_src_addr
);
1437 udp
.hdr
.uih_dst_addr
= current_named();
1438 udp
.hdr
.uih_dst_port
= named_port
;
1441 newjob(job_expect_named
, now
+ MEDIUM_TIMEOUT
, nil
);
1444 printf("To named %s:%u\n",
1445 inet_ntoa(current_named()), ntohs(named_port
));
1449 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1455 typedef struct data_cl
{ /* Data for connect or listen jobs. */
1456 int fd
; /* Open TCP channel. */
1457 int dn_fd
; /* TCP channel to the name daemon. */
1458 int retry
; /* Retrying a connect? */
1459 nwio_tcpcl_t tcpcl
; /* Flags. */
1462 typedef struct data_rw
{ /* Data for TCP read or write jobs. */
1463 int r_fd
; /* Read from this TCP channel. */
1464 int w_fd
; /* And write to this TCP channel. */
1465 struct data_rw
*rev
; /* Optional reverse TCP channel. */
1466 u8_t
*buf
; /* Buffer for bytes to transfer. */
1467 ssize_t offset
; /* Offset in buf to r/w at. */
1468 size_t size
; /* Size of buf. */
1471 static int job_setup_listen(void *data
, int expired
)
1472 /* Set up a listening channel for TCP DNS queries. */
1474 data_cl_t
*data_cl
= data
;
1475 nwio_tcpconf_t tcpconf
;
1476 nwio_tcpopt_t tcpopt
;
1479 if (!expired
) return 0;
1480 if (debug
>= 2) printf("%s: Setup listen\n", nowgmt());
1482 if (data_cl
== nil
) {
1483 if ((fd
= open(tcp_device
, O_RDWR
)) < 0) {
1484 if (errno
!= EMFILE
) report(tcp_device
);
1485 newjob(job_setup_listen
, now
+ SHORT_TIMEOUT
, nil
);
1489 tcpconf
.nwtc_flags
= NWTC_SHARED
| NWTC_LP_SET
| NWTC_UNSET_RA
1491 tcpconf
.nwtc_locport
= my_port
;
1492 if (ioctl(fd
, NWIOSTCPCONF
, &tcpconf
) == -1) fatal(tcp_device
);
1494 tcpopt
.nwto_flags
= NWTO_DEL_RST
;
1495 if (ioctl(fd
, NWIOSTCPOPT
, &tcpopt
) == -1) fatal(tcp_device
);
1497 data_cl
= allocate(nil
, sizeof(*data_cl
));
1499 data_cl
->tcpcl
.nwtcl_flags
= 0;
1502 newjob(job_listen
, NEVER
, data_cl
);
1506 static int job_listen(void *data
, int expired
)
1507 /* A connection on the TCP DNS query channel. */
1509 data_cl_t
*data_cl
= data
;
1511 /* Wait for a client. */
1512 if (asyn_ioctl(&asyn
, data_cl
->fd
, NWIOTCPLISTEN
, &data_cl
->tcpcl
) < 0) {
1513 if (errno
== EINPROGRESS
) return 0;
1516 /* Try again after a short time. */
1517 newjob(job_setup_listen
, now
+ SHORT_TIMEOUT
, data_cl
);
1520 if (debug
>= 2) printf("%s: Listen\n", nowgmt());
1522 /* Immediately resume listening. */
1523 newjob(job_setup_listen
, IMMEDIATE
, nil
);
1525 /* Set up a connect to the real name daemon. */
1527 newjob(job_setup_connect
, IMMEDIATE
, data_cl
);
1531 static void start_relay(int fd
, int dn_fd
)
1532 /* Start one or two read jobs after job_setup_connect() or job_connect(). */
1534 data_rw_t
*query
; /* Client to DNS daemon relay. */
1535 data_rw_t
*reply
; /* DNS daemon to client relay. */
1537 query
= allocate(nil
, sizeof(*query
));
1539 query
->buf
= allocate(nil
, sizeof(u16_t
));
1541 query
->size
= sizeof(u16_t
);
1542 if (dn_fd
== NO_FD
) {
1548 reply
= allocate(nil
, sizeof(*reply
));
1551 reply
->buf
= allocate(nil
, sizeof(u16_t
));
1553 reply
->size
= sizeof(u16_t
);
1557 newjob(job_read_reply
, now
+ LONG_TIMEOUT
, reply
);
1559 newjob(job_read_query
, now
+ LONG_TIMEOUT
, query
);
1562 static void close_relay(data_rw_t
*data_rw
)
1563 /* Close a relay channel. */
1565 if (data_rw
->rev
!= nil
) {
1566 /* Other end still active, signal EOF. */
1567 (void) ioctl(data_rw
->w_fd
, NWIOTCPSHUTDOWN
, nil
);
1568 data_rw
->rev
->rev
= nil
;
1570 /* Close both ends down. */
1571 asyn_close(&asyn
, data_rw
->r_fd
);
1572 close(data_rw
->r_fd
);
1573 if (data_rw
->w_fd
!= data_rw
->r_fd
) {
1574 asyn_close(&asyn
, data_rw
->w_fd
);
1575 close(data_rw
->w_fd
);
1578 deallocate(data_rw
->buf
);
1579 deallocate(data_rw
);
1582 static int job_setup_connect(void *data
, int expired
)
1583 /* Set up a connect for a TCP channel to the real name daemon. */
1585 nwio_tcpconf_t tcpconf
;
1587 data_cl_t
*data_cl
= data
;
1589 if (!expired
) return 0;
1590 if (debug
>= 2) printf("%s: Setup connect\n", nowgmt());
1592 if (n_nameds
== 0) {
1593 /* No name daemons to relay to, answer myself. */
1594 start_relay(data_cl
->fd
, NO_FD
);
1595 deallocate(data_cl
);
1599 if ((dn_fd
= open(tcp_device
, O_RDWR
)) < 0) {
1600 if (errno
!= EMFILE
) report(tcp_device
);
1601 if (++data_cl
->retry
< 5) {
1603 newjob(job_setup_connect
, now
+ SHORT_TIMEOUT
, data_cl
);
1605 /* Reply myself (bound to fail). */
1606 start_relay(data_cl
->fd
, NO_FD
);
1607 deallocate(data_cl
);
1612 tcpconf
.nwtc_flags
= NWTC_LP_SEL
| NWTC_SET_RA
| NWTC_SET_RP
;
1613 tcpconf
.nwtc_remaddr
= current_named();
1614 tcpconf
.nwtc_remport
= named_port
;
1615 if (ioctl(dn_fd
, NWIOSTCPCONF
, &tcpconf
) == -1) fatal(tcp_device
);
1618 data_cl
->dn_fd
= dn_fd
;
1619 data_cl
->tcpcl
.nwtcl_flags
= 0;
1620 newjob(job_connect
, NEVER
, data_cl
);
1624 static int job_connect(void *data
, int expired
)
1625 /* Connect to a TCP DNS query channel. */
1627 data_cl_t
*data_cl
= data
;
1629 /* Try to connect. */
1630 if (asyn_ioctl(&asyn
, data_cl
->dn_fd
, NWIOTCPCONN
, &data_cl
->tcpcl
) < 0) {
1631 if (errno
== EINPROGRESS
) return 0;
1632 if (errno
== EIO
) fatal(tcp_device
);
1634 /* Connection refused. */
1635 if (debug
>= 2) printf("%s: Connect: %s\n", nowgmt(), strerror(errno
));
1636 asyn_close(&asyn
, data_cl
->dn_fd
);
1637 close(data_cl
->dn_fd
);
1638 data_cl
->dn_fd
= NO_FD
;
1639 if (++data_cl
->retry
< 5) {
1640 /* Search a new name daemon. */
1643 force_expire(job_find_named
);
1645 newjob(job_setup_connect
, NEVER
, data_cl
);
1648 /* Reply with a failure eventually. */
1650 if (debug
>= 2) printf("%s: Connect\n", nowgmt());
1652 /* Read the query from the user, send on to the name daemon, etc. */
1653 start_relay(data_cl
->fd
, data_cl
->dn_fd
);
1654 deallocate(data_cl
);
1658 static void tcp_dns_tell(int fd
, u8_t
*buf
)
1659 /* Tell about a DNS packet on a TCP channel. */
1661 nwio_tcpconf_t tcpconf
;
1663 if (ioctl(fd
, NWIOGTCPCONF
, &tcpconf
) < 0) {
1664 printf("??\?:?? TCP ");
1666 printf("%s:%u TCP ", inet_ntoa(tcpconf
.nwtc_remaddr
),
1667 ntohs(tcpconf
.nwtc_remport
));
1669 dns_tell(0, oct2dns(buf
+ sizeof(u16_t
)), ntohs(upack16(buf
)));
1672 static int job_read_query(void *data
, int expired
)
1673 /* Read TCP queries from the client. */
1675 data_rw_t
*data_rw
= data
;
1678 /* Try to read count bytes. */
1679 count
= asyn_read(&asyn
, data_rw
->r_fd
,
1680 data_rw
->buf
+ data_rw
->offset
,
1681 data_rw
->size
- data_rw
->offset
);
1684 if (errno
== EINPROGRESS
&& !expired
) return 0;
1685 if (errno
== EIO
) fatal(tcp_device
);
1687 /* Remote end is late, or an error occurred. */
1689 printf("%s: TCP read query: %s\n", nowgmt(), strerror(errno
));
1691 close_relay(data_rw
);
1696 printf("%s: TCP read query, %d/%u bytes\n",
1697 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1701 close_relay(data_rw
);
1704 data_rw
->offset
+= count
;
1705 if (data_rw
->offset
== data_rw
->size
) {
1706 data_rw
->size
= sizeof(u16_t
) + ntohs(upack16(data_rw
->buf
));
1707 if (data_rw
->size
< sizeof(u16_t
)) {
1709 close_relay(data_rw
);
1712 if (data_rw
->offset
< data_rw
->size
) {
1713 /* Query not complete, read more. */
1714 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1715 newjob(job_read_query
, now
+ LONG_TIMEOUT
, data_rw
);
1720 if (data_rw
->size
< sizeof(u16_t
) + sizeof(dns_hdr_t
)) {
1721 close_relay(data_rw
);
1724 if (debug
>= 1) tcp_dns_tell(data_rw
->r_fd
, data_rw
->buf
);
1726 /* Relay or reply. */
1727 if (data_rw
->w_fd
!= data_rw
->r_fd
) {
1728 /* We have a real name daemon to do the work. */
1730 newjob(job_write_query
, now
+ LONG_TIMEOUT
, data_rw
);
1732 /* No real name daemons or none reachable, so use the hosts file. */
1736 if (data_rw
->size
< sizeof(u16_t
) + PACKETSZ
) {
1737 data_rw
->buf
= allocate(data_rw
->buf
, sizeof(u16_t
) + PACKETSZ
);
1740 /* Build a reply packet. */
1741 dp
= oct2dns(data_rw
->buf
+ sizeof(u16_t
));
1742 dlen
= data_rw
->size
- sizeof(u16_t
);
1743 if (!compose_reply(dp
, &dlen
)) {
1744 /* We're told to ask a name daemon, but that won't work. */
1745 close_relay(data_rw
);
1749 /* Start a reply write. */
1750 pack16(data_rw
->buf
, htons(dlen
));
1751 data_rw
->size
= sizeof(u16_t
) + dlen
;
1752 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1754 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1759 static int job_write_query(void *data
, int expired
)
1760 /* Relay a TCP query to the name daemon. */
1762 data_rw_t
*data_rw
= data
;
1765 /* Try to write count bytes to the name daemon. */
1766 count
= asyn_write(&asyn
, data_rw
->w_fd
,
1767 data_rw
->buf
+ data_rw
->offset
,
1768 data_rw
->size
- data_rw
->offset
);
1771 if (errno
== EINPROGRESS
&& !expired
) return 0;
1772 if (errno
== EIO
) fatal(tcp_device
);
1774 /* A write expired or failed (usually a broken connection.) */
1776 printf("%s: TCP write query: %s\n", nowgmt(), strerror(errno
));
1778 close_relay(data_rw
);
1783 printf("%s: TCP write query, %d/%u bytes\n",
1784 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1786 data_rw
->offset
+= count
;
1787 if (data_rw
->offset
< data_rw
->size
) {
1788 /* Partial write, continue. */
1789 newjob(job_write_query
, now
+ LONG_TIMEOUT
, data_rw
);
1792 if (debug
>= 1) tcp_dns_tell(data_rw
->w_fd
, data_rw
->buf
);
1794 /* Query fully send on, go read more queries. */
1796 data_rw
->size
= sizeof(u16_t
);
1797 newjob(job_read_query
, now
+ LONG_TIMEOUT
, data_rw
);
1801 static int job_read_reply(void *data
, int expired
)
1802 /* Read a TCP reply from the real name daemon. */
1804 data_rw_t
*data_rw
= data
;
1807 /* Try to read count bytes. */
1808 count
= asyn_read(&asyn
, data_rw
->r_fd
,
1809 data_rw
->buf
+ data_rw
->offset
,
1810 data_rw
->size
- data_rw
->offset
);
1813 if (errno
== EINPROGRESS
&& !expired
) return 0;
1814 if (errno
== EIO
) fatal(tcp_device
);
1816 /* Remote end is late, or an error occurred. */
1818 printf("%s: TCP read reply: %s\n", nowgmt(), strerror(errno
));
1820 close_relay(data_rw
);
1825 printf("%s: TCP read reply, %d/%u bytes\n",
1826 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1830 close_relay(data_rw
);
1833 data_rw
->offset
+= count
;
1834 if (data_rw
->offset
== data_rw
->size
) {
1835 data_rw
->size
= sizeof(u16_t
) + ntohs(upack16(data_rw
->buf
));
1836 if (data_rw
->size
< sizeof(u16_t
)) {
1838 close_relay(data_rw
);
1841 if (data_rw
->offset
< data_rw
->size
) {
1842 /* Reply not complete, read more. */
1843 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1844 newjob(job_read_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1848 if (debug
>= 1) tcp_dns_tell(data_rw
->r_fd
, data_rw
->buf
);
1850 /* Reply fully read, send it on. */
1852 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1856 static int job_write_reply(void *data
, int expired
)
1857 /* Send a TCP reply to the client. */
1859 data_rw_t
*data_rw
= data
;
1862 /* Try to write count bytes to the client. */
1863 count
= asyn_write(&asyn
, data_rw
->w_fd
,
1864 data_rw
->buf
+ data_rw
->offset
,
1865 data_rw
->size
- data_rw
->offset
);
1868 if (errno
== EINPROGRESS
&& !expired
) return 0;
1869 if (errno
== EIO
) fatal(tcp_device
);
1871 /* A write expired or failed (usually a broken connection.) */
1873 printf("%s: TCP write reply: %s\n", nowgmt(), strerror(errno
));
1875 close_relay(data_rw
);
1880 printf("%s: TCP write reply, %d/%u bytes\n",
1881 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1883 data_rw
->offset
+= count
;
1884 if (data_rw
->offset
< data_rw
->size
) {
1885 /* Partial write, continue. */
1886 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1889 if (debug
>= 1) tcp_dns_tell(data_rw
->w_fd
, data_rw
->buf
);
1891 /* Reply fully send on, go read more replies (or queries). */
1893 data_rw
->size
= sizeof(u16_t
);
1894 newjob(data_rw
->w_fd
!= data_rw
->r_fd
? job_read_reply
: job_read_query
,
1895 now
+ LONG_TIMEOUT
, data_rw
);
1900 static int job_dummy(void *data
, int expired
)
1904 #define job_setup_listen job_dummy
1905 #define job_setup_connect job_dummy
1906 #endif /* !DO_TCP */
1908 static void named_probe(ipaddr_t ip
)
1909 /* Send a probe to a name daemon, like 'host -r -t ns . <ip>'. */
1912 # define dlen (offsetof(dns_t, data) + 5)
1913 # define ulen (offsetof(udp_dns_t, dns) + dlen)
1915 /* Send a simple DNS query that all name servers can answer easily:
1916 * "What are the name servers for the root domain?"
1918 udp
.dns
.hdr
.dh_id
= new_id(ID_PROBE
, my_port
, ID_IPSELF
);
1919 udp
.dns
.hdr
.dh_flag1
= 0;
1920 udp
.dns
.hdr
.dh_flag2
= 0;
1921 udp
.dns
.hdr
.dh_qdcount
= HTONS(1);
1922 udp
.dns
.hdr
.dh_ancount
= HTONS(0);
1923 udp
.dns
.hdr
.dh_nscount
= HTONS(0);
1924 udp
.dns
.hdr
.dh_arcount
= HTONS(0);
1926 udp
.dns
.data
[0] = 0; /* Null name. */
1927 pack16(udp
.dns
.data
+1, HTONS(T_NS
));
1928 pack16(udp
.dns
.data
+3, HTONS(C_IN
));
1930 printf("PROBE %s ", inet_ntoa(ip
));
1931 dns_tell(0, &udp
.dns
, dlen
);
1934 udp
.hdr
.uih_dst_addr
= ip
;
1935 udp
.hdr
.uih_dst_port
= named_port
;
1936 udp
.hdr
.uih_ip_opt_len
= 0;
1937 udp
.hdr
.uih_data_len
= dlen
;
1939 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1944 static int job_find_named(void *data
, int expired
)
1945 /* Look for a real name daemon to answer real DNS queries. */
1947 if (!expired
) return 0;
1948 if (debug
>= 2) printf("%s: Find named\n", nowgmt());
1951 if (search_ct
< 0) {
1952 search_ct
= n_nameds
;
1956 if (--search_ct
< 0) {
1957 /* Forced end of search (named response!), or end of search with
1958 * nothing found. Search again after a long time.
1960 newjob(job_find_named
,
1961 (stale
> 0 || i_named
> 0) ? now
+ LONG_TIMEOUT
: NEVER
, nil
);
1962 force_expire(job_setup_connect
);
1966 /* Send a named probe. */
1967 i_named
= (i_named
+1) % n_nameds
;
1968 named_probe(current_named());
1970 /* Schedule the next call. */
1971 newjob(job_find_named
, now
+ SHORT_TIMEOUT
, nil
);
1975 static int job_expect_named(void *data
, int expired
)
1976 /* The real name server is expected to answer by now. */
1978 if (!expired
) return 0;
1979 if (debug
>= 2) printf("%s: Expect named\n", nowgmt());
1981 if (expecting() && !searching()) {
1982 /* No answer yet, start searching. */
1984 force_expire(job_find_named
);
1989 static void sig_handler(int sig
)
1990 /* A signal forces a search for a real name daemon, etc. */
1994 case SIGTERM
: done
= 1; break;
1995 case SIGHUP
: reinit
= 1; break;
1996 case SIGUSR1
: debug
++; break;
1997 case SIGUSR2
: debug
= 0; break;
2001 static void usage(void)
2003 fprintf(stderr
, "Usage: nonamed [-qs] [-d[level]] [-p port]\n");
2007 int main(int argc
, char **argv
)
2010 nwio_udpopt_t udpopt
;
2012 struct servent
*servent
;
2013 struct sigaction sa
;
2017 /* Debug output must be line buffered. */
2018 setvbuf(stdout
, nil
, _IOLBF
, 0);
2020 /* DNS service port number? */
2021 if ((servent
= getservbyname("domain", nil
)) == nil
) {
2022 fprintf(stderr
, "nonamed: \"domain\": unknown service\n");
2025 my_port
= servent
->s_port
;
2026 named_port
= servent
->s_port
;
2029 while (i
< argc
&& argv
[i
][0] == '-') {
2030 char *opt
= argv
[i
++] + 1, *end
;
2032 if (opt
[0] == '-' && opt
[1] == 0) break;
2035 case 'd': /* Debug level. */
2037 if (between('0', *opt
, '9')) debug
= strtoul(opt
, &opt
, 10);
2039 case 'p': /* Port to listen to (for testing.) */
2041 if (i
== argc
) usage();
2044 my_port
= htons(strtoul(opt
, &end
, 0));
2045 if (opt
== end
|| *end
!= 0) usage();
2051 case 'q': /* Quit after printing cache contents. */
2061 if (i
!= argc
) usage();
2064 /* Oops, just having a look at the cache. */
2072 /* Don't die on broken pipes, reinitialize on hangup, etc. */
2073 sa
.sa_handler
= SIG_IGN
;
2074 sigemptyset(&sa
.sa_mask
);
2076 sigaction(SIGPIPE
, &sa
, nil
);
2077 sa
.sa_handler
= sig_handler
;
2078 sigaction(SIGINT
, &sa
, nil
);
2079 sigaction(SIGHUP
, &sa
, nil
);
2080 sigaction(SIGUSR1
, &sa
, nil
);
2081 sigaction(SIGUSR2
, &sa
, nil
);
2082 sigaction(SIGTERM
, &sa
, nil
);
2084 /* TCP and UDP device names. */
2085 if ((tcp_device
= getenv("TCP_DEVICE")) == nil
) tcp_device
= TCP_DEVICE
;
2086 if ((udp_device
= getenv("UDP_DEVICE")) == nil
) udp_device
= UDP_DEVICE
;
2088 /* Open an UDP channel for incoming DNS queries. */
2089 if ((udp_fd
= open(udp_device
, O_RDWR
)) < 0) fatal(udp_device
);
2091 udpopt
.nwuo_flags
= NWUO_EXCL
| NWUO_LP_SET
| NWUO_EN_LOC
| NWUO_DI_BROAD
2092 | NWUO_RP_ANY
| NWUO_RA_ANY
| NWUO_RWDATALL
| NWUO_DI_IPOPT
;
2093 udpopt
.nwuo_locport
= my_port
;
2094 if (ioctl(udp_fd
, NWIOSUDPOPT
, &udpopt
) == -1
2095 || ioctl(udp_fd
, NWIOGUDPOPT
, &udpopt
) == -1
2100 /* The current time is... */
2103 /* Read configuration and data cached by the previous nonamed. */
2104 init_config(udpopt
.nwuo_locaddr
);
2108 /* Save process id. */
2109 if ((fp
= fopen(PIDFILE
, "w")) != nil
) {
2110 fprintf(fp
, "%u\n", (unsigned) getpid());
2115 /* Jobs that start the ball rolling. */
2116 newjob(job_read_udp
, NEVER
, nil
);
2117 newjob(job_setup_listen
, IMMEDIATE
, nil
);
2118 newjob(job_find_named
, IMMEDIATE
, nil
);
2121 openlog("nonamed", LOG_PID
, LOG_DAEMON
);
2124 /* There is always something in the queue. */
2125 assert(queue
!= nil
);
2127 /* Any expired jobs? */
2128 while (queue
->timeout
<= now
) {
2129 (void) execjob(queue
, 1);
2130 assert(queue
!= nil
);
2133 /* Check I/O jobs. */
2134 for (job
= queue
; job
!= nil
; job
= job
->next
) {
2135 if (execjob(job
, 0)) break;
2138 if (queue
->timeout
!= IMMEDIATE
) {
2139 struct timeval tv
, *tvp
;
2141 if (debug
>= 2) printf("%s: I/O wait", nowgmt());
2143 if (queue
->timeout
!= NEVER
) {
2144 tv
.tv_sec
= queue
->timeout
;
2147 if (debug
>= 2) printf(" (expires %s)\n", timegmt(tv
.tv_sec
));
2150 if (debug
>= 2) fputc('\n', stdout
);
2154 if (asyn_wait(&asyn
, 0, tvp
) < 0) {
2155 if (errno
!= EINTR
&& errno
!= EAGAIN
) fatal("fwait()");
2161 /* A hangup makes us go back to square one. */
2163 if (ioctl(udp_fd
, NWIOGUDPOPT
, &udpopt
) == -1) fatal(udp_device
);
2164 init_config(udpopt
.nwuo_locaddr
);
2166 force_expire(job_find_named
);
2170 (void) unlink(PIDFILE
);
2171 if (debug
>= 2) printf("sbrk(0) = %u\n", (unsigned) sbrk(0));