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