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