Initial public busybox upstream commit
[busybox4maemo] / networking / dnsd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini DNS server implementation for busybox
4  *
5  * Copyright (C) 2005 Roberto A. Foglietta (me@roberto.foglietta.name)
6  * Copyright (C) 2005 Odd Arild Olsen (oao at fibula dot no)
7  * Copyright (C) 2003 Paul Sheer
8  *
9  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
10  *
11  * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote
12  * it into a shape which I believe is both easier to understand and maintain.
13  * I also reused the input buffer for output and removed services he did not
14  * need.  [1] http://threading.2038bug.com/sheerdns/
15  *
16  * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
17  * the first porting of oao' scdns to busybox also.
18  */
19
20 #include "libbb.h"
21 #include <syslog.h>
22
23 //#define DEBUG 1
24 #define DEBUG 0
25
26 enum {
27         MAX_HOST_LEN = 16,      // longest host name allowed is 15
28         IP_STRING_LEN = 18,     // .xxx.xxx.xxx.xxx\0
29
30 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
31         MAX_NAME_LEN = (IP_STRING_LEN + 13),
32
33 /* Cannot get bigger packets than 512 per RFC1035
34    In practice this can be set considerably smaller:
35    Length of response packet is  header (12B) + 2*type(4B) + 2*class(4B) +
36    ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
37    2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
38 */
39         MAX_PACK_LEN = 512,
40
41         DEFAULT_TTL = 30,       // increase this when not testing?
42
43         REQ_A = 1,
44         REQ_PTR = 12
45 };
46
47 struct dns_head {               // the message from client and first part of response mag
48         uint16_t id;
49         uint16_t flags;
50         uint16_t nquer;         // accepts 0
51         uint16_t nansw;         // 1 in response
52         uint16_t nauth;         // 0
53         uint16_t nadd;          // 0
54 };
55 struct dns_prop {
56         uint16_t type;
57         uint16_t class;
58 };
59 struct dns_entry {              // element of known name, ip address and reversed ip address
60         struct dns_entry *next;
61         char ip[IP_STRING_LEN];         // dotted decimal IP
62         char rip[IP_STRING_LEN];        // length decimal reversed IP
63         char name[MAX_HOST_LEN];
64 };
65
66 static struct dns_entry *dnsentry;
67 static uint32_t ttl = DEFAULT_TTL;
68
69 static const char *fileconf = "/etc/dnsd.conf";
70
71 // Must match getopt32 call
72 #define OPT_daemon  (option_mask32 & 0x10)
73 #define OPT_verbose (option_mask32 & 0x20)
74
75
76 /*
77  * Convert host name from C-string to dns length/string.
78  */
79 static void convname(char *a, uint8_t *q)
80 {
81         int i = (q[0] == '.') ? 0 : 1;
82         for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
83                 a[i] = tolower(*q);
84         a[0] = i - 1;
85         a[i] = 0;
86 }
87
88 /*
89  * Insert length of substrings instead of dots
90  */
91 static void undot(uint8_t * rip)
92 {
93         int i = 0, s = 0;
94         while (rip[i])
95                 i++;
96         for (--i; i >= 0; i--) {
97                 if (rip[i] == '.') {
98                         rip[i] = s;
99                         s = 0;
100                 } else s++;
101         }
102 }
103
104 /*
105  * Read one line of hostname/IP from file
106  * Returns 0 for each valid entry read, -1 at EOF
107  * Assumes all host names are lower case only
108  * Hostnames with more than one label are not handled correctly.
109  * Presently the dot is copied into name without
110  * converting to a length/string substring for that label.
111  */
112 static int getfileentry(FILE * fp, struct dns_entry *s)
113 {
114         unsigned int a,b,c,d;
115         char *line, *r, *name;
116
117  restart:
118         line = r = xmalloc_fgets(fp);
119         if (!r)
120                 return -1;
121         while (*r == ' ' || *r == '\t') {
122                 r++;
123                 if (!*r || *r == '#' || *r == '\n') {
124                         free(line);
125                         goto restart; /* skipping empty/blank and commented lines  */
126                 }
127         }
128         name = r;
129         while (*r != ' ' && *r != '\t')
130                 r++;
131         *r++ = '\0';
132         if (sscanf(r, ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4) {
133                 free(line);
134                 goto restart; /* skipping wrong lines */
135         }
136
137         sprintf(s->ip, ".%u.%u.%u.%u"+1, a, b, c, d);
138         sprintf(s->rip, ".%u.%u.%u.%u", d, c, b, a);
139         undot((uint8_t*)s->rip);
140         convname(s->name, (uint8_t*)name);
141
142         if (OPT_verbose)
143                 fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
144
145         free(line);
146         return 0;
147 }
148
149 /*
150  * Read hostname/IP records from file
151  */
152 static void dnsentryinit(void)
153 {
154         FILE *fp;
155         struct dns_entry *m, *prev;
156
157         prev = dnsentry = NULL;
158         fp = xfopen(fileconf, "r");
159
160         while (1) {
161                 m = xzalloc(sizeof(*m));
162                 /*m->next = NULL;*/
163                 if (getfileentry(fp, m))
164                         break;
165
166                 if (prev == NULL)
167                         dnsentry = m;
168                 else
169                         prev->next = m;
170                 prev = m;
171         }
172         fclose(fp);
173 }
174
175 /*
176  * Look query up in dns records and return answer if found
177  * qs is the query string, first byte the string length
178  */
179 static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
180 {
181         int i;
182         struct dns_entry *d = dnsentry;
183
184         do {
185 #if DEBUG
186                 char *p,*q;
187                 q = (char *)&(qs[1]);
188                 p = &(d->name[1]);
189                 fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
190                         __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
191                         p, q, (int)strlen(q));
192 #endif
193                 if (type == REQ_A) { /* search by host name */
194                         for (i = 1; i <= (int)(d->name[0]); i++)
195                                 if (tolower(qs[i]) != d->name[i])
196                                         break;
197                         if (i > (int)(d->name[0])) {
198                                 strcpy((char *)as, d->ip);
199 #if DEBUG
200                                 fprintf(stderr, " OK as:%s\n", as);
201 #endif
202                                 return 0;
203                         }
204                 } else if (type == REQ_PTR) { /* search by IP-address */
205                         if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
206                                 strcpy((char *)as, d->name);
207                                 return 0;
208                         }
209                 }
210                 d = d->next;
211         } while (d);
212         return -1;
213 }
214
215 /*
216  * Decode message and generate answer
217  */
218 static int process_packet(uint8_t *buf)
219 {
220         uint8_t answstr[MAX_NAME_LEN + 1];
221         struct dns_head *head;
222         struct dns_prop *qprop;
223         uint8_t *from, *answb;
224         uint16_t outr_rlen;
225         uint16_t outr_flags;
226         uint16_t flags;
227         int lookup_result, type, packet_len;
228         int querystr_len;
229
230         answstr[0] = '\0';
231
232         head = (struct dns_head *)buf;
233         if (head->nquer == 0) {
234                 bb_error_msg("no queries");
235                 return -1;
236         }
237
238         if (head->flags & 0x8000) {
239                 bb_error_msg("ignoring response packet");
240                 return -1;
241         }
242
243         from = (void *)&head[1];        //  start of query string
244 //FIXME: strlen of untrusted data??!
245         querystr_len = strlen((char *)from) + 1 + sizeof(struct dns_prop);
246         answb = from + querystr_len;   // where to append answer block
247
248         outr_rlen = 0;
249         outr_flags = 0;
250
251         qprop = (struct dns_prop *)(answb - 4);
252         type = ntohs(qprop->type);
253
254         // only let REQ_A and REQ_PTR pass
255         if (!(type == REQ_A || type == REQ_PTR)) {
256                 goto empty_packet;      /* we can't handle the query type */
257         }
258
259         if (ntohs(qprop->class) != 1 /* class INET */ ) {
260                 outr_flags = 4; /* not supported */
261                 goto empty_packet;
262         }
263         /* we only support standard queries */
264
265         if ((ntohs(head->flags) & 0x7800) != 0)
266                 goto empty_packet;
267
268         // We have a standard query
269         bb_info_msg("%s", (char *)from);
270         lookup_result = table_lookup(type, answstr, from);
271         if (lookup_result != 0) {
272                 outr_flags = 3 | 0x0400;        // name do not exist and auth
273                 goto empty_packet;
274         }
275         if (type == REQ_A) {    // return an address
276                 struct in_addr a; // NB! its "struct { unsigned __long__ s_addr; }"
277                 uint32_t v32;
278                 if (!inet_aton((char*)answstr, &a)) { //dotted dec to long conv
279                         outr_flags = 1; /* Frmt err */
280                         goto empty_packet;
281                 }
282                 v32 = a.s_addr; /* in case long != int */
283                 memcpy(answstr, &v32, 4);
284                 outr_rlen = 4;                  // uint32_t IP
285         } else
286                 outr_rlen = strlen((char *)answstr) + 1;        // a host name
287         outr_flags |= 0x0400;                   /* authority-bit */
288         // we have an answer
289         head->nansw = htons(1);
290
291         // copy query block to answer block
292         memcpy(answb, from, querystr_len);
293         answb += querystr_len;
294
295         // and append answer rr
296 // FIXME: unaligned accesses??
297         *(uint32_t *) answb = htonl(ttl);
298         answb += 4;
299         *(uint16_t *) answb = htons(outr_rlen);
300         answb += 2;
301         memcpy(answb, answstr, outr_rlen);
302         answb += outr_rlen;
303
304  empty_packet:
305
306         flags = ntohs(head->flags);
307         // clear rcode and RA, set responsebit and our new flags
308         flags |= (outr_flags & 0xff80) | 0x8000;
309         head->flags = htons(flags);
310         head->nauth = head->nadd = 0;
311         head->nquer = htons(1);
312
313         packet_len = answb - buf;
314         return packet_len;
315 }
316
317 /*
318  * Exit on signal
319  */
320 static void interrupt(int sig)
321 {
322         /* unlink("/var/run/dnsd.lock"); */
323         bb_error_msg("interrupt, exiting\n");
324         kill_myself_with_sig(sig);
325 }
326
327 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
328 int dnsd_main(int argc ATTRIBUTE_UNUSED, char **argv)
329 {
330         const char *listen_interface = "0.0.0.0";
331         char *sttl, *sport;
332         len_and_sockaddr *lsa, *from, *to;
333         unsigned lsa_size;
334         int udps;
335         uint16_t port = 53;
336         /* Paranoid sizing: querystring x2 + ttl + outr_rlen + answstr */
337         /* I'd rather see process_packet() fixed instead... */
338         uint8_t buf[MAX_PACK_LEN * 2 + 4 + 2 + (MAX_NAME_LEN+1)];
339
340         getopt32(argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
341         //if (option_mask32 & 0x1) // -i
342         //if (option_mask32 & 0x2) // -c
343         if (option_mask32 & 0x4) // -t
344                 ttl = xatou_range(sttl, 1, 0xffffffff);
345         if (option_mask32 & 0x8) // -p
346                 port = xatou_range(sport, 1, 0xffff);
347
348         if (OPT_verbose) {
349                 bb_info_msg("listen_interface: %s", listen_interface);
350                 bb_info_msg("ttl: %d, port: %d", ttl, port);
351                 bb_info_msg("fileconf: %s", fileconf);
352         }
353
354         if (OPT_daemon) {
355                 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
356                 openlog(applet_name, LOG_PID, LOG_DAEMON);
357                 logmode = LOGMODE_SYSLOG;
358         }
359
360         dnsentryinit();
361
362         signal(SIGINT, interrupt);
363         bb_signals(0
364                 /* why? + (1 << SIGPIPE) */
365                 + (1 << SIGHUP)
366 #ifdef SIGTSTP
367                 + (1 << SIGTSTP)
368 #endif
369 #ifdef SIGURG
370                 + (1 << SIGURG)
371 #endif
372                 , SIG_IGN);
373
374         lsa = xdotted2sockaddr(listen_interface, port);
375         udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
376         xbind(udps, &lsa->u.sa, lsa->len);
377         socket_want_pktinfo(udps); /* needed for recv_from_to to work */
378         lsa_size = LSA_LEN_SIZE + lsa->len;
379         from = xzalloc(lsa_size);
380         to = xzalloc(lsa_size);
381
382         bb_info_msg("Accepting UDP packets on %s",
383                         xmalloc_sockaddr2dotted(&lsa->u.sa));
384
385         while (1) {
386                 int r;
387                 /* Try to get *DEST* address (to which of our addresses
388                  * this query was directed), and reply from the same address.
389                  * Or else we can exhibit usual UDP ugliness:
390                  * [ip1.multihomed.ip2] <=  query to ip1  <= peer
391                  * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
392                 memcpy(to, lsa, lsa_size);
393                 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
394                 if (r < 12 || r > MAX_PACK_LEN) {
395                         bb_error_msg("invalid packet size");
396                         continue;
397                 }
398                 if (OPT_verbose)
399                         bb_info_msg("Got UDP packet");
400                 buf[r] = '\0'; /* paranoia */
401                 r = process_packet(buf);
402                 if (r <= 0)
403                         continue;
404                 send_to_from(udps, buf, r, 0, &to->u.sa, &from->u.sa, lsa->len);
405         }
406         return 0;
407 }