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