7450b6f58c2bd2aeb9cd1953fe38c7006522abc1
[sip-router] / resolve.c
1 /* $Id$*/
2 /*
3  *
4  * Copyright (C) 2001-2003 FhG Fokus
5  *
6  * This file is part of ser, a free SIP server.
7  *
8  * ser is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version
12  *
13  * For a license to use the ser software under conditions
14  * other than those described here, or to purchase support for this
15  * software, please contact iptel.org by e-mail at the following addresses:
16  *    info@iptel.org
17  *
18  * ser is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License 
24  * along with this program; if not, write to the Free Software 
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  */
27 /*
28  * History:
29  * -------
30  *  2003-02-13  added proto to sip_resolvehost, for SRV lookups (andrei)
31  *  2003-07-03  default port value set according to proto (andrei)
32  *  2005-07-11  added resolv_init (timeouts a.s.o) (andrei)
33  *  2006-04-13  added sip_hostport2su()  (andrei)
34  *  2006-07-13  rdata structures put on diet (andrei)
35  *  2006-07-17  rdata contains now also the record name (andrei)
36  *  2006-08-18  get_record can append also the additional records to the
37  *               returned list (andrei)
38  *  2007-06-15  naptr support (andrei)
39  *  2007-10-10  short name resolution using search list supported (mma)
40  *              set dns_use_search_list=1 (default on)
41  *              new option dns_search_full_match (default on) controls
42  *              whether rest of the name is matched against search list
43  *              or blindly accepted (better performance but exploitable)
44  *  2008-01-31  resolver options use the configuration framework, and the
45  *               resolver is reinitialized when the options change (Miklos)
46  *  2008-08-12  sctp preference support for NAPTR queries (andrei)
47  *  2009-03-30  TXT record support (andrei)
48  *  2009-03-31  EBL record support (andrei)
49  *  2009-04-01  PTR record support (andrei)
50  */ 
51
52 /*!
53  * \file
54  * \brief SIP-router core :: 
55  * \ingroup core
56  * Module: \ref core
57  */
58
59
60 #include <sys/types.h>
61 #include <netinet/in.h>
62 #include <arpa/nameser.h>
63 #include <resolv.h>
64 #include <string.h>
65
66 #include "resolve.h"
67 #include "compiler_opt.h"
68 #include "dprint.h"
69 #include "mem/mem.h"
70 #include "ip_addr.h"
71 #include "error.h"
72 #include "globals.h" /* tcp_disable, tls_disable a.s.o */
73 #include "cfg_core.h"
74 #include "socket_info.h"
75
76 #ifdef USE_DNS_CACHE
77 #include "dns_cache.h"
78 #endif
79
80 /* counters framework */
81 struct dns_counters_h dns_cnts_h;
82 counter_def_t dns_cnt_defs[] =  {
83         {&dns_cnts_h.failed_dns_req, "failed_dns_request", 0, 0, 0,
84                 "incremented each time a DNS request has failed."},
85         {0, 0, 0, 0, 0, 0 }
86 };
87
88 /* mallocs for local stuff */
89 #define local_malloc pkg_malloc
90 #define local_free   pkg_free
91
92 #ifdef USE_NAPTR
93 static int naptr_proto_pref[PROTO_LAST+1];
94 #endif
95
96 #ifdef USE_NAPTR
97 void init_naptr_proto_prefs()
98 {
99         if ((PROTO_UDP > PROTO_LAST) || (PROTO_TCP > PROTO_LAST) ||
100                 (PROTO_TLS > PROTO_LAST) || (PROTO_SCTP > PROTO_LAST)){
101                 BUG("init_naptr_proto_prefs: array too small \n");
102                 return;
103         }
104         naptr_proto_pref[PROTO_UDP]=cfg_get(core, core_cfg, dns_udp_pref);
105         naptr_proto_pref[PROTO_TCP]=cfg_get(core, core_cfg, dns_tcp_pref);
106         naptr_proto_pref[PROTO_TLS]=cfg_get(core, core_cfg, dns_tls_pref);
107         naptr_proto_pref[PROTO_SCTP]=cfg_get(core, core_cfg, dns_sctp_pref);
108 }
109
110 #endif /* USE_NAPTR */
111
112 #ifdef DNS_WATCHDOG_SUPPORT
113 static on_resolv_reinit on_resolv_reinit_cb = NULL;
114
115 /* register the callback function */
116 int register_resolv_reinit_cb(on_resolv_reinit cb)
117 {
118         if (on_resolv_reinit_cb) {
119                 LOG(L_ERR, "ERROR: register_resolv_reinit_cb(): "
120                         "callback function has been already registered\n");
121                 return -1;
122         }
123         on_resolv_reinit_cb = cb;
124         return 0;
125 }
126 #endif
127
128 /* counter init function
129   must be called before fork
130 */
131 static int stat_init(void)
132 {
133         if (counter_register_array("dns", dns_cnt_defs) < 0)
134                 goto error;
135         return 0;
136 error:
137         return -1;
138 }
139
140 /* init. the resolver
141  * params: retr_time  - time before retransmitting (must be >0)
142  *         retr_no    - retransmissions number
143  *         servers_no - how many dns servers will be used
144  *                      (from the one listed in /etc/resolv.conf)
145  *         search     - if 0 the search list in /etc/resolv.conf will
146  *                      be ignored (HINT: even if you don't have a
147  *                      search list in resolv.conf, it's still better
148  *                      to set search to 0, because an empty seachlist
149  *                      means in fact search "" => it takes more time)
150  * If any of the parameters <0, the default (system specific) value
151  * will be used. See also resolv.conf(5).
152  * returns: 0 on success, -1 on error
153  */
154 static int _resolv_init(void)
155 {
156         dns_func.sr_res_init();
157 #ifdef HAVE_RESOLV_RES
158         if (cfg_get(core, core_cfg, dns_retr_time)>0)
159                 _res.retrans=cfg_get(core, core_cfg, dns_retr_time);
160         if (cfg_get(core, core_cfg, dns_retr_no)>0)
161                 _res.retry=cfg_get(core, core_cfg, dns_retr_no);
162         if ((cfg_get(core, core_cfg, dns_servers_no)>=0)
163                 && (cfg_get(core, core_cfg, dns_servers_no)<_res.nscount))
164                         _res.nscount=cfg_get(core, core_cfg, dns_servers_no);
165         if (cfg_get(core, core_cfg, dns_search_list)==0)
166                 _res.options&=~(RES_DEFNAMES|RES_DNSRCH);
167 #else
168 #warning "no resolv timeout support"
169         LOG(L_WARN, "WARNING: _resolv_init: no resolv options support - resolv"
170                         " options will be ignored\n");
171 #endif
172         return 0;
173 }
174
175 /* wrapper function to initialize the resolver at startup */
176 int resolv_init(void)
177 {
178         int res = -1;
179         _resolv_init();
180
181 #ifdef USE_NAPTR
182         init_naptr_proto_prefs();
183 #endif
184         /* init counter API only at startup
185          * This function must be called before DNS cache init method (if available)
186          */
187         res = stat_init();
188         return res;
189 }
190
191 /* wrapper function to reinitialize the resolver
192  * This function must be called by each child process whenever
193  * a resolver option changes
194  */
195 void resolv_reinit(str *gname, str *name)
196 {
197         _resolv_init();
198
199 #ifdef DNS_WATCHDOG_SUPPORT
200         if (on_resolv_reinit_cb) on_resolv_reinit_cb(name);
201 #endif
202         LOG(L_DBG, "DEBUG: resolv_reinit(): "
203                 "DNS resolver has been reinitialized\n");
204 }
205
206 /* fixup function for dns_reinit variable
207  * (resets the variable to 0)
208  */
209 int dns_reinit_fixup(void *handle, str *gname, str *name, void **val)
210 {
211         *val = (void *)(long)0;
212         return 0;
213 }
214
215 /* wrapper function to recalculate the naptr protocol preferences */
216 void reinit_naptr_proto_prefs(str *gname, str *name)
217 {
218 #ifdef USE_NAPTR
219         init_naptr_proto_prefs();
220 #endif
221 }
222
223 /* fixup function for dns_try_ipv6
224  * verifies that SER really listens on an ipv6 interface
225  */
226 int dns_try_ipv6_fixup(void *handle, str *gname, str *name, void **val)
227 {
228         if ((int)(long)(*val) && !(socket_types & SOCKET_T_IPV6)) {
229                 LOG(L_ERR, "ERROR: dns_try_ipv6_fixup(): "
230                         "SER does not listen on any ipv6 interface, "
231                         "there is no point in resolving ipv6 addresses\n");
232                 return -1;
233         }
234         return 0;
235 }
236
237  /*  skips over a domain name in a dns message
238  *  (it can be  a sequence of labels ending in \0, a pointer or
239  *   a sequence of labels ending in a pointer -- see rfc1035
240  *   returns pointer after the domain name or null on error*/
241 unsigned char* dns_skipname(unsigned char* p, unsigned char* end)
242 {
243         while(p<end){
244                 /* check if \0 (root label length) */
245                 if (*p==0){
246                         p+=1;
247                         break;
248                 }
249                 /* check if we found a pointer */
250                 if (((*p)&0xc0)==0xc0){
251                         /* if pointer skip over it (2 bytes) & we found the end */
252                         p+=2;
253                         break;
254                 }
255                 /* normal label */
256                 p+=*p+1;
257         }
258         return (p>end)?0:p;
259 }
260
261
262
263 /* parses the srv record into a srv_rdata structure
264  *   msg   - pointer to the dns message
265  *   end   - pointer to the end of the message
266  *   eor   - pointer to the end of the record/rdata
267  *   rdata - pointer  to the rdata part of the srv answer
268  * returns 0 on error, or a dyn. alloc'ed srv_rdata structure */
269 /* SRV rdata format:
270  *            111111
271  *  0123456789012345
272  * +----------------+
273  * |     priority   |
274  * |----------------|
275  * |     weight     |
276  * |----------------|
277  * |   port number  |
278  * |----------------|
279  * |                |
280  * ~      name      ~
281  * |                |
282  * +----------------+
283  */
284 struct srv_rdata* dns_srv_parser( unsigned char* msg, unsigned char* end,
285                                                                   unsigned char* eor,
286                                                                   unsigned char* rdata)
287 {
288         struct srv_rdata* srv;
289         unsigned short priority;
290         unsigned short weight;
291         unsigned short port;
292         int len;
293         char name[MAX_DNS_NAME];
294         
295         srv=0;
296         if ((rdata+6+1)>eor) goto error;
297         
298         memcpy((void*)&priority, rdata, 2);
299         memcpy((void*)&weight,   rdata+2, 2);
300         memcpy((void*)&port,     rdata+4, 2);
301         rdata+=6;
302         if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)<0)
303                 goto error;
304         len=strlen(name);
305         if (len>255)
306                 goto error;
307         /* alloc enought space for the struct + null terminated name */
308         srv=local_malloc(sizeof(struct srv_rdata)-1+len+1);
309         if (srv==0){
310                 LOG(L_ERR, "ERROR: dns_srv_parser: out of memory\n");
311                 goto error;
312         }
313         srv->priority=ntohs(priority);
314         srv->weight=ntohs(weight);
315         srv->port=ntohs(port);
316         srv->name_len=len;
317         memcpy(srv->name, name, srv->name_len);
318         srv->name[srv->name_len]=0;
319         
320         return srv;
321 error:
322         if (srv) local_free(srv);
323         return 0;
324 }
325
326
327 /* parses the naptr record into a naptr_rdata structure
328  *   msg   - pointer to the dns message
329  *   end   - pointer to the end of the message
330  *   eor   - pointer to the end of the record/rdata
331  *   rdata - pointer  to the rdata part of the naptr answer
332  * returns 0 on error, or a dyn. alloc'ed naptr_rdata structure */
333 /* NAPTR rdata format:
334  *            111111
335  *  0123456789012345
336  * +----------------+
337  * |      order     |
338  * |----------------|
339  * |   preference   |
340  * |----------------|
341  * ~     flags      ~
342  * |   (string)     |
343  * |----------------|
344  * ~    services    ~
345  * |   (string)     |
346  * |----------------|
347  * ~    regexp      ~
348  * |   (string)     |
349  * |----------------|
350  * ~  replacement   ~
351    |    (name)      |
352  * +----------------+
353  */
354 struct naptr_rdata* dns_naptr_parser( unsigned char* msg, unsigned char* end,
355                                                                                 unsigned char* eor,
356                                                                                 unsigned char* rdata)
357 {
358         struct naptr_rdata* naptr;
359         unsigned char* flags;
360         unsigned char* services;
361         unsigned char* regexp;
362         unsigned short order;
363         unsigned short pref;
364         unsigned char flags_len;
365         unsigned char services_len;
366         unsigned char regexp_len;
367         int len;
368         char repl[MAX_DNS_NAME];
369         
370         naptr = 0;
371         if ((rdata + 7 + 1)>eor) goto error;
372         
373         memcpy((void*)&order, rdata, 2);
374         memcpy((void*)&pref, rdata + 2, 2);
375         flags_len = rdata[4];
376         if ((rdata + 7 + 1 +  flags_len) > eor)
377                 goto error;
378         flags=rdata+5;
379         services_len = rdata[5 + flags_len];
380         if ((rdata + 7 + 1 + flags_len + services_len) > eor)
381                 goto error;
382         services=rdata + 6 + flags_len;
383         regexp_len = rdata[6 + flags_len + services_len];
384         if ((rdata + 7 +1 + flags_len + services_len + regexp_len) > eor)
385                 goto error;
386         regexp=rdata + 7 + flags_len + services_len;
387         rdata = rdata + 7 + flags_len + services_len + regexp_len;
388         if (dn_expand(msg, end, rdata, repl, MAX_DNS_NAME-1) == -1)
389                 goto error;
390         len=strlen(repl);
391         if (len>255)
392                 goto error;
393         naptr=local_malloc(sizeof(struct naptr_rdata)+flags_len+services_len+
394                                                 regexp_len+len+1-1);
395         if (naptr == 0){
396                 LOG(L_ERR, "ERROR: dns_naptr_parser: out of memory\n");
397                 goto error;
398         }
399         naptr->order=ntohs(order);
400         naptr->pref=ntohs(pref);
401         
402         naptr->flags=&naptr->str_table[0];
403         naptr->flags_len=flags_len;
404         memcpy(naptr->flags, flags, naptr->flags_len);
405         naptr->services=&naptr->str_table[flags_len];
406         naptr->services_len=services_len;
407         memcpy(naptr->services, services, naptr->services_len);
408         naptr->regexp=&naptr->str_table[flags_len+services_len];
409         naptr->regexp_len=regexp_len;
410         memcpy(naptr->regexp, regexp, naptr->regexp_len);
411         naptr->repl=&naptr->str_table[flags_len+services_len+regexp_len];
412         naptr->repl_len=len;
413         memcpy(naptr->repl, repl, len);
414         naptr->repl[len]=0; /* null term. */
415         
416         return naptr;
417 error:
418         if (naptr) local_free(naptr);
419         return 0;
420 }
421
422
423
424 /* parses a CNAME record into a cname_rdata structure */
425 struct cname_rdata* dns_cname_parser( unsigned char* msg, unsigned char* end,
426                                                                           unsigned char* rdata)
427 {
428         struct cname_rdata* cname;
429         int len;
430         char name[MAX_DNS_NAME];
431         
432         cname=0;
433         if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)==-1)
434                 goto error;
435         len=strlen(name);
436         if (len>255)
437                 goto error;
438         /* alloc sizeof struct + space for the null terminated name */
439         cname=local_malloc(sizeof(struct cname_rdata)-1+len+1);
440         if(cname==0){
441                 LOG(L_ERR, "ERROR: dns_cname_parser: out of memory\n");
442                 goto error;
443         }
444         cname->name_len=len;
445         memcpy(cname->name, name, cname->name_len);
446         cname->name[cname->name_len]=0;
447         return cname;
448 error:
449         if (cname) local_free(cname);
450         return 0;
451 }
452
453
454
455 /* parses an A record rdata into an a_rdata structure
456  * returns 0 on error or a dyn. alloc'ed a_rdata struct
457  */
458 struct a_rdata* dns_a_parser(unsigned char* rdata, unsigned char* eor)
459 {
460         struct a_rdata* a;
461         
462         if (rdata+4>eor) goto error;
463         a=(struct a_rdata*)local_malloc(sizeof(struct a_rdata));
464         if (a==0){
465                 LOG(L_ERR, "ERROR: dns_a_parser: out of memory\n");
466                 goto error;
467         }
468         memcpy(a->ip, rdata, 4);
469         return a;
470 error:
471         return 0;
472 }
473
474
475
476 /* parses an AAAA (ipv6) record rdata into an aaaa_rdata structure
477  * returns 0 on error or a dyn. alloc'ed aaaa_rdata struct */
478 struct aaaa_rdata* dns_aaaa_parser(unsigned char* rdata, unsigned char* eor)
479 {
480         struct aaaa_rdata* aaaa;
481         
482         if (rdata+16>eor) goto error;
483         aaaa=(struct aaaa_rdata*)local_malloc(sizeof(struct aaaa_rdata));
484         if (aaaa==0){
485                 LOG(L_ERR, "ERROR: dns_aaaa_parser: out of memory\n");
486                 goto error;
487         }
488         memcpy(aaaa->ip6, rdata, 16);
489         return aaaa;
490 error:
491         return 0;
492 }
493
494
495
496 /** parses a TXT record into a txt_rdata structure.
497  *   @param msg   - pointer to the dns message
498  *   @param end   - pointer to the end of the record (rdata end)
499  *   @param rdata - pointer  to the rdata part of the txt answer
500  * returns 0 on error, or a dyn. alloc'ed txt_rdata structure */
501 /*  TXT rdata format:
502  *
503  * one or several character strings:
504  *  01234567
505  * +--------------------+
506  * | len    | string   / ...
507  * |------------------+
508  */
509 static struct txt_rdata* dns_txt_parser(unsigned char* msg, unsigned char* end,
510                                                                                 unsigned char* rdata)
511 {
512         struct txt_rdata* txt;
513         int len, n, i;
514         int str_size;
515         unsigned char* p;
516         unsigned char* st;
517         
518         txt=0;
519         if (unlikely((rdata+1)>end)) goto error;
520         n=0;
521         str_size=0;
522         /* count the number of strings */
523         p=rdata;
524         do{
525                 len=*p;
526                 p+=len+1;
527                 str_size+=len+1; /* 1 for the term. 0 */
528                 if (unlikely(p>end)) goto error;
529                 n++;
530         }while(p<end);
531         /* alloc sizeof struct + space for the dns_cstr array + space for
532            the strings */
533         txt=local_malloc(sizeof(struct txt_rdata) +(n-1)*sizeof(struct dns_cstr)+
534                                                 str_size);
535         if(unlikely(txt==0)){
536                 LOG(L_ERR, "ERROR: dns_txt_parser: out of memory\n");
537                 goto error;
538         }
539         /* string table */
540         st=(unsigned char*)txt+sizeof(struct txt_rdata) +
541                 (n-1)*sizeof(struct dns_cstr);
542         txt->cstr_no=n;
543         txt->tslen=str_size;
544         /* fill the structure */
545         p=rdata;
546         for (i=0; i<n; i++){
547                 len=*p;
548                 memcpy(st, p+1, len);
549                 st[len]=0;
550                 txt->txt[i].cstr_len=len;
551                 txt->txt[i].cstr=(char*)st;
552                 st+=len+1;
553                 p+=len+1;
554         }
555         return txt;
556 error:
557         if (txt) local_free(txt);
558         return 0;
559 }
560
561
562
563 /** parses an EBL record into a txt_rdata structure.
564  *   @param msg   - pointer to the dns message
565  *   @param end   - pointer to the end of the dns message
566  *   @param eor   - pointer to the end of the record (rdata end)
567  *   @param rdata - pointer  to the rdata part of the txt answer
568  * returns 0 on error, or a dyn. alloc'ed txt_rdata structure */
569 /*  EBL rdata format:
570  *  (see http://tools.ietf.org/html/draft-ietf-enum-branch-location-record-03)
571  * one or several character strings:
572  *  01234567
573  * +--------+
574  * | postion|
575  * +-----------+
576  * / separator /
577  * +-----------+
578  * /   apex    /
579  * +----------+
580  *
581  * where separator is a character string ( 8 bit len, followed by len chars)
582  * and apex is a domain-name.
583  */
584 static struct ebl_rdata* dns_ebl_parser(unsigned char* msg, unsigned char* end,
585                                                                                 unsigned char* eor,
586                                                                                 unsigned char* rdata)
587 {
588         struct ebl_rdata* ebl;
589         int sep_len;
590         int apex_len;
591         char apex[MAX_DNS_NAME];
592         
593         ebl=0;
594         /* check if len is at least 4 chars (minimum possible):
595              pos (1 byte) +  sep. (min 1 byte) + apex (min. 2 bytes) 
596            and also check if rdata+1 (pos) + 1 (sep. len) + sep_len + 1 is ok*/
597         if (unlikely(((rdata+4)>eor)||((rdata+1+1+rdata[1]+2)>eor))) goto error;
598         sep_len=rdata[1];
599         if (unlikely(dn_expand(msg, end, rdata+1+1+sep_len,
600                                                         apex, MAX_DNS_NAME-1)==-1))
601                 goto error;
602         apex_len=strlen(apex);
603         /* alloc sizeof struct + space for the 2 null-terminated strings */
604         ebl=local_malloc(sizeof(struct ebl_rdata)-1+sep_len+1+apex_len+1);
605         if (ebl==0){
606                 LOG(L_ERR, "ERROR: dns_ebl_parser: out of memory\n");
607                 goto error;
608         }
609         ebl->position=rdata[0];
610         ebl->separator=&ebl->str_table[0];
611         ebl->apex=ebl->separator+sep_len+1;
612         ebl->separator_len=sep_len;
613         ebl->apex_len=apex_len;
614         memcpy(ebl->separator, rdata+2, sep_len);
615         ebl->separator[sep_len]=0;
616         memcpy(ebl->apex, apex, apex_len);
617         ebl->apex[apex_len]=0;
618         
619         return ebl;
620 error:
621         if (ebl) local_free(ebl);
622         return 0;
623 }
624
625
626
627 /* parses a PTR record into a ptr_rdata structure */
628 struct ptr_rdata* dns_ptr_parser( unsigned char* msg, unsigned char* end,
629                                                                           unsigned char* rdata)
630 {
631         struct ptr_rdata* pname;
632         int len;
633         char name[MAX_DNS_NAME];
634         
635         pname=0;
636         if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)==-1)
637                 goto error;
638         len=strlen(name);
639         if (len>255)
640                 goto error;
641         /* alloc sizeof struct + space for the null terminated name */
642         pname=local_malloc(sizeof(struct ptr_rdata)-1+len+1);
643         if(pname==0){
644                 LOG(L_ERR, "ERROR: dns_ptr_parser: out of memory\n");
645                 goto error;
646         }
647         pname->ptrdname_len=len;
648         memcpy(pname->ptrdname, name, pname->ptrdname_len);
649         pname->ptrdname[pname->ptrdname_len]=0;
650         return pname;
651 error:
652         if (pname) local_free(pname);
653         return 0;
654 }
655
656
657
658 /* frees completely a struct rdata list */
659 void free_rdata_list(struct rdata* head)
660 {
661         struct rdata* l;
662         struct rdata* next_l;
663         l=head;
664         while (l != 0) {
665                 next_l = l->next;
666                 /* free the parsed rdata*/
667                 if (l->rdata) local_free(l->rdata);
668                 local_free(l);
669                 l = next_l;
670         }
671 }
672
673 #ifdef HAVE_RESOLV_RES
674 /* checks whether supplied name exists in the resolver search list
675  * returns 1 if found
676  *         0 if not found
677  */
678 int match_search_list(const struct __res_state* res, char* name) {
679         int i;
680         for (i=0; (i<MAXDNSRCH) && (res->dnsrch[i]); i++) {
681                 if (strcasecmp(name, res->dnsrch[i])==0) 
682                         return 1;
683         }
684         return 0;
685 }
686 #endif
687
688 /* gets the DNS records for name:type
689  * returns a dyn. alloc'ed struct rdata linked list with the parsed responses
690  * or 0 on error
691  * see rfc1035 for the query/response format */
692 struct rdata* get_record(char* name, int type, int flags)
693 {
694         int size;
695         int skip;
696         int qno, answers_no;
697         int i, r;
698         static union dns_query buff;
699         unsigned char* p;
700         unsigned char* end;
701         unsigned char* rd_end;
702         static char rec_name[MAX_DNS_NAME]; /* placeholder for the record name */
703         int rec_name_len;
704         unsigned short rtype, class, rdlength;
705         unsigned int ttl;
706         struct rdata* head;
707         struct rdata** crt;
708         struct rdata** last;
709         struct rdata* rd;
710         struct srv_rdata* srv_rd;
711         struct srv_rdata* crt_srv;
712         int search_list_used;
713         int name_len;
714         struct rdata* fullname_rd;
715         char c;
716         
717         name_len=strlen(name);
718
719         for (i = 0; i < name_len; i++) {
720             c = name[i];
721             if (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) ||
722                 ((c >= '0') && (c <= '9')) || (name[i] == '.') ||
723                 (name[i] == '-') || (name[i] == '_'))
724                         continue;
725             LM_DBG("'%s' is not domain name\n", name);
726             return 0;
727         }
728
729         if (cfg_get(core, core_cfg, dns_search_list)==0) {
730                 search_list_used=0;
731                 name_len=0;
732         } else {
733                 search_list_used=1;
734         }
735         fullname_rd=0;
736
737         size=dns_func.sr_res_search(name, C_IN, type, buff.buff, sizeof(buff));
738
739         if (unlikely(size<0)) {
740                 DBG("get_record: lookup(%s, %d) failed\n", name, type);
741                 goto not_found;
742         }
743         else if (unlikely(size > sizeof(buff))) size=sizeof(buff);
744         head=rd=0;
745         last=crt=&head;
746         
747         p=buff.buff+DNS_HDR_SIZE;
748         end=buff.buff+size;
749         if (unlikely(p>=end)) goto error_boundary;
750         qno=ntohs((unsigned short)buff.hdr.qdcount);
751
752         for (r=0; r<qno; r++){
753                 /* skip the name of the question */
754                 if (unlikely((p=dns_skipname(p, end))==0)) {
755                         LOG(L_ERR, "ERROR: get_record: skipname==0\n");
756                         goto error;
757                 }
758                 p+=2+2; /* skip QCODE & QCLASS */
759         #if 0
760                 for (;(p<end && (*p)); p++);
761                 p+=1+2+2; /* skip the ending  '\0, QCODE and QCLASS */
762         #endif
763                 if (unlikely(p>end)) {
764                         LOG(L_ERR, "ERROR: get_record: p>=end\n");
765                         goto error;
766                 }
767         };
768         answers_no=ntohs((unsigned short)buff.hdr.ancount);
769 again:
770         for (r=0; (r<answers_no) && (p<end); r++){
771 #if 0
772                 /*  ignore it the default domain name */
773                 if ((p=dns_skipname(p, end))==0) {
774                         LOG(L_ERR, "ERROR: get_record: skip_name=0 (#2)\n");
775                         goto error;
776                 }
777 #else
778                 if (unlikely((skip=dn_expand(buff.buff, end, p, rec_name,
779                                                         MAX_DNS_NAME-1))==-1)){
780                         LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name) failed\n");
781                         goto error;
782                 }
783 #endif
784                 p+=skip;
785                 rec_name_len=strlen(rec_name);
786                 if (unlikely(rec_name_len>255)){
787                         LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name): name too"
788                                         " long  (%d)\n", rec_name_len);
789                         goto error;
790                 }
791                 /* check if enough space is left for type, class, ttl & size */
792                 if (unlikely((p+2+2+4+2)>end)) goto error_boundary;
793                 /* get type */
794                 memcpy((void*) &rtype, (void*)p, 2);
795                 rtype=ntohs(rtype);
796                 p+=2;
797                 /* get  class */
798                 memcpy((void*) &class, (void*)p, 2);
799                 class=ntohs(class);
800                 p+=2;
801                 /* get ttl*/
802                 memcpy((void*) &ttl, (void*)p, 4);
803                 ttl=ntohl(ttl);
804                 p+=4;
805                 /* get size */
806                 memcpy((void*)&rdlength, (void*)p, 2);
807                 rdlength=ntohs(rdlength);
808                 p+=2;
809                 rd_end=p+rdlength;
810                 if (unlikely((rd_end)>end)) goto error_boundary;
811                 if ((flags & RES_ONLY_TYPE) && (rtype!=type)){
812                         /* skip */
813                         p=rd_end;
814                         continue;
815                 }
816                 /* expand the "type" record  (rdata)*/
817                 
818                 rd=(struct rdata*) local_malloc(sizeof(struct rdata)+rec_name_len+
819                                                                                 1-1);
820                 if (rd==0){
821                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
822                         goto error;
823                 }
824                 rd->type=rtype;
825                 rd->pclass=class;
826                 rd->ttl=ttl;
827                 rd->next=0;
828                 memcpy(rd->name, rec_name, rec_name_len);
829                 rd->name[rec_name_len]=0;
830                 rd->name_len=rec_name_len;
831                 /* check if full name matches */
832                 if ((search_list_used==1)&&(fullname_rd==0)&&
833                                 (rec_name_len>=name_len)&&
834                                 (strncasecmp(rec_name, name, name_len)==0)) {
835                         /* now we have record whose name is the same (up-to the
836                          * name_len with the searched one):
837                          * if the length is the same - we found full match, no fake
838                          *  cname needed, just clear the flag
839                          * if the length of the name differs - it has matched using
840                          *  search list remember the rd, so we can create fake CNAME
841                          *  record when all answers are used and no better match found
842                          */
843                         if (rec_name_len==name_len)
844                                 search_list_used=0;
845                         /* this is safe.... here was rec_name_len > name_len */
846                         else if (rec_name[name_len]=='.') {
847 #ifdef HAVE_RESOLV_RES
848                                 if ((cfg_get(core, core_cfg, dns_search_fmatch)==0) ||
849                                                 (match_search_list(&_res, rec_name+name_len+1)!=0))
850 #endif
851                                         fullname_rd=rd;
852                         }
853                 }
854                 switch(rtype){
855                         case T_SRV:
856                                 srv_rd= dns_srv_parser(buff.buff, end, rd_end, p);
857                                 rd->rdata=(void*)srv_rd;
858                                 if (unlikely(srv_rd==0)) goto error_parse;
859                                 
860                                 /* insert sorted into the list */
861                                 for (crt=&head; *crt; crt= &((*crt)->next)){
862                                         if ((*crt)->type!=T_SRV)
863                                                 continue;
864                                         crt_srv=(struct srv_rdata*)(*crt)->rdata;
865                                         if ((srv_rd->priority <  crt_srv->priority) ||
866                                            ( (srv_rd->priority == crt_srv->priority) && 
867                                                          (srv_rd->weight > crt_srv->weight) ) ){
868                                                 /* insert here */
869                                                 goto skip;
870                                         }
871                                 }
872                                 last=&(rd->next); /*end of for => this will be the last
873                                                                         element*/
874                         skip:
875                                 /* insert here */
876                                 rd->next=*crt;
877                                 *crt=rd;
878                                 break;
879                         case T_A:
880                                 rd->rdata=(void*) dns_a_parser(p, rd_end);
881                                 if (unlikely(rd->rdata==0)) goto error_parse;
882                                 *last=rd; /* last points to the last "next" or the list
883                                                                 head*/
884                                 last=&(rd->next);
885                                 break;
886                         case T_AAAA:
887                                 rd->rdata=(void*) dns_aaaa_parser(p, rd_end);
888                                 if (unlikely(rd->rdata==0)) goto error_parse;
889                                 *last=rd;
890                                 last=&(rd->next);
891                                 break;
892                         case T_CNAME:
893                                 rd->rdata=(void*) dns_cname_parser(buff.buff, end, p);
894                                 if(unlikely(rd->rdata==0)) goto error_parse;
895                                 *last=rd;
896                                 last=&(rd->next);
897                                 break;
898                         case T_NAPTR:
899                                 rd->rdata=(void*)dns_naptr_parser(buff.buff, end, rd_end, p);
900                                 if(unlikely(rd->rdata==0)) goto error_parse;
901                                 *last=rd;
902                                 last=&(rd->next);
903                                 break;
904                         case T_TXT:
905                                 rd->rdata= dns_txt_parser(buff.buff, rd_end, p);
906                                 if (rd->rdata==0) goto error_parse;
907                                 *last=rd;
908                                 last=&(rd->next);
909                                 break;
910                         case T_EBL:
911                                 rd->rdata= dns_ebl_parser(buff.buff, end, rd_end, p);
912                                 if (rd->rdata==0) goto error_parse;
913                                 *last=rd;
914                                 last=&(rd->next);
915                                 break;
916                         case T_PTR:
917                                 rd->rdata=(void*) dns_ptr_parser(buff.buff, end, p);
918                                 if(unlikely(rd->rdata==0)) goto error_parse;
919                                 *last=rd;
920                                 last=&(rd->next);
921                                 break;
922                         default:
923                                 LOG(L_ERR, "WARNING: get_record: unknown type %d\n", rtype);
924                                 rd->rdata=0;
925                                 *last=rd;
926                                 last=&(rd->next);
927                 }
928                 
929                 p+=rdlength;
930                 
931         }
932         if (flags & RES_AR){
933                 flags&=~RES_AR;
934                 answers_no=ntohs((unsigned short)buff.hdr.nscount);
935 #ifdef RESOLVE_DBG
936                 DBG("get_record: skipping %d NS (p=%p, end=%p)\n", answers_no, p,
937                                 end);
938 #endif
939                 for (r=0; (r<answers_no) && (p<end); r++){
940                         /* skip over the ns records */
941                         if ((p=dns_skipname(p, end))==0) {
942                                 LOG(L_ERR, "ERROR: get_record: skip_name=0 (#3)\n");
943                                 goto error;
944                         }
945                         /* check if enough space is left for type, class, ttl & size */
946                         if (unlikely((p+2+2+4+2)>end)) goto error_boundary;
947                         memcpy((void*)&rdlength, (void*)p+2+2+4, 2);
948                         p+=2+2+4+2+ntohs(rdlength);
949                 }
950                 answers_no=ntohs((unsigned short)buff.hdr.arcount);
951 #ifdef RESOLVE_DBG
952                 DBG("get_record: parsing %d ARs (p=%p, end=%p)\n", answers_no, p,
953                                 end);
954 #endif
955                 goto again; /* add also the additional records */
956         }
957
958         /* if the name was expanded using DNS search list
959          * create fake CNAME record to convert the short name
960          * (queried) to long name (answered)
961          */
962         if ((search_list_used==1)&&(fullname_rd!=0)) {
963                 rd=(struct rdata*) local_malloc(sizeof(struct rdata)+name_len+1-1);
964                 if (unlikely(rd==0)){
965                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
966                         goto error;
967                 }
968                 rd->type=T_CNAME;
969                 rd->pclass=fullname_rd->pclass;
970                 rd->ttl=fullname_rd->ttl;
971                 rd->next=head;
972                 memcpy(rd->name, name, name_len);
973                 rd->name[name_len]=0;
974                 rd->name_len=name_len;
975                 /* alloc sizeof struct + space for the null terminated name */
976                 rd->rdata=(void*)local_malloc(sizeof(struct cname_rdata)-1+
977                                                                                 head->name_len+1);
978                 if(unlikely(rd->rdata==0)){
979                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
980                         goto error_rd;
981                 }
982                 ((struct cname_rdata*)(rd->rdata))->name_len=fullname_rd->name_len;
983                 memcpy(((struct cname_rdata*)(rd->rdata))->name, fullname_rd->name,
984                                 fullname_rd->name_len);
985                 ((struct cname_rdata*)(rd->rdata))->name[head->name_len]=0;
986                 head=rd;
987         }
988
989         return head;
990 error_boundary:
991                 LOG(L_ERR, "ERROR: get_record: end of query buff reached\n");
992                 if (head) free_rdata_list(head);
993                 return 0;
994 error_parse:
995                 LOG(L_ERR, "ERROR: get_record: rdata parse error (%s, %d), %p-%p"
996                                                 " rtype=%d, class=%d, ttl=%d, rdlength=%d \n",
997                                 name, type,
998                                 p, end, rtype, class, ttl, rdlength);
999 error_rd:
1000                 if (rd) local_free(rd); /* rd->rdata=0 & rd is not linked yet into
1001                                                                    the list */
1002 error:
1003                 LOG(L_ERR, "ERROR: get_record \n");
1004                 if (head) free_rdata_list(head);
1005 not_found:
1006         /* increment error counter */
1007         counter_inc(dns_cnts_h.failed_dns_req);
1008         return 0;
1009 }
1010
1011 #ifdef USE_NAPTR
1012
1013 /* service matching constants, lowercase */
1014 #define SIP_SCH         0x2b706973
1015 #define SIPS_SCH        0x73706973
1016 #define SIP_D2U         0x00753264
1017 #define SIP_D2T         0x00743264
1018 #define SIP_D2S         0x00733264
1019 #define SIPS_D2T        0x7432642b
1020
1021
1022 /* get protocol from a naptr rdata and check for validity
1023  * returns > 0 (PROTO_UDP, PROTO_TCP, PROTO_SCTP or PROTO_TLS)
1024  *         <=0  on error 
1025  */
1026 char naptr_get_sip_proto(struct naptr_rdata* n)
1027 {
1028         unsigned int s;
1029         char proto;
1030
1031         proto=-1;
1032         
1033         if ((n->flags_len!=1) || ((*n->flags | 0x20 )!='s'))
1034                 return -1;
1035         if (n->regexp_len!=0)
1036                 return -1;
1037         /* SIP+D2U, SIP+D2T, SIP+D2S, SIPS+D2T */
1038         if (n->services_len==7){ /* SIP+D2X */
1039                 s=n->services[0]+(n->services[1]<<8)+(n->services[2]<<16)+
1040                                 (n->services[3]<<24);
1041                 s|=0x20202020;
1042                 if (s==SIP_SCH){
1043                         s=n->services[4]+(n->services[5]<<8)+(n->services[6]<<16);
1044                         s|=0x00202020;
1045                         switch(s){
1046                                 case SIP_D2U:
1047                                         proto=PROTO_UDP;
1048                                         break;
1049                                 case SIP_D2T:
1050                                         proto=PROTO_TCP;
1051                                         break;
1052                                 case SIP_D2S:
1053                                         proto=PROTO_SCTP;
1054                                         break;
1055                                 default:
1056                                         return -1;
1057                         }
1058                 }else{
1059                         return -1;
1060                 }
1061         }else if  (n->services_len==8){ /*SIPS+D2T */
1062                 s=n->services[0]+(n->services[1]<<8)+(n->services[2]<<16)+
1063                                 (n->services[3]<<24);
1064                 s|=0x20202020;
1065                 if (s==SIPS_SCH){
1066                         s=n->services[4]+(n->services[5]<<8)+(n->services[6]<<16)+
1067                                         (n->services[7]<<24);
1068                         s|=0x20202020;
1069                         if (s==SIPS_D2T){
1070                                 proto=PROTO_TLS;
1071                         }
1072                 }else{
1073                         return -1;
1074                 }
1075         }else{
1076                 return -1;
1077         }
1078         return proto;
1079 }
1080
1081
1082
1083 inline static int proto_pref_score(char proto)
1084 {
1085         if ((proto>=PROTO_UDP) && (proto<= PROTO_LAST))
1086                 return naptr_proto_pref[(int)proto];
1087         return 0;
1088 }
1089
1090
1091
1092 /* returns true if we support the protocol */
1093 int naptr_proto_supported(char proto)
1094 {
1095         if (proto_pref_score(proto)<0)
1096                 return 0;
1097         switch(proto){
1098                 case PROTO_UDP:
1099                         return 1;
1100 #ifdef USE_TCP
1101                 case PROTO_TCP:
1102                         return !tcp_disable;
1103 #ifdef USE_TLS
1104                 case PROTO_TLS:
1105                         return !tls_disable;
1106 #endif /* USE_TLS */
1107 #endif /* USE_TCP */
1108 #ifdef USE_SCTP
1109                 case PROTO_SCTP:
1110                         return !sctp_disable;
1111 #endif
1112         }
1113         return 0;
1114 }
1115
1116
1117
1118
1119 /* returns true if new_proto is preferred over old_proto */
1120 int naptr_proto_preferred(char new_proto, char old_proto)
1121 {
1122         return proto_pref_score(new_proto)>proto_pref_score(old_proto);
1123 }
1124
1125
1126 /* choose between 2 naptr records, should take into account local
1127  * preferences too
1128  * returns 1 if the new record was selected, 0 otherwise */
1129 int naptr_choose (struct naptr_rdata** crt, char* crt_proto,
1130                                                                         struct naptr_rdata* n , char n_proto)
1131 {
1132 #ifdef NAPTR_DBG
1133         DBG("naptr_choose(o: %d w: %d p:%d , o: %d w:%d p:%d)\n",
1134                         *crt?(int)(*crt)->order:-1, *crt?(int)(*crt)->pref:-1,
1135                         (int)*crt_proto,
1136                         (int)n->order, (int)n->pref, (int)n_proto);
1137 #endif
1138         if ((*crt==0) || ((*crt_proto!=n_proto) && 
1139                                                 ( naptr_proto_preferred(n_proto, *crt_proto))) )
1140                         goto change;
1141         if (!naptr_proto_preferred(*crt_proto, n_proto) && 
1142                         ((n->order<(*crt)->order) || ((n->order== (*crt)->order) &&
1143                                                                 (n->pref < (*crt)->pref)))){
1144                         goto change;
1145         }
1146 #ifdef NAPTR_DBG
1147         DBG("naptr_choose: no change\n");
1148 #endif
1149         return 0;
1150 change:
1151 #ifdef NAPTR_DBG
1152         DBG("naptr_choose: changed\n");
1153 #endif
1154         *crt_proto=n_proto;
1155         *crt=n;
1156         return 1;
1157 }
1158 #endif /* USE_NAPTR */
1159
1160
1161
1162 /* internal sip srv resolver: resolves a host name trying:
1163  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
1164  *   query will be used for an A/AAAA lookup.
1165  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
1166  *   and *proto!=0 or port==0 && proto==0)
1167  * when performing SRV lookup (*port==0) it will use *proto to look for
1168  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
1169  * If zt is set, name will be assumed to be 0 terminated and some copy 
1170  * operations will be avoided.
1171  * If is_srv is set it will assume name has the srv prefixes for sip already
1172  *  appended and it's already 0-term'ed; if not it will append them internally.
1173  * If ars !=0, it will first try to look through them and only if the SRV
1174  *   record is not found it will try doing a DNS query  (ars will not be
1175  *   freed, the caller should take care of them)
1176  * returns: hostent struct & *port filled with the port from the SRV record;
1177  *  0 on error
1178  */
1179 struct hostent* srv_sip_resolvehost(str* name, int zt, unsigned short* port,
1180                                                                         char* proto, int is_srv, struct rdata* ars)
1181 {
1182         struct hostent* he;
1183         struct ip_addr* ip;
1184         static char tmp[MAX_DNS_NAME]; /* tmp. buff. for SRV lookups and
1185                                           null. term  strings */
1186         struct rdata* l;
1187         struct srv_rdata* srv;
1188         struct rdata* srv_head;
1189         char* srv_target;
1190         char srv_proto;
1191
1192         /* init */
1193         srv_head=0;
1194         srv_target=0;
1195         if (name->len >= MAX_DNS_NAME) {
1196                 LOG(L_ERR, "srv_sip_resolvehost: domain name too long\n");
1197                 he=0;
1198                 goto end;
1199         }
1200 #ifdef RESOLVE_DBG
1201         DBG("srv_sip_resolvehost: %.*s:%d proto=%d\n", name->len, name->s,
1202                         port?(int)*port:-1, proto?(int)*proto:-1);
1203 #endif
1204         if (is_srv){
1205                 /* skip directly to srv resolving */
1206                 srv_proto=(proto)?*proto:0;
1207                 *port=(srv_proto==PROTO_TLS)?SIPS_PORT:SIP_PORT;
1208                 if (zt){
1209                         srv_target=name->s; /* name.s must be 0 terminated in
1210                                                                   this case */
1211                 }else{
1212                         memcpy(tmp, name->s, name->len);
1213                         tmp[name->len] = '\0';
1214                         srv_target=tmp;
1215                 }
1216                 goto do_srv; /* skip to the actual srv query */
1217         }
1218         if (proto){ /* makes sure we have a protocol set*/
1219                 if (*proto==0)
1220                         *proto=srv_proto=PROTO_UDP; /* default */
1221                 else
1222                         srv_proto=*proto;
1223         }else{
1224                 srv_proto=PROTO_UDP;
1225         }
1226         /* try SRV if no port specified (draft-ietf-sip-srv-06) */
1227         if ((port)&&(*port==0)){
1228                 *port=(srv_proto==PROTO_TLS)?SIPS_PORT:SIP_PORT; /* just in case we
1229                                                                                                                   don't find another */
1230                 /* check if it's an ip address */
1231                 if (((ip=str2ip(name))!=0)
1232                           || ((ip=str2ip6(name))!=0) 
1233                          ){
1234                         /* we are lucky, this is an ip address */
1235                         he=ip_addr2he(name, ip);
1236                         goto end;
1237                 }
1238                 if ((name->len+SRV_MAX_PREFIX_LEN+1)>MAX_DNS_NAME){
1239                         LOG(L_WARN, "WARNING: srv_sip_resolvehost: domain name too long (%d),"
1240                                                 " unable to perform SRV lookup\n", name->len);
1241                 }else{
1242                         
1243                         switch(srv_proto){
1244                                 case PROTO_UDP:
1245                                 case PROTO_TCP:
1246                                 case PROTO_TLS:
1247                                 case PROTO_SCTP:
1248                                         create_srv_name(srv_proto, name, tmp);
1249                                         break;
1250                                 default:
1251                                         LOG(L_CRIT, "BUG: srv_sip_resolvehost: unknown proto %d\n",
1252                                                         srv_proto);
1253                                         he=0;
1254                                         goto end;
1255                         }
1256                         srv_target=tmp;
1257 do_srv:
1258                         /* try to find the SRV records inside previous ARs  first*/
1259                         for (l=ars; l; l=l->next){
1260                                 if (l->type!=T_SRV) continue; 
1261                                 srv=(struct srv_rdata*) l->rdata;
1262                                 if (srv==0){
1263                                         LOG(L_CRIT, "srv_sip_resolvehost: BUG: null rdata\n");
1264                                         /* cleanup on exit only */
1265                                         break;
1266                                 }
1267                                 he=resolvehost(srv->name);
1268                                 if (he!=0){
1269                                         /* we found it*/
1270 #ifdef RESOLVE_DBG
1271                                         DBG("srv_sip_resolvehost: found SRV(%s) = %s:%d in AR\n",
1272                                                         srv_target, srv->name, srv->port);
1273 #endif
1274                                         *port=srv->port;
1275                                         /* cleanup on exit */
1276                                         goto end;
1277                                 }
1278                         }
1279                         srv_head=get_record(srv_target, T_SRV, RES_ONLY_TYPE);
1280                         for(l=srv_head; l; l=l->next){
1281                                 if (l->type!=T_SRV) continue; /*should never happen*/
1282                                 srv=(struct srv_rdata*) l->rdata;
1283                                 if (srv==0){
1284                                         LOG(L_CRIT, "srv_sip_resolvehost: BUG: null rdata\n");
1285                                         /* cleanup on exit only */
1286                                         break;
1287                                 }
1288                                 he=resolvehost(srv->name);
1289                                 if (he!=0){
1290                                         /* we found it*/
1291 #ifdef RESOLVE_DBG
1292                                         DBG("srv_sip_resolvehost: SRV(%s) = %s:%d\n",
1293                                                         srv_target, srv->name, srv->port);
1294 #endif
1295                                         *port=srv->port;
1296                                         /* cleanup on exit */
1297                                         goto end;
1298                                 }
1299                         }
1300                         if (is_srv){
1301                                 /* if the name was already into SRV format it doesn't make
1302                                  * any sense to fall back to A/AAAA */
1303                                 he=0;
1304                                 goto end;
1305                         }
1306                         /* cleanup on exit */
1307 #ifdef RESOLVE_DBG
1308                         DBG("srv_sip_resolvehost: no SRV record found for %.*s," 
1309                                         " trying 'normal' lookup...\n", name->len, name->s);
1310 #endif
1311                 }
1312         }
1313         if (likely(!zt)){
1314                 memcpy(tmp, name->s, name->len);
1315                 tmp[name->len] = '\0';
1316                 he=resolvehost(tmp);
1317         }else{
1318                 he=resolvehost(name->s);
1319         }
1320 end:
1321 #ifdef RESOLVE_DBG
1322         DBG("srv_sip_resolvehost: returning %p (%.*s:%d proto=%d)\n",
1323                         he, name->len, name->s,
1324                         port?(int)*port:-1, proto?(int)*proto:-1);
1325 #endif
1326         if (srv_head)
1327                 free_rdata_list(srv_head);
1328         return he;
1329 }
1330
1331
1332
1333 #ifdef USE_NAPTR 
1334
1335
1336 /* iterates over a naptr rr list, returning each time a "good" naptr record
1337  * is found.( srv type, no regex and a supported protocol)
1338  * params:
1339  *         naptr_head - naptr rr list head
1340  *         tried      - bitmap used to keep track of the already tried records
1341  *                      (no more then sizeof(tried)*8 valid records are 
1342  *                      ever walked
1343  *         srv_name   - if succesfull, it will be set to the selected record
1344  *                      srv name (naptr repl.)
1345  *         proto      - if succesfull it will be set to the selected record
1346  *                      protocol
1347  * returns  0 if no more records found or a pointer to the selected record
1348  *  and sets  protocol and srv_name
1349  * WARNING: when calling first time make sure you run first 
1350  *           naptr_iterate_init(&tried)
1351  */
1352 struct rdata* naptr_sip_iterate(struct rdata* naptr_head, 
1353                                                                                 naptr_bmp_t* tried,
1354                                                                                 str* srv_name, char* proto)
1355 {
1356         int i, idx;
1357         struct rdata* l;
1358         struct rdata* l_saved;
1359         struct naptr_rdata* naptr;
1360         struct naptr_rdata* naptr_saved;
1361         char saved_proto;
1362         char naptr_proto;
1363
1364         idx=0;
1365         naptr_proto=PROTO_NONE;
1366         naptr_saved=0;
1367         l_saved=0;
1368         saved_proto=0;
1369         i=0;
1370         for(l=naptr_head; l && (i<MAX_NAPTR_RRS); l=l->next){
1371                 if (l->type!=T_NAPTR) continue; 
1372                 naptr=(struct naptr_rdata*) l->rdata;
1373                 if (naptr==0){
1374                                 LOG(L_CRIT, "naptr_iterate: BUG: null rdata\n");
1375                         goto end;
1376                 }
1377                 /* check if valid and get proto */
1378                 if ((naptr_proto=naptr_get_sip_proto(naptr))<=0) continue;
1379                 if (*tried& (1<<i)){
1380                         i++;
1381                         continue; /* already tried */
1382                 }
1383 #ifdef NAPTR_DBG
1384                 DBG("naptr_iterate: found a valid sip NAPTR rr %.*s,"
1385                                         " proto %d\n", naptr->repl_len, naptr->repl, 
1386                                         (int)naptr_proto);
1387 #endif
1388                 if ((naptr_proto_supported(naptr_proto))){
1389                         if (naptr_choose(&naptr_saved, &saved_proto,
1390                                                                 naptr, naptr_proto))
1391                                 idx=i;
1392                                 l_saved=l;
1393                         }
1394                 i++;
1395         }
1396         if (naptr_saved){
1397                 /* found something */
1398 #ifdef NAPTR_DBG
1399                 DBG("naptr_iterate: choosed NAPTR rr %.*s, proto %d"
1400                                         " tried: 0x%x\n", naptr_saved->repl_len, 
1401                                         naptr_saved->repl, (int)saved_proto, *tried);
1402 #endif
1403                 *tried|=1<<idx;
1404                 *proto=saved_proto;
1405                 srv_name->s=naptr_saved->repl;
1406                 srv_name->len=naptr_saved->repl_len;
1407                 return l_saved;
1408         }
1409 end:
1410         return 0;
1411 }
1412
1413 /* Prepend srv prefix according to the proto. */
1414 void create_srv_name(char proto, str *name, char *srv) {
1415         switch (proto) {
1416                 case PROTO_UDP:
1417                         memcpy(srv, SRV_UDP_PREFIX, SRV_UDP_PREFIX_LEN);
1418                         memcpy(srv+SRV_UDP_PREFIX_LEN, name->s, name->len);
1419                         srv[SRV_UDP_PREFIX_LEN + name->len] = '\0';
1420                         break;
1421                 case PROTO_TCP:
1422                         memcpy(srv, SRV_TCP_PREFIX, SRV_TCP_PREFIX_LEN);
1423                         memcpy(srv+SRV_TCP_PREFIX_LEN, name->s, name->len);
1424                         srv[SRV_TCP_PREFIX_LEN + name->len] = '\0';
1425                         break;
1426                 case PROTO_TLS:
1427                         memcpy(srv, SRV_TLS_PREFIX, SRV_TLS_PREFIX_LEN);
1428                         memcpy(srv+SRV_TLS_PREFIX_LEN, name->s, name->len);
1429                         srv[SRV_TLS_PREFIX_LEN + name->len] = '\0';
1430                         break;
1431                 case PROTO_SCTP:
1432                         memcpy(srv, SRV_SCTP_PREFIX, SRV_SCTP_PREFIX_LEN);
1433                         memcpy(srv+SRV_SCTP_PREFIX_LEN, name->s, name->len);
1434                         srv[SRV_SCTP_PREFIX_LEN + name->len] = '\0';
1435                         break;
1436                 default:
1437                         LOG(L_CRIT, "BUG: %s: unknown proto %d\n", __func__, proto);
1438         }
1439 }
1440
1441 size_t create_srv_pref_list(char *proto, struct dns_srv_proto *list) {
1442         struct dns_srv_proto tmp;
1443         size_t i,j,list_len;
1444         int default_order,max;
1445
1446         /* if proto available, then add only the forced protocol to the list */
1447         if (proto && *proto!=PROTO_NONE){
1448                 list[0].proto=*proto;
1449                 list_len=1;
1450         } else {
1451                 list_len = 0;
1452                 /*get protocols and preference scores, and add availble protocol(s) and score(s) to the list*/
1453                 for (i=PROTO_UDP; i<PROTO_LAST;i++) {
1454                         tmp.proto_pref = proto_pref_score(i);
1455                         /* if -1 so disabled continue with next protocol*/
1456                         if (naptr_proto_supported(i) == 0) {
1457                                 continue;
1458                         } else {
1459                                 list[i-1].proto_pref=tmp.proto_pref;
1460                                 list[i-1].proto=i;
1461                                 list_len++;
1462                         }
1463                 };
1464
1465                 /* if all protocol prefence scores equal, then set the perference to default values: udp,tcp,tls,sctp */
1466                 for (i=1; i<list_len;i++) {
1467                         if(list[0].proto_pref!=list[i].proto_pref){
1468                                 default_order=0;
1469                         }
1470                 }
1471                 if (default_order){
1472                         for (i=0; i<list_len;i++) {
1473                                 list[i].proto_pref=proto_pref_score(i);
1474                         }
1475                 }
1476
1477                 /* sorting the list */
1478                 for (i=0;i<list_len-1;i++) {
1479                         max=i;
1480                         for (j=i+1;j<list_len;j++) {
1481                                 if (list[j].proto_pref>list[max].proto_pref) { 
1482                                         max=j; 
1483                                 }
1484                         }
1485                         if (i!=max) {
1486                                 tmp=list[i];
1487                                 list[i]=list[max];
1488                                 list[max]=tmp;
1489                         }
1490                 }
1491
1492         }
1493         return list_len;
1494 }
1495
1496 /* Resolves SRV if no naptr found. 
1497  * It reuse dns_pref values and according that resolves supported protocols. 
1498  * If dns_pref are equal then it use udp,tcp,tls,sctp order.
1499  * returns: hostent struct & *port filled with the port from the SRV record;
1500  *  0 on error
1501  */
1502
1503 struct hostent* no_naptr_srv_sip_resolvehost(str* name, unsigned short* port, char* proto)
1504 {
1505         struct dns_srv_proto srv_proto_list[PROTO_LAST];
1506         struct hostent* he;
1507         struct ip_addr* ip;
1508         str srv_name;
1509         static char tmp_srv[MAX_DNS_NAME]; /* tmp. buff. for SRV lookups */
1510         size_t i,list_len;
1511         /* init variables */
1512         he=0;
1513
1514         /* check if it's an ip address */
1515         if (((ip=str2ip(name))!=0)
1516                           || ((ip=str2ip6(name))!=0)
1517                          ){
1518                 /* we are lucky, this is an ip address */
1519                 /* set proto if needed - default udp */
1520                 if ((proto)&&(*proto==PROTO_NONE))
1521                         *proto=PROTO_UDP;
1522                 /* set port if needed - default 5060/5061 */
1523                 if ((port)&&(*port==0))
1524                         *port=((proto) && (*proto==PROTO_TLS))?SIPS_PORT:SIP_PORT;
1525                 he=ip_addr2he(name, ip);
1526                 return he;
1527         }
1528
1529         if ((name->len+SRV_MAX_PREFIX_LEN+1)>MAX_DNS_NAME){
1530                 LOG(L_WARN, "WARNING: no_naptr_srv_sip_resolvehost: domain name too long"
1531                                                 " (%d), unable to perform SRV lookup\n", name->len);
1532         } else {
1533                 /* looping on the ordered list until we found a protocol what has srv record */
1534                 list_len = create_srv_pref_list(proto, srv_proto_list);
1535                 for (i=0; i<list_len;i++) {     
1536                         switch (srv_proto_list[i].proto) {
1537                                 case PROTO_UDP:
1538                                 case PROTO_TCP:
1539                                 case PROTO_TLS:
1540                                 case PROTO_SCTP:
1541                                         create_srv_name(srv_proto_list[i].proto, name, tmp_srv);
1542                                         break;
1543                                 default:
1544                                         LOG(L_CRIT, "BUG: no_naptr_srv_sip_resolvehost: unknown proto %d\n",
1545                                                         (int)srv_proto_list[i].proto);
1546                                         return 0;
1547                         }
1548                         /* set default port */
1549                         if ((port)&&(*port==0)){
1550                                 *port=(srv_proto_list[i].proto==PROTO_TLS)?SIPS_PORT:SIP_PORT; /* just in case we don't find another */
1551                         }
1552                         if ((proto)&&(*proto==0)){
1553                                 *proto = PROTO_UDP;
1554                         }
1555                         srv_name.s=tmp_srv;
1556                         srv_name.len=strlen(tmp_srv);
1557                         #ifdef USE_DNS_CACHE
1558                         he=dns_srv_get_he(&srv_name, port, dns_flags);
1559                         #else
1560                         he=srv_sip_resolvehost(&srv_name, 0, port, proto, 1, 0);
1561                         #endif
1562                         if (he!=0) {
1563                                 *proto = srv_proto_list[i].proto;
1564                                 return he;
1565                         }
1566                 }
1567         }
1568         return 0;
1569
1570
1571
1572 /* internal sip naptr resolver function: resolves a host name trying:
1573  * - NAPTR lookup if the address is not an ip and *proto==0 and *port==0.
1574  *   The result of the NAPTR query will be used for a SRV lookup
1575  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
1576  *   query will be used for an A/AAAA lookup.
1577  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
1578  *   and *proto!=0 or port==0 && proto==0)
1579  * when performing SRV lookup (*port==0) it will use proto to look for
1580  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
1581  * returns: hostent struct & *port filled with the port from the SRV record;
1582  *  0 on error
1583  */
1584 struct hostent* naptr_sip_resolvehost(str* name,  unsigned short* port,
1585                                                                                 char* proto)
1586 {
1587         struct hostent* he;
1588         struct ip_addr* ip;
1589         static char tmp[MAX_DNS_NAME]; /* tmp. buff. for SRV lookups and
1590                                           null. term  strings */
1591         struct rdata* l;
1592         struct rdata* naptr_head;
1593         char n_proto;
1594         str srv_name;
1595         naptr_bmp_t tried_bmp; /* tried bitmap */
1596         char origproto;
1597
1598         origproto = *proto;
1599         naptr_head=0;
1600         he=0;
1601         if (name->len >= MAX_DNS_NAME) {
1602                 LOG(L_ERR, "naptr_sip_resolvehost: domain name too long\n");
1603                 goto end;
1604         }
1605         /* try NAPTR if no port or protocol is specified and NAPTR lookup is
1606          * enabled */
1607         if (port && proto && (*proto==0) && (*port==0)){
1608                 *proto=PROTO_UDP; /* just in case we don't find another */
1609                 if ( ((ip=str2ip(name))!=0)
1610                           || ((ip=str2ip6(name))!=0)
1611                 ){
1612                         /* we are lucky, this is an ip address */
1613                         he=ip_addr2he(name,ip);
1614                         *port=SIP_PORT;
1615                         goto end;
1616                 }
1617                 memcpy(tmp, name->s, name->len);
1618                 tmp[name->len] = '\0';
1619                 naptr_head=get_record(tmp, T_NAPTR, RES_AR);
1620                 naptr_iterate_init(&tried_bmp);
1621                 while((l=naptr_sip_iterate(naptr_head, &tried_bmp,
1622                                                                                 &srv_name, &n_proto))!=0){
1623                         if ((he=srv_sip_resolvehost(&srv_name, 1, port, proto, 1, l))!=0){
1624                                 *proto=n_proto;
1625                                 return he;
1626                         }
1627                 }
1628                 /*clean up on exit*/
1629 #ifdef RESOLVE_DBG
1630                 DBG("naptr_sip_resolvehost: no NAPTR record found for %.*s," 
1631                                 " trying SRV lookup...\n", name->len, name->s);
1632 #endif
1633         }
1634         /* fallback to srv lookup */
1635         *proto = origproto;
1636         he=no_naptr_srv_sip_resolvehost(name,port,proto);
1637         /* fallback all the way down to A/AAAA */
1638         if (he==0) {
1639                 he=dns_get_he(name,dns_flags);
1640         }
1641 end:
1642         if (naptr_head)
1643                 free_rdata_list(naptr_head);
1644         return he;
1645 }
1646 #endif /* USE_NAPTR */
1647
1648
1649
1650 /* resolves a host name trying:
1651  * - NAPTR lookup if enabled, the address is not an ip and *proto==0 and 
1652  *   *port==0. The result of the NAPTR query will be used for a SRV lookup
1653  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
1654  *   query will be used for an A/AAAA lookup.
1655  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
1656  *   and *proto!=0 or port==0 && proto==0)
1657  * when performing SRV lookup (*port==0) it will use *proto to look for
1658  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
1659  *
1660  * returns: hostent struct & *port filled with the port from the SRV record;
1661  *  0 on error
1662  */
1663 struct hostent* _sip_resolvehost(str* name, unsigned short* port, char* proto)
1664 {
1665         struct hostent* res = NULL;
1666 #ifdef USE_NAPTR
1667         if (cfg_get(core, core_cfg, dns_try_naptr))
1668                 res = naptr_sip_resolvehost(name, port, proto);
1669         else
1670 #endif
1671         res = srv_sip_resolvehost(name, 0, port, proto, 0, 0);
1672         if( unlikely(!res) ){
1673                 /* failed DNS request */
1674                 counter_inc(dns_cnts_h.failed_dns_req);
1675         }
1676         return res;
1677 }
1678
1679
1680 /* resolve host, port, proto using sip rules (e.g. use SRV if port=0 a.s.o)
1681  *  and write the result in the sockaddr_union to
1682  *  returns -1 on error (resolve failed), 0 on success */
1683 int sip_hostport2su(union sockaddr_union* su, str* name, unsigned short port,
1684                                                 char* proto)
1685 {
1686         struct hostent* he;
1687         
1688         he=sip_resolvehost(name, &port, proto);
1689         if (he==0){
1690                 ser_error=E_BAD_ADDRESS;
1691                 LOG(L_ERR, "ERROR: sip_hostport2su: could not resolve hostname:"
1692                                         " \"%.*s\"\n", name->len, name->s);
1693                 goto error;
1694         }
1695         /* port filled by sip_resolvehost if empty*/
1696         if (hostent2su(su, he, 0, port)<0){
1697                 ser_error=E_BAD_ADDRESS;
1698                 goto error;
1699         }
1700         return 0;
1701 error:
1702         return -1;
1703 }