Modifying the return value of cfg_set* functions, in order to make
[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  */ 
45
46
47 #include <sys/types.h>
48 #include <netinet/in.h>
49 #include <arpa/nameser.h>
50 #include <resolv.h>
51 #include <string.h>
52
53 #include "resolve.h"
54 #include "compiler_opt.h"
55 #include "dprint.h"
56 #include "mem/mem.h"
57 #include "ip_addr.h"
58 #include "error.h"
59 #include "globals.h" /* tcp_disable, tls_disable a.s.o */
60
61 #ifdef USE_DNS_CACHE
62 #include "dns_cache.h"
63 #endif
64
65
66
67 /* mallocs for local stuff */
68 #define local_malloc pkg_malloc
69 #define local_free   pkg_free
70
71 #ifdef USE_IPV6
72 int dns_try_ipv6=1; /* default on */
73 #else
74 int dns_try_ipv6=0; /* off, if no ipv6 support */
75 #endif
76 int dns_try_naptr=0;  /* off by default */
77
78 int dns_udp_pref=3;  /* udp transport preference (for naptr) */
79 int dns_tcp_pref=2;  /* tcp transport preference (for naptr) */
80 int dns_tls_pref=1;  /* tls transport preference (for naptr) */
81
82 #ifdef USE_NAPTR
83 #define PROTO_LAST  PROTO_SCTP
84 static int naptr_proto_pref[PROTO_LAST];
85 #endif
86
87 /* declared in globals.h */
88 int dns_retr_time=-1;
89 int dns_retr_no=-1;
90 int dns_servers_no=-1;
91 int dns_search_list=-1;
92 int dns_search_fmatch=-1;
93
94 #ifdef USE_NAPTR
95 void init_naptr_proto_prefs()
96 {
97         if ((PROTO_UDP >= PROTO_LAST) || (PROTO_TCP >= PROTO_LAST) ||
98                 (PROTO_TLS >= PROTO_LAST)){
99                 BUG("init_naptr_proto_prefs: array too small \n");
100                 return;
101         }
102         naptr_proto_pref[PROTO_UDP]=dns_udp_pref;
103         naptr_proto_pref[PROTO_TCP]=dns_tcp_pref;
104         naptr_proto_pref[PROTO_TLS]=dns_tls_pref;
105 }
106
107 #endif /* USE_NAPTR */
108
109
110
111 /* init. the resolver
112  * params: retr_time  - time before retransmitting (must be >0)
113  *         retr_no    - retransmissions number
114  *         servers_no - how many dns servers will be used
115  *                      (from the one listed in /etc/resolv.conf)
116  *         search     - if 0 the search list in /etc/resolv.conf will
117  *                      be ignored (HINT: even if you don't have a
118  *                      search list in resolv.conf, it's still better
119  *                      to set search to 0, because an empty seachlist
120  *                      means in fact search "" => it takes more time)
121  * If any of the parameters <0, the default (system specific) value
122  * will be used. See also resolv.conf(5).
123  * returns: 0 on success, -1 on error
124  */
125 int resolv_init()
126 {
127         res_init();
128 #ifdef HAVE_RESOLV_RES
129         if (dns_retr_time>0)
130                 _res.retrans=dns_retr_time;
131         if (dns_retr_no>0)
132                 _res.retry=dns_retr_no;
133         if (dns_servers_no>=0)
134                 _res.nscount=dns_servers_no;
135         if (dns_search_list==0)
136                 _res.options&=~(RES_DEFNAMES|RES_DNSRCH);
137 #else
138 #warning "no resolv timeout support"
139         LOG(L_WARN, "WARNING: resolv_init: no resolv options support - resolv"
140                         " options will be ignored\n");
141 #endif
142 #ifdef USE_NAPTR
143         init_naptr_proto_prefs();
144 #endif
145         return 0;
146 }
147
148
149
150  /*  skips over a domain name in a dns message
151  *  (it can be  a sequence of labels ending in \0, a pointer or
152  *   a sequence of labels ending in a pointer -- see rfc1035
153  *   returns pointer after the domain name or null on error*/
154 unsigned char* dns_skipname(unsigned char* p, unsigned char* end)
155 {
156         while(p<end){
157                 /* check if \0 (root label length) */
158                 if (*p==0){
159                         p+=1;
160                         break;
161                 }
162                 /* check if we found a pointer */
163                 if (((*p)&0xc0)==0xc0){
164                         /* if pointer skip over it (2 bytes) & we found the end */
165                         p+=2;
166                         break;
167                 }
168                 /* normal label */
169                 p+=*p+1;
170         }
171         return (p>end)?0:p;
172 }
173
174
175
176 /* parses the srv record into a srv_rdata structure
177  *   msg   - pointer to the dns message
178  *   end   - pointer to the end of the message
179  *   rdata - pointer  to the rdata part of the srv answer
180  * returns 0 on error, or a dyn. alloc'ed srv_rdata structure */
181 /* SRV rdata format:
182  *            111111
183  *  0123456789012345
184  * +----------------+
185  * |     priority   |
186  * |----------------|
187  * |     weight     |
188  * |----------------|
189  * |   port number  |
190  * |----------------|
191  * |                |
192  * ~      name      ~
193  * |                |
194  * +----------------+
195  */
196 struct srv_rdata* dns_srv_parser( unsigned char* msg, unsigned char* end,
197                                                                   unsigned char* rdata)
198 {
199         struct srv_rdata* srv;
200         unsigned short priority;
201         unsigned short weight;
202         unsigned short port;
203         int len;
204         char name[MAX_DNS_NAME];
205         
206         srv=0;
207         if ((rdata+6+1)>end) goto error;
208         
209         memcpy((void*)&priority, rdata, 2);
210         memcpy((void*)&weight,   rdata+2, 2);
211         memcpy((void*)&port,     rdata+4, 2);
212         rdata+=6;
213         if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)<0)
214                 goto error;
215         len=strlen(name);
216         if (len>255)
217                 goto error;
218         /* alloc enought space for the struct + null terminated name */
219         srv=local_malloc(sizeof(struct srv_rdata)-1+len+1);
220         if (srv==0){
221                 LOG(L_ERR, "ERROR: dns_srv_parser: out of memory\n");
222                 goto error;
223         }
224         srv->priority=ntohs(priority);
225         srv->weight=ntohs(weight);
226         srv->port=ntohs(port);
227         srv->name_len=len;
228         memcpy(srv->name, name, srv->name_len);
229         srv->name[srv->name_len]=0;
230         
231         return srv;
232 error:
233         if (srv) local_free(srv);
234         return 0;
235 }
236
237
238 /* parses the naptr record into a naptr_rdata structure
239  *   msg   - pointer to the dns message
240  *   end   - pointer to the end of the message
241  *   rdata - pointer  to the rdata part of the naptr answer
242  * returns 0 on error, or a dyn. alloc'ed naptr_rdata structure */
243 /* NAPTR rdata format:
244  *            111111
245  *  0123456789012345
246  * +----------------+
247  * |      order     |
248  * |----------------|
249  * |   preference   |
250  * |----------------|
251  * ~     flags      ~
252  * |   (string)     |
253  * |----------------|
254  * ~    services    ~
255  * |   (string)     |
256  * |----------------|
257  * ~    regexp      ~
258  * |   (string)     |
259  * |----------------|
260  * ~  replacement   ~
261    |    (name)      |
262  * +----------------+
263  */
264 struct naptr_rdata* dns_naptr_parser( unsigned char* msg, unsigned char* end,
265                                                                   unsigned char* rdata)
266 {
267         struct naptr_rdata* naptr;
268         unsigned char* flags;
269         unsigned char* services;
270         unsigned char* regexp;
271         unsigned short order;
272         unsigned short pref;
273         unsigned char flags_len;
274         unsigned char services_len;
275         unsigned char regexp_len;
276         int len;
277         char repl[MAX_DNS_NAME];
278         
279         naptr = 0;
280         if ((rdata + 7 + 1)>end) goto error;
281         
282         memcpy((void*)&order, rdata, 2);
283         memcpy((void*)&pref, rdata + 2, 2);
284         flags_len = rdata[4];
285         if ((rdata + 7 + 1 +  flags_len) > end)
286                 goto error;
287         flags=rdata+5;
288         services_len = rdata[5 + flags_len];
289         if ((rdata + 7 + 1 + flags_len + services_len) > end)
290                 goto error;
291         services=rdata + 6 + flags_len;
292         regexp_len = rdata[6 + flags_len + services_len];
293         if ((rdata + 7 +1 + flags_len + services_len + regexp_len) > end)
294                 goto error;
295         regexp=rdata + 7 + flags_len + services_len;
296         rdata = rdata + 7 + flags_len + services_len + regexp_len;
297         if (dn_expand(msg, end, rdata, repl, MAX_DNS_NAME-1) == -1)
298                 goto error;
299         len=strlen(repl);
300         if (len>255)
301                 goto error;
302         naptr=local_malloc(sizeof(struct naptr_rdata)+flags_len+services_len+
303                                                 regexp_len+len+1-1);
304         if (naptr == 0){
305                 LOG(L_ERR, "ERROR: dns_naptr_parser: out of memory\n");
306                 goto error;
307         }
308         naptr->order=ntohs(order);
309         naptr->pref=ntohs(pref);
310         
311         naptr->flags=&naptr->str_table[0];
312         naptr->flags_len=flags_len;
313         memcpy(naptr->flags, flags, naptr->flags_len);
314         naptr->services=&naptr->str_table[flags_len];
315         naptr->services_len=services_len;
316         memcpy(naptr->services, services, naptr->services_len);
317         naptr->regexp=&naptr->str_table[flags_len+services_len];
318         naptr->regexp_len=regexp_len;
319         memcpy(naptr->regexp, regexp, naptr->regexp_len);
320         naptr->repl=&naptr->str_table[flags_len+services_len+regexp_len];
321         naptr->repl_len=len;
322         memcpy(naptr->repl, repl, len);
323         naptr->repl[len]=0; /* null term. */
324         
325         return naptr;
326 error:
327         if (naptr) local_free(naptr);
328         return 0;
329 }
330
331
332
333 /* parses a CNAME record into a cname_rdata structure */
334 struct cname_rdata* dns_cname_parser( unsigned char* msg, unsigned char* end,
335                                                                           unsigned char* rdata)
336 {
337         struct cname_rdata* cname;
338         int len;
339         char name[MAX_DNS_NAME];
340         
341         cname=0;
342         if (dn_expand(msg, end, rdata, name, MAX_DNS_NAME-1)==-1)
343                 goto error;
344         len=strlen(name);
345         if (len>255)
346                 goto error;
347         /* alloc sizeof struct + space for the null terminated name */
348         cname=local_malloc(sizeof(struct cname_rdata)-1+len+1);
349         if(cname==0){
350                 LOG(L_ERR, "ERROR: dns_cname_parser: out of memory\n");
351                 goto error;
352         }
353         cname->name_len=len;
354         memcpy(cname->name, name, cname->name_len);
355         cname->name[cname->name_len]=0;
356         return cname;
357 error:
358         if (cname) local_free(cname);
359         return 0;
360 }
361
362
363
364 /* parses an A record rdata into an a_rdata structure
365  * returns 0 on error or a dyn. alloc'ed a_rdata struct
366  */
367 struct a_rdata* dns_a_parser(unsigned char* rdata, unsigned char* end)
368 {
369         struct a_rdata* a;
370         
371         if (rdata+4>end) goto error;
372         a=(struct a_rdata*)local_malloc(sizeof(struct a_rdata));
373         if (a==0){
374                 LOG(L_ERR, "ERROR: dns_a_parser: out of memory\n");
375                 goto error;
376         }
377         memcpy(a->ip, rdata, 4);
378         return a;
379 error:
380         return 0;
381 }
382
383
384
385 /* parses an AAAA (ipv6) record rdata into an aaaa_rdata structure
386  * returns 0 on error or a dyn. alloc'ed aaaa_rdata struct */
387 struct aaaa_rdata* dns_aaaa_parser(unsigned char* rdata, unsigned char* end)
388 {
389         struct aaaa_rdata* aaaa;
390         
391         if (rdata+16>end) goto error;
392         aaaa=(struct aaaa_rdata*)local_malloc(sizeof(struct aaaa_rdata));
393         if (aaaa==0){
394                 LOG(L_ERR, "ERROR: dns_aaaa_parser: out of memory\n");
395                 goto error;
396         }
397         memcpy(aaaa->ip6, rdata, 16);
398         return aaaa;
399 error:
400         return 0;
401 }
402
403
404
405 /* frees completely a struct rdata list */
406 void free_rdata_list(struct rdata* head)
407 {
408         struct rdata* l;
409         struct rdata* next_l;
410         l=head;
411         while (l != 0) {
412                 next_l = l->next;
413                 /* free the parsed rdata*/
414                 if (l->rdata) local_free(l->rdata);
415                 local_free(l);
416                 l = next_l;
417         }
418 }
419
420 #ifdef HAVE_RESOLV_RES
421 /* checks whether supplied name exists in the resolver search list
422  * returns 1 if found
423  *         0 if not found
424  */
425 int match_search_list(const res_state res, char* name) {
426         int i;
427         for (i=0; (i<MAXDNSRCH) && (res->dnsrch[i]); i++) {
428                 if (strcasecmp(name, res->dnsrch[i])==0) 
429                         return 1;
430         }
431         return 0;
432 }
433 #endif
434
435 /* gets the DNS records for name:type
436  * returns a dyn. alloc'ed struct rdata linked list with the parsed responses
437  * or 0 on error
438  * see rfc1035 for the query/response format */
439 struct rdata* get_record(char* name, int type, int flags)
440 {
441         int size;
442         int skip;
443         int qno, answers_no;
444         int r;
445         static union dns_query buff;
446         unsigned char* p;
447         unsigned char* end;
448         static char rec_name[MAX_DNS_NAME]; /* placeholder for the record name */
449         int rec_name_len;
450         unsigned short rtype, class, rdlength;
451         unsigned int ttl;
452         struct rdata* head;
453         struct rdata** crt;
454         struct rdata** last;
455         struct rdata* rd;
456         struct srv_rdata* srv_rd;
457         struct srv_rdata* crt_srv;
458         int search_list_used;
459         int name_len;
460         struct rdata* fullname_rd;
461         
462         if (dns_search_list==0) {
463                 search_list_used=0;
464                 name_len=0;
465         } else {
466                 search_list_used=1;
467                 name_len=strlen(name);
468         }
469         fullname_rd=0;
470
471         size=res_search(name, C_IN, type, buff.buff, sizeof(buff));
472         if (size<0) {
473                 DBG("get_record: lookup(%s, %d) failed\n", name, type);
474                 goto not_found;
475         }
476         else if (size > sizeof(buff)) size=sizeof(buff);
477         head=rd=0;
478         last=crt=&head;
479         
480         p=buff.buff+DNS_HDR_SIZE;
481         end=buff.buff+size;
482         if (p>=end) goto error_boundary;
483         qno=ntohs((unsigned short)buff.hdr.qdcount);
484
485         for (r=0; r<qno; r++){
486                 /* skip the name of the question */
487                 if ((p=dns_skipname(p, end))==0) {
488                         LOG(L_ERR, "ERROR: get_record: skipname==0\n");
489                         goto error;
490                 }
491                 p+=2+2; /* skip QCODE & QCLASS */
492         #if 0
493                 for (;(p<end && (*p)); p++);
494                 p+=1+2+2; /* skip the ending  '\0, QCODE and QCLASS */
495         #endif
496                 if (p>end) {
497                         LOG(L_ERR, "ERROR: get_record: p>=end\n");
498                         goto error;
499                 }
500         };
501         answers_no=ntohs((unsigned short)buff.hdr.ancount);
502 again:
503         for (r=0; (r<answers_no) && (p<end); r++){
504 #if 0
505                 /*  ignore it the default domain name */
506                 if ((p=dns_skipname(p, end))==0) {
507                         LOG(L_ERR, "ERROR: get_record: skip_name=0 (#2)\n");
508                         goto error;
509                 }
510 #else
511                 if ((skip=dn_expand(buff.buff, end, p, rec_name, MAX_DNS_NAME-1))==-1){
512                         LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name) failed\n");
513                         goto error;
514                 }
515 #endif
516                 p+=skip;
517                 rec_name_len=strlen(rec_name);
518                 if (rec_name_len>255){
519                         LOG(L_ERR, "ERROR: get_record: dn_expand(rec_name): name too"
520                                         " long  (%d)\n", rec_name_len);
521                         goto error;
522                 }
523                 /* check if enough space is left for type, class, ttl & size */
524                 if ((p+2+2+4+2)>end) goto error_boundary;
525                 /* get type */
526                 memcpy((void*) &rtype, (void*)p, 2);
527                 rtype=ntohs(rtype);
528                 p+=2;
529                 /* get  class */
530                 memcpy((void*) &class, (void*)p, 2);
531                 class=ntohs(class);
532                 p+=2;
533                 /* get ttl*/
534                 memcpy((void*) &ttl, (void*)p, 4);
535                 ttl=ntohl(ttl);
536                 p+=4;
537                 /* get size */
538                 memcpy((void*)&rdlength, (void*)p, 2);
539                 rdlength=ntohs(rdlength);
540                 p+=2;
541                 if ((flags & RES_ONLY_TYPE) && (rtype!=type)){
542                         /* skip */
543                         p+=rdlength;
544                         continue;
545                 }
546                 /* expand the "type" record  (rdata)*/
547                 
548                 rd=(struct rdata*) local_malloc(sizeof(struct rdata)+rec_name_len+1-1);
549                 if (rd==0){
550                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
551                         goto error;
552                 }
553                 rd->type=rtype;
554                 rd->class=class;
555                 rd->ttl=ttl;
556                 rd->next=0;
557                 memcpy(rd->name, rec_name, rec_name_len);
558                 rd->name[rec_name_len]=0;
559                 rd->name_len=rec_name_len;
560                 /* check if full name matches */
561                 if ((search_list_used==1)&&(fullname_rd==0)&&
562                                 (rec_name_len>=name_len)&&
563                                 (strncasecmp(rec_name, name, name_len)==0)) {
564                         /* now we have record which's name is the same (up-to the name_len
565                          * with the searched one
566                          * if the length is the same - we found full match, no fake cname
567                          *   needed, just clear the flag
568                          * if the length of the name differs - it has matched using search list
569                          *   remember the rd, so we can create fake CNAME record when all answers
570                          *   are used and no better match found
571                          */
572                         if (rec_name_len==name_len)
573                                 search_list_used=0;
574                         /* this is safe.... here was rec_name_len > name_len */
575                         else if (rec_name[name_len]=='.') {
576 #ifdef HAVE_RESOLV_RES
577                                 if ((dns_search_fmatch==0) ||
578                                                 (match_search_list(&_res, rec_name+name_len+1)!=0))
579 #endif
580                                         fullname_rd=rd;
581                         }
582                 }
583                 switch(rtype){
584                         case T_SRV:
585                                 srv_rd= dns_srv_parser(buff.buff, end, p);
586                                 rd->rdata=(void*)srv_rd;
587                                 if (srv_rd==0) goto error_parse;
588                                 
589                                 /* insert sorted into the list */
590                                 for (crt=&head; *crt; crt= &((*crt)->next)){
591                                         if ((*crt)->type!=T_SRV)
592                                                 continue;
593                                         crt_srv=(struct srv_rdata*)(*crt)->rdata;
594                                         if ((srv_rd->priority <  crt_srv->priority) ||
595                                            ( (srv_rd->priority == crt_srv->priority) && 
596                                                          (srv_rd->weight > crt_srv->weight) ) ){
597                                                 /* insert here */
598                                                 goto skip;
599                                         }
600                                 }
601                                 last=&(rd->next); /*end of for => this will be the last elem*/
602                         skip:
603                                 /* insert here */
604                                 rd->next=*crt;
605                                 *crt=rd;
606                                 
607                                 break;
608                         case T_A:
609                                 rd->rdata=(void*) dns_a_parser(p,end);
610                                 if (rd->rdata==0) goto error_parse;
611                                 *last=rd; /* last points to the last "next" or the list head*/
612                                 last=&(rd->next);
613                                 break;
614                         case T_AAAA:
615                                 rd->rdata=(void*) dns_aaaa_parser(p,end);
616                                 if (rd->rdata==0) goto error_parse;
617                                 *last=rd;
618                                 last=&(rd->next);
619                                 break;
620                         case T_CNAME:
621                                 rd->rdata=(void*) dns_cname_parser(buff.buff, end, p);
622                                 if(rd->rdata==0) goto error_parse;
623                                 *last=rd;
624                                 last=&(rd->next);
625                                 break;
626                         case T_NAPTR:
627                                 rd->rdata=(void*) dns_naptr_parser(buff.buff, end, p);
628                                 if(rd->rdata==0) goto error_parse;
629                                 *last=rd;
630                                 last=&(rd->next);
631                                 break;
632                         default:
633                                 LOG(L_ERR, "WARNING: get_record: unknown type %d\n", rtype);
634                                 rd->rdata=0;
635                                 *last=rd;
636                                 last=&(rd->next);
637                 }
638                 
639                 p+=rdlength;
640                 
641         }
642         if (flags & RES_AR){
643                 flags&=~RES_AR;
644                 answers_no=ntohs((unsigned short)buff.hdr.nscount);
645 #ifdef RESOLVE_DBG
646                 DBG("get_record: skipping %d NS (p=%p, end=%p)\n", answers_no, p, end);
647 #endif
648                 for (r=0; (r<answers_no) && (p<end); r++){
649                         /* skip over the ns records */
650                         if ((p=dns_skipname(p, end))==0) {
651                                 LOG(L_ERR, "ERROR: get_record: skip_name=0 (#3)\n");
652                                 goto error;
653                         }
654                         /* check if enough space is left for type, class, ttl & size */
655                         if ((p+2+2+4+2)>end) goto error_boundary;
656                         memcpy((void*)&rdlength, (void*)p+2+2+4, 2);
657                         p+=2+2+4+2+ntohs(rdlength);
658                 }
659                 answers_no=ntohs((unsigned short)buff.hdr.arcount);
660 #ifdef RESOLVE_DBG
661                 DBG("get_record: parsing %d ARs (p=%p, end=%p)\n", answers_no, p, end);
662 #endif
663                 goto again; /* add also the additional records */
664         }
665
666         /* if the name was expanded using DNS search list
667          * create fake CNAME record to convert the short name
668          * (queried) to long name (answered)
669          */
670         if ((search_list_used==1)&&(fullname_rd!=0)) {
671                 rd=(struct rdata*) local_malloc(sizeof(struct rdata)+name_len+1-1);
672                 if (rd==0){
673                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
674                         goto error;
675                 }
676                 rd->type=T_CNAME;
677                 rd->class=fullname_rd->class;
678                 rd->ttl=fullname_rd->ttl;
679                 rd->next=head;
680                 memcpy(rd->name, name, name_len);
681                 rd->name[name_len]=0;
682                 rd->name_len=name_len;
683                 /* alloc sizeof struct + space for the null terminated name */
684                 rd->rdata=(void*)local_malloc(sizeof(struct cname_rdata)-1+head->name_len+1);
685                 if(rd->rdata==0){
686                         LOG(L_ERR, "ERROR: get_record: out of memory\n");
687                         goto error_rd;
688                 }
689                 ((struct cname_rdata*)(rd->rdata))->name_len=fullname_rd->name_len;
690                 memcpy(((struct cname_rdata*)(rd->rdata))->name, fullname_rd->name, fullname_rd->name_len);
691                 ((struct cname_rdata*)(rd->rdata))->name[head->name_len]=0;
692                 head=rd;
693         }
694
695         return head;
696 error_boundary:
697                 LOG(L_ERR, "ERROR: get_record: end of query buff reached\n");
698                 if (head) free_rdata_list(head);
699                 return 0;
700 error_parse:
701                 LOG(L_ERR, "ERROR: get_record: rdata parse error (%s, %d), %p-%p"
702                                                 " rtype=%d, class=%d, ttl=%d, rdlength=%d \n",
703                                 name, type,
704                                 p, end, rtype, class, ttl, rdlength);
705 error_rd:
706                 if (rd) local_free(rd); /* rd->rdata=0 & rd is not linked yet into
707                                                                    the list */
708 error:
709                 LOG(L_ERR, "ERROR: get_record \n");
710                 if (head) free_rdata_list(head);
711 not_found:
712         return 0;
713 }
714
715 #ifdef USE_NAPTR
716
717 /* service matching constants, lowercase */
718 #define SIP_SCH         0x2b706973
719 #define SIPS_SCH        0x73706973
720 #define SIP_D2U         0x00753264
721 #define SIP_D2T         0x00743264
722 #define SIP_D2S         0x00733264
723 #define SIPS_D2T        0x7432642b
724
725
726 /* get protocol from a naptr rdata and check for validity
727  * returns > 0 (PROTO_UDP, PROTO_TCP, PROTO_SCTP or PROTO_TLS)
728  *         <=0  on error 
729  */
730 char naptr_get_sip_proto(struct naptr_rdata* n)
731 {
732         unsigned int s;
733         char proto;
734
735         proto=-1;
736         
737         if ((n->flags_len!=1) || (*n->flags!='s'))
738                 return -1;
739         if (n->regexp_len!=0)
740                 return -1;
741         /* SIP+D2U, SIP+D2T, SIP+D2S, SIPS+D2T */
742         if (n->services_len==7){ /* SIP+D2X */
743                 s=n->services[0]+(n->services[1]<<8)+(n->services[2]<<16)+
744                                 (n->services[3]<<24);
745                 s|=0x20202020;
746                 if (s==SIP_SCH){
747                         s=n->services[4]+(n->services[5]<<8)+(n->services[6]<<16);
748                         s|=0x00202020;
749                         switch(s){
750                                 case SIP_D2U:
751                                         proto=PROTO_UDP;
752                                         break;
753                                 case SIP_D2T:
754                                         proto=PROTO_TCP;
755                                         break;
756                                 case SIP_D2S:
757                                         proto=PROTO_SCTP;
758                                         break;
759                                 default:
760                                         return -1;
761                         }
762                 }else{
763                         return -1;
764                 }
765         }else if  (n->services_len==8){ /*SIPS+D2T */
766                 s=n->services[0]+(n->services[1]<<8)+(n->services[2]<<16)+
767                                 (n->services[3]<<24);
768                 s|=0x20202020;
769                 if (s==SIPS_SCH){
770                         s=n->services[4]+(n->services[5]<<8)+(n->services[6]<<16)+
771                                         (n->services[7]<<24);
772                         s|=0x20202020;
773                         if (s==SIPS_D2T){
774                                 proto=PROTO_TLS;
775                         }
776                 }else{
777                         return -1;
778                 }
779         }else{
780                 return -1;
781         }
782         return proto;
783 }
784
785
786
787 inline static int proto_pref_score(char proto)
788 {
789         if ((proto>=PROTO_UDP) && (proto<= PROTO_TLS))
790                 return naptr_proto_pref[(int)proto];
791         return 0;
792 }
793
794
795
796 /* returns true if we support the protocol */
797 int naptr_proto_supported(char proto)
798 {
799         if (proto_pref_score(proto)<0)
800                 return 0;
801         switch(proto){
802                 case PROTO_UDP:
803                         return 1;
804 #ifdef USE_TCP
805                 case PROTO_TCP:
806                         return !tcp_disable;
807 #ifdef USE_TLS
808                 case PROTO_TLS:
809                         return !tls_disable;
810 #endif /* USE_TLS */
811 #endif /* USE_TCP */
812                 case PROTO_SCTP:
813                         return 0; /* not supported */
814         }
815         return 0;
816 }
817
818
819
820
821 /* returns true if new_proto is preferred over old_proto */
822 int naptr_proto_preferred(char new_proto, char old_proto)
823 {
824         return proto_pref_score(new_proto)>proto_pref_score(old_proto);
825 }
826
827
828 /* choose between 2 naptr records, should take into account local
829  * preferences too
830  * returns 1 if the new record was selected, 0 otherwise */
831 int naptr_choose (struct naptr_rdata** crt, char* crt_proto,
832                                                                         struct naptr_rdata* n , char n_proto)
833 {
834 #ifdef NAPTR_DBG
835         DBG("naptr_choose(o: %d w: %d p:%d , o: %d w:%d p:%d)\n",
836                         *crt?(int)(*crt)->order:-1, *crt?(int)(*crt)->pref:-1,
837                         (int)*crt_proto,
838                         (int)n->order, (int)n->pref, (int)n_proto);
839 #endif
840         if ((*crt==0) || ((*crt_proto!=n_proto) && 
841                                                 ( naptr_proto_preferred(n_proto, *crt_proto))) )
842                         goto change;
843         if ((n->order<(*crt)->order) || ((n->order== (*crt)->order) &&
844                                                                         (n->pref < (*crt)->pref))){
845                         goto change;
846         }
847 #ifdef NAPTR_DBG
848         DBG("naptr_choose: no change\n");
849 #endif
850         return 0;
851 change:
852 #ifdef NAPTR_DBG
853         DBG("naptr_choose: changed\n");
854 #endif
855         *crt_proto=n_proto;
856         *crt=n;
857         return 1;
858 }
859 #endif /* USE_NAPTR */
860
861
862
863 /* internal sip srv resolver: resolves a host name trying:
864  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
865  *   query will be used for an A/AAAA lookup.
866  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
867  *   and *proto!=0 or port==0 && proto==0)
868  * when performing SRV lookup (*port==0) it will use *proto to look for
869  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
870  * If zt is set, name will be assumed to be 0 terminated and some copy 
871  * operations will be avoided.
872  * If is_srv is set it will assume name has the srv prefixes for sip already
873  *  appended and it's already 0-term'ed; if not it will append them internally.
874  * If ars !=0, it will first try to look through them and only if the SRV
875  *   record is not found it will try doing a DNS query  (ars will not be
876  *   freed, the caller should take care of them)
877  * returns: hostent struct & *port filled with the port from the SRV record;
878  *  0 on error
879  */
880 struct hostent* srv_sip_resolvehost(str* name, int zt, unsigned short* port,
881                                                                         char* proto, int is_srv, struct rdata* ars)
882 {
883         struct hostent* he;
884         struct ip_addr* ip;
885         static char tmp[MAX_DNS_NAME]; /* tmp. buff. for SRV lookups and
886                                           null. term  strings */
887         struct rdata* l;
888         struct srv_rdata* srv;
889         struct rdata* srv_head;
890         char* srv_target;
891         char srv_proto;
892
893         /* init */
894         srv_head=0;
895         srv_target=0;
896         if (name->len >= MAX_DNS_NAME) {
897                 LOG(L_ERR, "sip_resolvehost: domain name too long\n");
898                 he=0;
899                 goto end;
900         }
901 #ifdef RESOLVE_DBG
902         DBG("srv_sip_resolvehost: %.*s:%d proto=%d\n", name->len, name->s,
903                         port?(int)*port:-1, proto?(int)*proto:-1);
904 #endif
905         if (is_srv){
906                 /* skip directly to srv resolving */
907                 srv_proto=(proto)?*proto:0;
908                 *port=(srv_proto==PROTO_TLS)?SIPS_PORT:SIP_PORT;
909                 if (zt){
910                         srv_target=name->s; /* name.s must be 0 terminated in
911                                                                   this case */
912                 }else{
913                         memcpy(tmp, name->s, name->len);
914                         tmp[name->len] = '\0';
915                         srv_target=tmp;
916                 }
917                 goto do_srv; /* skip to the actual srv query */
918         }
919         if (proto){ /* makes sure we have a protocol set*/
920                 if (*proto==0)
921                         *proto=srv_proto=PROTO_UDP; /* default */
922                 else
923                         srv_proto=*proto;
924         }else{
925                 srv_proto=PROTO_UDP;
926         }
927         /* try SRV if no port specified (draft-ietf-sip-srv-06) */
928         if ((port)&&(*port==0)){
929                 *port=(srv_proto==PROTO_TLS)?SIPS_PORT:SIP_PORT; /* just in case we
930                                                                                                                   don't find another */
931                 /* check if it's an ip address */
932                 if (((ip=str2ip(name))!=0)
933 #ifdef  USE_IPV6
934                           || ((ip=str2ip6(name))!=0) 
935 #endif
936                          ){
937                         /* we are lucky, this is an ip address */
938                         he=ip_addr2he(name, ip);
939                         goto end;
940                 }
941                 if ((name->len+SRV_MAX_PREFIX_LEN+1)>MAX_DNS_NAME){
942                         LOG(L_WARN, "WARNING: sip_resolvehost: domain name too long (%d),"
943                                                 " unable to perform SRV lookup\n", name->len);
944                 }else{
945                         
946                         switch(srv_proto){
947                                 case PROTO_NONE: /* no proto specified, use udp */
948                                         if (proto)
949                                                 *proto=PROTO_UDP;
950                                         /* no break */
951                                 case PROTO_UDP:
952                                         memcpy(tmp, SRV_UDP_PREFIX, SRV_UDP_PREFIX_LEN);
953                                         memcpy(tmp+SRV_UDP_PREFIX_LEN, name->s, name->len);
954                                         tmp[SRV_UDP_PREFIX_LEN + name->len] = '\0';
955                                         break;
956                                 case PROTO_TCP:
957                                         memcpy(tmp, SRV_TCP_PREFIX, SRV_TCP_PREFIX_LEN);
958                                         memcpy(tmp+SRV_TCP_PREFIX_LEN, name->s, name->len);
959                                         tmp[SRV_TCP_PREFIX_LEN + name->len] = '\0';
960                                         break;
961                                 case PROTO_TLS:
962                                         memcpy(tmp, SRV_TLS_PREFIX, SRV_TLS_PREFIX_LEN);
963                                         memcpy(tmp+SRV_TLS_PREFIX_LEN, name->s, name->len);
964                                         tmp[SRV_TLS_PREFIX_LEN + name->len] = '\0';
965                                         break;
966                                 default:
967                                         LOG(L_CRIT, "BUG: sip_resolvehost: unknown proto %d\n",
968                                                         srv_proto);
969                                         he=0;
970                                         goto end;
971                         }
972                         srv_target=tmp;
973 do_srv:
974                         /* try to find the SRV records inside previous ARs  first*/
975                         for (l=ars; l; l=l->next){
976                                 if (l->type!=T_SRV) continue; 
977                                 srv=(struct srv_rdata*) l->rdata;
978                                 if (srv==0){
979                                         LOG(L_CRIT, "sip_resolvehost: BUG: null rdata\n");
980                                         /* cleanup on exit only */
981                                         break;
982                                 }
983                                 he=resolvehost(srv->name);
984                                 if (he!=0){
985                                         /* we found it*/
986 #ifdef RESOLVE_DBG
987                                         DBG("sip_resolvehost: found SRV(%s) = %s:%d in AR\n",
988                                                         srv_target, srv->name, srv->port);
989 #endif
990                                         *port=srv->port;
991                                         /* cleanup on exit */
992                                         goto end;
993                                 }
994                         }
995                         srv_head=get_record(srv_target, T_SRV, RES_ONLY_TYPE);
996                         for(l=srv_head; l; l=l->next){
997                                 if (l->type!=T_SRV) continue; /*should never happen*/
998                                 srv=(struct srv_rdata*) l->rdata;
999                                 if (srv==0){
1000                                         LOG(L_CRIT, "sip_resolvehost: BUG: null rdata\n");
1001                                         /* cleanup on exit only */
1002                                         break;
1003                                 }
1004                                 he=resolvehost(srv->name);
1005                                 if (he!=0){
1006                                         /* we found it*/
1007 #ifdef RESOLVE_DBG
1008                                         DBG("sip_resolvehost: SRV(%s) = %s:%d\n",
1009                                                         srv_target, srv->name, srv->port);
1010 #endif
1011                                         *port=srv->port;
1012                                         /* cleanup on exit */
1013                                         goto end;
1014                                 }
1015                         }
1016                         if (is_srv){
1017                                 /* if the name was already into SRV format it doesn't make
1018                                  * any sense to fall back to A/AAAA */
1019                                 he=0;
1020                                 goto end;
1021                         }
1022                         /* cleanup on exit */
1023 #ifdef RESOLVE_DBG
1024                         DBG("sip_resolvehost: no SRV record found for %.*s," 
1025                                         " trying 'normal' lookup...\n", name->len, name->s);
1026 #endif
1027                 }
1028         }
1029 /*skip_srv:*/
1030         if (likely(!zt)){
1031                 memcpy(tmp, name->s, name->len);
1032                 tmp[name->len] = '\0';
1033                 he=resolvehost(tmp);
1034         }else{
1035                 he=resolvehost(name->s);
1036         }
1037 end:
1038 #ifdef RESOLVE_DBG
1039         DBG("srv_sip_resolvehost: returning %p (%.*s:%d proto=%d)\n",
1040                         he, name->len, name->s,
1041                         port?(int)*port:-1, proto?(int)*proto:-1);
1042 #endif
1043         if (srv_head)
1044                 free_rdata_list(srv_head);
1045         return he;
1046 }
1047
1048
1049
1050 #ifdef USE_NAPTR 
1051
1052
1053 /* iterates over a naptr rr list, returning each time a "good" naptr record
1054  * is found.( srv type, no regex and a supported protocol)
1055  * params:
1056  *         naptr_head - naptr rr list head
1057  *         tried      - bitmap used to keep track of the already tried records
1058  *                      (no more then sizeof(tried)*8 valid records are 
1059  *                      ever walked
1060  *         srv_name   - if succesfull, it will be set to the selected record
1061  *                      srv name (naptr repl.)
1062  *         proto      - if succesfull it will be set to the selected record
1063  *                      protocol
1064  * returns  0 if no more records found or a pointer to the selected record
1065  *  and sets  protocol and srv_name
1066  * WARNING: when calling first time make sure you run first 
1067  *           naptr_iterate_init(&tried)
1068  */
1069 struct rdata* naptr_sip_iterate(struct rdata* naptr_head, 
1070                                                                                 naptr_bmp_t* tried,
1071                                                                                 str* srv_name, char* proto)
1072 {
1073         int i, idx;
1074         struct rdata* l;
1075         struct rdata* l_saved;
1076         struct naptr_rdata* naptr;
1077         struct naptr_rdata* naptr_saved;
1078         char saved_proto;
1079         char naptr_proto;
1080
1081         idx=0;
1082         naptr_proto=PROTO_NONE;
1083         naptr_saved=0;
1084         l_saved=0;
1085         saved_proto=0;
1086         i=0;
1087         for(l=naptr_head; l && (i<MAX_NAPTR_RRS); l=l->next){
1088                 if (l->type!=T_NAPTR) continue; 
1089                 naptr=(struct naptr_rdata*) l->rdata;
1090                 if (naptr==0){
1091                                 LOG(L_CRIT, "naptr_iterate: BUG: null rdata\n");
1092                         goto end;
1093                 }
1094                 /* check if valid and get proto */
1095                 if ((naptr_proto=naptr_get_sip_proto(naptr))<=0) continue;
1096                 if (*tried& (1<<i)){
1097                         i++;
1098                         continue; /* already tried */
1099                 }
1100 #ifdef NAPTR_DBG
1101                 DBG("naptr_iterate: found a valid sip NAPTR rr %.*s,"
1102                                         " proto %d\n", naptr->repl_len, naptr->repl, 
1103                                         (int)naptr_proto);
1104 #endif
1105                 if ((naptr_proto_supported(naptr_proto))){
1106                         if (naptr_choose(&naptr_saved, &saved_proto,
1107                                                                 naptr, naptr_proto))
1108                                 idx=i;
1109                                 l_saved=l;
1110                         }
1111                 i++;
1112         }
1113         if (naptr_saved){
1114                 /* found something */
1115 #ifdef NAPTR_DBG
1116                 DBG("naptr_iterate: choosed NAPTR rr %.*s, proto %d"
1117                                         " tried: 0x%x\n", naptr_saved->repl_len, 
1118                                         naptr_saved->repl, (int)saved_proto, *tried);
1119 #endif
1120                 *tried|=1<<idx;
1121                 *proto=saved_proto;
1122                 srv_name->s=naptr_saved->repl;
1123                 srv_name->len=naptr_saved->repl_len;
1124                 return l_saved;
1125         }
1126 end:
1127         return 0;
1128 }
1129
1130
1131
1132
1133 /* internal sip naptr resolver function: resolves a host name trying:
1134  * - NAPTR lookup if the address is not an ip and *proto==0 and *port==0.
1135  *   The result of the NAPTR query will be used for a SRV lookup
1136  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
1137  *   query will be used for an A/AAAA lookup.
1138  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
1139  *   and *proto!=0 or port==0 && proto==0)
1140  * when performing SRV lookup (*port==0) it will use proto to look for
1141  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
1142  * returns: hostent struct & *port filled with the port from the SRV record;
1143  *  0 on error
1144  */
1145 struct hostent* naptr_sip_resolvehost(str* name,  unsigned short* port,
1146                                                                                 char* proto)
1147 {
1148         struct hostent* he;
1149         struct ip_addr* ip;
1150         static char tmp[MAX_DNS_NAME]; /* tmp. buff. for SRV lookups and
1151                                           null. term  strings */
1152         struct rdata* l;
1153         struct rdata* naptr_head;
1154         char n_proto;
1155         str srv_name;
1156         naptr_bmp_t tried_bmp; /* tried bitmap */
1157
1158
1159
1160         naptr_head=0;
1161         he=0;
1162         if (name->len >= MAX_DNS_NAME) {
1163                 LOG(L_ERR, "naptr_sip_resolvehost: domain name too long\n");
1164                 goto end;
1165         }
1166         /* try NAPTR if no port or protocol is specified and NAPTR lookup is
1167          * enabled */
1168         if (port && proto && (*proto==0) && (*port==0)){
1169                 *proto=PROTO_UDP; /* just in case we don't find another */
1170                 if ( ((ip=str2ip(name))!=0)
1171 #ifdef  USE_IPV6
1172                           || ((ip=str2ip6(name))!=0)
1173 #endif
1174                 ){
1175                         /* we are lucky, this is an ip address */
1176                         he=ip_addr2he(name,ip);
1177                         *port=SIP_PORT;
1178                         goto end;
1179                 }
1180                 memcpy(tmp, name->s, name->len);
1181                 tmp[name->len] = '\0';
1182                 naptr_head=get_record(tmp, T_NAPTR, RES_AR);
1183                 naptr_iterate_init(&tried_bmp);
1184                 while((l=naptr_sip_iterate(naptr_head, &tried_bmp,
1185                                                                                 &srv_name, &n_proto))!=0){
1186                         if ((he=srv_sip_resolvehost(&srv_name, 1, port, proto, 1, l))!=0){
1187                                 *proto=n_proto;
1188                                 return he;
1189                         }
1190                 }
1191                 /*clean up on exit*/
1192 #ifdef RESOLVE_DBG
1193                 DBG("naptr_sip_resolvehost: no NAPTR record found for %.*s," 
1194                                 " trying SRV lookup...\n", name->len, name->s);
1195 #endif
1196         }
1197         /* fallback to normal srv lookup */
1198         he=srv_sip_resolvehost(name, 0, port, proto, 0, 0);
1199 end:
1200         if (naptr_head)
1201                 free_rdata_list(naptr_head);
1202         return he;
1203 }
1204 #endif /* USE_NAPTR */
1205
1206
1207
1208 /* resolves a host name trying:
1209  * - NAPTR lookup if enabled, the address is not an ip and *proto==0 and 
1210  *   *port==0. The result of the NAPTR query will be used for a SRV lookup
1211  * - SRV lookup if the address is not an ip *port==0. The result of the SRV
1212  *   query will be used for an A/AAAA lookup.
1213  *  - normal A/AAAA lookup (either fallback from the above or if *port!=0
1214  *   and *proto!=0 or port==0 && proto==0)
1215  * when performing SRV lookup (*port==0) it will use *proto to look for
1216  * tcp or udp hosts, otherwise proto is unused; if proto==0 => no SRV lookup
1217  *
1218  * returns: hostent struct & *port filled with the port from the SRV record;
1219  *  0 on error
1220  */
1221 struct hostent* _sip_resolvehost(str* name, unsigned short* port, char* proto)
1222 {
1223 #ifdef USE_NAPTR
1224         if (dns_try_naptr)
1225                 return naptr_sip_resolvehost(name, port, proto);
1226 #endif
1227         return srv_sip_resolvehost(name, 0, port, proto, 0, 0);
1228 }
1229
1230
1231 /* resolve host, port, proto using sip rules (e.g. use SRV if port=0 a.s.o)
1232  *  and write the result in the sockaddr_union to
1233  *  returns -1 on error (resolve failed), 0 on success */
1234 int sip_hostport2su(union sockaddr_union* su, str* name, unsigned short port,
1235                                                 char* proto)
1236 {
1237         struct hostent* he;
1238         
1239         he=sip_resolvehost(name, &port, proto);
1240         if (he==0){
1241                 ser_error=E_BAD_ADDRESS;
1242                 LOG(L_ERR, "ERROR: sip_hostport2su: could not resolve hostname:"
1243                                         " \"%.*s\"\n", name->len, name->s);
1244                 goto error;
1245         }
1246         /* port filled by sip_resolvehost if empty*/
1247         if (hostent2su(su, he, 0, port)<0){
1248                 ser_error=E_BAD_ADDRESS;
1249                 goto error;
1250         }
1251         return 0;
1252 error:
1253         return -1;
1254 }