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