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