1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 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: Amitay Isaacs  <amitay@w-o-i.com>                           |
16   |          Eric Warnke    <ericw@albany.edu>                           |
17   |          Rasmus Lerdorf <rasmus@php.net>                             |
18   |          Gerrit Thomson <334647@swin.edu.au>                         |
19   |          Jani Taskinen  <sniper@iki.fi>                              |
20   |          Stig Venaas    <venaas@uninett.no>                          |
21   |          Doug Goldstein <cardoe@cardoe.com>                          |
22   | PHP 4.0 updates:  Zeev Suraski <zeev@zend.com>                       |
23   +----------------------------------------------------------------------+
24 */
25
26/* $Id: 6ad3a936005748c5207fdf0c2a59a65d066cc0f9 $ */
27#define IS_EXT_MODULE
28
29#ifdef HAVE_CONFIG_H
30#include "config.h"
31#endif
32
33/* Additional headers for NetWare */
34#if defined(NETWARE) && (NEW_LIBC)
35#include <sys/select.h>
36#include <sys/timeval.h>
37#endif
38
39#include "php.h"
40#include "php_ini.h"
41
42#include <stddef.h>
43
44#include "ext/standard/dl.h"
45#include "php_ldap.h"
46
47#ifdef PHP_WIN32
48#include <string.h>
49#include "config.w32.h"
50#if HAVE_NSLDAP
51#include <winsock2.h>
52#endif
53#define strdup _strdup
54#undef WINDOWS
55#undef strcasecmp
56#undef strncasecmp
57#define WINSOCK 1
58#define __STDC__ 1
59#endif
60
61#include "ext/standard/php_string.h"
62#include "ext/standard/info.h"
63
64#ifdef HAVE_LDAP_SASL_H
65#include <sasl.h>
66#elif defined(HAVE_LDAP_SASL_SASL_H)
67#include <sasl/sasl.h>
68#endif
69
70#define PHP_LDAP_ESCAPE_FILTER 0x01
71#define PHP_LDAP_ESCAPE_DN     0x02
72
73typedef struct {
74    LDAP *link;
75#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
76    zval rebindproc;
77#endif
78} ldap_linkdata;
79
80typedef struct {
81    LDAPMessage *data;
82    BerElement  *ber;
83    zval         res;
84} ldap_resultentry;
85
86ZEND_DECLARE_MODULE_GLOBALS(ldap)
87static PHP_GINIT_FUNCTION(ldap);
88
89static int le_link, le_result, le_result_entry;
90
91#ifdef COMPILE_DL_LDAP
92ZEND_GET_MODULE(ldap)
93#endif
94
95static void _close_ldap_link(zend_resource *rsrc) /* {{{ */
96{
97    ldap_linkdata *ld = (ldap_linkdata *)rsrc->ptr;
98
99    ldap_unbind_s(ld->link);
100#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
101    zval_ptr_dtor(&ld->rebindproc);
102#endif
103    efree(ld);
104    LDAPG(num_links)--;
105}
106/* }}} */
107
108static void _free_ldap_result(zend_resource *rsrc) /* {{{ */
109{
110    LDAPMessage *result = (LDAPMessage *)rsrc->ptr;
111    ldap_msgfree(result);
112}
113/* }}} */
114
115static void _free_ldap_result_entry(zend_resource *rsrc) /* {{{ */
116{
117    ldap_resultentry *entry = (ldap_resultentry *)rsrc->ptr;
118
119    if (entry->ber != NULL) {
120        ber_free(entry->ber, 0);
121        entry->ber = NULL;
122    }
123    zval_ptr_dtor(&entry->res);
124    efree(entry);
125}
126/* }}} */
127
128/* {{{ PHP_INI_BEGIN
129 */
130PHP_INI_BEGIN()
131    STD_PHP_INI_ENTRY_EX("ldap.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_ldap_globals, ldap_globals, display_link_numbers)
132PHP_INI_END()
133/* }}} */
134
135/* {{{ PHP_GINIT_FUNCTION
136 */
137static PHP_GINIT_FUNCTION(ldap)
138{
139    ldap_globals->num_links = 0;
140}
141/* }}} */
142
143/* {{{ PHP_MINIT_FUNCTION
144 */
145PHP_MINIT_FUNCTION(ldap)
146{
147    REGISTER_INI_ENTRIES();
148
149    /* Constants to be used with deref-parameter in php_ldap_do_search() */
150    REGISTER_LONG_CONSTANT("LDAP_DEREF_NEVER", LDAP_DEREF_NEVER, CONST_PERSISTENT | CONST_CS);
151    REGISTER_LONG_CONSTANT("LDAP_DEREF_SEARCHING", LDAP_DEREF_SEARCHING, CONST_PERSISTENT | CONST_CS);
152    REGISTER_LONG_CONSTANT("LDAP_DEREF_FINDING", LDAP_DEREF_FINDING, CONST_PERSISTENT | CONST_CS);
153    REGISTER_LONG_CONSTANT("LDAP_DEREF_ALWAYS", LDAP_DEREF_ALWAYS, CONST_PERSISTENT | CONST_CS);
154
155    /* Constants to be used with ldap_modify_batch() */
156    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_ADD", LDAP_MODIFY_BATCH_ADD, CONST_PERSISTENT | CONST_CS);
157    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE", LDAP_MODIFY_BATCH_REMOVE, CONST_PERSISTENT | CONST_CS);
158    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE_ALL", LDAP_MODIFY_BATCH_REMOVE_ALL, CONST_PERSISTENT | CONST_CS);
159    REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REPLACE", LDAP_MODIFY_BATCH_REPLACE, CONST_PERSISTENT | CONST_CS);
160    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_ATTRIB", LDAP_MODIFY_BATCH_ATTRIB, CONST_PERSISTENT | CONST_CS);
161    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_MODTYPE", LDAP_MODIFY_BATCH_MODTYPE, CONST_PERSISTENT | CONST_CS);
162    REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_VALUES", LDAP_MODIFY_BATCH_VALUES, CONST_PERSISTENT | CONST_CS);
163
164#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
165    /* LDAP options */
166    REGISTER_LONG_CONSTANT("LDAP_OPT_DEREF", LDAP_OPT_DEREF, CONST_PERSISTENT | CONST_CS);
167    REGISTER_LONG_CONSTANT("LDAP_OPT_SIZELIMIT", LDAP_OPT_SIZELIMIT, CONST_PERSISTENT | CONST_CS);
168    REGISTER_LONG_CONSTANT("LDAP_OPT_TIMELIMIT", LDAP_OPT_TIMELIMIT, CONST_PERSISTENT | CONST_CS);
169#ifdef LDAP_OPT_NETWORK_TIMEOUT
170    REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_OPT_NETWORK_TIMEOUT, CONST_PERSISTENT | CONST_CS);
171#elif defined (LDAP_X_OPT_CONNECT_TIMEOUT)
172    REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_X_OPT_CONNECT_TIMEOUT, CONST_PERSISTENT | CONST_CS);
173#endif
174    REGISTER_LONG_CONSTANT("LDAP_OPT_PROTOCOL_VERSION", LDAP_OPT_PROTOCOL_VERSION, CONST_PERSISTENT | CONST_CS);
175    REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_NUMBER", LDAP_OPT_ERROR_NUMBER, CONST_PERSISTENT | CONST_CS);
176    REGISTER_LONG_CONSTANT("LDAP_OPT_REFERRALS", LDAP_OPT_REFERRALS, CONST_PERSISTENT | CONST_CS);
177#ifdef LDAP_OPT_RESTART
178    REGISTER_LONG_CONSTANT("LDAP_OPT_RESTART", LDAP_OPT_RESTART, CONST_PERSISTENT | CONST_CS);
179#endif
180#ifdef LDAP_OPT_HOST_NAME
181    REGISTER_LONG_CONSTANT("LDAP_OPT_HOST_NAME", LDAP_OPT_HOST_NAME, CONST_PERSISTENT | CONST_CS);
182#endif
183    REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_STRING", LDAP_OPT_ERROR_STRING, CONST_PERSISTENT | CONST_CS);
184#ifdef LDAP_OPT_MATCHED_DN
185    REGISTER_LONG_CONSTANT("LDAP_OPT_MATCHED_DN", LDAP_OPT_MATCHED_DN, CONST_PERSISTENT | CONST_CS);
186#endif
187    REGISTER_LONG_CONSTANT("LDAP_OPT_SERVER_CONTROLS", LDAP_OPT_SERVER_CONTROLS, CONST_PERSISTENT | CONST_CS);
188    REGISTER_LONG_CONSTANT("LDAP_OPT_CLIENT_CONTROLS", LDAP_OPT_CLIENT_CONTROLS, CONST_PERSISTENT | CONST_CS);
189#endif
190#ifdef LDAP_OPT_DEBUG_LEVEL
191    REGISTER_LONG_CONSTANT("LDAP_OPT_DEBUG_LEVEL", LDAP_OPT_DEBUG_LEVEL, CONST_PERSISTENT | CONST_CS);
192#endif
193
194#ifdef HAVE_LDAP_SASL
195    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_MECH", LDAP_OPT_X_SASL_MECH, CONST_PERSISTENT | CONST_CS);
196    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_REALM", LDAP_OPT_X_SASL_REALM, CONST_PERSISTENT | CONST_CS);
197    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHCID", LDAP_OPT_X_SASL_AUTHCID, CONST_PERSISTENT | CONST_CS);
198    REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHZID", LDAP_OPT_X_SASL_AUTHZID, CONST_PERSISTENT | CONST_CS);
199#endif
200
201#ifdef ORALDAP
202    REGISTER_LONG_CONSTANT("GSLC_SSL_NO_AUTH", GSLC_SSL_NO_AUTH, CONST_PERSISTENT | CONST_CS);
203    REGISTER_LONG_CONSTANT("GSLC_SSL_ONEWAY_AUTH", GSLC_SSL_ONEWAY_AUTH, CONST_PERSISTENT | CONST_CS);
204    REGISTER_LONG_CONSTANT("GSLC_SSL_TWOWAY_AUTH", GSLC_SSL_TWOWAY_AUTH, CONST_PERSISTENT | CONST_CS);
205#endif
206
207    REGISTER_LONG_CONSTANT("LDAP_ESCAPE_FILTER", PHP_LDAP_ESCAPE_FILTER, CONST_PERSISTENT | CONST_CS);
208    REGISTER_LONG_CONSTANT("LDAP_ESCAPE_DN", PHP_LDAP_ESCAPE_DN, CONST_PERSISTENT | CONST_CS);
209
210    le_link = zend_register_list_destructors_ex(_close_ldap_link, NULL, "ldap link", module_number);
211    le_result = zend_register_list_destructors_ex(_free_ldap_result, NULL, "ldap result", module_number);
212    le_result_entry = zend_register_list_destructors_ex(_free_ldap_result_entry, NULL, "ldap result entry", module_number);
213
214    ldap_module_entry.type = type;
215
216    return SUCCESS;
217}
218/* }}} */
219
220/* {{{ PHP_MSHUTDOWN_FUNCTION
221 */
222PHP_MSHUTDOWN_FUNCTION(ldap)
223{
224    UNREGISTER_INI_ENTRIES();
225    return SUCCESS;
226}
227/* }}} */
228
229/* {{{ PHP_MINFO_FUNCTION
230 */
231PHP_MINFO_FUNCTION(ldap)
232{
233    char tmp[32];
234#if HAVE_NSLDAP
235    LDAPVersion ver;
236    double SDKVersion;
237#endif
238
239    php_info_print_table_start();
240    php_info_print_table_row(2, "LDAP Support", "enabled");
241    php_info_print_table_row(2, "RCS Version", "$Id: 6ad3a936005748c5207fdf0c2a59a65d066cc0f9 $");
242
243    if (LDAPG(max_links) == -1) {
244        snprintf(tmp, 31, ZEND_LONG_FMT "/unlimited", LDAPG(num_links));
245    } else {
246        snprintf(tmp, 31, ZEND_LONG_FMT "/" ZEND_LONG_FMT, LDAPG(num_links), LDAPG(max_links));
247    }
248    php_info_print_table_row(2, "Total Links", tmp);
249
250#ifdef LDAP_API_VERSION
251    snprintf(tmp, 31, "%d", LDAP_API_VERSION);
252    php_info_print_table_row(2, "API Version", tmp);
253#endif
254
255#ifdef LDAP_VENDOR_NAME
256    php_info_print_table_row(2, "Vendor Name", LDAP_VENDOR_NAME);
257#endif
258
259#ifdef LDAP_VENDOR_VERSION
260    snprintf(tmp, 31, "%d", LDAP_VENDOR_VERSION);
261    php_info_print_table_row(2, "Vendor Version", tmp);
262#endif
263
264#if HAVE_NSLDAP
265    SDKVersion = ldap_version(&ver);
266    snprintf(tmp, 31, "%F", SDKVersion/100.0);
267    php_info_print_table_row(2, "SDK Version", tmp);
268
269    snprintf(tmp, 31, "%F", ver.protocol_version/100.0);
270    php_info_print_table_row(2, "Highest LDAP Protocol Supported", tmp);
271
272    snprintf(tmp, 31, "%F", ver.SSL_version/100.0);
273    php_info_print_table_row(2, "SSL Level Supported", tmp);
274
275    if (ver.security_level != LDAP_SECURITY_NONE) {
276        snprintf(tmp, 31, "%d", ver.security_level);
277    } else {
278        strcpy(tmp, "SSL not enabled");
279    }
280    php_info_print_table_row(2, "Level of Encryption", tmp);
281#endif
282
283#ifdef HAVE_LDAP_SASL
284    php_info_print_table_row(2, "SASL Support", "Enabled");
285#endif
286
287    php_info_print_table_end();
288    DISPLAY_INI_ENTRIES();
289}
290/* }}} */
291
292/* {{{ proto resource ldap_connect([string host [, int port [, string wallet [, string wallet_passwd [, int authmode]]]]])
293   Connect to an LDAP server */
294PHP_FUNCTION(ldap_connect)
295{
296    char *host = NULL;
297    size_t hostlen;
298    zend_long port = 389; /* Default port */
299#ifdef HAVE_ORALDAP
300    char *wallet = NULL, *walletpasswd = NULL;
301    size_t walletlen = 0, walletpasswdlen = 0;
302    zend_long authmode = GSLC_SSL_NO_AUTH;
303    int ssl=0;
304#endif
305    ldap_linkdata *ld;
306    LDAP *ldap;
307
308#ifdef HAVE_ORALDAP
309    if (ZEND_NUM_ARGS() == 3 || ZEND_NUM_ARGS() == 4) {
310        WRONG_PARAM_COUNT;
311    }
312
313    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|slssl", &host, &hostlen, &port, &wallet, &walletlen, &walletpasswd, &walletpasswdlen, &authmode) != SUCCESS) {
314        RETURN_FALSE;
315    }
316
317    if (ZEND_NUM_ARGS() == 5) {
318        ssl = 1;
319    }
320#else
321    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|sl", &host, &hostlen, &port) != SUCCESS) {
322        RETURN_FALSE;
323    }
324#endif
325
326    if (LDAPG(max_links) != -1 && LDAPG(num_links) >= LDAPG(max_links)) {
327        php_error_docref(NULL, E_WARNING, "Too many open links (%pd)", LDAPG(num_links));
328        RETURN_FALSE;
329    }
330
331    ld = ecalloc(1, sizeof(ldap_linkdata));
332
333#ifdef LDAP_API_FEATURE_X_OPENLDAP
334    if (host != NULL && strchr(host, '/')) {
335        int rc;
336
337        rc = ldap_initialize(&ldap, host);
338        if (rc != LDAP_SUCCESS) {
339            efree(ld);
340            php_error_docref(NULL, E_WARNING, "Could not create session handle: %s", ldap_err2string(rc));
341            RETURN_FALSE;
342        }
343    } else {
344        ldap = ldap_init(host, port);
345    }
346#else
347    ldap = ldap_open(host, port);
348#endif
349
350    if (ldap == NULL) {
351        efree(ld);
352        RETURN_FALSE;
353    } else {
354#ifdef HAVE_ORALDAP
355        if (ssl) {
356            if (ldap_init_SSL(&ldap->ld_sb, wallet, walletpasswd, authmode)) {
357                efree(ld);
358                php_error_docref(NULL, E_WARNING, "SSL init failed");
359                RETURN_FALSE;
360            }
361        }
362#endif
363        LDAPG(num_links)++;
364        ld->link = ldap;
365        RETURN_RES(zend_register_resource(ld, le_link));
366    }
367
368}
369/* }}} */
370
371/* {{{ _get_lderrno
372 */
373static int _get_lderrno(LDAP *ldap)
374{
375#if !HAVE_NSLDAP
376#if LDAP_API_VERSION > 2000 || HAVE_ORALDAP
377    int lderr;
378
379    /* New versions of OpenLDAP do it this way */
380    ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
381    return lderr;
382#else
383    return ldap->ld_errno;
384#endif
385#else
386    return ldap_get_lderrno(ldap, NULL, NULL);
387#endif
388}
389/* }}} */
390
391/* {{{ _set_lderrno
392 */
393static void _set_lderrno(LDAP *ldap, int lderr)
394{
395#if !HAVE_NSLDAP
396#if LDAP_API_VERSION > 2000 || HAVE_ORALDAP
397    /* New versions of OpenLDAP do it this way */
398    ldap_set_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
399#else
400    ldap->ld_errno = lderr;
401#endif
402#else
403    ldap_set_lderrno(ldap, lderr, NULL, NULL);
404#endif
405}
406/* }}} */
407
408/* {{{ proto bool ldap_bind(resource link [, string dn [, string password]])
409   Bind to LDAP directory */
410PHP_FUNCTION(ldap_bind)
411{
412    zval *link;
413    char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
414    size_t ldap_bind_dnlen, ldap_bind_pwlen;
415    ldap_linkdata *ld;
416    int rc;
417
418    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|ss", &link, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen) != SUCCESS) {
419        RETURN_FALSE;
420    }
421
422    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
423        RETURN_FALSE;
424    }
425
426    if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
427        _set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
428        php_error_docref(NULL, E_WARNING, "DN contains a null byte");
429        RETURN_FALSE;
430    }
431
432    if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
433        _set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
434        php_error_docref(NULL, E_WARNING, "Password contains a null byte");
435        RETURN_FALSE;
436    }
437
438    if ((rc = ldap_bind_s(ld->link, ldap_bind_dn, ldap_bind_pw, LDAP_AUTH_SIMPLE)) != LDAP_SUCCESS) {
439        php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
440        RETURN_FALSE;
441    } else {
442        RETURN_TRUE;
443    }
444}
445/* }}} */
446
447#ifdef HAVE_LDAP_SASL
448typedef struct {
449    char *mech;
450    char *realm;
451    char *authcid;
452    char *passwd;
453    char *authzid;
454} php_ldap_bictx;
455
456/* {{{ _php_sasl_setdefs
457 */
458static php_ldap_bictx *_php_sasl_setdefs(LDAP *ld, char *sasl_mech, char *sasl_realm, char *sasl_authc_id, char *passwd, char *sasl_authz_id)
459{
460    php_ldap_bictx *ctx;
461
462    ctx = ber_memalloc(sizeof(php_ldap_bictx));
463    ctx->mech    = (sasl_mech) ? ber_strdup(sasl_mech) : NULL;
464    ctx->realm   = (sasl_realm) ? ber_strdup(sasl_realm) : NULL;
465    ctx->authcid = (sasl_authc_id) ? ber_strdup(sasl_authc_id) : NULL;
466    ctx->passwd  = (passwd) ? ber_strdup(passwd) : NULL;
467    ctx->authzid = (sasl_authz_id) ? ber_strdup(sasl_authz_id) : NULL;
468
469    if (ctx->mech == NULL) {
470        ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &ctx->mech);
471    }
472    if (ctx->realm == NULL) {
473        ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &ctx->realm);
474    }
475    if (ctx->authcid == NULL) {
476        ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &ctx->authcid);
477    }
478    if (ctx->authzid == NULL) {
479        ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &ctx->authzid);
480    }
481
482    return ctx;
483}
484/* }}} */
485
486/* {{{ _php_sasl_freedefs
487 */
488static void _php_sasl_freedefs(php_ldap_bictx *ctx)
489{
490    if (ctx->mech) ber_memfree(ctx->mech);
491    if (ctx->realm) ber_memfree(ctx->realm);
492    if (ctx->authcid) ber_memfree(ctx->authcid);
493    if (ctx->passwd) ber_memfree(ctx->passwd);
494    if (ctx->authzid) ber_memfree(ctx->authzid);
495    ber_memfree(ctx);
496}
497/* }}} */
498
499/* {{{ _php_sasl_interact
500   Internal interact function for SASL */
501static int _php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)
502{
503    sasl_interact_t *interact = in;
504    const char *p;
505    php_ldap_bictx *ctx = defaults;
506
507    for (;interact->id != SASL_CB_LIST_END;interact++) {
508        p = NULL;
509        switch(interact->id) {
510            case SASL_CB_GETREALM:
511                p = ctx->realm;
512                break;
513            case SASL_CB_AUTHNAME:
514                p = ctx->authcid;
515                break;
516            case SASL_CB_USER:
517                p = ctx->authzid;
518                break;
519            case SASL_CB_PASS:
520                p = ctx->passwd;
521                break;
522        }
523        if (p) {
524            interact->result = p;
525            interact->len = strlen(interact->result);
526        }
527    }
528    return LDAP_SUCCESS;
529}
530/* }}} */
531
532/* {{{ proto bool ldap_sasl_bind(resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authc_id [, string sasl_authz_id [, string props]]]]]]])
533   Bind to LDAP directory using SASL */
534PHP_FUNCTION(ldap_sasl_bind)
535{
536    zval *link;
537    ldap_linkdata *ld;
538    char *binddn = NULL;
539    char *passwd = NULL;
540    char *sasl_mech = NULL;
541    char *sasl_realm = NULL;
542    char *sasl_authz_id = NULL;
543    char *sasl_authc_id = NULL;
544    char *props = NULL;
545    size_t rc, dn_len, passwd_len, mech_len, realm_len, authc_id_len, authz_id_len, props_len;
546    php_ldap_bictx *ctx;
547
548    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|sssssss", &link, &binddn, &dn_len, &passwd, &passwd_len, &sasl_mech, &mech_len, &sasl_realm, &realm_len, &sasl_authc_id, &authc_id_len, &sasl_authz_id, &authz_id_len, &props, &props_len) != SUCCESS) {
549        RETURN_FALSE;
550    }
551
552    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
553        RETURN_FALSE;
554    }
555
556    ctx = _php_sasl_setdefs(ld->link, sasl_mech, sasl_realm, sasl_authc_id, passwd, sasl_authz_id);
557
558    if (props) {
559        ldap_set_option(ld->link, LDAP_OPT_X_SASL_SECPROPS, props);
560    }
561
562    rc = ldap_sasl_interactive_bind_s(ld->link, binddn, ctx->mech, NULL, NULL, LDAP_SASL_QUIET, _php_sasl_interact, ctx);
563    if (rc != LDAP_SUCCESS) {
564        php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
565        RETVAL_FALSE;
566    } else {
567        RETVAL_TRUE;
568    }
569    _php_sasl_freedefs(ctx);
570}
571/* }}} */
572#endif /* HAVE_LDAP_SASL */
573
574/* {{{ proto bool ldap_unbind(resource link)
575   Unbind from LDAP directory */
576PHP_FUNCTION(ldap_unbind)
577{
578    zval *link;
579    ldap_linkdata *ld;
580
581    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
582        RETURN_FALSE;
583    }
584
585    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
586        RETURN_FALSE;
587    }
588
589    zend_list_close(Z_RES_P(link));
590    RETURN_TRUE;
591}
592/* }}} */
593
594/* {{{ php_set_opts
595 */
596static void php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref)
597{
598    /* sizelimit */
599    if (sizelimit > -1) {
600#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
601        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_sizelimit);
602        ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit);
603#else
604        *old_sizelimit = ldap->ld_sizelimit;
605        ldap->ld_sizelimit = sizelimit;
606#endif
607    }
608
609    /* timelimit */
610    if (timelimit > -1) {
611#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
612        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_timelimit);
613        ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &timelimit);
614#else
615        *old_timelimit = ldap->ld_timelimit;
616        ldap->ld_timelimit = timelimit;
617#endif
618    }
619
620    /* deref */
621    if (deref > -1) {
622#if (LDAP_API_VERSION >= 2004) || HAVE_NSLDAP || HAVE_ORALDAP
623        ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_deref);
624        ldap_set_option(ldap, LDAP_OPT_DEREF, &deref);
625#else
626        *old_deref = ldap->ld_deref;
627        ldap->ld_deref = deref;
628#endif
629    }
630}
631/* }}} */
632
633/* {{{ php_ldap_do_search
634 */
635static void php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope)
636{
637    zval *link, *base_dn, *filter, *attrs = NULL, *attr;
638    zend_long attrsonly, sizelimit, timelimit, deref;
639    char *ldap_base_dn = NULL, *ldap_filter = NULL, **ldap_attrs = NULL;
640    ldap_linkdata *ld = NULL;
641    LDAPMessage *ldap_res;
642    int ldap_attrsonly = 0, ldap_sizelimit = -1, ldap_timelimit = -1, ldap_deref = -1;
643    int old_ldap_sizelimit = -1, old_ldap_timelimit = -1, old_ldap_deref = -1;
644    int num_attribs = 0, ret = 1, i, errno, argcount = ZEND_NUM_ARGS();
645
646    if (zend_parse_parameters(argcount, "zzz|allll", &link, &base_dn, &filter, &attrs, &attrsonly,
647        &sizelimit, &timelimit, &deref) == FAILURE) {
648        return;
649    }
650
651    /* Reverse -> fall through */
652    switch (argcount) {
653        case 8:
654            ldap_deref = deref;
655        case 7:
656            ldap_timelimit = timelimit;
657        case 6:
658            ldap_sizelimit = sizelimit;
659        case 5:
660            ldap_attrsonly = attrsonly;
661        case 4:
662            num_attribs = zend_hash_num_elements(Z_ARRVAL_P(attrs));
663            ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
664
665            for (i = 0; i<num_attribs; i++) {
666                if ((attr = zend_hash_index_find(Z_ARRVAL_P(attrs), i)) == NULL) {
667                    php_error_docref(NULL, E_WARNING, "Array initialization wrong");
668                    ret = 0;
669                    goto cleanup;
670                }
671
672                SEPARATE_ZVAL(attr);
673                convert_to_string_ex(attr);
674                ldap_attrs[i] = Z_STRVAL_P(attr);
675            }
676            ldap_attrs[num_attribs] = NULL;
677        default:
678            break;
679    }
680
681    /* parallel search? */
682    if (Z_TYPE_P(link) == IS_ARRAY) {
683        int i, nlinks, nbases, nfilters, *rcs;
684        ldap_linkdata **lds;
685        zval *entry, resource;
686
687        nlinks = zend_hash_num_elements(Z_ARRVAL_P(link));
688        if (nlinks == 0) {
689            php_error_docref(NULL, E_WARNING, "No links in link array");
690            ret = 0;
691            goto cleanup;
692        }
693
694        if (Z_TYPE_P(base_dn) == IS_ARRAY) {
695            nbases = zend_hash_num_elements(Z_ARRVAL_P(base_dn));
696            if (nbases != nlinks) {
697                php_error_docref(NULL, E_WARNING, "Base must either be a string, or an array with the same number of elements as the links array");
698                ret = 0;
699                goto cleanup;
700            }
701            zend_hash_internal_pointer_reset(Z_ARRVAL_P(base_dn));
702        } else {
703            nbases = 0; /* this means string, not array */
704            /* If anything else than string is passed, ldap_base_dn = NULL */
705            if (Z_TYPE_P(base_dn) == IS_STRING) {
706                ldap_base_dn = Z_STRVAL_P(base_dn);
707            } else {
708                ldap_base_dn = NULL;
709            }
710        }
711
712        if (Z_TYPE_P(filter) == IS_ARRAY) {
713            nfilters = zend_hash_num_elements(Z_ARRVAL_P(filter));
714            if (nfilters != nlinks) {
715                php_error_docref(NULL, E_WARNING, "Filter must either be a string, or an array with the same number of elements as the links array");
716                ret = 0;
717                goto cleanup;
718            }
719            zend_hash_internal_pointer_reset(Z_ARRVAL_P(filter));
720        } else {
721            nfilters = 0; /* this means string, not array */
722            convert_to_string_ex(filter);
723            ldap_filter = Z_STRVAL_P(filter);
724        }
725
726        lds = safe_emalloc(nlinks, sizeof(ldap_linkdata), 0);
727        rcs = safe_emalloc(nlinks, sizeof(*rcs), 0);
728
729        zend_hash_internal_pointer_reset(Z_ARRVAL_P(link));
730        for (i=0; i<nlinks; i++) {
731            entry = zend_hash_get_current_data(Z_ARRVAL_P(link));
732
733            ld = (ldap_linkdata *) zend_fetch_resource_ex(entry, "ldap link", le_link);
734            if (ld == NULL) {
735                ret = 0;
736                goto cleanup_parallel;
737            }
738            if (nbases != 0) { /* base_dn an array? */
739                entry = zend_hash_get_current_data(Z_ARRVAL_P(base_dn));
740                zend_hash_move_forward(Z_ARRVAL_P(base_dn));
741
742                /* If anything else than string is passed, ldap_base_dn = NULL */
743                if (Z_TYPE_P(entry) == IS_STRING) {
744                    ldap_base_dn = Z_STRVAL_P(entry);
745                } else {
746                    ldap_base_dn = NULL;
747                }
748            }
749            if (nfilters != 0) { /* filter an array? */
750                entry = zend_hash_get_current_data(Z_ARRVAL_P(filter));
751                zend_hash_move_forward(Z_ARRVAL_P(filter));
752                convert_to_string_ex(entry);
753                ldap_filter = Z_STRVAL_P(entry);
754            }
755
756            php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
757
758            /* Run the actual search */
759            rcs[i] = ldap_search(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly);
760            lds[i] = ld;
761            zend_hash_move_forward(Z_ARRVAL_P(link));
762        }
763
764        array_init(return_value);
765
766        /* Collect results from the searches */
767        for (i=0; i<nlinks; i++) {
768            if (rcs[i] != -1) {
769                rcs[i] = ldap_result(lds[i]->link, LDAP_RES_ANY, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
770            }
771            if (rcs[i] != -1) {
772                ZVAL_RES(&resource, zend_register_resource(ldap_res, le_result));
773                add_next_index_zval(return_value, &resource);
774            } else {
775                add_next_index_bool(return_value, 0);
776            }
777        }
778
779cleanup_parallel:
780        efree(lds);
781        efree(rcs);
782    } else {
783        convert_to_string_ex(filter);
784        ldap_filter = Z_STRVAL_P(filter);
785
786        /* If anything else than string is passed, ldap_base_dn = NULL */
787        if (Z_TYPE_P(base_dn) == IS_STRING) {
788            ldap_base_dn = Z_STRVAL_P(base_dn);
789        }
790
791        ld = (ldap_linkdata *) zend_fetch_resource_ex(link, "ldap link", le_link);
792        if (ld == NULL) {
793            ret = 0;
794            goto cleanup;
795        }
796
797        php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
798
799        /* Run the actual search */
800        errno = ldap_search_s(ld->link, ldap_base_dn, scope, ldap_filter, ldap_attrs, ldap_attrsonly, &ldap_res);
801
802        if (errno != LDAP_SUCCESS
803            && errno != LDAP_SIZELIMIT_EXCEEDED
804#ifdef LDAP_ADMINLIMIT_EXCEEDED
805            && errno != LDAP_ADMINLIMIT_EXCEEDED
806#endif
807#ifdef LDAP_REFERRAL
808            && errno != LDAP_REFERRAL
809#endif
810        ) {
811            php_error_docref(NULL, E_WARNING, "Search: %s", ldap_err2string(errno));
812            ret = 0;
813        } else {
814            if (errno == LDAP_SIZELIMIT_EXCEEDED) {
815                php_error_docref(NULL, E_WARNING, "Partial search results returned: Sizelimit exceeded");
816            }
817#ifdef LDAP_ADMINLIMIT_EXCEEDED
818            else if (errno == LDAP_ADMINLIMIT_EXCEEDED) {
819                php_error_docref(NULL, E_WARNING, "Partial search results returned: Adminlimit exceeded");
820            }
821#endif
822
823            RETVAL_RES(zend_register_resource(ldap_res, le_result));
824        }
825    }
826
827cleanup:
828    if (ld) {
829        /* Restoring previous options */
830        php_set_opts(ld->link, old_ldap_sizelimit, old_ldap_timelimit, old_ldap_deref, &ldap_sizelimit, &ldap_timelimit, &ldap_deref);
831    }
832    if (ldap_attrs != NULL) {
833        efree(ldap_attrs);
834    }
835    if (!ret) {
836        RETVAL_BOOL(ret);
837    }
838}
839/* }}} */
840
841/* {{{ proto resource ldap_read(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
842   Read an entry */
843PHP_FUNCTION(ldap_read)
844{
845    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_BASE);
846}
847/* }}} */
848
849/* {{{ proto resource ldap_list(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
850   Single-level search */
851PHP_FUNCTION(ldap_list)
852{
853    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_ONELEVEL);
854}
855/* }}} */
856
857/* {{{ proto resource ldap_search(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])
858   Search LDAP tree under base_dn */
859PHP_FUNCTION(ldap_search)
860{
861    php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_SUBTREE);
862}
863/* }}} */
864
865/* {{{ proto bool ldap_free_result(resource result)
866   Free result memory */
867PHP_FUNCTION(ldap_free_result)
868{
869    zval *result;
870    LDAPMessage *ldap_result;
871
872    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) != SUCCESS) {
873        return;
874    }
875
876    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
877        RETURN_FALSE;
878    }
879
880    zend_list_close(Z_RES_P(result));  /* Delete list entry */
881    RETVAL_TRUE;
882}
883/* }}} */
884
885/* {{{ proto int ldap_count_entries(resource link, resource result)
886   Count the number of entries in a search result */
887PHP_FUNCTION(ldap_count_entries)
888{
889    zval *link, *result;
890    ldap_linkdata *ld;
891    LDAPMessage *ldap_result;
892
893    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
894        return;
895    }
896
897    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
898        RETURN_FALSE;
899    }
900
901    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
902        RETURN_FALSE;
903    }
904
905    RETURN_LONG(ldap_count_entries(ld->link, ldap_result));
906}
907/* }}} */
908
909/* {{{ proto resource ldap_first_entry(resource link, resource result)
910   Return first result id */
911PHP_FUNCTION(ldap_first_entry)
912{
913    zval *link, *result;
914    ldap_linkdata *ld;
915    ldap_resultentry *resultentry;
916    LDAPMessage *ldap_result, *entry;
917
918    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
919        return;
920    }
921
922    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
923        RETURN_FALSE;
924    }
925
926    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
927        RETURN_FALSE;
928    }
929
930    if ((entry = ldap_first_entry(ld->link, ldap_result)) == NULL) {
931        RETVAL_FALSE;
932    } else {
933        resultentry = emalloc(sizeof(ldap_resultentry));
934        RETVAL_RES(zend_register_resource(resultentry, le_result_entry));
935        ZVAL_COPY(&resultentry->res, result);
936        resultentry->data = entry;
937        resultentry->ber = NULL;
938    }
939}
940/* }}} */
941
942/* {{{ proto resource ldap_next_entry(resource link, resource result_entry)
943   Get next result entry */
944PHP_FUNCTION(ldap_next_entry)
945{
946    zval *link, *result_entry;
947    ldap_linkdata *ld;
948    ldap_resultentry *resultentry, *resultentry_next;
949    LDAPMessage *entry_next;
950
951    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
952        return;
953    }
954
955    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
956        RETURN_FALSE;
957    }
958    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
959        RETURN_FALSE;
960    }
961
962    if ((entry_next = ldap_next_entry(ld->link, resultentry->data)) == NULL) {
963        RETVAL_FALSE;
964    } else {
965        resultentry_next = emalloc(sizeof(ldap_resultentry));
966        RETVAL_RES(zend_register_resource(resultentry_next, le_result_entry));
967        ZVAL_COPY(&resultentry_next->res, &resultentry->res);
968        resultentry_next->data = entry_next;
969        resultentry_next->ber = NULL;
970    }
971}
972/* }}} */
973
974/* {{{ proto array ldap_get_entries(resource link, resource result)
975   Get all result entries */
976PHP_FUNCTION(ldap_get_entries)
977{
978    zval *link, *result;
979    LDAPMessage *ldap_result, *ldap_result_entry;
980    zval tmp1, tmp2;
981    ldap_linkdata *ld;
982    LDAP *ldap;
983    int num_entries, num_attrib, num_values, i;
984    BerElement *ber;
985    char *attribute;
986    size_t attr_len;
987    struct berval **ldap_value;
988    char *dn;
989
990    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
991        return;
992    }
993
994    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
995        RETURN_FALSE;
996    }
997    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
998        RETURN_FALSE;
999    }
1000
1001    ldap = ld->link;
1002    num_entries = ldap_count_entries(ldap, ldap_result);
1003
1004    array_init(return_value);
1005    add_assoc_long(return_value, "count", num_entries);
1006
1007    if (num_entries == 0) {
1008        return;
1009    }
1010
1011    ldap_result_entry = ldap_first_entry(ldap, ldap_result);
1012    if (ldap_result_entry == NULL) {
1013        zval_dtor(return_value);
1014        RETURN_FALSE;
1015    }
1016
1017    num_entries = 0;
1018    while (ldap_result_entry != NULL) {
1019        array_init(&tmp1);
1020
1021        num_attrib = 0;
1022        attribute = ldap_first_attribute(ldap, ldap_result_entry, &ber);
1023
1024        while (attribute != NULL) {
1025            ldap_value = ldap_get_values_len(ldap, ldap_result_entry, attribute);
1026            num_values = ldap_count_values_len(ldap_value);
1027
1028            array_init(&tmp2);
1029            add_assoc_long(&tmp2, "count", num_values);
1030            for (i = 0; i < num_values; i++) {
1031                add_index_stringl(&tmp2, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1032            }
1033            ldap_value_free_len(ldap_value);
1034
1035            attr_len = strlen(attribute);
1036            zend_hash_str_update(Z_ARRVAL(tmp1), php_strtolower(attribute, attr_len), attr_len, &tmp2);
1037            add_index_string(&tmp1, num_attrib, attribute);
1038
1039            num_attrib++;
1040#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1041            ldap_memfree(attribute);
1042#endif
1043            attribute = ldap_next_attribute(ldap, ldap_result_entry, ber);
1044        }
1045#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1046        if (ber != NULL) {
1047            ber_free(ber, 0);
1048        }
1049#endif
1050
1051        add_assoc_long(&tmp1, "count", num_attrib);
1052        dn = ldap_get_dn(ldap, ldap_result_entry);
1053        add_assoc_string(&tmp1, "dn", dn);
1054#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1055        ldap_memfree(dn);
1056#else
1057        free(dn);
1058#endif
1059
1060        zend_hash_index_update(Z_ARRVAL_P(return_value), num_entries, &tmp1);
1061
1062        num_entries++;
1063        ldap_result_entry = ldap_next_entry(ldap, ldap_result_entry);
1064    }
1065
1066    add_assoc_long(return_value, "count", num_entries);
1067
1068}
1069/* }}} */
1070
1071/* {{{ proto string ldap_first_attribute(resource link, resource result_entry)
1072   Return first attribute */
1073PHP_FUNCTION(ldap_first_attribute)
1074{
1075    zval *link, *result_entry;
1076    ldap_linkdata *ld;
1077    ldap_resultentry *resultentry;
1078    char *attribute;
1079    zend_long dummy_ber;
1080
1081    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1082        return;
1083    }
1084
1085    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1086        RETURN_FALSE;
1087    }
1088
1089    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1090        RETURN_FALSE;
1091    }
1092
1093    if ((attribute = ldap_first_attribute(ld->link, resultentry->data, &resultentry->ber)) == NULL) {
1094        RETURN_FALSE;
1095    } else {
1096        RETVAL_STRING(attribute);
1097#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1098        ldap_memfree(attribute);
1099#endif
1100    }
1101}
1102/* }}} */
1103
1104/* {{{ proto string ldap_next_attribute(resource link, resource result_entry)
1105   Get the next attribute in result */
1106PHP_FUNCTION(ldap_next_attribute)
1107{
1108    zval *link, *result_entry;
1109    ldap_linkdata *ld;
1110    ldap_resultentry *resultentry;
1111    char *attribute;
1112    zend_long dummy_ber;
1113
1114    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1115        return;
1116    }
1117
1118    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1119        RETURN_FALSE;
1120    }
1121
1122    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1123        RETURN_FALSE;
1124    }
1125
1126    if (resultentry->ber == NULL) {
1127        php_error_docref(NULL, E_WARNING, "called before calling ldap_first_attribute() or no attributes found in result entry");
1128        RETURN_FALSE;
1129    }
1130
1131    if ((attribute = ldap_next_attribute(ld->link, resultentry->data, resultentry->ber)) == NULL) {
1132#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1133        if (resultentry->ber != NULL) {
1134            ber_free(resultentry->ber, 0);
1135            resultentry->ber = NULL;
1136        }
1137#endif
1138        RETURN_FALSE;
1139    } else {
1140        RETVAL_STRING(attribute);
1141#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1142        ldap_memfree(attribute);
1143#endif
1144    }
1145}
1146/* }}} */
1147
1148/* {{{ proto array ldap_get_attributes(resource link, resource result_entry)
1149   Get attributes from a search result entry */
1150PHP_FUNCTION(ldap_get_attributes)
1151{
1152    zval *link, *result_entry;
1153    zval tmp;
1154    ldap_linkdata *ld;
1155    ldap_resultentry *resultentry;
1156    char *attribute;
1157    struct berval **ldap_value;
1158    int i, num_values, num_attrib;
1159    BerElement *ber;
1160
1161    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
1162        return;
1163    }
1164
1165    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1166        RETURN_FALSE;
1167    }
1168
1169    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1170        RETURN_FALSE;
1171    }
1172
1173    array_init(return_value);
1174    num_attrib = 0;
1175
1176    attribute = ldap_first_attribute(ld->link, resultentry->data, &ber);
1177    while (attribute != NULL) {
1178        ldap_value = ldap_get_values_len(ld->link, resultentry->data, attribute);
1179        num_values = ldap_count_values_len(ldap_value);
1180
1181        array_init(&tmp);
1182        add_assoc_long(&tmp, "count", num_values);
1183        for (i = 0; i < num_values; i++) {
1184            add_index_stringl(&tmp, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1185        }
1186        ldap_value_free_len(ldap_value);
1187
1188        zend_hash_str_update(Z_ARRVAL_P(return_value), attribute, strlen(attribute), &tmp);
1189        add_index_string(return_value, num_attrib, attribute);
1190
1191        num_attrib++;
1192#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1193        ldap_memfree(attribute);
1194#endif
1195        attribute = ldap_next_attribute(ld->link, resultentry->data, ber);
1196    }
1197#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1198    if (ber != NULL) {
1199        ber_free(ber, 0);
1200    }
1201#endif
1202
1203    add_assoc_long(return_value, "count", num_attrib);
1204}
1205/* }}} */
1206
1207/* {{{ proto array ldap_get_values_len(resource link, resource result_entry, string attribute)
1208   Get all values with lengths from a result entry */
1209PHP_FUNCTION(ldap_get_values_len)
1210{
1211    zval *link, *result_entry;
1212    ldap_linkdata *ld;
1213    ldap_resultentry *resultentry;
1214    char *attr;
1215    struct berval **ldap_value_len;
1216    int i, num_values;
1217    size_t attr_len;
1218
1219    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result_entry, &attr, &attr_len) != SUCCESS) {
1220        return;
1221    }
1222
1223    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1224        RETURN_FALSE;
1225    }
1226
1227    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1228        RETURN_FALSE;
1229    }
1230
1231    if ((ldap_value_len = ldap_get_values_len(ld->link, resultentry->data, attr)) == NULL) {
1232        php_error_docref(NULL, E_WARNING, "Cannot get the value(s) of attribute %s", ldap_err2string(_get_lderrno(ld->link)));
1233        RETURN_FALSE;
1234    }
1235
1236    num_values = ldap_count_values_len(ldap_value_len);
1237    array_init(return_value);
1238
1239    for (i=0; i<num_values; i++) {
1240        add_next_index_stringl(return_value, ldap_value_len[i]->bv_val, ldap_value_len[i]->bv_len);
1241    }
1242
1243    add_assoc_long(return_value, "count", num_values);
1244    ldap_value_free_len(ldap_value_len);
1245
1246}
1247/* }}} */
1248
1249/* {{{ proto string ldap_get_dn(resource link, resource result_entry)
1250   Get the DN of a result entry */
1251PHP_FUNCTION(ldap_get_dn)
1252{
1253    zval *link, *result_entry;
1254    ldap_linkdata *ld;
1255    ldap_resultentry *resultentry;
1256    char *text;
1257
1258    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
1259        return;
1260    }
1261
1262    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1263        RETURN_FALSE;
1264    }
1265
1266    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1267        RETURN_FALSE;
1268    }
1269
1270    text = ldap_get_dn(ld->link, resultentry->data);
1271    if (text != NULL) {
1272        RETVAL_STRING(text);
1273#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1274        ldap_memfree(text);
1275#else
1276        free(text);
1277#endif
1278    } else {
1279        RETURN_FALSE;
1280    }
1281}
1282/* }}} */
1283
1284/* {{{ proto array ldap_explode_dn(string dn, int with_attrib)
1285   Splits DN into its component parts */
1286PHP_FUNCTION(ldap_explode_dn)
1287{
1288    zend_long with_attrib;
1289    char *dn, **ldap_value;
1290    int i, count;
1291    size_t dn_len;
1292
1293    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &dn, &dn_len, &with_attrib) != SUCCESS) {
1294        return;
1295    }
1296
1297    if (!(ldap_value = ldap_explode_dn(dn, with_attrib))) {
1298        /* Invalid parameters were passed to ldap_explode_dn */
1299        RETURN_FALSE;
1300    }
1301
1302    i=0;
1303    while (ldap_value[i] != NULL) i++;
1304    count = i;
1305
1306    array_init(return_value);
1307
1308    add_assoc_long(return_value, "count", count);
1309    for (i = 0; i<count; i++) {
1310        add_index_string(return_value, i, ldap_value[i]);
1311    }
1312
1313    ldap_value_free(ldap_value);
1314}
1315/* }}} */
1316
1317/* {{{ proto string ldap_dn2ufn(string dn)
1318   Convert DN to User Friendly Naming format */
1319PHP_FUNCTION(ldap_dn2ufn)
1320{
1321    char *dn, *ufn;
1322    size_t dn_len;
1323
1324    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dn, &dn_len) != SUCCESS) {
1325        return;
1326    }
1327
1328    ufn = ldap_dn2ufn(dn);
1329
1330    if (ufn != NULL) {
1331        RETVAL_STRING(ufn);
1332#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP || WINDOWS
1333        ldap_memfree(ufn);
1334#endif
1335    } else {
1336        RETURN_FALSE;
1337    }
1338}
1339/* }}} */
1340
1341
1342/* added to fix use of ldap_modify_add for doing an ldap_add, gerrit thomson. */
1343#define PHP_LD_FULL_ADD 0xff
1344/* {{{ php_ldap_do_modify
1345 */
1346static void php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper)
1347{
1348    zval *link, *entry, *value, *ivalue;
1349    ldap_linkdata *ld;
1350    char *dn;
1351    LDAPMod **ldap_mods;
1352    int i, j, num_attribs, num_values;
1353    size_t dn_len;
1354    int *num_berval;
1355    zend_string *attribute;
1356    zend_ulong index;
1357    int is_full_add=0; /* flag for full add operation so ldap_mod_add can be put back into oper, gerrit THomson */
1358
1359    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa", &link, &dn, &dn_len, &entry) != SUCCESS) {
1360        return;
1361    }
1362
1363    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1364        RETURN_FALSE;
1365    }
1366
1367    num_attribs = zend_hash_num_elements(Z_ARRVAL_P(entry));
1368    ldap_mods = safe_emalloc((num_attribs+1), sizeof(LDAPMod *), 0);
1369    num_berval = safe_emalloc(num_attribs, sizeof(int), 0);
1370    zend_hash_internal_pointer_reset(Z_ARRVAL_P(entry));
1371
1372    /* added by gerrit thomson to fix ldap_add using ldap_mod_add */
1373    if (oper == PHP_LD_FULL_ADD) {
1374        oper = LDAP_MOD_ADD;
1375        is_full_add = 1;
1376    }
1377    /* end additional , gerrit thomson */
1378
1379    for (i = 0; i < num_attribs; i++) {
1380        ldap_mods[i] = emalloc(sizeof(LDAPMod));
1381        ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
1382        ldap_mods[i]->mod_type = NULL;
1383
1384        if (zend_hash_get_current_key(Z_ARRVAL_P(entry), &attribute, &index) == HASH_KEY_IS_STRING) {
1385            ldap_mods[i]->mod_type = estrndup(attribute->val, attribute->len);
1386        } else {
1387            php_error_docref(NULL, E_WARNING, "Unknown attribute in the data");
1388            /* Free allocated memory */
1389            while (i >= 0) {
1390                if (ldap_mods[i]->mod_type) {
1391                    efree(ldap_mods[i]->mod_type);
1392                }
1393                efree(ldap_mods[i]);
1394                i--;
1395            }
1396            efree(num_berval);
1397            efree(ldap_mods);
1398            RETURN_FALSE;
1399        }
1400
1401        value = zend_hash_get_current_data(Z_ARRVAL_P(entry));
1402
1403        if (Z_TYPE_P(value) != IS_ARRAY) {
1404            num_values = 1;
1405        } else {
1406            num_values = zend_hash_num_elements(Z_ARRVAL_P(value));
1407        }
1408
1409        num_berval[i] = num_values;
1410        ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0);
1411
1412/* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */
1413        if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) {
1414            convert_to_string_ex(value);
1415            ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval));
1416            ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value);
1417            ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value);
1418        } else {
1419            for (j = 0; j < num_values; j++) {
1420                if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) {
1421                    php_error_docref(NULL, E_WARNING, "Value array must have consecutive indices 0, 1, ...");
1422                    num_berval[i] = j;
1423                    num_attribs = i + 1;
1424                    RETVAL_FALSE;
1425                    goto errexit;
1426                }
1427                convert_to_string_ex(ivalue);
1428                ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval));
1429                ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue);
1430                ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue);
1431            }
1432        }
1433        ldap_mods[i]->mod_bvalues[num_values] = NULL;
1434        zend_hash_move_forward(Z_ARRVAL_P(entry));
1435    }
1436    ldap_mods[num_attribs] = NULL;
1437
1438/* check flag to see if do_mod was called to perform full add , gerrit thomson */
1439    if (is_full_add == 1) {
1440        if ((i = ldap_add_s(ld->link, dn, ldap_mods)) != LDAP_SUCCESS) {
1441            php_error_docref(NULL, E_WARNING, "Add: %s", ldap_err2string(i));
1442            RETVAL_FALSE;
1443        } else RETVAL_TRUE;
1444    } else {
1445        if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1446            php_error_docref(NULL, E_WARNING, "Modify: %s", ldap_err2string(i));
1447            RETVAL_FALSE;
1448        } else RETVAL_TRUE;
1449    }
1450
1451errexit:
1452    for (i = 0; i < num_attribs; i++) {
1453        efree(ldap_mods[i]->mod_type);
1454        for (j = 0; j < num_berval[i]; j++) {
1455            efree(ldap_mods[i]->mod_bvalues[j]);
1456        }
1457        efree(ldap_mods[i]->mod_bvalues);
1458        efree(ldap_mods[i]);
1459    }
1460    efree(num_berval);
1461    efree(ldap_mods);
1462
1463    return;
1464}
1465/* }}} */
1466
1467/* {{{ proto bool ldap_add(resource link, string dn, array entry)
1468   Add entries to LDAP directory */
1469PHP_FUNCTION(ldap_add)
1470{
1471    /* use a newly define parameter into the do_modify so ldap_mod_add can be used the way it is supposed to be used , Gerrit THomson */
1472    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD);
1473}
1474/* }}} */
1475
1476/* three functions for attribute base modifications, gerrit Thomson */
1477
1478/* {{{ proto bool ldap_mod_replace(resource link, string dn, array entry)
1479   Replace attribute values with new ones */
1480PHP_FUNCTION(ldap_mod_replace)
1481{
1482    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE);
1483}
1484/* }}} */
1485
1486/* {{{ proto bool ldap_mod_add(resource link, string dn, array entry)
1487   Add attribute values to current */
1488PHP_FUNCTION(ldap_mod_add)
1489{
1490    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD);
1491}
1492/* }}} */
1493
1494/* {{{ proto bool ldap_mod_del(resource link, string dn, array entry)
1495   Delete attribute values */
1496PHP_FUNCTION(ldap_mod_del)
1497{
1498    php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE);
1499}
1500/* }}} */
1501
1502/* {{{ proto bool ldap_delete(resource link, string dn)
1503   Delete an entry from a directory */
1504PHP_FUNCTION(ldap_delete)
1505{
1506    zval *link;
1507    ldap_linkdata *ld;
1508    char *dn;
1509    int rc;
1510    size_t dn_len;
1511
1512    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &link, &dn, &dn_len) != SUCCESS) {
1513        return;
1514    }
1515
1516    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1517        RETURN_FALSE;
1518    }
1519
1520    if ((rc = ldap_delete_s(ld->link, dn)) != LDAP_SUCCESS) {
1521        php_error_docref(NULL, E_WARNING, "Delete: %s", ldap_err2string(rc));
1522        RETURN_FALSE;
1523    }
1524
1525    RETURN_TRUE;
1526}
1527/* }}} */
1528
1529/* {{{ _ldap_str_equal_to_const
1530 */
1531static int _ldap_str_equal_to_const(const char *str, uint str_len, const char *cstr)
1532{
1533    int i;
1534
1535    if (strlen(cstr) != str_len)
1536        return 0;
1537
1538    for (i = 0; i < str_len; ++i) {
1539        if (str[i] != cstr[i]) {
1540            return 0;
1541        }
1542    }
1543
1544    return 1;
1545}
1546/* }}} */
1547
1548/* {{{ _ldap_strlen_max
1549 */
1550static int _ldap_strlen_max(const char *str, uint max_len)
1551{
1552    int i;
1553
1554    for (i = 0; i < max_len; ++i) {
1555        if (str[i] == '\0') {
1556            return i;
1557        }
1558    }
1559
1560    return max_len;
1561}
1562/* }}} */
1563
1564/* {{{ _ldap_hash_fetch
1565 */
1566static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)
1567{
1568    *out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key));
1569}
1570/* }}} */
1571
1572/* {{{ proto bool ldap_modify_batch(resource link, string dn, array modifs)
1573   Perform multiple modifications as part of one operation */
1574PHP_FUNCTION(ldap_modify_batch)
1575{
1576    ldap_linkdata *ld;
1577    zval *link, *mods, *mod, *modinfo, *modval;
1578    zval *attrib, *modtype, *vals;
1579    zval *fetched;
1580    char *dn;
1581    size_t dn_len;
1582    int i, j, k;
1583    int num_mods, num_modprops, num_modvals;
1584    LDAPMod **ldap_mods;
1585    uint oper;
1586
1587    /*
1588    $mods = array(
1589        array(
1590            "attrib" => "unicodePwd",
1591            "modtype" => LDAP_MODIFY_BATCH_REMOVE,
1592            "values" => array($oldpw)
1593        ),
1594        array(
1595            "attrib" => "unicodePwd",
1596            "modtype" => LDAP_MODIFY_BATCH_ADD,
1597            "values" => array($newpw)
1598        ),
1599        array(
1600            "attrib" => "userPrincipalName",
1601            "modtype" => LDAP_MODIFY_BATCH_REPLACE,
1602            "values" => array("janitor@corp.contoso.com")
1603        ),
1604        array(
1605            "attrib" => "userCert",
1606            "modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL
1607        )
1608    );
1609    */
1610
1611    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa", &link, &dn, &dn_len, &mods) != SUCCESS) {
1612        return;
1613    }
1614
1615    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1616        RETURN_FALSE;
1617    }
1618
1619    /* perform validation */
1620    {
1621        zend_string *modkey;
1622        zend_long modtype;
1623
1624        /* to store the wrongly-typed keys */
1625        zend_ulong tmpUlong;
1626
1627        /* make sure the DN contains no NUL bytes */
1628        if (_ldap_strlen_max(dn, dn_len) != dn_len) {
1629            php_error_docref(NULL, E_WARNING, "DN must not contain NUL bytes");
1630            RETURN_FALSE;
1631        }
1632
1633        /* make sure the top level is a normal array */
1634        zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods));
1635        if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) {
1636            php_error_docref(NULL, E_WARNING, "Modifications array must not be string-indexed");
1637            RETURN_FALSE;
1638        }
1639
1640        num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods));
1641
1642        for (i = 0; i < num_mods; i++) {
1643            /* is the numbering consecutive? */
1644            if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) {
1645                php_error_docref(NULL, E_WARNING, "Modifications array must have consecutive indices 0, 1, ...");
1646                RETURN_FALSE;
1647            }
1648            mod = fetched;
1649
1650            /* is it an array? */
1651            if (Z_TYPE_P(mod) != IS_ARRAY) {
1652                php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be an array itself");
1653                RETURN_FALSE;
1654            }
1655
1656            /* for the modification hashtable... */
1657            zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod));
1658            num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod));
1659
1660            for (j = 0; j < num_modprops; j++) {
1661                /* are the keys strings? */
1662                if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong) != HASH_KEY_IS_STRING) {
1663                    php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be string-indexed");
1664                    RETURN_FALSE;
1665                }
1666
1667                /* is this a valid entry? */
1668                if (
1669                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_ATTRIB) &&
1670                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_MODTYPE) &&
1671                    !_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_VALUES)
1672                ) {
1673                    php_error_docref(NULL, E_WARNING, "The only allowed keys in entries of the modifications array are '" LDAP_MODIFY_BATCH_ATTRIB "', '" LDAP_MODIFY_BATCH_MODTYPE "' and '" LDAP_MODIFY_BATCH_VALUES "'");
1674                    RETURN_FALSE;
1675                }
1676
1677                fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod));
1678                modinfo = fetched;
1679
1680                /* does the value type match the key? */
1681                if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_ATTRIB)) {
1682                    if (Z_TYPE_P(modinfo) != IS_STRING) {
1683                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must be a string");
1684                        RETURN_FALSE;
1685                    }
1686
1687                    if (Z_STRLEN_P(modinfo) != _ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) {
1688                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must not contain NUL bytes");
1689                        RETURN_FALSE;
1690                    }
1691                }
1692                else if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_MODTYPE)) {
1693                    if (Z_TYPE_P(modinfo) != IS_LONG) {
1694                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_MODTYPE "' value must be a long");
1695                        RETURN_FALSE;
1696                    }
1697
1698                    /* is the value in range? */
1699                    modtype = Z_LVAL_P(modinfo);
1700                    if (
1701                        modtype != LDAP_MODIFY_BATCH_ADD &&
1702                        modtype != LDAP_MODIFY_BATCH_REMOVE &&
1703                        modtype != LDAP_MODIFY_BATCH_REPLACE &&
1704                        modtype != LDAP_MODIFY_BATCH_REMOVE_ALL
1705                    ) {
1706                        php_error_docref(NULL, E_WARNING, "The '" LDAP_MODIFY_BATCH_MODTYPE "' value must match one of the LDAP_MODIFY_BATCH_* constants");
1707                        RETURN_FALSE;
1708                    }
1709
1710                    /* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */
1711                    if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) {
1712                        if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
1713                            php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must not be provided");
1714                            RETURN_FALSE;
1715                        }
1716                    }
1717                    else {
1718                        if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
1719                            php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is not LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must be provided");
1720                            RETURN_FALSE;
1721                        }
1722                    }
1723                }
1724                else if (_ldap_str_equal_to_const(modkey->val, modkey->len, LDAP_MODIFY_BATCH_VALUES)) {
1725                    if (Z_TYPE_P(modinfo) != IS_ARRAY) {
1726                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' value must be an array");
1727                        RETURN_FALSE;
1728                    }
1729
1730                    /* is the array not empty? */
1731                    zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo));
1732                    num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo));
1733                    if (num_modvals == 0) {
1734                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have at least one element");
1735                        RETURN_FALSE;
1736                    }
1737
1738                    /* are its keys integers? */
1739                    if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) {
1740                        php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must not be string-indexed");
1741                        RETURN_FALSE;
1742                    }
1743
1744                    /* are the keys consecutive? */
1745                    for (k = 0; k < num_modvals; k++) {
1746                        if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) {
1747                            php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have consecutive indices 0, 1, ...");
1748                            RETURN_FALSE;
1749                        }
1750                        modval = fetched;
1751
1752                        /* is the data element a string? */
1753                        if (Z_TYPE_P(modval) != IS_STRING) {
1754                            php_error_docref(NULL, E_WARNING, "Each element of a '" LDAP_MODIFY_BATCH_VALUES "' array must be a string");
1755                            RETURN_FALSE;
1756                        }
1757                    }
1758                }
1759
1760                zend_hash_move_forward(Z_ARRVAL_P(mod));
1761            }
1762        }
1763    }
1764    /* validation was successful */
1765
1766    /* allocate array of modifications */
1767    ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0);
1768
1769    /* for each modification */
1770    for (i = 0; i < num_mods; i++) {
1771        /* allocate the modification struct */
1772        ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0);
1773
1774        /* fetch the relevant data */
1775        fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i);
1776        mod = fetched;
1777
1778        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib);
1779        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype);
1780        _ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals);
1781
1782        /* map the modification type */
1783        switch (Z_LVAL_P(modtype)) {
1784            case LDAP_MODIFY_BATCH_ADD:
1785                oper = LDAP_MOD_ADD;
1786                break;
1787            case LDAP_MODIFY_BATCH_REMOVE:
1788            case LDAP_MODIFY_BATCH_REMOVE_ALL:
1789                oper = LDAP_MOD_DELETE;
1790                break;
1791            case LDAP_MODIFY_BATCH_REPLACE:
1792                oper = LDAP_MOD_REPLACE;
1793                break;
1794            default:
1795                php_error_docref(NULL, E_ERROR, "Unknown and uncaught modification type.");
1796                RETURN_FALSE;
1797        }
1798
1799        /* fill in the basic info */
1800        ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
1801        ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib));
1802
1803        if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) {
1804            /* no values */
1805            ldap_mods[i]->mod_bvalues = NULL;
1806        }
1807        else {
1808            /* allocate space for the values as part of this modification */
1809            num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals));
1810            ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0);
1811
1812            /* for each value */
1813            for (j = 0; j < num_modvals; j++) {
1814                /* fetch it */
1815                fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j);
1816                modval = fetched;
1817
1818                /* allocate the data struct */
1819                ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0);
1820
1821                /* fill it */
1822                ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(modval);
1823                ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(Z_STRVAL_P(modval), Z_STRLEN_P(modval));
1824            }
1825
1826            /* NULL-terminate values */
1827            ldap_mods[i]->mod_bvalues[num_modvals] = NULL;
1828        }
1829    }
1830
1831    /* NULL-terminate modifications */
1832    ldap_mods[num_mods] = NULL;
1833
1834    /* perform (finally) */
1835    if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1836        php_error_docref(NULL, E_WARNING, "Batch Modify: %s", ldap_err2string(i));
1837        RETVAL_FALSE;
1838    } else RETVAL_TRUE;
1839
1840    /* clean up */
1841    {
1842        for (i = 0; i < num_mods; i++) {
1843            /* attribute */
1844            efree(ldap_mods[i]->mod_type);
1845
1846            if (ldap_mods[i]->mod_bvalues != NULL) {
1847                /* each BER value */
1848                for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) {
1849                    /* free the data bytes */
1850                    efree(ldap_mods[i]->mod_bvalues[j]->bv_val);
1851
1852                    /* free the bvalue struct */
1853                    efree(ldap_mods[i]->mod_bvalues[j]);
1854                }
1855
1856                /* the BER value array */
1857                efree(ldap_mods[i]->mod_bvalues);
1858            }
1859
1860            /* the modification */
1861            efree(ldap_mods[i]);
1862        }
1863
1864        /* the modifications array */
1865        efree(ldap_mods);
1866    }
1867}
1868/* }}} */
1869
1870/* {{{ proto int ldap_errno(resource link)
1871   Get the current ldap error number */
1872PHP_FUNCTION(ldap_errno)
1873{
1874    zval *link;
1875    ldap_linkdata *ld;
1876
1877    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
1878        return;
1879    }
1880
1881    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1882        RETURN_FALSE;
1883    }
1884
1885    RETURN_LONG(_get_lderrno(ld->link));
1886}
1887/* }}} */
1888
1889/* {{{ proto string ldap_err2str(int errno)
1890   Convert error number to error string */
1891PHP_FUNCTION(ldap_err2str)
1892{
1893    zend_long perrno;
1894
1895    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perrno) != SUCCESS) {
1896        return;
1897    }
1898
1899    RETURN_STRING(ldap_err2string(perrno));
1900}
1901/* }}} */
1902
1903/* {{{ proto string ldap_error(resource link)
1904   Get the current ldap error string */
1905PHP_FUNCTION(ldap_error)
1906{
1907    zval *link;
1908    ldap_linkdata *ld;
1909    int ld_errno;
1910
1911    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
1912        return;
1913    }
1914
1915    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1916        RETURN_FALSE;
1917    }
1918
1919    ld_errno = _get_lderrno(ld->link);
1920
1921    RETURN_STRING(ldap_err2string(ld_errno));
1922}
1923/* }}} */
1924
1925/* {{{ proto bool ldap_compare(resource link, string dn, string attr, string value)
1926   Determine if an entry has a specific value for one of its attributes */
1927PHP_FUNCTION(ldap_compare)
1928{
1929    zval *link;
1930    char *dn, *attr, *value;
1931    size_t dn_len, attr_len, value_len;
1932    ldap_linkdata *ld;
1933    int errno;
1934
1935    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsss", &link, &dn, &dn_len, &attr, &attr_len, &value, &value_len) != SUCCESS) {
1936        return;
1937    }
1938
1939    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1940        RETURN_FALSE;
1941    }
1942
1943    errno = ldap_compare_s(ld->link, dn, attr, value);
1944
1945    switch (errno) {
1946        case LDAP_COMPARE_TRUE:
1947            RETURN_TRUE;
1948            break;
1949
1950        case LDAP_COMPARE_FALSE:
1951            RETURN_FALSE;
1952            break;
1953    }
1954
1955    php_error_docref(NULL, E_WARNING, "Compare: %s", ldap_err2string(errno));
1956    RETURN_LONG(-1);
1957}
1958/* }}} */
1959
1960/* {{{ proto bool ldap_sort(resource link, resource result, string sortfilter)
1961   Sort LDAP result entries */
1962PHP_FUNCTION(ldap_sort)
1963{
1964    zval *link, *result;
1965    ldap_linkdata *ld;
1966    char *sortfilter;
1967    size_t sflen;
1968    zend_resource *le;
1969
1970    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result, &sortfilter, &sflen) != SUCCESS) {
1971        RETURN_FALSE;
1972    }
1973
1974    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1975        RETURN_FALSE;
1976    }
1977
1978    if ((le = zend_hash_index_find_ptr(&EG(regular_list), Z_RES_HANDLE_P(result))) == NULL || le->type != le_result) {
1979        php_error_docref(NULL, E_WARNING, "Supplied resource is not a valid ldap result resource");
1980        RETURN_FALSE;
1981    }
1982
1983    if (ldap_sort_entries(ld->link, (LDAPMessage **) &le->ptr, sflen ? sortfilter : NULL, strcmp) != LDAP_SUCCESS) {
1984        php_error_docref(NULL, E_WARNING, "%s", ldap_err2string(errno));
1985        RETURN_FALSE;
1986    }
1987
1988    RETURN_TRUE;
1989}
1990/* }}} */
1991
1992#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
1993/* {{{ proto bool ldap_get_option(resource link, int option, mixed retval)
1994   Get the current value of various session-wide parameters */
1995PHP_FUNCTION(ldap_get_option)
1996{
1997    zval *link, *retval;
1998    ldap_linkdata *ld;
1999    zend_long option;
2000
2001    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz/", &link, &option, &retval) != SUCCESS) {
2002        return;
2003    }
2004
2005    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2006        RETURN_FALSE;
2007    }
2008
2009    switch (option) {
2010    /* options with int value */
2011    case LDAP_OPT_DEREF:
2012    case LDAP_OPT_SIZELIMIT:
2013    case LDAP_OPT_TIMELIMIT:
2014    case LDAP_OPT_PROTOCOL_VERSION:
2015    case LDAP_OPT_ERROR_NUMBER:
2016    case LDAP_OPT_REFERRALS:
2017#ifdef LDAP_OPT_RESTART
2018    case LDAP_OPT_RESTART:
2019#endif
2020        {
2021            int val;
2022
2023            if (ldap_get_option(ld->link, option, &val)) {
2024                RETURN_FALSE;
2025            }
2026            zval_ptr_dtor(retval);
2027            ZVAL_LONG(retval, val);
2028        } break;
2029#ifdef LDAP_OPT_NETWORK_TIMEOUT
2030    case LDAP_OPT_NETWORK_TIMEOUT:
2031        {
2032            struct timeval *timeout = NULL;
2033
2034            if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
2035                if (timeout) {
2036                    ldap_memfree(timeout);
2037                }
2038                RETURN_FALSE;
2039            }
2040            if (!timeout) {
2041                RETURN_FALSE;
2042            }
2043            zval_ptr_dtor(retval);
2044            ZVAL_LONG(retval, timeout->tv_sec);
2045            ldap_memfree(timeout);
2046        } break;
2047#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
2048    case LDAP_X_OPT_CONNECT_TIMEOUT:
2049        {
2050            int timeout;
2051
2052            if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
2053                RETURN_FALSE;
2054            }
2055            zval_ptr_dtor(retval);
2056            ZVAL_LONG(retval, (timeout / 1000));
2057        } break;
2058#endif
2059    /* options with string value */
2060    case LDAP_OPT_ERROR_STRING:
2061#ifdef LDAP_OPT_HOST_NAME
2062    case LDAP_OPT_HOST_NAME:
2063#endif
2064#ifdef HAVE_LDAP_SASL
2065    case LDAP_OPT_X_SASL_MECH:
2066    case LDAP_OPT_X_SASL_REALM:
2067    case LDAP_OPT_X_SASL_AUTHCID:
2068    case LDAP_OPT_X_SASL_AUTHZID:
2069#endif
2070#ifdef LDAP_OPT_MATCHED_DN
2071    case LDAP_OPT_MATCHED_DN:
2072#endif
2073        {
2074            char *val = NULL;
2075
2076            if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') {
2077                if (val) {
2078                    ldap_memfree(val);
2079                }
2080                RETURN_FALSE;
2081            }
2082            zval_ptr_dtor(retval);
2083            ZVAL_STRING(retval, val);
2084            ldap_memfree(val);
2085        } break;
2086/* options not implemented
2087    case LDAP_OPT_SERVER_CONTROLS:
2088    case LDAP_OPT_CLIENT_CONTROLS:
2089    case LDAP_OPT_API_INFO:
2090    case LDAP_OPT_API_FEATURE_INFO:
2091*/
2092    default:
2093        RETURN_FALSE;
2094    }
2095    RETURN_TRUE;
2096}
2097/* }}} */
2098
2099/* {{{ proto bool ldap_set_option(resource link, int option, mixed newval)
2100   Set the value of various session-wide parameters */
2101PHP_FUNCTION(ldap_set_option)
2102{
2103    zval *link, *newval;
2104    ldap_linkdata *ld;
2105    LDAP *ldap;
2106    zend_long option;
2107
2108    if (zend_parse_parameters(ZEND_NUM_ARGS(), "zlz", &link, &option, &newval) != SUCCESS) {
2109        return;
2110    }
2111
2112    if (Z_TYPE_P(link) == IS_NULL) {
2113        ldap = NULL;
2114    } else {
2115        if ((ld = (ldap_linkdata *)zend_fetch_resource_ex(link, "ldap link", le_link)) == NULL) {
2116            RETURN_FALSE;
2117        }
2118        ldap = ld->link;
2119    }
2120
2121    switch (option) {
2122    /* options with int value */
2123    case LDAP_OPT_DEREF:
2124    case LDAP_OPT_SIZELIMIT:
2125    case LDAP_OPT_TIMELIMIT:
2126    case LDAP_OPT_PROTOCOL_VERSION:
2127    case LDAP_OPT_ERROR_NUMBER:
2128#ifdef LDAP_OPT_DEBUG_LEVEL
2129    case LDAP_OPT_DEBUG_LEVEL:
2130#endif
2131        {
2132            int val;
2133
2134            convert_to_long_ex(newval);
2135            val = Z_LVAL_P(newval);
2136            if (ldap_set_option(ldap, option, &val)) {
2137                RETURN_FALSE;
2138            }
2139        } break;
2140#ifdef LDAP_OPT_NETWORK_TIMEOUT
2141    case LDAP_OPT_NETWORK_TIMEOUT:
2142        {
2143            struct timeval timeout;
2144
2145            convert_to_long_ex(newval);
2146            timeout.tv_sec = Z_LVAL_P(newval);
2147            timeout.tv_usec = 0;
2148            if (ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
2149                RETURN_FALSE;
2150            }
2151        } break;
2152#elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
2153    case LDAP_X_OPT_CONNECT_TIMEOUT:
2154        {
2155            int timeout;
2156
2157            convert_to_long_ex(newval);
2158            timeout = 1000 * Z_LVAL_P(newval); /* Convert to milliseconds */
2159            if (ldap_set_option(ldap, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
2160                RETURN_FALSE;
2161            }
2162        } break;
2163#endif
2164        /* options with string value */
2165    case LDAP_OPT_ERROR_STRING:
2166#ifdef LDAP_OPT_HOST_NAME
2167    case LDAP_OPT_HOST_NAME:
2168#endif
2169#ifdef HAVE_LDAP_SASL
2170    case LDAP_OPT_X_SASL_MECH:
2171    case LDAP_OPT_X_SASL_REALM:
2172    case LDAP_OPT_X_SASL_AUTHCID:
2173    case LDAP_OPT_X_SASL_AUTHZID:
2174#endif
2175#ifdef LDAP_OPT_MATCHED_DN
2176    case LDAP_OPT_MATCHED_DN:
2177#endif
2178        {
2179            char *val;
2180            convert_to_string_ex(newval);
2181            val = Z_STRVAL_P(newval);
2182            if (ldap_set_option(ldap, option, val)) {
2183                RETURN_FALSE;
2184            }
2185        } break;
2186        /* options with boolean value */
2187    case LDAP_OPT_REFERRALS:
2188#ifdef LDAP_OPT_RESTART
2189    case LDAP_OPT_RESTART:
2190#endif
2191        {
2192            void *val;
2193            convert_to_boolean_ex(newval);
2194            val = Z_TYPE_P(newval) == IS_TRUE
2195                ? LDAP_OPT_ON : LDAP_OPT_OFF;
2196            if (ldap_set_option(ldap, option, val)) {
2197                RETURN_FALSE;
2198            }
2199        } break;
2200        /* options with control list value */
2201    case LDAP_OPT_SERVER_CONTROLS:
2202    case LDAP_OPT_CLIENT_CONTROLS:
2203        {
2204            LDAPControl *ctrl, **ctrls, **ctrlp;
2205            zval *ctrlval, *val;
2206            int ncontrols;
2207            char error=0;
2208
2209            if ((Z_TYPE_P(newval) != IS_ARRAY) || !(ncontrols = zend_hash_num_elements(Z_ARRVAL_P(newval)))) {
2210                php_error_docref(NULL, E_WARNING, "Expected non-empty array value for this option");
2211                RETURN_FALSE;
2212            }
2213            ctrls = safe_emalloc((1 + ncontrols), sizeof(*ctrls), 0);
2214            *ctrls = NULL;
2215            ctrlp = ctrls;
2216            ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(newval), ctrlval) {
2217                if (Z_TYPE_P(ctrlval) != IS_ARRAY) {
2218                    php_error_docref(NULL, E_WARNING, "The array value must contain only arrays, where each array is a control");
2219                    error = 1;
2220                    break;
2221                }
2222                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "oid", sizeof("oid") - 1)) == NULL) {
2223                    php_error_docref(NULL, E_WARNING, "Control must have an oid key");
2224                    error = 1;
2225                    break;
2226                }
2227                ctrl = *ctrlp = emalloc(sizeof(**ctrlp));
2228                convert_to_string_ex(val);
2229                ctrl->ldctl_oid = Z_STRVAL_P(val);
2230                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "value", sizeof("value") - 1)) != NULL) {
2231                    convert_to_string_ex(val);
2232                    ctrl->ldctl_value.bv_val = Z_STRVAL_P(val);
2233                    ctrl->ldctl_value.bv_len = Z_STRLEN_P(val);
2234                } else {
2235                    ctrl->ldctl_value.bv_val = NULL;
2236                    ctrl->ldctl_value.bv_len = 0;
2237                }
2238                if ((val = zend_hash_str_find(Z_ARRVAL_P(ctrlval), "iscritical", sizeof("iscritical") - 1)) != NULL) {
2239                    convert_to_boolean_ex(val);
2240                    ctrl->ldctl_iscritical = Z_TYPE_P(val) == IS_TRUE;
2241                } else {
2242                    ctrl->ldctl_iscritical = 0;
2243                }
2244
2245                ++ctrlp;
2246                *ctrlp = NULL;
2247            } ZEND_HASH_FOREACH_END();
2248            if (!error) {
2249                error = ldap_set_option(ldap, option, ctrls);
2250            }
2251            ctrlp = ctrls;
2252            while (*ctrlp) {
2253                efree(*ctrlp);
2254                ctrlp++;
2255            }
2256            efree(ctrls);
2257            if (error) {
2258                RETURN_FALSE;
2259            }
2260        } break;
2261    default:
2262        RETURN_FALSE;
2263    }
2264    RETURN_TRUE;
2265}
2266/* }}} */
2267
2268#ifdef HAVE_LDAP_PARSE_RESULT
2269/* {{{ proto bool ldap_parse_result(resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)
2270   Extract information from result */
2271PHP_FUNCTION(ldap_parse_result)
2272{
2273    zval *link, *result, *errcode, *matcheddn, *errmsg, *referrals;
2274    ldap_linkdata *ld;
2275    LDAPMessage *ldap_result;
2276    char **lreferrals, **refp;
2277    char *lmatcheddn, *lerrmsg;
2278    int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
2279
2280    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrz/|z/z/z/", &link, &result, &errcode, &matcheddn, &errmsg, &referrals) != SUCCESS) {
2281        return;
2282    }
2283
2284    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2285        RETURN_FALSE;
2286    }
2287
2288    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
2289        RETURN_FALSE;
2290    }
2291
2292    rc = ldap_parse_result(ld->link, ldap_result, &lerrcode,
2293                myargcount > 3 ? &lmatcheddn : NULL,
2294                myargcount > 4 ? &lerrmsg : NULL,
2295                myargcount > 5 ? &lreferrals : NULL,
2296                NULL /* &serverctrls */,
2297                0);
2298    if (rc != LDAP_SUCCESS) {
2299        php_error_docref(NULL, E_WARNING, "Unable to parse result: %s", ldap_err2string(rc));
2300        RETURN_FALSE;
2301    }
2302
2303    zval_ptr_dtor(errcode);
2304    ZVAL_LONG(errcode, lerrcode);
2305
2306    /* Reverse -> fall through */
2307    switch (myargcount) {
2308        case 6:
2309            zval_ptr_dtor(referrals);
2310            array_init(referrals);
2311            if (lreferrals != NULL) {
2312                refp = lreferrals;
2313                while (*refp) {
2314                    add_next_index_string(referrals, *refp);
2315                    refp++;
2316                }
2317                ldap_value_free(lreferrals);
2318            }
2319        case 5:
2320            zval_ptr_dtor(errmsg);
2321            if (lerrmsg == NULL) {
2322                ZVAL_EMPTY_STRING(errmsg);
2323            } else {
2324                ZVAL_STRING(errmsg, lerrmsg);
2325                ldap_memfree(lerrmsg);
2326            }
2327        case 4:
2328            zval_ptr_dtor(matcheddn);
2329            if (lmatcheddn == NULL) {
2330                ZVAL_EMPTY_STRING(matcheddn);
2331            } else {
2332                ZVAL_STRING(matcheddn, lmatcheddn);
2333                ldap_memfree(lmatcheddn);
2334            }
2335    }
2336    RETURN_TRUE;
2337}
2338/* }}} */
2339#endif
2340
2341/* {{{ proto resource ldap_first_reference(resource link, resource result)
2342   Return first reference */
2343PHP_FUNCTION(ldap_first_reference)
2344{
2345    zval *link, *result;
2346    ldap_linkdata *ld;
2347    ldap_resultentry *resultentry;
2348    LDAPMessage *ldap_result, *entry;
2349
2350    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
2351        return;
2352    }
2353
2354    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2355        RETURN_FALSE;
2356    }
2357
2358    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
2359        RETURN_FALSE;
2360    }
2361
2362    if ((entry = ldap_first_reference(ld->link, ldap_result)) == NULL) {
2363        RETVAL_FALSE;
2364    } else {
2365        resultentry = emalloc(sizeof(ldap_resultentry));
2366        RETVAL_RES(zend_register_resource(resultentry, le_result_entry));
2367        ZVAL_COPY(&resultentry->res, result);
2368        resultentry->data = entry;
2369        resultentry->ber = NULL;
2370    }
2371}
2372/* }}} */
2373
2374/* {{{ proto resource ldap_next_reference(resource link, resource reference_entry)
2375   Get next reference */
2376PHP_FUNCTION(ldap_next_reference)
2377{
2378    zval *link, *result_entry;
2379    ldap_linkdata *ld;
2380    ldap_resultentry *resultentry, *resultentry_next;
2381    LDAPMessage *entry_next;
2382
2383    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
2384        return;
2385    }
2386
2387    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2388        RETURN_FALSE;
2389    }
2390
2391    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
2392        RETURN_FALSE;
2393    }
2394
2395    if ((entry_next = ldap_next_reference(ld->link, resultentry->data)) == NULL) {
2396        RETVAL_FALSE;
2397    } else {
2398        resultentry_next = emalloc(sizeof(ldap_resultentry));
2399        RETVAL_RES(zend_register_resource(resultentry_next, le_result_entry));
2400        ZVAL_COPY(&resultentry_next->res, &resultentry->res);
2401        resultentry_next->data = entry_next;
2402        resultentry_next->ber = NULL;
2403    }
2404}
2405/* }}} */
2406
2407#ifdef HAVE_LDAP_PARSE_REFERENCE
2408/* {{{ proto bool ldap_parse_reference(resource link, resource reference_entry, array referrals)
2409   Extract information from reference entry */
2410PHP_FUNCTION(ldap_parse_reference)
2411{
2412    zval *link, *result_entry, *referrals;
2413    ldap_linkdata *ld;
2414    ldap_resultentry *resultentry;
2415    char **lreferrals, **refp;
2416
2417    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrz/", &link, &result_entry, &referrals) != SUCCESS) {
2418        return;
2419    }
2420
2421    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2422        RETURN_FALSE;
2423    }
2424
2425    if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
2426        RETURN_FALSE;
2427    }
2428
2429    if (ldap_parse_reference(ld->link, resultentry->data, &lreferrals, NULL /* &serverctrls */, 0) != LDAP_SUCCESS) {
2430        RETURN_FALSE;
2431    }
2432
2433    zval_ptr_dtor(referrals);
2434    array_init(referrals);
2435    if (lreferrals != NULL) {
2436        refp = lreferrals;
2437        while (*refp) {
2438            add_next_index_string(referrals, *refp);
2439            refp++;
2440        }
2441        ldap_value_free(lreferrals);
2442    }
2443    RETURN_TRUE;
2444}
2445/* }}} */
2446#endif
2447
2448/* {{{ proto bool ldap_rename(resource link, string dn, string newrdn, string newparent, bool deleteoldrdn);
2449   Modify the name of an entry */
2450PHP_FUNCTION(ldap_rename)
2451{
2452    zval *link;
2453    ldap_linkdata *ld;
2454    int rc;
2455    char *dn, *newrdn, *newparent;
2456    size_t dn_len, newrdn_len, newparent_len;
2457    zend_bool deleteoldrdn;
2458
2459    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsssb", &link, &dn, &dn_len, &newrdn, &newrdn_len, &newparent, &newparent_len, &deleteoldrdn) != SUCCESS) {
2460        return;
2461    }
2462
2463    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2464        RETURN_FALSE;
2465    }
2466
2467    if (newparent_len == 0) {
2468        newparent = NULL;
2469    }
2470
2471#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
2472    rc = ldap_rename_s(ld->link, dn, newrdn, newparent, deleteoldrdn, NULL, NULL);
2473#else
2474    if (newparent_len != 0) {
2475        php_error_docref(NULL, E_WARNING, "You are using old LDAP API, newparent must be the empty string, can only modify RDN");
2476        RETURN_FALSE;
2477    }
2478/* could support old APIs but need check for ldap_modrdn2()/ldap_modrdn() */
2479    rc = ldap_modrdn2_s(ld->link, dn, newrdn, deleteoldrdn);
2480#endif
2481
2482    if (rc == LDAP_SUCCESS) {
2483        RETURN_TRUE;
2484    }
2485    RETURN_FALSE;
2486}
2487/* }}} */
2488
2489#ifdef HAVE_LDAP_START_TLS_S
2490/* {{{ proto bool ldap_start_tls(resource link)
2491   Start TLS */
2492PHP_FUNCTION(ldap_start_tls)
2493{
2494    zval *link;
2495    ldap_linkdata *ld;
2496    int rc, protocol = LDAP_VERSION3;
2497
2498    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
2499        return;
2500    }
2501
2502    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2503        RETURN_FALSE;
2504    }
2505
2506    if (((rc = ldap_set_option(ld->link, LDAP_OPT_PROTOCOL_VERSION, &protocol)) != LDAP_SUCCESS) ||
2507        ((rc = ldap_start_tls_s(ld->link, NULL, NULL)) != LDAP_SUCCESS)
2508    ) {
2509        php_error_docref(NULL, E_WARNING,"Unable to start TLS: %s", ldap_err2string(rc));
2510        RETURN_FALSE;
2511    } else {
2512        RETURN_TRUE;
2513    }
2514}
2515/* }}} */
2516#endif
2517#endif /* (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP */
2518
2519#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
2520/* {{{ _ldap_rebind_proc()
2521*/
2522int _ldap_rebind_proc(LDAP *ldap, const char *url, ber_tag_t req, ber_int_t msgid, void *params)
2523{
2524    ldap_linkdata *ld;
2525    int retval;
2526    zval cb_args[2];
2527    zval cb_retval;
2528    zval *cb_link = (zval *) params;
2529
2530    ld = (ldap_linkdata *) zend_fetch_resource_ex(cb_link, "ldap link", le_link);
2531
2532    /* link exists and callback set? */
2533    if (ld == NULL || Z_ISUNDEF(ld->rebindproc)) {
2534        php_error_docref(NULL, E_WARNING, "Link not found or no callback set");
2535        return LDAP_OTHER;
2536    }
2537
2538    /* callback */
2539    ZVAL_COPY_VALUE(&cb_args[0], cb_link);
2540    ZVAL_STRING(&cb_args[1], url);
2541    if (call_user_function_ex(EG(function_table), NULL, &ld->rebindproc, &cb_retval, 2, cb_args, 0, NULL) == SUCCESS && !Z_ISUNDEF(cb_retval)) {
2542        convert_to_long_ex(&cb_retval);
2543        retval = Z_LVAL(cb_retval);
2544        zval_ptr_dtor(&cb_retval);
2545    } else {
2546        php_error_docref(NULL, E_WARNING, "rebind_proc PHP callback failed");
2547        retval = LDAP_OTHER;
2548    }
2549    zval_ptr_dtor(&cb_args[1]);
2550    return retval;
2551}
2552/* }}} */
2553
2554/* {{{ proto bool ldap_set_rebind_proc(resource link, string callback)
2555   Set a callback function to do re-binds on referral chasing. */
2556PHP_FUNCTION(ldap_set_rebind_proc)
2557{
2558    zval *link, *callback;
2559    ldap_linkdata *ld;
2560    zend_string *callback_name;
2561
2562    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rz", &link, &callback) != SUCCESS) {
2563        RETURN_FALSE;
2564    }
2565
2566    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2567        RETURN_FALSE;
2568    }
2569
2570    if (Z_TYPE_P(callback) == IS_STRING && Z_STRLEN_P(callback) == 0) {
2571        /* unregister rebind procedure */
2572        if (!Z_ISUNDEF(ld->rebindproc)) {
2573            zval_ptr_dtor(&ld->rebindproc);
2574            ZVAL_UNDEF(&ld->rebindproc);
2575            ldap_set_rebind_proc(ld->link, NULL, NULL);
2576        }
2577        RETURN_TRUE;
2578    }
2579
2580    /* callable? */
2581    if (!zend_is_callable(callback, 0, &callback_name)) {
2582        php_error_docref(NULL, E_WARNING, "Two arguments expected for '%s' to be a valid callback", callback_name->val);
2583        zend_string_release(callback_name);
2584        RETURN_FALSE;
2585    }
2586    zend_string_release(callback_name);
2587
2588    /* register rebind procedure */
2589    if (Z_ISUNDEF(ld->rebindproc)) {
2590        ldap_set_rebind_proc(ld->link, _ldap_rebind_proc, (void *) link);
2591    } else {
2592        zval_ptr_dtor(&ld->rebindproc);
2593    }
2594
2595    ZVAL_COPY(&ld->rebindproc, callback);
2596    RETURN_TRUE;
2597}
2598/* }}} */
2599#endif
2600
2601static void php_ldap_do_escape(const zend_bool *map, const char *value, size_t valuelen, char **result, size_t *resultlen)
2602{
2603    char hex[] = "0123456789abcdef";
2604    int i, p = 0;
2605    size_t len = 0;
2606
2607    for (i = 0; i < valuelen; i++) {
2608        len += (map[(unsigned char) value[i]]) ? 3 : 1;
2609    }
2610
2611    (*result) = (char *) safe_emalloc(1, len, 1);
2612    (*resultlen) = len;
2613
2614    for (i = 0; i < valuelen; i++) {
2615        unsigned char v = (unsigned char) value[i];
2616
2617        if (map[v]) {
2618            (*result)[p++] = '\\';
2619            (*result)[p++] = hex[v >> 4];
2620            (*result)[p++] = hex[v & 0x0f];
2621        } else {
2622            (*result)[p++] = v;
2623        }
2624    }
2625
2626    (*result)[p++] = '\0';
2627}
2628
2629static void php_ldap_escape_map_set_chars(zend_bool *map, const char *chars, const int charslen, char escape)
2630{
2631    int i = 0;
2632    while (i < charslen) {
2633        map[(unsigned char) chars[i++]] = escape;
2634    }
2635}
2636
2637PHP_FUNCTION(ldap_escape)
2638{
2639    char *value, *ignores, *result;
2640    size_t valuelen = 0, ignoreslen = 0;
2641    int i;
2642    size_t resultlen;
2643    zend_long flags = 0;
2644    zend_bool map[256] = {0}, havecharlist = 0;
2645
2646    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sl", &value, &valuelen, &ignores, &ignoreslen, &flags) != SUCCESS) {
2647        return;
2648    }
2649
2650    if (!valuelen) {
2651        RETURN_EMPTY_STRING();
2652    }
2653
2654    if (flags & PHP_LDAP_ESCAPE_FILTER) {
2655        havecharlist = 1;
2656        php_ldap_escape_map_set_chars(map, "\\*()\0", sizeof("\\*()\0") - 1, 1);
2657    }
2658
2659    if (flags & PHP_LDAP_ESCAPE_DN) {
2660        havecharlist = 1;
2661        php_ldap_escape_map_set_chars(map, "\\,=+<>;\"#", sizeof("\\,=+<>;\"#") - 1, 1);
2662    }
2663
2664    if (!havecharlist) {
2665        for (i = 0; i < 256; i++) {
2666            map[i] = 1;
2667        }
2668    }
2669
2670    if (ignoreslen) {
2671        php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0);
2672    }
2673
2674    php_ldap_do_escape(map, value, valuelen, &result, &resultlen);
2675
2676    RETVAL_STRINGL(result, resultlen);
2677    efree(result);
2678}
2679
2680#ifdef STR_TRANSLATION
2681/* {{{ php_ldap_do_translate
2682 */
2683static void php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS, int way)
2684{
2685    char *value;
2686    size_t value_len;
2687    int result;
2688
2689    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) != SUCCESS) {
2690        return;
2691    }
2692
2693    if (value_len == 0) {
2694        RETURN_FALSE;
2695    }
2696
2697    if (way == 1) {
2698        result = ldap_8859_to_t61(&value, &value_len, 0);
2699    } else {
2700        result = ldap_t61_to_8859(&value, &value_len, 0);
2701    }
2702
2703    if (result == LDAP_SUCCESS) {
2704        RETVAL_STRINGL(value, value_len);
2705        free(value);
2706    } else {
2707        php_error_docref(NULL, E_WARNING, "Conversion from iso-8859-1 to t61 failed: %s", ldap_err2string(result));
2708        RETVAL_FALSE;
2709    }
2710}
2711/* }}} */
2712
2713/* {{{ proto string ldap_t61_to_8859(string value)
2714   Translate t61 characters to 8859 characters */
2715PHP_FUNCTION(ldap_t61_to_8859)
2716{
2717    php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2718}
2719/* }}} */
2720
2721/* {{{ proto string ldap_8859_to_t61(string value)
2722   Translate 8859 characters to t61 characters */
2723PHP_FUNCTION(ldap_8859_to_t61)
2724{
2725    php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2726}
2727/* }}} */
2728#endif
2729
2730#ifdef LDAP_CONTROL_PAGEDRESULTS
2731/* {{{ proto mixed ldap_control_paged_result(resource link, int pagesize [, bool iscritical [, string cookie]])
2732   Inject paged results control*/
2733PHP_FUNCTION(ldap_control_paged_result)
2734{
2735    zend_long pagesize;
2736    zend_bool iscritical;
2737    zval *link;
2738    char *cookie = NULL;
2739    size_t cookie_len = 0;
2740    struct berval lcookie = { 0, NULL };
2741    ldap_linkdata *ld;
2742    LDAP *ldap;
2743    BerElement *ber = NULL;
2744    LDAPControl ctrl, *ctrlsp[2];
2745    int rc, myargcount = ZEND_NUM_ARGS();
2746
2747    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rl|bs", &link, &pagesize, &iscritical, &cookie, &cookie_len) != SUCCESS) {
2748        return;
2749    }
2750
2751    if (Z_TYPE_P(link) == IS_NULL) {
2752        ldap = NULL;
2753    } else {
2754        if ((ld = (ldap_linkdata *)zend_fetch_resource_ex(link, "ldap link", le_link)) == NULL) {
2755            RETURN_FALSE;
2756        }
2757        ldap = ld->link;
2758    }
2759
2760    ber = ber_alloc_t(LBER_USE_DER);
2761    if (ber == NULL) {
2762        php_error_docref(NULL, E_WARNING, "Unable to alloc BER encoding resources for paged results control");
2763        RETURN_FALSE;
2764    }
2765
2766    ctrl.ldctl_iscritical = 0;
2767
2768    switch (myargcount) {
2769        case 4:
2770            lcookie.bv_val = cookie;
2771            lcookie.bv_len = cookie_len;
2772            /* fallthru */
2773        case 3:
2774            ctrl.ldctl_iscritical = (int)iscritical;
2775            /* fallthru */
2776    }
2777
2778    if (ber_printf(ber, "{iO}", (int)pagesize, &lcookie) == LBER_ERROR) {
2779        php_error_docref(NULL, E_WARNING, "Unable to BER printf paged results control");
2780        RETVAL_FALSE;
2781        goto lcpr_error_out;
2782    }
2783    rc = ber_flatten2(ber, &ctrl.ldctl_value, 0);
2784    if (rc == LBER_ERROR) {
2785        php_error_docref(NULL, E_WARNING, "Unable to BER encode paged results control");
2786        RETVAL_FALSE;
2787        goto lcpr_error_out;
2788    }
2789
2790    ctrl.ldctl_oid = LDAP_CONTROL_PAGEDRESULTS;
2791
2792    if (ldap) {
2793        /* directly set the option */
2794        ctrlsp[0] = &ctrl;
2795        ctrlsp[1] = NULL;
2796
2797        rc = ldap_set_option(ldap, LDAP_OPT_SERVER_CONTROLS, ctrlsp);
2798        if (rc != LDAP_SUCCESS) {
2799            php_error_docref(NULL, E_WARNING, "Unable to set paged results control: %s (%d)", ldap_err2string(rc), rc);
2800            RETVAL_FALSE;
2801            goto lcpr_error_out;
2802        }
2803        RETVAL_TRUE;
2804    } else {
2805        /* return a PHP control object */
2806        array_init(return_value);
2807
2808        add_assoc_string(return_value, "oid", ctrl.ldctl_oid);
2809        if (ctrl.ldctl_value.bv_len) {
2810            add_assoc_stringl(return_value, "value", ctrl.ldctl_value.bv_val, ctrl.ldctl_value.bv_len);
2811        }
2812        if (ctrl.ldctl_iscritical) {
2813            add_assoc_bool(return_value, "iscritical", ctrl.ldctl_iscritical);
2814        }
2815    }
2816
2817lcpr_error_out:
2818    if (ber != NULL) {
2819        ber_free(ber, 1);
2820    }
2821    return;
2822}
2823/* }}} */
2824
2825/* {{{ proto bool ldap_control_paged_result_response(resource link, resource result [, string &cookie [, int &estimated]])
2826   Extract paged results control response */
2827PHP_FUNCTION(ldap_control_paged_result_response)
2828{
2829    zval *link, *result, *cookie, *estimated;
2830    struct berval lcookie;
2831    int lestimated;
2832    ldap_linkdata *ld;
2833    LDAPMessage *ldap_result;
2834    LDAPControl **lserverctrls, *lctrl;
2835    BerElement *ber;
2836    ber_tag_t tag;
2837    int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
2838
2839    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|z/z/", &link, &result, &cookie, &estimated) != SUCCESS) {
2840        return;
2841    }
2842
2843    if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2844        RETURN_FALSE;
2845    }
2846
2847    if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
2848        RETURN_FALSE;
2849    }
2850
2851    rc = ldap_parse_result(ld->link,
2852                ldap_result,
2853                &lerrcode,
2854                NULL,       /* matcheddn */
2855                NULL,       /* errmsg */
2856                NULL,       /* referrals */
2857                &lserverctrls,
2858                0);
2859
2860    if (rc != LDAP_SUCCESS) {
2861        php_error_docref(NULL, E_WARNING, "Unable to parse result: %s (%d)", ldap_err2string(rc), rc);
2862        RETURN_FALSE;
2863    }
2864
2865    if (lerrcode != LDAP_SUCCESS) {
2866        php_error_docref(NULL, E_WARNING, "Result is: %s (%d)", ldap_err2string(lerrcode), lerrcode);
2867        RETURN_FALSE;
2868    }
2869
2870    if (lserverctrls == NULL) {
2871        php_error_docref(NULL, E_WARNING, "No server controls in result");
2872        RETURN_FALSE;
2873    }
2874
2875    lctrl = ldap_find_control(LDAP_CONTROL_PAGEDRESULTS, lserverctrls);
2876    if (lctrl == NULL) {
2877        ldap_controls_free(lserverctrls);
2878        php_error_docref(NULL, E_WARNING, "No paged results control response in result");
2879        RETURN_FALSE;
2880    }
2881
2882    ber = ber_init(&lctrl->ldctl_value);
2883    if (ber == NULL) {
2884        ldap_controls_free(lserverctrls);
2885        php_error_docref(NULL, E_WARNING, "Unable to alloc BER decoding resources for paged results control response");
2886        RETURN_FALSE;
2887    }
2888
2889    tag = ber_scanf(ber, "{io}", &lestimated, &lcookie);
2890    (void)ber_free(ber, 1);
2891
2892    if (tag == LBER_ERROR) {
2893        ldap_controls_free(lserverctrls);
2894        php_error_docref(NULL, E_WARNING, "Unable to decode paged results control response");
2895        RETURN_FALSE;
2896    }
2897
2898    if (lestimated < 0) {
2899        ldap_controls_free(lserverctrls);
2900        php_error_docref(NULL, E_WARNING, "Invalid paged results control response value");
2901        RETURN_FALSE;
2902    }
2903
2904    ldap_controls_free(lserverctrls);
2905    if (myargcount == 4) {
2906        zval_dtor(estimated);
2907        ZVAL_LONG(estimated, lestimated);
2908    }
2909
2910    zval_ptr_dtor(cookie);
2911    if (lcookie.bv_len == 0) {
2912        ZVAL_EMPTY_STRING(cookie);
2913    } else {
2914        ZVAL_STRINGL(cookie, lcookie.bv_val, lcookie.bv_len);
2915    }
2916    ldap_memfree(lcookie.bv_val);
2917
2918    RETURN_TRUE;
2919}
2920/* }}} */
2921#endif
2922
2923/* {{{ arginfo */
2924ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_connect, 0, 0, 0)
2925    ZEND_ARG_INFO(0, hostname)
2926    ZEND_ARG_INFO(0, port)
2927#ifdef HAVE_ORALDAP
2928    ZEND_ARG_INFO(0, wallet)
2929    ZEND_ARG_INFO(0, wallet_passwd)
2930    ZEND_ARG_INFO(0, authmode)
2931#endif
2932ZEND_END_ARG_INFO()
2933
2934ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_resource, 0, 0, 1)
2935    ZEND_ARG_INFO(0, link_identifier)
2936ZEND_END_ARG_INFO()
2937
2938ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_bind, 0, 0, 1)
2939    ZEND_ARG_INFO(0, link_identifier)
2940    ZEND_ARG_INFO(0, bind_rdn)
2941    ZEND_ARG_INFO(0, bind_password)
2942ZEND_END_ARG_INFO()
2943
2944#ifdef HAVE_LDAP_SASL
2945ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sasl_bind, 0, 0, 1)
2946    ZEND_ARG_INFO(0, link)
2947    ZEND_ARG_INFO(0, binddn)
2948    ZEND_ARG_INFO(0, password)
2949    ZEND_ARG_INFO(0, sasl_mech)
2950    ZEND_ARG_INFO(0, sasl_realm)
2951    ZEND_ARG_INFO(0, sasl_authz_id)
2952    ZEND_ARG_INFO(0, props)
2953ZEND_END_ARG_INFO()
2954#endif
2955
2956ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_read, 0, 0, 3)
2957    ZEND_ARG_INFO(0, link_identifier)
2958    ZEND_ARG_INFO(0, base_dn)
2959    ZEND_ARG_INFO(0, filter)
2960    ZEND_ARG_INFO(0, attributes)
2961    ZEND_ARG_INFO(0, attrsonly)
2962    ZEND_ARG_INFO(0, sizelimit)
2963    ZEND_ARG_INFO(0, timelimit)
2964    ZEND_ARG_INFO(0, deref)
2965ZEND_END_ARG_INFO()
2966
2967ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_list, 0, 0, 3)
2968    ZEND_ARG_INFO(0, link_identifier)
2969    ZEND_ARG_INFO(0, base_dn)
2970    ZEND_ARG_INFO(0, filter)
2971    ZEND_ARG_INFO(0, attributes)
2972    ZEND_ARG_INFO(0, attrsonly)
2973    ZEND_ARG_INFO(0, sizelimit)
2974    ZEND_ARG_INFO(0, timelimit)
2975    ZEND_ARG_INFO(0, deref)
2976ZEND_END_ARG_INFO()
2977
2978ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_search, 0, 0, 3)
2979    ZEND_ARG_INFO(0, link_identifier)
2980    ZEND_ARG_INFO(0, base_dn)
2981    ZEND_ARG_INFO(0, filter)
2982    ZEND_ARG_INFO(0, attributes)
2983    ZEND_ARG_INFO(0, attrsonly)
2984    ZEND_ARG_INFO(0, sizelimit)
2985    ZEND_ARG_INFO(0, timelimit)
2986    ZEND_ARG_INFO(0, deref)
2987ZEND_END_ARG_INFO()
2988
2989ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_count_entries, 0, 0, 2)
2990    ZEND_ARG_INFO(0, link_identifier)
2991    ZEND_ARG_INFO(0, result_identifier)
2992ZEND_END_ARG_INFO()
2993
2994ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_entry, 0, 0, 2)
2995    ZEND_ARG_INFO(0, link_identifier)
2996    ZEND_ARG_INFO(0, result_identifier)
2997ZEND_END_ARG_INFO()
2998
2999ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_entry, 0, 0, 2)
3000    ZEND_ARG_INFO(0, link_identifier)
3001    ZEND_ARG_INFO(0, result_identifier)
3002ZEND_END_ARG_INFO()
3003
3004ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_entries, 0, 0, 2)
3005    ZEND_ARG_INFO(0, link_identifier)
3006    ZEND_ARG_INFO(0, result_identifier)
3007ZEND_END_ARG_INFO()
3008
3009ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_attribute, 0, 0, 2)
3010    ZEND_ARG_INFO(0, link_identifier)
3011    ZEND_ARG_INFO(0, result_entry_identifier)
3012ZEND_END_ARG_INFO()
3013
3014ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_attribute, 0, 0, 2)
3015    ZEND_ARG_INFO(0, link_identifier)
3016    ZEND_ARG_INFO(0, result_entry_identifier)
3017ZEND_END_ARG_INFO()
3018
3019ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_attributes, 0, 0, 2)
3020    ZEND_ARG_INFO(0, link_identifier)
3021    ZEND_ARG_INFO(0, result_entry_identifier)
3022ZEND_END_ARG_INFO()
3023
3024ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values, 0, 0, 3)
3025    ZEND_ARG_INFO(0, link_identifier)
3026    ZEND_ARG_INFO(0, result_entry_identifier)
3027    ZEND_ARG_INFO(0, attribute)
3028ZEND_END_ARG_INFO()
3029
3030ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_values_len, 0, 0, 3)
3031    ZEND_ARG_INFO(0, link_identifier)
3032    ZEND_ARG_INFO(0, result_entry_identifier)
3033    ZEND_ARG_INFO(0, attribute)
3034ZEND_END_ARG_INFO()
3035
3036ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_dn, 0, 0, 2)
3037    ZEND_ARG_INFO(0, link_identifier)
3038    ZEND_ARG_INFO(0, result_entry_identifier)
3039ZEND_END_ARG_INFO()
3040
3041ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_explode_dn, 0, 0, 2)
3042    ZEND_ARG_INFO(0, dn)
3043    ZEND_ARG_INFO(0, with_attrib)
3044ZEND_END_ARG_INFO()
3045
3046ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_dn2ufn, 0, 0, 1)
3047    ZEND_ARG_INFO(0, dn)
3048ZEND_END_ARG_INFO()
3049
3050ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_add, 0, 0, 3)
3051    ZEND_ARG_INFO(0, link_identifier)
3052    ZEND_ARG_INFO(0, dn)
3053    ZEND_ARG_INFO(0, entry)
3054ZEND_END_ARG_INFO()
3055
3056ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_delete, 0, 0, 2)
3057    ZEND_ARG_INFO(0, link_identifier)
3058    ZEND_ARG_INFO(0, dn)
3059ZEND_END_ARG_INFO()
3060
3061ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify, 0, 0, 3)
3062    ZEND_ARG_INFO(0, link_identifier)
3063    ZEND_ARG_INFO(0, dn)
3064    ZEND_ARG_INFO(0, entry)
3065ZEND_END_ARG_INFO()
3066
3067ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_modify_batch, 0, 0, 3)
3068    ZEND_ARG_INFO(0, link_identifier)
3069    ZEND_ARG_INFO(0, dn)
3070    ZEND_ARG_ARRAY_INFO(0, modifications_info, 0)
3071ZEND_END_ARG_INFO()
3072
3073ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_add, 0, 0, 3)
3074    ZEND_ARG_INFO(0, link_identifier)
3075    ZEND_ARG_INFO(0, dn)
3076    ZEND_ARG_INFO(0, entry)
3077ZEND_END_ARG_INFO()
3078
3079ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_replace, 0, 0, 3)
3080    ZEND_ARG_INFO(0, link_identifier)
3081    ZEND_ARG_INFO(0, dn)
3082    ZEND_ARG_INFO(0, entry)
3083ZEND_END_ARG_INFO()
3084
3085ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_mod_del, 0, 0, 3)
3086    ZEND_ARG_INFO(0, link_identifier)
3087    ZEND_ARG_INFO(0, dn)
3088    ZEND_ARG_INFO(0, entry)
3089ZEND_END_ARG_INFO()
3090
3091ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_err2str, 0, 0, 1)
3092    ZEND_ARG_INFO(0, errno)
3093ZEND_END_ARG_INFO()
3094
3095ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_compare, 0, 0, 4)
3096    ZEND_ARG_INFO(0, link_identifier)
3097    ZEND_ARG_INFO(0, dn)
3098    ZEND_ARG_INFO(0, attribute)
3099    ZEND_ARG_INFO(0, value)
3100ZEND_END_ARG_INFO()
3101
3102ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_sort, 0, 0, 3)
3103    ZEND_ARG_INFO(0, link)
3104    ZEND_ARG_INFO(0, result)
3105    ZEND_ARG_INFO(0, sortfilter)
3106ZEND_END_ARG_INFO()
3107
3108#ifdef LDAP_CONTROL_PAGEDRESULTS
3109ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result, 0, 0, 2)
3110    ZEND_ARG_INFO(0, link)
3111    ZEND_ARG_INFO(0, pagesize)
3112    ZEND_ARG_INFO(0, iscritical)
3113    ZEND_ARG_INFO(0, cookie)
3114ZEND_END_ARG_INFO();
3115
3116ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_control_paged_result_response, 0, 0, 2)
3117    ZEND_ARG_INFO(0, link)
3118    ZEND_ARG_INFO(0, result)
3119    ZEND_ARG_INFO(1, cookie)
3120    ZEND_ARG_INFO(1, estimated)
3121ZEND_END_ARG_INFO();
3122#endif
3123
3124#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
3125ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_rename, 0, 0, 5)
3126    ZEND_ARG_INFO(0, link_identifier)
3127    ZEND_ARG_INFO(0, dn)
3128    ZEND_ARG_INFO(0, newrdn)
3129    ZEND_ARG_INFO(0, newparent)
3130    ZEND_ARG_INFO(0, deleteoldrdn)
3131ZEND_END_ARG_INFO()
3132
3133ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_get_option, 0, 0, 3)
3134    ZEND_ARG_INFO(0, link_identifier)
3135    ZEND_ARG_INFO(0, option)
3136    ZEND_ARG_INFO(1, retval)
3137ZEND_END_ARG_INFO()
3138
3139ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_option, 0, 0, 3)
3140    ZEND_ARG_INFO(0, link_identifier)
3141    ZEND_ARG_INFO(0, option)
3142    ZEND_ARG_INFO(0, newval)
3143ZEND_END_ARG_INFO()
3144
3145ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_first_reference, 0, 0, 2)
3146    ZEND_ARG_INFO(0, link)
3147    ZEND_ARG_INFO(0, result)
3148ZEND_END_ARG_INFO()
3149
3150ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_next_reference, 0, 0, 2)
3151    ZEND_ARG_INFO(0, link)
3152    ZEND_ARG_INFO(0, entry)
3153ZEND_END_ARG_INFO()
3154
3155#ifdef HAVE_LDAP_PARSE_REFERENCE
3156ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_reference, 0, 0, 3)
3157    ZEND_ARG_INFO(0, link)
3158    ZEND_ARG_INFO(0, entry)
3159    ZEND_ARG_INFO(1, referrals)
3160ZEND_END_ARG_INFO()
3161#endif
3162
3163
3164#ifdef HAVE_LDAP_PARSE_RESULT
3165ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_parse_result, 0, 0, 3)
3166    ZEND_ARG_INFO(0, link)
3167    ZEND_ARG_INFO(0, result)
3168    ZEND_ARG_INFO(1, errcode)
3169    ZEND_ARG_INFO(1, matcheddn)
3170    ZEND_ARG_INFO(1, errmsg)
3171    ZEND_ARG_INFO(1, referrals)
3172ZEND_END_ARG_INFO()
3173#endif
3174#endif
3175
3176#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3177ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_set_rebind_proc, 0, 0, 2)
3178    ZEND_ARG_INFO(0, link)
3179    ZEND_ARG_INFO(0, callback)
3180ZEND_END_ARG_INFO()
3181#endif
3182
3183ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_escape, 0, 0, 1)
3184    ZEND_ARG_INFO(0, value)
3185    ZEND_ARG_INFO(0, ignore)
3186    ZEND_ARG_INFO(0, flags)
3187ZEND_END_ARG_INFO()
3188
3189#ifdef STR_TRANSLATION
3190ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_t61_to_8859, 0, 0, 1)
3191    ZEND_ARG_INFO(0, value)
3192ZEND_END_ARG_INFO()
3193
3194ZEND_BEGIN_ARG_INFO_EX(arginfo_ldap_8859_to_t61, 0, 0, 1)
3195    ZEND_ARG_INFO(0, value)
3196ZEND_END_ARG_INFO()
3197#endif
3198/* }}} */
3199
3200/*
3201    This is just a small subset of the functionality provided by the LDAP library. All the
3202    operations are synchronous. Referrals are not handled automatically.
3203*/
3204/* {{{ ldap_functions[]
3205 */
3206const zend_function_entry ldap_functions[] = {
3207    PHP_FE(ldap_connect,                                arginfo_ldap_connect)
3208    PHP_FALIAS(ldap_close,      ldap_unbind,            arginfo_ldap_resource)
3209    PHP_FE(ldap_bind,                                   arginfo_ldap_bind)
3210#ifdef HAVE_LDAP_SASL
3211    PHP_FE(ldap_sasl_bind,                              arginfo_ldap_sasl_bind)
3212#endif
3213    PHP_FE(ldap_unbind,                                 arginfo_ldap_resource)
3214    PHP_FE(ldap_read,                                   arginfo_ldap_read)
3215    PHP_FE(ldap_list,                                   arginfo_ldap_list)
3216    PHP_FE(ldap_search,                                 arginfo_ldap_search)
3217    PHP_FE(ldap_free_result,                            arginfo_ldap_resource)
3218    PHP_FE(ldap_count_entries,                          arginfo_ldap_count_entries)
3219    PHP_FE(ldap_first_entry,                            arginfo_ldap_first_entry)
3220    PHP_FE(ldap_next_entry,                             arginfo_ldap_next_entry)
3221    PHP_FE(ldap_get_entries,                            arginfo_ldap_get_entries)
3222    PHP_FE(ldap_first_attribute,                        arginfo_ldap_first_attribute)
3223    PHP_FE(ldap_next_attribute,                         arginfo_ldap_next_attribute)
3224    PHP_FE(ldap_get_attributes,                         arginfo_ldap_get_attributes)
3225    PHP_FALIAS(ldap_get_values, ldap_get_values_len,    arginfo_ldap_get_values)
3226    PHP_FE(ldap_get_values_len,                         arginfo_ldap_get_values_len)
3227    PHP_FE(ldap_get_dn,                                 arginfo_ldap_get_dn)
3228    PHP_FE(ldap_explode_dn,                             arginfo_ldap_explode_dn)
3229    PHP_FE(ldap_dn2ufn,                                 arginfo_ldap_dn2ufn)
3230    PHP_FE(ldap_add,                                    arginfo_ldap_add)
3231    PHP_FE(ldap_delete,                                 arginfo_ldap_delete)
3232    PHP_FE(ldap_modify_batch,                           arginfo_ldap_modify_batch)
3233    PHP_FALIAS(ldap_modify,     ldap_mod_replace,       arginfo_ldap_modify)
3234
3235/* additional functions for attribute based modifications, Gerrit Thomson */
3236    PHP_FE(ldap_mod_add,                                arginfo_ldap_mod_add)
3237    PHP_FE(ldap_mod_replace,                            arginfo_ldap_mod_replace)
3238    PHP_FE(ldap_mod_del,                                arginfo_ldap_mod_del)
3239/* end gjt mod */
3240
3241    PHP_FE(ldap_errno,                                  arginfo_ldap_resource)
3242    PHP_FE(ldap_err2str,                                arginfo_ldap_err2str)
3243    PHP_FE(ldap_error,                                  arginfo_ldap_resource)
3244    PHP_FE(ldap_compare,                                arginfo_ldap_compare)
3245    PHP_FE(ldap_sort,                                   arginfo_ldap_sort)
3246
3247#if (LDAP_API_VERSION > 2000) || HAVE_NSLDAP || HAVE_ORALDAP
3248    PHP_FE(ldap_rename,                                 arginfo_ldap_rename)
3249    PHP_FE(ldap_get_option,                             arginfo_ldap_get_option)
3250    PHP_FE(ldap_set_option,                             arginfo_ldap_set_option)
3251    PHP_FE(ldap_first_reference,                        arginfo_ldap_first_reference)
3252    PHP_FE(ldap_next_reference,                         arginfo_ldap_next_reference)
3253#ifdef HAVE_LDAP_PARSE_REFERENCE
3254    PHP_FE(ldap_parse_reference,                        arginfo_ldap_parse_reference)
3255#endif
3256#ifdef HAVE_LDAP_PARSE_RESULT
3257    PHP_FE(ldap_parse_result,                           arginfo_ldap_parse_result)
3258#endif
3259#ifdef HAVE_LDAP_START_TLS_S
3260    PHP_FE(ldap_start_tls,                              arginfo_ldap_resource)
3261#endif
3262#endif
3263
3264#if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3265    PHP_FE(ldap_set_rebind_proc,                        arginfo_ldap_set_rebind_proc)
3266#endif
3267
3268    PHP_FE(ldap_escape,                                 arginfo_ldap_escape)
3269
3270#ifdef STR_TRANSLATION
3271    PHP_FE(ldap_t61_to_8859,                            arginfo_ldap_t61_to_8859)
3272    PHP_FE(ldap_8859_to_t61,                            arginfo_ldap_8859_to_t61)
3273#endif
3274
3275#ifdef LDAP_CONTROL_PAGEDRESULTS
3276    PHP_FE(ldap_control_paged_result,                           arginfo_ldap_control_paged_result)
3277    PHP_FE(ldap_control_paged_result_response,      arginfo_ldap_control_paged_result_response)
3278#endif
3279    PHP_FE_END
3280};
3281/* }}} */
3282
3283zend_module_entry ldap_module_entry = { /* {{{ */
3284    STANDARD_MODULE_HEADER,
3285    "ldap",
3286    ldap_functions,
3287    PHP_MINIT(ldap),
3288    PHP_MSHUTDOWN(ldap),
3289    NULL,
3290    NULL,
3291    PHP_MINFO(ldap),
3292    PHP_LDAP_VERSION,
3293    PHP_MODULE_GLOBALS(ldap),
3294    PHP_GINIT(ldap),
3295    NULL,
3296    NULL,
3297    STANDARD_MODULE_PROPERTIES_EX
3298};
3299/* }}} */
3300
3301/*
3302 * Local variables:
3303 * tab-width: 4
3304 * c-basic-offset: 4
3305 * End:
3306 * vim600: sw=4 ts=4 fdm=marker
3307 * vim<600: sw=4 ts=4
3308 */
3309