Move *BSD compatibility layer to extra file.
[darkstat] / dns.c
1 /* darkstat 3
2 * copyright (c) 2001-2011 Emil Mikulic.
3 *
4 * dns.c: synchronous DNS in a child process.
5 *
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
8 */
9
10 #include "cdefs.h"
11 #include "conv.h"
12 #include "config.h"
13 #include "decode.h"
14 #include "dns.h"
15 #include "err.h"
16 #include "hosts_db.h"
17 #include "queue.h"
18 #include "str.h"
19 #include "tree.h"
20 #include "bsd.h" /* for setproctitle, strlcpy */
21
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 #include <sys/wait.h>
25 #include <assert.h>
26 #include <errno.h>
27 #include <netdb.h>
28 #include <signal.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 static void dns_main(void) _noreturn_; /* the child process runs this */
34
35 #define CHILD 0 /* child process uses this socket */
36 #define PARENT 1
37 static int sock[2];
38 static pid_t pid = -1;
39
40 struct dns_reply {
41 struct addr addr;
42 int error; /* for gai_strerror(), or 0 if no error */
43 char name[256]; /* http://tools.ietf.org/html/rfc1034#section-3.1 */
44 };
45
46 void
47 dns_init(const char *privdrop_user)
48 {
49 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sock) == -1)
50 err(1, "socketpair");
51
52 pid = fork();
53 if (pid == -1)
54 err(1, "fork");
55
56 if (pid == 0) {
57 /* We are the child. */
58 privdrop(NULL /* don't chroot */, privdrop_user);
59 close(sock[PARENT]);
60 sock[PARENT] = -1;
61 daemonize_finish(); /* drop our copy of the lifeline! */
62 if (signal(SIGUSR1, SIG_IGN) == SIG_ERR)
63 errx(1, "signal(SIGUSR1, ignore) failed");
64 dns_main();
65 verbosef("fell out of dns_main()");
66 exit(0);
67 } else {
68 /* We are the parent. */
69 close(sock[CHILD]);
70 sock[CHILD] = -1;
71 fd_set_nonblock(sock[PARENT]);
72 verbosef("DNS child has PID %d", pid);
73 }
74 }
75
76 void
77 dns_stop(void)
78 {
79 if (pid == -1)
80 return; /* no child was started */
81 close(sock[PARENT]);
82 if (kill(pid, SIGINT) == -1)
83 err(1, "kill");
84 verbosef("dns_stop() waiting for child");
85 if (waitpid(pid, NULL, 0) == -1)
86 err(1, "waitpid");
87 verbosef("dns_stop() done waiting for child");
88 }
89
90 struct tree_rec {
91 RB_ENTRY(tree_rec) ptree;
92 struct addr ip;
93 };
94
95 static int
96 tree_cmp(struct tree_rec *a, struct tree_rec *b)
97 {
98 if (a->ip.family != b->ip.family)
99 /* Sort IPv4 to the left of IPv6. */
100 return ((a->ip.family == IPv4) ? -1 : +1);
101
102 if (a->ip.family == IPv4)
103 return (memcmp(&a->ip.ip.v4, &b->ip.ip.v4, sizeof(a->ip.ip.v4)));
104 else {
105 assert(a->ip.family == IPv6);
106 return (memcmp(&a->ip.ip.v6, &b->ip.ip.v6, sizeof(a->ip.ip.v6)));
107 }
108 }
109
110 static RB_HEAD(tree_t, tree_rec) ip_tree = RB_INITIALIZER(&tree_rec);
111 /* Quiet warnings. */
112 static struct tree_rec * tree_t_RB_NEXT(struct tree_rec *elm)
113 _unused_;
114 static struct tree_rec * tree_t_RB_MINMAX(struct tree_t *head, int val)
115 _unused_;
116 RB_GENERATE(tree_t, tree_rec, ptree, tree_cmp)
117
118 void
119 dns_queue(const struct addr *const ipaddr)
120 {
121 struct tree_rec *rec;
122 ssize_t num_w;
123
124 if (pid == -1)
125 return; /* no child was started - we're not doing any DNS */
126
127 if ((ipaddr->family != IPv4) && (ipaddr->family != IPv6)) {
128 verbosef("dns_queue() for unknown family %d", ipaddr->family);
129 return;
130 }
131
132 rec = xmalloc(sizeof(*rec));
133 memcpy(&rec->ip, ipaddr, sizeof(rec->ip));
134
135 if (RB_INSERT(tree_t, &ip_tree, rec) != NULL) {
136 /* Already queued - this happens seldom enough that we don't care about
137 * the performance hit of needlessly malloc()ing. */
138 verbosef("already queued %s", addr_to_str(ipaddr));
139 free(rec);
140 return;
141 }
142
143 num_w = write(sock[PARENT], ipaddr, sizeof(*ipaddr)); /* won't block */
144 if (num_w == 0)
145 warnx("dns_queue: write: ignoring end of file");
146 else if (num_w == -1)
147 warn("dns_queue: ignoring write error");
148 else if (num_w != sizeof(*ipaddr))
149 err(1, "dns_queue: wrote %zu instead of %zu", num_w, sizeof(*ipaddr));
150 }
151
152 static void
153 dns_unqueue(const struct addr *const ipaddr)
154 {
155 struct tree_rec tmp, *rec;
156
157 memcpy(&tmp.ip, ipaddr, sizeof(tmp.ip));
158 if ((rec = RB_FIND(tree_t, &ip_tree, &tmp)) != NULL) {
159 RB_REMOVE(tree_t, &ip_tree, rec);
160 free(rec);
161 }
162 else
163 verbosef("couldn't unqueue %s - not in queue!", addr_to_str(ipaddr));
164 }
165
166 /*
167 * Returns non-zero if result waiting, stores IP and name into given pointers
168 * (name buffer is allocated by dns_poll)
169 */
170 static int
171 dns_get_result(struct addr *ipaddr, char **name)
172 {
173 struct dns_reply reply;
174 ssize_t numread;
175
176 numread = read(sock[PARENT], &reply, sizeof(reply));
177 if (numread == -1) {
178 if (errno == EAGAIN)
179 return (0); /* no input waiting */
180 else
181 goto error;
182 }
183 if (numread == 0)
184 goto error; /* EOF */
185 if (numread != sizeof(reply))
186 errx(1, "dns_get_result read got %zu, expected %zu",
187 numread, sizeof(reply));
188
189 /* Return successful reply. */
190 memcpy(ipaddr, &reply.addr, sizeof(*ipaddr));
191 if (reply.error != 0) {
192 /* Identify common special cases. */
193 const char *type = "none";
194
195 if (reply.addr.family == IPv6) {
196 if (IN6_IS_ADDR_LINKLOCAL(&reply.addr.ip.v6))
197 type = "link-local";
198 else if (IN6_IS_ADDR_SITELOCAL(&reply.addr.ip.v6))
199 type = "site-local";
200 else if (IN6_IS_ADDR_MULTICAST(&reply.addr.ip.v6))
201 type = "multicast";
202 } else { /* AF_INET */
203 if (IN_MULTICAST(reply.addr.ip.v4))
204 type = "multicast";
205 }
206 xasprintf(name, "(%s)", type);
207 }
208 else /* Correctly resolved name. */
209 *name = xstrdup(reply.name);
210
211 dns_unqueue(&reply.addr);
212 return (1);
213
214 error:
215 warn("dns_get_result: ignoring read error");
216 /* FIXME: re-align to stream? restart dns child? */
217 return (0);
218 }
219
220 void
221 dns_poll(void)
222 {
223 struct addr ip;
224 char *name;
225
226 if (pid == -1)
227 return; /* no child was started - we're not doing any DNS */
228
229 while (dns_get_result(&ip, &name)) {
230 /* push into hosts_db */
231 struct bucket *b = host_find(&ip);
232
233 if (b == NULL) {
234 verbosef("resolved %s to %s but it's not in the DB!",
235 addr_to_str(&ip), name);
236 return;
237 }
238 if (b->u.host.dns != NULL) {
239 verbosef("resolved %s to %s but it's already in the DB!",
240 addr_to_str(&ip), name);
241 return;
242 }
243 b->u.host.dns = name;
244 }
245 }
246
247 /* ------------------------------------------------------------------------ */
248
249 struct qitem {
250 STAILQ_ENTRY(qitem) entries;
251 struct addr ip;
252 };
253
254 STAILQ_HEAD(qhead, qitem) queue = STAILQ_HEAD_INITIALIZER(queue);
255
256 static void
257 enqueue(const struct addr *const ip)
258 {
259 struct qitem *i;
260
261 i = xmalloc(sizeof(*i));
262 memcpy(&i->ip, ip, sizeof(i->ip));
263 STAILQ_INSERT_TAIL(&queue, i, entries);
264 verbosef("DNS: enqueued %s", addr_to_str(ip));
265 }
266
267 /* Return non-zero and populate <ip> pointer if queue isn't empty. */
268 static int
269 dequeue(struct addr *ip)
270 {
271 struct qitem *i;
272
273 i = STAILQ_FIRST(&queue);
274 if (i == NULL)
275 return (0);
276 STAILQ_REMOVE_HEAD(&queue, entries);
277 memcpy(ip, &i->ip, sizeof(*ip));
278 free(i);
279 verbosef("DNS: dequeued %s", addr_to_str(ip));
280 return 1;
281 }
282
283 static void
284 xwrite(const int d, const void *buf, const size_t nbytes)
285 {
286 ssize_t ret = write(d, buf, nbytes);
287
288 if (ret == -1)
289 err(1, "write");
290 if (ret != (ssize_t)nbytes)
291 err(1, "wrote %d bytes instead of all %d bytes", (int)ret, (int)nbytes);
292 }
293
294 static void
295 dns_main(void)
296 {
297 struct addr ip;
298
299 setproctitle("DNS child");
300 fd_set_nonblock(sock[CHILD]);
301 verbosef("DNS child entering main DNS loop");
302 for (;;) {
303 int blocking;
304
305 if (STAILQ_EMPTY(&queue)) {
306 blocking = 1;
307 fd_set_block(sock[CHILD]);
308 verbosef("entering blocking read loop");
309 } else {
310 blocking = 0;
311 fd_set_nonblock(sock[CHILD]);
312 verbosef("non-blocking poll");
313 }
314 for (;;) {
315 /* While we have input to process... */
316 ssize_t numread = read(sock[CHILD], &ip, sizeof(ip));
317 if (numread == 0)
318 exit(0); /* end of file, nothing more to do here. */
319 if (numread == -1) {
320 if (!blocking && (errno == EAGAIN))
321 break; /* ran out of input */
322 /* else error */
323 err(1, "DNS: read failed");
324 }
325 if (numread != sizeof(ip))
326 err(1, "DNS: read got %zu bytes, expecting %zu",
327 numread, sizeof(ip));
328 enqueue(&ip);
329 if (blocking) {
330 /* After one blocking read, become non-blocking so that when we
331 * run out of input we fall through to queue processing.
332 */
333 blocking = 0;
334 fd_set_nonblock(sock[CHILD]);
335 }
336 }
337
338 /* Process queue. */
339 if (dequeue(&ip)) {
340 struct dns_reply reply;
341 struct sockaddr_in sin;
342 struct sockaddr_in6 sin6;
343 char host[NI_MAXHOST];
344 int ret, flags;
345
346 reply.addr = ip;
347 flags = NI_NAMEREQD;
348 # ifdef NI_IDN
349 flags |= NI_IDN;
350 # endif
351 switch (ip.family) {
352 case IPv4:
353 sin.sin_family = AF_INET;
354 sin.sin_addr.s_addr = ip.ip.v4;
355 ret = getnameinfo((struct sockaddr *) &sin, sizeof(sin),
356 host, sizeof(host), NULL, 0, flags);
357 break;
358 case IPv6:
359 sin6.sin6_family = AF_INET6;
360 memcpy(&sin6.sin6_addr, &ip.ip.v6, sizeof(sin6.sin6_addr));
361 ret = getnameinfo((struct sockaddr *) &sin6, sizeof(sin6),
362 host, sizeof(host), NULL, 0, flags);
363 break;
364 default:
365 ret = EAI_FAMILY;
366 }
367
368 if (ret != 0) {
369 reply.name[0] = '\0';
370 reply.error = ret;
371 } else {
372 assert(sizeof(reply.name) > sizeof(char *)); /* not just a ptr */
373 strlcpy(reply.name, host, sizeof(reply.name));
374 reply.error = 0;
375 }
376 fd_set_block(sock[CHILD]);
377 xwrite(sock[CHILD], &reply, sizeof(reply));
378 verbosef("DNS: %s is \"%s\".", addr_to_str(&reply.addr),
379 (ret == 0) ? reply.name : gai_strerror(ret));
380 }
381 }
382 }
383
384 /* vim:set ts=3 sw=3 tw=78 expandtab: */