176cef697a127b44136a4c44d6ba6c162dc9ea05
[asterisk/asterisk.git] / enum.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Funding provided by nic.at
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief ENUM Support for Asterisk
24  *
25  * \author Mark Spencer <markster@digium.com>
26  *
27  * \arg Funding provided by nic.at
28  */
29
30 #include <sys/types.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <arpa/nameser.h>
34 #if __APPLE_CC__ >= 1495
35 #include <arpa/nameser_compat.h>
36 #endif
37 #include <resolv.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>
41 #include <regex.h>
42 #include <unistd.h>
43 #include <errno.h>
44
45 #include "asterisk.h"
46
47 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48
49 #include "asterisk/logger.h"
50 #include "asterisk/options.h"
51 #include "asterisk/enum.h"
52 #include "asterisk/dns.h"
53 #include "asterisk/channel.h"
54 #include "asterisk/config.h"
55 #include "asterisk/utils.h"
56
57 #ifdef __APPLE__
58 #undef T_NAPTR
59 #define T_NAPTR 35
60 #endif
61
62 #ifdef __APPLE__
63 #undef T_TXT
64 #define T_TXT 16
65 #endif
66
67 #define TOPLEV "e164.arpa."     /*!< The IETF Enum standard root, managed by the ITU */
68
69 /* Linked list from config file */
70 static struct enum_search {
71         char toplev[512];
72         struct enum_search *next;
73 } *toplevs;
74
75 static int enumver = 0;
76
77 AST_MUTEX_DEFINE_STATIC(enumlock);
78
79 struct naptr {
80         unsigned short order;
81         unsigned short pref;
82 } __attribute__ ((__packed__));
83
84 /*! \brief Parse NAPTR record information elements */
85 static int parse_ie(char *data, int maxdatalen, char *src, int srclen)
86 {
87         int len, olen;
88
89         len = olen = (int)src[0];
90         src++;
91         srclen--;
92         if (len > srclen) {
93                 ast_log(LOG_WARNING, "Want %d, got %d\n", len, srclen);
94                 return -1;
95         }
96         if (len > maxdatalen)
97                 len = maxdatalen;
98         memcpy(data, src, len);
99         return olen + 1;
100 }
101
102 /*! \brief Parse DNS NAPTR record used in ENUM ---*/
103 static int parse_naptr(char *dst, int dstsize, char *tech, int techsize, char *answer, int len, char *naptrinput)
104 {
105
106         char tech_return[80];
107         char *oanswer = answer;
108         char flags[512] = "";
109         char services[512] = "";
110         char *p;
111         char regexp[512] = "";
112         char repl[512] = "";
113         char temp[512] = "";
114         char delim;
115         char *delim2;
116         char *pattern, *subst, *d;
117         int res;
118         int regexp_len, size, backref;
119         int d_len = sizeof(temp) - 1;
120         regex_t preg;
121         regmatch_t pmatch[9];
122
123         tech_return[0] = '\0';
124
125         dst[0] = '\0';
126
127         if (len < sizeof(struct naptr)) {
128                 ast_log(LOG_WARNING, "NAPTR record length too short\n");
129                 return -1;
130         }
131         answer += sizeof(struct naptr);
132         len -= sizeof(struct naptr);
133         if ((res = parse_ie(flags, sizeof(flags) - 1, answer, len)) < 0) {
134                 ast_log(LOG_WARNING, "Failed to get flags from NAPTR record\n");
135                 return -1;
136         } else {
137                 answer += res;
138                 len -= res;
139         }
140         if ((res = parse_ie(services, sizeof(services) - 1, answer, len)) < 0) {
141                 ast_log(LOG_WARNING, "Failed to get services from NAPTR record\n");
142                 return -1;
143         } else {
144                 answer += res;
145                 len -= res;
146         }
147         if ((res = parse_ie(regexp, sizeof(regexp) - 1, answer, len)) < 0) {
148                 ast_log(LOG_WARNING, "Failed to get regexp from NAPTR record\n");
149                 return -1;
150         } else {
151                 answer += res;
152                 len -= res;
153         }
154
155         if ((res = dn_expand((unsigned char *)oanswer, (unsigned char *)answer + len, (unsigned char *)answer, repl, sizeof(repl) - 1)) < 0) {
156                 ast_log(LOG_WARNING, "Failed to expand hostname\n");
157                 return -1;
158         }
159
160         if (option_debug > 2)   /* Advanced NAPTR debugging */
161                 ast_log(LOG_DEBUG, "NAPTR input='%s', flags='%s', services='%s', regexp='%s', repl='%s'\n",
162                         naptrinput, flags, services, regexp, repl);
163
164         if (tolower(flags[0]) != 'u') {
165                 ast_log(LOG_WARNING, "NAPTR Flag must be 'U' or 'u'.\n");
166                 return -1;
167         }
168
169         p = strstr(services, "e2u+");
170         if (p == NULL)
171                 p = strstr(services, "E2U+");
172         if (p){
173                 p = p + 4;
174                 if (strchr(p, ':')){
175                         p = strchr(p, ':') + 1;
176                 }
177                 ast_copy_string(tech_return, p, sizeof(tech_return));
178         } else {
179
180                 p = strstr(services, "+e2u");
181                 if (p == NULL)
182                         p = strstr(services, "+E2U");
183                 if (p) {
184                         *p = 0;
185                         p = strchr(services, ':');
186                         if (p)
187                                 *p = 0;
188                         ast_copy_string(tech_return, services, sizeof(tech_return));
189                 }
190         }
191
192         /* DEDBUGGING STUB
193         ast_copy_string(regexp, "!^\\+43(.*)$!\\1@bla.fasel!", sizeof(regexp) - 1);
194         */
195
196         regexp_len = strlen(regexp);
197         if (regexp_len < 7) {
198                 ast_log(LOG_WARNING, "Regex too short to be meaningful.\n");
199                 return -1;
200         }
201
202
203         delim = regexp[0];
204         delim2 = strchr(regexp + 1, delim);
205         if ((delim2 == NULL) || (regexp[regexp_len-1] != delim)) {
206                 ast_log(LOG_WARNING, "Regex delimiter error (on \"%s\").\n",regexp);
207                 return -1;
208         }
209
210         pattern = regexp + 1;
211         *delim2 = 0;
212         subst   = delim2 + 1;
213         regexp[regexp_len-1] = 0;
214
215 #if 0
216         printf("Pattern: %s\n", pattern);
217         printf("Subst: %s\n", subst);
218        printf("Input: %s\n", naptrinput);
219 #endif
220
221 /*
222  * now do the regex wizardry.
223  */
224
225         if (regcomp(&preg, pattern, REG_EXTENDED | REG_NEWLINE)) {
226                 ast_log(LOG_WARNING, "NAPTR Regex compilation error (regex = \"%s\").\n",regexp);
227                 return -1;
228         }
229
230         if (preg.re_nsub > 9) {
231                 ast_log(LOG_WARNING, "NAPTR Regex compilation error: too many subs.\n");
232                 regfree(&preg);
233                 return -1;
234         }
235
236         if (regexec(&preg, naptrinput, 9, pmatch, 0)) {
237                 ast_log(LOG_WARNING, "NAPTR Regex match failed.\n");
238                 regfree(&preg);
239                 return -1;
240         }
241         regfree(&preg);
242
243         d = temp;
244         d_len--;
245         while (*subst && (d_len > 0)) {
246                 if ((subst[0] == '\\') && isdigit(subst[1]) && (pmatch[subst[1]-'0'].rm_so != -1)) {
247                         backref = subst[1]-'0';
248                         size = pmatch[backref].rm_eo - pmatch[backref].rm_so;
249                         if (size > d_len) {
250                                 ast_log(LOG_WARNING, "Not enough space during NAPTR regex substitution.\n");
251                                 return -1;
252                                 }
253                         memcpy(d, naptrinput + pmatch[backref].rm_so, size);
254                         d += size;
255                         d_len -= size;
256                         subst += 2;
257                 } else if (isprint(*subst)) {
258                         *d++ = *subst++;
259                         d_len--;
260                 } else {
261                         ast_log(LOG_WARNING, "Error during regex substitution.\n");
262                         return -1;
263                 }
264         }
265         *d = 0;
266         ast_copy_string(dst, temp, dstsize);
267         dst[dstsize - 1] = '\0';
268
269         if (*tech != '\0'){ /* check if it is requested NAPTR */
270                 if (!strncasecmp(tech, "ALL", techsize)){
271                         return 1; /* return or count any RR */
272                 }
273                 if (!strncasecmp(tech_return, tech, sizeof(tech_return)<techsize?sizeof(tech_return):techsize)){
274                         ast_copy_string(tech, tech_return, techsize);
275                         return 1; /* we got out RR */
276                 } else { /* go to the next RR in the DNS answer */
277                         return 0;
278                 }
279         }
280
281         /* tech was not specified, return first parsed RR */
282         ast_copy_string(tech, tech_return, techsize);
283
284         return 1;
285 }
286
287 /* do not return requested value, just count RRs and return thei number in dst */
288 #define ENUMLOOKUP_OPTIONS_COUNT       1
289
290 struct enum_naptr_rr {
291         struct naptr naptr; /* order and preference of RR */
292         char *result; /* result of naptr parsing,e.g.: tel:+5553 */
293         char *tech; /* Technology (from URL scheme) */
294         int sort_pos; /* sort position */
295 };
296
297 struct enum_context {
298         char *dst;      /* Destination part of URL from ENUM */
299         int dstlen;     /* Length */
300         char *tech;     /* Technology (from URL scheme) */
301         int techlen;    /* Length */
302         char *txt;      /* TXT record in TXT lookup */
303         int txtlen;     /* Length */
304         char *naptrinput;       /* The number to lookup */
305         int position; /* used as counter for RRs or specifies position of required RR */
306         int options; /* options , see ENUMLOOKUP_OPTIONS_* defined above */
307         struct enum_naptr_rr *naptr_rrs; /* array of parsed NAPTR RRs */
308         int naptr_rrs_count; /* Size of array naptr_rrs */
309 };
310
311 /*! \brief Callback for TXT record lookup */
312 static int txt_callback(void *context, char *answer, int len, char *fullanswer)
313 {
314         struct enum_context *c = (struct enum_context *)context;
315 #if 0
316         printf("ENUMTXT Called\n");
317 #endif
318
319         if (answer == NULL) {
320                 c->txt = NULL;
321                 c->txtlen = 0;
322                 return 0;
323         }
324
325         /* skip over first byte, as for some reason it's a vertical tab character */
326         answer += 1;
327         len -= 1;
328
329         /* answer is not null-terminated, but should be */
330        /* this is safe to do, as answer has extra bytes on the end we can
331            safely overwrite with a null */
332         answer[len] = '\0';
333         /* now increment len so that len includes the null, so that we can
334            compare apples to apples */
335         len +=1;
336
337         /* finally, copy the answer into c->txt */
338         ast_copy_string(c->txt, answer, len < c->txtlen ? len : (c->txtlen));
339
340         /* just to be safe, let's make sure c->txt is null terminated */
341         c->txt[(c->txtlen)-1] = '\0';
342
343         return 1;
344 }
345
346 /*! \brief Callback from ENUM lookup function */
347 static int enum_callback(void *context, char *answer, int len, char *fullanswer)
348 {
349        struct enum_context *c = context;
350        void *p = NULL;
351        int res;
352
353        res = parse_naptr(c->dst, c->dstlen, c->tech, c->techlen, answer, len, c->naptrinput);
354
355        if (res < 0) {
356                 ast_log(LOG_WARNING, "Failed to parse naptr :(\n");
357                 return -1;
358        } else if (res > 0 && !ast_strlen_zero(c->dst)){ /* ok, we got needed NAPTR */
359                if (c->options & ENUMLOOKUP_OPTIONS_COUNT){ /* counting RRs */
360                        c->position++;
361                        snprintf(c->dst, c->dstlen, "%d", c->position);
362                } else  {
363                        if ((p = ast_realloc(c->naptr_rrs, sizeof(*c->naptr_rrs) * (c->naptr_rrs_count + 1)))) {
364                                c->naptr_rrs = p;
365                                memcpy(&c->naptr_rrs[c->naptr_rrs_count].naptr, answer, sizeof(c->naptr_rrs->naptr));
366                                /* printf("order=%d, pref=%d\n", ntohs(c->naptr_rrs[c->naptr_rrs_count].naptr.order), ntohs(c->naptr_rrs[c->naptr_rrs_count].naptr.pref)); */
367                                c->naptr_rrs[c->naptr_rrs_count].result = strdup(c->dst);
368                                c->naptr_rrs[c->naptr_rrs_count].tech = strdup(c->tech);
369                                c->naptr_rrs[c->naptr_rrs_count].sort_pos = c->naptr_rrs_count;
370                                c->naptr_rrs_count++;
371                        }
372                        c->dst[0] = 0;
373                }
374                return 0;
375         }
376
377        if (c->options & ENUMLOOKUP_OPTIONS_COUNT)       { /* counting RRs */
378                snprintf(c->dst, c->dstlen, "%d", c->position);
379        }
380
381         return 0;
382 }
383
384 /*! \brief ENUM lookup */
385 int ast_get_enum(struct ast_channel *chan, const char *number, char *dst, int dstlen, char *tech, int techlen, char* suffix, char* options)
386 {
387         struct enum_context context;
388         char tmp[259 + 512];
389         char naptrinput[512];
390         int pos = strlen(number) - 1;
391         int newpos = 0;
392         int ret = -1;
393         struct enum_search *s = NULL;
394         int version = -1;
395         /* for ISN rewrite */
396         char *p1 = NULL;
397         char *p2 = NULL;
398         int k = 0;
399         int i = 0;
400         int z = 0;
401
402         if (number[0] == 'n') {
403                 strncpy(naptrinput, number+1, sizeof(naptrinput));
404         } else {
405                 strncpy(naptrinput, number, sizeof(naptrinput));
406         }
407
408         context.naptrinput = naptrinput;        /* The number */
409         context.dst = dst;                      /* Return string */
410         context.dstlen = dstlen;
411         context.tech = tech;
412         context.techlen = techlen;
413         context.options = 0;
414         context.position = 1;
415         context.naptr_rrs = NULL;
416         context.naptr_rrs_count = 0;
417
418         if (options != NULL) {
419                 if (*options == 'c') {
420                         context.options = ENUMLOOKUP_OPTIONS_COUNT;
421                         context.position = 0;
422                 } else {
423                         context.position = atoi(options);
424                         if (context.position < 1)
425                                 context.position = 1;
426                 }
427         }
428
429         if (pos > 128)
430                 pos = 128;
431
432         /* ISN rewrite */
433         p1 = strchr(number, '*');
434
435         if (number[0] == 'n') { /* do not perform ISN rewrite ('n' is testing flag) */
436                 p1 = NULL;
437                 k = 1; /* strip 'n' from number */
438         }
439
440         if (p1 != NULL) {
441                 p2 = p1+1;
442                 while (p1 > number){
443                         p1--;
444                         tmp[newpos++] = *p1;
445                         tmp[newpos++] = '.';
446                 }
447                 if (*p2) {
448                         while(*p2 && newpos < 128){
449                                 tmp[newpos++] = *p2;
450                                 p2++;
451                         }
452                         tmp[newpos++] = '.';
453                 }
454
455         } else {
456                 while (pos >= k) {
457                         if (isdigit(number[pos])) {
458                                 tmp[newpos++] = number[pos];
459                                 tmp[newpos++] = '.';
460                         }
461                         pos--;
462                 }
463         }
464
465         if (chan && ast_autoservice_start(chan) < 0)
466                 return -1;
467
468         for (;;) {
469                 ast_mutex_lock(&enumlock);
470                 if (version != enumver) {
471                         /* Ooh, a reload... */
472                         s = toplevs;
473                         version = enumver;
474                 } else {
475                         s = s->next;
476                 }
477                 if (suffix != NULL) {
478                         strncpy(tmp + newpos, suffix, sizeof(tmp) - newpos - 1);
479                 } else if (s) {
480                         strncpy(tmp + newpos, s->toplev, sizeof(tmp) - newpos - 1);
481                 }
482                 ast_mutex_unlock(&enumlock);
483                 if (!s)
484                         break;
485                 ret = ast_search_dns(&context, tmp, C_IN, T_NAPTR, enum_callback);
486                 if (ret > 0)
487                         break;
488                 if (suffix != NULL)
489                        break;
490         }
491         if (ret < 0) {
492                 ast_log(LOG_DEBUG, "No such number found: %s (%s)\n", tmp, strerror(errno));
493                 strcpy(dst, "0");
494                 ret = 0;
495         }
496
497         if (context.naptr_rrs_count >= context.position && ! (context.options & ENUMLOOKUP_OPTIONS_COUNT)) {
498                 /* sort array by NAPTR order/preference */
499                 for (k=0; k<context.naptr_rrs_count; k++) {
500                         for (i=0; i<context.naptr_rrs_count; i++) {
501                                 /* use order first and then preference to compare */
502                                 if ((ntohs(context.naptr_rrs[k].naptr.order) < ntohs(context.naptr_rrs[i].naptr.order)
503                                                 && context.naptr_rrs[k].sort_pos > context.naptr_rrs[i].sort_pos)
504                                         || (ntohs(context.naptr_rrs[k].naptr.order) > ntohs(context.naptr_rrs[i].naptr.order)
505                                                 && context.naptr_rrs[k].sort_pos < context.naptr_rrs[i].sort_pos)){
506                                         z = context.naptr_rrs[k].sort_pos;
507                                         context.naptr_rrs[k].sort_pos = context.naptr_rrs[i].sort_pos;
508                                         context.naptr_rrs[i].sort_pos = z;
509                                         continue;
510                                 }
511                                 if (ntohs(context.naptr_rrs[k].naptr.order) == ntohs(context.naptr_rrs[i].naptr.order)) {
512                                         if ((ntohs(context.naptr_rrs[k].naptr.pref) < ntohs(context.naptr_rrs[i].naptr.pref)
513                                                         && context.naptr_rrs[k].sort_pos > context.naptr_rrs[i].sort_pos)
514                                                 || (ntohs(context.naptr_rrs[k].naptr.pref) > ntohs(context.naptr_rrs[i].naptr.pref)
515                                                         && context.naptr_rrs[k].sort_pos < context.naptr_rrs[i].sort_pos)){
516                                                 z = context.naptr_rrs[k].sort_pos;
517                                                 context.naptr_rrs[k].sort_pos = context.naptr_rrs[i].sort_pos;
518                                                 context.naptr_rrs[i].sort_pos = z;
519                                         }
520                                 }
521                         }
522                 }
523                 for (k=0; k<context.naptr_rrs_count; k++) {
524                         if (context.naptr_rrs[k].sort_pos == context.position-1) {
525                                 ast_copy_string(context.dst, context.naptr_rrs[k].result, dstlen);
526                                 ast_copy_string(context.tech, context.naptr_rrs[k].tech, techlen);
527                                 break;
528                         }
529                 }
530         } else if (!(context.options & ENUMLOOKUP_OPTIONS_COUNT)) {
531                 context.dst[0] = 0;
532         }
533         if (chan)
534                 ret |= ast_autoservice_stop(chan);
535
536         for (k=0; k<context.naptr_rrs_count; k++) {
537                 free(context.naptr_rrs[k].result);
538                 free(context.naptr_rrs[k].tech);
539         }
540
541         free(context.naptr_rrs);
542
543         return ret;
544 }
545
546 /*! \brief Get TXT record from DNS.
547         Really has nothing to do with enum, but anyway...
548  */
549 int ast_get_txt(struct ast_channel *chan, const char *number, char *dst, int dstlen, char *tech, int techlen, char *txt, int txtlen)
550 {
551         struct enum_context context;
552         char tmp[259 + 512];
553         char naptrinput[512] = "+";
554         int pos = strlen(number) - 1;
555         int newpos = 0;
556         int ret = -1;
557         struct enum_search *s = NULL;
558         int version = -1;
559
560         strncat(naptrinput, number, sizeof(naptrinput) - 2);
561
562         context.naptrinput = naptrinput;
563         context.dst = dst;
564         context.dstlen = dstlen;
565         context.tech = tech;
566         context.techlen = techlen;
567         context.txt = txt;
568         context.txtlen = txtlen;
569
570         if (pos > 128)
571                 pos = 128;
572         while (pos >= 0) {
573                 tmp[newpos++] = number[pos--];
574                 tmp[newpos++] = '.';
575         }
576
577         if (chan && ast_autoservice_start(chan) < 0)
578                 return -1;
579
580         for (;;) {
581                 ast_mutex_lock(&enumlock);
582                 if (version != enumver) {
583                         /* Ooh, a reload... */
584                         s = toplevs;
585                         version = enumver;
586                 } else {
587                         s = s->next;
588                 }
589                 if (s) {
590                         strncpy(tmp + newpos, s->toplev, sizeof(tmp) - newpos - 1);
591                 }
592                 ast_mutex_unlock(&enumlock);
593                 if (!s)
594                         break;
595
596                 ret = ast_search_dns(&context, tmp, C_IN, T_TXT, txt_callback);
597                 if (ret > 0)
598                         break;
599         }
600         if (ret < 0) {
601                 if (option_debug > 1)
602                         ast_log(LOG_DEBUG, "No such number found in ENUM: %s (%s)\n", tmp, strerror(errno));
603                 ret = 0;
604         }
605         if (chan)
606                 ret |= ast_autoservice_stop(chan);
607         return ret;
608 }
609
610 /*! \brief Add enum tree to linked list */
611 static struct enum_search *enum_newtoplev(char *s)
612 {
613         struct enum_search *tmp;
614
615         if ((tmp = ast_calloc(1, sizeof(*tmp)))) {              
616                 ast_copy_string(tmp->toplev, s, sizeof(tmp->toplev));
617         }
618         return tmp;
619 }
620
621 /*! \brief Initialize the ENUM support subsystem */
622 int ast_enum_init(void)
623 {
624         struct ast_config *cfg;
625         struct enum_search *s, *sl;
626         struct ast_variable *v;
627
628         /* Destroy existing list */
629         ast_mutex_lock(&enumlock);
630         s = toplevs;
631         while(s) {
632                 sl = s;
633                 s = s->next;
634                 free(sl);
635         }
636         toplevs = NULL;
637         cfg = ast_config_load("enum.conf");
638         if (cfg) {
639                 sl = NULL;
640                 v = ast_variable_browse(cfg, "general");
641                 while(v) {
642                         if (!strcasecmp(v->name, "search")) {
643                                 s = enum_newtoplev(v->value);
644                                 if (s) {
645                                         if (sl)
646                                                 sl->next = s;
647                                         else
648                                                 toplevs = s;
649                                         sl = s;
650                                 }
651                         }
652                         v = v->next;
653                 }
654                 ast_config_destroy(cfg);
655         } else {
656                 toplevs = enum_newtoplev(TOPLEV);
657         }
658         enumver++;
659         ast_mutex_unlock(&enumlock);
660         return 0;
661 }
662
663 int ast_enum_reload(void)
664 {
665         return ast_enum_init();
666 }