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