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