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