fix #>&- syntax for closing fds
[oweals/busybox.git] / 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 #define OPT_verbose (option_mask32)
67
68
69 /*
70  * Convert host name from C-string to dns length/string.
71  */
72 static void convname(char *a, uint8_t *q)
73 {
74         int i = (q[0] == '.') ? 0 : 1;
75         for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
76                 a[i] = tolower(*q);
77         a[0] = i - 1;
78         a[i] = 0;
79 }
80
81 /*
82  * Insert length of substrings instead of dots
83  */
84 static void undot(uint8_t *rip)
85 {
86         int i = 0, s = 0;
87         while (rip[i])
88                 i++;
89         for (--i; i >= 0; i--) {
90                 if (rip[i] == '.') {
91                         rip[i] = s;
92                         s = 0;
93                 } else s++;
94         }
95 }
96
97 /*
98  * Read hostname/IP records from file
99  */
100 static struct dns_entry *parse_conf_file(const char *fileconf)
101 {
102         char *token[2];
103         parser_t *parser;
104         struct dns_entry *m, *prev, *conf_data;
105
106         prev = conf_data = NULL;
107         parser = config_open(fileconf);
108         while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
109                 unsigned a, b, c, d;
110                 /*
111                  * Assumes all host names are lower case only
112                  * Hostnames with more than one label are not handled correctly.
113                  * Presently the dot is copied into name without
114                  * converting to a length/string substring for that label.
115                  */
116 //              if (!token[1] || sscanf(token[1], ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4)
117                 if (sscanf(token[1], ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4)
118                         continue;
119
120                 m = xzalloc(sizeof(*m));
121                 /*m->next = NULL;*/
122                 sprintf(m->ip, ".%u.%u.%u.%u"+1, a, b, c, d);
123                 sprintf(m->rip, ".%u.%u.%u.%u", d, c, b, a);
124                 undot((uint8_t*)m->rip);
125                 convname(m->name, (uint8_t*)token[0]);
126
127                 if (OPT_verbose)
128                         bb_error_msg("name:%s, ip:%s", &(m->name[1]), m->ip);
129
130                 if (prev == NULL)
131                         conf_data = m;
132                 else
133                         prev->next = m;
134                 prev = m;
135         }
136         config_close(parser);
137         return conf_data;
138 }
139
140 /*
141  * Look query up in dns records and return answer if found
142  * qs is the query string, first byte the string length
143  */
144 static int table_lookup(struct dns_entry *d, uint16_t type, uint8_t *as, uint8_t *qs)
145 {
146         int i;
147
148         do {
149 #if DEBUG
150                 char *p, *q;
151                 q = (char *)&(qs[1]);
152                 p = &(d->name[1]);
153                 fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
154                         __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
155                         p, q, (int)strlen(q));
156 #endif
157                 if (type == REQ_A) {
158                         /* search by host name */
159                         for (i = 1; i <= (int)(d->name[0]); i++)
160                                 if (tolower(qs[i]) != d->name[i])
161                                         break;
162                         if (i > (int)(d->name[0])
163                          || (d->name[0] == 1 && d->name[1] == '*')
164                         ) {
165                                 strcpy((char *)as, d->ip);
166 #if DEBUG
167                                 fprintf(stderr, " OK as:%s\n", as);
168 #endif
169                                 return 0;
170                         }
171                 } else if (type == REQ_PTR) {
172                         /* search by IP-address */
173                         if ((d->name[0] != 1 || d->name[1] != '*')
174                          && !strncmp(d->rip + 1, (char*)qs + 1, strlen(d->rip)-1)
175                         ) {
176                                 strcpy((char *)as, d->name);
177                                 return 0;
178                         }
179                 }
180                 d = d->next;
181         } while (d);
182         return -1;
183 }
184
185 /*
186  * Decode message and generate answer
187  */
188 static int process_packet(struct dns_entry *conf_data, uint32_t conf_ttl, uint8_t *buf)
189 {
190         uint8_t answstr[MAX_NAME_LEN + 1];
191         struct dns_head *head;
192         struct dns_prop *qprop;
193         uint8_t *from, *answb;
194         uint16_t outr_rlen;
195         uint16_t outr_flags;
196         uint16_t flags;
197         int lookup_result, type, packet_len;
198         int querystr_len;
199
200         answstr[0] = '\0';
201
202         head = (struct dns_head *)buf;
203         if (head->nquer == 0) {
204                 bb_error_msg("no queries");
205                 return -1;
206         }
207
208         if (head->flags & 0x8000) {
209                 bb_error_msg("ignoring response packet");
210                 return -1;
211         }
212
213         from = (void *)&head[1];        //  start of query string
214 //FIXME: strlen of untrusted data??!
215         querystr_len = strlen((char *)from) + 1 + sizeof(struct dns_prop);
216         answb = from + querystr_len;   // where to append answer block
217
218         outr_rlen = 0;
219         outr_flags = 0;
220
221         qprop = (struct dns_prop *)(answb - 4);
222         type = ntohs(qprop->type);
223
224         // only let REQ_A and REQ_PTR pass
225         if (!(type == REQ_A || type == REQ_PTR)) {
226                 goto empty_packet;      /* we can't handle the query type */
227         }
228
229         if (ntohs(qprop->class) != 1 /* class INET */ ) {
230                 outr_flags = 4; /* not supported */
231                 goto empty_packet;
232         }
233         /* we only support standard queries */
234
235         if ((ntohs(head->flags) & 0x7800) != 0)
236                 goto empty_packet;
237
238         // We have a standard query
239         bb_info_msg("%s", (char *)from);
240         lookup_result = table_lookup(conf_data, type, answstr, from);
241         if (lookup_result != 0) {
242                 outr_flags = 3 | 0x0400;        // name do not exist and auth
243                 goto empty_packet;
244         }
245         if (type == REQ_A) {    // return an address
246                 struct in_addr a; // NB! its "struct { unsigned __long__ s_addr; }"
247                 uint32_t v32;
248                 if (!inet_aton((char*)answstr, &a)) { //dotted dec to long conv
249                         outr_flags = 1; /* Frmt err */
250                         goto empty_packet;
251                 }
252                 v32 = a.s_addr; /* in case long != int */
253                 move_to_unaligned32(answstr, v32);
254                 outr_rlen = 4;                  // uint32_t IP
255         } else
256                 outr_rlen = strlen((char *)answstr) + 1;        // a host name
257         outr_flags |= 0x0400;                   /* authority-bit */
258         // we have an answer
259         head->nansw = htons(1);
260
261         // copy query block to answer block
262         memcpy(answb, from, querystr_len);
263         answb += querystr_len;
264
265         // and append answer rr
266 // FIXME: unaligned accesses??
267         *(uint32_t *) answb = htonl(conf_ttl);
268         answb += 4;
269         *(uint16_t *) answb = htons(outr_rlen);
270         answb += 2;
271         memcpy(answb, answstr, outr_rlen);
272         answb += outr_rlen;
273
274  empty_packet:
275
276         flags = ntohs(head->flags);
277         // clear rcode and RA, set responsebit and our new flags
278         flags |= (outr_flags & 0xff80) | 0x8000;
279         head->flags = htons(flags);
280         head->nauth = head->nadd = 0;
281         head->nquer = htons(1);
282
283         packet_len = answb - buf;
284         return packet_len;
285 }
286
287 /*
288  * Exit on signal
289  */
290 //static void interrupt(int sig)
291 //{
292 //      /* unlink("/var/run/dnsd.lock"); */
293 //      bb_error_msg("interrupt, exiting\n");
294 //      kill_myself_with_sig(sig);
295 //}
296
297 int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
298 int dnsd_main(int argc UNUSED_PARAM, char **argv)
299 {
300         const char *listen_interface = "0.0.0.0";
301         const char *fileconf = "/etc/dnsd.conf";
302         struct dns_entry *conf_data;
303         uint32_t conf_ttl = DEFAULT_TTL;
304         char *sttl, *sport;
305         len_and_sockaddr *lsa, *from, *to;
306         unsigned lsa_size;
307         int udps, opts;
308         uint16_t port = 53;
309         /* Paranoid sizing: querystring x2 + ttl + outr_rlen + answstr */
310         /* I'd rather see process_packet() fixed instead... */
311         uint8_t buf[MAX_PACK_LEN * 2 + 4 + 2 + (MAX_NAME_LEN+1)];
312
313         opts = getopt32(argv, "vi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
314         //if (opts & 0x1) // -v
315         //if (opts & 0x2) // -i
316         //if (opts & 0x4) // -c
317         if (opts & 0x8) // -t
318                 conf_ttl = xatou_range(sttl, 1, 0xffffffff);
319         if (opts & 0x10) // -p
320                 port = xatou_range(sport, 1, 0xffff);
321         if (opts & 0x20) { // -d
322                 bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
323                 openlog(applet_name, LOG_PID, LOG_DAEMON);
324                 logmode = LOGMODE_SYSLOG;
325         }
326         /* Clear all except "verbose" bit */
327         option_mask32 &= 1;
328
329         conf_data = parse_conf_file(fileconf);
330
331 //      signal(SIGINT, interrupt); - just for one message?
332         bb_signals(0
333                 /* why? + (1 << SIGPIPE) */
334                 + (1 << SIGHUP)
335 #ifdef SIGTSTP
336                 + (1 << SIGTSTP)
337 #endif
338 #ifdef SIGURG
339                 + (1 << SIGURG)
340 #endif
341                 , SIG_IGN);
342
343         lsa = xdotted2sockaddr(listen_interface, port);
344         udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
345         xbind(udps, &lsa->u.sa, lsa->len);
346         socket_want_pktinfo(udps); /* needed for recv_from_to to work */
347         lsa_size = LSA_LEN_SIZE + lsa->len;
348         from = xzalloc(lsa_size);
349         to = xzalloc(lsa_size);
350
351         bb_info_msg("Accepting UDP packets on %s",
352                         xmalloc_sockaddr2dotted(&lsa->u.sa));
353
354         while (1) {
355                 int r;
356                 /* Try to get *DEST* address (to which of our addresses
357                  * this query was directed), and reply from the same address.
358                  * Or else we can exhibit usual UDP ugliness:
359                  * [ip1.multihomed.ip2] <=  query to ip1  <= peer
360                  * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
361                 memcpy(to, lsa, lsa_size);
362                 r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
363                 if (r < 12 || r > MAX_PACK_LEN) {
364                         bb_error_msg("invalid packet size");
365                         continue;
366                 }
367                 if (OPT_verbose)
368                         bb_info_msg("Got UDP packet");
369                 buf[r] = '\0'; /* paranoia */
370                 r = process_packet(conf_data, conf_ttl, buf);
371                 if (r <= 0)
372                         continue;
373                 send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
374         }
375         return 0;
376 }