Turn two unreachable statements into errx().
[darkstat] / dns.c
1 /* darkstat 3
2 * copyright (c) 2001-2014 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 errx(1, "DNS child fell out of dns_main()");
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 RB_GENERATE_STATIC(tree_t, tree_rec, ptree, tree_cmp)
115
116 void
117 dns_queue(const struct addr *const ipaddr)
118 {
119 struct tree_rec *rec;
120 ssize_t num_w;
121
122 if (pid == -1)
123 return; /* no child was started - we're not doing any DNS */
124
125 if ((ipaddr->family != IPv4) && (ipaddr->family != IPv6)) {
126 verbosef("dns_queue() for unknown family %d", ipaddr->family);
127 return;
128 }
129
130 rec = xmalloc(sizeof(*rec));
131 memcpy(&rec->ip, ipaddr, sizeof(rec->ip));
132
133 if (RB_INSERT(tree_t, &ip_tree, rec) != NULL) {
134 /* Already queued - this happens seldom enough that we don't care about
135 * the performance hit of needlessly malloc()ing. */
136 verbosef("already queued %s", addr_to_str(ipaddr));
137 free(rec);
138 return;
139 }
140
141 num_w = write(dns_sock[PARENT], ipaddr, sizeof(*ipaddr)); /* won't block */
142 if (num_w == 0)
143 warnx("dns_queue: write: ignoring end of file");
144 else if (num_w == -1)
145 warn("dns_queue: ignoring write error");
146 else if (num_w != sizeof(*ipaddr))
147 err(1, "dns_queue: wrote %zu instead of %zu", num_w, sizeof(*ipaddr));
148 }
149
150 static void
151 dns_unqueue(const struct addr *const ipaddr)
152 {
153 struct tree_rec tmp, *rec;
154
155 memcpy(&tmp.ip, ipaddr, sizeof(tmp.ip));
156 if ((rec = RB_FIND(tree_t, &ip_tree, &tmp)) != NULL) {
157 RB_REMOVE(tree_t, &ip_tree, rec);
158 free(rec);
159 }
160 else
161 verbosef("couldn't unqueue %s - not in queue!", addr_to_str(ipaddr));
162 }
163
164 /*
165 * Returns non-zero if result waiting, stores IP and name into given pointers
166 * (name buffer is allocated by dns_poll)
167 */
168 static int
169 dns_get_result(struct addr *ipaddr, char **name)
170 {
171 struct dns_reply reply;
172 ssize_t numread;
173
174 numread = read(dns_sock[PARENT], &reply, sizeof(reply));
175 if (numread == -1) {
176 if (errno == EAGAIN)
177 return (0); /* no input waiting */
178 else
179 goto error;
180 }
181 if (numread == 0)
182 goto error; /* EOF */
183 if (numread != sizeof(reply))
184 errx(1, "dns_get_result read got %zu, expected %zu",
185 numread, sizeof(reply));
186
187 /* Return successful reply. */
188 memcpy(ipaddr, &reply.addr, sizeof(*ipaddr));
189 if (reply.error != 0) {
190 /* Identify common special cases. */
191 const char *type = "none";
192
193 if (reply.addr.family == IPv6) {
194 if (IN6_IS_ADDR_LINKLOCAL(&reply.addr.ip.v6))
195 type = "link-local";
196 else if (IN6_IS_ADDR_SITELOCAL(&reply.addr.ip.v6))
197 type = "site-local";
198 else if (IN6_IS_ADDR_MULTICAST(&reply.addr.ip.v6))
199 type = "multicast";
200 } else {
201 assert(reply.addr.family == IPv4);
202 if (IN_MULTICAST(htonl(reply.addr.ip.v4)))
203 type = "multicast";
204 }
205 xasprintf(name, "(%s)", type);
206 }
207 else /* Correctly resolved name. */
208 *name = xstrdup(reply.name);
209
210 dns_unqueue(&reply.addr);
211 return (1);
212
213 error:
214 warn("dns_get_result: ignoring read error");
215 /* FIXME: re-align to stream? restart dns child? */
216 return (0);
217 }
218
219 void
220 dns_poll(void)
221 {
222 struct addr ip;
223 char *name;
224
225 if (pid == -1)
226 return; /* no child was started - we're not doing any DNS */
227
228 while (dns_get_result(&ip, &name)) {
229 /* push into hosts_db */
230 struct bucket *b = host_find(&ip);
231
232 if (b == NULL) {
233 verbosef("resolved %s to %s but it's not in the DB!",
234 addr_to_str(&ip), name);
235 return;
236 }
237 if (b->u.host.dns != NULL) {
238 verbosef("resolved %s to %s but it's already in the DB!",
239 addr_to_str(&ip), name);
240 return;
241 }
242 b->u.host.dns = name;
243 }
244 }
245
246 /* ------------------------------------------------------------------------ */
247
248 struct qitem {
249 STAILQ_ENTRY(qitem) entries;
250 struct addr ip;
251 };
252
253 static STAILQ_HEAD(qhead, qitem) queue = STAILQ_HEAD_INITIALIZER(queue);
254
255 static void
256 enqueue(const struct addr *const ip)
257 {
258 struct qitem *i;
259
260 i = xmalloc(sizeof(*i));
261 memcpy(&i->ip, ip, sizeof(i->ip));
262 STAILQ_INSERT_TAIL(&queue, i, entries);
263 verbosef("DNS: enqueued %s", addr_to_str(ip));
264 }
265
266 /* Return non-zero and populate <ip> pointer if queue isn't empty. */
267 static int
268 dequeue(struct addr *ip)
269 {
270 struct qitem *i;
271
272 i = STAILQ_FIRST(&queue);
273 if (i == NULL)
274 return (0);
275 STAILQ_REMOVE_HEAD(&queue, entries);
276 memcpy(ip, &i->ip, sizeof(*ip));
277 free(i);
278 verbosef("DNS: dequeued %s", addr_to_str(ip));
279 return 1;
280 }
281
282 static void
283 xwrite(const int d, const void *buf, const size_t nbytes)
284 {
285 ssize_t ret = write(d, buf, nbytes);
286
287 if (ret == -1)
288 err(1, "write");
289 if (ret != (ssize_t)nbytes)
290 err(1, "wrote %d bytes instead of all %d bytes", (int)ret, (int)nbytes);
291 }
292
293 static void
294 dns_main(void)
295 {
296 struct addr ip;
297
298 setproctitle("DNS child");
299 fd_set_nonblock(dns_sock[CHILD]);
300 verbosef("DNS child entering main DNS loop");
301 for (;;) {
302 int blocking;
303
304 if (STAILQ_EMPTY(&queue)) {
305 blocking = 1;
306 fd_set_block(dns_sock[CHILD]);
307 verbosef("entering blocking read loop");
308 } else {
309 blocking = 0;
310 fd_set_nonblock(dns_sock[CHILD]);
311 verbosef("non-blocking poll");
312 }
313 for (;;) {
314 /* While we have input to process... */
315 ssize_t numread = read(dns_sock[CHILD], &ip, sizeof(ip));
316 if (numread == 0)
317 exit(0); /* end of file, nothing more to do here. */
318 if (numread == -1) {
319 if (!blocking && (errno == EAGAIN))
320 break; /* ran out of input */
321 /* else error */
322 err(1, "DNS: read failed");
323 }
324 if (numread != sizeof(ip))
325 err(1, "DNS: read got %zu bytes, expecting %zu",
326 numread, sizeof(ip));
327 enqueue(&ip);
328 if (blocking) {
329 /* After one blocking read, become non-blocking so that when we
330 * run out of input we fall through to queue processing.
331 */
332 blocking = 0;
333 fd_set_nonblock(dns_sock[CHILD]);
334 }
335 }
336
337 /* Process queue. */
338 if (dequeue(&ip)) {
339 struct dns_reply reply;
340 struct sockaddr_in sin;
341 struct sockaddr_in6 sin6;
342 struct hostent *he;
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 if (ret == EAI_FAMILY) {
358 verbosef("getnameinfo error %s, trying gethostbyname",
359 gai_strerror(ret));
360 he = gethostbyaddr(&sin.sin_addr.s_addr,
361 sizeof(sin.sin_addr.s_addr), sin.sin_family);
362 if (he == NULL) {
363 ret = EAI_FAIL;
364 verbosef("gethostbyname error %s", hstrerror(h_errno));
365 } else {
366 ret = 0;
367 strlcpy(host, he->h_name, sizeof(host));
368 }
369 }
370 break;
371 case IPv6:
372 sin6.sin6_family = AF_INET6;
373 memcpy(&sin6.sin6_addr, &ip.ip.v6, sizeof(sin6.sin6_addr));
374 ret = getnameinfo((struct sockaddr *) &sin6, sizeof(sin6),
375 host, sizeof(host), NULL, 0, flags);
376 break;
377 default:
378 errx(1, "unexpected ip.family = %d", ip.family);
379 }
380
381 if (ret != 0) {
382 reply.name[0] = '\0';
383 reply.error = ret;
384 } else {
385 assert(sizeof(reply.name) > sizeof(char *)); /* not just a ptr */
386 strlcpy(reply.name, host, sizeof(reply.name));
387 reply.error = 0;
388 }
389 fd_set_block(dns_sock[CHILD]);
390 xwrite(dns_sock[CHILD], &reply, sizeof(reply));
391 verbosef("DNS: %s is \"%s\".", addr_to_str(&reply.addr),
392 (ret == 0) ? reply.name : gai_strerror(ret));
393 }
394 }
395 }
396
397 /* vim:set ts=3 sw=3 tw=78 expandtab: */