Declare DNS header locally too
[asterisk/asterisk.git] / enum.c
1 /*
2  * ENUM Support for Asterisk
3  *
4  * Copyright (C) 2003 Digium
5  *
6  * Written by Mark Spencer <markster@digium.com>
7  *
8  * Funding provided by nic.at
9  *
10  * Distributed under the terms of the GNU GPL
11  *
12  */
13
14 #include <string.h>
15 #include <fcntl.h>
16 #include <unistd.h>
17 #include <stdlib.h>
18 #include <resolv.h>
19 #include <errno.h>
20
21 #include <asterisk/logger.h>
22 #include <asterisk/options.h>
23 #include <asterisk/enum.h>
24 #include <asterisk/channel.h>
25 #include <asterisk/config.h>
26
27 #define MAX_SIZE 4096
28
29 #define TOPLEV "e164.arpa."
30
31 typedef struct {
32         unsigned        id :16;         /* query identification number */
33 #if BYTE_ORDER == BIG_ENDIAN
34                         /* fields in third byte */
35         unsigned        qr: 1;          /* response flag */
36         unsigned        opcode: 4;      /* purpose of message */
37         unsigned        aa: 1;          /* authoritive answer */
38         unsigned        tc: 1;          /* truncated message */
39         unsigned        rd: 1;          /* recursion desired */
40                         /* fields in fourth byte */
41         unsigned        ra: 1;          /* recursion available */
42         unsigned        unused :1;      /* unused bits (MBZ as of 4.9.3a3) */
43         unsigned        ad: 1;          /* authentic data from named */
44         unsigned        cd: 1;          /* checking disabled by resolver */
45         unsigned        rcode :4;       /* response code */
46 #endif
47 #if BYTE_ORDER == LITTLE_ENDIAN || BYTE_ORDER == PDP_ENDIAN
48                         /* fields in third byte */
49         unsigned        rd :1;          /* recursion desired */
50         unsigned        tc :1;          /* truncated message */
51         unsigned        aa :1;          /* authoritive answer */
52         unsigned        opcode :4;      /* purpose of message */
53         unsigned        qr :1;          /* response flag */
54                         /* fields in fourth byte */
55         unsigned        rcode :4;       /* response code */
56         unsigned        cd: 1;          /* checking disabled by resolver */
57         unsigned        ad: 1;          /* authentic data from named */
58         unsigned        unused :1;      /* unused bits (MBZ as of 4.9.3a3) */
59         unsigned        ra :1;          /* recursion available */
60 #endif
61                         /* remaining bytes */
62         unsigned        qdcount :16;    /* number of question entries */
63         unsigned        ancount :16;    /* number of answer entries */
64         unsigned        nscount :16;    /* number of authority entries */
65         unsigned        arcount :16;    /* number of resource entries */
66 } dns_HEADER;
67
68 static struct enum_search {
69         char toplev[80];
70         struct enum_search *next;
71 } *toplevs;
72
73 static int enumver = 0;
74
75 static pthread_mutex_t enumlock = AST_MUTEX_INITIALIZER;
76
77 static int skip_name(unsigned char *s, int len)
78 {
79         /* Shamelessly take from SER */
80         int x = 0;
81         while(x < len) {
82                 if (!*s) {
83                         s++;
84                         x++;
85                         break;
86                 }
87                 if (((*s) & 0xc0) == 0xc0) {
88                         s += 2;
89                         x += 2;
90                         break;
91                 }
92                 x += *s + 1;
93                 s += *s + 1;
94         }
95         if (x >= len)
96                 return -1;
97         return x;
98 }
99
100 struct dn_answer {
101         unsigned short rtype;
102         unsigned short class;
103         unsigned int ttl;
104         unsigned short size;
105 } __attribute__ ((__packed__));
106
107 struct naptr {
108         unsigned short order;
109         unsigned short pref;
110 } __attribute__ ((__packed__));
111
112 static int parse_ie(unsigned char *data, int maxdatalen, unsigned char *src, int srclen)
113 {
114         int len, olen;
115         len = olen = (int)src[0];
116         src++;
117         srclen--;
118         if (len > srclen) {
119                 ast_log(LOG_WARNING, "Want %d, got %d\n", len, srclen);
120                 return -1;
121         }
122         if (len > maxdatalen)
123                 len = maxdatalen;
124         memcpy(data, src, len);
125         return olen + 1;
126 }
127
128 static int parse_naptr(unsigned char *dst, int dstsize, char *tech, int techsize, unsigned char *answer, int len)
129 {
130         unsigned char *oanswer = answer;
131         unsigned char flags[80] = "";
132         unsigned char services[80] = "";
133         unsigned char regexp[80] = "";
134         unsigned char repl[80] = "";
135         int res;
136         
137         if (len < sizeof(struct naptr)) {
138                 printf("Length too short\n");
139                 return -1;
140         }
141         answer += sizeof(struct naptr);
142         len -= sizeof(struct naptr);
143         if ((res = parse_ie(flags, sizeof(flags) - 1, answer, len)) < 0) {
144                 ast_log(LOG_WARNING, "Failed to get flags\n");
145                 return -1; 
146         } else { answer += res; len -= res; }
147         if ((res = parse_ie(services, sizeof(services) - 1, answer, len)) < 0) {
148                 ast_log(LOG_WARNING, "Failed to get services\n");
149                 return -1; 
150         } else { answer += res; len -= res; }
151         if ((res = parse_ie(regexp, sizeof(regexp) - 1, answer, len)) < 0)
152                 return -1; else { answer += res; len -= res; }
153         if ((res = dn_expand(oanswer,answer + len,answer, repl, sizeof(repl) - 1)) < 0) {
154                 ast_log(LOG_WARNING, "Failed to expand hostname\n");
155                 return -1;
156         } 
157 #if 0
158         printf("Flags: %s\n", flags);
159         printf("Services: %s\n", services);
160         printf("Regexp: %s\n", regexp);
161         printf("Repl: %s\n", repl);
162 #endif
163         if (!strncmp(regexp, "!^.*$!", 6)) {
164                 if (!strncmp(services, "E2U+voice:", 10)) {
165                         if (regexp[strlen(regexp) - 1] == '!')
166                                 regexp[strlen(regexp) - 1] = '\0';
167 #if 0
168                         printf("Technology: %s\n", services + 10);
169                         printf("Destination: %s\n", regexp + 6);
170 #endif
171                         strncpy(dst, regexp + 6, dstsize);
172                         strncpy(tech, services + 10, techsize);
173                 }
174         } else
175                 ast_log(LOG_WARNING, "Non-total substitution not yet supported\n");
176         return 0;
177 }
178
179 static int parse_answer(unsigned char *dst, int dstlen, unsigned char *tech, int techlen, unsigned char *answer, int len)
180 {
181         /*
182          * This function is influenced by "ser" the SIP router.
183          */
184         int x;
185         int res;
186         dns_HEADER *h;
187         struct dn_answer *ans;
188         dst[0] = '\0';
189         tech[0] = '\0';
190 #if 0
191         for (x=0;x<len;x++) {
192                 if ((answer[x] < 32) || (answer[x] > 127)) {
193                         if (lastlit)
194                                 printf("\"");
195                         printf(" 0x%02x", answer[x]);
196                         lastlit = 0;
197                 } else {
198                         if (!lastlit) 
199                                 printf(" \"");
200                         printf("%c", answer[x]);
201                         lastlit = 1;
202                 }
203         }
204         printf("\n");
205 #endif  
206         h = (dns_HEADER *)answer;
207         /* Skip over DNS header */
208         answer += sizeof(dns_HEADER);
209         len -= sizeof(dns_HEADER);
210 #if 0
211         printf("Query count: %d\n", ntohs(h->qdcount));
212 #endif
213         for (x=0;x<ntohs(h->qdcount);x++) {
214                 if ((res = skip_name(answer, len)) < 0) {
215                         ast_log(LOG_WARNING, "Couldn't skip over name\n");
216                         return -1;
217                 }
218                 answer += res;
219                 len -= res;
220                 answer += 4;    /* Skip QCODE / QCLASS */
221                 len -= 4;
222                 if (len < 0) {
223                         ast_log(LOG_WARNING, "Strange query size\n");
224                         return -1;
225                 }
226         }
227 #if 0
228         printf("Length remaining: %d\n", len);
229         printf("Answer count: %d\n", ntohs(h->ancount));
230         printf("Looking for %d/%d\n", C_IN, T_NAPTR);
231 #endif
232         for (x=0;x<ntohs(h->ancount);x++) {
233                 if ((res = skip_name(answer, len) < 0)) {
234                         ast_log(LOG_WARNING, "Failed to skip name :(\n");
235                         return -1;
236                 }
237                 answer += res;
238                 len -= res;
239                 /* XXX Why am I adding 2 here? XXX */
240                 answer += 2;
241                 len -= 2;
242                 ans = (struct dn_answer *)answer;
243                 answer += sizeof(struct dn_answer);
244                 len -= sizeof(struct dn_answer);
245                 if (len < 0)
246                         return -1;
247 #if 0
248                 printf("Type: %d, class: %d, ttl: %d, length: %d\n", ntohs(ans->rtype), ntohs(ans->class),
249                         ntohl(ans->ttl), ntohs(ans->size));
250 #endif                  
251                 len -= ntohs(ans->size);
252                 if (len < 0) {
253                         ast_log(LOG_WARNING, "Length exceeds frame\n");
254                         return -1;
255                 }
256                 if ((ntohs(ans->class) == C_IN) && (ntohs(ans->rtype) == T_NAPTR)) {
257                         if (parse_naptr(dst, dstlen, tech, techlen, answer, ntohs(ans->size)))
258                                 ast_log(LOG_WARNING, "Failed to parse naptr :(\n");
259                         if (strlen(dst))
260                                 return 0;
261                 }
262                 answer += ntohs(ans->size);
263         }
264         return 0;
265 }
266
267 int ast_get_enum(struct ast_channel *chan, const char *number, char *dst, int dstlen, char *tech, int techlen)
268 {
269         unsigned char answer[MAX_SIZE];
270         char tmp[259 + 80];
271         int pos = strlen(number) - 1;
272         int newpos=0;
273         int res = -1;
274         int ret = -1;
275         struct enum_search *s = NULL;
276         int version = -1;
277         struct __res_state enumstate;
278         res_ninit(&enumstate);  
279         if (chan && ast_autoservice_start(chan) < 0)
280                 return -1;
281         
282         if (pos > 128)
283                 pos = 128;
284         while(pos >= 0) {
285                 tmp[newpos++] = number[pos--];
286                 tmp[newpos++] = '.';
287         }
288 #if 0
289         printf("Looking for '%s'\n", tmp);
290 #endif  
291         
292         for(;;) {
293                 ast_pthread_mutex_lock(&enumlock);
294                 if (version != enumver) {
295                         /* Ooh, a reload... */
296                         s = toplevs;
297                 } else {
298                         s = s->next;
299                 }
300                 if (s) {
301                         strcpy(tmp + newpos, s->toplev);
302                 }
303                 ast_pthread_mutex_unlock(&enumlock);
304                 if (!s)
305                         break;
306                 res = res_nsearch(&enumstate, tmp, C_IN, T_NAPTR, answer, sizeof(answer));
307                 if (res > 0)
308                         break;
309         }
310         if (res > 0) {
311                 if ((res = parse_answer(dst, dstlen, tech, techlen, answer, res))) {
312                         ast_log(LOG_WARNING, "Parse error returned %d\n", res);
313                         ret = 0;
314                 } else {
315                         ast_log(LOG_DEBUG, "Found technology '%s', destination '%s'\n", tech, dst);
316                         ret = 1;
317                 }
318         } else {
319                 ast_log(LOG_DEBUG, "No such number found: %s (%s)\n", tmp, strerror(errno));
320                 ret = 0;
321         }
322         if (chan)
323                 ret |= ast_autoservice_stop(chan);
324         res_nclose(&enumstate);
325         return ret;
326 }
327
328 static struct enum_search *enum_newtoplev(char *s)
329 {
330         struct enum_search *tmp;
331         tmp = malloc(sizeof(struct enum_search));
332         if (tmp) {
333                 memset(tmp, 0, sizeof(struct enum_search));
334                 strncpy(tmp->toplev, s, sizeof(tmp->toplev) - 1);
335         }
336         return tmp;
337 }
338
339 int ast_enum_init(void)
340 {
341         struct ast_config *cfg;
342         struct enum_search *s, *sl;
343         struct ast_variable *v;
344
345         /* Destroy existing list */
346         ast_pthread_mutex_lock(&enumlock);
347         s = toplevs;
348         while(s) {
349                 sl = s;
350                 s = s->next;
351                 free(sl);
352         }
353         toplevs = NULL;
354         cfg = ast_load("enum.conf");
355         if (cfg) {
356                 sl = NULL;
357                 v = ast_variable_browse(cfg, "general");
358                 while(v) {
359                         if (!strcasecmp(v->name, "search")) {
360                                 s = enum_newtoplev(v->value);
361                                 if (s) {
362                                         if (sl)
363                                                 sl->next = s;
364                                         else
365                                                 toplevs = s;
366                                         sl = s;
367                                 }
368                         }
369                         v = v->next;
370                 }
371                 ast_destroy(cfg);
372         } else {
373                 toplevs = enum_newtoplev(TOPLEV);
374         }
375         enumver++;
376         ast_pthread_mutex_unlock(&enumlock);
377         return 0;
378 }
379
380 int ast_enum_reload(void)
381 {
382         return ast_enum_init();
383 }