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