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