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