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