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