h_dns_server.c revision 1.2 1 /* $NetBSD: h_dns_server.c,v 1.2 2014/01/06 16:42:57 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.2 2014/01/06 16:42:57 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 <paths.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49
50 #include <sys/socket.h>
51
52 #include <netinet/in.h>
53 #include <netinet6/in6.h>
54
55 union sockaddr_either {
56 struct sockaddr s;
57 struct sockaddr_in sin;
58 struct sockaddr_in6 sin6;
59 };
60
61 /* A DNS question and its corresponding answer */
62
63 struct dns_data {
64 size_t qname_size;
65 const char *qname; /* Wire-encode question name */
66 int qtype;
67 size_t answer_size;
68 const char *answer; /* One wire-encoded answer RDATA */
69 };
70
71 /* Convert C string constant to length + data pair */
72 #define STR_DATA(s) sizeof(s) - 1, s
73
74 /* Canned DNS queestion-answer pairs */
75 struct dns_data data[] = {
76 /* Forward mappings */
77 /* localhost IN A -> 127.0.0.1 */
78 { STR_DATA("\011localhost\000"), 1,
79 STR_DATA("\177\000\000\001") },
80 /* localhost IN AAAA -> ::1 */
81 { STR_DATA("\011localhost\000"), 28,
82 STR_DATA("\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001") },
83 /* sixthavenue.astron.com IN A -> 38.117.134.16 */
84 { STR_DATA("\013sixthavenue\006astron\003com\000"), 1,
85 STR_DATA("\046\165\206\020") },
86 /* sixthavenue.astron.com IN AAAA -> 2620:106:3003:1f00:3e4a:92ff:fef4:e180 */
87 { STR_DATA("\013sixthavenue\006astron\003com\000"), 28,
88 STR_DATA("\x26\x20\x01\x06\x30\x03\x1f\x00\x3e\x4a\x92\xff\xfe\xf4\xe1\x80") },
89 /* Reverse mappings */
90 { STR_DATA("\0011\0010\0010\003127\007in-addr\004arpa\000"), 12,
91 STR_DATA("\011localhost\000") },
92 { STR_DATA("\0011\0010\0010\0010\0010\0010\0010\0010"
93 "\0010\0010\0010\0010\0010\0010\0010\0010"
94 "\0010\0010\0010\0010\0010\0010\0010\0010"
95 "\0010\0010\0010\0010\0010\0010\0010\0010"
96 "\003ip6\004arpa\000"), 12,
97 STR_DATA("\011localhost\000") },
98 { STR_DATA("\00216\003134\003117\00238"
99 "\007in-addr\004arpa\000"), 12,
100 STR_DATA("\013sixthavenue\006astron\003com\000") },
101 { STR_DATA("\0010\0018\0011\001e\0014\001f\001e\001f"
102 "\001f\001f\0012\0019\001a\0014\001e\0013"
103 "\0010\0010\001f\0011\0013\0010\0010\0013"
104 "\0016\0010\0011\0010\0010\0012\0016\0012"
105 "\003ip6\004arpa\000"), 12,
106 STR_DATA("\013sixthavenue\006astron\003com\000") },
107 /* End marker */
108 { STR_DATA(""), 0, STR_DATA("") }
109 };
110
111 /*
112 * Compare two DNS names for equality. If equal, return their
113 * length, and if not, return zero. Does not handle compression.
114 */
115 static int
116 name_eq(const unsigned char *a, const unsigned char *b) {
117 const unsigned char *a_save = a;
118 for (;;) {
119 int i;
120 int lena = *a++;
121 int lenb = *b++;
122 if (lena != lenb)
123 return 0;
124 if (lena == 0)
125 return a - a_save;
126 for (i = 0; i < lena; i++)
127 if (tolower(a[i]) != tolower(b[i]))
128 return 0;
129 a += lena;
130 b += lena;
131 }
132 }
133
134 /* XXX the daemon2_* functions should be in a library */
135
136 int __daemon2_detach_pipe[2];
137
138 static int
139 daemon2_fork(void)
140 {
141 int r;
142 int fd;
143 int i;
144
145 /*
146 * Set up the pipe, making sure the write end does not
147 * get allocated one of the file descriptors that will
148 * be closed in daemon2_detach().
149 */
150 for (i = 0; i < 3; i++) {
151 r = pipe(__daemon2_detach_pipe);
152 if (r < 0)
153 return -1;
154 if (__daemon2_detach_pipe[1] <= STDERR_FILENO &&
155 (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
156 (void)dup2(fd, __daemon2_detach_pipe[0]);
157 (void)dup2(fd, __daemon2_detach_pipe[1]);
158 if (fd > STDERR_FILENO)
159 (void)close(fd);
160 continue;
161 }
162 break;
163 }
164
165 r = fork();
166 if (r < 0) {
167 return -1;
168 } else if (r == 0) {
169 /* child */
170 close(__daemon2_detach_pipe[0]);
171 return 0;
172 }
173 /* Parent */
174
175 (void) close(__daemon2_detach_pipe[1]);
176
177 for (;;) {
178 char dummy;
179 r = read(__daemon2_detach_pipe[0], &dummy, 1);
180 if (r < 0) {
181 if (errno == EINTR)
182 continue;
183 _exit(1);
184 } else if (r == 0) {
185 _exit(1);
186 } else { /* r > 0 */
187 _exit(0);
188 }
189 }
190 }
191
192 static int
193 daemon2_detach(int nochdir, int noclose)
194 {
195 int r;
196 int fd;
197
198 if (setsid() == -1)
199 return -1;
200
201 if (!nochdir)
202 (void)chdir("/");
203
204 if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
205 (void)dup2(fd, STDIN_FILENO);
206 (void)dup2(fd, STDOUT_FILENO);
207 (void)dup2(fd, STDERR_FILENO);
208 if (fd > STDERR_FILENO)
209 (void)close(fd);
210 }
211
212 while (1) {
213 r = write(__daemon2_detach_pipe[1], "", 1);
214 if (r < 0) {
215 if (errno == EINTR)
216 continue;
217 /* May get "broken pipe" here if parent is killed */
218 return -1;
219 } else if (r == 0) {
220 /* Should not happen */
221 return -1;
222 } else {
223 break;
224 }
225 }
226
227 (void) close(__daemon2_detach_pipe[1]);
228
229 return 0;
230 }
231
232 int main(int argc, char **argv) {
233 int s, r, protocol;
234 union sockaddr_either saddr;
235 struct dns_data *dp;
236 unsigned char *p;
237 char pidfile_name[40];
238 FILE *f;
239 int one = 1;
240
241 daemon2_fork();
242
243 if (argc < 2 || ((protocol = argv[1][0]) != '4' && protocol != '6'))
244 errx(1, "usage: dns_server 4 | 6");
245 s = socket(protocol == '4' ? PF_INET : PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
246 if (s < 0)
247 err(1, "socket");
248 if (protocol == '4') {
249 memset(&saddr.sin, 0, sizeof(saddr.sin));
250 saddr.sin.sin_family = AF_INET;
251 saddr.sin.sin_len = sizeof(saddr.sin);
252 saddr.sin.sin_port = htons(53);
253 saddr.sin.sin_addr.s_addr = INADDR_ANY;
254 } else {
255 static struct in6_addr loopback = IN6ADDR_LOOPBACK_INIT;
256 memset(&saddr.sin6, 0, sizeof(saddr.sin6));
257 saddr.sin6.sin6_family = AF_INET6;
258 saddr.sin6.sin6_len = sizeof(saddr.sin6);
259 saddr.sin6.sin6_port = htons(53);
260 saddr.sin6.sin6_addr = loopback;
261 }
262
263 r = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
264 if (r < 0)
265 err(1, "setsockopt");
266
267 r = bind(s,
268 (struct sockaddr *) &saddr,
269 protocol == '4' ? sizeof(struct sockaddr_in) :
270 sizeof(struct sockaddr_in6));
271 if (r < 0)
272 err(1, "bind");
273
274 snprintf(pidfile_name, sizeof pidfile_name,
275 "dns_server_%c.pid", protocol);
276 f = fopen(pidfile_name, "w");
277 fprintf(f, "%d", getpid());
278 fclose(f);
279 daemon2_detach(0, 0);
280
281 for (;;) {
282 unsigned char buf[512];
283 union sockaddr_either from;
284 ssize_t nrecv, nsent;
285 socklen_t fromlen =
286 protocol == '4' ? sizeof(struct sockaddr_in) :
287 sizeof(struct sockaddr_in6);
288 memset(buf, 0, sizeof buf);
289 nrecv = recvfrom(s, buf, sizeof buf, 0, &from.s, &fromlen);
290 if (nrecv < 0)
291 err(1, "recvfrom");
292 if (nrecv < 12)
293 continue; /* Too short */
294 if ((buf[2] & 0x80) != 0)
295 continue; /* Not a query */
296 if (!(buf[4] == 0 && buf[5] == 1))
297 continue; /* QDCOUNT is not 1 */
298
299 for (dp = data; dp->qname_size != 0; dp++) {
300 int qtype, qclass;
301 p = buf + 12; /* Point to QNAME */
302 int n = name_eq(p, (const unsigned char *) dp->qname);
303 if (n == 0)
304 continue; /* Name does not match */
305 p += n; /* Skip QNAME */
306 qtype = *p++ << 8;
307 qtype |= *p++;
308 if (qtype != dp->qtype)
309 continue;
310 qclass = *p++ << 8;
311 qclass |= *p++;
312 if (qclass != 1) /* IN */
313 continue;
314 goto found;
315 }
316 continue;
317 found:
318 buf[2] |= 0x80; /* QR */
319 buf[3] |= 0x80; /* RA */
320 memset(buf + 6, 0, 6); /* Clear ANCOUNT, NSCOUNT, ARCOUNT */
321 buf[7] = 1; /* ANCOUNT */
322 memcpy(p, dp->qname, dp->qname_size);
323 p += dp->qname_size;
324 *p++ = dp->qtype >> 8;
325 *p++ = dp->qtype & 0xFF;
326 *p++ = 0;
327 *p++ = 1; /* IN */
328 memset(p, 0, 4); /* TTL = 0 */
329 p += 4;
330 *p++ = 0; /* RDLENGTH MSB */
331 *p++ = dp->answer_size; /* RDLENGTH LSB */
332 memcpy(p, dp->answer, dp->answer_size);
333 p += dp->answer_size;
334 nsent = sendto(s, buf, p - buf, 0, &from.s, fromlen);
335 if (nsent != p - buf)
336 warn("sendto");
337 }
338 }
339