release
[hcoop/zz_old/debian/djbdns.git] / dns_rcip.c
CommitLineData
dc0d77d7
CE
1#include "taia.h"
2#include "openreadclose.h"
3#include "byte.h"
4#include "ip4.h"
5#include "env.h"
6#include "dns.h"
7
8static stralloc data = {0};
9
10static int init(char ip[64])
11{
12 int i;
13 int j;
14 int iplen = 0;
15 char *x;
16
17 x = env_get("DNSCACHEIP");
18 if (x)
19 while (iplen <= 60) {
20 if (*x == '.')
21 ++x;
22 else {
23 i = ip4_scan(x,ip + iplen);
24 if (!i) break;
25 x += i;
26 iplen += 4;
27 }
28 }
29
30 if (!iplen) {
31 i = openreadclose("/etc/resolv.conf",&data,64);
32 if (i == -1) return -1;
33 if (i) {
34 if (!stralloc_append(&data,"\n")) return -1;
35 i = 0;
36 for (j = 0;j < data.len;++j)
37 if (data.s[j] == '\n') {
38 if (byte_equal("nameserver ",11,data.s + i) || byte_equal("nameserver\t",11,data.s + i)) {
39 i += 10;
40 while ((data.s[i] == ' ') || (data.s[i] == '\t'))
41 ++i;
42 if (iplen <= 60)
43 if (ip4_scan(data.s + i,ip + iplen)) {
44 if (byte_equal(ip + iplen,4,"\0\0\0\0"))
45 byte_copy(ip + iplen,4,"\177\0\0\1");
46 iplen += 4;
47 }
48 }
49 i = j + 1;
50 }
51 }
52 }
53
54 if (!iplen) {
55 byte_copy(ip,4,"\177\0\0\1");
56 iplen = 4;
57 }
58 byte_zero(ip + iplen,64 - iplen);
59 return 0;
60}
61
62static int ok = 0;
63static unsigned int uses;
64static struct taia deadline;
65static char ip[64]; /* defined if ok */
66
67int dns_resolvconfip(char s[64])
68{
69 struct taia now;
70
71 taia_now(&now);
72 if (taia_less(&deadline,&now)) ok = 0;
73 if (!uses) ok = 0;
74
75 if (!ok) {
76 if (init(ip) == -1) return -1;
77 taia_uint(&deadline,600);
78 taia_add(&deadline,&now,&deadline);
79 uses = 10000;
80 ok = 1;
81 }
82
83 --uses;
84 byte_copy(s,64,ip);
85 return 0;
86}