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