xref: /freebsd/contrib/netbsd-tests/lib/libc/net/h_dns_server.c (revision dd41de95a84d979615a2ef11df6850622bf6184e)
1 /*	$NetBSD: h_dns_server.c,v 1.4 2014/03/29 16:10:54 gson Exp $	*/
2 
3 /*-
4  * Copyright (c) 2013 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Andreas Gustafsson.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * A minimal DNS server capable of providing canned answers to the
34  * specific queries issued by t_hostent.sh and nothing more.
35  */
36 
37 #include <sys/cdefs.h>
38 __RCSID("$NetBSD: h_dns_server.c,v 1.4 2014/03/29 16:10:54 gson Exp $");
39 
40 #include <ctype.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <memory.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <unistd.h>
48 
49 #include <sys/socket.h>
50 
51 #include <netinet/in.h>
52 #ifdef __NetBSD__
53 #include <netinet6/in6.h>
54 #endif
55 
56 #ifdef __FreeBSD__
57 #include <paths.h>
58 #endif
59 
60 union sockaddr_either {
61 	struct sockaddr s;
62 	struct sockaddr_in sin;
63 	struct sockaddr_in6 sin6;
64 };
65 
66 #ifdef DEBUG
67 #define DPRINTF(...)	fprintf(stderr, __VA_ARGS__)
68 #else
69 #define DPRINTF(...)
70 #endif
71 
72 /* A DNS question and its corresponding answer */
73 
74 struct dns_data {
75 	size_t qname_size;
76 	const char *qname; /* Wire-encode question name */
77 	int qtype;
78 	size_t answer_size;
79 	const char *answer; /* One wire-encoded answer RDATA */
80 };
81 
82 /* Convert C string constant to length + data pair */
83 #define STR_DATA(s) sizeof(s) - 1, s
84 
85 /* Canned DNS queestion-answer pairs */
86 struct dns_data data[] = {
87 	/* Forward mappings */
88 	/* localhost IN A -> 127.0.0.1 */
89 	{ STR_DATA("\011localhost\000"), 1,
90 	  STR_DATA("\177\000\000\001") },
91 	/* localhost IN AAAA -> ::1 */
92 	{ STR_DATA("\011localhost\000"), 28,
93 	  STR_DATA("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001") },
94 	/* sixthavenue.astron.com IN A -> 38.117.134.16 */
95 	{ STR_DATA("\013sixthavenue\006astron\003com\000"), 1,
96 	  STR_DATA("\046\165\206\020") },
97 	/* sixthavenue.astron.com IN AAAA -> 2620:106:3003:1f00:3e4a:92ff:fef4:e180 */
98 	{ STR_DATA("\013sixthavenue\006astron\003com\000"), 28,
99 	  STR_DATA("\x26\x20\x01\x06\x30\x03\x1f\x00\x3e\x4a\x92\xff\xfe\xf4\xe1\x80") },
100 	/* Reverse mappings */
101 	{ STR_DATA("\0011\0010\0010\003127\007in-addr\004arpa\000"), 12,
102 	  STR_DATA("\011localhost\000") },
103 	{ STR_DATA("\0011\0010\0010\0010\0010\0010\0010\0010"
104 		   "\0010\0010\0010\0010\0010\0010\0010\0010"
105 		   "\0010\0010\0010\0010\0010\0010\0010\0010"
106 		   "\0010\0010\0010\0010\0010\0010\0010\0010"
107 		   "\003ip6\004arpa\000"), 12,
108 	  STR_DATA("\011localhost\000") },
109 	{ STR_DATA("\00216\003134\003117\00238"
110 		   "\007in-addr\004arpa\000"), 12,
111 	  STR_DATA("\013sixthavenue\006astron\003com\000") },
112 	{ STR_DATA("\0010\0018\0011\001e\0014\001f\001e\001f"
113 		   "\001f\001f\0012\0019\001a\0014\001e\0013"
114 		   "\0010\0010\001f\0011\0013\0010\0010\0013"
115 		   "\0016\0010\0011\0010\0010\0012\0016\0012"
116 		   "\003ip6\004arpa\000"), 12,
117 	  STR_DATA("\013sixthavenue\006astron\003com\000") },
118 	/* End marker */
119 	{ STR_DATA(""), 0, STR_DATA("") }
120 };
121 
122 /*
123  * Compare two DNS names for equality.	If equal, return their
124  * length, and if not, return zero.  Does not handle compression.
125  */
126 static int
127 name_eq(const unsigned char *a, const unsigned char *b) {
128 	const unsigned char *a_save = a;
129 	for (;;) {
130 		int i;
131 		int lena = *a++;
132 		int lenb = *b++;
133 		if (lena != lenb)
134 			return 0;
135 		if (lena == 0)
136 			return a - a_save;
137 		for (i = 0; i < lena; i++)
138 			if (tolower(a[i]) != tolower(b[i]))
139 				return 0;
140 		a += lena;
141 		b += lena;
142 	}
143 }
144 
145 #ifdef DEBUG
146 static char *
147 name2str(const void *v, char *buf, size_t buflen) {
148 	const unsigned char *a = v;
149 	char *b = buf;
150 	char *eb = buf + buflen;
151 
152 #define ADDC(c) do { \
153 		if (b < eb) \
154 			*b++ = c; \
155 		else \
156 			return NULL; \
157 	} while (/*CONSTCOND*/0)
158 	for (int did = 0;; did++) {
159 		int lena = *a++;
160 		if (lena == 0) {
161 			ADDC('\0');
162 			return buf;
163 		}
164 		if (did)
165 			ADDC('.');
166 		for (int i = 0; i < lena; i++)
167 			ADDC(a[i]);
168 		a += lena;
169 	}
170 }
171 #endif
172 
173 #ifdef __FreeBSD__
174 /* XXX the daemon2_* functions should be in a library */
175 
176 int __daemon2_detach_pipe[2];
177 
178 static int
179 daemon2_fork(void)
180 {
181 	int r;
182 	int fd;
183 	int i;
184 
185 	/*
186 	 * Set up the pipe, making sure the write end does not
187 	 * get allocated one of the file descriptors that will
188 	 * be closed in daemon2_detach().
189 	 */
190 	for (i = 0; i < 3; i++) {
191 	    r = pipe(__daemon2_detach_pipe);
192 	    if (r < 0)
193 		    return -1;
194 	    if (__daemon2_detach_pipe[1] <= STDERR_FILENO &&
195 		(fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
196 		    (void)dup2(fd, __daemon2_detach_pipe[0]);
197 		    (void)dup2(fd, __daemon2_detach_pipe[1]);
198 		    if (fd > STDERR_FILENO)
199 			    (void)close(fd);
200 		    continue;
201 	    }
202 	    break;
203 	}
204 
205 	r = fork();
206 	if (r < 0) {
207 		return -1;
208 	} else if (r == 0) {
209 		/* child */
210 		close(__daemon2_detach_pipe[0]);
211 		return 0;
212        }
213        /* Parent */
214 
215        (void) close(__daemon2_detach_pipe[1]);
216 
217        for (;;) {
218 	       char dummy;
219 	       r = read(__daemon2_detach_pipe[0], &dummy, 1);
220 	       if (r < 0) {
221 		       if (errno == EINTR)
222 			       continue;
223 		       _exit(1);
224 	       } else if (r == 0) {
225 		       _exit(1);
226 	       } else { /* r > 0 */
227 		       _exit(0);
228 	       }
229        }
230 }
231 
232 static int
233 daemon2_detach(int nochdir, int noclose)
234 {
235 	int r;
236 	int fd;
237 
238 	if (setsid() == -1)
239 		return -1;
240 
241 	if (!nochdir)
242 		(void)chdir("/");
243 
244 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
245 		(void)dup2(fd, STDIN_FILENO);
246 		(void)dup2(fd, STDOUT_FILENO);
247 		(void)dup2(fd, STDERR_FILENO);
248 		if (fd > STDERR_FILENO)
249 			(void)close(fd);
250 	}
251 
252 	while (1) {
253 		r = write(__daemon2_detach_pipe[1], "", 1);
254 		if (r < 0) {
255 			if (errno == EINTR)
256 				continue;
257 			/* May get "broken pipe" here if parent is killed */
258 			return -1;
259 		} else if (r == 0) {
260 			/* Should not happen */
261 			return -1;
262 		} else {
263 			break;
264 		}
265 	}
266 
267 	(void) close(__daemon2_detach_pipe[1]);
268 
269 	return 0;
270 }
271 #endif
272 
273 int main(int argc, char **argv) {
274 	int s, r, protocol;
275 	union sockaddr_either saddr;
276 	struct dns_data *dp;
277 	unsigned char *p;
278 	char pidfile_name[40];
279 	FILE *f;
280 	int one = 1;
281 #ifdef DEBUG
282 	char buf1[1024], buf2[1024];
283 #endif
284 
285 #ifdef __FreeBSD__
286 	daemon2_fork();
287 #endif
288 	if (argc < 2 || ((protocol = argv[1][0]) != '4' && protocol != '6'))
289 		errx(1, "usage: dns_server 4 | 6");
290 	s = socket(protocol == '4' ? PF_INET : PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
291 	if (s < 0)
292 		err(1, "socket");
293 	if (protocol == '4') {
294 		memset(&saddr.sin, 0, sizeof(saddr.sin));
295 		saddr.sin.sin_family = AF_INET;
296 		saddr.sin.sin_len = sizeof(saddr.sin);
297 		saddr.sin.sin_port = htons(53);
298 		saddr.sin.sin_addr.s_addr = INADDR_ANY;
299 	} else {
300 		static struct in6_addr loopback = IN6ADDR_LOOPBACK_INIT;
301 		memset(&saddr.sin6, 0, sizeof(saddr.sin6));
302 		saddr.sin6.sin6_family = AF_INET6;
303 		saddr.sin6.sin6_len = sizeof(saddr.sin6);
304 		saddr.sin6.sin6_port = htons(53);
305 		saddr.sin6.sin6_addr = loopback;
306 	}
307 
308 	r = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
309 	if (r < 0)
310 		err(1, "setsockopt");
311 
312 	r = bind(s,
313 		 (struct sockaddr *) &saddr,
314 		 protocol == '4' ? sizeof(struct sockaddr_in) :
315 				   sizeof(struct sockaddr_in6));
316 	if (r < 0)
317 		err(1, "bind");
318 
319 	snprintf(pidfile_name, sizeof pidfile_name,
320 		 "dns_server_%c.pid", protocol);
321 	f = fopen(pidfile_name, "w");
322 	fprintf(f, "%d", getpid());
323 	fclose(f);
324 #ifdef __FreeBSD__
325 #ifdef DEBUG
326 	daemon2_detach(0, 1);
327 #else
328 	daemon2_detach(0, 0);
329 #endif
330 #else
331 #ifdef DEBUG
332 	daemon(0, 1);
333 #else
334 	daemon(0, 0);
335 #endif
336 #endif
337 
338 	for (;;) {
339 		unsigned char buf[512];
340 		union sockaddr_either from;
341 		ssize_t nrecv, nsent;
342 		socklen_t fromlen =
343 			protocol == '4' ? sizeof(struct sockaddr_in) :
344 					  sizeof(struct sockaddr_in6);
345 		memset(buf, 0, sizeof buf);
346 		nrecv = recvfrom(s, buf, sizeof buf, 0, &from.s, &fromlen);
347 		if (nrecv < 0)
348 			err(1, "recvfrom");
349 		if (nrecv < 12) {
350 			DPRINTF("Too short %zd\n", nrecv);
351 			continue;
352 		}
353 		if ((buf[2] & 0x80) != 0) {
354 			DPRINTF("Not a query 0x%x\n", buf[2]);
355 			continue;
356 		}
357 		if (!(buf[4] == 0 && buf[5] == 1)) {
358 			DPRINTF("QCOUNT is not 1 0x%x 0x%x\n", buf[4], buf[5]);
359 			continue; /* QDCOUNT is not 1 */
360 		}
361 
362 		for (dp = data; dp->qname_size != 0; dp++) {
363 			int qtype, qclass;
364 			p = buf + 12; /* Point to QNAME */
365 			int n = name_eq(p, (const unsigned char *) dp->qname);
366 			if (n == 0) {
367 				DPRINTF("no match name %s != %s\n",
368 				    name2str(p, buf1, sizeof(buf1)),
369 				    name2str(dp->qname, buf2, sizeof(buf2)));
370 				continue; /* Name does not match */
371 			}
372 			DPRINTF("match name %s\n",
373 			    name2str(p, buf1, sizeof(buf1)));
374 			p += n; /* Skip QNAME */
375 			qtype = *p++ << 8;
376 			qtype |= *p++;
377 			if (qtype != dp->qtype) {
378 				DPRINTF("no match name 0x%x != 0x%x\n",
379 				    qtype, dp->qtype);
380 				continue;
381 			}
382 			DPRINTF("match type 0x%x\n", qtype);
383 			qclass = *p++ << 8;
384 			qclass |= *p++;
385 			if (qclass != 1) { /* IN */
386 				DPRINTF("no match class %d != 1\n", qclass);
387 				continue;
388 			}
389 			DPRINTF("match class %d\n", qclass);
390 			goto found;
391 		}
392 		continue;
393 	found:
394 		buf[2] |= 0x80; /* QR */
395 		buf[3] |= 0x80; /* RA */
396 		memset(buf + 6, 0, 6); /* Clear ANCOUNT, NSCOUNT, ARCOUNT */
397 		buf[7] = 1; /* ANCOUNT */
398 		memcpy(p, dp->qname, dp->qname_size);
399 		p += dp->qname_size;
400 		*p++ = dp->qtype >> 8;
401 		*p++ = dp->qtype & 0xFF;
402 		*p++ = 0;
403 		*p++ = 1; /* IN */
404 		memset(p, 0, 4); /* TTL = 0 */
405 		p += 4;
406 		*p++ = 0;		/* RDLENGTH MSB */
407 		*p++ = dp->answer_size;	/* RDLENGTH LSB */
408 		memcpy(p, dp->answer, dp->answer_size);
409 		p += dp->answer_size;
410 		nsent = sendto(s, buf, p - buf, 0, &from.s, fromlen);
411 		DPRINTF("sent %zd\n", nsent);
412 		if (nsent != p - buf)
413 			warn("sendto");
414 	}
415 }
416