xref: /PHP-7.4/ext/standard/dns.c (revision 45f52285)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: The typical suspects                                        |
16    |          Pollita <pollita@php.net>                                   |
17    |          Marcus Boerger <helly@php.net>                              |
18    +----------------------------------------------------------------------+
19  */
20 
21 /* {{{ includes */
22 #include "php.h"
23 #include "php_network.h"
24 
25 #if HAVE_SYS_SOCKET_H
26 #include <sys/socket.h>
27 #endif
28 
29 #ifdef PHP_WIN32
30 # include "win32/inet.h"
31 # include <winsock2.h>
32 # include <windows.h>
33 # include <Ws2tcpip.h>
34 #else
35 #include <netinet/in.h>
36 #if HAVE_ARPA_INET_H
37 #include <arpa/inet.h>
38 #endif
39 #include <netdb.h>
40 #ifdef _OSD_POSIX
41 #undef STATUS
42 #undef T_UNSPEC
43 #endif
44 #if HAVE_ARPA_NAMESER_H
45 #ifdef DARWIN
46 # define BIND_8_COMPAT 1
47 #endif
48 #include <arpa/nameser.h>
49 #endif
50 #if HAVE_RESOLV_H
51 #include <resolv.h>
52 #endif
53 #ifdef HAVE_DNS_H
54 #include <dns.h>
55 #endif
56 #endif
57 
58 #ifndef MAXHOSTNAMELEN
59 #define MAXHOSTNAMELEN 255
60 #endif
61 
62 /* For the local hostname obtained via gethostname which is different from the
63    dns-related MAXHOSTNAMELEN constant above */
64 #ifndef HOST_NAME_MAX
65 #define HOST_NAME_MAX 255
66 #endif
67 
68 #include "php_dns.h"
69 
70 /* type compat */
71 #ifndef DNS_T_A
72 #define DNS_T_A		1
73 #endif
74 #ifndef DNS_T_NS
75 #define DNS_T_NS	2
76 #endif
77 #ifndef DNS_T_CNAME
78 #define DNS_T_CNAME	5
79 #endif
80 #ifndef DNS_T_SOA
81 #define DNS_T_SOA	6
82 #endif
83 #ifndef DNS_T_PTR
84 #define DNS_T_PTR	12
85 #endif
86 #ifndef DNS_T_HINFO
87 #define DNS_T_HINFO	13
88 #endif
89 #ifndef DNS_T_MINFO
90 #define DNS_T_MINFO	14
91 #endif
92 #ifndef DNS_T_MX
93 #define DNS_T_MX	15
94 #endif
95 #ifndef DNS_T_TXT
96 #define DNS_T_TXT	16
97 #endif
98 #ifndef DNS_T_AAAA
99 #define DNS_T_AAAA	28
100 #endif
101 #ifndef DNS_T_SRV
102 #define DNS_T_SRV	33
103 #endif
104 #ifndef DNS_T_NAPTR
105 #define DNS_T_NAPTR	35
106 #endif
107 #ifndef DNS_T_A6
108 #define DNS_T_A6	38
109 #endif
110 #ifndef DNS_T_CAA
111 #define DNS_T_CAA	257
112 #endif
113 
114 #ifndef DNS_T_ANY
115 #define DNS_T_ANY	255
116 #endif
117 /* }}} */
118 
119 static zend_string *php_gethostbyaddr(char *ip);
120 static zend_string *php_gethostbyname(char *name);
121 
122 #ifdef HAVE_GETHOSTNAME
123 /* {{{ proto string gethostname()
124    Get the host name of the current machine */
PHP_FUNCTION(gethostname)125 PHP_FUNCTION(gethostname)
126 {
127 	char buf[HOST_NAME_MAX + 1];
128 
129 	if (zend_parse_parameters_none() == FAILURE) {
130 		return;
131 	}
132 
133 	if (gethostname(buf, sizeof(buf))) {
134 		php_error_docref(NULL, E_WARNING, "unable to fetch host [%d]: %s", errno, strerror(errno));
135 		RETURN_FALSE;
136 	}
137 
138 	RETURN_STRING(buf);
139 }
140 /* }}} */
141 #endif
142 
143 /* TODO: Reimplement the gethostby* functions using the new winxp+ API, in dns_win32.c, then
144  we can have a dns.c, dns_unix.c and dns_win32.c instead of a messy dns.c full of #ifdef
145 */
146 
147 /* {{{ proto string gethostbyaddr(string ip_address)
148    Get the Internet host name corresponding to a given IP address */
PHP_FUNCTION(gethostbyaddr)149 PHP_FUNCTION(gethostbyaddr)
150 {
151 	char *addr;
152 	size_t addr_len;
153 	zend_string *hostname;
154 
155 	ZEND_PARSE_PARAMETERS_START(1, 1)
156 		Z_PARAM_STRING(addr, addr_len)
157 	ZEND_PARSE_PARAMETERS_END();
158 
159 	hostname = php_gethostbyaddr(addr);
160 
161 	if (hostname == NULL) {
162 #if HAVE_IPV6 && HAVE_INET_PTON
163 		php_error_docref(NULL, E_WARNING, "Address is not a valid IPv4 or IPv6 address");
164 #else
165 		php_error_docref(NULL, E_WARNING, "Address is not in a.b.c.d form");
166 #endif
167 		RETVAL_FALSE;
168 	} else {
169 		RETVAL_STR(hostname);
170 	}
171 }
172 /* }}} */
173 
174 /* {{{ php_gethostbyaddr */
php_gethostbyaddr(char * ip)175 static zend_string *php_gethostbyaddr(char *ip)
176 {
177 #if HAVE_IPV6 && HAVE_INET_PTON
178 	struct in6_addr addr6;
179 #endif
180 	struct in_addr addr;
181 	struct hostent *hp;
182 
183 #if HAVE_IPV6 && HAVE_INET_PTON
184 	if (inet_pton(AF_INET6, ip, &addr6)) {
185 		hp = gethostbyaddr((char *) &addr6, sizeof(addr6), AF_INET6);
186 	} else if (inet_pton(AF_INET, ip, &addr)) {
187 		hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
188 	} else {
189 		return NULL;
190 	}
191 #else
192 	addr.s_addr = inet_addr(ip);
193 
194 	if (addr.s_addr == -1) {
195 		return NULL;
196 	}
197 
198 	hp = gethostbyaddr((char *) &addr, sizeof(addr), AF_INET);
199 #endif
200 
201 	if (!hp || hp->h_name == NULL || hp->h_name[0] == '\0') {
202 		return zend_string_init(ip, strlen(ip), 0);
203 	}
204 
205 	return zend_string_init(hp->h_name, strlen(hp->h_name), 0);
206 }
207 /* }}} */
208 
209 /* {{{ proto string gethostbyname(string hostname)
210    Get the IP address corresponding to a given Internet host name */
PHP_FUNCTION(gethostbyname)211 PHP_FUNCTION(gethostbyname)
212 {
213 	char *hostname;
214 	size_t hostname_len;
215 
216 	ZEND_PARSE_PARAMETERS_START(1, 1)
217 		Z_PARAM_STRING(hostname, hostname_len)
218 	ZEND_PARSE_PARAMETERS_END();
219 
220 	if(hostname_len > MAXFQDNLEN) {
221 		/* name too long, protect from CVE-2015-0235 */
222 		php_error_docref(NULL, E_WARNING, "Host name is too long, the limit is %d characters", MAXFQDNLEN);
223 		RETURN_STRINGL(hostname, hostname_len);
224 	}
225 
226 	RETURN_STR(php_gethostbyname(hostname));
227 }
228 /* }}} */
229 
230 /* {{{ proto array gethostbynamel(string hostname)
231    Return a list of IP addresses that a given hostname resolves to. */
PHP_FUNCTION(gethostbynamel)232 PHP_FUNCTION(gethostbynamel)
233 {
234 	char *hostname;
235 	size_t hostname_len;
236 	struct hostent *hp;
237 	struct in_addr in;
238 	int i;
239 
240 	ZEND_PARSE_PARAMETERS_START(1, 1)
241 		Z_PARAM_STRING(hostname, hostname_len)
242 	ZEND_PARSE_PARAMETERS_END();
243 
244 	if(hostname_len > MAXFQDNLEN) {
245 		/* name too long, protect from CVE-2015-0235 */
246 		php_error_docref(NULL, E_WARNING, "Host name is too long, the limit is %d characters", MAXFQDNLEN);
247 		RETURN_FALSE;
248 	}
249 
250 	hp = php_network_gethostbyname(hostname);
251 	if (!hp) {
252 		RETURN_FALSE;
253 	}
254 
255 	array_init(return_value);
256 
257 	for (i = 0;; i++) {
258 		/* On macos h_addr_list entries may be misaligned. */
259 		struct in_addr *h_addr_entry; /* Don't call this h_addr, it's a macro! */
260 		memcpy(&h_addr_entry, &hp->h_addr_list[i], sizeof(struct in_addr *));
261 		if (!h_addr_entry) {
262 			return;
263 		}
264 
265 		in = *h_addr_entry;
266 		add_next_index_string(return_value, inet_ntoa(in));
267 	}
268 }
269 /* }}} */
270 
271 /* {{{ php_gethostbyname */
php_gethostbyname(char * name)272 static zend_string *php_gethostbyname(char *name)
273 {
274 	struct hostent *hp;
275 	struct in_addr *h_addr_0; /* Don't call this h_addr, it's a macro! */
276 	struct in_addr in;
277 	char *address;
278 
279 	hp = php_network_gethostbyname(name);
280 	if (!hp) {
281 		return zend_string_init(name, strlen(name), 0);
282 	}
283 
284 	/* On macos h_addr_list entries may be misaligned. */
285 	memcpy(&h_addr_0, &hp->h_addr_list[0], sizeof(struct in_addr *));
286 	if (!h_addr_0) {
287 		return zend_string_init(name, strlen(name), 0);
288 	}
289 
290 	memcpy(&in.s_addr, h_addr_0, sizeof(in.s_addr));
291 
292 	address = inet_ntoa(in);
293 	return zend_string_init(address, strlen(address), 0);
294 }
295 /* }}} */
296 
297 #if HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32)
298 # define PHP_DNS_NUM_TYPES	13	/* Number of DNS Types Supported by PHP currently */
299 
300 # define PHP_DNS_A      0x00000001
301 # define PHP_DNS_NS     0x00000002
302 # define PHP_DNS_CNAME  0x00000010
303 # define PHP_DNS_SOA    0x00000020
304 # define PHP_DNS_PTR    0x00000800
305 # define PHP_DNS_HINFO  0x00001000
306 # define PHP_DNS_CAA    0x00002000
307 # define PHP_DNS_MX     0x00004000
308 # define PHP_DNS_TXT    0x00008000
309 # define PHP_DNS_A6     0x01000000
310 # define PHP_DNS_SRV    0x02000000
311 # define PHP_DNS_NAPTR  0x04000000
312 # define PHP_DNS_AAAA   0x08000000
313 # define PHP_DNS_ANY    0x10000000
314 # define PHP_DNS_ALL    (PHP_DNS_A|PHP_DNS_NS|PHP_DNS_CNAME|PHP_DNS_SOA|PHP_DNS_PTR|PHP_DNS_HINFO|PHP_DNS_CAA|PHP_DNS_MX|PHP_DNS_TXT|PHP_DNS_A6|PHP_DNS_SRV|PHP_DNS_NAPTR|PHP_DNS_AAAA)
315 #endif /* HAVE_FULL_DNS_FUNCS || defined(PHP_WIN32) */
316 
317 /* Note: These functions are defined in ext/standard/dns_win32.c for Windows! */
318 #if !defined(PHP_WIN32) && HAVE_DNS_SEARCH_FUNC
319 
320 #ifndef HFIXEDSZ
321 #define HFIXEDSZ        12      /* fixed data in header <arpa/nameser.h> */
322 #endif /* HFIXEDSZ */
323 
324 #ifndef QFIXEDSZ
325 #define QFIXEDSZ        4       /* fixed data in query <arpa/nameser.h> */
326 #endif /* QFIXEDSZ */
327 
328 #undef MAXHOSTNAMELEN
329 #define MAXHOSTNAMELEN  1024
330 
331 #ifndef MAXRESOURCERECORDS
332 #define MAXRESOURCERECORDS	64
333 #endif /* MAXRESOURCERECORDS */
334 
335 typedef union {
336 	HEADER qb1;
337 	u_char qb2[65536];
338 } querybuf;
339 
340 /* just a hack to free resources allocated by glibc in __res_nsend()
341  * See also:
342  *   res_thread_freeres() in glibc/resolv/res_init.c
343  *   __libc_res_nsend()   in resolv/res_send.c
344  * */
345 
346 #if defined(__GLIBC__) && !defined(HAVE_DEPRECATED_DNS_FUNCS)
347 #define php_dns_free_res(__res__) _php_dns_free_res(__res__)
_php_dns_free_res(struct __res_state * res)348 static void _php_dns_free_res(struct __res_state *res) { /* {{{ */
349 	int ns;
350 	for (ns = 0; ns < MAXNS; ns++) {
351 		if (res->_u._ext.nsaddrs[ns] != NULL) {
352 			free (res->_u._ext.nsaddrs[ns]);
353 			res->_u._ext.nsaddrs[ns] = NULL;
354 		}
355 	}
356 } /* }}} */
357 #else
358 #define php_dns_free_res(__res__)
359 #endif
360 
361 /* {{{ proto bool dns_check_record(string host [, string type])
362    Check DNS records corresponding to a given Internet host name or IP address */
PHP_FUNCTION(dns_check_record)363 PHP_FUNCTION(dns_check_record)
364 {
365 	HEADER *hp;
366 	querybuf answer;
367 	char *hostname, *rectype = NULL;
368 	size_t hostname_len, rectype_len = 0;
369 	int type = DNS_T_MX, i;
370 #if defined(HAVE_DNS_SEARCH)
371 	struct sockaddr_storage from;
372 	uint32_t fromsize = sizeof(from);
373 	dns_handle_t handle;
374 #elif defined(HAVE_RES_NSEARCH)
375 	struct __res_state state;
376 	struct __res_state *handle = &state;
377 #endif
378 
379 	ZEND_PARSE_PARAMETERS_START(1, 2)
380 		Z_PARAM_STRING(hostname, hostname_len)
381 		Z_PARAM_OPTIONAL
382 		Z_PARAM_STRING(rectype, rectype_len)
383 	ZEND_PARSE_PARAMETERS_END();
384 
385 	if (hostname_len == 0) {
386 		php_error_docref(NULL, E_WARNING, "Host cannot be empty");
387 		RETURN_FALSE;
388 	}
389 
390 	if (rectype) {
391 		if (!strcasecmp("A",     rectype)) type = DNS_T_A;
392 		else if (!strcasecmp("NS",    rectype)) type = DNS_T_NS;
393 		else if (!strcasecmp("MX",    rectype)) type = DNS_T_MX;
394 		else if (!strcasecmp("PTR",   rectype)) type = DNS_T_PTR;
395 		else if (!strcasecmp("ANY",   rectype)) type = DNS_T_ANY;
396 		else if (!strcasecmp("SOA",   rectype)) type = DNS_T_SOA;
397 		else if (!strcasecmp("CAA",   rectype)) type = DNS_T_CAA;
398 		else if (!strcasecmp("TXT",   rectype)) type = DNS_T_TXT;
399 		else if (!strcasecmp("CNAME", rectype)) type = DNS_T_CNAME;
400 		else if (!strcasecmp("AAAA",  rectype)) type = DNS_T_AAAA;
401 		else if (!strcasecmp("SRV",   rectype)) type = DNS_T_SRV;
402 		else if (!strcasecmp("NAPTR", rectype)) type = DNS_T_NAPTR;
403 		else if (!strcasecmp("A6",    rectype)) type = DNS_T_A6;
404 		else {
405 			php_error_docref(NULL, E_WARNING, "Type '%s' not supported", rectype);
406 			RETURN_FALSE;
407 		}
408 	}
409 
410 #if defined(HAVE_DNS_SEARCH)
411 	handle = dns_open(NULL);
412 	if (handle == NULL) {
413 		RETURN_FALSE;
414 	}
415 #elif defined(HAVE_RES_NSEARCH)
416     memset(&state, 0, sizeof(state));
417     if (res_ninit(handle)) {
418 			RETURN_FALSE;
419 	}
420 #else
421 	res_init();
422 #endif
423 
424 	i = php_dns_search(handle, hostname, C_IN, type, answer.qb2, sizeof answer);
425 	php_dns_free_handle(handle);
426 
427 	if (i < 0) {
428 		RETURN_FALSE;
429 	}
430 	hp = (HEADER *)&answer;
431 	RETURN_BOOL(ntohs(hp->ancount) != 0);
432 }
433 /* }}} */
434 
435 #if HAVE_FULL_DNS_FUNCS
436 
437 #define CHECKCP(n) do { \
438 	if (cp + n > end) { \
439 		return NULL; \
440 	} \
441 } while (0)
442 
443 /* {{{ php_parserr */
php_parserr(u_char * cp,u_char * end,querybuf * answer,int type_to_fetch,int store,int raw,zval * subarray)444 static u_char *php_parserr(u_char *cp, u_char *end, querybuf *answer, int type_to_fetch, int store, int raw, zval *subarray)
445 {
446 	u_short type, class, dlen;
447 	u_long ttl;
448 	long n, i;
449 	u_short s;
450 	u_char *tp, *p;
451 	char name[MAXHOSTNAMELEN];
452 	int have_v6_break = 0, in_v6_break = 0;
453 
454 	ZVAL_UNDEF(subarray);
455 
456 	n = dn_expand(answer->qb2, end, cp, name, sizeof(name) - 2);
457 	if (n < 0) {
458 		return NULL;
459 	}
460 	cp += n;
461 
462 	CHECKCP(10);
463 	GETSHORT(type, cp);
464 	GETSHORT(class, cp);
465 	GETLONG(ttl, cp);
466 	GETSHORT(dlen, cp);
467 	CHECKCP(dlen);
468     if (dlen == 0) {
469         /* No data in the response - nothing to do */
470         return NULL;
471     }
472     if (type_to_fetch != DNS_T_ANY && type != type_to_fetch) {
473 		cp += dlen;
474 		return cp;
475 	}
476 
477 	if (!store) {
478 		cp += dlen;
479 		return cp;
480 	}
481 
482 	array_init(subarray);
483 
484 	add_assoc_string(subarray, "host", name);
485 	add_assoc_string(subarray, "class", "IN");
486 	add_assoc_long(subarray, "ttl", ttl);
487 	(void) class;
488 
489 	if (raw) {
490 		add_assoc_long(subarray, "type", type);
491 		add_assoc_stringl(subarray, "data", (char*) cp, (uint32_t) dlen);
492 		cp += dlen;
493 		return cp;
494 	}
495 
496 	switch (type) {
497 		case DNS_T_A:
498 			CHECKCP(4);
499 			add_assoc_string(subarray, "type", "A");
500 			snprintf(name, sizeof(name), "%d.%d.%d.%d", cp[0], cp[1], cp[2], cp[3]);
501 			add_assoc_string(subarray, "ip", name);
502 			cp += dlen;
503 			break;
504 		case DNS_T_MX:
505 			CHECKCP(2);
506 			add_assoc_string(subarray, "type", "MX");
507 			GETSHORT(n, cp);
508 			add_assoc_long(subarray, "pri", n);
509 			/* no break; */
510 		case DNS_T_CNAME:
511 			if (type == DNS_T_CNAME) {
512 				add_assoc_string(subarray, "type", "CNAME");
513 			}
514 			/* no break; */
515 		case DNS_T_NS:
516 			if (type == DNS_T_NS) {
517 				add_assoc_string(subarray, "type", "NS");
518 			}
519 			/* no break; */
520 		case DNS_T_PTR:
521 			if (type == DNS_T_PTR) {
522 				add_assoc_string(subarray, "type", "PTR");
523 			}
524 			n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
525 			if (n < 0) {
526 				return NULL;
527 			}
528 			cp += n;
529 			add_assoc_string(subarray, "target", name);
530 			break;
531 		case DNS_T_HINFO:
532 			/* See RFC 1010 for values */
533 			add_assoc_string(subarray, "type", "HINFO");
534 			CHECKCP(1);
535 			n = *cp & 0xFF;
536 			cp++;
537 			CHECKCP(n);
538 			add_assoc_stringl(subarray, "cpu", (char*)cp, n);
539 			cp += n;
540 			CHECKCP(1);
541 			n = *cp & 0xFF;
542 			cp++;
543 			CHECKCP(n);
544 			add_assoc_stringl(subarray, "os", (char*)cp, n);
545 			cp += n;
546 			break;
547 		case DNS_T_CAA:
548 			/* See RFC 6844 for values https://tools.ietf.org/html/rfc6844 */
549 			add_assoc_string(subarray, "type", "CAA");
550 			// 1 flag byte
551 			CHECKCP(1);
552 			n = *cp & 0xFF;
553 			add_assoc_long(subarray, "flags", n);
554 			cp++;
555 			// Tag length (1 byte)
556 			CHECKCP(1);
557 			n = *cp & 0xFF;
558 			cp++;
559 			CHECKCP(n);
560 			add_assoc_stringl(subarray, "tag", (char*)cp, n);
561 			cp += n;
562 			if ( (size_t) dlen < ((size_t)n) + 2 ) {
563 				return NULL;
564 			}
565 			n = dlen - n - 2;
566 			CHECKCP(n);
567 			add_assoc_stringl(subarray, "value", (char*)cp, n);
568 			cp += n;
569 			break;
570 		case DNS_T_TXT:
571 			{
572 				int l1 = 0, l2 = 0;
573 				zval entries;
574 				zend_string *tp;
575 
576 				add_assoc_string(subarray, "type", "TXT");
577 				tp = zend_string_alloc(dlen, 0);
578 
579 				array_init(&entries);
580 
581 				while (l1 < dlen) {
582 					n = cp[l1];
583 					if ((l1 + n) >= dlen) {
584 						// Invalid chunk length, truncate
585 						n = dlen - (l1 + 1);
586 					}
587 					if (n) {
588 						memcpy(ZSTR_VAL(tp) + l2 , cp + l1 + 1, n);
589 						add_next_index_stringl(&entries, (char *) cp + l1 + 1, n);
590 					}
591 					l1 = l1 + n + 1;
592 					l2 = l2 + n;
593 				}
594 				ZSTR_VAL(tp)[l2] = '\0';
595 				ZSTR_LEN(tp) = l2;
596 				cp += dlen;
597 
598 				add_assoc_str(subarray, "txt", tp);
599 				add_assoc_zval(subarray, "entries", &entries);
600 			}
601 			break;
602 		case DNS_T_SOA:
603 			add_assoc_string(subarray, "type", "SOA");
604 			n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
605 			if (n < 0) {
606 				return NULL;
607 			}
608 			cp += n;
609 			add_assoc_string(subarray, "mname", name);
610 			n = dn_expand(answer->qb2, end, cp, name, (sizeof name) -2);
611 			if (n < 0) {
612 				return NULL;
613 			}
614 			cp += n;
615 			add_assoc_string(subarray, "rname", name);
616 			CHECKCP(5*4);
617 			GETLONG(n, cp);
618 			add_assoc_long(subarray, "serial", n);
619 			GETLONG(n, cp);
620 			add_assoc_long(subarray, "refresh", n);
621 			GETLONG(n, cp);
622 			add_assoc_long(subarray, "retry", n);
623 			GETLONG(n, cp);
624 			add_assoc_long(subarray, "expire", n);
625 			GETLONG(n, cp);
626 			add_assoc_long(subarray, "minimum-ttl", n);
627 			break;
628 		case DNS_T_AAAA:
629 			tp = (u_char*)name;
630 			CHECKCP(8*2);
631 			for(i=0; i < 8; i++) {
632 				GETSHORT(s, cp);
633 				if (s != 0) {
634 					if (tp > (u_char *)name) {
635 						in_v6_break = 0;
636 						tp[0] = ':';
637 						tp++;
638 					}
639 					tp += sprintf((char*)tp,"%x",s);
640 				} else {
641 					if (!have_v6_break) {
642 						have_v6_break = 1;
643 						in_v6_break = 1;
644 						tp[0] = ':';
645 						tp++;
646 					} else if (!in_v6_break) {
647 						tp[0] = ':';
648 						tp++;
649 						tp[0] = '0';
650 						tp++;
651 					}
652 				}
653 			}
654 			if (have_v6_break && in_v6_break) {
655 				tp[0] = ':';
656 				tp++;
657 			}
658 			tp[0] = '\0';
659 			add_assoc_string(subarray, "type", "AAAA");
660 			add_assoc_string(subarray, "ipv6", name);
661 			break;
662 		case DNS_T_A6:
663 			p = cp;
664 			add_assoc_string(subarray, "type", "A6");
665 			CHECKCP(1);
666 			n = ((int)cp[0]) & 0xFF;
667 			cp++;
668 			add_assoc_long(subarray, "masklen", n);
669 			tp = (u_char*)name;
670 			if (n > 15) {
671 				have_v6_break = 1;
672 				in_v6_break = 1;
673 				tp[0] = ':';
674 				tp++;
675 			}
676 			if (n % 16 > 8) {
677 				/* Partial short */
678 				if (cp[0] != 0) {
679 					if (tp > (u_char *)name) {
680 						in_v6_break = 0;
681 						tp[0] = ':';
682 						tp++;
683 					}
684 					sprintf((char*)tp, "%x", cp[0] & 0xFF);
685 				} else {
686 					if (!have_v6_break) {
687 						have_v6_break = 1;
688 						in_v6_break = 1;
689 						tp[0] = ':';
690 						tp++;
691 					} else if (!in_v6_break) {
692 						tp[0] = ':';
693 						tp++;
694 						tp[0] = '0';
695 						tp++;
696 					}
697 				}
698 				cp++;
699 			}
700 			for (i = (n + 8) / 16; i < 8; i++) {
701 				CHECKCP(2);
702 				GETSHORT(s, cp);
703 				if (s != 0) {
704 					if (tp > (u_char *)name) {
705 						in_v6_break = 0;
706 						tp[0] = ':';
707 						tp++;
708 					}
709 					tp += sprintf((char*)tp,"%x",s);
710 				} else {
711 					if (!have_v6_break) {
712 						have_v6_break = 1;
713 						in_v6_break = 1;
714 						tp[0] = ':';
715 						tp++;
716 					} else if (!in_v6_break) {
717 						tp[0] = ':';
718 						tp++;
719 						tp[0] = '0';
720 						tp++;
721 					}
722 				}
723 			}
724 			if (have_v6_break && in_v6_break) {
725 				tp[0] = ':';
726 				tp++;
727 			}
728 			tp[0] = '\0';
729 			add_assoc_string(subarray, "ipv6", name);
730 			if (cp < p + dlen) {
731 				n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
732 				if (n < 0) {
733 					return NULL;
734 				}
735 				cp += n;
736 				add_assoc_string(subarray, "chain", name);
737 			}
738 			break;
739 		case DNS_T_SRV:
740 			CHECKCP(3*2);
741 			add_assoc_string(subarray, "type", "SRV");
742 			GETSHORT(n, cp);
743 			add_assoc_long(subarray, "pri", n);
744 			GETSHORT(n, cp);
745 			add_assoc_long(subarray, "weight", n);
746 			GETSHORT(n, cp);
747 			add_assoc_long(subarray, "port", n);
748 			n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
749 			if (n < 0) {
750 				return NULL;
751 			}
752 			cp += n;
753 			add_assoc_string(subarray, "target", name);
754 			break;
755 		case DNS_T_NAPTR:
756 			CHECKCP(2*2);
757 			add_assoc_string(subarray, "type", "NAPTR");
758 			GETSHORT(n, cp);
759 			add_assoc_long(subarray, "order", n);
760 			GETSHORT(n, cp);
761 			add_assoc_long(subarray, "pref", n);
762 
763 			CHECKCP(1);
764 			n = (cp[0] & 0xFF);
765 			cp++;
766 			CHECKCP(n);
767 			add_assoc_stringl(subarray, "flags", (char*)cp, n);
768 			cp += n;
769 
770 			CHECKCP(1);
771 			n = (cp[0] & 0xFF);
772 			cp++;
773 			CHECKCP(n);
774 			add_assoc_stringl(subarray, "services", (char*)cp, n);
775 			cp += n;
776 
777 			CHECKCP(1);
778 			n = (cp[0] & 0xFF);
779 			cp++;
780 			CHECKCP(n);
781 			add_assoc_stringl(subarray, "regex", (char*)cp, n);
782 			cp += n;
783 
784 			n = dn_expand(answer->qb2, end, cp, name, (sizeof name) - 2);
785 			if (n < 0) {
786 				return NULL;
787 			}
788 			cp += n;
789 			add_assoc_string(subarray, "replacement", name);
790 			break;
791 		default:
792 			zval_ptr_dtor(subarray);
793 			ZVAL_UNDEF(subarray);
794 			cp += dlen;
795 			break;
796 	}
797 
798 	return cp;
799 }
800 /* }}} */
801 
802 /* {{{ proto array|false dns_get_record(string hostname [, int type[, array &authns[, array &addtl[, bool raw]]]])
803    Get any Resource Record corresponding to a given Internet host name */
PHP_FUNCTION(dns_get_record)804 PHP_FUNCTION(dns_get_record)
805 {
806 	char *hostname;
807 	size_t hostname_len;
808 	zend_long type_param = PHP_DNS_ANY;
809 	zval *authns = NULL, *addtl = NULL;
810 	int type_to_fetch;
811 	int dns_errno;
812 #if defined(HAVE_DNS_SEARCH)
813 	struct sockaddr_storage from;
814 	uint32_t fromsize = sizeof(from);
815 	dns_handle_t handle;
816 #elif defined(HAVE_RES_NSEARCH)
817 	struct __res_state state;
818 	struct __res_state *handle = &state;
819 #endif
820 	HEADER *hp;
821 	querybuf answer;
822 	u_char *cp = NULL, *end = NULL;
823 	int n, qd, an, ns = 0, ar = 0;
824 	int type, first_query = 1, store_results = 1;
825 	zend_bool raw = 0;
826 
827 	ZEND_PARSE_PARAMETERS_START(1, 5)
828 		Z_PARAM_STRING(hostname, hostname_len)
829 		Z_PARAM_OPTIONAL
830 		Z_PARAM_LONG(type_param)
831 		Z_PARAM_ZVAL(authns)
832 		Z_PARAM_ZVAL(addtl)
833 		Z_PARAM_BOOL(raw)
834 	ZEND_PARSE_PARAMETERS_END();
835 
836 	if (authns) {
837 		authns = zend_try_array_init(authns);
838 		if (!authns) {
839 			return;
840 		}
841 	}
842 	if (addtl) {
843 		addtl = zend_try_array_init(addtl);
844 		if (!addtl) {
845 			return;
846 		}
847 	}
848 
849 	if (!raw) {
850 		if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {
851 			php_error_docref(NULL, E_WARNING, "Type '" ZEND_LONG_FMT "' not supported", type_param);
852 			RETURN_FALSE;
853 		}
854 	} else {
855 		if ((type_param < 1) || (type_param > 0xFFFF)) {
856 			php_error_docref(NULL, E_WARNING,
857 				"Numeric DNS record type must be between 1 and 65535, '" ZEND_LONG_FMT "' given", type_param);
858 			RETURN_FALSE;
859 		}
860 	}
861 
862 	/* Initialize the return array */
863 	array_init(return_value);
864 
865 	/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )
866 	 *   If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )
867 	 *   store_results is used to skip storing the results retrieved in step
868 	 *   NUMTYPES+1 when results were already fetched.
869 	 * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )
870 	 * - In case of raw mode, we query only the requestd type instead of looping type by type
871 	 *   before going with the additional info stuff.
872 	 */
873 
874 	if (raw) {
875 		type = -1;
876 	} else if (type_param == PHP_DNS_ANY) {
877 		type = PHP_DNS_NUM_TYPES + 1;
878 	} else {
879 		type = 0;
880 	}
881 
882 	for ( ;
883 		type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;
884 		type++
885 	) {
886 		first_query = 0;
887 		switch (type) {
888 			case -1: /* raw */
889 				type_to_fetch = type_param;
890 				/* skip over the rest and go directly to additional records */
891 				type = PHP_DNS_NUM_TYPES - 1;
892 				break;
893 			case 0:
894 				type_to_fetch = type_param&PHP_DNS_A     ? DNS_T_A     : 0;
895 				break;
896 			case 1:
897 				type_to_fetch = type_param&PHP_DNS_NS    ? DNS_T_NS    : 0;
898 				break;
899 			case 2:
900 				type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;
901 				break;
902 			case 3:
903 				type_to_fetch = type_param&PHP_DNS_SOA   ? DNS_T_SOA   : 0;
904 				break;
905 			case 4:
906 				type_to_fetch = type_param&PHP_DNS_PTR   ? DNS_T_PTR   : 0;
907 				break;
908 			case 5:
909 				type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;
910 				break;
911 			case 6:
912 				type_to_fetch = type_param&PHP_DNS_MX    ? DNS_T_MX    : 0;
913 				break;
914 			case 7:
915 				type_to_fetch = type_param&PHP_DNS_TXT   ? DNS_T_TXT   : 0;
916 				break;
917 			case 8:
918 				type_to_fetch = type_param&PHP_DNS_AAAA	 ? DNS_T_AAAA  : 0;
919 				break;
920 			case 9:
921 				type_to_fetch = type_param&PHP_DNS_SRV   ? DNS_T_SRV   : 0;
922 				break;
923 			case 10:
924 				type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;
925 				break;
926 			case 11:
927 				type_to_fetch = type_param&PHP_DNS_A6	 ? DNS_T_A6 : 0;
928 				break;
929 			case 12:
930 				type_to_fetch = type_param&PHP_DNS_CAA ? DNS_T_CAA : 0;
931 				break;
932 			case PHP_DNS_NUM_TYPES:
933 				store_results = 0;
934 				continue;
935 			default:
936 			case (PHP_DNS_NUM_TYPES + 1):
937 				type_to_fetch = DNS_T_ANY;
938 				break;
939 		}
940 
941 		if (type_to_fetch) {
942 #if defined(HAVE_DNS_SEARCH)
943 			handle = dns_open(NULL);
944 			if (handle == NULL) {
945 				zend_array_destroy(Z_ARR_P(return_value));
946 				RETURN_FALSE;
947 			}
948 #elif defined(HAVE_RES_NSEARCH)
949 		    memset(&state, 0, sizeof(state));
950 		    if (res_ninit(handle)) {
951 		    	zend_array_destroy(Z_ARR_P(return_value));
952 				RETURN_FALSE;
953 			}
954 #else
955 			res_init();
956 #endif
957 
958 			n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);
959 
960 			if (n < 0) {
961 				dns_errno = php_dns_errno(handle);
962 				php_dns_free_handle(handle);
963 				switch (dns_errno) {
964 					case NO_DATA:
965 					case HOST_NOT_FOUND:
966 						continue;
967 
968 					case NO_RECOVERY:
969 						php_error_docref(NULL, E_WARNING, "An unexpected server failure occurred.");
970 						break;
971 
972 					case TRY_AGAIN:
973 						php_error_docref(NULL, E_WARNING, "A temporary server error occurred.");
974 						break;
975 
976 					default:
977 						php_error_docref(NULL, E_WARNING, "DNS Query failed");
978 				}
979 				zend_array_destroy(Z_ARR_P(return_value));
980 				RETURN_FALSE;
981 			}
982 
983 			cp = answer.qb2 + HFIXEDSZ;
984 			end = answer.qb2 + n;
985 			hp = (HEADER *)&answer;
986 			qd = ntohs(hp->qdcount);
987 			an = ntohs(hp->ancount);
988 			ns = ntohs(hp->nscount);
989 			ar = ntohs(hp->arcount);
990 
991 			/* Skip QD entries, they're only used by dn_expand later on */
992 			while (qd-- > 0) {
993 				n = dn_skipname(cp, end);
994 				if (n < 0) {
995 					php_error_docref(NULL, E_WARNING, "Unable to parse DNS data received");
996 					zend_array_destroy(Z_ARR_P(return_value));
997 					php_dns_free_handle(handle);
998 					RETURN_FALSE;
999 				}
1000 				cp += n + QFIXEDSZ;
1001 			}
1002 
1003 			/* YAY! Our real answers! */
1004 			while (an-- && cp && cp < end) {
1005 				zval retval;
1006 
1007 				cp = php_parserr(cp, end, &answer, type_to_fetch, store_results, raw, &retval);
1008 				if (Z_TYPE(retval) != IS_UNDEF && store_results) {
1009 					add_next_index_zval(return_value, &retval);
1010 				}
1011 			}
1012 
1013 			if (authns || addtl) {
1014 				/* List of Authoritative Name Servers
1015 				 * Process when only requesting addtl so that we can skip through the section
1016 				 */
1017 				while (ns-- > 0 && cp && cp < end) {
1018 					zval retval;
1019 
1020 					cp = php_parserr(cp, end, &answer, DNS_T_ANY, authns != NULL, raw, &retval);
1021 					if (Z_TYPE(retval) != IS_UNDEF) {
1022 						add_next_index_zval(authns, &retval);
1023 					}
1024 				}
1025 			}
1026 
1027 			if (addtl) {
1028 				/* Additional records associated with authoritative name servers */
1029 				while (ar-- > 0 && cp && cp < end) {
1030 					zval retval;
1031 
1032 					cp = php_parserr(cp, end, &answer, DNS_T_ANY, 1, raw, &retval);
1033 					if (Z_TYPE(retval) != IS_UNDEF) {
1034 						add_next_index_zval(addtl, &retval);
1035 					}
1036 				}
1037 			}
1038 			php_dns_free_handle(handle);
1039 		}
1040 	}
1041 }
1042 /* }}} */
1043 
1044 /* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight])
1045    Get MX records corresponding to a given Internet host name */
PHP_FUNCTION(dns_get_mx)1046 PHP_FUNCTION(dns_get_mx)
1047 {
1048 	char *hostname;
1049 	size_t hostname_len;
1050 	zval *mx_list, *weight_list = NULL;
1051 	int count, qdc;
1052 	u_short type, weight;
1053 	querybuf answer;
1054 	char buf[MAXHOSTNAMELEN];
1055 	HEADER *hp;
1056 	u_char *cp, *end;
1057 	int i;
1058 #if defined(HAVE_DNS_SEARCH)
1059 	struct sockaddr_storage from;
1060 	uint32_t fromsize = sizeof(from);
1061 	dns_handle_t handle;
1062 #elif defined(HAVE_RES_NSEARCH)
1063 	struct __res_state state;
1064 	struct __res_state *handle = &state;
1065 #endif
1066 
1067 	ZEND_PARSE_PARAMETERS_START(2, 3)
1068 		Z_PARAM_STRING(hostname, hostname_len)
1069 		Z_PARAM_ZVAL(mx_list)
1070 		Z_PARAM_OPTIONAL
1071 		Z_PARAM_ZVAL(weight_list)
1072 	ZEND_PARSE_PARAMETERS_END();
1073 
1074 	mx_list = zend_try_array_init(mx_list);
1075 	if (!mx_list) {
1076 		return;
1077 	}
1078 
1079 	if (weight_list) {
1080 		weight_list = zend_try_array_init(weight_list);
1081 		if (!weight_list) {
1082 			return;
1083 		}
1084 	}
1085 
1086 #if defined(HAVE_DNS_SEARCH)
1087 	handle = dns_open(NULL);
1088 	if (handle == NULL) {
1089 		RETURN_FALSE;
1090 	}
1091 #elif defined(HAVE_RES_NSEARCH)
1092     memset(&state, 0, sizeof(state));
1093     if (res_ninit(handle)) {
1094 			RETURN_FALSE;
1095 	}
1096 #else
1097 	res_init();
1098 #endif
1099 
1100 	i = php_dns_search(handle, hostname, C_IN, DNS_T_MX, answer.qb2, sizeof answer);
1101 	if (i < 0) {
1102 		php_dns_free_handle(handle);
1103 		RETURN_FALSE;
1104 	}
1105 	hp = (HEADER *)&answer;
1106 	cp = answer.qb2 + HFIXEDSZ;
1107 	end = answer.qb2 + i;
1108 	for (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {
1109 		if ((i = dn_skipname(cp, end)) < 0 ) {
1110 			php_dns_free_handle(handle);
1111 			RETURN_FALSE;
1112 		}
1113 	}
1114 	count = ntohs((unsigned short)hp->ancount);
1115 	while (--count >= 0 && cp < end) {
1116 		if ((i = dn_skipname(cp, end)) < 0 ) {
1117 			php_dns_free_handle(handle);
1118 			RETURN_FALSE;
1119 		}
1120 		cp += i;
1121 		GETSHORT(type, cp);
1122 		cp += INT16SZ + INT32SZ;
1123 		GETSHORT(i, cp);
1124 		if (type != DNS_T_MX) {
1125 			cp += i;
1126 			continue;
1127 		}
1128 		GETSHORT(weight, cp);
1129 		if ((i = dn_expand(answer.qb2, end, cp, buf, sizeof(buf)-1)) < 0) {
1130 			php_dns_free_handle(handle);
1131 			RETURN_FALSE;
1132 		}
1133 		cp += i;
1134 		add_next_index_string(mx_list, buf);
1135 		if (weight_list) {
1136 			add_next_index_long(weight_list, weight);
1137 		}
1138 	}
1139 	php_dns_free_handle(handle);
1140 	RETURN_BOOL(zend_hash_num_elements(Z_ARRVAL_P(mx_list)) != 0);
1141 }
1142 /* }}} */
1143 #endif /* HAVE_FULL_DNS_FUNCS */
1144 #endif /* !defined(PHP_WIN32) && HAVE_DNS_SEARCH_FUNC */
1145 
1146 #if HAVE_FULL_DNS_FUNCS && !defined(PHP_WIN32)
PHP_MINIT_FUNCTION(dns)1147 PHP_MINIT_FUNCTION(dns) {
1148 	REGISTER_LONG_CONSTANT("DNS_A",     PHP_DNS_A,     CONST_CS | CONST_PERSISTENT);
1149 	REGISTER_LONG_CONSTANT("DNS_NS",    PHP_DNS_NS,    CONST_CS | CONST_PERSISTENT);
1150 	REGISTER_LONG_CONSTANT("DNS_CNAME", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT);
1151 	REGISTER_LONG_CONSTANT("DNS_SOA",   PHP_DNS_SOA,   CONST_CS | CONST_PERSISTENT);
1152 	REGISTER_LONG_CONSTANT("DNS_PTR",   PHP_DNS_PTR,   CONST_CS | CONST_PERSISTENT);
1153 	REGISTER_LONG_CONSTANT("DNS_HINFO", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT);
1154 	REGISTER_LONG_CONSTANT("DNS_CAA",   PHP_DNS_CAA,   CONST_CS | CONST_PERSISTENT);
1155 	REGISTER_LONG_CONSTANT("DNS_MX",    PHP_DNS_MX,    CONST_CS | CONST_PERSISTENT);
1156 	REGISTER_LONG_CONSTANT("DNS_TXT",   PHP_DNS_TXT,   CONST_CS | CONST_PERSISTENT);
1157 	REGISTER_LONG_CONSTANT("DNS_SRV",   PHP_DNS_SRV,   CONST_CS | CONST_PERSISTENT);
1158 	REGISTER_LONG_CONSTANT("DNS_NAPTR", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT);
1159 	REGISTER_LONG_CONSTANT("DNS_AAAA",  PHP_DNS_AAAA,  CONST_CS | CONST_PERSISTENT);
1160 	REGISTER_LONG_CONSTANT("DNS_A6",    PHP_DNS_A6,    CONST_CS | CONST_PERSISTENT);
1161 	REGISTER_LONG_CONSTANT("DNS_ANY",   PHP_DNS_ANY,   CONST_CS | CONST_PERSISTENT);
1162 	REGISTER_LONG_CONSTANT("DNS_ALL",   PHP_DNS_ALL,   CONST_CS | CONST_PERSISTENT);
1163 	return SUCCESS;
1164 }
1165 #endif /* HAVE_FULL_DNS_FUNCS */
1166