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_FUNCTIONnull125 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_FUNCTIONnull149 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_FUNCTIONnull211 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_FUNCTIONnull232 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_FUNCTIONnull363 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_FUNCTIONnull804 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 #if defined(HAVE_DNS_SEARCH)
812 	struct sockaddr_storage from;
813 	uint32_t fromsize = sizeof(from);
814 	dns_handle_t handle;
815 #elif defined(HAVE_RES_NSEARCH)
816 	struct __res_state state;
817 	struct __res_state *handle = &state;
818 #endif
819 	HEADER *hp;
820 	querybuf answer;
821 	u_char *cp = NULL, *end = NULL;
822 	int n, qd, an, ns = 0, ar = 0;
823 	int type, first_query = 1, store_results = 1;
824 	zend_bool raw = 0;
825 
826 	ZEND_PARSE_PARAMETERS_START(1, 5)
827 		Z_PARAM_STRING(hostname, hostname_len)
828 		Z_PARAM_OPTIONAL
829 		Z_PARAM_LONG(type_param)
830 		Z_PARAM_ZVAL(authns)
831 		Z_PARAM_ZVAL(addtl)
832 		Z_PARAM_BOOL(raw)
833 	ZEND_PARSE_PARAMETERS_END();
834 
835 	if (authns) {
836 		authns = zend_try_array_init(authns);
837 		if (!authns) {
838 			return;
839 		}
840 	}
841 	if (addtl) {
842 		addtl = zend_try_array_init(addtl);
843 		if (!addtl) {
844 			return;
845 		}
846 	}
847 
848 	if (!raw) {
849 		if ((type_param & ~PHP_DNS_ALL) && (type_param != PHP_DNS_ANY)) {
850 			php_error_docref(NULL, E_WARNING, "Type '" ZEND_LONG_FMT "' not supported", type_param);
851 			RETURN_FALSE;
852 		}
853 	} else {
854 		if ((type_param < 1) || (type_param > 0xFFFF)) {
855 			php_error_docref(NULL, E_WARNING,
856 				"Numeric DNS record type must be between 1 and 65535, '" ZEND_LONG_FMT "' given", type_param);
857 			RETURN_FALSE;
858 		}
859 	}
860 
861 	/* Initialize the return array */
862 	array_init(return_value);
863 
864 	/* - We emulate an or'ed type mask by querying type by type. (Steps 0 - NUMTYPES-1 )
865 	 *   If additional info is wanted we check again with DNS_T_ANY (step NUMTYPES / NUMTYPES+1 )
866 	 *   store_results is used to skip storing the results retrieved in step
867 	 *   NUMTYPES+1 when results were already fetched.
868 	 * - In case of PHP_DNS_ANY we use the directly fetch DNS_T_ANY. (step NUMTYPES+1 )
869 	 * - In case of raw mode, we query only the requestd type instead of looping type by type
870 	 *   before going with the additional info stuff.
871 	 */
872 
873 	if (raw) {
874 		type = -1;
875 	} else if (type_param == PHP_DNS_ANY) {
876 		type = PHP_DNS_NUM_TYPES + 1;
877 	} else {
878 		type = 0;
879 	}
880 
881 	for ( ;
882 		type < (addtl ? (PHP_DNS_NUM_TYPES + 2) : PHP_DNS_NUM_TYPES) || first_query;
883 		type++
884 	) {
885 		first_query = 0;
886 		switch (type) {
887 			case -1: /* raw */
888 				type_to_fetch = type_param;
889 				/* skip over the rest and go directly to additional records */
890 				type = PHP_DNS_NUM_TYPES - 1;
891 				break;
892 			case 0:
893 				type_to_fetch = type_param&PHP_DNS_A     ? DNS_T_A     : 0;
894 				break;
895 			case 1:
896 				type_to_fetch = type_param&PHP_DNS_NS    ? DNS_T_NS    : 0;
897 				break;
898 			case 2:
899 				type_to_fetch = type_param&PHP_DNS_CNAME ? DNS_T_CNAME : 0;
900 				break;
901 			case 3:
902 				type_to_fetch = type_param&PHP_DNS_SOA   ? DNS_T_SOA   : 0;
903 				break;
904 			case 4:
905 				type_to_fetch = type_param&PHP_DNS_PTR   ? DNS_T_PTR   : 0;
906 				break;
907 			case 5:
908 				type_to_fetch = type_param&PHP_DNS_HINFO ? DNS_T_HINFO : 0;
909 				break;
910 			case 6:
911 				type_to_fetch = type_param&PHP_DNS_MX    ? DNS_T_MX    : 0;
912 				break;
913 			case 7:
914 				type_to_fetch = type_param&PHP_DNS_TXT   ? DNS_T_TXT   : 0;
915 				break;
916 			case 8:
917 				type_to_fetch = type_param&PHP_DNS_AAAA	 ? DNS_T_AAAA  : 0;
918 				break;
919 			case 9:
920 				type_to_fetch = type_param&PHP_DNS_SRV   ? DNS_T_SRV   : 0;
921 				break;
922 			case 10:
923 				type_to_fetch = type_param&PHP_DNS_NAPTR ? DNS_T_NAPTR : 0;
924 				break;
925 			case 11:
926 				type_to_fetch = type_param&PHP_DNS_A6	 ? DNS_T_A6 : 0;
927 				break;
928 			case 12:
929 				type_to_fetch = type_param&PHP_DNS_CAA ? DNS_T_CAA : 0;
930 				break;
931 			case PHP_DNS_NUM_TYPES:
932 				store_results = 0;
933 				continue;
934 			default:
935 			case (PHP_DNS_NUM_TYPES + 1):
936 				type_to_fetch = DNS_T_ANY;
937 				break;
938 		}
939 
940 		if (type_to_fetch) {
941 #if defined(HAVE_DNS_SEARCH)
942 			handle = dns_open(NULL);
943 			if (handle == NULL) {
944 				zend_array_destroy(Z_ARR_P(return_value));
945 				RETURN_FALSE;
946 			}
947 #elif defined(HAVE_RES_NSEARCH)
948 		    memset(&state, 0, sizeof(state));
949 		    if (res_ninit(handle)) {
950 		    	zend_array_destroy(Z_ARR_P(return_value));
951 				RETURN_FALSE;
952 			}
953 #else
954 			res_init();
955 #endif
956 
957 			n = php_dns_search(handle, hostname, C_IN, type_to_fetch, answer.qb2, sizeof answer);
958 
959 			if (n < 0) {
960 				php_dns_free_handle(handle);
961 				switch (h_errno) {
962 					case NO_DATA:
963 					case HOST_NOT_FOUND:
964 						continue;
965 
966 					case NO_RECOVERY:
967 						php_error_docref(NULL, E_WARNING, "An unexpected server failure occurred.");
968 						break;
969 
970 					case TRY_AGAIN:
971 						php_error_docref(NULL, E_WARNING, "A temporary server error occurred.");
972 						break;
973 
974 					default:
975 						php_error_docref(NULL, E_WARNING, "DNS Query failed");
976 				}
977 				zend_array_destroy(Z_ARR_P(return_value));
978 				RETURN_FALSE;
979 			}
980 
981 			cp = answer.qb2 + HFIXEDSZ;
982 			end = answer.qb2 + n;
983 			hp = (HEADER *)&answer;
984 			qd = ntohs(hp->qdcount);
985 			an = ntohs(hp->ancount);
986 			ns = ntohs(hp->nscount);
987 			ar = ntohs(hp->arcount);
988 
989 			/* Skip QD entries, they're only used by dn_expand later on */
990 			while (qd-- > 0) {
991 				n = dn_skipname(cp, end);
992 				if (n < 0) {
993 					php_error_docref(NULL, E_WARNING, "Unable to parse DNS data received");
994 					zend_array_destroy(Z_ARR_P(return_value));
995 					php_dns_free_handle(handle);
996 					RETURN_FALSE;
997 				}
998 				cp += n + QFIXEDSZ;
999 			}
1000 
1001 			/* YAY! Our real answers! */
1002 			while (an-- && cp && cp < end) {
1003 				zval retval;
1004 
1005 				cp = php_parserr(cp, end, &answer, type_to_fetch, store_results, raw, &retval);
1006 				if (Z_TYPE(retval) != IS_UNDEF && store_results) {
1007 					add_next_index_zval(return_value, &retval);
1008 				}
1009 			}
1010 
1011 			if (authns || addtl) {
1012 				/* List of Authoritative Name Servers
1013 				 * Process when only requesting addtl so that we can skip through the section
1014 				 */
1015 				while (ns-- > 0 && cp && cp < end) {
1016 					zval retval;
1017 
1018 					cp = php_parserr(cp, end, &answer, DNS_T_ANY, authns != NULL, raw, &retval);
1019 					if (Z_TYPE(retval) != IS_UNDEF) {
1020 						add_next_index_zval(authns, &retval);
1021 					}
1022 				}
1023 			}
1024 
1025 			if (addtl) {
1026 				/* Additional records associated with authoritative name servers */
1027 				while (ar-- > 0 && cp && cp < end) {
1028 					zval retval;
1029 
1030 					cp = php_parserr(cp, end, &answer, DNS_T_ANY, 1, raw, &retval);
1031 					if (Z_TYPE(retval) != IS_UNDEF) {
1032 						add_next_index_zval(addtl, &retval);
1033 					}
1034 				}
1035 			}
1036 			php_dns_free_handle(handle);
1037 		}
1038 	}
1039 }
1040 /* }}} */
1041 
1042 /* {{{ proto bool dns_get_mx(string hostname, array mxhosts [, array weight])
1043    Get MX records corresponding to a given Internet host name */
PHP_FUNCTIONnull1044 PHP_FUNCTION(dns_get_mx)
1045 {
1046 	char *hostname;
1047 	size_t hostname_len;
1048 	zval *mx_list, *weight_list = NULL;
1049 	int count, qdc;
1050 	u_short type, weight;
1051 	querybuf answer;
1052 	char buf[MAXHOSTNAMELEN];
1053 	HEADER *hp;
1054 	u_char *cp, *end;
1055 	int i;
1056 #if defined(HAVE_DNS_SEARCH)
1057 	struct sockaddr_storage from;
1058 	uint32_t fromsize = sizeof(from);
1059 	dns_handle_t handle;
1060 #elif defined(HAVE_RES_NSEARCH)
1061 	struct __res_state state;
1062 	struct __res_state *handle = &state;
1063 #endif
1064 
1065 	ZEND_PARSE_PARAMETERS_START(2, 3)
1066 		Z_PARAM_STRING(hostname, hostname_len)
1067 		Z_PARAM_ZVAL(mx_list)
1068 		Z_PARAM_OPTIONAL
1069 		Z_PARAM_ZVAL(weight_list)
1070 	ZEND_PARSE_PARAMETERS_END();
1071 
1072 	mx_list = zend_try_array_init(mx_list);
1073 	if (!mx_list) {
1074 		return;
1075 	}
1076 
1077 	if (weight_list) {
1078 		weight_list = zend_try_array_init(weight_list);
1079 		if (!weight_list) {
1080 			return;
1081 		}
1082 	}
1083 
1084 #if defined(HAVE_DNS_SEARCH)
1085 	handle = dns_open(NULL);
1086 	if (handle == NULL) {
1087 		RETURN_FALSE;
1088 	}
1089 #elif defined(HAVE_RES_NSEARCH)
1090     memset(&state, 0, sizeof(state));
1091     if (res_ninit(handle)) {
1092 			RETURN_FALSE;
1093 	}
1094 #else
1095 	res_init();
1096 #endif
1097 
1098 	i = php_dns_search(handle, hostname, C_IN, DNS_T_MX, answer.qb2, sizeof answer);
1099 	if (i < 0) {
1100 		php_dns_free_handle(handle);
1101 		RETURN_FALSE;
1102 	}
1103 	hp = (HEADER *)&answer;
1104 	cp = answer.qb2 + HFIXEDSZ;
1105 	end = answer.qb2 + i;
1106 	for (qdc = ntohs((unsigned short)hp->qdcount); qdc--; cp += i + QFIXEDSZ) {
1107 		if ((i = dn_skipname(cp, end)) < 0 ) {
1108 			php_dns_free_handle(handle);
1109 			RETURN_FALSE;
1110 		}
1111 	}
1112 	count = ntohs((unsigned short)hp->ancount);
1113 	while (--count >= 0 && cp < end) {
1114 		if ((i = dn_skipname(cp, end)) < 0 ) {
1115 			php_dns_free_handle(handle);
1116 			RETURN_FALSE;
1117 		}
1118 		cp += i;
1119 		GETSHORT(type, cp);
1120 		cp += INT16SZ + INT32SZ;
1121 		GETSHORT(i, cp);
1122 		if (type != DNS_T_MX) {
1123 			cp += i;
1124 			continue;
1125 		}
1126 		GETSHORT(weight, cp);
1127 		if ((i = dn_expand(answer.qb2, end, cp, buf, sizeof(buf)-1)) < 0) {
1128 			php_dns_free_handle(handle);
1129 			RETURN_FALSE;
1130 		}
1131 		cp += i;
1132 		add_next_index_string(mx_list, buf);
1133 		if (weight_list) {
1134 			add_next_index_long(weight_list, weight);
1135 		}
1136 	}
1137 	php_dns_free_handle(handle);
1138 	RETURN_BOOL(zend_hash_num_elements(Z_ARRVAL_P(mx_list)) != 0);
1139 }
1140 /* }}} */
1141 #endif /* HAVE_FULL_DNS_FUNCS */
1142 #endif /* !defined(PHP_WIN32) && HAVE_DNS_SEARCH_FUNC */
1143 
1144 #if HAVE_FULL_DNS_FUNCS && !defined(PHP_WIN32)
PHP_MINIT_FUNCTIONnull1145 PHP_MINIT_FUNCTION(dns) {
1146 	REGISTER_LONG_CONSTANT("DNS_A",     PHP_DNS_A,     CONST_CS | CONST_PERSISTENT);
1147 	REGISTER_LONG_CONSTANT("DNS_NS",    PHP_DNS_NS,    CONST_CS | CONST_PERSISTENT);
1148 	REGISTER_LONG_CONSTANT("DNS_CNAME", PHP_DNS_CNAME, CONST_CS | CONST_PERSISTENT);
1149 	REGISTER_LONG_CONSTANT("DNS_SOA",   PHP_DNS_SOA,   CONST_CS | CONST_PERSISTENT);
1150 	REGISTER_LONG_CONSTANT("DNS_PTR",   PHP_DNS_PTR,   CONST_CS | CONST_PERSISTENT);
1151 	REGISTER_LONG_CONSTANT("DNS_HINFO", PHP_DNS_HINFO, CONST_CS | CONST_PERSISTENT);
1152 	REGISTER_LONG_CONSTANT("DNS_CAA",   PHP_DNS_CAA,   CONST_CS | CONST_PERSISTENT);
1153 	REGISTER_LONG_CONSTANT("DNS_MX",    PHP_DNS_MX,    CONST_CS | CONST_PERSISTENT);
1154 	REGISTER_LONG_CONSTANT("DNS_TXT",   PHP_DNS_TXT,   CONST_CS | CONST_PERSISTENT);
1155 	REGISTER_LONG_CONSTANT("DNS_SRV",   PHP_DNS_SRV,   CONST_CS | CONST_PERSISTENT);
1156 	REGISTER_LONG_CONSTANT("DNS_NAPTR", PHP_DNS_NAPTR, CONST_CS | CONST_PERSISTENT);
1157 	REGISTER_LONG_CONSTANT("DNS_AAAA",  PHP_DNS_AAAA,  CONST_CS | CONST_PERSISTENT);
1158 	REGISTER_LONG_CONSTANT("DNS_A6",    PHP_DNS_A6,    CONST_CS | CONST_PERSISTENT);
1159 	REGISTER_LONG_CONSTANT("DNS_ANY",   PHP_DNS_ANY,   CONST_CS | CONST_PERSISTENT);
1160 	REGISTER_LONG_CONSTANT("DNS_ALL",   PHP_DNS_ALL,   CONST_CS | CONST_PERSISTENT);
1161 	return SUCCESS;
1162 }
1163 #endif /* HAVE_FULL_DNS_FUNCS */
1164