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