xref: /PHP-8.2/ext/ldap/ldap.c (revision f4c45ee3)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | https://www.php.net/license/3_01.txt                                 |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Amitay Isaacs  <amitay@w-o-i.com>                           |
14    |          Eric Warnke    <ericw@albany.edu>                           |
15    |          Rasmus Lerdorf <rasmus@php.net>                             |
16    |          Gerrit Thomson <334647@swin.edu.au>                         |
17    |          Jani Taskinen  <sniper@iki.fi>                              |
18    |          Stig Venaas    <venaas@uninett.no>                          |
19    |          Doug Goldstein <cardoe@cardoe.com>                          |
20    |          Côme Chilliet  <mcmic@php.net>                              |
21    | PHP 4.0 updates:  Zeev Suraski <zeev@php.net>                        |
22    +----------------------------------------------------------------------+
23  */
24 
25 #ifdef HAVE_CONFIG_H
26 #include "config.h"
27 #endif
28 
29 #include "php.h"
30 #include "php_ini.h"
31 #include "Zend/zend_attributes.h"
32 
33 #include <stddef.h>
34 
35 #include "ext/standard/dl.h"
36 #include "php_ldap.h"
37 
38 #ifdef PHP_WIN32
39 #include <string.h>
40 #include "config.w32.h"
41 #undef WINDOWS
42 #undef strcasecmp
43 #undef strncasecmp
44 #define WINSOCK 1
45 #define __STDC__ 1
46 #endif
47 
48 #include "ext/standard/info.h"
49 
50 #ifdef HAVE_LDAP_SASL
51 #include <sasl/sasl.h>
52 #endif
53 
54 #define PHP_LDAP_ESCAPE_FILTER 0x01
55 #define PHP_LDAP_ESCAPE_DN     0x02
56 
57 #include "ldap_arginfo.h"
58 
59 #if defined(LDAP_CONTROL_PAGEDRESULTS) && !defined(HAVE_LDAP_CONTROL_FIND)
ldap_control_find(const char * oid,LDAPControl ** ctrls,LDAPControl *** nextctrlp)60 LDAPControl *ldap_control_find( const char *oid, LDAPControl **ctrls, LDAPControl ***nextctrlp)
61 {
62 	assert(nextctrlp == NULL);
63 	return ldap_find_control(oid, ctrls);
64 }
65 #endif
66 
67 #if !defined(LDAP_API_FEATURE_X_OPENLDAP)
ldap_memvfree(void ** v)68 void ldap_memvfree(void **v)
69 {
70 	ldap_value_free((char **)v);
71 }
72 #endif
73 
74 typedef struct {
75 	LDAP *link;
76 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
77 	zval rebindproc;
78 #endif
79 	zend_object std;
80 } ldap_linkdata;
81 
82 typedef struct {
83 	LDAPMessage *result;
84 	zend_object std;
85 } ldap_resultdata;
86 
87 typedef struct {
88 	LDAPMessage *data;
89 	BerElement  *ber;
90 	zval         res;
91 	zend_object std;
92 } ldap_result_entry;
93 
94 ZEND_DECLARE_MODULE_GLOBALS(ldap)
95 static PHP_GINIT_FUNCTION(ldap);
96 
97 static zend_class_entry *ldap_link_ce, *ldap_result_ce, *ldap_result_entry_ce;
98 static zend_object_handlers ldap_link_object_handlers, ldap_result_object_handlers, ldap_result_entry_object_handlers;
99 
100 #ifdef COMPILE_DL_LDAP
101 #ifdef ZTS
102 ZEND_TSRMLS_CACHE_DEFINE()
103 #endif
ZEND_GET_MODULE(ldap)104 ZEND_GET_MODULE(ldap)
105 #endif
106 
107 static inline ldap_linkdata *ldap_link_from_obj(zend_object *obj) {
108 	return (ldap_linkdata *)((char *)(obj) - XtOffsetOf(ldap_linkdata, std));
109 }
110 
111 #define Z_LDAP_LINK_P(zv) ldap_link_from_obj(Z_OBJ_P(zv))
112 
ldap_link_create_object(zend_class_entry * class_type)113 static zend_object *ldap_link_create_object(zend_class_entry *class_type) {
114 	ldap_linkdata *intern = zend_object_alloc(sizeof(ldap_linkdata), class_type);
115 
116 	zend_object_std_init(&intern->std, class_type);
117 	object_properties_init(&intern->std, class_type);
118 	intern->std.handlers = &ldap_link_object_handlers;
119 
120 	return &intern->std;
121 }
122 
ldap_link_get_constructor(zend_object * object)123 static zend_function *ldap_link_get_constructor(zend_object *object) {
124 	zend_throw_error(NULL, "Cannot directly construct LDAP\\Connection, use ldap_connect() instead");
125 	return NULL;
126 }
127 
ldap_link_free(ldap_linkdata * ld)128 static void ldap_link_free(ldap_linkdata *ld)
129 {
130 	/* We use ldap_destroy rather than ldap_unbind here, because ldap_unbind
131 	 * will skip the destructor entirely if a critical client control is set. */
132 	ldap_destroy(ld->link);
133 	ld->link = NULL;
134 
135 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
136 	zval_ptr_dtor(&ld->rebindproc);
137 #endif
138 
139 	LDAPG(num_links)--;
140 }
141 
ldap_link_free_obj(zend_object * obj)142 static void ldap_link_free_obj(zend_object *obj)
143 {
144 	ldap_linkdata *ld = ldap_link_from_obj(obj);
145 
146 	if (ld->link) {
147 		ldap_link_free(ld);
148 	}
149 
150 	zend_object_std_dtor(&ld->std);
151 }
152 
ldap_result_from_obj(zend_object * obj)153 static inline ldap_resultdata *ldap_result_from_obj(zend_object *obj) {
154 	return (ldap_resultdata *)((char *)(obj) - XtOffsetOf(ldap_resultdata, std));
155 }
156 
157 #define Z_LDAP_RESULT_P(zv) ldap_result_from_obj(Z_OBJ_P(zv))
158 
ldap_result_create_object(zend_class_entry * class_type)159 static zend_object *ldap_result_create_object(zend_class_entry *class_type) {
160 	ldap_resultdata *intern = zend_object_alloc(sizeof(ldap_resultdata), class_type);
161 
162 	zend_object_std_init(&intern->std, class_type);
163 	object_properties_init(&intern->std, class_type);
164 	intern->std.handlers = &ldap_result_object_handlers;
165 
166 	return &intern->std;
167 }
168 
ldap_result_get_constructor(zend_object * object)169 static zend_function *ldap_result_get_constructor(zend_object *object) {
170 	zend_throw_error(NULL, "Cannot directly construct LDAP\\Result, use the dedicated functions instead");
171 	return NULL;
172 }
173 
ldap_result_free(ldap_resultdata * result)174 static void ldap_result_free(ldap_resultdata *result)
175 {
176 	ldap_msgfree(result->result);
177 	result->result = NULL;
178 }
179 
ldap_result_free_obj(zend_object * obj)180 static void ldap_result_free_obj(zend_object *obj)
181 {
182 	ldap_resultdata *result = ldap_result_from_obj(obj);
183 
184 	if (result->result) {
185 		ldap_result_free(result);
186 	}
187 
188 	zend_object_std_dtor(&result->std);
189 }
190 
ldap_result_entry_from_obj(zend_object * obj)191 static inline ldap_result_entry *ldap_result_entry_from_obj(zend_object *obj) {
192 	return (ldap_result_entry *)((char *)(obj) - XtOffsetOf(ldap_result_entry, std));
193 }
194 
195 #define Z_LDAP_RESULT_ENTRY_P(zv) ldap_result_entry_from_obj(Z_OBJ_P(zv))
196 
ldap_result_entry_create_object(zend_class_entry * class_type)197 static zend_object *ldap_result_entry_create_object(zend_class_entry *class_type) {
198 	ldap_result_entry *intern = zend_object_alloc(sizeof(ldap_result_entry), class_type);
199 
200 	zend_object_std_init(&intern->std, class_type);
201 	object_properties_init(&intern->std, class_type);
202 	intern->std.handlers = &ldap_result_entry_object_handlers;
203 
204 	return &intern->std;
205 }
206 
ldap_result_entry_get_constructor(zend_object * obj)207 static zend_function *ldap_result_entry_get_constructor(zend_object *obj) {
208 	zend_throw_error(NULL, "Cannot directly construct LDAP\\ResultEntry, use the dedicated functions instead");
209 	return NULL;
210 }
211 
ldap_result_entry_free_obj(zend_object * obj)212 static void ldap_result_entry_free_obj(zend_object *obj)
213 {
214 	ldap_result_entry *entry = ldap_result_entry_from_obj(obj);
215 
216 	if (entry->ber != NULL) {
217 		ber_free(entry->ber, 0);
218 		entry->ber = NULL;
219 	}
220 	zval_ptr_dtor(&entry->res);
221 
222 	zend_object_std_dtor(&entry->std);
223 }
224 
225 #define VERIFY_LDAP_LINK_CONNECTED(ld) \
226 { \
227 	if (!ld->link) { \
228 		zend_throw_error(NULL, "LDAP connection has already been closed"); \
229 		RETURN_THROWS(); \
230 	} \
231 }
232 
233 #define VERIFY_LDAP_RESULT_OPEN(lr) \
234 { \
235 	if (!lr->result) { \
236 		zend_throw_error(NULL, "LDAP result has already been closed"); \
237 		RETURN_THROWS(); \
238 	} \
239 }
240 
241 /* {{{ Parse controls from and to arrays */
_php_ldap_control_to_array(LDAP * ld,LDAPControl * ctrl,zval * array,int request)242 static void _php_ldap_control_to_array(LDAP *ld, LDAPControl* ctrl, zval* array, int request)
243 {
244 	array_init(array);
245 
246 	add_assoc_string(array, "oid", ctrl->ldctl_oid);
247 	if (request) {
248 		/* iscritical field only makes sense in request controls (which may be obtained by ldap_get_option) */
249 		add_assoc_bool(array, "iscritical", (ctrl->ldctl_iscritical != 0));
250 	}
251 
252 	/* If it is a known oid, parse to values */
253 	if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PASSWORDPOLICYRESPONSE) == 0) {
254 		int expire = 0, grace = 0, rc;
255 		LDAPPasswordPolicyError pperr;
256 		zval value;
257 
258 		rc = ldap_parse_passwordpolicy_control(ld, ctrl, &expire, &grace, &pperr);
259 		if ( rc == LDAP_SUCCESS ) {
260 			array_init(&value);
261 			add_assoc_long(&value, "expire", expire);
262 			add_assoc_long(&value, "grace", grace);
263 
264 			if ( pperr != PP_noError ) {
265 				add_assoc_long(&value, "error", pperr);
266 			}
267 			add_assoc_zval(array, "value", &value);
268 		} else {
269 			add_assoc_null(array, "value");
270 		}
271 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS) == 0) {
272 		int lestimated, rc;
273 		struct berval lcookie = { 0L, NULL };
274 		zval value;
275 
276 		if (ctrl->ldctl_value.bv_len) {
277 			/* ldap_parse_pageresponse_control() allocates lcookie.bv_val */
278 			rc = ldap_parse_pageresponse_control(ld, ctrl, &lestimated, &lcookie);
279 		} else {
280 			/* ldap_parse_pageresponse_control will crash if value is empty */
281 			rc = -1;
282 		}
283 
284 		if ( rc == LDAP_SUCCESS ) {
285 			array_init(&value);
286 			add_assoc_long(&value, "size", lestimated);
287 			add_assoc_stringl(&value, "cookie", lcookie.bv_val, lcookie.bv_len);
288 			add_assoc_zval(array, "value", &value);
289 		} else {
290 			add_assoc_null(array, "value");
291 		}
292 
293 		if (lcookie.bv_val) {
294 			ldap_memfree(lcookie.bv_val);
295 		}
296 	} else if ((strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PRE_READ) == 0) || (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_POST_READ) == 0)) {
297 		BerElement *ber;
298 		struct berval bv;
299 
300 		ber = ber_init(&ctrl->ldctl_value);
301 		if (ber == NULL) {
302 			add_assoc_null(array, "value");
303 		} else if (ber_scanf(ber, "{m{" /*}}*/, &bv) == LBER_ERROR) {
304 			add_assoc_null(array, "value");
305 		} else {
306 			zval value;
307 
308 			array_init(&value);
309 			add_assoc_stringl(&value, "dn", bv.bv_val, bv.bv_len);
310 
311 			while (ber_scanf(ber, "{m" /*}*/, &bv) != LBER_ERROR) {
312 				int	 i;
313 				BerVarray vals = NULL;
314 				zval tmp;
315 
316 				if (ber_scanf(ber, "[W]", &vals) == LBER_ERROR || vals == NULL)
317 				{
318 					break;
319 				}
320 
321 				array_init(&tmp);
322 				for (i = 0; vals[i].bv_val != NULL; i++) {
323 					add_next_index_stringl(&tmp, vals[i].bv_val, vals[i].bv_len);
324 				}
325 				add_assoc_zval(&value, bv.bv_val, &tmp);
326 
327 				ber_bvarray_free(vals);
328 			}
329 			add_assoc_zval(array, "value", &value);
330 		}
331 
332 		if (ber != NULL) {
333 			ber_free(ber, 1);
334 		}
335 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_SORTRESPONSE) == 0) {
336 		zval value;
337 		int errcode, rc;
338 		char* attribute;
339 
340 		if (ctrl->ldctl_value.bv_len) {
341 			rc = ldap_parse_sortresponse_control(ld, ctrl, &errcode, &attribute);
342 		} else {
343 			rc = -1;
344 		}
345 		if ( rc == LDAP_SUCCESS ) {
346 			array_init(&value);
347 			add_assoc_long(&value, "errcode", errcode);
348 			if (attribute) {
349 				add_assoc_string(&value, "attribute", attribute);
350 				ldap_memfree(attribute);
351 			}
352 			add_assoc_zval(array, "value", &value);
353 		} else {
354 			add_assoc_null(array, "value");
355 		}
356 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_VLVRESPONSE) == 0) {
357 		int target, count, errcode, rc;
358 		struct berval *context;
359 		zval value;
360 
361 		if (ctrl->ldctl_value.bv_len) {
362 			rc = ldap_parse_vlvresponse_control(ld, ctrl, &target, &count, &context, &errcode);
363 		} else {
364 			rc = -1;
365 		}
366 		if ( rc == LDAP_SUCCESS ) {
367 			array_init(&value);
368 			add_assoc_long(&value, "target", target);
369 			add_assoc_long(&value, "count", count);
370 			add_assoc_long(&value, "errcode", errcode);
371 			if (context) {
372 				add_assoc_stringl(&value, "context", context->bv_val, context->bv_len);
373 			}
374 			add_assoc_zval(array, "value", &value);
375 			ber_bvfree(context);
376 		} else {
377 			add_assoc_null(array, "value");
378 		}
379 	} else {
380 		if (ctrl->ldctl_value.bv_len) {
381 			add_assoc_stringl(array, "value", ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len);
382 		} else {
383 			add_assoc_null(array, "value");
384 		}
385 	}
386 }
387 
_php_ldap_control_from_array(LDAP * ld,LDAPControl ** ctrl,zval * array)388 static int _php_ldap_control_from_array(LDAP *ld, LDAPControl** ctrl, zval* array)
389 {
390 	zval* val;
391 	zend_string *control_oid;
392 	int control_iscritical = 0, rc = LDAP_SUCCESS;
393 	char** ldap_attrs = NULL;
394 	LDAPSortKey** sort_keys = NULL;
395 	zend_string *tmpstring = NULL, **tmpstrings1 = NULL, **tmpstrings2 = NULL;
396 	size_t num_tmpstrings1 = 0, num_tmpstrings2 = 0;
397 
398 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "oid", sizeof("oid") - 1)) == NULL) {
399 		zend_value_error("%s(): Control must have an \"oid\" key", get_active_function_name());
400 		return -1;
401 	}
402 
403 	control_oid = zval_get_string(val);
404 	if (EG(exception)) {
405 		return -1;
406 	}
407 
408 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "iscritical", sizeof("iscritical") - 1)) != NULL) {
409 		control_iscritical = zend_is_true(val);
410 	} else {
411 		control_iscritical = 0;
412 	}
413 
414 	BerElement *ber = NULL;
415 	struct berval control_value = { 0L, NULL };
416 	int control_value_alloc = 0;
417 
418 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "value", sizeof("value") - 1)) != NULL) {
419 		if (Z_TYPE_P(val) != IS_ARRAY) {
420 			tmpstring = zval_get_string(val);
421 			if (EG(exception)) {
422 				rc = -1;
423 				goto failure;
424 			}
425 			control_value.bv_val = ZSTR_VAL(tmpstring);
426 			control_value.bv_len = ZSTR_LEN(tmpstring);
427 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_PAGEDRESULTS) == 0) {
428 			zval* tmp;
429 			int pagesize = 1;
430 			struct berval cookie = { 0L, NULL };
431 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "size", sizeof("size") - 1)) != NULL) {
432 				pagesize = zval_get_long(tmp);
433 			}
434 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "cookie", sizeof("cookie") - 1)) != NULL) {
435 				tmpstring = zval_get_string(tmp);
436 				if (EG(exception)) {
437 					rc = -1;
438 					goto failure;
439 				}
440 				cookie.bv_val = ZSTR_VAL(tmpstring);
441 				cookie.bv_len = ZSTR_LEN(tmpstring);
442 			}
443 			/* ldap_create_page_control_value() allocates memory for control_value.bv_val */
444 			control_value_alloc = 1;
445 			rc = ldap_create_page_control_value(ld, pagesize, &cookie, &control_value);
446 			if (rc != LDAP_SUCCESS) {
447 				php_error_docref(NULL, E_WARNING, "Failed to create paged result control value: %s (%d)", ldap_err2string(rc), rc);
448 			}
449 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_ASSERT) == 0) {
450 			zval* tmp;
451 			zend_string* assert;
452 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "filter", sizeof("filter") - 1)) == NULL) {
453 				rc = -1;
454 				zend_value_error("%s(): Control must have a \"filter\" key", get_active_function_name());
455 			} else {
456 				assert = zval_get_string(tmp);
457 				if (EG(exception)) {
458 					rc = -1;
459 					goto failure;
460 				}
461 				/* ldap_create_assertion_control_value does not reset ld_errno, we need to do it ourselves
462 					 See http://www.openldap.org/its/index.cgi/Incoming?id=8674 */
463 				int success = LDAP_SUCCESS;
464 				ldap_set_option(ld, LDAP_OPT_RESULT_CODE, &success);
465 				/* ldap_create_assertion_control_value() allocates memory for control_value.bv_val */
466 				control_value_alloc = 1;
467 				rc = ldap_create_assertion_control_value(ld, ZSTR_VAL(assert), &control_value);
468 				if (rc != LDAP_SUCCESS) {
469 					php_error_docref(NULL, E_WARNING, "Failed to create assert control value: %s (%d)", ldap_err2string(rc), rc);
470 				}
471 				zend_string_release(assert);
472 			}
473 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_VALUESRETURNFILTER) == 0) {
474 			zval* tmp;
475 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "filter", sizeof("filter") - 1)) == NULL) {
476 				rc = -1;
477 				zend_value_error("%s(): Control must have a \"filter\" key", get_active_function_name());
478 			} else {
479 				ber = ber_alloc_t(LBER_USE_DER);
480 				if (ber == NULL) {
481 					rc = -1;
482 					php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
483 				} else {
484 					tmpstring = zval_get_string(tmp);
485 					if (EG(exception)) {
486 						rc = -1;
487 						goto failure;
488 					}
489 					if (ldap_put_vrFilter(ber, ZSTR_VAL(tmpstring)) == -1) {
490 						rc = -1;
491 						php_error_docref(NULL, E_WARNING, "Failed to create control value: Bad ValuesReturnFilter: %s", ZSTR_VAL(tmpstring));
492 					} else if (ber_flatten2(ber, &control_value, control_value_alloc) == -1) {
493 						rc = -1;
494 					}
495 				}
496 			}
497 		} else if ((strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_PRE_READ) == 0) || (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_POST_READ) == 0)) {
498 			zval* tmp;
499 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "attrs", sizeof("attrs") - 1)) == NULL) {
500 				rc = -1;
501 				zend_value_error("%s(): Control must have an \"attrs\" key", get_active_function_name());
502 			} else {
503 				ber = ber_alloc_t(LBER_USE_DER);
504 
505 				if (ber == NULL) {
506 					rc = -1;
507 					php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
508 				} else {
509 					int num_attribs, i;
510 					zval* attr;
511 
512 					num_attribs = zend_hash_num_elements(Z_ARRVAL_P(tmp));
513 					ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
514 					tmpstrings1 = safe_emalloc(num_attribs, sizeof(zend_string*), 0);
515 					num_tmpstrings1 = 0;
516 
517 					for (i = 0; i<num_attribs; i++) {
518 						if ((attr = zend_hash_index_find(Z_ARRVAL_P(tmp), i)) == NULL) {
519 							rc = -1;
520 							php_error_docref(NULL, E_WARNING, "Failed to encode attribute list");
521 							goto failure;
522 						}
523 
524 						tmpstrings1[num_tmpstrings1] = zval_get_string(attr);
525 						if (EG(exception)) {
526 							rc = -1;
527 							goto failure;
528 						}
529 						ldap_attrs[i] = ZSTR_VAL(tmpstrings1[num_tmpstrings1]);
530 						++num_tmpstrings1;
531 					}
532 					ldap_attrs[num_attribs] = NULL;
533 
534 					ber_init2( ber, NULL, LBER_USE_DER );
535 
536 					if (ber_printf(ber, "{v}", ldap_attrs) == -1) {
537 						rc = -1;
538 						php_error_docref(NULL, E_WARNING, "Failed to encode attribute list");
539 					} else {
540 						int err;
541 						err = ber_flatten2(ber, &control_value, control_value_alloc);
542 						if (err < 0) {
543 							rc = -1;
544 							php_error_docref(NULL, E_WARNING, "Failed to encode control value (%d)", err);
545 						}
546 					}
547 				}
548 			}
549 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_SORTREQUEST) == 0) {
550 			int num_keys, i;
551 			zval *sortkey, *tmp;
552 
553 			num_keys = zend_hash_num_elements(Z_ARRVAL_P(val));
554 			sort_keys = safe_emalloc((num_keys+1), sizeof(LDAPSortKey*), 0);
555 			tmpstrings1 = safe_emalloc(num_keys, sizeof(zend_string*), 0);
556 			tmpstrings2 = safe_emalloc(num_keys, sizeof(zend_string*), 0);
557 			num_tmpstrings1 = 0;
558 			num_tmpstrings2 = 0;
559 
560 			for (i = 0; i<num_keys; i++) {
561 				if ((sortkey = zend_hash_index_find(Z_ARRVAL_P(val), i)) == NULL) {
562 					rc = -1;
563 					php_error_docref(NULL, E_WARNING, "Failed to encode sort keys list");
564 					goto failure;
565 				}
566 
567 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "attr", sizeof("attr") - 1)) == NULL) {
568 					rc = -1;
569 					zend_value_error("%s(): Sort key list must have an \"attr\" key", get_active_function_name());
570 					goto failure;
571 				}
572 				sort_keys[i] = emalloc(sizeof(LDAPSortKey));
573 				tmpstrings1[num_tmpstrings1] = zval_get_string(tmp);
574 				if (EG(exception)) {
575 					rc = -1;
576 					goto failure;
577 				}
578 				sort_keys[i]->attributeType = ZSTR_VAL(tmpstrings1[num_tmpstrings1]);
579 				++num_tmpstrings1;
580 
581 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "oid", sizeof("oid") - 1)) != NULL) {
582 					tmpstrings2[num_tmpstrings2] = zval_get_string(tmp);
583 					if (EG(exception)) {
584 						rc = -1;
585 						goto failure;
586 					}
587 					sort_keys[i]->orderingRule = ZSTR_VAL(tmpstrings2[num_tmpstrings2]);
588 					++num_tmpstrings2;
589 				} else {
590 					sort_keys[i]->orderingRule = NULL;
591 				}
592 
593 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "reverse", sizeof("reverse") - 1)) != NULL) {
594 					sort_keys[i]->reverseOrder = zend_is_true(tmp);
595 				} else {
596 					sort_keys[i]->reverseOrder = 0;
597 				}
598 			}
599 			sort_keys[num_keys] = NULL;
600 			/* ldap_create_sort_control_value() allocates memory for control_value.bv_val */
601 			control_value_alloc = 1;
602 			rc = ldap_create_sort_control_value(ld, sort_keys, &control_value);
603 			if (rc != LDAP_SUCCESS) {
604 				php_error_docref(NULL, E_WARNING, "Failed to create sort control value: %s (%d)", ldap_err2string(rc), rc);
605 			}
606 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_VLVREQUEST) == 0) {
607 			zval* tmp;
608 			LDAPVLVInfo vlvInfo;
609 			struct berval attrValue;
610 			struct berval context;
611 
612 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "before", sizeof("before") - 1)) != NULL) {
613 				vlvInfo.ldvlv_before_count = zval_get_long(tmp);
614 			} else {
615 				rc = -1;
616 				zend_value_error("%s(): Array value for VLV control must have a \"before\" key", get_active_function_name());
617 				goto failure;
618 			}
619 
620 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "after", sizeof("after") - 1)) != NULL) {
621 				vlvInfo.ldvlv_after_count = zval_get_long(tmp);
622 			} else {
623 				rc = -1;
624 				zend_value_error("%s(): Array value for VLV control must have an \"after\" key", get_active_function_name());
625 				goto failure;
626 			}
627 
628 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "attrvalue", sizeof("attrvalue") - 1)) != NULL) {
629 				tmpstring = zval_get_string(tmp);
630 				if (EG(exception)) {
631 					rc = -1;
632 					goto failure;
633 				}
634 				attrValue.bv_val = ZSTR_VAL(tmpstring);
635 				attrValue.bv_len = ZSTR_LEN(tmpstring);
636 				vlvInfo.ldvlv_attrvalue = &attrValue;
637 			} else if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "offset", sizeof("offset") - 1)) != NULL) {
638 				vlvInfo.ldvlv_attrvalue = NULL;
639 				vlvInfo.ldvlv_offset = zval_get_long(tmp);
640 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "count", sizeof("count") - 1)) != NULL) {
641 					vlvInfo.ldvlv_count = zval_get_long(tmp);
642 				} else {
643 					rc = -1;
644 					zend_value_error("%s(): Array value for VLV control must have a \"count\" key", get_active_function_name());
645 					goto failure;
646 				}
647 			} else {
648 				rc = -1;
649 				zend_value_error("%s(): Array value for VLV control must have either an \"attrvalue\" or an \"offset\" key", get_active_function_name());
650 				goto failure;
651 			}
652 
653 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "context", sizeof("context") - 1)) != NULL) {
654 				tmpstring = zval_get_string(tmp);
655 				if (EG(exception)) {
656 					rc = -1;
657 					goto failure;
658 				}
659 				context.bv_val = ZSTR_VAL(tmpstring);
660 				context.bv_len = ZSTR_LEN(tmpstring);
661 				vlvInfo.ldvlv_context = &context;
662 			} else {
663 				vlvInfo.ldvlv_context = NULL;
664 			}
665 
666 			/* ldap_create_vlv_control_value() allocates memory for control_value.bv_val */
667 			control_value_alloc = 1;
668 			rc = ldap_create_vlv_control_value(ld, &vlvInfo, &control_value);
669 			if (rc != LDAP_SUCCESS) {
670 				php_error_docref(NULL, E_WARNING, "Failed to create VLV control value: %s (%d)", ldap_err2string(rc), rc);
671 			}
672 		} else {
673 			zend_type_error("%s(): Control OID %s cannot be of type array", get_active_function_name(), ZSTR_VAL(control_oid));
674 			rc = -1;
675 		}
676 	}
677 
678 	if (rc == LDAP_SUCCESS) {
679 		rc = ldap_control_create(ZSTR_VAL(control_oid), control_iscritical, &control_value, 1, ctrl);
680 	}
681 
682 failure:
683 	zend_string_release(control_oid);
684 	if (tmpstring != NULL) {
685 		zend_string_release(tmpstring);
686 	}
687 	if (tmpstrings1 != NULL) {
688 		int i;
689 		for (i = 0; i < num_tmpstrings1; ++i) {
690 			zend_string_release(tmpstrings1[i]);
691 		}
692 		efree(tmpstrings1);
693 	}
694 	if (tmpstrings2 != NULL) {
695 		int i;
696 		for (i = 0; i < num_tmpstrings2; ++i) {
697 			zend_string_release(tmpstrings2[i]);
698 		}
699 		efree(tmpstrings2);
700 	}
701 	if (control_value.bv_val != NULL && control_value_alloc != 0) {
702 		ber_memfree(control_value.bv_val);
703 	}
704 	if (ber != NULL) {
705 		ber_free(ber, 1);
706 	}
707 	if (ldap_attrs != NULL) {
708 		efree(ldap_attrs);
709 	}
710 	if (sort_keys != NULL) {
711 		LDAPSortKey** sortp = sort_keys;
712 		while (*sortp) {
713 			efree(*sortp);
714 			sortp++;
715 		}
716 		efree(sort_keys);
717 		sort_keys = NULL;
718 	}
719 
720 	if (rc == LDAP_SUCCESS) {
721 		return LDAP_SUCCESS;
722 	}
723 
724 	/* Failed */
725 	*ctrl = NULL;
726 	return -1;
727 }
728 
_php_ldap_controls_to_array(LDAP * ld,LDAPControl ** ctrls,zval * array,int request)729 static void _php_ldap_controls_to_array(LDAP *ld, LDAPControl** ctrls, zval* array, int request)
730 {
731 	zval tmp1;
732 	LDAPControl **ctrlp;
733 
734 	array = zend_try_array_init(array);
735 	if (!array) {
736 		return;
737 	}
738 
739 	if (ctrls == NULL) {
740 		return;
741 	}
742 	ctrlp = ctrls;
743 	while (*ctrlp != NULL) {
744 		_php_ldap_control_to_array(ld, *ctrlp, &tmp1, request);
745 		add_assoc_zval(array, (*ctrlp)->ldctl_oid, &tmp1);
746 		ctrlp++;
747 	}
748 	ldap_controls_free(ctrls);
749 }
750 
_php_ldap_controls_from_array(LDAP * ld,zval * array,uint32_t arg_num)751 static LDAPControl** _php_ldap_controls_from_array(LDAP *ld, zval* array, uint32_t arg_num)
752 {
753 	int ncontrols;
754 	LDAPControl** ctrlp, **ctrls = NULL;
755 	zval* ctrlarray;
756 	int error = 0;
757 
758 	ncontrols = zend_hash_num_elements(Z_ARRVAL_P(array));
759 	ctrls = safe_emalloc((1 + ncontrols), sizeof(*ctrls), 0);
760 	*ctrls = NULL;
761 	ctrlp = ctrls;
762 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(array), ctrlarray) {
763 		if (Z_TYPE_P(ctrlarray) != IS_ARRAY) {
764 			zend_argument_type_error(arg_num, "must contain only arrays, where each array is a control");
765 			error = 1;
766 			break;
767 		}
768 
769 		if (_php_ldap_control_from_array(ld, ctrlp, ctrlarray) == LDAP_SUCCESS) {
770 			++ctrlp;
771 		} else {
772 			error = 1;
773 			break;
774 		}
775 
776 		*ctrlp = NULL;
777 	} ZEND_HASH_FOREACH_END();
778 
779 	if (error) {
780 		ctrlp = ctrls;
781 		while (*ctrlp) {
782 			ldap_control_free(*ctrlp);
783 			ctrlp++;
784 		}
785 		efree(ctrls);
786 		ctrls = NULL;
787 	}
788 
789 	return ctrls;
790 }
791 
_php_ldap_controls_free(LDAPControl *** ctrls)792 static void _php_ldap_controls_free (LDAPControl*** ctrls)
793 {
794 	LDAPControl **ctrlp;
795 
796 	if (*ctrls) {
797 		ctrlp = *ctrls;
798 		while (*ctrlp) {
799 			ldap_control_free(*ctrlp);
800 			ctrlp++;
801 		}
802 		efree(*ctrls);
803 		*ctrls = NULL;
804 	}
805 }
806 /* }}} */
807 
808 /* {{{ PHP_INI_BEGIN */
809 PHP_INI_BEGIN()
810 	STD_PHP_INI_ENTRY_EX("ldap.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_ldap_globals, ldap_globals, display_link_numbers)
PHP_INI_END()811 PHP_INI_END()
812 /* }}} */
813 
814 /* {{{ PHP_GINIT_FUNCTION */
815 static PHP_GINIT_FUNCTION(ldap)
816 {
817 #if defined(COMPILE_DL_LDAP) && defined(ZTS)
818 	ZEND_TSRMLS_CACHE_UPDATE();
819 #endif
820 	ldap_globals->num_links = 0;
821 }
822 /* }}} */
823 
824 /* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(ldap)825 PHP_MINIT_FUNCTION(ldap)
826 {
827 	REGISTER_INI_ENTRIES();
828 
829 	ldap_link_ce = register_class_LDAP_Connection();
830 	ldap_link_ce->create_object = ldap_link_create_object;
831 
832 	memcpy(&ldap_link_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
833 	ldap_link_object_handlers.offset = XtOffsetOf(ldap_linkdata, std);
834 	ldap_link_object_handlers.free_obj = ldap_link_free_obj;
835 	ldap_link_object_handlers.get_constructor = ldap_link_get_constructor;
836 	ldap_link_object_handlers.clone_obj = NULL;
837 	ldap_link_object_handlers.compare = zend_objects_not_comparable;
838 
839 	ldap_result_ce = register_class_LDAP_Result();
840 	ldap_result_ce->create_object = ldap_result_create_object;
841 
842 	memcpy(&ldap_result_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
843 	ldap_result_object_handlers.offset = XtOffsetOf(ldap_resultdata, std);
844 	ldap_result_object_handlers.free_obj = ldap_result_free_obj;
845 	ldap_result_object_handlers.get_constructor = ldap_result_get_constructor;
846 	ldap_result_object_handlers.clone_obj = NULL;
847 	ldap_result_object_handlers.compare = zend_objects_not_comparable;
848 
849 	ldap_result_entry_ce = register_class_LDAP_ResultEntry();
850 	ldap_result_entry_ce->create_object = ldap_result_entry_create_object;
851 
852 	memcpy(&ldap_result_entry_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
853 	ldap_result_entry_object_handlers.offset = XtOffsetOf(ldap_result_entry, std);
854 	ldap_result_entry_object_handlers.free_obj = ldap_result_entry_free_obj;
855 	ldap_result_entry_object_handlers.get_constructor = ldap_result_entry_get_constructor;
856 	ldap_result_entry_object_handlers.clone_obj = NULL;
857 	ldap_result_entry_object_handlers.compare = zend_objects_not_comparable;
858 
859 	register_ldap_symbols(module_number);
860 
861 	ldap_module_entry.type = type;
862 
863 	return SUCCESS;
864 }
865 /* }}} */
866 
867 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(ldap)868 PHP_MSHUTDOWN_FUNCTION(ldap)
869 {
870 	UNREGISTER_INI_ENTRIES();
871 	return SUCCESS;
872 }
873 /* }}} */
874 
875 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(ldap)876 PHP_MINFO_FUNCTION(ldap)
877 {
878 	char tmp[32];
879 
880 	php_info_print_table_start();
881 	php_info_print_table_row(2, "LDAP Support", "enabled");
882 
883 	if (LDAPG(max_links) == -1) {
884 		snprintf(tmp, 31, ZEND_LONG_FMT "/unlimited", LDAPG(num_links));
885 	} else {
886 		snprintf(tmp, 31, ZEND_LONG_FMT "/" ZEND_LONG_FMT, LDAPG(num_links), LDAPG(max_links));
887 	}
888 	php_info_print_table_row(2, "Total Links", tmp);
889 
890 #ifdef LDAP_API_VERSION
891 	snprintf(tmp, 31, "%d", LDAP_API_VERSION);
892 	php_info_print_table_row(2, "API Version", tmp);
893 #endif
894 
895 #ifdef LDAP_VENDOR_NAME
896 	php_info_print_table_row(2, "Vendor Name", LDAP_VENDOR_NAME);
897 #endif
898 
899 #ifdef LDAP_VENDOR_VERSION
900 	snprintf(tmp, 31, "%d", LDAP_VENDOR_VERSION);
901 	php_info_print_table_row(2, "Vendor Version", tmp);
902 #endif
903 
904 #ifdef HAVE_LDAP_SASL
905 	php_info_print_table_row(2, "SASL Support", "Enabled");
906 #endif
907 
908 	php_info_print_table_end();
909 	DISPLAY_INI_ENTRIES();
910 }
911 /* }}} */
912 
913 /* {{{ Connect to an LDAP server */
PHP_FUNCTION(ldap_connect)914 PHP_FUNCTION(ldap_connect)
915 {
916 	char *host = NULL;
917 	size_t hostlen = 0;
918 	zend_long port = LDAP_PORT;
919 #ifdef HAVE_ORALDAP
920 	char *wallet = NULL, *walletpasswd = NULL;
921 	size_t walletlen = 0, walletpasswdlen = 0;
922 	zend_long authmode = GSLC_SSL_NO_AUTH;
923 	int ssl=0;
924 #endif
925 	ldap_linkdata *ld;
926 	LDAP *ldap = NULL;
927 
928 #ifdef HAVE_ORALDAP
929 	if (ZEND_NUM_ARGS() == 3 || ZEND_NUM_ARGS() == 4) {
930 		WRONG_PARAM_COUNT;
931 	}
932 
933 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!lssl", &host, &hostlen, &port, &wallet, &walletlen, &walletpasswd, &walletpasswdlen, &authmode) != SUCCESS) {
934 		RETURN_THROWS();
935 	}
936 
937 	if (ZEND_NUM_ARGS() == 5) {
938 		ssl = 1;
939 	}
940 #else
941 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s!l", &host, &hostlen, &port) != SUCCESS) {
942 		RETURN_THROWS();
943 	}
944 #endif
945 
946 	if (LDAPG(max_links) != -1 && LDAPG(num_links) >= LDAPG(max_links)) {
947 		php_error_docref(NULL, E_WARNING, "Too many open links (" ZEND_LONG_FMT ")", LDAPG(num_links));
948 		RETURN_FALSE;
949 	}
950 
951 	object_init_ex(return_value, ldap_link_ce);
952 	ld = Z_LDAP_LINK_P(return_value);
953 
954 	{
955 		int rc = LDAP_SUCCESS;
956 		char	*url = host;
957 		if (url && !ldap_is_ldap_url(url)) {
958 			size_t urllen = hostlen + sizeof( "ldap://:65535" );
959 
960 			if (port <= 0 || port > 65535) {
961 				zend_argument_value_error(2, "must be between 1 and 65535");
962 				RETURN_THROWS();
963 			}
964 
965 			url = emalloc(urllen);
966 			snprintf( url, urllen, "ldap://%s:" ZEND_LONG_FMT, host, port );
967 		}
968 
969 #ifdef LDAP_API_FEATURE_X_OPENLDAP
970 		/* ldap_init() is deprecated, use ldap_initialize() instead.
971 		 */
972 		rc = ldap_initialize(&ldap, url);
973 #else /* ! LDAP_API_FEATURE_X_OPENLDAP */
974 		/* ldap_init does not support URLs.
975 		 * We must try the original host and port information.
976 		 */
977 		ldap = ldap_init(host, port);
978 		if (ldap == NULL) {
979 			zval_ptr_dtor(return_value);
980 			php_error_docref(NULL, E_WARNING, "Could not create session handle");
981 			RETURN_FALSE;
982 		}
983 #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */
984 		if (url != host) {
985 			efree(url);
986 		}
987 		if (rc != LDAP_SUCCESS) {
988 			zval_ptr_dtor(return_value);
989 			php_error_docref(NULL, E_WARNING, "Could not create session handle: %s", ldap_err2string(rc));
990 			RETURN_FALSE;
991 		}
992 	}
993 
994 	if (ldap == NULL) {
995 		zval_ptr_dtor(return_value);
996 		RETURN_FALSE;
997 	} else {
998 #ifdef HAVE_ORALDAP
999 		if (ssl) {
1000 			if (ldap_init_SSL(&ldap->ld_sb, wallet, walletpasswd, authmode)) {
1001 				zval_ptr_dtor(return_value);
1002 				php_error_docref(NULL, E_WARNING, "SSL init failed");
1003 				RETURN_FALSE;
1004 			}
1005 		}
1006 #endif
1007 		LDAPG(num_links)++;
1008 		ld->link = ldap;
1009 	}
1010 
1011 }
1012 /* }}} */
1013 
1014 /* {{{ _get_lderrno */
_get_lderrno(LDAP * ldap)1015 static int _get_lderrno(LDAP *ldap)
1016 {
1017 #if LDAP_API_VERSION > 2000 || defined(HAVE_ORALDAP)
1018 	int lderr;
1019 
1020 	/* New versions of OpenLDAP do it this way */
1021 	ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
1022 	return lderr;
1023 #else
1024 	return ldap->ld_errno;
1025 #endif
1026 }
1027 /* }}} */
1028 
1029 /* {{{ _set_lderrno */
_set_lderrno(LDAP * ldap,int lderr)1030 static void _set_lderrno(LDAP *ldap, int lderr)
1031 {
1032 #if LDAP_API_VERSION > 2000 || defined(HAVE_ORALDAP)
1033 	/* New versions of OpenLDAP do it this way */
1034 	ldap_set_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
1035 #else
1036 	ldap->ld_errno = lderr;
1037 #endif
1038 }
1039 /* }}} */
1040 
1041 /* {{{ Bind to LDAP directory */
PHP_FUNCTION(ldap_bind)1042 PHP_FUNCTION(ldap_bind)
1043 {
1044 	zval *link;
1045 	char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
1046 	size_t ldap_bind_dnlen, ldap_bind_pwlen;
1047 	ldap_linkdata *ld;
1048 	int rc;
1049 
1050 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|s!s!", &link, ldap_link_ce, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen) != SUCCESS) {
1051 		RETURN_THROWS();
1052 	}
1053 
1054 	ld = Z_LDAP_LINK_P(link);
1055 	VERIFY_LDAP_LINK_CONNECTED(ld);
1056 
1057 	if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
1058 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1059 		zend_argument_type_error(2, "must not contain null bytes");
1060 		RETURN_THROWS();
1061 	}
1062 
1063 	if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
1064 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1065 		zend_argument_type_error(3, "must not contain null bytes");
1066 		RETURN_THROWS();
1067 	}
1068 
1069 	{
1070 #ifdef LDAP_API_FEATURE_X_OPENLDAP
1071 		/* ldap_simple_bind_s() is deprecated, use ldap_sasl_bind_s() instead.
1072 		 */
1073 		struct berval   cred;
1074 
1075 		cred.bv_val = ldap_bind_pw;
1076 		cred.bv_len = ldap_bind_pw ? ldap_bind_pwlen : 0;
1077 		rc = ldap_sasl_bind_s(ld->link, ldap_bind_dn, LDAP_SASL_SIMPLE, &cred,
1078 				NULL, NULL,     /* no controls right now */
1079 				NULL);	  /* we don't care about the server's credentials */
1080 #else /* ! LDAP_API_FEATURE_X_OPENLDAP */
1081 		rc = ldap_simple_bind_s(ld->link, ldap_bind_dn, ldap_bind_pw);
1082 #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */
1083 	}
1084 	if ( rc != LDAP_SUCCESS) {
1085 		php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
1086 		RETURN_FALSE;
1087 	} else {
1088 		RETURN_TRUE;
1089 	}
1090 }
1091 /* }}} */
1092 
1093 /* {{{ Bind to LDAP directory */
PHP_FUNCTION(ldap_bind_ext)1094 PHP_FUNCTION(ldap_bind_ext)
1095 {
1096 	zval *serverctrls = NULL;
1097 	zval *link;
1098 	char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
1099 	size_t ldap_bind_dnlen, ldap_bind_pwlen;
1100 	ldap_linkdata *ld;
1101 	LDAPControl **lserverctrls = NULL;
1102 	ldap_resultdata *result;
1103 	LDAPMessage *ldap_res;
1104 	int rc;
1105 
1106 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|s!s!a!", &link, ldap_link_ce, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen, &serverctrls) != SUCCESS) {
1107 		RETURN_THROWS();
1108 	}
1109 
1110 	ld = Z_LDAP_LINK_P(link);
1111 	VERIFY_LDAP_LINK_CONNECTED(ld);
1112 
1113 	if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
1114 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1115 		zend_argument_type_error(2, "must not contain null bytes");
1116 		RETURN_THROWS();
1117 	}
1118 
1119 	if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
1120 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1121 		zend_argument_type_error(3, "must not contain null bytes");
1122 		RETURN_THROWS();
1123 	}
1124 
1125 	if (serverctrls) {
1126 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
1127 		if (lserverctrls == NULL) {
1128 			RETVAL_FALSE;
1129 			goto cleanup;
1130 		}
1131 	}
1132 
1133 	{
1134 		/* ldap_simple_bind() is deprecated, use ldap_sasl_bind() instead */
1135 		struct berval   cred;
1136 		int msgid;
1137 
1138 		cred.bv_val = ldap_bind_pw;
1139 		cred.bv_len = ldap_bind_pw ? ldap_bind_pwlen : 0;
1140 		/* asynchronous call */
1141 		rc = ldap_sasl_bind(ld->link, ldap_bind_dn, LDAP_SASL_SIMPLE, &cred,
1142 				lserverctrls, NULL, &msgid);
1143 		if (rc != LDAP_SUCCESS ) {
1144 			php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s (%d)", ldap_err2string(rc), rc);
1145 			RETVAL_FALSE;
1146 			goto cleanup;
1147 		}
1148 
1149 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
1150 		if (rc == -1) {
1151 			php_error_docref(NULL, E_WARNING, "Bind operation failed");
1152 			RETVAL_FALSE;
1153 			goto cleanup;
1154 		}
1155 
1156 		/* return a PHP control object */
1157 		object_init_ex(return_value, ldap_result_ce);
1158 		result = Z_LDAP_RESULT_P(return_value);
1159 		result->result = ldap_res;
1160 	}
1161 
1162 cleanup:
1163 	if (lserverctrls) {
1164 		_php_ldap_controls_free(&lserverctrls);
1165 	}
1166 
1167 	return;
1168 }
1169 /* }}} */
1170 
1171 #ifdef HAVE_LDAP_SASL
1172 typedef struct {
1173 	char *mech;
1174 	char *realm;
1175 	char *authcid;
1176 	char *passwd;
1177 	char *authzid;
1178 } php_ldap_bictx;
1179 
1180 /* {{{ _php_sasl_setdefs */
_php_sasl_setdefs(LDAP * ld,char * sasl_mech,char * sasl_realm,char * sasl_authc_id,char * passwd,char * sasl_authz_id)1181 static php_ldap_bictx *_php_sasl_setdefs(LDAP *ld, char *sasl_mech, char *sasl_realm, char *sasl_authc_id, char *passwd, char *sasl_authz_id)
1182 {
1183 	php_ldap_bictx *ctx;
1184 
1185 	ctx = ber_memalloc(sizeof(php_ldap_bictx));
1186 	ctx->mech    = (sasl_mech) ? ber_strdup(sasl_mech) : NULL;
1187 	ctx->realm   = (sasl_realm) ? ber_strdup(sasl_realm) : NULL;
1188 	ctx->authcid = (sasl_authc_id) ? ber_strdup(sasl_authc_id) : NULL;
1189 	ctx->passwd  = (passwd) ? ber_strdup(passwd) : NULL;
1190 	ctx->authzid = (sasl_authz_id) ? ber_strdup(sasl_authz_id) : NULL;
1191 
1192 	if (ctx->mech == NULL) {
1193 		ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &ctx->mech);
1194 	}
1195 	if (ctx->realm == NULL) {
1196 		ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &ctx->realm);
1197 	}
1198 	if (ctx->authcid == NULL) {
1199 		ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &ctx->authcid);
1200 	}
1201 	if (ctx->authzid == NULL) {
1202 		ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &ctx->authzid);
1203 	}
1204 
1205 	return ctx;
1206 }
1207 /* }}} */
1208 
1209 /* {{{ _php_sasl_freedefs */
_php_sasl_freedefs(php_ldap_bictx * ctx)1210 static void _php_sasl_freedefs(php_ldap_bictx *ctx)
1211 {
1212 	if (ctx->mech) ber_memfree(ctx->mech);
1213 	if (ctx->realm) ber_memfree(ctx->realm);
1214 	if (ctx->authcid) ber_memfree(ctx->authcid);
1215 	if (ctx->passwd) ber_memfree(ctx->passwd);
1216 	if (ctx->authzid) ber_memfree(ctx->authzid);
1217 	ber_memfree(ctx);
1218 }
1219 /* }}} */
1220 
1221 /* {{{ _php_sasl_interact
1222    Internal interact function for SASL */
_php_sasl_interact(LDAP * ld,unsigned flags,void * defaults,void * in)1223 static int _php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)
1224 {
1225 	sasl_interact_t *interact = in;
1226 	const char *p;
1227 	php_ldap_bictx *ctx = defaults;
1228 
1229 	for (;interact->id != SASL_CB_LIST_END;interact++) {
1230 		p = NULL;
1231 		switch(interact->id) {
1232 			case SASL_CB_GETREALM:
1233 				p = ctx->realm;
1234 				break;
1235 			case SASL_CB_AUTHNAME:
1236 				p = ctx->authcid;
1237 				break;
1238 			case SASL_CB_USER:
1239 				p = ctx->authzid;
1240 				break;
1241 			case SASL_CB_PASS:
1242 				p = ctx->passwd;
1243 				break;
1244 		}
1245 		if (p) {
1246 			interact->result = p;
1247 			interact->len = strlen(interact->result);
1248 		}
1249 	}
1250 	return LDAP_SUCCESS;
1251 }
1252 /* }}} */
1253 
1254 /* {{{ Bind to LDAP directory using SASL */
PHP_FUNCTION(ldap_sasl_bind)1255 PHP_FUNCTION(ldap_sasl_bind)
1256 {
1257 	zval *link;
1258 	ldap_linkdata *ld;
1259 	char *binddn = NULL;
1260 	char *passwd = NULL;
1261 	char *sasl_mech = NULL;
1262 	char *sasl_realm = NULL;
1263 	char *sasl_authz_id = NULL;
1264 	char *sasl_authc_id = NULL;
1265 	char *props = NULL;
1266 	size_t rc, dn_len, passwd_len, mech_len, realm_len, authc_id_len, authz_id_len, props_len;
1267 	php_ldap_bictx *ctx;
1268 
1269 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O|s!s!s!s!s!s!s!", &link, ldap_link_ce, &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) {
1270 		RETURN_THROWS();
1271 	}
1272 
1273 	ld = Z_LDAP_LINK_P(link);
1274 	VERIFY_LDAP_LINK_CONNECTED(ld);
1275 
1276 	ctx = _php_sasl_setdefs(ld->link, sasl_mech, sasl_realm, sasl_authc_id, passwd, sasl_authz_id);
1277 
1278 	if (props) {
1279 		ldap_set_option(ld->link, LDAP_OPT_X_SASL_SECPROPS, props);
1280 	}
1281 
1282 	rc = ldap_sasl_interactive_bind_s(ld->link, binddn, ctx->mech, NULL, NULL, LDAP_SASL_QUIET, _php_sasl_interact, ctx);
1283 	if (rc != LDAP_SUCCESS) {
1284 		php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
1285 		RETVAL_FALSE;
1286 	} else {
1287 		RETVAL_TRUE;
1288 	}
1289 	_php_sasl_freedefs(ctx);
1290 }
1291 /* }}} */
1292 #endif /* HAVE_LDAP_SASL */
1293 
1294 /* {{{ Unbind from LDAP directory */
PHP_FUNCTION(ldap_unbind)1295 PHP_FUNCTION(ldap_unbind)
1296 {
1297 	zval *link;
1298 	ldap_linkdata *ld;
1299 
1300 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
1301 		RETURN_THROWS();
1302 	}
1303 
1304 	ld = Z_LDAP_LINK_P(link);
1305 	VERIFY_LDAP_LINK_CONNECTED(ld);
1306 
1307 	ldap_link_free(ld);
1308 
1309 	RETURN_TRUE;
1310 }
1311 /* }}} */
1312 
1313 /* {{{ php_set_opts */
php_set_opts(LDAP * ldap,int sizelimit,int timelimit,int deref,int * old_sizelimit,int * old_timelimit,int * old_deref)1314 static void php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref)
1315 {
1316 	/* sizelimit */
1317 	if (sizelimit > -1) {
1318 #if (LDAP_API_VERSION >= 2004) || defined(HAVE_ORALDAP)
1319 		ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_sizelimit);
1320 		ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit);
1321 #else
1322 		*old_sizelimit = ldap->ld_sizelimit;
1323 		ldap->ld_sizelimit = sizelimit;
1324 #endif
1325 	}
1326 
1327 	/* timelimit */
1328 	if (timelimit > -1) {
1329 #if (LDAP_API_VERSION >= 2004) || defined(HAVE_ORALDAP)
1330 		ldap_get_option(ldap, LDAP_OPT_TIMELIMIT, old_timelimit);
1331 		ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &timelimit);
1332 #else
1333 		*old_timelimit = ldap->ld_timelimit;
1334 		ldap->ld_timelimit = timelimit;
1335 #endif
1336 	}
1337 
1338 	/* deref */
1339 	if (deref > -1) {
1340 #if (LDAP_API_VERSION >= 2004) || defined(HAVE_ORALDAP)
1341 		ldap_get_option(ldap, LDAP_OPT_DEREF, old_deref);
1342 		ldap_set_option(ldap, LDAP_OPT_DEREF, &deref);
1343 #else
1344 		*old_deref = ldap->ld_deref;
1345 		ldap->ld_deref = deref;
1346 #endif
1347 	}
1348 }
1349 /* }}} */
1350 
1351 /* {{{ php_ldap_do_search */
php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS,int scope)1352 static void php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope)
1353 {
1354 	zval *link, *attrs = NULL, *attr, *serverctrls = NULL;
1355 	zend_string *base_dn_str, *filter_str;
1356 	HashTable *base_dn_ht, *filter_ht;
1357 	zend_long attrsonly, sizelimit, timelimit, deref;
1358 	zend_string *ldap_filter = NULL, *ldap_base_dn = NULL;
1359 	char **ldap_attrs = NULL;
1360 	ldap_linkdata *ld = NULL;
1361 	ldap_resultdata *result;
1362 	LDAPMessage *ldap_res = NULL;
1363 	LDAPControl **lserverctrls = NULL;
1364 	int ldap_attrsonly = 0, ldap_sizelimit = -1, ldap_timelimit = -1, ldap_deref = -1;
1365 	int old_ldap_sizelimit = -1, old_ldap_timelimit = -1, old_ldap_deref = -1;
1366 	int num_attribs = 0, ret = 1, i, ldap_errno, argcount = ZEND_NUM_ARGS();
1367 
1368 	ZEND_PARSE_PARAMETERS_START(3, 9)
1369 		Z_PARAM_ZVAL(link)
1370 		Z_PARAM_ARRAY_HT_OR_STR(base_dn_ht, base_dn_str)
1371 		Z_PARAM_ARRAY_HT_OR_STR(filter_ht, filter_str)
1372 		Z_PARAM_OPTIONAL
1373 		Z_PARAM_ARRAY_EX(attrs, 0, 1)
1374 		Z_PARAM_LONG(attrsonly)
1375 		Z_PARAM_LONG(sizelimit)
1376 		Z_PARAM_LONG(timelimit)
1377 		Z_PARAM_LONG(deref)
1378 		Z_PARAM_ARRAY_EX(serverctrls, 1, 1)
1379 	ZEND_PARSE_PARAMETERS_END();
1380 
1381 	/* Reverse -> fall through */
1382 	switch (argcount) {
1383 		case 9:
1384 		case 8:
1385 			ldap_deref = deref;
1386 			ZEND_FALLTHROUGH;
1387 		case 7:
1388 			ldap_timelimit = timelimit;
1389 			ZEND_FALLTHROUGH;
1390 		case 6:
1391 			ldap_sizelimit = sizelimit;
1392 			ZEND_FALLTHROUGH;
1393 		case 5:
1394 			ldap_attrsonly = attrsonly;
1395 			ZEND_FALLTHROUGH;
1396 		case 4:
1397 			num_attribs = zend_hash_num_elements(Z_ARRVAL_P(attrs));
1398 			ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
1399 
1400 			for (i = 0; i<num_attribs; i++) {
1401 				if ((attr = zend_hash_index_find(Z_ARRVAL_P(attrs), i)) == NULL) {
1402 					php_error_docref(NULL, E_WARNING, "Array initialization wrong");
1403 					ret = 0;
1404 					goto cleanup;
1405 				}
1406 
1407 				convert_to_string(attr);
1408 				if (EG(exception)) {
1409 					ret = 0;
1410 					goto cleanup;
1411 				}
1412 				ldap_attrs[i] = Z_STRVAL_P(attr);
1413 			}
1414 			ldap_attrs[num_attribs] = NULL;
1415 			ZEND_FALLTHROUGH;
1416 		default:
1417 			break;
1418 	}
1419 
1420 	/* parallel search? */
1421 	if (Z_TYPE_P(link) == IS_ARRAY) {
1422 		int i, nlinks, nbases, nfilters, *rcs;
1423 		ldap_linkdata **lds;
1424 		zval *entry, object;
1425 
1426 		nlinks = zend_hash_num_elements(Z_ARRVAL_P(link));
1427 		if (nlinks == 0) {
1428 			zend_argument_value_error(1, "cannot be empty");
1429 			ret = 0;
1430 			goto cleanup;
1431 		}
1432 
1433 		if (base_dn_ht) {
1434 			nbases = zend_hash_num_elements(base_dn_ht);
1435 			if (nbases != nlinks) {
1436 				zend_argument_value_error(2, "must have the same number of elements as the links array");
1437 				ret = 0;
1438 				goto cleanup;
1439 			}
1440 			zend_hash_internal_pointer_reset(base_dn_ht);
1441 		} else {
1442 			nbases = 0; /* this means string, not array */
1443 			ldap_base_dn = zend_string_copy(base_dn_str);
1444 			if (EG(exception)) {
1445 				ret = 0;
1446 				goto cleanup;
1447 			}
1448 		}
1449 
1450 		if (filter_ht) {
1451 			nfilters = zend_hash_num_elements(filter_ht);
1452 			if (nfilters != nlinks) {
1453 				zend_argument_value_error(3, "must have the same number of elements as the links array");
1454 				ret = 0;
1455 				goto cleanup;
1456 			}
1457 			zend_hash_internal_pointer_reset(filter_ht);
1458 		} else {
1459 			nfilters = 0; /* this means string, not array */
1460 			ldap_filter = zend_string_copy(filter_str);
1461 		}
1462 
1463 		lds = safe_emalloc(nlinks, sizeof(ldap_linkdata), 0);
1464 		rcs = safe_emalloc(nlinks, sizeof(*rcs), 0);
1465 
1466 		zend_hash_internal_pointer_reset(Z_ARRVAL_P(link));
1467 		for (i=0; i<nlinks; i++) {
1468 			entry = zend_hash_get_current_data(Z_ARRVAL_P(link));
1469 
1470 			if (Z_TYPE_P(entry) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(entry), ldap_link_ce)) {
1471 				zend_argument_value_error(1, "must only contain objects of type LDAP");
1472 				ret = 0;
1473 				goto cleanup_parallel;
1474 			}
1475 
1476 			ld = Z_LDAP_LINK_P(entry);
1477 			if (!ld->link) {
1478 				zend_throw_error(NULL, "LDAP connection has already been closed");
1479 				ret = 0;
1480 				goto cleanup_parallel;
1481 			}
1482 
1483 			if (nbases != 0) { /* base_dn an array? */
1484 				entry = zend_hash_get_current_data(base_dn_ht);
1485 				zend_hash_move_forward(base_dn_ht);
1486 				ldap_base_dn = zval_get_string(entry);
1487 				if (EG(exception)) {
1488 					ret = 0;
1489 					goto cleanup_parallel;
1490 				}
1491 			}
1492 			if (nfilters != 0) { /* filter an array? */
1493 				entry = zend_hash_get_current_data(filter_ht);
1494 				zend_hash_move_forward(filter_ht);
1495 				ldap_filter = zval_get_string(entry);
1496 				if (EG(exception)) {
1497 					ret = 0;
1498 					goto cleanup_parallel;
1499 				}
1500 			}
1501 
1502 			if (serverctrls) {
1503 				/* We have to parse controls again for each link as they use it */
1504 				_php_ldap_controls_free(&lserverctrls);
1505 				lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 9);
1506 				if (lserverctrls == NULL) {
1507 					rcs[i] = -1;
1508 					continue;
1509 				}
1510 			}
1511 
1512 			php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
1513 
1514 			/* Run the actual search */
1515 			ldap_search_ext(ld->link, ZSTR_VAL(ldap_base_dn), scope, ZSTR_VAL(ldap_filter), ldap_attrs, ldap_attrsonly, lserverctrls, NULL, NULL, ldap_sizelimit, &rcs[i]);
1516 			lds[i] = ld;
1517 			zend_hash_move_forward(Z_ARRVAL_P(link));
1518 		}
1519 
1520 		array_init(return_value);
1521 
1522 		/* Collect results from the searches */
1523 		for (i=0; i<nlinks; i++) {
1524 			if (rcs[i] != -1) {
1525 				rcs[i] = ldap_result(lds[i]->link, LDAP_RES_ANY, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
1526 			}
1527 			if (rcs[i] != -1) {
1528 				object_init_ex(&object, ldap_result_ce);
1529 				result = Z_LDAP_RESULT_P(&object);
1530 				result->result = ldap_res;
1531 				add_next_index_zval(return_value, &object);
1532 			} else {
1533 				add_next_index_bool(return_value, 0);
1534 			}
1535 		}
1536 
1537 cleanup_parallel:
1538 		efree(lds);
1539 		efree(rcs);
1540 	} else if (Z_TYPE_P(link) == IS_OBJECT && instanceof_function(Z_OBJCE_P(link), ldap_link_ce)) {
1541 		ld = Z_LDAP_LINK_P(link);
1542 		if (!ld->link) {
1543 			zend_throw_error(NULL, "LDAP connection has already been closed");
1544 			ret = 0;
1545 			goto cleanup;
1546 		}
1547 
1548 		if (!base_dn_str) {
1549 			zend_argument_type_error(2, "must be of type string when argument #1 ($ldap) is an LDAP instance");
1550 			ret = 0;
1551 			goto cleanup;
1552 		}
1553 		ldap_base_dn = zend_string_copy(base_dn_str);
1554 
1555 		if (!filter_str) {
1556 			zend_argument_type_error(3, "must be of type string when argument #1 ($ldap) is an LDAP instance");
1557 			ret = 0;
1558 			goto cleanup;
1559 		}
1560 		ldap_filter = zend_string_copy(filter_str);
1561 
1562 		if (serverctrls) {
1563 			lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 9);
1564 			if (lserverctrls == NULL) {
1565 				ret = 0;
1566 				goto cleanup;
1567 			}
1568 		}
1569 
1570 		php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
1571 
1572 		/* Run the actual search */
1573 		ldap_errno = ldap_search_ext_s(ld->link, ZSTR_VAL(ldap_base_dn), scope, ZSTR_VAL(ldap_filter), ldap_attrs, ldap_attrsonly, lserverctrls, NULL, NULL, ldap_sizelimit, &ldap_res);
1574 
1575 		if (ldap_errno != LDAP_SUCCESS
1576 			&& ldap_errno != LDAP_SIZELIMIT_EXCEEDED
1577 #ifdef LDAP_ADMINLIMIT_EXCEEDED
1578 			&& ldap_errno != LDAP_ADMINLIMIT_EXCEEDED
1579 #endif
1580 #ifdef LDAP_REFERRAL
1581 			&& ldap_errno != LDAP_REFERRAL
1582 #endif
1583 		) {
1584 			/* ldap_res should be freed regardless of return value of ldap_search_ext_s()
1585 			 * see: https://linux.die.net/man/3/ldap_search_ext_s */
1586 			if (ldap_res != NULL) {
1587 				ldap_msgfree(ldap_res);
1588 			}
1589 			php_error_docref(NULL, E_WARNING, "Search: %s", ldap_err2string(ldap_errno));
1590 			ret = 0;
1591 		} else {
1592 			if (ldap_errno == LDAP_SIZELIMIT_EXCEEDED) {
1593 				php_error_docref(NULL, E_WARNING, "Partial search results returned: Sizelimit exceeded");
1594 			}
1595 #ifdef LDAP_ADMINLIMIT_EXCEEDED
1596 			else if (ldap_errno == LDAP_ADMINLIMIT_EXCEEDED) {
1597 				php_error_docref(NULL, E_WARNING, "Partial search results returned: Adminlimit exceeded");
1598 			}
1599 #endif
1600 			object_init_ex(return_value, ldap_result_ce);
1601 			result = Z_LDAP_RESULT_P(return_value);
1602 			result->result = ldap_res;
1603 		}
1604 	} else {
1605 		zend_argument_type_error(1, "must be of type LDAP|array, %s given", zend_zval_type_name(link));
1606 	}
1607 
1608 cleanup:
1609 	if (ld) {
1610 		/* Restoring previous options */
1611 		php_set_opts(ld->link, old_ldap_sizelimit, old_ldap_timelimit, old_ldap_deref, &ldap_sizelimit, &ldap_timelimit, &ldap_deref);
1612 	}
1613 	if (ldap_filter) {
1614 		zend_string_release(ldap_filter);
1615 	}
1616 	if (ldap_base_dn) {
1617 		zend_string_release(ldap_base_dn);
1618 	}
1619 	if (ldap_attrs != NULL) {
1620 		efree(ldap_attrs);
1621 	}
1622 	if (!ret) {
1623 		RETVAL_BOOL(ret);
1624 	}
1625 	if (lserverctrls) {
1626 		_php_ldap_controls_free(&lserverctrls);
1627 	}
1628 }
1629 /* }}} */
1630 
1631 /* {{{ Read an entry */
PHP_FUNCTION(ldap_read)1632 PHP_FUNCTION(ldap_read)
1633 {
1634 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_BASE);
1635 }
1636 /* }}} */
1637 
1638 /* {{{ Single-level search */
PHP_FUNCTION(ldap_list)1639 PHP_FUNCTION(ldap_list)
1640 {
1641 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_ONELEVEL);
1642 }
1643 /* }}} */
1644 
1645 /* {{{ Search LDAP tree under base_dn */
PHP_FUNCTION(ldap_search)1646 PHP_FUNCTION(ldap_search)
1647 {
1648 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_SUBTREE);
1649 }
1650 /* }}} */
1651 
1652 /* {{{ Free result memory */
PHP_FUNCTION(ldap_free_result)1653 PHP_FUNCTION(ldap_free_result)
1654 {
1655 	zval *result;
1656 	ldap_resultdata *ldap_result;
1657 
1658 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &result, ldap_result_ce) != SUCCESS) {
1659 		RETURN_THROWS();
1660 	}
1661 
1662 	ldap_result = Z_LDAP_RESULT_P(result);
1663 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
1664 
1665 	ldap_result_free(ldap_result);
1666 
1667 	RETVAL_TRUE;
1668 }
1669 /* }}} */
1670 
1671 /* {{{ Count the number of entries in a search result */
PHP_FUNCTION(ldap_count_entries)1672 PHP_FUNCTION(ldap_count_entries)
1673 {
1674 	zval *link, *result;
1675 	ldap_linkdata *ld;
1676 	ldap_resultdata *ldap_result;
1677 
1678 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
1679 		RETURN_THROWS();
1680 	}
1681 
1682 	ld = Z_LDAP_LINK_P(link);
1683 	VERIFY_LDAP_LINK_CONNECTED(ld);
1684 
1685 	ldap_result = Z_LDAP_RESULT_P(result);
1686 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
1687 
1688 	RETURN_LONG(ldap_count_entries(ld->link, ldap_result->result));
1689 }
1690 /* }}} */
1691 
1692 /* {{{ Return first result id */
PHP_FUNCTION(ldap_first_entry)1693 PHP_FUNCTION(ldap_first_entry)
1694 {
1695 	zval *link, *result;
1696 	ldap_linkdata *ld;
1697 	ldap_result_entry *resultentry;
1698 	ldap_resultdata *ldap_result;
1699 	LDAPMessage *entry;
1700 
1701 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
1702 		RETURN_THROWS();
1703 	}
1704 
1705 	ld = Z_LDAP_LINK_P(link);
1706 	VERIFY_LDAP_LINK_CONNECTED(ld);
1707 
1708 	ldap_result = Z_LDAP_RESULT_P(result);
1709 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
1710 
1711 	if ((entry = ldap_first_entry(ld->link, ldap_result->result)) == NULL) {
1712 		RETVAL_FALSE;
1713 	} else {
1714 		object_init_ex(return_value, ldap_result_entry_ce);
1715 		resultentry = Z_LDAP_RESULT_ENTRY_P(return_value);
1716 		ZVAL_COPY(&resultentry->res, result);
1717 		resultentry->data = entry;
1718 		resultentry->ber = NULL;
1719 	}
1720 }
1721 /* }}} */
1722 
1723 /* {{{ Get next result entry */
PHP_FUNCTION(ldap_next_entry)1724 PHP_FUNCTION(ldap_next_entry)
1725 {
1726 	zval *link, *result_entry;
1727 	ldap_linkdata *ld;
1728 	ldap_result_entry *resultentry, *resultentry_next;
1729 	LDAPMessage *entry_next;
1730 
1731 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
1732 		RETURN_THROWS();
1733 	}
1734 
1735 	ld = Z_LDAP_LINK_P(link);
1736 	VERIFY_LDAP_LINK_CONNECTED(ld);
1737 
1738 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
1739 
1740 	if ((entry_next = ldap_next_entry(ld->link, resultentry->data)) == NULL) {
1741 		RETVAL_FALSE;
1742 	} else {
1743 		object_init_ex(return_value, ldap_result_entry_ce);
1744 		resultentry_next = Z_LDAP_RESULT_ENTRY_P(return_value);
1745 		ZVAL_COPY(&resultentry_next->res, &resultentry->res);
1746 		resultentry_next->data = entry_next;
1747 		resultentry_next->ber = NULL;
1748 	}
1749 }
1750 /* }}} */
1751 
1752 /* {{{ Get all result entries */
PHP_FUNCTION(ldap_get_entries)1753 PHP_FUNCTION(ldap_get_entries)
1754 {
1755 	zval *link, *result;
1756 	ldap_resultdata *ldap_result;
1757 	LDAPMessage *ldap_result_entry;
1758 	zval tmp1, tmp2;
1759 	ldap_linkdata *ld;
1760 	LDAP *ldap;
1761 	int num_entries, num_attrib, num_values, i;
1762 	BerElement *ber;
1763 	char *attribute;
1764 	size_t attr_len;
1765 	struct berval **ldap_value;
1766 	char *dn;
1767 
1768 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
1769 		RETURN_THROWS();
1770 	}
1771 
1772 	ld = Z_LDAP_LINK_P(link);
1773 	VERIFY_LDAP_LINK_CONNECTED(ld);
1774 
1775 	ldap_result = Z_LDAP_RESULT_P(result);
1776 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
1777 
1778 	ldap = ld->link;
1779 	num_entries = ldap_count_entries(ldap, ldap_result->result);
1780 
1781 	array_init(return_value);
1782 	add_assoc_long(return_value, "count", num_entries);
1783 
1784 	if (num_entries == 0) {
1785 		return;
1786 	}
1787 
1788 	ldap_result_entry = ldap_first_entry(ldap, ldap_result->result);
1789 	if (ldap_result_entry == NULL) {
1790 		zend_array_destroy(Z_ARR_P(return_value));
1791 		RETURN_FALSE;
1792 	}
1793 
1794 	num_entries = 0;
1795 	while (ldap_result_entry != NULL) {
1796 		array_init(&tmp1);
1797 
1798 		num_attrib = 0;
1799 		attribute = ldap_first_attribute(ldap, ldap_result_entry, &ber);
1800 
1801 		while (attribute != NULL) {
1802 			ldap_value = ldap_get_values_len(ldap, ldap_result_entry, attribute);
1803 			num_values = ldap_count_values_len(ldap_value);
1804 
1805 			array_init(&tmp2);
1806 			add_assoc_long(&tmp2, "count", num_values);
1807 			for (i = 0; i < num_values; i++) {
1808 				add_index_stringl(&tmp2, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1809 			}
1810 			ldap_value_free_len(ldap_value);
1811 
1812 			attr_len = strlen(attribute);
1813 			zend_str_tolower(attribute, attr_len);
1814 			zend_hash_str_update(Z_ARRVAL(tmp1), attribute, attr_len, &tmp2);
1815 			add_index_string(&tmp1, num_attrib, attribute);
1816 
1817 			num_attrib++;
1818 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1819 			ldap_memfree(attribute);
1820 #endif
1821 			attribute = ldap_next_attribute(ldap, ldap_result_entry, ber);
1822 		}
1823 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1824 		if (ber != NULL) {
1825 			ber_free(ber, 0);
1826 		}
1827 #endif
1828 
1829 		add_assoc_long(&tmp1, "count", num_attrib);
1830 		dn = ldap_get_dn(ldap, ldap_result_entry);
1831 		if (dn) {
1832 			add_assoc_string(&tmp1, "dn", dn);
1833 		} else {
1834 			add_assoc_null(&tmp1, "dn");
1835 		}
1836 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1837 		ldap_memfree(dn);
1838 #else
1839 		free(dn);
1840 #endif
1841 
1842 		zend_hash_index_update(Z_ARRVAL_P(return_value), num_entries, &tmp1);
1843 
1844 		num_entries++;
1845 		ldap_result_entry = ldap_next_entry(ldap, ldap_result_entry);
1846 	}
1847 
1848 	add_assoc_long(return_value, "count", num_entries);
1849 
1850 }
1851 /* }}} */
1852 
1853 /* {{{ Return first attribute */
PHP_FUNCTION(ldap_first_attribute)1854 PHP_FUNCTION(ldap_first_attribute)
1855 {
1856 	zval *link, *result_entry;
1857 	ldap_linkdata *ld;
1858 	ldap_result_entry *resultentry;
1859 	char *attribute;
1860 
1861 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
1862 		RETURN_THROWS();
1863 	}
1864 
1865 	ld = Z_LDAP_LINK_P(link);
1866 	VERIFY_LDAP_LINK_CONNECTED(ld);
1867 
1868 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
1869 
1870 	if ((attribute = ldap_first_attribute(ld->link, resultentry->data, &resultentry->ber)) == NULL) {
1871 		RETURN_FALSE;
1872 	} else {
1873 		RETVAL_STRING(attribute);
1874 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1875 		ldap_memfree(attribute);
1876 #endif
1877 	}
1878 }
1879 /* }}} */
1880 
1881 /* {{{ Get the next attribute in result */
PHP_FUNCTION(ldap_next_attribute)1882 PHP_FUNCTION(ldap_next_attribute)
1883 {
1884 	zval *link, *result_entry;
1885 	ldap_linkdata *ld;
1886 	ldap_result_entry *resultentry;
1887 	char *attribute;
1888 
1889 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
1890 		RETURN_THROWS();
1891 	}
1892 
1893 	ld = Z_LDAP_LINK_P(link);
1894 	VERIFY_LDAP_LINK_CONNECTED(ld);
1895 
1896 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
1897 
1898 	if (resultentry->ber == NULL) {
1899 		php_error_docref(NULL, E_WARNING, "Called before calling ldap_first_attribute() or no attributes found in result entry");
1900 		RETURN_FALSE;
1901 	}
1902 
1903 	if ((attribute = ldap_next_attribute(ld->link, resultentry->data, resultentry->ber)) == NULL) {
1904 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1905 		if (resultentry->ber != NULL) {
1906 			ber_free(resultentry->ber, 0);
1907 			resultentry->ber = NULL;
1908 		}
1909 #endif
1910 		RETURN_FALSE;
1911 	} else {
1912 		RETVAL_STRING(attribute);
1913 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1914 		ldap_memfree(attribute);
1915 #endif
1916 	}
1917 }
1918 /* }}} */
1919 
1920 /* {{{ Get attributes from a search result entry */
PHP_FUNCTION(ldap_get_attributes)1921 PHP_FUNCTION(ldap_get_attributes)
1922 {
1923 	zval *link, *result_entry;
1924 	zval tmp;
1925 	ldap_linkdata *ld;
1926 	ldap_result_entry *resultentry;
1927 	char *attribute;
1928 	struct berval **ldap_value;
1929 	int i, num_values, num_attrib;
1930 	BerElement *ber;
1931 
1932 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
1933 		RETURN_THROWS();
1934 	}
1935 
1936 	ld = Z_LDAP_LINK_P(link);
1937 	VERIFY_LDAP_LINK_CONNECTED(ld);
1938 
1939 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
1940 
1941 	array_init(return_value);
1942 	num_attrib = 0;
1943 
1944 	attribute = ldap_first_attribute(ld->link, resultentry->data, &ber);
1945 	while (attribute != NULL) {
1946 		ldap_value = ldap_get_values_len(ld->link, resultentry->data, attribute);
1947 		num_values = ldap_count_values_len(ldap_value);
1948 
1949 		array_init(&tmp);
1950 		add_assoc_long(&tmp, "count", num_values);
1951 		for (i = 0; i < num_values; i++) {
1952 			add_index_stringl(&tmp, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1953 		}
1954 		ldap_value_free_len(ldap_value);
1955 
1956 		zend_hash_str_update(Z_ARRVAL_P(return_value), attribute, strlen(attribute), &tmp);
1957 		add_index_string(return_value, num_attrib, attribute);
1958 
1959 		num_attrib++;
1960 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1961 		ldap_memfree(attribute);
1962 #endif
1963 		attribute = ldap_next_attribute(ld->link, resultentry->data, ber);
1964 	}
1965 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
1966 	if (ber != NULL) {
1967 		ber_free(ber, 0);
1968 	}
1969 #endif
1970 
1971 	add_assoc_long(return_value, "count", num_attrib);
1972 }
1973 /* }}} */
1974 
1975 /* {{{ Get all values with lengths from a result entry */
PHP_FUNCTION(ldap_get_values_len)1976 PHP_FUNCTION(ldap_get_values_len)
1977 {
1978 	zval *link, *result_entry;
1979 	ldap_linkdata *ld;
1980 	ldap_result_entry *resultentry;
1981 	char *attr;
1982 	struct berval **ldap_value_len;
1983 	int i, num_values;
1984 	size_t attr_len;
1985 
1986 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OOs", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce, &attr, &attr_len) != SUCCESS) {
1987 		RETURN_THROWS();
1988 	}
1989 
1990 	ld = Z_LDAP_LINK_P(link);
1991 	VERIFY_LDAP_LINK_CONNECTED(ld);
1992 
1993 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
1994 
1995 	if ((ldap_value_len = ldap_get_values_len(ld->link, resultentry->data, attr)) == NULL) {
1996 		php_error_docref(NULL, E_WARNING, "Cannot get the value(s) of attribute %s", ldap_err2string(_get_lderrno(ld->link)));
1997 		RETURN_FALSE;
1998 	}
1999 
2000 	num_values = ldap_count_values_len(ldap_value_len);
2001 	array_init(return_value);
2002 
2003 	for (i=0; i<num_values; i++) {
2004 		add_next_index_stringl(return_value, ldap_value_len[i]->bv_val, ldap_value_len[i]->bv_len);
2005 	}
2006 
2007 	add_assoc_long(return_value, "count", num_values);
2008 	ldap_value_free_len(ldap_value_len);
2009 
2010 }
2011 /* }}} */
2012 
2013 /* {{{ Get the DN of a result entry */
PHP_FUNCTION(ldap_get_dn)2014 PHP_FUNCTION(ldap_get_dn)
2015 {
2016 	zval *link, *result_entry;
2017 	ldap_linkdata *ld;
2018 	ldap_result_entry *resultentry;
2019 	char *text;
2020 
2021 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
2022 		RETURN_THROWS();
2023 	}
2024 
2025 	ld = Z_LDAP_LINK_P(link);
2026 	VERIFY_LDAP_LINK_CONNECTED(ld);
2027 
2028 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
2029 
2030 	text = ldap_get_dn(ld->link, resultentry->data);
2031 	if (text != NULL) {
2032 		RETVAL_STRING(text);
2033 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
2034 		ldap_memfree(text);
2035 #else
2036 		free(text);
2037 #endif
2038 	} else {
2039 		RETURN_FALSE;
2040 	}
2041 }
2042 /* }}} */
2043 
2044 /* {{{ Splits DN into its component parts */
PHP_FUNCTION(ldap_explode_dn)2045 PHP_FUNCTION(ldap_explode_dn)
2046 {
2047 	zend_long with_attrib;
2048 	char *dn, **ldap_value;
2049 	int i, count;
2050 	size_t dn_len;
2051 
2052 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &dn, &dn_len, &with_attrib) != SUCCESS) {
2053 		RETURN_THROWS();
2054 	}
2055 
2056 	if (!(ldap_value = ldap_explode_dn(dn, with_attrib))) {
2057 		/* Invalid parameters were passed to ldap_explode_dn */
2058 		RETURN_FALSE;
2059 	}
2060 
2061 	i=0;
2062 	while (ldap_value[i] != NULL) i++;
2063 	count = i;
2064 
2065 	array_init(return_value);
2066 
2067 	add_assoc_long(return_value, "count", count);
2068 	for (i = 0; i<count; i++) {
2069 		add_index_string(return_value, i, ldap_value[i]);
2070 	}
2071 
2072 	ldap_memvfree((void **)ldap_value);
2073 }
2074 /* }}} */
2075 
2076 /* {{{ Convert DN to User Friendly Naming format */
PHP_FUNCTION(ldap_dn2ufn)2077 PHP_FUNCTION(ldap_dn2ufn)
2078 {
2079 	char *dn, *ufn;
2080 	size_t dn_len;
2081 
2082 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dn, &dn_len) != SUCCESS) {
2083 		RETURN_THROWS();
2084 	}
2085 
2086 	ufn = ldap_dn2ufn(dn);
2087 
2088 	if (ufn != NULL) {
2089 		RETVAL_STRING(ufn);
2090 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) || WINDOWS
2091 		ldap_memfree(ufn);
2092 #endif
2093 	} else {
2094 		RETURN_FALSE;
2095 	}
2096 }
2097 /* }}} */
2098 
2099 
2100 /* added to fix use of ldap_modify_add for doing an ldap_add, gerrit thomson. */
2101 #define PHP_LD_FULL_ADD 0xff
2102 /* {{{ php_ldap_do_modify */
php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS,int oper,int ext)2103 static void php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper, int ext)
2104 {
2105 	zval *serverctrls = NULL;
2106 	zval *link, *entry, *value, *ivalue;
2107 	ldap_linkdata *ld;
2108 	char *dn;
2109 	LDAPMod **ldap_mods;
2110 	LDAPControl **lserverctrls = NULL;
2111 	ldap_resultdata *result;
2112 	LDAPMessage *ldap_res;
2113 	int i, j, num_attribs, num_values, msgid;
2114 	size_t dn_len;
2115 	int *num_berval;
2116 	zend_string *attribute;
2117 	zend_ulong index;
2118 	int is_full_add=0; /* flag for full add operation so ldap_mod_add can be put back into oper, gerrit THomson */
2119 
2120 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osa/|a!", &link, ldap_link_ce, &dn, &dn_len, &entry, &serverctrls) != SUCCESS) {
2121 		RETURN_THROWS();
2122 	}
2123 
2124 	ld = Z_LDAP_LINK_P(link);
2125 	VERIFY_LDAP_LINK_CONNECTED(ld);
2126 
2127 	num_attribs = zend_hash_num_elements(Z_ARRVAL_P(entry));
2128 	ldap_mods = safe_emalloc((num_attribs+1), sizeof(LDAPMod *), 0);
2129 	num_berval = safe_emalloc(num_attribs, sizeof(int), 0);
2130 	zend_hash_internal_pointer_reset(Z_ARRVAL_P(entry));
2131 
2132 	/* added by gerrit thomson to fix ldap_add using ldap_mod_add */
2133 	if (oper == PHP_LD_FULL_ADD) {
2134 		oper = LDAP_MOD_ADD;
2135 		is_full_add = 1;
2136 	}
2137 	/* end additional , gerrit thomson */
2138 
2139 	for (i = 0; i < num_attribs; i++) {
2140 		ldap_mods[i] = emalloc(sizeof(LDAPMod));
2141 		ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
2142 		ldap_mods[i]->mod_type = NULL;
2143 
2144 		if (zend_hash_get_current_key(Z_ARRVAL_P(entry), &attribute, &index) == HASH_KEY_IS_STRING) {
2145 			ldap_mods[i]->mod_type = estrndup(ZSTR_VAL(attribute), ZSTR_LEN(attribute));
2146 		} else {
2147 			php_error_docref(NULL, E_WARNING, "Unknown attribute in the data");
2148 			/* Free allocated memory */
2149 			while (i >= 0) {
2150 				if (ldap_mods[i]->mod_type) {
2151 					efree(ldap_mods[i]->mod_type);
2152 				}
2153 				efree(ldap_mods[i]);
2154 				i--;
2155 			}
2156 			efree(num_berval);
2157 			efree(ldap_mods);
2158 			RETURN_FALSE;
2159 		}
2160 
2161 		value = zend_hash_get_current_data(Z_ARRVAL_P(entry));
2162 
2163 		ZVAL_DEREF(value);
2164 		if (Z_TYPE_P(value) != IS_ARRAY) {
2165 			num_values = 1;
2166 		} else {
2167 			SEPARATE_ARRAY(value);
2168 			num_values = zend_hash_num_elements(Z_ARRVAL_P(value));
2169 		}
2170 
2171 		num_berval[i] = num_values;
2172 		ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0);
2173 
2174 /* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */
2175 		if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) {
2176 			convert_to_string(value);
2177 			if (EG(exception)) {
2178 				RETVAL_FALSE;
2179 				goto cleanup;
2180 			}
2181 			ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval));
2182 			ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value);
2183 			ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value);
2184 		} else {
2185 			for (j = 0; j < num_values; j++) {
2186 				if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) {
2187 					zend_argument_value_error(3, "must contain arrays with consecutive integer indices starting from 0");
2188 					num_berval[i] = j;
2189 					num_attribs = i + 1;
2190 					RETVAL_FALSE;
2191 					goto cleanup;
2192 				}
2193 				convert_to_string(ivalue);
2194 				if (EG(exception)) {
2195 					RETVAL_FALSE;
2196 					goto cleanup;
2197 				}
2198 				ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval));
2199 				ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue);
2200 				ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue);
2201 			}
2202 		}
2203 		ldap_mods[i]->mod_bvalues[num_values] = NULL;
2204 		zend_hash_move_forward(Z_ARRVAL_P(entry));
2205 	}
2206 	ldap_mods[num_attribs] = NULL;
2207 
2208 	if (serverctrls) {
2209 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
2210 		if (lserverctrls == NULL) {
2211 			RETVAL_FALSE;
2212 			goto cleanup;
2213 		}
2214 	}
2215 
2216 /* check flag to see if do_mod was called to perform full add , gerrit thomson */
2217 	if (is_full_add == 1) {
2218 		if (ext) {
2219 			i = ldap_add_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2220 		} else {
2221 			i = ldap_add_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2222 		}
2223 		if (i != LDAP_SUCCESS) {
2224 			php_error_docref(NULL, E_WARNING, "Add: %s", ldap_err2string(i));
2225 			RETVAL_FALSE;
2226 		} else if (ext) {
2227 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2228 			if (i == -1) {
2229 				php_error_docref(NULL, E_WARNING, "Add operation failed");
2230 				RETVAL_FALSE;
2231 				goto cleanup;
2232 			}
2233 
2234 			/* return a PHP control object */
2235 			object_init_ex(return_value, ldap_result_ce);
2236 			result = Z_LDAP_RESULT_P(return_value);
2237 			result->result = ldap_res;
2238 		} else RETVAL_TRUE;
2239 	} else {
2240 		if (ext) {
2241 			i = ldap_modify_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2242 		} else {
2243 			i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2244 		}
2245 		if (i != LDAP_SUCCESS) {
2246 			php_error_docref(NULL, E_WARNING, "Modify: %s", ldap_err2string(i));
2247 			RETVAL_FALSE;
2248 		} else if (ext) {
2249 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2250 			if (i == -1) {
2251 				php_error_docref(NULL, E_WARNING, "Modify operation failed");
2252 				RETVAL_FALSE;
2253 				goto cleanup;
2254 			}
2255 
2256 			/* return a PHP control object */
2257 			object_init_ex(return_value, ldap_result_ce);
2258 			result = Z_LDAP_RESULT_P(return_value);
2259 			result->result = ldap_res;
2260 		} else RETVAL_TRUE;
2261 	}
2262 
2263 cleanup:
2264 	for (i = 0; i < num_attribs; i++) {
2265 		efree(ldap_mods[i]->mod_type);
2266 		for (j = 0; j < num_berval[i]; j++) {
2267 			efree(ldap_mods[i]->mod_bvalues[j]);
2268 		}
2269 		efree(ldap_mods[i]->mod_bvalues);
2270 		efree(ldap_mods[i]);
2271 	}
2272 	efree(num_berval);
2273 	efree(ldap_mods);
2274 
2275 	if (lserverctrls) {
2276 		_php_ldap_controls_free(&lserverctrls);
2277 	}
2278 
2279 	return;
2280 }
2281 /* }}} */
2282 
2283 /* {{{ Add entries to LDAP directory */
PHP_FUNCTION(ldap_add)2284 PHP_FUNCTION(ldap_add)
2285 {
2286 	/* 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 */
2287 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 0);
2288 }
2289 /* }}} */
2290 
2291 /* {{{ Add entries to LDAP directory */
PHP_FUNCTION(ldap_add_ext)2292 PHP_FUNCTION(ldap_add_ext)
2293 {
2294 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 1);
2295 }
2296 /* }}} */
2297 
2298 /* three functions for attribute base modifications, gerrit Thomson */
2299 
2300 /* {{{ Replace attribute values with new ones */
PHP_FUNCTION(ldap_mod_replace)2301 PHP_FUNCTION(ldap_mod_replace)
2302 {
2303 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 0);
2304 }
2305 /* }}} */
2306 
2307 /* {{{ Replace attribute values with new ones */
PHP_FUNCTION(ldap_mod_replace_ext)2308 PHP_FUNCTION(ldap_mod_replace_ext)
2309 {
2310 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 1);
2311 }
2312 /* }}} */
2313 
2314 /* {{{ Add attribute values to current */
PHP_FUNCTION(ldap_mod_add)2315 PHP_FUNCTION(ldap_mod_add)
2316 {
2317 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 0);
2318 }
2319 /* }}} */
2320 
2321 /* {{{ Add attribute values to current */
PHP_FUNCTION(ldap_mod_add_ext)2322 PHP_FUNCTION(ldap_mod_add_ext)
2323 {
2324 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 1);
2325 }
2326 /* }}} */
2327 
2328 /* {{{ Delete attribute values */
PHP_FUNCTION(ldap_mod_del)2329 PHP_FUNCTION(ldap_mod_del)
2330 {
2331 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 0);
2332 }
2333 /* }}} */
2334 
2335 /* {{{ Delete attribute values */
PHP_FUNCTION(ldap_mod_del_ext)2336 PHP_FUNCTION(ldap_mod_del_ext)
2337 {
2338 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 1);
2339 }
2340 /* }}} */
2341 
2342 /* {{{ php_ldap_do_delete */
php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS,int ext)2343 static void php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS, int ext)
2344 {
2345 	zval *serverctrls = NULL;
2346 	zval *link;
2347 	ldap_linkdata *ld;
2348 	LDAPControl **lserverctrls = NULL;
2349 	ldap_resultdata *result;
2350 	LDAPMessage *ldap_res;
2351 	char *dn;
2352 	int rc, msgid;
2353 	size_t dn_len;
2354 
2355 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Os|a!", &link, ldap_link_ce, &dn, &dn_len, &serverctrls) != SUCCESS) {
2356 		RETURN_THROWS();
2357 	}
2358 
2359 	ld = Z_LDAP_LINK_P(link);
2360 	VERIFY_LDAP_LINK_CONNECTED(ld);
2361 
2362 	if (serverctrls) {
2363 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 3);
2364 		if (lserverctrls == NULL) {
2365 			RETVAL_FALSE;
2366 			goto cleanup;
2367 		}
2368 	}
2369 
2370 	if (ext) {
2371 		rc = ldap_delete_ext(ld->link, dn, lserverctrls, NULL, &msgid);
2372 	} else {
2373 		rc = ldap_delete_ext_s(ld->link, dn, lserverctrls, NULL);
2374 	}
2375 	if (rc != LDAP_SUCCESS) {
2376 		php_error_docref(NULL, E_WARNING, "Delete: %s", ldap_err2string(rc));
2377 		RETVAL_FALSE;
2378 		goto cleanup;
2379 	} else if (ext) {
2380 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2381 		if (rc == -1) {
2382 			php_error_docref(NULL, E_WARNING, "Delete operation failed");
2383 			RETVAL_FALSE;
2384 			goto cleanup;
2385 		}
2386 
2387 		/* return a PHP control object */
2388 		object_init_ex(return_value, ldap_result_ce);
2389 		result = Z_LDAP_RESULT_P(return_value);
2390 		result->result = ldap_res;
2391 	} else {
2392 		RETVAL_TRUE;
2393 	}
2394 
2395 cleanup:
2396 	if (lserverctrls) {
2397 		_php_ldap_controls_free(&lserverctrls);
2398 	}
2399 
2400 	return;
2401 }
2402 /* }}} */
2403 
2404 /* {{{ Delete an entry from a directory */
PHP_FUNCTION(ldap_delete)2405 PHP_FUNCTION(ldap_delete)
2406 {
2407 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2408 }
2409 /* }}} */
2410 
2411 /* {{{ Delete an entry from a directory */
PHP_FUNCTION(ldap_delete_ext)2412 PHP_FUNCTION(ldap_delete_ext)
2413 {
2414 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2415 }
2416 /* }}} */
2417 
2418 /* {{{ _ldap_str_equal_to_const */
_ldap_str_equal_to_const(const char * str,size_t str_len,const char * cstr)2419 static size_t _ldap_str_equal_to_const(const char *str, size_t str_len, const char *cstr)
2420 {
2421 	size_t i;
2422 
2423 	if (strlen(cstr) != str_len)
2424 		return 0;
2425 
2426 	for (i = 0; i < str_len; ++i) {
2427 		if (str[i] != cstr[i]) {
2428 			return 0;
2429 		}
2430 	}
2431 
2432 	return 1;
2433 }
2434 /* }}} */
2435 
2436 /* {{{ _ldap_strlen_max */
_ldap_strlen_max(const char * str,size_t max_len)2437 static size_t _ldap_strlen_max(const char *str, size_t max_len)
2438 {
2439 	size_t i;
2440 
2441 	for (i = 0; i < max_len; ++i) {
2442 		if (str[i] == '\0') {
2443 			return i;
2444 		}
2445 	}
2446 
2447 	return max_len;
2448 }
2449 /* }}} */
2450 
2451 /* {{{ _ldap_hash_fetch */
_ldap_hash_fetch(zval * hashTbl,const char * key,zval ** out)2452 static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)
2453 {
2454 	*out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key));
2455 }
2456 /* }}} */
2457 
2458 /* {{{ Perform multiple modifications as part of one operation */
PHP_FUNCTION(ldap_modify_batch)2459 PHP_FUNCTION(ldap_modify_batch)
2460 {
2461 	zval *serverctrls = NULL;
2462 	ldap_linkdata *ld;
2463 	zval *link, *mods, *mod, *modinfo;
2464 	zend_string *modval;
2465 	zval *attrib, *modtype, *vals;
2466 	zval *fetched;
2467 	char *dn;
2468 	size_t dn_len;
2469 	int i, j, k;
2470 	int num_mods, num_modprops, num_modvals;
2471 	LDAPMod **ldap_mods;
2472 	LDAPControl **lserverctrls = NULL;
2473 	uint32_t oper;
2474 
2475 	/*
2476 	$mods = array(
2477 		array(
2478 			"attrib" => "unicodePwd",
2479 			"modtype" => LDAP_MODIFY_BATCH_REMOVE,
2480 			"values" => array($oldpw)
2481 		),
2482 		array(
2483 			"attrib" => "unicodePwd",
2484 			"modtype" => LDAP_MODIFY_BATCH_ADD,
2485 			"values" => array($newpw)
2486 		),
2487 		array(
2488 			"attrib" => "userPrincipalName",
2489 			"modtype" => LDAP_MODIFY_BATCH_REPLACE,
2490 			"values" => array("janitor@corp.contoso.com")
2491 		),
2492 		array(
2493 			"attrib" => "userCert",
2494 			"modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL
2495 		)
2496 	);
2497 	*/
2498 
2499 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osa/|a!", &link, ldap_link_ce, &dn, &dn_len, &mods, &serverctrls) != SUCCESS) {
2500 		RETURN_THROWS();
2501 	}
2502 
2503 	ld = Z_LDAP_LINK_P(link);
2504 	VERIFY_LDAP_LINK_CONNECTED(ld);
2505 
2506 	/* perform validation */
2507 	{
2508 		zend_string *modkey;
2509 		zend_long modtype;
2510 
2511 		/* to store the wrongly-typed keys */
2512 		zend_ulong tmpUlong;
2513 
2514 		/* make sure the DN contains no NUL bytes */
2515 		if (_ldap_strlen_max(dn, dn_len) != dn_len) {
2516 			zend_argument_type_error(2, "must not contain null bytes");
2517 			RETURN_THROWS();
2518 		}
2519 
2520 		/* make sure the top level is a normal array */
2521 		zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods));
2522 		if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) {
2523 			zend_argument_type_error(3, "must be integer-indexed");
2524 			RETURN_THROWS();
2525 		}
2526 
2527 		num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods));
2528 
2529 		for (i = 0; i < num_mods; i++) {
2530 			/* is the numbering consecutive? */
2531 			if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) {
2532 				zend_argument_value_error(3, "must have consecutive integer indices starting from 0");
2533 				RETURN_THROWS();
2534 			}
2535 			mod = fetched;
2536 
2537 			/* is it an array? */
2538 			if (Z_TYPE_P(mod) != IS_ARRAY) {
2539 				zend_argument_value_error(3, "must only contain arrays");
2540 				RETURN_THROWS();
2541 			}
2542 
2543 			SEPARATE_ARRAY(mod);
2544 			/* for the modification hashtable... */
2545 			zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod));
2546 			num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod));
2547 			bool has_attrib_key = false;
2548 			bool has_modtype_key = false;
2549 
2550 			for (j = 0; j < num_modprops; j++) {
2551 
2552 				/* are the keys strings? */
2553 				if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong) != HASH_KEY_IS_STRING) {
2554 					zend_argument_type_error(3, "must only contain string-indexed arrays");
2555 					RETURN_THROWS();
2556 				}
2557 
2558 				/* is this a valid entry? */
2559 				if (
2560 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB) &&
2561 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE) &&
2562 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)
2563 				) {
2564 					zend_argument_value_error(3, "must contain arrays only containing the \"" LDAP_MODIFY_BATCH_ATTRIB "\", \"" LDAP_MODIFY_BATCH_MODTYPE "\" and \"" LDAP_MODIFY_BATCH_VALUES "\" keys");
2565 					RETURN_THROWS();
2566 				}
2567 
2568 				fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod));
2569 				modinfo = fetched;
2570 
2571 				/* does the value type match the key? */
2572 				if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB)) {
2573 					has_attrib_key = true;
2574 					if (Z_TYPE_P(modinfo) != IS_STRING) {
2575 						zend_type_error("%s(): Option \"" LDAP_MODIFY_BATCH_ATTRIB "\" must be of type string, %s given", get_active_function_name(), zend_zval_type_name(modinfo));
2576 						RETURN_THROWS();
2577 					}
2578 
2579 					if (Z_STRLEN_P(modinfo) != _ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) {
2580 						zend_type_error("%s(): Option \"" LDAP_MODIFY_BATCH_ATTRIB "\" cannot contain null-bytes", get_active_function_name());
2581 						RETURN_THROWS();
2582 					}
2583 				}
2584 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE)) {
2585 					has_modtype_key = true;
2586 					if (Z_TYPE_P(modinfo) != IS_LONG) {
2587 						zend_type_error("%s(): Option \"" LDAP_MODIFY_BATCH_MODTYPE "\" must be of type int, %s given", get_active_function_name(), zend_zval_type_name(modinfo));
2588 						RETURN_THROWS();
2589 					}
2590 
2591 					/* is the value in range? */
2592 					modtype = Z_LVAL_P(modinfo);
2593 					if (
2594 						modtype != LDAP_MODIFY_BATCH_ADD &&
2595 						modtype != LDAP_MODIFY_BATCH_REMOVE &&
2596 						modtype != LDAP_MODIFY_BATCH_REPLACE &&
2597 						modtype != LDAP_MODIFY_BATCH_REMOVE_ALL
2598 					) {
2599 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_MODTYPE "\" must be one of the LDAP_MODIFY_BATCH_* constants", get_active_function_name());
2600 						RETURN_THROWS();
2601 					}
2602 
2603 					/* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */
2604 					if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2605 						if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2606 							zend_value_error("%s(): If option \"" LDAP_MODIFY_BATCH_MODTYPE "\" is LDAP_MODIFY_BATCH_REMOVE_ALL, option \"" LDAP_MODIFY_BATCH_VALUES "\" cannot be provided", get_active_function_name());
2607 							RETURN_THROWS();
2608 						}
2609 					}
2610 					else {
2611 						if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2612 							zend_value_error("%s(): If option \"" LDAP_MODIFY_BATCH_MODTYPE "\" is not LDAP_MODIFY_BATCH_REMOVE_ALL, option \"" LDAP_MODIFY_BATCH_VALUES "\" must be provided", get_active_function_name());
2613 							RETURN_THROWS();
2614 						}
2615 					}
2616 				}
2617 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)) {
2618 					if (Z_TYPE_P(modinfo) != IS_ARRAY) {
2619 						zend_type_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" must be of type array, %s given", get_active_function_name(), zend_zval_type_name(modinfo));
2620 						RETURN_THROWS();
2621 					}
2622 
2623 					SEPARATE_ARRAY(modinfo);
2624 					/* is the array not empty? */
2625 					zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo));
2626 					num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo));
2627 					if (num_modvals == 0) {
2628 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" cannot be empty", get_active_function_name());
2629 						RETURN_THROWS();
2630 					}
2631 
2632 					/* are its keys integers? */
2633 					if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) {
2634 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" must be integer-indexed", get_active_function_name());
2635 						RETURN_THROWS();
2636 					}
2637 
2638 					/* are the keys consecutive? */
2639 					for (k = 0; k < num_modvals; k++) {
2640 						if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) {
2641 							zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" must have consecutive integer indices starting from 0", get_active_function_name());
2642 							RETURN_THROWS();
2643 						}
2644 					}
2645 				}
2646 
2647 				zend_hash_move_forward(Z_ARRVAL_P(mod));
2648 			}
2649 
2650 			if (!has_attrib_key) {
2651 				zend_value_error("%s(): Required option \"" LDAP_MODIFY_BATCH_ATTRIB "\" is missing", get_active_function_name());
2652 				RETURN_THROWS();
2653 			}
2654 			if (!has_modtype_key) {
2655 				zend_value_error("%s(): Required option \"" LDAP_MODIFY_BATCH_MODTYPE "\" is missing", get_active_function_name());
2656 				RETURN_THROWS();
2657 			}
2658 		}
2659 	}
2660 	/* validation was successful */
2661 
2662 	/* allocate array of modifications */
2663 	ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0);
2664 
2665 	/* for each modification */
2666 	for (i = 0; i < num_mods; i++) {
2667 		/* allocate the modification struct */
2668 		ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0);
2669 
2670 		/* fetch the relevant data */
2671 		fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i);
2672 		mod = fetched;
2673 
2674 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib);
2675 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype);
2676 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals);
2677 
2678 		/* map the modification type */
2679 		switch (Z_LVAL_P(modtype)) {
2680 			case LDAP_MODIFY_BATCH_ADD:
2681 				oper = LDAP_MOD_ADD;
2682 				break;
2683 			case LDAP_MODIFY_BATCH_REMOVE:
2684 			case LDAP_MODIFY_BATCH_REMOVE_ALL:
2685 				oper = LDAP_MOD_DELETE;
2686 				break;
2687 			case LDAP_MODIFY_BATCH_REPLACE:
2688 				oper = LDAP_MOD_REPLACE;
2689 				break;
2690 			default:
2691 				zend_throw_error(NULL, "Unknown and uncaught modification type.");
2692 				RETVAL_FALSE;
2693 				efree(ldap_mods[i]);
2694 				num_mods = i;
2695 				goto cleanup;
2696 		}
2697 
2698 		/* fill in the basic info */
2699 		ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
2700 		ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib));
2701 
2702 		if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2703 			/* no values */
2704 			ldap_mods[i]->mod_bvalues = NULL;
2705 		}
2706 		else {
2707 			/* allocate space for the values as part of this modification */
2708 			num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals));
2709 			ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0);
2710 
2711 			/* for each value */
2712 			for (j = 0; j < num_modvals; j++) {
2713 				/* fetch it */
2714 				fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j);
2715 				modval = zval_get_string(fetched);
2716 				if (EG(exception)) {
2717 					RETVAL_FALSE;
2718 					ldap_mods[i]->mod_bvalues[j] = NULL;
2719 					num_mods = i + 1;
2720 					goto cleanup;
2721 				}
2722 
2723 				/* allocate the data struct */
2724 				ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0);
2725 
2726 				/* fill it */
2727 				ldap_mods[i]->mod_bvalues[j]->bv_len = ZSTR_LEN(modval);
2728 				ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(ZSTR_VAL(modval), ZSTR_LEN(modval));
2729 				zend_string_release(modval);
2730 			}
2731 
2732 			/* NULL-terminate values */
2733 			ldap_mods[i]->mod_bvalues[num_modvals] = NULL;
2734 		}
2735 	}
2736 
2737 	/* NULL-terminate modifications */
2738 	ldap_mods[num_mods] = NULL;
2739 
2740 	if (serverctrls) {
2741 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
2742 		if (lserverctrls == NULL) {
2743 			RETVAL_FALSE;
2744 			goto cleanup;
2745 		}
2746 	}
2747 
2748 	/* perform (finally) */
2749 	if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL)) != LDAP_SUCCESS) {
2750 		php_error_docref(NULL, E_WARNING, "Batch Modify: %s", ldap_err2string(i));
2751 		RETVAL_FALSE;
2752 	} else RETVAL_TRUE;
2753 
2754 	/* clean up */
2755 	cleanup: {
2756 		for (i = 0; i < num_mods; i++) {
2757 			/* attribute */
2758 			efree(ldap_mods[i]->mod_type);
2759 
2760 			if (ldap_mods[i]->mod_bvalues != NULL) {
2761 				/* each BER value */
2762 				for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) {
2763 					/* free the data bytes */
2764 					efree(ldap_mods[i]->mod_bvalues[j]->bv_val);
2765 
2766 					/* free the bvalue struct */
2767 					efree(ldap_mods[i]->mod_bvalues[j]);
2768 				}
2769 
2770 				/* the BER value array */
2771 				efree(ldap_mods[i]->mod_bvalues);
2772 			}
2773 
2774 			/* the modification */
2775 			efree(ldap_mods[i]);
2776 		}
2777 
2778 		/* the modifications array */
2779 		efree(ldap_mods);
2780 
2781 		if (lserverctrls) {
2782 			_php_ldap_controls_free(&lserverctrls);
2783 		}
2784 	}
2785 }
2786 /* }}} */
2787 
2788 /* {{{ Get the current ldap error number */
PHP_FUNCTION(ldap_errno)2789 PHP_FUNCTION(ldap_errno)
2790 {
2791 	zval *link;
2792 	ldap_linkdata *ld;
2793 
2794 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
2795 		RETURN_THROWS();
2796 	}
2797 
2798 	ld = Z_LDAP_LINK_P(link);
2799 	VERIFY_LDAP_LINK_CONNECTED(ld);
2800 
2801 	RETURN_LONG(_get_lderrno(ld->link));
2802 }
2803 /* }}} */
2804 
2805 /* {{{ Convert error number to error string */
PHP_FUNCTION(ldap_err2str)2806 PHP_FUNCTION(ldap_err2str)
2807 {
2808 	zend_long perrno;
2809 
2810 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perrno) != SUCCESS) {
2811 		RETURN_THROWS();
2812 	}
2813 
2814 	RETURN_STRING(ldap_err2string(perrno));
2815 }
2816 /* }}} */
2817 
2818 /* {{{ Get the current ldap error string */
PHP_FUNCTION(ldap_error)2819 PHP_FUNCTION(ldap_error)
2820 {
2821 	zval *link;
2822 	ldap_linkdata *ld;
2823 	int ld_errno;
2824 
2825 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
2826 		RETURN_THROWS();
2827 	}
2828 
2829 	ld = Z_LDAP_LINK_P(link);
2830 	VERIFY_LDAP_LINK_CONNECTED(ld);
2831 
2832 	ld_errno = _get_lderrno(ld->link);
2833 
2834 	RETURN_STRING(ldap_err2string(ld_errno));
2835 }
2836 /* }}} */
2837 
2838 /* {{{ Determine if an entry has a specific value for one of its attributes */
PHP_FUNCTION(ldap_compare)2839 PHP_FUNCTION(ldap_compare)
2840 {
2841 	zval *serverctrls = NULL;
2842 	zval *link;
2843 	char *dn, *attr, *value;
2844 	size_t dn_len, attr_len, value_len;
2845 	ldap_linkdata *ld;
2846 	LDAPControl **lserverctrls = NULL;
2847 	int ldap_errno;
2848 	struct berval lvalue;
2849 
2850 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osss|a!", &link, ldap_link_ce, &dn, &dn_len, &attr, &attr_len, &value, &value_len, &serverctrls) != SUCCESS) {
2851 		RETURN_THROWS();
2852 	}
2853 
2854 	ld = Z_LDAP_LINK_P(link);
2855 	VERIFY_LDAP_LINK_CONNECTED(ld);
2856 
2857 	if (serverctrls) {
2858 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 5);
2859 		if (lserverctrls == NULL) {
2860 			RETVAL_FALSE;
2861 			goto cleanup;
2862 		}
2863 	}
2864 
2865 	lvalue.bv_val = value;
2866 	lvalue.bv_len = value_len;
2867 
2868 	ldap_errno = ldap_compare_ext_s(ld->link, dn, attr, &lvalue, lserverctrls, NULL);
2869 
2870 	switch (ldap_errno) {
2871 		case LDAP_COMPARE_TRUE:
2872 			RETVAL_TRUE;
2873 			break;
2874 
2875 		case LDAP_COMPARE_FALSE:
2876 			RETVAL_FALSE;
2877 			break;
2878 
2879 		default:
2880 			php_error_docref(NULL, E_WARNING, "Compare: %s", ldap_err2string(ldap_errno));
2881 			RETVAL_LONG(-1);
2882 	}
2883 
2884 cleanup:
2885 	if (lserverctrls) {
2886 		_php_ldap_controls_free(&lserverctrls);
2887 	}
2888 
2889 	return;
2890 }
2891 /* }}} */
2892 
2893 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP)
2894 /* {{{ Get the current value of various session-wide parameters */
PHP_FUNCTION(ldap_get_option)2895 PHP_FUNCTION(ldap_get_option)
2896 {
2897 	zval *link, *retval;
2898 	ldap_linkdata *ld;
2899 	zend_long option;
2900 
2901 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Olz", &link, ldap_link_ce, &option, &retval) != SUCCESS) {
2902 		RETURN_THROWS();
2903 	}
2904 
2905 	ld = Z_LDAP_LINK_P(link);
2906 	VERIFY_LDAP_LINK_CONNECTED(ld);
2907 
2908 	switch (option) {
2909 	/* options with int value */
2910 	case LDAP_OPT_DEREF:
2911 	case LDAP_OPT_SIZELIMIT:
2912 	case LDAP_OPT_TIMELIMIT:
2913 	case LDAP_OPT_PROTOCOL_VERSION:
2914 	case LDAP_OPT_ERROR_NUMBER:
2915 	case LDAP_OPT_REFERRALS:
2916 #ifdef LDAP_OPT_RESTART
2917 	case LDAP_OPT_RESTART:
2918 #endif
2919 #ifdef LDAP_OPT_X_SASL_NOCANON
2920 	case LDAP_OPT_X_SASL_NOCANON:
2921 #endif
2922 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
2923 	case LDAP_OPT_X_TLS_REQUIRE_CERT:
2924 #endif
2925 #ifdef LDAP_OPT_X_TLS_CRLCHECK
2926 	case LDAP_OPT_X_TLS_CRLCHECK:
2927 #endif
2928 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
2929 	case LDAP_OPT_X_TLS_PROTOCOL_MIN:
2930 #endif
2931 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
2932 	case LDAP_OPT_X_KEEPALIVE_IDLE:
2933 	case LDAP_OPT_X_KEEPALIVE_PROBES:
2934 	case LDAP_OPT_X_KEEPALIVE_INTERVAL:
2935 #endif
2936 		{
2937 			int val;
2938 
2939 			if (ldap_get_option(ld->link, option, &val)) {
2940 				RETURN_FALSE;
2941 			}
2942 			ZEND_TRY_ASSIGN_REF_LONG(retval, val);
2943 		} break;
2944 #ifdef LDAP_OPT_NETWORK_TIMEOUT
2945 	case LDAP_OPT_NETWORK_TIMEOUT:
2946 		{
2947 			struct timeval *timeout = NULL;
2948 
2949 			if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
2950 				if (timeout) {
2951 					ldap_memfree(timeout);
2952 				}
2953 				RETURN_FALSE;
2954 			}
2955 			if (!timeout) {
2956 				RETURN_FALSE;
2957 			}
2958 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
2959 			ldap_memfree(timeout);
2960 		} break;
2961 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
2962 	case LDAP_X_OPT_CONNECT_TIMEOUT:
2963 		{
2964 			int timeout;
2965 
2966 			if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
2967 				RETURN_FALSE;
2968 			}
2969 			ZEND_TRY_ASSIGN_REF_LONG(retval, (timeout / 1000));
2970 		} break;
2971 #endif
2972 #ifdef LDAP_OPT_TIMEOUT
2973 	case LDAP_OPT_TIMEOUT:
2974 		{
2975 			struct timeval *timeout = NULL;
2976 
2977 			if (ldap_get_option(ld->link, LDAP_OPT_TIMEOUT, (void *) &timeout)) {
2978 				if (timeout) {
2979 					ldap_memfree(timeout);
2980 				}
2981 				RETURN_FALSE;
2982 			}
2983 			if (!timeout) {
2984 				RETURN_FALSE;
2985 			}
2986 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
2987 			ldap_memfree(timeout);
2988 		} break;
2989 #endif
2990 	/* options with string value */
2991 	case LDAP_OPT_ERROR_STRING:
2992 #ifdef LDAP_OPT_HOST_NAME
2993 	case LDAP_OPT_HOST_NAME:
2994 #endif
2995 #ifdef HAVE_LDAP_SASL
2996 	case LDAP_OPT_X_SASL_MECH:
2997 	case LDAP_OPT_X_SASL_REALM:
2998 	case LDAP_OPT_X_SASL_AUTHCID:
2999 	case LDAP_OPT_X_SASL_AUTHZID:
3000 #endif
3001 #ifdef LDAP_OPT_X_SASL_USERNAME
3002 	case LDAP_OPT_X_SASL_USERNAME:
3003 #endif
3004 #if (LDAP_API_VERSION > 2000)
3005 	case LDAP_OPT_X_TLS_CACERTDIR:
3006 	case LDAP_OPT_X_TLS_CACERTFILE:
3007 	case LDAP_OPT_X_TLS_CERTFILE:
3008 	case LDAP_OPT_X_TLS_CIPHER_SUITE:
3009 	case LDAP_OPT_X_TLS_KEYFILE:
3010 	case LDAP_OPT_X_TLS_RANDOM_FILE:
3011 #endif
3012 #ifdef LDAP_OPT_X_TLS_PACKAGE
3013 	case LDAP_OPT_X_TLS_PACKAGE:
3014 #endif
3015 #ifdef LDAP_OPT_X_TLS_CRLFILE
3016 	case LDAP_OPT_X_TLS_CRLFILE:
3017 #endif
3018 #ifdef LDAP_OPT_X_TLS_DHFILE
3019 	case LDAP_OPT_X_TLS_DHFILE:
3020 #endif
3021 #ifdef LDAP_OPT_MATCHED_DN
3022 	case LDAP_OPT_MATCHED_DN:
3023 #endif
3024 		{
3025 			char *val = NULL;
3026 
3027 			if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') {
3028 				if (val) {
3029 					ldap_memfree(val);
3030 				}
3031 				RETURN_FALSE;
3032 			}
3033 			ZEND_TRY_ASSIGN_REF_STRING(retval, val);
3034 			ldap_memfree(val);
3035 		} break;
3036 	case LDAP_OPT_SERVER_CONTROLS:
3037 	case LDAP_OPT_CLIENT_CONTROLS:
3038 		{
3039 			LDAPControl **ctrls = NULL;
3040 
3041 			if (ldap_get_option(ld->link, option, &ctrls) || ctrls == NULL) {
3042 				if (ctrls) {
3043 					ldap_memfree(ctrls);
3044 				}
3045 				RETURN_FALSE;
3046 			}
3047 			_php_ldap_controls_to_array(ld->link, ctrls, retval, 1);
3048 		} break;
3049 /* options not implemented
3050 	case LDAP_OPT_API_INFO:
3051 	case LDAP_OPT_API_FEATURE_INFO:
3052 */
3053 	default:
3054 		RETURN_FALSE;
3055 	}
3056 	RETURN_TRUE;
3057 }
3058 /* }}} */
3059 
3060 /* {{{ Set the value of various session-wide parameters */
PHP_FUNCTION(ldap_set_option)3061 PHP_FUNCTION(ldap_set_option)
3062 {
3063 	zval *link = NULL, *newval;
3064 	ldap_linkdata *ld;
3065 	LDAP *ldap;
3066 	zend_long option;
3067 
3068 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O!lz", &link, ldap_link_ce, &option, &newval) != SUCCESS) {
3069 		RETURN_THROWS();
3070 	}
3071 
3072 	if (!link) {
3073 		ldap = NULL;
3074 	} else {
3075 		ld = Z_LDAP_LINK_P(link);
3076 		VERIFY_LDAP_LINK_CONNECTED(ld);
3077 		ldap = ld->link;
3078 	}
3079 
3080 	switch (option) {
3081 	/* options with int value */
3082 	case LDAP_OPT_DEREF:
3083 	case LDAP_OPT_SIZELIMIT:
3084 	case LDAP_OPT_TIMELIMIT:
3085 	case LDAP_OPT_PROTOCOL_VERSION:
3086 	case LDAP_OPT_ERROR_NUMBER:
3087 #ifdef LDAP_OPT_DEBUG_LEVEL
3088 	case LDAP_OPT_DEBUG_LEVEL:
3089 #endif
3090 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
3091 	case LDAP_OPT_X_TLS_REQUIRE_CERT:
3092 #endif
3093 #ifdef LDAP_OPT_X_TLS_CRLCHECK
3094 	case LDAP_OPT_X_TLS_CRLCHECK:
3095 #endif
3096 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
3097 	case LDAP_OPT_X_TLS_PROTOCOL_MIN:
3098 #endif
3099 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
3100 	case LDAP_OPT_X_KEEPALIVE_IDLE:
3101 	case LDAP_OPT_X_KEEPALIVE_PROBES:
3102 	case LDAP_OPT_X_KEEPALIVE_INTERVAL:
3103 #endif
3104 		{
3105 			int val;
3106 
3107 			convert_to_long(newval);
3108 			if (ZEND_LONG_EXCEEDS_INT(Z_LVAL_P(newval))) {
3109 				zend_argument_value_error(3, "is too large");
3110 				RETURN_THROWS();
3111 			}
3112 			val = (int)Z_LVAL_P(newval);
3113 			if (ldap_set_option(ldap, option, &val)) {
3114 				RETURN_FALSE;
3115 			}
3116 		} break;
3117 #ifdef LDAP_OPT_NETWORK_TIMEOUT
3118 	case LDAP_OPT_NETWORK_TIMEOUT:
3119 		{
3120 			struct timeval timeout;
3121 
3122 			convert_to_long(newval);
3123 			timeout.tv_sec = Z_LVAL_P(newval);
3124 			timeout.tv_usec = 0;
3125 			if (ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
3126 				RETURN_FALSE;
3127 			}
3128 		} break;
3129 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
3130 	case LDAP_X_OPT_CONNECT_TIMEOUT:
3131 		{
3132 			int timeout;
3133 
3134 			convert_to_long(newval);
3135 			timeout = 1000 * Z_LVAL_P(newval); /* Convert to milliseconds */
3136 			if (ldap_set_option(ldap, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
3137 				RETURN_FALSE;
3138 			}
3139 		} break;
3140 #endif
3141 #ifdef LDAP_OPT_TIMEOUT
3142 	case LDAP_OPT_TIMEOUT:
3143 		{
3144 			struct timeval timeout;
3145 
3146 			convert_to_long(newval);
3147 			timeout.tv_sec = Z_LVAL_P(newval);
3148 			timeout.tv_usec = 0;
3149 			if (ldap_set_option(ldap, LDAP_OPT_TIMEOUT, (void *) &timeout)) {
3150 				RETURN_FALSE;
3151 			}
3152 		} break;
3153 #endif
3154 		/* options with string value */
3155 	case LDAP_OPT_ERROR_STRING:
3156 #ifdef LDAP_OPT_HOST_NAME
3157 	case LDAP_OPT_HOST_NAME:
3158 #endif
3159 #ifdef HAVE_LDAP_SASL
3160 	case LDAP_OPT_X_SASL_MECH:
3161 	case LDAP_OPT_X_SASL_REALM:
3162 	case LDAP_OPT_X_SASL_AUTHCID:
3163 	case LDAP_OPT_X_SASL_AUTHZID:
3164 #endif
3165 #if (LDAP_API_VERSION > 2000)
3166 	case LDAP_OPT_X_TLS_CACERTDIR:
3167 	case LDAP_OPT_X_TLS_CACERTFILE:
3168 	case LDAP_OPT_X_TLS_CERTFILE:
3169 	case LDAP_OPT_X_TLS_CIPHER_SUITE:
3170 	case LDAP_OPT_X_TLS_KEYFILE:
3171 	case LDAP_OPT_X_TLS_RANDOM_FILE:
3172 #endif
3173 #ifdef LDAP_OPT_X_TLS_CRLFILE
3174 	case LDAP_OPT_X_TLS_CRLFILE:
3175 #endif
3176 #ifdef LDAP_OPT_X_TLS_DHFILE
3177 	case LDAP_OPT_X_TLS_DHFILE:
3178 #endif
3179 #ifdef LDAP_OPT_MATCHED_DN
3180 	case LDAP_OPT_MATCHED_DN:
3181 #endif
3182 		{
3183 			zend_string *val;
3184 			val = zval_get_string(newval);
3185 			if (EG(exception)) {
3186 				RETURN_THROWS();
3187 			}
3188 			if (ldap_set_option(ldap, option, ZSTR_VAL(val))) {
3189 				zend_string_release(val);
3190 				RETURN_FALSE;
3191 			}
3192 			zend_string_release(val);
3193 		} break;
3194 		/* options with boolean value */
3195 	case LDAP_OPT_REFERRALS:
3196 #ifdef LDAP_OPT_RESTART
3197 	case LDAP_OPT_RESTART:
3198 #endif
3199 #ifdef LDAP_OPT_X_SASL_NOCANON
3200 	case LDAP_OPT_X_SASL_NOCANON:
3201 #endif
3202 		{
3203 			void *val;
3204 			val = zend_is_true(newval) ? LDAP_OPT_ON : LDAP_OPT_OFF;
3205 			if (ldap_set_option(ldap, option, val)) {
3206 				RETURN_FALSE;
3207 			}
3208 		} break;
3209 		/* options with control list value */
3210 	case LDAP_OPT_SERVER_CONTROLS:
3211 	case LDAP_OPT_CLIENT_CONTROLS:
3212 		{
3213 			LDAPControl **ctrls;
3214 			int rc;
3215 
3216 			if (Z_TYPE_P(newval) != IS_ARRAY) {
3217 				zend_argument_type_error(3, "must be of type array for the LDAP_OPT_CLIENT_CONTROLS option, %s given", zend_zval_type_name(newval));
3218 				RETURN_THROWS();
3219 			}
3220 
3221 			ctrls = _php_ldap_controls_from_array(ldap, newval, 3);
3222 
3223 			if (ctrls == NULL) {
3224 				RETURN_FALSE;
3225 			} else {
3226 				rc = ldap_set_option(ldap, option, ctrls);
3227 				_php_ldap_controls_free(&ctrls);
3228 				if (rc != LDAP_SUCCESS) {
3229 					RETURN_FALSE;
3230 				}
3231 			}
3232 		} break;
3233 	default:
3234 		RETURN_FALSE;
3235 	}
3236 	RETURN_TRUE;
3237 }
3238 /* }}} */
3239 
3240 #ifdef HAVE_LDAP_PARSE_RESULT
3241 /* {{{ Extract information from result */
PHP_FUNCTION(ldap_parse_result)3242 PHP_FUNCTION(ldap_parse_result)
3243 {
3244 	zval *link, *result, *errcode, *matcheddn, *errmsg, *referrals, *serverctrls;
3245 	ldap_linkdata *ld;
3246 	ldap_resultdata *ldap_result;
3247 	LDAPControl **lserverctrls = NULL;
3248 	char **lreferrals, **refp;
3249 	char *lmatcheddn, *lerrmsg;
3250 	int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
3251 
3252 	if (zend_parse_parameters(myargcount, "OOz|zzzz", &link, ldap_link_ce, &result, ldap_result_ce, &errcode, &matcheddn, &errmsg, &referrals, &serverctrls) != SUCCESS) {
3253 		RETURN_THROWS();
3254 	}
3255 
3256 	ld = Z_LDAP_LINK_P(link);
3257 	VERIFY_LDAP_LINK_CONNECTED(ld);
3258 
3259 	ldap_result = Z_LDAP_RESULT_P(result);
3260 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3261 
3262 	rc = ldap_parse_result(ld->link, ldap_result->result, &lerrcode,
3263 				myargcount > 3 ? &lmatcheddn : NULL,
3264 				myargcount > 4 ? &lerrmsg : NULL,
3265 				myargcount > 5 ? &lreferrals : NULL,
3266 				myargcount > 6 ? &lserverctrls : NULL,
3267 				0);
3268 	if (rc != LDAP_SUCCESS) {
3269 		php_error_docref(NULL, E_WARNING, "Unable to parse result: %s", ldap_err2string(rc));
3270 		RETURN_FALSE;
3271 	}
3272 
3273 	ZEND_TRY_ASSIGN_REF_LONG(errcode, lerrcode);
3274 
3275 	/* Reverse -> fall through */
3276 	switch (myargcount) {
3277 		case 7:
3278 			_php_ldap_controls_to_array(ld->link, lserverctrls, serverctrls, 0);
3279 			ZEND_FALLTHROUGH;
3280 		case 6:
3281 			referrals = zend_try_array_init(referrals);
3282 			if (!referrals) {
3283 				RETURN_THROWS();
3284 			}
3285 			if (lreferrals != NULL) {
3286 				refp = lreferrals;
3287 				while (*refp) {
3288 					add_next_index_string(referrals, *refp);
3289 					refp++;
3290 				}
3291 				ldap_memvfree((void**)lreferrals);
3292 			}
3293 			ZEND_FALLTHROUGH;
3294 		case 5:
3295 			if (lerrmsg == NULL) {
3296 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(errmsg);
3297 			} else {
3298 				ZEND_TRY_ASSIGN_REF_STRING(errmsg, lerrmsg);
3299 				ldap_memfree(lerrmsg);
3300 			}
3301 			ZEND_FALLTHROUGH;
3302 		case 4:
3303 			if (lmatcheddn == NULL) {
3304 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(matcheddn);
3305 			} else {
3306 				ZEND_TRY_ASSIGN_REF_STRING(matcheddn, lmatcheddn);
3307 				ldap_memfree(lmatcheddn);
3308 			}
3309 	}
3310 	RETURN_TRUE;
3311 }
3312 /* }}} */
3313 #endif
3314 
3315 /* {{{ Extended operation response parsing, Pierangelo Masarati */
3316 #ifdef HAVE_LDAP_PARSE_EXTENDED_RESULT
3317 /* {{{ Extract information from extended operation result */
PHP_FUNCTION(ldap_parse_exop)3318 PHP_FUNCTION(ldap_parse_exop)
3319 {
3320 	zval *link, *result, *retdata, *retoid;
3321 	ldap_linkdata *ld;
3322 	ldap_resultdata *ldap_result;
3323 	char *lretoid;
3324 	struct berval *lretdata;
3325 	int rc, myargcount = ZEND_NUM_ARGS();
3326 
3327 	if (zend_parse_parameters(myargcount, "OO|zz", &link, ldap_link_ce, &result, ldap_result_ce, &retdata, &retoid) != SUCCESS) {
3328 		RETURN_THROWS();
3329 	}
3330 
3331 	ld = Z_LDAP_LINK_P(link);
3332 	VERIFY_LDAP_LINK_CONNECTED(ld);
3333 
3334 	ldap_result = Z_LDAP_RESULT_P(result);
3335 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3336 
3337 	rc = ldap_parse_extended_result(ld->link, ldap_result->result,
3338 				myargcount > 3 ? &lretoid: NULL,
3339 				myargcount > 2 ? &lretdata: NULL,
3340 				0);
3341 	if (rc != LDAP_SUCCESS) {
3342 		php_error_docref(NULL, E_WARNING, "Unable to parse extended operation result: %s", ldap_err2string(rc));
3343 		RETURN_FALSE;
3344 	}
3345 
3346 	/* Reverse -> fall through */
3347 	switch (myargcount) {
3348 		case 4:
3349 			if (lretoid == NULL) {
3350 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retoid);
3351 			} else {
3352 				ZEND_TRY_ASSIGN_REF_STRING(retoid, lretoid);
3353 				ldap_memfree(lretoid);
3354 			}
3355 			ZEND_FALLTHROUGH;
3356 		case 3:
3357 			/* use arg #3 as the data returned by the server */
3358 			if (lretdata == NULL) {
3359 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retdata);
3360 			} else {
3361 				ZEND_TRY_ASSIGN_REF_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len);
3362 				ldap_memfree(lretdata->bv_val);
3363 				ldap_memfree(lretdata);
3364 			}
3365 	}
3366 	RETURN_TRUE;
3367 }
3368 /* }}} */
3369 #endif
3370 /* }}} */
3371 
3372 /* {{{ Count the number of references in a search result */
PHP_FUNCTION(ldap_count_references)3373 PHP_FUNCTION(ldap_count_references)
3374 {
3375 	zval *link, *result;
3376 	ldap_linkdata *ld;
3377 	ldap_resultdata *ldap_result;
3378 
3379 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
3380 		RETURN_THROWS();
3381 	}
3382 
3383 	ld = Z_LDAP_LINK_P(link);
3384 	VERIFY_LDAP_LINK_CONNECTED(ld);
3385 
3386 	ldap_result = Z_LDAP_RESULT_P(result);
3387 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3388 
3389 	RETURN_LONG(ldap_count_references(ld->link, ldap_result->result));
3390 }
3391 /* }}} */
3392 
3393 /* {{{ Return first reference */
PHP_FUNCTION(ldap_first_reference)3394 PHP_FUNCTION(ldap_first_reference)
3395 {
3396 	zval *link, *result;
3397 	ldap_linkdata *ld;
3398 	ldap_result_entry *resultentry;
3399 	ldap_resultdata *ldap_result;
3400 	LDAPMessage *entry;
3401 
3402 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
3403 		RETURN_THROWS();
3404 	}
3405 
3406 	ld = Z_LDAP_LINK_P(link);
3407 	VERIFY_LDAP_LINK_CONNECTED(ld);
3408 
3409 	ldap_result = Z_LDAP_RESULT_P(result);
3410 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3411 
3412 	if ((entry = ldap_first_reference(ld->link, ldap_result->result)) == NULL) {
3413 		RETVAL_FALSE;
3414 	} else {
3415 		object_init_ex(return_value, ldap_result_entry_ce);
3416 		resultentry = Z_LDAP_RESULT_ENTRY_P(return_value);
3417 		ZVAL_COPY(&resultentry->res, result);
3418 		resultentry->data = entry;
3419 		resultentry->ber = NULL;
3420 	}
3421 }
3422 /* }}} */
3423 
3424 /* {{{ Get next reference */
PHP_FUNCTION(ldap_next_reference)3425 PHP_FUNCTION(ldap_next_reference)
3426 {
3427 	zval *link, *result_entry;
3428 	ldap_linkdata *ld;
3429 	ldap_result_entry *resultentry, *resultentry_next;
3430 	LDAPMessage *entry_next;
3431 
3432 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
3433 		RETURN_THROWS();
3434 	}
3435 
3436 	ld = Z_LDAP_LINK_P(link);
3437 	VERIFY_LDAP_LINK_CONNECTED(ld);
3438 
3439 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
3440 
3441 	if ((entry_next = ldap_next_reference(ld->link, resultentry->data)) == NULL) {
3442 		RETVAL_FALSE;
3443 	} else {
3444 		object_init_ex(return_value, ldap_result_entry_ce);
3445 		resultentry_next = Z_LDAP_RESULT_ENTRY_P(return_value);
3446 		ZVAL_COPY(&resultentry_next->res, &resultentry->res);
3447 		resultentry_next->data = entry_next;
3448 		resultentry_next->ber = NULL;
3449 	}
3450 }
3451 /* }}} */
3452 
3453 #ifdef HAVE_LDAP_PARSE_REFERENCE
3454 /* {{{ Extract information from reference entry */
PHP_FUNCTION(ldap_parse_reference)3455 PHP_FUNCTION(ldap_parse_reference)
3456 {
3457 	zval *link, *result_entry, *referrals;
3458 	ldap_linkdata *ld;
3459 	ldap_result_entry *resultentry;
3460 	char **lreferrals, **refp;
3461 
3462 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OOz", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce, &referrals) != SUCCESS) {
3463 		RETURN_THROWS();
3464 	}
3465 
3466 	ld = Z_LDAP_LINK_P(link);
3467 	VERIFY_LDAP_LINK_CONNECTED(ld);
3468 
3469 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
3470 
3471 	if (ldap_parse_reference(ld->link, resultentry->data, &lreferrals, NULL /* &serverctrls */, 0) != LDAP_SUCCESS) {
3472 		RETURN_FALSE;
3473 	}
3474 
3475 	referrals = zend_try_array_init(referrals);
3476 	if (!referrals) {
3477 		RETURN_THROWS();
3478 	}
3479 
3480 	if (lreferrals != NULL) {
3481 		refp = lreferrals;
3482 		while (*refp) {
3483 			add_next_index_string(referrals, *refp);
3484 			refp++;
3485 		}
3486 		ldap_memvfree((void**)lreferrals);
3487 	}
3488 	RETURN_TRUE;
3489 }
3490 /* }}} */
3491 #endif
3492 
3493 /* {{{ php_ldap_do_rename */
php_ldap_do_rename(INTERNAL_FUNCTION_PARAMETERS,int ext)3494 static void php_ldap_do_rename(INTERNAL_FUNCTION_PARAMETERS, int ext)
3495 {
3496 	zval *serverctrls = NULL;
3497 	zval *link;
3498 	ldap_linkdata *ld;
3499 	LDAPControl **lserverctrls = NULL;
3500 	ldap_resultdata *result;
3501 	LDAPMessage *ldap_res;
3502 	int rc, msgid;
3503 	char *dn, *newrdn, *newparent;
3504 	size_t dn_len, newrdn_len, newparent_len;
3505 	bool deleteoldrdn;
3506 
3507 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osssb|a!", &link, ldap_link_ce, &dn, &dn_len, &newrdn, &newrdn_len, &newparent, &newparent_len, &deleteoldrdn, &serverctrls) != SUCCESS) {
3508 		RETURN_THROWS();
3509 	}
3510 
3511 	ld = Z_LDAP_LINK_P(link);
3512 	VERIFY_LDAP_LINK_CONNECTED(ld);
3513 
3514 	if (newparent_len == 0) {
3515 		newparent = NULL;
3516 	}
3517 
3518 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP)
3519 	if (serverctrls) {
3520 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 6);
3521 		if (lserverctrls == NULL) {
3522 			RETVAL_FALSE;
3523 			goto cleanup;
3524 		}
3525 	}
3526 
3527 	if (ext) {
3528 		rc = ldap_rename(ld->link, dn, newrdn, newparent, deleteoldrdn, lserverctrls, NULL, &msgid);
3529 	} else {
3530 		rc = ldap_rename_s(ld->link, dn, newrdn, newparent, deleteoldrdn, lserverctrls, NULL);
3531 	}
3532 #else
3533 	if (newparent_len != 0) {
3534 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, newparent must be the empty string, can only modify RDN");
3535 		RETURN_FALSE;
3536 	}
3537 	if (serverctrls) {
3538 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, controls are not supported");
3539 		RETURN_FALSE;
3540 	}
3541 	if (ext) {
3542 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, ldap_rename_ext is not supported");
3543 		RETURN_FALSE;
3544 	}
3545 /* could support old APIs but need check for ldap_modrdn2()/ldap_modrdn() */
3546 	rc = ldap_modrdn2_s(ld->link, dn, newrdn, deleteoldrdn);
3547 #endif
3548 
3549 	if (rc != LDAP_SUCCESS) {
3550 		RETVAL_FALSE;
3551 	} else if (ext) {
3552 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3553 		if (rc == -1) {
3554 			php_error_docref(NULL, E_WARNING, "Rename operation failed");
3555 			RETVAL_FALSE;
3556 			goto cleanup;
3557 		}
3558 
3559 		/* return a PHP control object */
3560 		object_init_ex(return_value, ldap_result_ce);
3561 		result = Z_LDAP_RESULT_P(return_value);
3562 		result->result = ldap_res;
3563 	} else {
3564 		RETVAL_TRUE;
3565 	}
3566 
3567 cleanup:
3568 	if (lserverctrls) {
3569 		_php_ldap_controls_free(&lserverctrls);
3570 	}
3571 
3572 	return;
3573 }
3574 /* }}} */
3575 
3576 /* {{{ Modify the name of an entry */
PHP_FUNCTION(ldap_rename)3577 PHP_FUNCTION(ldap_rename)
3578 {
3579 	php_ldap_do_rename(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3580 }
3581 /* }}} */
3582 
3583 /* {{{ Modify the name of an entry */
PHP_FUNCTION(ldap_rename_ext)3584 PHP_FUNCTION(ldap_rename_ext)
3585 {
3586 	php_ldap_do_rename(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3587 }
3588 /* }}} */
3589 
3590 #ifdef HAVE_LDAP_START_TLS_S
3591 /* {{{ Start TLS */
PHP_FUNCTION(ldap_start_tls)3592 PHP_FUNCTION(ldap_start_tls)
3593 {
3594 	zval *link;
3595 	ldap_linkdata *ld;
3596 	int rc, protocol = LDAP_VERSION3;
3597 
3598 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
3599 		RETURN_THROWS();
3600 	}
3601 
3602 	ld = Z_LDAP_LINK_P(link);
3603 	VERIFY_LDAP_LINK_CONNECTED(ld);
3604 
3605 	if (((rc = ldap_set_option(ld->link, LDAP_OPT_PROTOCOL_VERSION, &protocol)) != LDAP_SUCCESS) ||
3606 		((rc = ldap_start_tls_s(ld->link, NULL, NULL)) != LDAP_SUCCESS)
3607 	) {
3608 		php_error_docref(NULL, E_WARNING,"Unable to start TLS: %s", ldap_err2string(rc));
3609 		RETURN_FALSE;
3610 	} else {
3611 		RETURN_TRUE;
3612 	}
3613 }
3614 /* }}} */
3615 #endif
3616 #endif /* (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) */
3617 
3618 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3619 /* {{{ _ldap_rebind_proc() */
_ldap_rebind_proc(LDAP * ldap,const char * url,ber_tag_t req,ber_int_t msgid,void * params)3620 int _ldap_rebind_proc(LDAP *ldap, const char *url, ber_tag_t req, ber_int_t msgid, void *params)
3621 {
3622 	ldap_linkdata *ld = NULL;
3623 	int retval;
3624 	zval cb_args[2];
3625 	zval cb_retval;
3626 	zval *cb_link = (zval *) params;
3627 
3628 	ld = Z_LDAP_LINK_P(cb_link);
3629 	if (!ld->link) {
3630 		zend_throw_error(NULL, "LDAP connection has already been closed");
3631 		return LDAP_OTHER;
3632 	}
3633 
3634 	/* link exists and callback set? */
3635 	if (Z_ISUNDEF(ld->rebindproc)) {
3636 		php_error_docref(NULL, E_WARNING, "No callback set");
3637 		return LDAP_OTHER;
3638 	}
3639 
3640 	/* callback */
3641 	ZVAL_COPY_VALUE(&cb_args[0], cb_link);
3642 	ZVAL_STRING(&cb_args[1], url);
3643 	if (call_user_function(EG(function_table), NULL, &ld->rebindproc, &cb_retval, 2, cb_args) == SUCCESS && !Z_ISUNDEF(cb_retval)) {
3644 		retval = zval_get_long(&cb_retval);
3645 		zval_ptr_dtor(&cb_retval);
3646 	} else {
3647 		php_error_docref(NULL, E_WARNING, "rebind_proc PHP callback failed");
3648 		retval = LDAP_OTHER;
3649 	}
3650 	zval_ptr_dtor(&cb_args[1]);
3651 	return retval;
3652 }
3653 /* }}} */
3654 
3655 /* {{{ Set a callback function to do re-binds on referral chasing. */
PHP_FUNCTION(ldap_set_rebind_proc)3656 PHP_FUNCTION(ldap_set_rebind_proc)
3657 {
3658 	zval *link;
3659 	zend_fcall_info fci;
3660 	zend_fcall_info_cache fcc;
3661 	ldap_linkdata *ld;
3662 
3663 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Of!", &link, ldap_link_ce, &fci, &fcc) == FAILURE) {
3664 		RETURN_THROWS();
3665 	}
3666 
3667 	ld = Z_LDAP_LINK_P(link);
3668 	VERIFY_LDAP_LINK_CONNECTED(ld);
3669 
3670 	if (!ZEND_FCI_INITIALIZED(fci)) {
3671 		/* unregister rebind procedure */
3672 		if (!Z_ISUNDEF(ld->rebindproc)) {
3673 			zval_ptr_dtor(&ld->rebindproc);
3674 			ZVAL_UNDEF(&ld->rebindproc);
3675 			ldap_set_rebind_proc(ld->link, NULL, NULL);
3676 		}
3677 		RETURN_TRUE;
3678 	}
3679 
3680 	/* register rebind procedure */
3681 	if (Z_ISUNDEF(ld->rebindproc)) {
3682 		ldap_set_rebind_proc(ld->link, _ldap_rebind_proc, (void *) link);
3683 	} else {
3684 		zval_ptr_dtor(&ld->rebindproc);
3685 	}
3686 
3687 	ZVAL_COPY(&ld->rebindproc, &fci.function_name);
3688 	RETURN_TRUE;
3689 }
3690 /* }}} */
3691 #endif
3692 
php_ldap_do_escape(const bool * map,const char * value,size_t valuelen,zend_long flags)3693 static zend_string* php_ldap_do_escape(const bool *map, const char *value, size_t valuelen, zend_long flags)
3694 {
3695 	char hex[] = "0123456789abcdef";
3696 	size_t i, p = 0;
3697 	size_t len = 0;
3698 	zend_string *ret;
3699 
3700 	for (i = 0; i < valuelen; i++) {
3701 		len += (map[(unsigned char) value[i]]) ? 3 : 1;
3702 	}
3703 	/* Per RFC 4514, a leading and trailing space must be escaped */
3704 	if ((flags & PHP_LDAP_ESCAPE_DN) && (value[0] == ' ')) {
3705 		len += 2;
3706 	}
3707 	if ((flags & PHP_LDAP_ESCAPE_DN) && ((valuelen > 1) && (value[valuelen - 1] == ' '))) {
3708 		len += 2;
3709 	}
3710 
3711 	ret =  zend_string_alloc(len, 0);
3712 
3713 	for (i = 0; i < valuelen; i++) {
3714 		unsigned char v = (unsigned char) value[i];
3715 
3716 		if (map[v] || ((flags & PHP_LDAP_ESCAPE_DN) && ((i == 0) || (i + 1 == valuelen)) && (v == ' '))) {
3717 			ZSTR_VAL(ret)[p++] = '\\';
3718 			ZSTR_VAL(ret)[p++] = hex[v >> 4];
3719 			ZSTR_VAL(ret)[p++] = hex[v & 0x0f];
3720 		} else {
3721 			ZSTR_VAL(ret)[p++] = v;
3722 		}
3723 	}
3724 
3725 	ZSTR_VAL(ret)[p] = '\0';
3726 	ZSTR_LEN(ret) = p;
3727 	return ret;
3728 }
3729 
php_ldap_escape_map_set_chars(bool * map,const char * chars,const size_t charslen,char escape)3730 static void php_ldap_escape_map_set_chars(bool *map, const char *chars, const size_t charslen, char escape)
3731 {
3732 	size_t i = 0;
3733 	while (i < charslen) {
3734 		map[(unsigned char) chars[i++]] = escape;
3735 	}
3736 }
3737 
PHP_FUNCTION(ldap_escape)3738 PHP_FUNCTION(ldap_escape)
3739 {
3740 	char *value, *ignores;
3741 	size_t valuelen = 0, ignoreslen = 0;
3742 	int i;
3743 	zend_long flags = 0;
3744 	bool map[256] = {0}, havecharlist = 0;
3745 
3746 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sl", &value, &valuelen, &ignores, &ignoreslen, &flags) != SUCCESS) {
3747 		RETURN_THROWS();
3748 	}
3749 
3750 	if (!valuelen) {
3751 		RETURN_EMPTY_STRING();
3752 	}
3753 
3754 	if (flags & PHP_LDAP_ESCAPE_FILTER) {
3755 		havecharlist = 1;
3756 		php_ldap_escape_map_set_chars(map, "\\*()\0", sizeof("\\*()\0") - 1, 1);
3757 	}
3758 
3759 	if (flags & PHP_LDAP_ESCAPE_DN) {
3760 		havecharlist = 1;
3761 		php_ldap_escape_map_set_chars(map, "\\,=+<>;\"#\r", sizeof("\\,=+<>;\"#\r") - 1, 1);
3762 	}
3763 
3764 	if (!havecharlist) {
3765 		for (i = 0; i < 256; i++) {
3766 			map[i] = 1;
3767 		}
3768 	}
3769 
3770 	if (ignoreslen) {
3771 		php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0);
3772 	}
3773 
3774 	RETURN_NEW_STR(php_ldap_do_escape(map, value, valuelen, flags));
3775 }
3776 
3777 #ifdef STR_TRANSLATION
3778 /* {{{ php_ldap_do_translate */
php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS,int way)3779 static void php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS, int way)
3780 {
3781 	char *value;
3782 	size_t value_len;
3783 	int result;
3784 
3785 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) != SUCCESS) {
3786 		RETURN_THROWS();
3787 	}
3788 
3789 	if (value_len == 0) {
3790 		RETURN_FALSE;
3791 	}
3792 
3793 	if (way == 1) {
3794 		result = ldap_8859_to_t61(&value, &value_len, 0);
3795 	} else {
3796 		result = ldap_t61_to_8859(&value, &value_len, 0);
3797 	}
3798 
3799 	if (result == LDAP_SUCCESS) {
3800 		RETVAL_STRINGL(value, value_len);
3801 		free(value);
3802 	} else {
3803 		php_error_docref(NULL, E_WARNING, "Conversion from ISO-8859-1 to t61 failed: %s", ldap_err2string(result));
3804 		RETVAL_FALSE;
3805 	}
3806 }
3807 /* }}} */
3808 
3809 /* {{{ Translate t61 characters to 8859 characters */
PHP_FUNCTION(ldap_t61_to_8859)3810 PHP_FUNCTION(ldap_t61_to_8859)
3811 {
3812 	php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3813 }
3814 /* }}} */
3815 
3816 /* {{{ Translate 8859 characters to t61 characters */
PHP_FUNCTION(ldap_8859_to_t61)3817 PHP_FUNCTION(ldap_8859_to_t61)
3818 {
3819 	php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3820 }
3821 /* }}} */
3822 #endif
3823 
3824 /* {{{ Extended operations, Pierangelo Masarati */
3825 #ifdef HAVE_LDAP_EXTENDED_OPERATION_S
3826 /* {{{ Extended operation */
PHP_FUNCTION(ldap_exop)3827 PHP_FUNCTION(ldap_exop)
3828 {
3829 	zval *serverctrls = NULL;
3830 	zval *link, *retdata = NULL, *retoid = NULL;
3831 	char *lretoid = NULL;
3832 	zend_string *reqoid, *reqdata = NULL;
3833 	struct berval lreqdata, *lretdata = NULL;
3834 	ldap_linkdata *ld;
3835 	ldap_resultdata *result;
3836 	LDAPMessage *ldap_res;
3837 	LDAPControl **lserverctrls = NULL;
3838 	int rc, msgid;
3839 
3840 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OS|S!a!zz", &link, ldap_link_ce, &reqoid, &reqdata, &serverctrls, &retdata, &retoid) != SUCCESS) {
3841 		RETURN_THROWS();
3842 	}
3843 
3844 	ld = Z_LDAP_LINK_P(link);
3845 	VERIFY_LDAP_LINK_CONNECTED(ld);
3846 
3847 	if (reqdata) {
3848 		lreqdata.bv_val = ZSTR_VAL(reqdata);
3849 		lreqdata.bv_len = ZSTR_LEN(reqdata);
3850 	} else {
3851 		lreqdata.bv_len = 0;
3852 	}
3853 
3854 	if (serverctrls) {
3855 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
3856 		if (lserverctrls == NULL) {
3857 			RETVAL_FALSE;
3858 			goto cleanup;
3859 		}
3860 	}
3861 
3862 	if (retdata) {
3863 		/* synchronous call */
3864 		rc = ldap_extended_operation_s(ld->link, ZSTR_VAL(reqoid),
3865 			lreqdata.bv_len > 0 ? &lreqdata: NULL,
3866 			lserverctrls,
3867 			NULL,
3868 			retoid ? &lretoid : NULL,
3869 			&lretdata );
3870 		if (rc != LDAP_SUCCESS ) {
3871 			php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", ZSTR_VAL(reqoid), ldap_err2string(rc), rc);
3872 			RETVAL_FALSE;
3873 			goto cleanup;
3874 		}
3875 
3876 		if (retoid) {
3877 			if (lretoid) {
3878 				ZEND_TRY_ASSIGN_REF_STRING(retoid, lretoid);
3879 				ldap_memfree(lretoid);
3880 			} else {
3881 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retoid);
3882 			}
3883 		}
3884 
3885 		if (lretdata) {
3886 			ZEND_TRY_ASSIGN_REF_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len);
3887 			ldap_memfree(lretdata->bv_val);
3888 			ldap_memfree(lretdata);
3889 		} else {
3890 			ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retdata);
3891 		}
3892 
3893 		RETVAL_TRUE;
3894 		goto cleanup;
3895 	}
3896 
3897 	/* asynchronous call */
3898 	rc = ldap_extended_operation(ld->link, ZSTR_VAL(reqoid),
3899 		lreqdata.bv_len > 0 ? &lreqdata: NULL,
3900 		lserverctrls,
3901 		NULL,
3902 		&msgid);
3903 	if (rc != LDAP_SUCCESS ) {
3904 		php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", ZSTR_VAL(reqoid), ldap_err2string(rc), rc);
3905 		RETVAL_FALSE;
3906 		goto cleanup;
3907 	}
3908 
3909 	rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3910 	if (rc == -1) {
3911 		php_error_docref(NULL, E_WARNING, "Extended operation %s failed", ZSTR_VAL(reqoid));
3912 		RETVAL_FALSE;
3913 		goto cleanup;
3914 	}
3915 
3916 	/* return a PHP control object */
3917 	object_init_ex(return_value, ldap_result_ce);
3918 	result = Z_LDAP_RESULT_P(return_value);
3919 	result->result = ldap_res;
3920 
3921 	cleanup:
3922 	if (lserverctrls) {
3923 		_php_ldap_controls_free(&lserverctrls);
3924 	}
3925 }
3926 /* }}} */
3927 #endif
3928 
3929 #ifdef HAVE_LDAP_PASSWD
3930 /* {{{ Passwd modify extended operation */
PHP_FUNCTION(ldap_exop_passwd)3931 PHP_FUNCTION(ldap_exop_passwd)
3932 {
3933 	zval *link, *serverctrls;
3934 	struct berval luser = { 0L, NULL };
3935 	struct berval loldpw = { 0L, NULL };
3936 	struct berval lnewpw = { 0L, NULL };
3937 	struct berval lgenpasswd = { 0L, NULL };
3938 	LDAPControl *ctrl, **lserverctrls = NULL, *requestctrls[2] = { NULL, NULL };
3939 	LDAPMessage* ldap_res = NULL;
3940 	ldap_linkdata *ld;
3941 	int rc, myargcount = ZEND_NUM_ARGS(), msgid, err;
3942 	char* errmsg = NULL;
3943 
3944 	if (zend_parse_parameters(myargcount, "O|sssz/", &link, ldap_link_ce, &luser.bv_val, &luser.bv_len, &loldpw.bv_val, &loldpw.bv_len, &lnewpw.bv_val, &lnewpw.bv_len, &serverctrls) == FAILURE) {
3945 		RETURN_THROWS();
3946 	}
3947 
3948 	ld = Z_LDAP_LINK_P(link);
3949 	VERIFY_LDAP_LINK_CONNECTED(ld);
3950 
3951 	switch (myargcount) {
3952 		case 5:
3953 			/* ldap_create_passwordpolicy_control() allocates ctrl */
3954 			if (ldap_create_passwordpolicy_control(ld->link, &ctrl) == LDAP_SUCCESS) {
3955 				requestctrls[0] = ctrl;
3956 			}
3957 	}
3958 
3959 	/* asynchronous call to get result and controls */
3960 	rc = ldap_passwd(ld->link, &luser,
3961 		loldpw.bv_len > 0 ? &loldpw : NULL,
3962 		lnewpw.bv_len > 0 ? &lnewpw : NULL,
3963 		requestctrls,
3964 		NULL, &msgid);
3965 
3966 	if (requestctrls[0] != NULL) {
3967 		ldap_control_free(requestctrls[0]);
3968 	}
3969 
3970 	if (rc != LDAP_SUCCESS ) {
3971 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3972 		RETVAL_FALSE;
3973 		goto cleanup;
3974 	}
3975 
3976 	rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3977 	if ((rc < 0) || !ldap_res) {
3978 		rc = _get_lderrno(ld->link);
3979 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3980 		RETVAL_FALSE;
3981 		goto cleanup;
3982 	}
3983 
3984 	rc = ldap_parse_passwd(ld->link, ldap_res, &lgenpasswd);
3985 	if( rc != LDAP_SUCCESS ) {
3986 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3987 		RETVAL_FALSE;
3988 		goto cleanup;
3989 	}
3990 
3991 	rc = ldap_parse_result(ld->link, ldap_res, &err, NULL, &errmsg, NULL, (myargcount > 4 ? &lserverctrls : NULL), 0);
3992 	if( rc != LDAP_SUCCESS ) {
3993 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3994 		RETVAL_FALSE;
3995 		goto cleanup;
3996 	}
3997 
3998 	if (myargcount > 4) {
3999 		_php_ldap_controls_to_array(ld->link, lserverctrls, serverctrls, 0);
4000 	}
4001 
4002 	/* return */
4003 	if (lnewpw.bv_len == 0) {
4004 		if (lgenpasswd.bv_len == 0) {
4005 			RETVAL_EMPTY_STRING();
4006 		} else {
4007 			RETVAL_STRINGL(lgenpasswd.bv_val, lgenpasswd.bv_len);
4008 		}
4009 	} else if (err == LDAP_SUCCESS) {
4010 		RETVAL_TRUE;
4011 	} else {
4012 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", (errmsg ? errmsg : ldap_err2string(err)), err);
4013 		RETVAL_FALSE;
4014 	}
4015 
4016 cleanup:
4017 	if (lgenpasswd.bv_val != NULL) {
4018 		ldap_memfree(lgenpasswd.bv_val);
4019 	}
4020 	if (ldap_res != NULL) {
4021 		ldap_msgfree(ldap_res);
4022 	}
4023 	if (errmsg != NULL) {
4024 		ldap_memfree(errmsg);
4025 	}
4026 }
4027 /* }}} */
4028 #endif
4029 
4030 #ifdef HAVE_LDAP_WHOAMI_S
4031 /* {{{ Whoami extended operation */
PHP_FUNCTION(ldap_exop_whoami)4032 PHP_FUNCTION(ldap_exop_whoami)
4033 {
4034 	zval *link;
4035 	struct berval *lauthzid;
4036 	ldap_linkdata *ld;
4037 	int rc;
4038 
4039 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) == FAILURE) {
4040 		RETURN_THROWS();
4041 	}
4042 
4043 	ld = Z_LDAP_LINK_P(link);
4044 	VERIFY_LDAP_LINK_CONNECTED(ld);
4045 
4046 	/* synchronous call */
4047 	rc = ldap_whoami_s(ld->link, &lauthzid, NULL, NULL);
4048 	if (rc != LDAP_SUCCESS ) {
4049 		php_error_docref(NULL, E_WARNING, "Whoami extended operation failed: %s (%d)", ldap_err2string(rc), rc);
4050 		RETURN_FALSE;
4051 	}
4052 
4053 	if (lauthzid == NULL) {
4054 		RETVAL_EMPTY_STRING();
4055 	} else {
4056 		RETVAL_STRINGL(lauthzid->bv_val, lauthzid->bv_len);
4057 		ldap_memfree(lauthzid->bv_val);
4058 		ldap_memfree(lauthzid);
4059 	}
4060 }
4061 /* }}} */
4062 #endif
4063 
4064 #ifdef HAVE_LDAP_REFRESH_S
4065 /* {{{ DDS refresh extended operation */
PHP_FUNCTION(ldap_exop_refresh)4066 PHP_FUNCTION(ldap_exop_refresh)
4067 {
4068 	zval *link;
4069 	zend_long ttl;
4070 	struct berval ldn;
4071 	ber_int_t lttl;
4072 	ber_int_t newttl;
4073 	ldap_linkdata *ld;
4074 	int rc;
4075 
4076 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osl", &link, ldap_link_ce, &ldn.bv_val, &ldn.bv_len, &ttl) != SUCCESS) {
4077 		RETURN_THROWS();
4078 	}
4079 
4080 	ld = Z_LDAP_LINK_P(link);
4081 	VERIFY_LDAP_LINK_CONNECTED(ld);
4082 
4083 	lttl = (ber_int_t) ttl;
4084 
4085 	rc = ldap_refresh_s(ld->link, &ldn, lttl, &newttl, NULL, NULL);
4086 	if (rc != LDAP_SUCCESS ) {
4087 		php_error_docref(NULL, E_WARNING, "Refresh extended operation failed: %s (%d)", ldap_err2string(rc), rc);
4088 		RETURN_FALSE;
4089 	}
4090 
4091 	RETURN_LONG(newttl);
4092 }
4093 /* }}} */
4094 #endif
4095 
4096 zend_module_entry ldap_module_entry = { /* {{{ */
4097 	STANDARD_MODULE_HEADER,
4098 	"ldap",
4099 	ext_functions,
4100 	PHP_MINIT(ldap),
4101 	PHP_MSHUTDOWN(ldap),
4102 	NULL,
4103 	NULL,
4104 	PHP_MINFO(ldap),
4105 	PHP_LDAP_VERSION,
4106 	PHP_MODULE_GLOBALS(ldap),
4107 	PHP_GINIT(ldap),
4108 	NULL,
4109 	NULL,
4110 	STANDARD_MODULE_PROPERTIES_EX
4111 };
4112 /* }}} */
4113