dnsd: getfileentry was leaking memory
[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 "busybox.h"
21
22 static const char *fileconf = "/etc/dnsd.conf";
23 #define LOCK_FILE       "/var/run/dnsd.lock"
24
25 // Must match getopt32 call
26 #define OPT_daemon  (option_mask32 & 0x10)
27 #define OPT_verbose (option_mask32 & 0x20)
28
29 //#define DEBUG 1
30 #define DEBUG 0
31
32 enum {
33         MAX_HOST_LEN = 16,      // longest host name allowed is 15
34         IP_STRING_LEN = 18,     // .xxx.xxx.xxx.xxx\0
35
36 //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
37         MAX_NAME_LEN = (IP_STRING_LEN + 13),
38
39 /* Cannot get bigger packets than 512 per RFC1035
40    In practice this can be set considerably smaller:
41    Length of response packet is  header (12B) + 2*type(4B) + 2*class(4B) +
42    ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
43    2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
44 */
45         MAX_PACK_LEN = 512 + 1,
46
47         DEFAULT_TTL = 30,       // increase this when not testing?
48
49         REQ_A = 1,
50         REQ_PTR = 12
51 };
52
53 struct dns_repl {               // resource record, add 0 or 1 to accepted dns_msg in resp
54         uint16_t rlen;
55         uint8_t *r;             // resource
56         uint16_t flags;
57 };
58
59 struct dns_head {               // the message from client and first part of response mag
60         uint16_t id;
61         uint16_t flags;
62         uint16_t nquer;         // accepts 0
63         uint16_t nansw;         // 1 in response
64         uint16_t nauth;         // 0
65         uint16_t nadd;          // 0
66 };
67 struct dns_prop {
68         uint16_t type;
69         uint16_t class;
70 };
71 struct dns_entry {              // element of known name, ip address and reversed ip address
72         struct dns_entry *next;
73         char ip[IP_STRING_LEN];         // dotted decimal IP
74         char rip[IP_STRING_LEN];        // length decimal reversed IP
75         char name[MAX_HOST_LEN];
76 };
77
78 static struct dns_entry *dnsentry = NULL;
79 static uint32_t ttl = DEFAULT_TTL;
80
81 /*
82  * Convert host name from C-string to dns length/string.
83  */
84 static void convname(char *a, uint8_t *q)
85 {
86         int i = (q[0] == '.') ? 0 : 1;
87         for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
88                 a[i] = tolower(*q);
89         a[0] = i - 1;
90         a[i] = 0;
91 }
92
93 /*
94  * Insert length of substrings instead of dots
95  */
96 static void undot(uint8_t * rip)
97 {
98         int i = 0, s = 0;
99         while (rip[i])
100                 i++;
101         for (--i; i >= 0; i--) {
102                 if (rip[i] == '.') {
103                         rip[i] = s;
104                         s = 0;
105                 } else s++;
106         }
107 }
108
109 /*
110  * Read one line of hostname/IP from file
111  * Returns 0 for each valid entry read, -1 at EOF
112  * Assumes all host names are lower case only
113  * Hostnames with more than one label are not handled correctly.
114  * Presently the dot is copied into name without
115  * converting to a length/string substring for that label.
116  */
117
118 static int getfileentry(FILE * fp, struct dns_entry *s)
119 {
120         unsigned int a,b,c,d;
121         char *line, *r, *name;
122
123  restart:
124         line = r = xmalloc_fgets(fp);
125         if (!r)
126                 return -1;
127         while (*r == ' ' || *r == '\t') {
128                 r++;
129                 if (!*r || *r == '#' || *r == '\n') {
130                         free(line);
131                         goto restart; /* skipping empty/blank and commented lines  */
132                 }
133         }
134         name = r;
135         while (*r != ' ' && *r != '\t')
136                 r++;
137         *r++ = '\0';
138         if (sscanf(r, "%u.%u.%u.%u", &a, &b, &c, &d) != 4) {
139                 free(line);
140                 goto restart; /* skipping wrong lines */
141         }
142
143         sprintf(s->ip, "%u.%u.%u.%u", a, b, c, d);
144         sprintf(s->rip, ".%u.%u.%u.%u", d, c, b, a);
145         undot((uint8_t*)s->rip);
146         convname(s->name, (uint8_t*)name);
147
148         if (OPT_verbose)
149                 fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
150
151         free(line);
152         return 0;
153 }
154
155 /*
156  * Read hostname/IP records from file
157  */
158 static void dnsentryinit(void)
159 {
160         FILE *fp;
161         struct dns_entry *m, *prev;
162
163         prev = dnsentry = NULL;
164         fp = xfopen(fileconf, "r");
165
166         while (1) {
167                 m = xzalloc(sizeof(*m));
168                 /*m->next = NULL;*/
169                 if (getfileentry(fp, m))
170                         break;
171
172                 if (prev == NULL)
173                         dnsentry = m;
174                 else
175                         prev->next = m;
176                 prev = m;
177         }
178         fclose(fp);
179 }
180
181 /*
182  * Look query up in dns records and return answer if found
183  * qs is the query string, first byte the string length
184  */
185 static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
186 {
187         int i;
188         struct dns_entry *d=dnsentry;
189
190         do {
191 #if DEBUG
192                 char *p,*q;
193                 q = (char *)&(qs[1]);
194                 p = &(d->name[1]);
195                 fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
196                         __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
197                         p, q, (int)strlen(q));
198 #endif
199                 if (type == REQ_A) { /* search by host name */
200                         for (i = 1; i <= (int)(d->name[0]); i++)
201                                 if (tolower(qs[i]) != d->name[i])
202                                         break;
203                         if (i > (int)(d->name[0])) {
204 #if DEBUG
205                                 fprintf(stderr, " OK");
206 #endif
207                                 strcpy((char *)as, d->ip);
208 #if DEBUG
209                                 fprintf(stderr, " as:%s\n", as);
210 #endif
211                                         return 0;
212                         }
213                 } else
214                 if (type == REQ_PTR) { /* search by IP-address */
215                         if (!strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
216                                 strcpy((char *)as, d->name);
217                                 return 0;
218                         }
219                 }
220                 d = d->next;
221         } while (d);
222         return -1;
223 }
224
225
226 /*
227  * Decode message and generate answer
228  */
229 #define eret(s) do { fputs(s, stderr); return -1; } while (0)
230 static int process_packet(uint8_t * buf)
231 {
232         struct dns_head *head;
233         struct dns_prop *qprop;
234         struct dns_repl outr;
235         void *next, *from, *answb;
236
237         uint8_t answstr[MAX_NAME_LEN + 1];
238         int lookup_result, type, len, packet_len;
239         uint16_t flags;
240
241         answstr[0] = '\0';
242
243         head = (struct dns_head *)buf;
244         if (head->nquer == 0)
245                 eret("no queries\n");
246
247         if (head->flags & 0x8000)
248                 eret("ignoring response packet\n");
249
250         from = (void *)&head[1];        //  start of query string
251         next = answb = from + strlen((char *)from) + 1 + sizeof(struct dns_prop);   // where to append answer block
252
253         outr.rlen = 0;                  // may change later
254         outr.r = NULL;
255         outr.flags = 0;
256
257         qprop = (struct dns_prop *)(answb - 4);
258         type = ntohs(qprop->type);
259
260         // only let REQ_A and REQ_PTR pass
261         if (!(type == REQ_A || type == REQ_PTR)) {
262                 goto empty_packet;      /* we can't handle the query type */
263         }
264
265         if (ntohs(qprop->class) != 1 /* class INET */ ) {
266                 outr.flags = 4; /* not supported */
267                 goto empty_packet;
268         }
269         /* we only support standard queries */
270
271         if ((ntohs(head->flags) & 0x7800) != 0)
272                 goto empty_packet;
273
274         // We have a standard query
275         bb_info_msg("%s", (char *)from);
276         lookup_result = table_lookup(type, answstr, (uint8_t*)from);
277         if (lookup_result != 0) {
278                 outr.flags = 3 | 0x0400;        //name do not exist and auth
279                 goto empty_packet;
280         }
281         if (type == REQ_A) {    // return an address
282                 struct in_addr a;
283                 if (!inet_aton((char*)answstr, &a)) {//dotted dec to long conv
284                         outr.flags = 1; /* Frmt err */
285                         goto empty_packet;
286                 }
287                 memcpy(answstr, &a.s_addr, 4);  // save before a disappears
288                 outr.rlen = 4;                  // uint32_t IP
289         }
290         else
291                 outr.rlen = strlen((char *)answstr) + 1;        // a host name
292         outr.r = answstr;                       // 32 bit ip or a host name
293         outr.flags |= 0x0400;                   /* authority-bit */
294         // we have an answer
295         head->nansw = htons(1);
296
297         // copy query block to answer block
298         len = answb - from;
299         memcpy(answb, from, len);
300         next += len;
301
302         // and append answer rr
303         *(uint32_t *) next = htonl(ttl);
304         next += 4;
305         *(uint16_t *) next = htons(outr.rlen);
306         next += 2;
307         memcpy(next, (void *)answstr, outr.rlen);
308         next += outr.rlen;
309
310  empty_packet:
311
312         flags = ntohs(head->flags);
313         // clear rcode and RA, set responsebit and our new flags
314         flags |= (outr.flags & 0xff80) | 0x8000;
315         head->flags = htons(flags);
316         head->nauth = head->nadd = htons(0);
317         head->nquer = htons(1);
318
319         packet_len = next - (void *)buf;
320         return packet_len;
321 }
322
323 /*
324  * Exit on signal
325  */
326 static void interrupt(int x)
327 {
328         unlink(LOCK_FILE);
329         bb_error_msg("interrupt, exiting\n");
330         exit(2);
331 }
332
333 int dnsd_main(int argc, char **argv)
334 {
335         char *listen_interface = NULL;
336         char *sttl, *sport;
337         len_and_sockaddr *lsa;
338         int udps;
339         uint16_t port = 53;
340         uint8_t buf[MAX_PACK_LEN];
341
342         getopt32(argc, argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
343         //if (option_mask32 & 0x1) // -i
344         //if (option_mask32 & 0x2) // -c
345         if (option_mask32 & 0x4) // -t
346                 ttl = xatou_range(sttl, 1, 0xffffffff);
347         if (option_mask32 & 0x8) // -p
348                 port = xatou_range(sttl, 1, 0xffff);
349
350         if (OPT_verbose) {
351                 bb_info_msg("listen_interface: %s", listen_interface);
352                 bb_info_msg("ttl: %d, port: %d", ttl, port);
353                 bb_info_msg("fileconf: %s", fileconf);
354         }
355
356         if (OPT_daemon) {
357 //FIXME: NOMMU will NOT set LOGMODE_SYSLOG!
358 #ifdef BB_NOMMU
359                 /* reexec for vfork() do continue parent */
360                 vfork_daemon_rexec(1, 0, argc, argv, "-d");
361 #else
362                 xdaemon(1, 0);
363 #endif
364                 logmode = LOGMODE_SYSLOG;
365         }
366
367         dnsentryinit();
368
369         signal(SIGINT, interrupt);
370         signal(SIGPIPE, SIG_IGN);
371         signal(SIGHUP, SIG_IGN);
372 #ifdef SIGTSTP
373         signal(SIGTSTP, SIG_IGN);
374 #endif
375 #ifdef SIGURG
376         signal(SIGURG, SIG_IGN);
377 #endif
378
379         lsa = host2sockaddr(listen_interface, port);
380         udps = xsocket(lsa->sa.sa_family, SOCK_DGRAM, 0);
381         xbind(udps, &lsa->sa, lsa->len);
382         // xlisten(udps, 50); - ?!! DGRAM sockets are never listened on I think?
383         bb_info_msg("Accepting UDP packets on %s",
384                         xmalloc_sockaddr2dotted(&lsa->sa, lsa->len));
385
386         while (1) {
387                 fd_set fdset;
388                 int r;
389
390                 FD_ZERO(&fdset);
391                 FD_SET(udps, &fdset);
392                 // Block until a message arrives
393 // FIXME: Fantastic. select'ing on just one fd??
394 // Why no just block on it doing recvfrom() ?
395                 r = select(udps + 1, &fdset, NULL, NULL, NULL);
396                 if (r < 0)
397                         bb_perror_msg_and_die("select error");
398                 if (r == 0)
399                         bb_perror_msg_and_die("select spurious return");
400
401                 /* Can this test ever be false? - yes */
402                 if (FD_ISSET(udps, &fdset)) {
403                         socklen_t fromlen = lsa->len;
404 // FIXME: need to get *DEST* address (to which of our addresses
405 // this query was directed), and reply from the same address.
406 // Or else we can exhibit usual UDP ugliness:
407 // [ip1.multihomed.ip2] <=  query to ip1  <= peer
408 // [ip1.multihomed.ip2] => reply from ip2 => peer (confused)
409                         r = recvfrom(udps, buf, sizeof(buf), 0, &lsa->sa, &fromlen);
410                         if (OPT_verbose)
411                                 bb_info_msg("Got UDP packet");
412
413                         if (r < 12 || r > 512) {
414                                 bb_error_msg("invalid packet size");
415                                 continue;
416                         }
417                         if (r <= 0)
418                                 continue;
419                         r = process_packet(buf);
420                         if (r <= 0)
421                                 continue;
422                         sendto(udps, buf, r, 0, &lsa->sa, fromlen);
423                 }
424         }
425 }