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