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>
29 #include <netinet/in.h>
30 #include <arpa/nameser.h>
32 #include <net/netlib.h>
33 #include <net/gen/in.h>
34 #include <net/gen/inet.h>
35 #include <arpa/nameser.h>
38 #include <net/gen/socket.h>
39 #include <net/gen/tcp.h>
40 #include <net/gen/tcp_io.h>
41 #include <net/gen/udp.h>
42 #include <net/gen/udp_hdr.h>
43 #include <net/gen/udp_io.h>
44 #include <net/gen/dhcp.h>
47 #include <minix/paths.h>
54 #define HTTL 3600L /* Default time to live for /etc/hosts data. */
55 #define SHORT_TIMEOUT 2 /* If you expect an answer soon. */
56 #define MEDIUM_TIMEOUT 4 /* Soon, but not that soon. */
57 #define LONG_TIMEOUT 300 /* For stream connections to a real named. */
58 #define N_IDS 256 /* Keep track of this many queries. */
59 #define N_DATAMAX (4096*sizeof(char *)) /* Default response cache size. */
60 #define N_NAMEDS 8 /* Max # name daemons we can keep track of. */
61 #define NO_FD (-1) /* No name daemon channel here. */
62 #define T_NXD ((u16_t) -1) /* A "type" signalling a nonexistent domain. */
64 /* Can't do async I/O under standard Minix, so forget about TCP. */
65 #define DO_TCP (__minix_vmd || !__minix)
67 /* Host data, file to store our process id in, our cache, DHCP's cache. */
68 static char HOSTS
[]= _PATH_HOSTS
;
69 static char PIDFILE
[]= "/usr/run/nonamed.pid";
70 static char NNCACHE
[]= "/usr/adm/nonamed.cache";
71 static char DHCPCACHE
[]= _PATH_DHCPCACHE
;
73 /* Magic string to head the cache file. */
74 static char MAGIC
[4]= "NND\2";
76 #define arraysize(a) (sizeof(a) / sizeof((a)[0]))
77 #define arraylimit(a) ((a) + arraysize(a))
78 #define between(a, c, z) ((unsigned) ((c) - (a)) <= (unsigned) ((z) - (a)))
80 /* The start of time and the far future. */
81 #define IMMEDIATE ((time_t) 0)
82 #define NEVER ((time_t) ((time_t) -1 < 0 ? LONG_MAX : ULONG_MAX))
84 static unsigned debug
; /* Debug level. */
85 static time_t now
; /* Current time. */
86 static u32_t stale
; /* Extension time for stale data. */
87 static u32_t httl
; /* TTL for /etc/hosts data. */
88 static int reinit
, done
; /* Reinit config / program is done. */
89 static int single
; /* Run single on a nondefault interface. */
90 static int localonly
; /* Only accept local queries. */
91 #define LOCALHOST 0x7F000001
93 static void report(const char *label
)
95 fprintf(stderr
, "nonamed: %s: %s\n", label
, strerror(errno
));
98 static void fatal(const char *label
)
101 if (debug
>= 3) { fflush(nil
); abort(); }
105 static void *allocate(void *mem
, size_t size
)
107 if ((mem
= realloc(mem
, size
)) == nil
) fatal("malloc()");
111 static void deallocate(void *mem
)
116 static char *timegmt(time_t t
)
117 /* Simple "time in seconds to GMT time today" converter. */
120 static char asctime
[sizeof("00:00:00")];
127 sprintf(asctime
, "%02u:%02u:%02u", h
, m
, s
);
131 static char *nowgmt(void)
136 #define PC(n) ((void) sizeof(char [sizeof(*(n)) == 1]), (char *) (n))
137 #define namecpy(n1, n2) strcpy(PC(n1), PC(n2))
138 #define namecat(n1, n2) strcat(PC(n1), PC(n2))
139 #define namechr(n, c) ((u8_t *) strchr(PC(n), (c)))
140 #define namecmp(n1, n2) strcasecmp(PC(n1), PC(n2))
141 #define namencmp(n1, n2, len) strncasecmp(PC(n1), PC(n2), len)
143 typedef struct dns
{ /* A DNS packet. */
144 HEADER hdr
; /* DNS header. */
145 u8_t data
[PACKETSZ
- sizeof(HEADER
)]; /* DNS data. */
148 /* Addres of DNS packet to octet address, or vv. */
149 #define dns2oct(dp) ((u8_t *) (dp))
150 #define oct2dns(dp) ((dns_t *) (dp))
152 typedef struct query
{ /* One cached answer to a query. */
153 struct query
*less
; /* Less recently used. */
154 struct query
*more
; /* More recently used. */
155 time_t age
; /* Time it was added. */
156 time_t stale
; /* Time it goes stale by TTL. */
157 u16_t usage
; /* Counts of queries answered. */
158 u8_t flags
; /* QF_REFRESH. */
159 size_t size
; /* Size of DNS packet. */
160 dns_t dns
; /* Answer to query as a DNS packet. */
163 #define QF_REFRESH 0x01 /* This stale data must be refreshed. */
164 #define QU_SHIFT 1 /* To shift usage by when evicting. */
166 /* Size of new query_t or existing query_t. */
167 #define query_allocsize(dnssize) (offsetof(query_t, dns) + (dnssize))
168 #define query_size(qp) query_allocsize((qp)->size)
170 static query_t
*mru
, *lru
; /* Most and least recently used answers. */
171 static int q_refresh
; /* Set when an entry needs refreshing. */
173 static void pack16(u8_t
*buf
, u16_t s
)
174 /* Pack a 16 bit value into a byte array. */
176 buf
[0]= ((u8_t
*) &s
)[0];
177 buf
[1]= ((u8_t
*) &s
)[1];
180 static void pack32(u8_t
*buf
, u32_t l
)
181 /* Pack a 32 bit value into a byte array. */
183 buf
[0]= ((u8_t
*) &l
)[0];
184 buf
[1]= ((u8_t
*) &l
)[1];
185 buf
[2]= ((u8_t
*) &l
)[2];
186 buf
[3]= ((u8_t
*) &l
)[3];
189 static u16_t
upack16(u8_t
*buf
)
190 /* Unpack a 16 bit value from a byte array. */
194 ((u8_t
*) &s
)[0]= buf
[0];
195 ((u8_t
*) &s
)[1]= buf
[1];
199 static u32_t
upack32(u8_t
*buf
)
200 /* Unpack a 32 bit value from a byte array. */
204 ((u8_t
*) &l
)[0]= buf
[0];
205 ((u8_t
*) &l
)[1]= buf
[1];
206 ((u8_t
*) &l
)[2]= buf
[2];
207 ((u8_t
*) &l
)[3]= buf
[3];
211 /* Encoding of RRs: i(paddr), d(omain), l(ong), c(har), s(tring), (s)h(ort). */
212 static char *encoding
[] = {
213 "c*", /* anything unknown is c* */
232 static char *itoa(char *fmt
, u32_t i
)
234 static char output
[32 + 3 * sizeof(i
)];
236 sprintf(output
, fmt
, (unsigned long) i
);
240 static char *classname(unsigned class)
241 /* Class name of a resource record, for debug purposes. */
243 static char *classes
[] = { "IN", "CS", "CHAOS", "HS" };
245 if ((class - C_IN
) < arraysize(classes
)) return classes
[class - C_IN
];
246 return itoa("C_%u", class);
249 static char *typename(unsigned type
)
250 /* Type name of a resource record, for debug purposes. */
252 static char type_A
[][6] = {
253 "A", "NS", "MD", "MF", "CNAME", "SOA", "MB", "MG", "MR", "NULL",
254 "WKS", "PTR", "HINFO", "MINFO", "MX", "TXT",
256 static char type_AXFR
[][6] = {
257 "AXFR", "MAILB", "MAILA", "ANY",
259 if ((type
- T_A
) < arraysize(type_A
)) return type_A
[type
- T_A
];
260 if ((type
- T_AXFR
) < arraysize(type_AXFR
)) return type_AXFR
[type
- T_AXFR
];
261 return itoa("T_%u", type
);
264 static int print_qrr(dns_t
*dp
, size_t size
, u8_t
*cp0
, int q
)
265 /* Print a query (q) or resource record (!q) from 'cp0' in a DNS packet for
266 * debug purposes. Return number of bytes skipped or -1 on error.
269 u8_t name
[MAXDNAME
+1];
273 u16_t type
, class, rdlength
;
278 dlim
= dns2oct(dp
) + size
;
279 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
280 if (r
== -1) return -1;
282 if (cp
+ 2 * sizeof(u16_t
) > dlim
) return -1;
283 type
= ntohs(upack16(cp
));
285 class= ntohs(upack16(cp
));
287 printf("%-25s", (char *) name
);
289 /* We're just printing a query segment, stop right here. */
290 printf(" %8s", classname(class));
291 printf(" %-5s", typename(type
));
294 if (cp
+ sizeof(u32_t
) + sizeof(u16_t
) > dlim
) return -1;
295 ttl
= ntohl(upack32(cp
));
297 rdlength
= ntohs(upack16(cp
));
299 if (cp
+ rdlength
> dlim
) return -1;
300 rlim
= cp
+ rdlength
;
301 printf(" %5lu", (unsigned long) ttl
);
302 printf(" %s", classname(class));
303 printf(" %-5s", typename(type
));
304 ep
= type
< arraysize(encoding
) ? encoding
[type
] : encoding
[0];
308 if (cp
+ sizeof(u32_t
) > rlim
) return -1;
309 printf(" %s", inet_ntoa(upack32(cp
)));
313 if (cp
+ sizeof(u32_t
) > rlim
) return -1;
314 printf(" %ld", (long)(i32_t
) ntohl(upack32(cp
)));
318 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
319 if (r
== -1) return -1;
320 printf(" %s", (char *) name
);
324 if (cp
>= rlim
) return -1;
325 printf(" %02X", *cp
++);
329 if (cp
+ r
> rlim
) return -1;
330 printf(" \"%.*s\"", *cp
, (char *) (cp
+ 1));
334 if (cp
+ sizeof(u16_t
) > rlim
) return -1;
335 printf(" %u", ntohs(upack16(cp
)));
339 if (*ep
== '*') ep
= cp
< rlim
? ep
-1 : ep
+1;
344 static void dns_tell(int indent
, dns_t
*dp
, size_t size
)
345 /* Explain a DNS packet, for debug purposes. */
350 static char label
[4][4]= { "QD:", "AN:", "NS:", "AR:" };
351 static char rcodes
[][9] = {
352 "NOERROR", "FORMERR", "SERVFAIL", "NXDOMAIN", "NOTIMP", "REFUSED"
355 if (size
< sizeof(HEADER
)) return;
357 printf("%*s", indent
, "");
358 printf("DNS %s:", (dp
->hdr
.qr
) ? "reply" : "query");
360 printf(" %s", r
< arraysize(rcodes
) ? rcodes
[r
] : itoa("ERR_%lu", r
));
361 if (dp
->hdr
.aa
) printf(" AA");
362 if (dp
->hdr
.tc
) printf(" TC");
363 if (dp
->hdr
.rd
) printf(" RD");
364 if (dp
->hdr
.ra
) printf(" RA");
365 if (dp
->hdr
.ad
) printf(" AD");
366 if (dp
->hdr
.cd
) printf(" CD");
369 count
[0]= ntohs(dp
->hdr
.qdcount
);
370 count
[1]= ntohs(dp
->hdr
.ancount
);
371 count
[2]= ntohs(dp
->hdr
.nscount
);
372 count
[3]= ntohs(dp
->hdr
.arcount
);
374 for (i
= 0; i
< 4; i
++) {
375 while (count
[i
] > 0) {
376 printf("%*s", indent
, "");
377 printf(" %s ", label
[i
]);
378 r
= print_qrr(dp
, size
, cp
, (i
== 0));
387 static u32_t
dns_ttl(dns_t
*dp
, size_t size
, u32_t delta
)
388 /* Compute the minimum TTL of all RRs in a DNS packet and subtract delta from
389 * all TTLs. (We are actually only interested in the minimum (delta = 0) or
390 * the subtraction (delta > 0). It was easier to roll this into one routine.)
393 u8_t
*cp
, *rdp
, *dlim
;
394 int r
, i
, hasttl
, hassoa
;
395 unsigned type
, count
[4];
396 u32_t ttl
, minimum
, minttl
;
398 u8_t name
[MAXDNAME
+1];
401 minttl
= 365*24*3600L;
402 dlim
= dns2oct(dp
) + size
;
403 if (size
< sizeof(HEADER
)) return 0;
405 rcode
= dp
->hdr
.rcode
;
406 count
[0]= ntohs(dp
->hdr
.qdcount
);
407 count
[1]= ntohs(dp
->hdr
.ancount
);
408 count
[2]= ntohs(dp
->hdr
.nscount
);
409 count
[3]= ntohs(dp
->hdr
.arcount
);
411 for (i
= 0; i
< 4 && cp
< dlim
; i
++) {
412 while (count
[i
] > 0) {
413 r
= dn_expand(dns2oct(dp
), dlim
, cp
, name
, MAXDNAME
);
415 cp
+= r
+ 2 * sizeof(u16_t
);
417 if (cp
+ sizeof(u32_t
) + sizeof(u16_t
) > dlim
) break;
418 type
= upack16(cp
- 2 * sizeof(u16_t
));
419 ttl
= ntohl(upack32(cp
));
420 ttl
= ttl
< delta
? 0 : ttl
- delta
;
421 if (rcode
== NXDOMAIN
&& i
== 2 && type
== HTONS(T_SOA
)) {
422 rdp
= cp
+ sizeof(u32_t
) + sizeof(u16_t
);
423 r
= dn_expand(dns2oct(dp
), dlim
, rdp
, name
, MAXDNAME
);
426 r
= dn_expand(dns2oct(dp
), dlim
, rdp
, name
, MAXDNAME
);
428 rdp
+= r
+ 4 * sizeof(u32_t
);
429 if (rdp
+ sizeof(u32_t
) > dlim
) break;
430 minimum
= ntohl(upack32(rdp
));
431 if (ttl
> minimum
) ttl
= minimum
;
434 if (delta
!= 0) pack32(cp
, htonl(ttl
));
435 if (ttl
< minttl
) minttl
= ttl
;
438 cp
+= sizeof(u16_t
) + ntohs(upack16(cp
));
443 return ((rcode
== NOERROR
&& hasttl
) || (rcode
== NXDOMAIN
&& hassoa
))
447 /* Total cached query data. */
448 static size_t n_datamax
= N_DATAMAX
;
449 static size_t n_data
;
451 static query_t
*extract_query(query_t
*qp
)
452 /* Take a query out of the query cache. */
455 *(qp
->less
!= nil
? &qp
->less
->more
: &lru
) = qp
->more
;
456 *(qp
->more
!= nil
? &qp
->more
->less
: &mru
) = qp
->less
;
457 n_data
-= query_size(qp
);
461 static query_t
*get_query(u8_t
*name
, unsigned type
)
462 /* Find a query and if so remove it from the cache and return it. */
465 u8_t qname
[MAXDNAME
+1];
468 for (qp
= mru
; qp
!= nil
; qp
= less
) {
470 if (qp
->stale
<= now
- stale
) {
471 /* This answer has expired. */
472 deallocate(extract_query(qp
));
474 r
= dn_expand(dns2oct(&qp
->dns
), dns2oct(&qp
->dns
) + qp
->size
,
475 qp
->dns
.data
, qname
, MAXDNAME
);
476 if (r
== -1) continue;
477 if (namecmp(qname
, name
) == 0 && upack16(qp
->dns
.data
+r
) == type
) {
478 /* Found an answer to the query. */
479 return extract_query(qp
);
486 static void insert_query(query_t
*qp
)
487 /* (Re)insert a query into the cache. */
489 *(qp
->less
!= nil
? &qp
->less
->more
: &lru
) = qp
;
490 *(qp
->more
!= nil
? &qp
->more
->less
: &mru
) = qp
;
491 n_data
+= query_size(qp
);
493 /* Try to delete the LRU while there is too much memory in use. If
494 * its usage count is too high then it gets a second chance.
496 while (n_data
> n_datamax
&& lru
!= nil
) {
497 if ((lru
->usage
>>= QU_SHIFT
) == 0 || lru
->stale
<= now
- stale
) {
498 deallocate(extract_query(lru
));
500 lru
->less
= mru
; /* Make list circular. */
502 mru
= lru
; /* Move one over, making LRU the MRU. */
504 lru
->less
= nil
; /* Break the circle. */
511 for (qp
= mru
; qp
!= nil
; qp
= qp
->less
) n
++;
512 printf("%u cached repl%s, %u bytes, sbrk(0) = %u\n",
513 n
, n
== 1 ? "y" : "ies",
519 static void put_query(query_t
*qp
)
520 /* Add a new query to the cache as the MRU. */
527 static void cache2file(void)
528 /* Store the cached data into the cache file. */
534 char newcache
[sizeof(NNCACHE
) + sizeof(".new")];
538 strcpy(newcache
, NNCACHE
);
539 strcat(newcache
, ".new");
541 if ((fp
= fopen(newcache
, "w")) == nil
) {
542 if ((errno
!= ENOENT
&& errno
!= EROFS
) || debug
>= 2) report(newcache
);
545 if (debug
>= 2) printf("Writing %s:\n", newcache
);
548 fwrite(MAGIC
, 1, sizeof(MAGIC
), fp
);
550 for (qp
= lru
; qp
!= nil
; qp
= qp
->more
) {
551 if (qp
->stale
<= now
- stale
) continue;
553 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
554 qp
->usage
, (long) (now
- qp
->age
), qp
->flags
);
555 dns_tell(2, &qp
->dns
, qp
->size
);
557 pack32(data
+0, htonl(qp
->age
));
559 pack16(data
+5, htons(qp
->size
));
560 pack16(data
+7, htons(qp
->usage
));
561 fwrite(data
, 1, sizeof(data
), fp
);
562 fwrite(&qp
->dns
, 1, qp
->size
, fp
);
563 if (ferror(fp
)) break;
566 if (ferror(fp
) || fclose(fp
) == EOF
) {
568 (void) unlink(newcache
);
572 if (debug
>= 2) printf("mv %s %s\n", newcache
, NNCACHE
);
573 if (rename(newcache
, NNCACHE
) < 0) {
574 fprintf(stderr
, "nonamed: mv %s %s: %s\n",
575 newcache
, NNCACHE
, strerror(errno
));
576 (void) unlink(newcache
);
580 static void file2cache(void)
581 /* Read cached data from the cache file. */
590 if ((fp
= fopen(NNCACHE
, "r")) == nil
) {
591 if (errno
!= ENOENT
|| debug
>= 2) report(NNCACHE
);
594 if (debug
>= 2) printf("Reading %s:\n", NNCACHE
);
597 fread(data
, 1, sizeof(MAGIC
), fp
);
598 if (ferror(fp
) || memcmp(MAGIC
, data
, sizeof(MAGIC
)) != 0) goto err
;
601 fread(data
, 1, sizeof(data
), fp
);
602 if (feof(fp
) || ferror(fp
)) break;
603 dlen
= ntohs(upack16(data
+5));
604 qp
= allocate(nil
, query_allocsize(dlen
));
605 qp
->age
= htonl(upack32(data
+0));
607 if (qp
->flags
& QF_REFRESH
) q_refresh
= 1;
609 qp
->usage
= htons(upack16(data
+7));
610 fread(&qp
->dns
, 1, qp
->size
, fp
);
611 if (feof(fp
) || ferror(fp
)) {
615 qp
->stale
= qp
->age
+ dns_ttl(&qp
->dns
, dlen
, 0);
617 printf("Usage = %u, Age = %ld, Flags = %02X:\n",
618 qp
->usage
, (long) (now
- qp
->age
), qp
->flags
);
619 dns_tell(2, &qp
->dns
, dlen
);
625 /* The cache file did not end at EOF or is otherwise a mess. */
626 fprintf(stderr
, "nonamed: %s: %s\n", NNCACHE
,
627 ferror(fp
) ? strerror(errno
) : "Corrupt");
628 while (lru
!= nil
) deallocate(extract_query(lru
));
633 typedef int handler_t(void *data
, int expired
);
635 /* All actions are in the form of "jobs". */
637 struct job
*next
, **prev
; /* To make a job queue. */
638 handler_t
*handler
; /* Function to handle this job. */
639 time_t timeout
; /* Moment it times out. */
640 void *data
; /* Data associated with the job. */
643 static job_t
*queue
; /* Main job queue. */
645 static void newjob(handler_t
*handler
, time_t timeout
, void *data
)
646 /* Create a new job with the given handler, timeout time and data. */
650 job
= allocate(nil
, sizeof(*job
));
651 job
->handler
= handler
;
652 job
->timeout
= timeout
;
655 for (prev
= &queue
; *prev
!= nil
; prev
= &(*prev
)->next
) {
656 if (job
->timeout
< (*prev
)->timeout
) break;
661 if (job
->next
!= nil
) job
->next
->prev
= &job
->next
;
664 static int execjob(job_t
*job
, int expired
)
665 /* Execute a job by calling the handler. Remove the job if it returns true,
666 * indicating that it is done. Expired is set if the job timed out. It is
667 * otherwise called to check for I/O.
670 if ((*job
->handler
)(job
->data
, expired
)) {
671 *job
->prev
= job
->next
;
672 if (job
->next
!= nil
) job
->next
->prev
= job
->prev
;
679 static void force_expire(handler_t
*handler
)
680 /* Force jobs to expire immediately, the named searcher for instance. */
682 job_t
*job
, **prev
= &queue
;
684 while ((job
= *prev
) != nil
) {
685 if (job
->handler
== handler
&& job
->timeout
!= IMMEDIATE
) {
687 if (job
->next
!= nil
) job
->next
->prev
= prev
;
688 newjob(job
->handler
, IMMEDIATE
, job
->data
);
696 static int nxdomain(u8_t
*name
)
697 /* True iff the two top level components in a name are repeated in the name,
698 * or if in-addr.arpa is found within a name. Such things happen often in a
699 * search for an already fully qualified local name. For instance:
700 * flotsam.cs.vu.nl.cs.vu.nl. (We don't want this at boot time.)
706 end
= namechr(name
, 0);
708 while (top
> name
&& *--top
!= '.') {}
709 while (top
> name
&& *--top
!= '.') {}
713 if (p
== name
) return 0;
715 if (namencmp(p
, top
, n
) == 0 && p
[n
] == '.') return 1;
716 if (namencmp(p
, ".in-addr.arpa.", 14) == 0) return 1;
721 typedef struct id2id
{
722 u16_t id
; /* ID of old query. */
723 u16_t port
; /* Reply port. */
724 ipaddr_t ip
; /* Reply address. */
727 static id2id_t id2id
[N_IDS
];
728 static u16_t id_counter
;
730 static u16_t
new_id(u16_t in_id
, u16_t in_port
, ipaddr_t in_ip
)
731 /* An incoming UDP query must be relabeled with a new ID before it can be
732 * send on to a real name daemon.
739 idp
= &id2id
[id
% N_IDS
];
746 static int old_id(u16_t id
, u16_t
*out_id
, u16_t
*out_port
, ipaddr_t
*out_ip
)
747 /* Translate a reply id back to the id, port, and address used in the query.
748 * Return true if the translation is possible.
752 if ((u16_t
) (id_counter
- id
) > N_IDS
) {
756 /* We know this one. */
757 id2id_t
*idp
= &id2id
[id
% N_IDS
];
759 if (idp
->port
== 0) return 0; /* Named is trying to fool us? */
761 *out_port
= idp
->port
;
768 /* IDs used to mark my own queries to name servers, must be new_id translated
769 * to make them unique "on the wire".
771 #define ID_IPSELF HTONL(0) /* "I did it myself" address. */
772 #define ID_PROBE HTONS(0) /* Name server probe. */
773 #define ID_REFRESH HTONS(1) /* Query to refresh a cache entry. */
775 static char *tcp_device
, *udp_device
; /* TCP and UDP device names. */
776 static int udp_fd
; /* To send or receive UDP packets. */
777 static asynchio_t asyn
; /* For I/O in progress. */
778 static ipaddr_t my_ip
; /* My IP address. */
779 static u16_t my_port
, named_port
; /* Port numbers, normally "domain". */
781 static ipaddr_t named
[N_NAMEDS
]; /* Addresses of all name servers. */
782 static unsigned n_nameds
; /* Number of configured name daemons. */
783 static unsigned i_named
; /* Index to current name server. */
784 static int expect
; /* Set when we expect an answer. */
785 static int search_ct
= -1; /* Named search count and state. */
786 static int dirty
; /* True when new entry put in cache. */
788 #define current_named() (+named[i_named])
789 #define searching() (search_ct > 0)
790 #define start_searching() ((void) (search_ct= -1))
791 #define stop_searching() ((void) (search_ct= 0))
792 #define expecting() (+expect)
793 #define start_expecting() ((void) (expect= 1))
794 #define stop_expecting() ((void) (expect= 0))
796 static time_t filetime(const char *file
)
797 /* Get the modified time of a file. */
801 return stat(file
, &st
) == 0 ? st
.st_mtime
: 0;
804 static void init_config(ipaddr_t ifip
)
805 /* Read name daemon list and other special stuff from the hosts file. */
809 static time_t hosts_time
, dhcp_time
;
812 /* See if anything really changed. */
813 if (((ifip
^ HTONL(LOCALHOST
)) & HTONL(0xFF000000)) == 0) ifip
= my_ip
;
815 dt
= filetime(DHCPCACHE
);
816 if (ifip
== my_ip
&& ht
== hosts_time
&& dt
== dhcp_time
) return;
822 printf("%s: I am nonamed %s at %s:%u\n",
823 nowgmt(), version
, inet_ntoa(my_ip
), ntohs(my_port
));
832 while ((he
= gethostent()) != nil
) {
833 memcpy(&nip
, he
->h_addr
, sizeof(u32_t
));
835 if (namecmp(he
->h_name
, "%ttl") == 0) httl
= nip
;
836 if (namecmp(he
->h_name
, "%stale") == 0) stale
= hip
;
837 if (namecmp(he
->h_name
, "%memory") == 0) n_datamax
= hip
;
838 if (namecmp(he
->h_name
, "%nameserver") == 0) {
839 if (nip
!= my_ip
|| named_port
!= my_port
) {
840 if (n_nameds
< N_NAMEDS
) named
[n_nameds
++]= nip
;
848 /* No name daemons found in the host file. What about DHCP? */
855 if ((fd
= open(DHCPCACHE
, O_RDONLY
)) < 0) {
856 if (errno
!= ENOENT
) fatal(DHCPCACHE
);
858 while ((r
= read(fd
, &d
, sizeof(d
))) == sizeof(d
)) {
859 if (d
.yiaddr
== my_ip
) break;
861 if (r
< 0) fatal(DHCPCACHE
);
864 if (r
== sizeof(d
) && dhcp_gettag(&d
, DHCP_TAG_DNS
, &data
, &len
)) {
865 while (len
>= sizeof(nip
)) {
866 memcpy(&nip
, data
, sizeof(nip
));
869 if (nip
!= my_ip
|| named_port
!= my_port
) {
870 if (n_nameds
< N_NAMEDS
) named
[n_nameds
++]= nip
;
879 static handler_t job_save_cache
, job_read_udp
, job_find_named
, job_expect_named
;
881 static handler_t job_setup_listen
, job_listen
, job_setup_connect
, job_connect
;
882 static handler_t job_read_query
, job_write_query
;
883 static handler_t job_read_reply
, job_write_reply
;
886 static int query_hosts(u8_t
*qname
, unsigned type
, dns_t
*dp
, size_t *pdlen
)
887 /* Read the /etc/hosts file to try and answer an A or PTR query. Return
888 * true iff an answer can be found, with the answer copied to *dp.
896 u8_t name
[MAXDNAME
+1];
899 struct hostent localhost
;
900 static char *noaliases
[]= { nil
};
901 static ipaddr_t localaddr
;
902 static char *localaddrlist
[]= { (char *) &localaddr
, nil
};
904 localaddr
= HTONL(LOCALHOST
);
906 if (single
) return 0;
908 /* Assume we can answer. */
919 dns
.hdr
.qdcount
= HTONS(1);
921 dns
.hdr
.nscount
= HTONS(0);
922 dns
.hdr
.arcount
= HTONS(0);
924 dnvec
[0]= dns2oct(&dns
);
927 r
= dn_comp(qname
, cp
, arraysize(dns
.data
), dnvec
, arraylimit(dnvec
));
928 if (r
== -1) return 0;
932 pack16(cp
, HTONS(C_IN
));
935 /* Localhost is fixed to 127.0.0.1. */
937 namencmp(qname
, "localhost.", 10) == 0 ? (char *) qname
: "localhost";
938 localhost
.h_aliases
= noaliases
;
939 localhost
.h_addr_list
= localaddrlist
;
944 int type_host
= NTOHS(type
);
947 if (namecmp(qname
, he
->h_name
) == 0) {
949 r
= dn_comp((u8_t
*) he
->h_name
, cp
, arraylimit(dns
.data
) - cp
,
950 dnvec
, arraylimit(dnvec
));
951 if (r
== -1) return 0;
953 if (cp
+ 3 * sizeof(u16_t
) + 2 * sizeof(u32_t
)
954 > arraylimit(dns
.data
)) { r
= -1; break; }
955 pack16(cp
, HTONS(T_A
));
957 pack16(cp
, HTONS(C_IN
));
961 pack16(cp
, HTONS(sizeof(u32_t
)));
963 memcpy(cp
, he
->h_addr
, sizeof(u32_t
));
970 domain
= namechr(he
->h_name
, '.');
971 for (i
= 0; he
->h_aliases
[i
] != nil
; i
++) {
972 namecpy(name
, he
->h_aliases
[i
]);
973 if (domain
!= nil
&& namechr(name
, '.') == nil
) {
974 namecat(name
, domain
);
976 if (namecmp(qname
, name
) == 0) {
977 r
= dn_comp(name
, cp
, arraylimit(dns
.data
) - cp
,
978 dnvec
, arraylimit(dnvec
));
981 if (cp
+ 3 * sizeof(u16_t
)
982 + 1 * sizeof(u32_t
) > arraylimit(dns
.data
)) return 0;
983 pack16(cp
, HTONS(T_CNAME
));
985 pack16(cp
, HTONS(C_IN
));
989 /* pack16(cp, htonl(RDLENGTH)) */
991 r
= dn_comp((u8_t
*) he
->h_name
, cp
,
992 arraylimit(dns
.data
) - cp
,
993 dnvec
, arraylimit(dnvec
));
995 pack16(cp
- sizeof(u16_t
), htons(r
));
998 if (type
== HTONS(T_A
)) goto addA
; /* really wants A */
1004 if (ancount
> 0) break;
1005 if (he
->h_name
[0] == '%') break;
1006 sprintf((char *) name
, "%d.%d.%d.%d.in-addr.arpa",
1007 ((u8_t
*) he
->h_addr
)[3],
1008 ((u8_t
*) he
->h_addr
)[2],
1009 ((u8_t
*) he
->h_addr
)[1],
1010 ((u8_t
*) he
->h_addr
)[0]);
1011 if (namecmp(qname
, name
) == 0) {
1012 r
= dn_comp(name
, cp
, arraylimit(dns
.data
) - cp
,
1013 dnvec
, arraylimit(dnvec
));
1016 if (cp
+ 3 * sizeof(u16_t
) + 1 * sizeof(u32_t
)
1017 > arraylimit(dns
.data
)) { r
= -1; break; }
1018 pack16(cp
, HTONS(T_PTR
));
1019 cp
+= sizeof(u16_t
);
1020 pack16(cp
, HTONS(C_IN
));
1021 cp
+= sizeof(u16_t
);
1023 cp
+= sizeof(u32_t
);
1024 /* pack16(cp, htonl(RDLENGTH)) */
1025 cp
+= sizeof(u16_t
);
1026 r
= dn_comp((u8_t
*) he
->h_name
, cp
,
1027 arraylimit(dns
.data
) - cp
, dnvec
, arraylimit(dnvec
));
1028 if (r
== -1) return 0;
1029 pack16(cp
- sizeof(u16_t
), htons(r
));
1035 } while (r
!= -1 && (he
= gethostent()) != nil
);
1038 if (r
== -1 || ancount
== 0) return 0;
1040 dns
.hdr
.ancount
= htons(ancount
);
1041 memcpy(dp
, &dns
, *pdlen
= cp
- dns2oct(&dns
));
1045 static int query_chaos(u8_t
*qname
, unsigned type
, dns_t
*dp
, size_t *pdlen
)
1046 /* Report my version. Can't let BIND take all the credit. :-) */
1053 if (type
!= HTONS(T_TXT
) || namecmp(qname
, "version.bind") != 0) return 0;
1065 dns
.hdr
.qdcount
= HTONS(1);
1066 dns
.hdr
.ancount
= HTONS(1);
1067 dns
.hdr
.nscount
= HTONS(0);
1068 dns
.hdr
.arcount
= htons(n_nameds
);
1070 dnvec
[0]= dns2oct(&dns
);
1073 r
= dn_comp(qname
, cp
, arraysize(dns
.data
), dnvec
, arraylimit(dnvec
));
1074 if (r
== -1) return 0;
1077 cp
+= sizeof(u16_t
);
1078 pack16(cp
, HTONS(C_CHAOS
));
1079 cp
+= sizeof(u16_t
);
1081 r
= dn_comp(qname
, cp
, arraylimit(dns
.data
) - cp
, dnvec
, arraylimit(dnvec
));
1082 if (r
== -1) return 0;
1084 pack16(cp
, HTONS(T_TXT
));
1085 cp
+= sizeof(u16_t
);
1086 pack16(cp
, HTONS(C_CHAOS
));
1087 cp
+= sizeof(u16_t
);
1088 pack32(cp
, HTONL(0));
1089 cp
+= sizeof(u32_t
);
1090 /* pack16(cp, htonl(RDLENGTH)) */
1091 cp
+= sizeof(u16_t
);
1092 sprintf((char *) cp
+ 1, "nonamed %s at %s:%u",
1093 version
, inet_ntoa(my_ip
), ntohs(my_port
));
1094 r
= strlen((char *) cp
+ 1) + 1;
1095 pack16(cp
- sizeof(u16_t
), htons(r
));
1098 for (n
= 0, i
= i_named
; n
< n_nameds
; n
++, i
= (i
+1) % n_nameds
) {
1099 r
= dn_comp((u8_t
*) "%nameserver", cp
, arraylimit(dns
.data
) - cp
,
1100 dnvec
, arraylimit(dnvec
));
1101 if (r
== -1) return 0;
1103 if (cp
+ 3 * sizeof(u16_t
)
1104 + 2 * sizeof(u32_t
) > arraylimit(dns
.data
)) return 0;
1105 pack16(cp
, HTONS(T_A
));
1106 cp
+= sizeof(u16_t
);
1107 pack16(cp
, HTONS(C_IN
));
1108 cp
+= sizeof(u16_t
);
1109 pack32(cp
, HTONL(0));
1110 cp
+= sizeof(u32_t
);
1111 pack16(cp
, HTONS(sizeof(u32_t
)));
1112 cp
+= sizeof(u16_t
);
1113 memcpy(cp
, &named
[i
], sizeof(u32_t
));
1114 cp
+= sizeof(u32_t
);
1117 memcpy(dp
, &dns
, *pdlen
= cp
- dns2oct(&dns
));
1121 static void cache_reply(dns_t
*dp
, size_t dlen
)
1122 /* Store a DNS packet in the cache. */
1125 query_t
*qp
, *less
, *more
;
1129 u8_t name
[MAXDNAME
];
1132 if ((dp
->hdr
.rd
&& !dp
->hdr
.tc
)) return;
1133 if (dp
->hdr
.qdcount
!= HTONS(1)) return;
1135 r
= dn_expand(dns2oct(dp
), dns2oct(dp
) + dlen
, cp
, name
, MAXDNAME
);
1136 if (r
== -1) return;
1139 cp
+= sizeof(u16_t
);
1140 if (upack16(cp
) != HTONS(C_IN
)) return;
1142 /* Delete old cached data, if any. Note where it is in the LRU. */
1143 if ((qp
= get_query(name
, type
)) != nil
) {
1149 /* Not yet in the cache. */
1155 /* Determine minimum TTL. Discard if zero, never cache zero TTLs. */
1156 if ((minttl
= dns_ttl(dp
, dlen
, 0)) == 0) return;
1158 /* Enter new reply in cache. */
1159 qp
= allocate(nil
, query_allocsize(dlen
));
1166 memcpy(&qp
->dns
, dp
, dlen
);
1167 qp
->stale
= qp
->age
+ minttl
;
1169 if (debug
>= 1) printf("Answer cached\n");
1171 /* Save the cache soon. */
1174 newjob(job_save_cache
, now
+ LONG_TIMEOUT
, nil
);
1178 static int job_save_cache(void *data
, int expired
)
1179 /* Some time after the cache is changed it is written back to disk. */
1181 if (!expired
) return 0;
1187 static int compose_reply(dns_t
*dp
, size_t *pdlen
)
1188 /* Try to compose a reply to a request in *dp using the hosts file or
1189 * cached data. Return answer in *dp with its size in *pdlen. Return true
1190 * iff an answer is given.
1193 size_t dlen
= *pdlen
;
1196 unsigned id
, type
, class;
1198 u8_t name
[MAXDNAME
];
1201 r
= dn_expand(dns2oct(dp
), dns2oct(dp
) + dlen
, cp
, name
, MAXDNAME
);
1204 if (cp
+ 2 * sizeof(u16_t
) > dns2oct(dp
) + dlen
) {
1208 cp
+= sizeof(u16_t
);
1210 cp
+= sizeof(u16_t
);
1214 /* Remember ID and RD. */
1219 /* Malformed query, reply "FORMERR". */
1225 dp
->hdr
.rcode
= FORMERR
;
1227 if (class == HTONS(C_IN
) && query_hosts(name
, type
, dp
, pdlen
)) {
1228 /* Answer to this query is in the hosts file. */
1231 if (class == HTONS(C_IN
) && (qp
= get_query(name
, type
)) != nil
) {
1232 /* Answer to this query is present in the cache. */
1233 memcpy(dp
, &qp
->dns
, dlen
= qp
->size
);
1235 (void) dns_ttl(dp
, dlen
, now
- qp
->age
);
1237 if (qp
->stale
<= now
) {
1238 qp
->flags
|= QF_REFRESH
;
1245 if (class == HTONS(C_CHAOS
) && query_chaos(name
, type
, dp
, pdlen
)) {
1246 /* Return our version numbers. */
1249 if (n_nameds
== 0 || nxdomain(name
)) {
1250 /* No real name daemon present, or this name has a repeated top level
1251 * domain sequence. Reply "no such domain".
1258 dp
->hdr
.rcode
= NXDOMAIN
;
1261 /* "Recursion Desired" is off, so don't bother to relay. */
1266 dp
->hdr
.rcode
= NOERROR
;
1268 /* Caller needs to consult with a real name daemon. */
1272 /* Copy ID and RD back to answer. */
1279 typedef struct udp_dns
{ /* One DNS packet over UDP. */
1280 udp_io_hdr_t hdr
; /* UDP header (source/destination). */
1281 dns_t dns
; /* DNS packet. */
1284 static void refresh_cache(void)
1285 /* Find a stale entry in the cache that was used to answer a query, and send
1286 * a request to a name server that should refresh this entry.
1294 u8_t qname
[MAXDNAME
+1];
1298 if (!q_refresh
) return;
1299 for (qp
= lru
; qp
!= nil
; qp
= qp
->more
) {
1300 if ((qp
->flags
& QF_REFRESH
) && qp
->stale
> now
- stale
) break;
1307 /* Found one to refresh. */
1308 qp
->flags
&= ~QF_REFRESH
;
1309 r
= dn_expand(dns2oct(&qp
->dns
), dns2oct(&qp
->dns
) + qp
->size
,
1310 qp
->dns
.data
, qname
, MAXDNAME
);
1311 if (r
== -1) return;
1312 type
= upack16(qp
->dns
.data
+r
);
1314 dnvec
[0]= dns2oct(&udp
.dns
);
1317 r
= dn_comp(qname
, cp
, arraysize(udp
.dns
.data
), dnvec
, arraylimit(dnvec
));
1318 if (r
== -1) return;
1321 cp
+= sizeof(u16_t
);
1322 pack16(cp
, HTONS(C_IN
));
1323 cp
+= sizeof(u16_t
);
1324 dlen
= cp
- dns2oct(&udp
.dns
);
1326 udp
.dns
.hdr
.id
= new_id(ID_REFRESH
, my_port
, ID_IPSELF
);
1328 udp
.dns
.hdr
.opcode
= 0;
1334 udp
.dns
.hdr
.unused
= 0;
1337 udp
.dns
.hdr
.rcode
= 0;
1338 udp
.dns
.hdr
.qdcount
= HTONS(1);
1339 udp
.dns
.hdr
.ancount
= HTONS(0);
1340 udp
.dns
.hdr
.nscount
= HTONS(0);
1341 udp
.dns
.hdr
.arcount
= HTONS(0);
1343 udp
.hdr
.uih_dst_addr
= current_named();
1344 udp
.hdr
.uih_dst_port
= named_port
;
1345 udp
.hdr
.uih_ip_opt_len
= 0;
1346 udp
.hdr
.uih_data_len
= dlen
;
1349 printf("Refresh to %s:%u:\n",
1350 inet_ntoa(current_named()), ntohs(named_port
));
1351 dns_tell(0, &udp
.dns
, dlen
);
1353 ulen
= offsetof(udp_dns_t
, dns
) + dlen
;
1354 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1357 static int job_read_udp(void *data
, int expired
)
1358 /* Read UDP queries and replies. */
1362 static udp_dns_t udp
;
1369 /* Try to read a packet. */
1370 ulen
= asyn_read(&asyn
, udp_fd
, &udp
, sizeof(udp
));
1371 dlen
= ulen
- offsetof(udp_dns_t
, dns
);
1374 if (errno
== EINPROGRESS
&& !expired
) return 0;
1375 if (errno
== EIO
) fatal(udp_device
);
1378 printf("%s: UDP read: %s\n", nowgmt(), strerror(errno
));
1382 printf("%s: UDP read, %d bytes\n", nowgmt(), (int) ulen
);
1386 /* Restart this job no matter what. */
1387 newjob(job_read_udp
, NEVER
, nil
);
1389 if (ulen
< (ssize_t
) (sizeof(udp_io_hdr_t
) + sizeof(HEADER
))) return 1;
1392 printf("%s:%u UDP ", inet_ntoa(udp
.hdr
.uih_src_addr
),
1393 ntohs(udp
.hdr
.uih_src_port
));
1394 dns_tell(0, &udp
.dns
, dlen
);
1397 /* Check, and if necessary reinitialize my configuration. */
1398 init_config(udp
.hdr
.uih_dst_addr
);
1400 if (udp
.dns
.hdr
.qr
) {
1401 /* This is a remote named reply, not a query. */
1403 /* Response to a query previously relayed? */
1404 if (!old_id(udp
.dns
.hdr
.id
, &id
, &port
, &ip
)) return 1;
1406 if (ip
== ID_IPSELF
&& id
== ID_PROBE
) {
1408 /* We have found a name server! */
1412 for (i
= 0; i
< n_nameds
; i
++) {
1413 if (named
[i
] == udp
.hdr
.uih_src_addr
) {
1416 printf("Current named = %s\n",
1417 inet_ntoa(current_named()));
1420 force_expire(job_find_named
);
1426 /* We got an answer, so stop worrying. */
1429 force_expire(job_expect_named
);
1432 /* Put the information in the cache. */
1433 cache_reply(&udp
.dns
, dlen
);
1435 /* Refresh a cached entry that was used when stale. */
1438 /* Discard reply to myself. */
1439 if (ip
== ID_IPSELF
) return 1;
1441 /* Send the reply to the process that asked for it. */
1443 udp
.hdr
.uih_dst_addr
= ip
;
1444 udp
.hdr
.uih_dst_port
= port
;
1445 if (debug
>= 1) printf("To client %s:%u\n", inet_ntoa(ip
), ntohs(port
));
1448 if (udp
.dns
.hdr
.qdcount
!= HTONS(1)) return 1;
1451 /* Check if it's a local query. */
1452 if(ntohl(udp
.hdr
.uih_src_addr
) != LOCALHOST
) {
1453 syslog(LOG_WARNING
, "nonamed: dropped query from %s",
1454 inet_ntoa(udp
.hdr
.uih_src_addr
));
1459 /* Try to compose a reply from local data. */
1460 if (compose_reply(&udp
.dns
, &dlen
)) {
1461 udp
.hdr
.uih_dst_addr
= udp
.hdr
.uih_src_addr
;
1462 udp
.hdr
.uih_dst_port
= udp
.hdr
.uih_src_port
;
1463 udp
.hdr
.uih_ip_opt_len
= 0;
1464 udp
.hdr
.uih_data_len
= dlen
;
1465 ulen
= offsetof(udp_dns_t
, dns
) + dlen
;
1467 /* Send an UDP DNS reply. */
1469 printf("%s:%u UDP ", inet_ntoa(udp
.hdr
.uih_dst_addr
),
1470 ntohs(udp
.hdr
.uih_dst_port
));
1471 dns_tell(0, &udp
.dns
, dlen
);
1474 /* Let a real name daemon handle the query. */
1475 udp
.dns
.hdr
.id
= new_id(udp
.dns
.hdr
.id
,
1476 udp
.hdr
.uih_src_port
, udp
.hdr
.uih_src_addr
);
1477 udp
.hdr
.uih_dst_addr
= current_named();
1478 udp
.hdr
.uih_dst_port
= named_port
;
1481 newjob(job_expect_named
, now
+ MEDIUM_TIMEOUT
, nil
);
1484 printf("To named %s:%u\n",
1485 inet_ntoa(current_named()), ntohs(named_port
));
1489 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1495 typedef struct data_cl
{ /* Data for connect or listen jobs. */
1496 int fd
; /* Open TCP channel. */
1497 int dn_fd
; /* TCP channel to the name daemon. */
1498 int retry
; /* Retrying a connect? */
1499 nwio_tcpcl_t tcpcl
; /* Flags. */
1502 typedef struct data_rw
{ /* Data for TCP read or write jobs. */
1503 int r_fd
; /* Read from this TCP channel. */
1504 int w_fd
; /* And write to this TCP channel. */
1505 struct data_rw
*rev
; /* Optional reverse TCP channel. */
1506 u8_t
*buf
; /* Buffer for bytes to transfer. */
1507 ssize_t offset
; /* Offset in buf to r/w at. */
1508 size_t size
; /* Size of buf. */
1511 static int job_setup_listen(void *data
, int expired
)
1512 /* Set up a listening channel for TCP DNS queries. */
1514 data_cl_t
*data_cl
= data
;
1515 nwio_tcpconf_t tcpconf
;
1516 nwio_tcpopt_t tcpopt
;
1519 if (!expired
) return 0;
1520 if (debug
>= 2) printf("%s: Setup listen\n", nowgmt());
1522 if (data_cl
== nil
) {
1523 if ((fd
= open(tcp_device
, O_RDWR
)) < 0) {
1524 if (errno
!= EMFILE
) report(tcp_device
);
1525 newjob(job_setup_listen
, now
+ SHORT_TIMEOUT
, nil
);
1529 tcpconf
.nwtc_flags
= NWTC_SHARED
| NWTC_LP_SET
| NWTC_UNSET_RA
1531 tcpconf
.nwtc_locport
= my_port
;
1532 if (ioctl(fd
, NWIOSTCPCONF
, &tcpconf
) == -1) fatal(tcp_device
);
1534 tcpopt
.nwto_flags
= NWTO_DEL_RST
;
1535 if (ioctl(fd
, NWIOSTCPOPT
, &tcpopt
) == -1) fatal(tcp_device
);
1537 data_cl
= allocate(nil
, sizeof(*data_cl
));
1539 data_cl
->tcpcl
.nwtcl_flags
= 0;
1542 newjob(job_listen
, NEVER
, data_cl
);
1546 static int job_listen(void *data
, int expired
)
1547 /* A connection on the TCP DNS query channel. */
1549 data_cl_t
*data_cl
= data
;
1551 /* Wait for a client. */
1552 if (asyn_ioctl(&asyn
, data_cl
->fd
, NWIOTCPLISTEN
, &data_cl
->tcpcl
) < 0) {
1553 if (errno
== EINPROGRESS
) return 0;
1556 /* Try again after a short time. */
1557 newjob(job_setup_listen
, now
+ SHORT_TIMEOUT
, data_cl
);
1560 if (debug
>= 2) printf("%s: Listen\n", nowgmt());
1562 /* Immediately resume listening. */
1563 newjob(job_setup_listen
, IMMEDIATE
, nil
);
1565 /* Set up a connect to the real name daemon. */
1567 newjob(job_setup_connect
, IMMEDIATE
, data_cl
);
1571 static void start_relay(int fd
, int dn_fd
)
1572 /* Start one or two read jobs after job_setup_connect() or job_connect(). */
1574 data_rw_t
*query
; /* Client to DNS daemon relay. */
1575 data_rw_t
*reply
; /* DNS daemon to client relay. */
1577 query
= allocate(nil
, sizeof(*query
));
1579 query
->buf
= allocate(nil
, sizeof(u16_t
));
1581 query
->size
= sizeof(u16_t
);
1582 if (dn_fd
== NO_FD
) {
1588 reply
= allocate(nil
, sizeof(*reply
));
1591 reply
->buf
= allocate(nil
, sizeof(u16_t
));
1593 reply
->size
= sizeof(u16_t
);
1597 newjob(job_read_reply
, now
+ LONG_TIMEOUT
, reply
);
1599 newjob(job_read_query
, now
+ LONG_TIMEOUT
, query
);
1602 static void close_relay(data_rw_t
*data_rw
)
1603 /* Close a relay channel. */
1605 if (data_rw
->rev
!= nil
) {
1606 /* Other end still active, signal EOF. */
1607 (void) ioctl(data_rw
->w_fd
, NWIOTCPSHUTDOWN
, nil
);
1608 data_rw
->rev
->rev
= nil
;
1610 /* Close both ends down. */
1611 asyn_close(&asyn
, data_rw
->r_fd
);
1612 close(data_rw
->r_fd
);
1613 if (data_rw
->w_fd
!= data_rw
->r_fd
) {
1614 asyn_close(&asyn
, data_rw
->w_fd
);
1615 close(data_rw
->w_fd
);
1618 deallocate(data_rw
->buf
);
1619 deallocate(data_rw
);
1622 static int job_setup_connect(void *data
, int expired
)
1623 /* Set up a connect for a TCP channel to the real name daemon. */
1625 nwio_tcpconf_t tcpconf
;
1627 data_cl_t
*data_cl
= data
;
1629 if (!expired
) return 0;
1630 if (debug
>= 2) printf("%s: Setup connect\n", nowgmt());
1632 if (n_nameds
== 0) {
1633 /* No name daemons to relay to, answer myself. */
1634 start_relay(data_cl
->fd
, NO_FD
);
1635 deallocate(data_cl
);
1639 if ((dn_fd
= open(tcp_device
, O_RDWR
)) < 0) {
1640 if (errno
!= EMFILE
) report(tcp_device
);
1641 if (++data_cl
->retry
< 5) {
1643 newjob(job_setup_connect
, now
+ SHORT_TIMEOUT
, data_cl
);
1645 /* Reply myself (bound to fail). */
1646 start_relay(data_cl
->fd
, NO_FD
);
1647 deallocate(data_cl
);
1652 tcpconf
.nwtc_flags
= NWTC_LP_SEL
| NWTC_SET_RA
| NWTC_SET_RP
;
1653 tcpconf
.nwtc_remaddr
= current_named();
1654 tcpconf
.nwtc_remport
= named_port
;
1655 if (ioctl(dn_fd
, NWIOSTCPCONF
, &tcpconf
) == -1) fatal(tcp_device
);
1658 data_cl
->dn_fd
= dn_fd
;
1659 data_cl
->tcpcl
.nwtcl_flags
= 0;
1660 newjob(job_connect
, NEVER
, data_cl
);
1664 static int job_connect(void *data
, int expired
)
1665 /* Connect to a TCP DNS query channel. */
1667 data_cl_t
*data_cl
= data
;
1669 /* Try to connect. */
1670 if (asyn_ioctl(&asyn
, data_cl
->dn_fd
, NWIOTCPCONN
, &data_cl
->tcpcl
) < 0) {
1671 if (errno
== EINPROGRESS
) return 0;
1672 if (errno
== EIO
) fatal(tcp_device
);
1674 /* Connection refused. */
1675 if (debug
>= 2) printf("%s: Connect: %s\n", nowgmt(), strerror(errno
));
1676 asyn_close(&asyn
, data_cl
->dn_fd
);
1677 close(data_cl
->dn_fd
);
1678 data_cl
->dn_fd
= NO_FD
;
1679 if (++data_cl
->retry
< 5) {
1680 /* Search a new name daemon. */
1683 force_expire(job_find_named
);
1685 newjob(job_setup_connect
, NEVER
, data_cl
);
1688 /* Reply with a failure eventually. */
1690 if (debug
>= 2) printf("%s: Connect\n", nowgmt());
1692 /* Read the query from the user, send on to the name daemon, etc. */
1693 start_relay(data_cl
->fd
, data_cl
->dn_fd
);
1694 deallocate(data_cl
);
1698 static void tcp_dns_tell(int fd
, u8_t
*buf
)
1699 /* Tell about a DNS packet on a TCP channel. */
1701 nwio_tcpconf_t tcpconf
;
1703 if (ioctl(fd
, NWIOGTCPCONF
, &tcpconf
) < 0) {
1704 printf("??\?:?? TCP ");
1706 printf("%s:%u TCP ", inet_ntoa(tcpconf
.nwtc_remaddr
),
1707 ntohs(tcpconf
.nwtc_remport
));
1709 dns_tell(0, oct2dns(buf
+ sizeof(u16_t
)), ntohs(upack16(buf
)));
1712 static int job_read_query(void *data
, int expired
)
1713 /* Read TCP queries from the client. */
1715 data_rw_t
*data_rw
= data
;
1718 /* Try to read count bytes. */
1719 count
= asyn_read(&asyn
, data_rw
->r_fd
,
1720 data_rw
->buf
+ data_rw
->offset
,
1721 data_rw
->size
- data_rw
->offset
);
1724 if (errno
== EINPROGRESS
&& !expired
) return 0;
1725 if (errno
== EIO
) fatal(tcp_device
);
1727 /* Remote end is late, or an error occurred. */
1729 printf("%s: TCP read query: %s\n", nowgmt(), strerror(errno
));
1731 close_relay(data_rw
);
1736 printf("%s: TCP read query, %d/%u bytes\n",
1737 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1741 close_relay(data_rw
);
1744 data_rw
->offset
+= count
;
1745 if (data_rw
->offset
== data_rw
->size
) {
1746 data_rw
->size
= sizeof(u16_t
) + ntohs(upack16(data_rw
->buf
));
1747 if (data_rw
->size
< sizeof(u16_t
)) {
1749 close_relay(data_rw
);
1752 if (data_rw
->offset
< data_rw
->size
) {
1753 /* Query not complete, read more. */
1754 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1755 newjob(job_read_query
, now
+ LONG_TIMEOUT
, data_rw
);
1760 if (data_rw
->size
< sizeof(u16_t
) + sizeof(dns_hdr_t
)) {
1761 close_relay(data_rw
);
1764 if (debug
>= 1) tcp_dns_tell(data_rw
->r_fd
, data_rw
->buf
);
1766 /* Relay or reply. */
1767 if (data_rw
->w_fd
!= data_rw
->r_fd
) {
1768 /* We have a real name daemon to do the work. */
1770 newjob(job_write_query
, now
+ LONG_TIMEOUT
, data_rw
);
1772 /* No real name daemons or none reachable, so use the hosts file. */
1776 if (data_rw
->size
< sizeof(u16_t
) + PACKETSZ
) {
1777 data_rw
->buf
= allocate(data_rw
->buf
, sizeof(u16_t
) + PACKETSZ
);
1780 /* Build a reply packet. */
1781 dp
= oct2dns(data_rw
->buf
+ sizeof(u16_t
));
1782 dlen
= data_rw
->size
- sizeof(u16_t
);
1783 if (!compose_reply(dp
, &dlen
)) {
1784 /* We're told to ask a name daemon, but that won't work. */
1785 close_relay(data_rw
);
1789 /* Start a reply write. */
1790 pack16(data_rw
->buf
, htons(dlen
));
1791 data_rw
->size
= sizeof(u16_t
) + dlen
;
1792 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1794 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1799 static int job_write_query(void *data
, int expired
)
1800 /* Relay a TCP query to the name daemon. */
1802 data_rw_t
*data_rw
= data
;
1805 /* Try to write count bytes to the name daemon. */
1806 count
= asyn_write(&asyn
, data_rw
->w_fd
,
1807 data_rw
->buf
+ data_rw
->offset
,
1808 data_rw
->size
- data_rw
->offset
);
1811 if (errno
== EINPROGRESS
&& !expired
) return 0;
1812 if (errno
== EIO
) fatal(tcp_device
);
1814 /* A write expired or failed (usually a broken connection.) */
1816 printf("%s: TCP write query: %s\n", nowgmt(), strerror(errno
));
1818 close_relay(data_rw
);
1823 printf("%s: TCP write query, %d/%u bytes\n",
1824 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1826 data_rw
->offset
+= count
;
1827 if (data_rw
->offset
< data_rw
->size
) {
1828 /* Partial write, continue. */
1829 newjob(job_write_query
, now
+ LONG_TIMEOUT
, data_rw
);
1832 if (debug
>= 1) tcp_dns_tell(data_rw
->w_fd
, data_rw
->buf
);
1834 /* Query fully send on, go read more queries. */
1836 data_rw
->size
= sizeof(u16_t
);
1837 newjob(job_read_query
, now
+ LONG_TIMEOUT
, data_rw
);
1841 static int job_read_reply(void *data
, int expired
)
1842 /* Read a TCP reply from the real name daemon. */
1844 data_rw_t
*data_rw
= data
;
1847 /* Try to read count bytes. */
1848 count
= asyn_read(&asyn
, data_rw
->r_fd
,
1849 data_rw
->buf
+ data_rw
->offset
,
1850 data_rw
->size
- data_rw
->offset
);
1853 if (errno
== EINPROGRESS
&& !expired
) return 0;
1854 if (errno
== EIO
) fatal(tcp_device
);
1856 /* Remote end is late, or an error occurred. */
1858 printf("%s: TCP read reply: %s\n", nowgmt(), strerror(errno
));
1860 close_relay(data_rw
);
1865 printf("%s: TCP read reply, %d/%u bytes\n",
1866 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1870 close_relay(data_rw
);
1873 data_rw
->offset
+= count
;
1874 if (data_rw
->offset
== data_rw
->size
) {
1875 data_rw
->size
= sizeof(u16_t
) + ntohs(upack16(data_rw
->buf
));
1876 if (data_rw
->size
< sizeof(u16_t
)) {
1878 close_relay(data_rw
);
1881 if (data_rw
->offset
< data_rw
->size
) {
1882 /* Reply not complete, read more. */
1883 data_rw
->buf
= allocate(data_rw
->buf
, data_rw
->size
);
1884 newjob(job_read_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1888 if (debug
>= 1) tcp_dns_tell(data_rw
->r_fd
, data_rw
->buf
);
1890 /* Reply fully read, send it on. */
1892 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1896 static int job_write_reply(void *data
, int expired
)
1897 /* Send a TCP reply to the client. */
1899 data_rw_t
*data_rw
= data
;
1902 /* Try to write count bytes to the client. */
1903 count
= asyn_write(&asyn
, data_rw
->w_fd
,
1904 data_rw
->buf
+ data_rw
->offset
,
1905 data_rw
->size
- data_rw
->offset
);
1908 if (errno
== EINPROGRESS
&& !expired
) return 0;
1909 if (errno
== EIO
) fatal(tcp_device
);
1911 /* A write expired or failed (usually a broken connection.) */
1913 printf("%s: TCP write reply: %s\n", nowgmt(), strerror(errno
));
1915 close_relay(data_rw
);
1920 printf("%s: TCP write reply, %d/%u bytes\n",
1921 nowgmt(), data_rw
->offset
+ count
, data_rw
->size
);
1923 data_rw
->offset
+= count
;
1924 if (data_rw
->offset
< data_rw
->size
) {
1925 /* Partial write, continue. */
1926 newjob(job_write_reply
, now
+ LONG_TIMEOUT
, data_rw
);
1929 if (debug
>= 1) tcp_dns_tell(data_rw
->w_fd
, data_rw
->buf
);
1931 /* Reply fully send on, go read more replies (or queries). */
1933 data_rw
->size
= sizeof(u16_t
);
1934 newjob(data_rw
->w_fd
!= data_rw
->r_fd
? job_read_reply
: job_read_query
,
1935 now
+ LONG_TIMEOUT
, data_rw
);
1940 static int job_dummy(void *data
, int expired
)
1944 #define job_setup_listen job_dummy
1945 #define job_setup_connect job_dummy
1946 #endif /* !DO_TCP */
1948 static void named_probe(ipaddr_t ip
)
1949 /* Send a probe to a name daemon, like 'host -r -t ns . <ip>'. */
1952 # define dlen (offsetof(dns_t, data) + 5)
1953 # define ulen (offsetof(udp_dns_t, dns) + dlen)
1955 /* Send a simple DNS query that all name servers can answer easily:
1956 * "What are the name servers for the root domain?"
1958 udp
.dns
.hdr
.id
= new_id(ID_PROBE
, my_port
, ID_IPSELF
);
1960 udp
.dns
.hdr
.opcode
= 0;
1965 udp
.dns
.hdr
.unused
= 0;
1968 udp
.dns
.hdr
.rcode
= 0;
1969 udp
.dns
.hdr
.qdcount
= HTONS(1);
1970 udp
.dns
.hdr
.ancount
= HTONS(0);
1971 udp
.dns
.hdr
.nscount
= HTONS(0);
1972 udp
.dns
.hdr
.arcount
= HTONS(0);
1974 udp
.dns
.data
[0] = 0; /* Null name. */
1975 pack16(udp
.dns
.data
+1, HTONS(T_NS
));
1976 pack16(udp
.dns
.data
+3, HTONS(C_IN
));
1978 printf("PROBE %s ", inet_ntoa(ip
));
1979 dns_tell(0, &udp
.dns
, dlen
);
1982 udp
.hdr
.uih_dst_addr
= ip
;
1983 udp
.hdr
.uih_dst_port
= named_port
;
1984 udp
.hdr
.uih_ip_opt_len
= 0;
1985 udp
.hdr
.uih_data_len
= dlen
;
1987 if (write(udp_fd
, &udp
, ulen
) < 0) fatal(udp_device
);
1992 static int job_find_named(void *data
, int expired
)
1993 /* Look for a real name daemon to answer real DNS queries. */
1995 if (!expired
) return 0;
1996 if (debug
>= 2) printf("%s: Find named\n", nowgmt());
1999 if (search_ct
< 0) {
2000 search_ct
= n_nameds
;
2004 if (--search_ct
< 0) {
2005 /* Forced end of search (named response!), or end of search with
2006 * nothing found. Search again after a long time.
2008 newjob(job_find_named
,
2009 (stale
> 0 || i_named
> 0) ? now
+ LONG_TIMEOUT
: NEVER
, nil
);
2010 force_expire(job_setup_connect
);
2014 /* Send a named probe. */
2015 i_named
= (i_named
+1) % n_nameds
;
2016 named_probe(current_named());
2018 /* Schedule the next call. */
2019 newjob(job_find_named
, now
+ SHORT_TIMEOUT
, nil
);
2023 static int job_expect_named(void *data
, int expired
)
2024 /* The real name server is expected to answer by now. */
2026 if (!expired
) return 0;
2027 if (debug
>= 2) printf("%s: Expect named\n", nowgmt());
2029 if (expecting() && !searching()) {
2030 /* No answer yet, start searching. */
2032 force_expire(job_find_named
);
2037 static void sig_handler(int sig
)
2038 /* A signal forces a search for a real name daemon, etc. */
2042 case SIGTERM
: done
= 1; break;
2043 case SIGHUP
: reinit
= 1; break;
2044 case SIGUSR1
: debug
++; break;
2045 case SIGUSR2
: debug
= 0; break;
2049 static void usage(void)
2051 fprintf(stderr
, "Usage: nonamed [-qs] [-d[level]] [-p port]\n");
2055 int main(int argc
, char **argv
)
2058 nwio_udpopt_t udpopt
;
2060 struct servent
*servent
;
2061 struct sigaction sa
;
2065 /* Debug output must be line buffered. */
2066 setvbuf(stdout
, nil
, _IOLBF
, 0);
2068 /* DNS service port number? */
2069 if ((servent
= getservbyname("domain", nil
)) == nil
) {
2070 fprintf(stderr
, "nonamed: \"domain\": unknown service\n");
2073 my_port
= servent
->s_port
;
2074 named_port
= servent
->s_port
;
2077 while (i
< argc
&& argv
[i
][0] == '-') {
2078 char *opt
= argv
[i
++] + 1, *end
;
2080 if (opt
[0] == '-' && opt
[1] == 0) break;
2083 case 'd': /* Debug level. */
2085 if (between('0', *opt
, '9')) debug
= strtoul(opt
, &opt
, 10);
2087 case 'p': /* Port to listen to (for testing.) */
2089 if (i
== argc
) usage();
2092 my_port
= htons(strtoul(opt
, &end
, 0));
2093 if (opt
== end
|| *end
!= 0) usage();
2099 case 'q': /* Quit after printing cache contents. */
2109 if (i
!= argc
) usage();
2112 /* Oops, just having a look at the cache. */
2120 /* Don't die on broken pipes, reinitialize on hangup, etc. */
2121 sa
.sa_handler
= SIG_IGN
;
2122 sigemptyset(&sa
.sa_mask
);
2124 sigaction(SIGPIPE
, &sa
, nil
);
2125 sa
.sa_handler
= sig_handler
;
2126 sigaction(SIGINT
, &sa
, nil
);
2127 sigaction(SIGHUP
, &sa
, nil
);
2128 sigaction(SIGUSR1
, &sa
, nil
);
2129 sigaction(SIGUSR2
, &sa
, nil
);
2130 sigaction(SIGTERM
, &sa
, nil
);
2132 /* TCP and UDP device names. */
2133 if ((tcp_device
= getenv("TCP_DEVICE")) == nil
) tcp_device
= TCP_DEVICE
;
2134 if ((udp_device
= getenv("UDP_DEVICE")) == nil
) udp_device
= UDP_DEVICE
;
2136 /* Open an UDP channel for incoming DNS queries. */
2137 if ((udp_fd
= open(udp_device
, O_RDWR
)) < 0) fatal(udp_device
);
2139 udpopt
.nwuo_flags
= NWUO_EXCL
| NWUO_LP_SET
| NWUO_EN_LOC
| NWUO_DI_BROAD
2140 | NWUO_RP_ANY
| NWUO_RA_ANY
| NWUO_RWDATALL
| NWUO_DI_IPOPT
;
2141 udpopt
.nwuo_locport
= my_port
;
2142 if (ioctl(udp_fd
, NWIOSUDPOPT
, &udpopt
) == -1
2143 || ioctl(udp_fd
, NWIOGUDPOPT
, &udpopt
) == -1
2148 /* The current time is... */
2151 /* Read configuration and data cached by the previous nonamed. */
2152 init_config(udpopt
.nwuo_locaddr
);
2156 /* Save process id. */
2157 if ((fp
= fopen(PIDFILE
, "w")) != nil
) {
2158 fprintf(fp
, "%u\n", (unsigned) getpid());
2163 /* Jobs that start the ball rolling. */
2164 newjob(job_read_udp
, NEVER
, nil
);
2165 newjob(job_setup_listen
, IMMEDIATE
, nil
);
2166 newjob(job_find_named
, IMMEDIATE
, nil
);
2169 openlog("nonamed", LOG_PID
, LOG_DAEMON
);
2172 /* There is always something in the queue. */
2173 assert(queue
!= nil
);
2175 /* Any expired jobs? */
2176 while (queue
->timeout
<= now
) {
2177 (void) execjob(queue
, 1);
2178 assert(queue
!= nil
);
2181 /* Check I/O jobs. */
2182 for (job
= queue
; job
!= nil
; job
= job
->next
) {
2183 if (execjob(job
, 0)) break;
2186 if (queue
->timeout
!= IMMEDIATE
) {
2187 struct timeval tv
, *tvp
;
2189 if (debug
>= 2) printf("%s: I/O wait", nowgmt());
2191 if (queue
->timeout
!= NEVER
) {
2192 tv
.tv_sec
= queue
->timeout
;
2195 if (debug
>= 2) printf(" (expires %s)\n", timegmt(tv
.tv_sec
));
2198 if (debug
>= 2) fputc('\n', stdout
);
2202 if (asyn_wait(&asyn
, 0, tvp
) < 0) {
2203 if (errno
!= EINTR
&& errno
!= EAGAIN
) fatal("fwait()");
2209 /* A hangup makes us go back to square one. */
2211 if (ioctl(udp_fd
, NWIOGUDPOPT
, &udpopt
) == -1) fatal(udp_device
);
2212 init_config(udpopt
.nwuo_locaddr
);
2214 force_expire(job_find_named
);
2218 (void) unlink(PIDFILE
);
2219 if (debug
>= 2) printf("sbrk(0) = %u\n", (unsigned) sbrk(0));