xref: /PHP-8.2/ext/ldap/ldap.c (revision 21260318)
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 			RETVAL_FALSE;
2154 			num_berval[i] = 0;
2155 			num_attribs = i + 1;
2156 			ldap_mods[i]->mod_bvalues = NULL;
2157 			goto cleanup;
2158 		}
2159 
2160 		value = zend_hash_get_current_data(Z_ARRVAL_P(entry));
2161 
2162 		ZVAL_DEREF(value);
2163 		if (Z_TYPE_P(value) != IS_ARRAY) {
2164 			num_values = 1;
2165 		} else {
2166 			SEPARATE_ARRAY(value);
2167 			num_values = zend_hash_num_elements(Z_ARRVAL_P(value));
2168 		}
2169 
2170 		num_berval[i] = num_values;
2171 		ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0);
2172 
2173 /* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */
2174 		if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) {
2175 			convert_to_string(value);
2176 			if (EG(exception)) {
2177 				RETVAL_FALSE;
2178 				num_berval[i] = 0;
2179 				num_attribs = i + 1;
2180 				goto cleanup;
2181 			}
2182 			ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval));
2183 			ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value);
2184 			ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value);
2185 		} else {
2186 			for (j = 0; j < num_values; j++) {
2187 				if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) {
2188 					zend_argument_value_error(3, "must contain arrays with consecutive integer indices starting from 0");
2189 					num_berval[i] = j;
2190 					num_attribs = i + 1;
2191 					RETVAL_FALSE;
2192 					goto cleanup;
2193 				}
2194 				convert_to_string(ivalue);
2195 				if (EG(exception)) {
2196 					num_berval[i] = j;
2197 					num_attribs = i + 1;
2198 					RETVAL_FALSE;
2199 					goto cleanup;
2200 				}
2201 				ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval));
2202 				ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue);
2203 				ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue);
2204 			}
2205 		}
2206 		ldap_mods[i]->mod_bvalues[num_values] = NULL;
2207 		zend_hash_move_forward(Z_ARRVAL_P(entry));
2208 	}
2209 	ldap_mods[num_attribs] = NULL;
2210 
2211 	if (serverctrls) {
2212 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
2213 		if (lserverctrls == NULL) {
2214 			RETVAL_FALSE;
2215 			goto cleanup;
2216 		}
2217 	}
2218 
2219 /* check flag to see if do_mod was called to perform full add , gerrit thomson */
2220 	if (is_full_add == 1) {
2221 		if (ext) {
2222 			i = ldap_add_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2223 		} else {
2224 			i = ldap_add_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2225 		}
2226 		if (i != LDAP_SUCCESS) {
2227 			php_error_docref(NULL, E_WARNING, "Add: %s", ldap_err2string(i));
2228 			RETVAL_FALSE;
2229 		} else if (ext) {
2230 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2231 			if (i == -1) {
2232 				php_error_docref(NULL, E_WARNING, "Add operation failed");
2233 				RETVAL_FALSE;
2234 				goto cleanup;
2235 			}
2236 
2237 			/* return a PHP control object */
2238 			object_init_ex(return_value, ldap_result_ce);
2239 			result = Z_LDAP_RESULT_P(return_value);
2240 			result->result = ldap_res;
2241 		} else RETVAL_TRUE;
2242 	} else {
2243 		if (ext) {
2244 			i = ldap_modify_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2245 		} else {
2246 			i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2247 		}
2248 		if (i != LDAP_SUCCESS) {
2249 			php_error_docref(NULL, E_WARNING, "Modify: %s", ldap_err2string(i));
2250 			RETVAL_FALSE;
2251 		} else if (ext) {
2252 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2253 			if (i == -1) {
2254 				php_error_docref(NULL, E_WARNING, "Modify operation failed");
2255 				RETVAL_FALSE;
2256 				goto cleanup;
2257 			}
2258 
2259 			/* return a PHP control object */
2260 			object_init_ex(return_value, ldap_result_ce);
2261 			result = Z_LDAP_RESULT_P(return_value);
2262 			result->result = ldap_res;
2263 		} else RETVAL_TRUE;
2264 	}
2265 
2266 cleanup:
2267 	for (i = 0; i < num_attribs; i++) {
2268 		efree(ldap_mods[i]->mod_type);
2269 		for (j = 0; j < num_berval[i]; j++) {
2270 			efree(ldap_mods[i]->mod_bvalues[j]);
2271 		}
2272 		efree(ldap_mods[i]->mod_bvalues);
2273 		efree(ldap_mods[i]);
2274 	}
2275 	efree(num_berval);
2276 	efree(ldap_mods);
2277 
2278 	if (lserverctrls) {
2279 		_php_ldap_controls_free(&lserverctrls);
2280 	}
2281 
2282 	return;
2283 }
2284 /* }}} */
2285 
2286 /* {{{ Add entries to LDAP directory */
PHP_FUNCTION(ldap_add)2287 PHP_FUNCTION(ldap_add)
2288 {
2289 	/* 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 */
2290 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 0);
2291 }
2292 /* }}} */
2293 
2294 /* {{{ Add entries to LDAP directory */
PHP_FUNCTION(ldap_add_ext)2295 PHP_FUNCTION(ldap_add_ext)
2296 {
2297 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 1);
2298 }
2299 /* }}} */
2300 
2301 /* three functions for attribute base modifications, gerrit Thomson */
2302 
2303 /* {{{ Replace attribute values with new ones */
PHP_FUNCTION(ldap_mod_replace)2304 PHP_FUNCTION(ldap_mod_replace)
2305 {
2306 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 0);
2307 }
2308 /* }}} */
2309 
2310 /* {{{ Replace attribute values with new ones */
PHP_FUNCTION(ldap_mod_replace_ext)2311 PHP_FUNCTION(ldap_mod_replace_ext)
2312 {
2313 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 1);
2314 }
2315 /* }}} */
2316 
2317 /* {{{ Add attribute values to current */
PHP_FUNCTION(ldap_mod_add)2318 PHP_FUNCTION(ldap_mod_add)
2319 {
2320 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 0);
2321 }
2322 /* }}} */
2323 
2324 /* {{{ Add attribute values to current */
PHP_FUNCTION(ldap_mod_add_ext)2325 PHP_FUNCTION(ldap_mod_add_ext)
2326 {
2327 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 1);
2328 }
2329 /* }}} */
2330 
2331 /* {{{ Delete attribute values */
PHP_FUNCTION(ldap_mod_del)2332 PHP_FUNCTION(ldap_mod_del)
2333 {
2334 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 0);
2335 }
2336 /* }}} */
2337 
2338 /* {{{ Delete attribute values */
PHP_FUNCTION(ldap_mod_del_ext)2339 PHP_FUNCTION(ldap_mod_del_ext)
2340 {
2341 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 1);
2342 }
2343 /* }}} */
2344 
2345 /* {{{ php_ldap_do_delete */
php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS,int ext)2346 static void php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS, int ext)
2347 {
2348 	zval *serverctrls = NULL;
2349 	zval *link;
2350 	ldap_linkdata *ld;
2351 	LDAPControl **lserverctrls = NULL;
2352 	ldap_resultdata *result;
2353 	LDAPMessage *ldap_res;
2354 	char *dn;
2355 	int rc, msgid;
2356 	size_t dn_len;
2357 
2358 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Os|a!", &link, ldap_link_ce, &dn, &dn_len, &serverctrls) != SUCCESS) {
2359 		RETURN_THROWS();
2360 	}
2361 
2362 	ld = Z_LDAP_LINK_P(link);
2363 	VERIFY_LDAP_LINK_CONNECTED(ld);
2364 
2365 	if (serverctrls) {
2366 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 3);
2367 		if (lserverctrls == NULL) {
2368 			RETVAL_FALSE;
2369 			goto cleanup;
2370 		}
2371 	}
2372 
2373 	if (ext) {
2374 		rc = ldap_delete_ext(ld->link, dn, lserverctrls, NULL, &msgid);
2375 	} else {
2376 		rc = ldap_delete_ext_s(ld->link, dn, lserverctrls, NULL);
2377 	}
2378 	if (rc != LDAP_SUCCESS) {
2379 		php_error_docref(NULL, E_WARNING, "Delete: %s", ldap_err2string(rc));
2380 		RETVAL_FALSE;
2381 		goto cleanup;
2382 	} else if (ext) {
2383 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2384 		if (rc == -1) {
2385 			php_error_docref(NULL, E_WARNING, "Delete operation failed");
2386 			RETVAL_FALSE;
2387 			goto cleanup;
2388 		}
2389 
2390 		/* return a PHP control object */
2391 		object_init_ex(return_value, ldap_result_ce);
2392 		result = Z_LDAP_RESULT_P(return_value);
2393 		result->result = ldap_res;
2394 	} else {
2395 		RETVAL_TRUE;
2396 	}
2397 
2398 cleanup:
2399 	if (lserverctrls) {
2400 		_php_ldap_controls_free(&lserverctrls);
2401 	}
2402 
2403 	return;
2404 }
2405 /* }}} */
2406 
2407 /* {{{ Delete an entry from a directory */
PHP_FUNCTION(ldap_delete)2408 PHP_FUNCTION(ldap_delete)
2409 {
2410 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2411 }
2412 /* }}} */
2413 
2414 /* {{{ Delete an entry from a directory */
PHP_FUNCTION(ldap_delete_ext)2415 PHP_FUNCTION(ldap_delete_ext)
2416 {
2417 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2418 }
2419 /* }}} */
2420 
2421 /* {{{ _ldap_str_equal_to_const */
_ldap_str_equal_to_const(const char * str,size_t str_len,const char * cstr)2422 static size_t _ldap_str_equal_to_const(const char *str, size_t str_len, const char *cstr)
2423 {
2424 	size_t i;
2425 
2426 	if (strlen(cstr) != str_len)
2427 		return 0;
2428 
2429 	for (i = 0; i < str_len; ++i) {
2430 		if (str[i] != cstr[i]) {
2431 			return 0;
2432 		}
2433 	}
2434 
2435 	return 1;
2436 }
2437 /* }}} */
2438 
2439 /* {{{ _ldap_strlen_max */
_ldap_strlen_max(const char * str,size_t max_len)2440 static size_t _ldap_strlen_max(const char *str, size_t max_len)
2441 {
2442 	size_t i;
2443 
2444 	for (i = 0; i < max_len; ++i) {
2445 		if (str[i] == '\0') {
2446 			return i;
2447 		}
2448 	}
2449 
2450 	return max_len;
2451 }
2452 /* }}} */
2453 
2454 /* {{{ _ldap_hash_fetch */
_ldap_hash_fetch(zval * hashTbl,const char * key,zval ** out)2455 static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)
2456 {
2457 	*out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key));
2458 }
2459 /* }}} */
2460 
2461 /* {{{ Perform multiple modifications as part of one operation */
PHP_FUNCTION(ldap_modify_batch)2462 PHP_FUNCTION(ldap_modify_batch)
2463 {
2464 	zval *serverctrls = NULL;
2465 	ldap_linkdata *ld;
2466 	zval *link, *mods, *mod, *modinfo;
2467 	zend_string *modval;
2468 	zval *attrib, *modtype, *vals;
2469 	zval *fetched;
2470 	char *dn;
2471 	size_t dn_len;
2472 	int i, j, k;
2473 	int num_mods, num_modprops, num_modvals;
2474 	LDAPMod **ldap_mods;
2475 	LDAPControl **lserverctrls = NULL;
2476 	uint32_t oper;
2477 
2478 	/*
2479 	$mods = array(
2480 		array(
2481 			"attrib" => "unicodePwd",
2482 			"modtype" => LDAP_MODIFY_BATCH_REMOVE,
2483 			"values" => array($oldpw)
2484 		),
2485 		array(
2486 			"attrib" => "unicodePwd",
2487 			"modtype" => LDAP_MODIFY_BATCH_ADD,
2488 			"values" => array($newpw)
2489 		),
2490 		array(
2491 			"attrib" => "userPrincipalName",
2492 			"modtype" => LDAP_MODIFY_BATCH_REPLACE,
2493 			"values" => array("janitor@corp.contoso.com")
2494 		),
2495 		array(
2496 			"attrib" => "userCert",
2497 			"modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL
2498 		)
2499 	);
2500 	*/
2501 
2502 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osa/|a!", &link, ldap_link_ce, &dn, &dn_len, &mods, &serverctrls) != SUCCESS) {
2503 		RETURN_THROWS();
2504 	}
2505 
2506 	ld = Z_LDAP_LINK_P(link);
2507 	VERIFY_LDAP_LINK_CONNECTED(ld);
2508 
2509 	/* perform validation */
2510 	{
2511 		zend_string *modkey;
2512 		zend_long modtype;
2513 
2514 		/* to store the wrongly-typed keys */
2515 		zend_ulong tmpUlong;
2516 
2517 		/* make sure the DN contains no NUL bytes */
2518 		if (_ldap_strlen_max(dn, dn_len) != dn_len) {
2519 			zend_argument_type_error(2, "must not contain null bytes");
2520 			RETURN_THROWS();
2521 		}
2522 
2523 		/* make sure the top level is a normal array */
2524 		zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods));
2525 		if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) {
2526 			zend_argument_type_error(3, "must be integer-indexed");
2527 			RETURN_THROWS();
2528 		}
2529 
2530 		num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods));
2531 
2532 		for (i = 0; i < num_mods; i++) {
2533 			/* is the numbering consecutive? */
2534 			if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) {
2535 				zend_argument_value_error(3, "must have consecutive integer indices starting from 0");
2536 				RETURN_THROWS();
2537 			}
2538 			mod = fetched;
2539 
2540 			/* is it an array? */
2541 			if (Z_TYPE_P(mod) != IS_ARRAY) {
2542 				zend_argument_value_error(3, "must only contain arrays");
2543 				RETURN_THROWS();
2544 			}
2545 
2546 			SEPARATE_ARRAY(mod);
2547 			/* for the modification hashtable... */
2548 			zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod));
2549 			num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod));
2550 			bool has_attrib_key = false;
2551 			bool has_modtype_key = false;
2552 
2553 			for (j = 0; j < num_modprops; j++) {
2554 
2555 				/* are the keys strings? */
2556 				if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong) != HASH_KEY_IS_STRING) {
2557 					zend_argument_type_error(3, "must only contain string-indexed arrays");
2558 					RETURN_THROWS();
2559 				}
2560 
2561 				/* is this a valid entry? */
2562 				if (
2563 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB) &&
2564 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE) &&
2565 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)
2566 				) {
2567 					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");
2568 					RETURN_THROWS();
2569 				}
2570 
2571 				fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod));
2572 				modinfo = fetched;
2573 
2574 				/* does the value type match the key? */
2575 				if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB)) {
2576 					has_attrib_key = true;
2577 					if (Z_TYPE_P(modinfo) != IS_STRING) {
2578 						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));
2579 						RETURN_THROWS();
2580 					}
2581 
2582 					if (Z_STRLEN_P(modinfo) != _ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) {
2583 						zend_type_error("%s(): Option \"" LDAP_MODIFY_BATCH_ATTRIB "\" cannot contain null-bytes", get_active_function_name());
2584 						RETURN_THROWS();
2585 					}
2586 				}
2587 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE)) {
2588 					has_modtype_key = true;
2589 					if (Z_TYPE_P(modinfo) != IS_LONG) {
2590 						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));
2591 						RETURN_THROWS();
2592 					}
2593 
2594 					/* is the value in range? */
2595 					modtype = Z_LVAL_P(modinfo);
2596 					if (
2597 						modtype != LDAP_MODIFY_BATCH_ADD &&
2598 						modtype != LDAP_MODIFY_BATCH_REMOVE &&
2599 						modtype != LDAP_MODIFY_BATCH_REPLACE &&
2600 						modtype != LDAP_MODIFY_BATCH_REMOVE_ALL
2601 					) {
2602 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_MODTYPE "\" must be one of the LDAP_MODIFY_BATCH_* constants", get_active_function_name());
2603 						RETURN_THROWS();
2604 					}
2605 
2606 					/* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */
2607 					if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2608 						if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2609 							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());
2610 							RETURN_THROWS();
2611 						}
2612 					}
2613 					else {
2614 						if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2615 							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());
2616 							RETURN_THROWS();
2617 						}
2618 					}
2619 				}
2620 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)) {
2621 					if (Z_TYPE_P(modinfo) != IS_ARRAY) {
2622 						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));
2623 						RETURN_THROWS();
2624 					}
2625 
2626 					SEPARATE_ARRAY(modinfo);
2627 					/* is the array not empty? */
2628 					zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo));
2629 					num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo));
2630 					if (num_modvals == 0) {
2631 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" cannot be empty", get_active_function_name());
2632 						RETURN_THROWS();
2633 					}
2634 
2635 					/* are its keys integers? */
2636 					if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) {
2637 						zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" must be integer-indexed", get_active_function_name());
2638 						RETURN_THROWS();
2639 					}
2640 
2641 					/* are the keys consecutive? */
2642 					for (k = 0; k < num_modvals; k++) {
2643 						if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) {
2644 							zend_value_error("%s(): Option \"" LDAP_MODIFY_BATCH_VALUES "\" must have consecutive integer indices starting from 0", get_active_function_name());
2645 							RETURN_THROWS();
2646 						}
2647 					}
2648 				}
2649 
2650 				zend_hash_move_forward(Z_ARRVAL_P(mod));
2651 			}
2652 
2653 			if (!has_attrib_key) {
2654 				zend_value_error("%s(): Required option \"" LDAP_MODIFY_BATCH_ATTRIB "\" is missing", get_active_function_name());
2655 				RETURN_THROWS();
2656 			}
2657 			if (!has_modtype_key) {
2658 				zend_value_error("%s(): Required option \"" LDAP_MODIFY_BATCH_MODTYPE "\" is missing", get_active_function_name());
2659 				RETURN_THROWS();
2660 			}
2661 		}
2662 	}
2663 	/* validation was successful */
2664 
2665 	/* allocate array of modifications */
2666 	ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0);
2667 
2668 	/* for each modification */
2669 	for (i = 0; i < num_mods; i++) {
2670 		/* allocate the modification struct */
2671 		ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0);
2672 
2673 		/* fetch the relevant data */
2674 		fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i);
2675 		mod = fetched;
2676 
2677 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib);
2678 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype);
2679 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals);
2680 
2681 		/* map the modification type */
2682 		switch (Z_LVAL_P(modtype)) {
2683 			case LDAP_MODIFY_BATCH_ADD:
2684 				oper = LDAP_MOD_ADD;
2685 				break;
2686 			case LDAP_MODIFY_BATCH_REMOVE:
2687 			case LDAP_MODIFY_BATCH_REMOVE_ALL:
2688 				oper = LDAP_MOD_DELETE;
2689 				break;
2690 			case LDAP_MODIFY_BATCH_REPLACE:
2691 				oper = LDAP_MOD_REPLACE;
2692 				break;
2693 			default:
2694 				zend_throw_error(NULL, "Unknown and uncaught modification type.");
2695 				RETVAL_FALSE;
2696 				efree(ldap_mods[i]);
2697 				num_mods = i;
2698 				goto cleanup;
2699 		}
2700 
2701 		/* fill in the basic info */
2702 		ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
2703 		ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib));
2704 
2705 		if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2706 			/* no values */
2707 			ldap_mods[i]->mod_bvalues = NULL;
2708 		}
2709 		else {
2710 			/* allocate space for the values as part of this modification */
2711 			num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals));
2712 			ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0);
2713 
2714 			/* for each value */
2715 			for (j = 0; j < num_modvals; j++) {
2716 				/* fetch it */
2717 				fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j);
2718 				modval = zval_get_string(fetched);
2719 				if (EG(exception)) {
2720 					RETVAL_FALSE;
2721 					ldap_mods[i]->mod_bvalues[j] = NULL;
2722 					num_mods = i + 1;
2723 					goto cleanup;
2724 				}
2725 
2726 				/* allocate the data struct */
2727 				ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0);
2728 
2729 				/* fill it */
2730 				ldap_mods[i]->mod_bvalues[j]->bv_len = ZSTR_LEN(modval);
2731 				ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(ZSTR_VAL(modval), ZSTR_LEN(modval));
2732 				zend_string_release(modval);
2733 			}
2734 
2735 			/* NULL-terminate values */
2736 			ldap_mods[i]->mod_bvalues[num_modvals] = NULL;
2737 		}
2738 	}
2739 
2740 	/* NULL-terminate modifications */
2741 	ldap_mods[num_mods] = NULL;
2742 
2743 	if (serverctrls) {
2744 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
2745 		if (lserverctrls == NULL) {
2746 			RETVAL_FALSE;
2747 			goto cleanup;
2748 		}
2749 	}
2750 
2751 	/* perform (finally) */
2752 	if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL)) != LDAP_SUCCESS) {
2753 		php_error_docref(NULL, E_WARNING, "Batch Modify: %s", ldap_err2string(i));
2754 		RETVAL_FALSE;
2755 	} else RETVAL_TRUE;
2756 
2757 	/* clean up */
2758 	cleanup: {
2759 		for (i = 0; i < num_mods; i++) {
2760 			/* attribute */
2761 			efree(ldap_mods[i]->mod_type);
2762 
2763 			if (ldap_mods[i]->mod_bvalues != NULL) {
2764 				/* each BER value */
2765 				for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) {
2766 					/* free the data bytes */
2767 					efree(ldap_mods[i]->mod_bvalues[j]->bv_val);
2768 
2769 					/* free the bvalue struct */
2770 					efree(ldap_mods[i]->mod_bvalues[j]);
2771 				}
2772 
2773 				/* the BER value array */
2774 				efree(ldap_mods[i]->mod_bvalues);
2775 			}
2776 
2777 			/* the modification */
2778 			efree(ldap_mods[i]);
2779 		}
2780 
2781 		/* the modifications array */
2782 		efree(ldap_mods);
2783 
2784 		if (lserverctrls) {
2785 			_php_ldap_controls_free(&lserverctrls);
2786 		}
2787 	}
2788 }
2789 /* }}} */
2790 
2791 /* {{{ Get the current ldap error number */
PHP_FUNCTION(ldap_errno)2792 PHP_FUNCTION(ldap_errno)
2793 {
2794 	zval *link;
2795 	ldap_linkdata *ld;
2796 
2797 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
2798 		RETURN_THROWS();
2799 	}
2800 
2801 	ld = Z_LDAP_LINK_P(link);
2802 	VERIFY_LDAP_LINK_CONNECTED(ld);
2803 
2804 	RETURN_LONG(_get_lderrno(ld->link));
2805 }
2806 /* }}} */
2807 
2808 /* {{{ Convert error number to error string */
PHP_FUNCTION(ldap_err2str)2809 PHP_FUNCTION(ldap_err2str)
2810 {
2811 	zend_long perrno;
2812 
2813 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perrno) != SUCCESS) {
2814 		RETURN_THROWS();
2815 	}
2816 
2817 	RETURN_STRING(ldap_err2string(perrno));
2818 }
2819 /* }}} */
2820 
2821 /* {{{ Get the current ldap error string */
PHP_FUNCTION(ldap_error)2822 PHP_FUNCTION(ldap_error)
2823 {
2824 	zval *link;
2825 	ldap_linkdata *ld;
2826 	int ld_errno;
2827 
2828 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
2829 		RETURN_THROWS();
2830 	}
2831 
2832 	ld = Z_LDAP_LINK_P(link);
2833 	VERIFY_LDAP_LINK_CONNECTED(ld);
2834 
2835 	ld_errno = _get_lderrno(ld->link);
2836 
2837 	RETURN_STRING(ldap_err2string(ld_errno));
2838 }
2839 /* }}} */
2840 
2841 /* {{{ Determine if an entry has a specific value for one of its attributes */
PHP_FUNCTION(ldap_compare)2842 PHP_FUNCTION(ldap_compare)
2843 {
2844 	zval *serverctrls = NULL;
2845 	zval *link;
2846 	char *dn, *attr, *value;
2847 	size_t dn_len, attr_len, value_len;
2848 	ldap_linkdata *ld;
2849 	LDAPControl **lserverctrls = NULL;
2850 	int ldap_errno;
2851 	struct berval lvalue;
2852 
2853 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osss|a!", &link, ldap_link_ce, &dn, &dn_len, &attr, &attr_len, &value, &value_len, &serverctrls) != SUCCESS) {
2854 		RETURN_THROWS();
2855 	}
2856 
2857 	ld = Z_LDAP_LINK_P(link);
2858 	VERIFY_LDAP_LINK_CONNECTED(ld);
2859 
2860 	if (serverctrls) {
2861 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 5);
2862 		if (lserverctrls == NULL) {
2863 			RETVAL_FALSE;
2864 			goto cleanup;
2865 		}
2866 	}
2867 
2868 	lvalue.bv_val = value;
2869 	lvalue.bv_len = value_len;
2870 
2871 	ldap_errno = ldap_compare_ext_s(ld->link, dn, attr, &lvalue, lserverctrls, NULL);
2872 
2873 	switch (ldap_errno) {
2874 		case LDAP_COMPARE_TRUE:
2875 			RETVAL_TRUE;
2876 			break;
2877 
2878 		case LDAP_COMPARE_FALSE:
2879 			RETVAL_FALSE;
2880 			break;
2881 
2882 		default:
2883 			php_error_docref(NULL, E_WARNING, "Compare: %s", ldap_err2string(ldap_errno));
2884 			RETVAL_LONG(-1);
2885 	}
2886 
2887 cleanup:
2888 	if (lserverctrls) {
2889 		_php_ldap_controls_free(&lserverctrls);
2890 	}
2891 
2892 	return;
2893 }
2894 /* }}} */
2895 
2896 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP)
2897 /* {{{ Get the current value of various session-wide parameters */
PHP_FUNCTION(ldap_get_option)2898 PHP_FUNCTION(ldap_get_option)
2899 {
2900 	zval *link, *retval;
2901 	ldap_linkdata *ld;
2902 	zend_long option;
2903 
2904 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Olz", &link, ldap_link_ce, &option, &retval) != SUCCESS) {
2905 		RETURN_THROWS();
2906 	}
2907 
2908 	ld = Z_LDAP_LINK_P(link);
2909 	VERIFY_LDAP_LINK_CONNECTED(ld);
2910 
2911 	switch (option) {
2912 	/* options with int value */
2913 	case LDAP_OPT_DEREF:
2914 	case LDAP_OPT_SIZELIMIT:
2915 	case LDAP_OPT_TIMELIMIT:
2916 	case LDAP_OPT_PROTOCOL_VERSION:
2917 	case LDAP_OPT_ERROR_NUMBER:
2918 	case LDAP_OPT_REFERRALS:
2919 #ifdef LDAP_OPT_RESTART
2920 	case LDAP_OPT_RESTART:
2921 #endif
2922 #ifdef LDAP_OPT_X_SASL_NOCANON
2923 	case LDAP_OPT_X_SASL_NOCANON:
2924 #endif
2925 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
2926 	case LDAP_OPT_X_TLS_REQUIRE_CERT:
2927 #endif
2928 #ifdef LDAP_OPT_X_TLS_CRLCHECK
2929 	case LDAP_OPT_X_TLS_CRLCHECK:
2930 #endif
2931 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
2932 	case LDAP_OPT_X_TLS_PROTOCOL_MIN:
2933 #endif
2934 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
2935 	case LDAP_OPT_X_KEEPALIVE_IDLE:
2936 	case LDAP_OPT_X_KEEPALIVE_PROBES:
2937 	case LDAP_OPT_X_KEEPALIVE_INTERVAL:
2938 #endif
2939 		{
2940 			int val;
2941 
2942 			if (ldap_get_option(ld->link, option, &val)) {
2943 				RETURN_FALSE;
2944 			}
2945 			ZEND_TRY_ASSIGN_REF_LONG(retval, val);
2946 		} break;
2947 #ifdef LDAP_OPT_NETWORK_TIMEOUT
2948 	case LDAP_OPT_NETWORK_TIMEOUT:
2949 		{
2950 			struct timeval *timeout = NULL;
2951 
2952 			if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
2953 				if (timeout) {
2954 					ldap_memfree(timeout);
2955 				}
2956 				RETURN_FALSE;
2957 			}
2958 			if (!timeout) {
2959 				RETURN_FALSE;
2960 			}
2961 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
2962 			ldap_memfree(timeout);
2963 		} break;
2964 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
2965 	case LDAP_X_OPT_CONNECT_TIMEOUT:
2966 		{
2967 			int timeout;
2968 
2969 			if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
2970 				RETURN_FALSE;
2971 			}
2972 			ZEND_TRY_ASSIGN_REF_LONG(retval, (timeout / 1000));
2973 		} break;
2974 #endif
2975 #ifdef LDAP_OPT_TIMEOUT
2976 	case LDAP_OPT_TIMEOUT:
2977 		{
2978 			struct timeval *timeout = NULL;
2979 
2980 			if (ldap_get_option(ld->link, LDAP_OPT_TIMEOUT, (void *) &timeout)) {
2981 				if (timeout) {
2982 					ldap_memfree(timeout);
2983 				}
2984 				RETURN_FALSE;
2985 			}
2986 			if (!timeout) {
2987 				RETURN_FALSE;
2988 			}
2989 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
2990 			ldap_memfree(timeout);
2991 		} break;
2992 #endif
2993 	/* options with string value */
2994 	case LDAP_OPT_ERROR_STRING:
2995 #ifdef LDAP_OPT_HOST_NAME
2996 	case LDAP_OPT_HOST_NAME:
2997 #endif
2998 #ifdef HAVE_LDAP_SASL
2999 	case LDAP_OPT_X_SASL_MECH:
3000 	case LDAP_OPT_X_SASL_REALM:
3001 	case LDAP_OPT_X_SASL_AUTHCID:
3002 	case LDAP_OPT_X_SASL_AUTHZID:
3003 #endif
3004 #ifdef LDAP_OPT_X_SASL_USERNAME
3005 	case LDAP_OPT_X_SASL_USERNAME:
3006 #endif
3007 #if (LDAP_API_VERSION > 2000)
3008 	case LDAP_OPT_X_TLS_CACERTDIR:
3009 	case LDAP_OPT_X_TLS_CACERTFILE:
3010 	case LDAP_OPT_X_TLS_CERTFILE:
3011 	case LDAP_OPT_X_TLS_CIPHER_SUITE:
3012 	case LDAP_OPT_X_TLS_KEYFILE:
3013 	case LDAP_OPT_X_TLS_RANDOM_FILE:
3014 #endif
3015 #ifdef LDAP_OPT_X_TLS_PACKAGE
3016 	case LDAP_OPT_X_TLS_PACKAGE:
3017 #endif
3018 #ifdef LDAP_OPT_X_TLS_CRLFILE
3019 	case LDAP_OPT_X_TLS_CRLFILE:
3020 #endif
3021 #ifdef LDAP_OPT_X_TLS_DHFILE
3022 	case LDAP_OPT_X_TLS_DHFILE:
3023 #endif
3024 #ifdef LDAP_OPT_MATCHED_DN
3025 	case LDAP_OPT_MATCHED_DN:
3026 #endif
3027 		{
3028 			char *val = NULL;
3029 
3030 			if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') {
3031 				if (val) {
3032 					ldap_memfree(val);
3033 				}
3034 				RETURN_FALSE;
3035 			}
3036 			ZEND_TRY_ASSIGN_REF_STRING(retval, val);
3037 			ldap_memfree(val);
3038 		} break;
3039 	case LDAP_OPT_SERVER_CONTROLS:
3040 	case LDAP_OPT_CLIENT_CONTROLS:
3041 		{
3042 			LDAPControl **ctrls = NULL;
3043 
3044 			if (ldap_get_option(ld->link, option, &ctrls) || ctrls == NULL) {
3045 				if (ctrls) {
3046 					ldap_memfree(ctrls);
3047 				}
3048 				RETURN_FALSE;
3049 			}
3050 			_php_ldap_controls_to_array(ld->link, ctrls, retval, 1);
3051 		} break;
3052 /* options not implemented
3053 	case LDAP_OPT_API_INFO:
3054 	case LDAP_OPT_API_FEATURE_INFO:
3055 */
3056 	default:
3057 		RETURN_FALSE;
3058 	}
3059 	RETURN_TRUE;
3060 }
3061 /* }}} */
3062 
3063 /* {{{ Set the value of various session-wide parameters */
PHP_FUNCTION(ldap_set_option)3064 PHP_FUNCTION(ldap_set_option)
3065 {
3066 	zval *link = NULL, *newval;
3067 	ldap_linkdata *ld;
3068 	LDAP *ldap;
3069 	zend_long option;
3070 
3071 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O!lz", &link, ldap_link_ce, &option, &newval) != SUCCESS) {
3072 		RETURN_THROWS();
3073 	}
3074 
3075 	if (!link) {
3076 		ldap = NULL;
3077 	} else {
3078 		ld = Z_LDAP_LINK_P(link);
3079 		VERIFY_LDAP_LINK_CONNECTED(ld);
3080 		ldap = ld->link;
3081 	}
3082 
3083 	switch (option) {
3084 	/* options with int value */
3085 	case LDAP_OPT_DEREF:
3086 	case LDAP_OPT_SIZELIMIT:
3087 	case LDAP_OPT_TIMELIMIT:
3088 	case LDAP_OPT_PROTOCOL_VERSION:
3089 	case LDAP_OPT_ERROR_NUMBER:
3090 #ifdef LDAP_OPT_DEBUG_LEVEL
3091 	case LDAP_OPT_DEBUG_LEVEL:
3092 #endif
3093 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
3094 	case LDAP_OPT_X_TLS_REQUIRE_CERT:
3095 #endif
3096 #ifdef LDAP_OPT_X_TLS_CRLCHECK
3097 	case LDAP_OPT_X_TLS_CRLCHECK:
3098 #endif
3099 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
3100 	case LDAP_OPT_X_TLS_PROTOCOL_MIN:
3101 #endif
3102 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
3103 	case LDAP_OPT_X_KEEPALIVE_IDLE:
3104 	case LDAP_OPT_X_KEEPALIVE_PROBES:
3105 	case LDAP_OPT_X_KEEPALIVE_INTERVAL:
3106 #endif
3107 		{
3108 			int val;
3109 
3110 			convert_to_long(newval);
3111 			if (ZEND_LONG_EXCEEDS_INT(Z_LVAL_P(newval))) {
3112 				zend_argument_value_error(3, "is too large");
3113 				RETURN_THROWS();
3114 			}
3115 			val = (int)Z_LVAL_P(newval);
3116 			if (ldap_set_option(ldap, option, &val)) {
3117 				RETURN_FALSE;
3118 			}
3119 		} break;
3120 #ifdef LDAP_OPT_NETWORK_TIMEOUT
3121 	case LDAP_OPT_NETWORK_TIMEOUT:
3122 		{
3123 			struct timeval timeout;
3124 
3125 			convert_to_long(newval);
3126 			timeout.tv_sec = Z_LVAL_P(newval);
3127 			timeout.tv_usec = 0;
3128 			if (ldap_set_option(ldap, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
3129 				RETURN_FALSE;
3130 			}
3131 		} break;
3132 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
3133 	case LDAP_X_OPT_CONNECT_TIMEOUT:
3134 		{
3135 			int timeout;
3136 
3137 			convert_to_long(newval);
3138 			timeout = 1000 * Z_LVAL_P(newval); /* Convert to milliseconds */
3139 			if (ldap_set_option(ldap, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
3140 				RETURN_FALSE;
3141 			}
3142 		} break;
3143 #endif
3144 #ifdef LDAP_OPT_TIMEOUT
3145 	case LDAP_OPT_TIMEOUT:
3146 		{
3147 			struct timeval timeout;
3148 
3149 			convert_to_long(newval);
3150 			timeout.tv_sec = Z_LVAL_P(newval);
3151 			timeout.tv_usec = 0;
3152 			if (ldap_set_option(ldap, LDAP_OPT_TIMEOUT, (void *) &timeout)) {
3153 				RETURN_FALSE;
3154 			}
3155 		} break;
3156 #endif
3157 		/* options with string value */
3158 	case LDAP_OPT_ERROR_STRING:
3159 #ifdef LDAP_OPT_HOST_NAME
3160 	case LDAP_OPT_HOST_NAME:
3161 #endif
3162 #ifdef HAVE_LDAP_SASL
3163 	case LDAP_OPT_X_SASL_MECH:
3164 	case LDAP_OPT_X_SASL_REALM:
3165 	case LDAP_OPT_X_SASL_AUTHCID:
3166 	case LDAP_OPT_X_SASL_AUTHZID:
3167 #endif
3168 #if (LDAP_API_VERSION > 2000)
3169 	case LDAP_OPT_X_TLS_CACERTDIR:
3170 	case LDAP_OPT_X_TLS_CACERTFILE:
3171 	case LDAP_OPT_X_TLS_CERTFILE:
3172 	case LDAP_OPT_X_TLS_CIPHER_SUITE:
3173 	case LDAP_OPT_X_TLS_KEYFILE:
3174 	case LDAP_OPT_X_TLS_RANDOM_FILE:
3175 #endif
3176 #ifdef LDAP_OPT_X_TLS_CRLFILE
3177 	case LDAP_OPT_X_TLS_CRLFILE:
3178 #endif
3179 #ifdef LDAP_OPT_X_TLS_DHFILE
3180 	case LDAP_OPT_X_TLS_DHFILE:
3181 #endif
3182 #ifdef LDAP_OPT_MATCHED_DN
3183 	case LDAP_OPT_MATCHED_DN:
3184 #endif
3185 		{
3186 			zend_string *val;
3187 			val = zval_get_string(newval);
3188 			if (EG(exception)) {
3189 				RETURN_THROWS();
3190 			}
3191 			if (ldap_set_option(ldap, option, ZSTR_VAL(val))) {
3192 				zend_string_release(val);
3193 				RETURN_FALSE;
3194 			}
3195 			zend_string_release(val);
3196 		} break;
3197 		/* options with boolean value */
3198 	case LDAP_OPT_REFERRALS:
3199 #ifdef LDAP_OPT_RESTART
3200 	case LDAP_OPT_RESTART:
3201 #endif
3202 #ifdef LDAP_OPT_X_SASL_NOCANON
3203 	case LDAP_OPT_X_SASL_NOCANON:
3204 #endif
3205 		{
3206 			void *val;
3207 			val = zend_is_true(newval) ? LDAP_OPT_ON : LDAP_OPT_OFF;
3208 			if (ldap_set_option(ldap, option, val)) {
3209 				RETURN_FALSE;
3210 			}
3211 		} break;
3212 		/* options with control list value */
3213 	case LDAP_OPT_SERVER_CONTROLS:
3214 	case LDAP_OPT_CLIENT_CONTROLS:
3215 		{
3216 			LDAPControl **ctrls;
3217 			int rc;
3218 
3219 			if (Z_TYPE_P(newval) != IS_ARRAY) {
3220 				zend_argument_type_error(3, "must be of type array for the LDAP_OPT_CLIENT_CONTROLS option, %s given", zend_zval_type_name(newval));
3221 				RETURN_THROWS();
3222 			}
3223 
3224 			ctrls = _php_ldap_controls_from_array(ldap, newval, 3);
3225 
3226 			if (ctrls == NULL) {
3227 				RETURN_FALSE;
3228 			} else {
3229 				rc = ldap_set_option(ldap, option, ctrls);
3230 				_php_ldap_controls_free(&ctrls);
3231 				if (rc != LDAP_SUCCESS) {
3232 					RETURN_FALSE;
3233 				}
3234 			}
3235 		} break;
3236 	default:
3237 		RETURN_FALSE;
3238 	}
3239 	RETURN_TRUE;
3240 }
3241 /* }}} */
3242 
3243 #ifdef HAVE_LDAP_PARSE_RESULT
3244 /* {{{ Extract information from result */
PHP_FUNCTION(ldap_parse_result)3245 PHP_FUNCTION(ldap_parse_result)
3246 {
3247 	zval *link, *result, *errcode, *matcheddn, *errmsg, *referrals, *serverctrls;
3248 	ldap_linkdata *ld;
3249 	ldap_resultdata *ldap_result;
3250 	LDAPControl **lserverctrls = NULL;
3251 	char **lreferrals, **refp;
3252 	char *lmatcheddn, *lerrmsg;
3253 	int rc, lerrcode, myargcount = ZEND_NUM_ARGS();
3254 
3255 	if (zend_parse_parameters(myargcount, "OOz|zzzz", &link, ldap_link_ce, &result, ldap_result_ce, &errcode, &matcheddn, &errmsg, &referrals, &serverctrls) != SUCCESS) {
3256 		RETURN_THROWS();
3257 	}
3258 
3259 	ld = Z_LDAP_LINK_P(link);
3260 	VERIFY_LDAP_LINK_CONNECTED(ld);
3261 
3262 	ldap_result = Z_LDAP_RESULT_P(result);
3263 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3264 
3265 	rc = ldap_parse_result(ld->link, ldap_result->result, &lerrcode,
3266 				myargcount > 3 ? &lmatcheddn : NULL,
3267 				myargcount > 4 ? &lerrmsg : NULL,
3268 				myargcount > 5 ? &lreferrals : NULL,
3269 				myargcount > 6 ? &lserverctrls : NULL,
3270 				0);
3271 	if (rc != LDAP_SUCCESS) {
3272 		php_error_docref(NULL, E_WARNING, "Unable to parse result: %s", ldap_err2string(rc));
3273 		RETURN_FALSE;
3274 	}
3275 
3276 	ZEND_TRY_ASSIGN_REF_LONG(errcode, lerrcode);
3277 
3278 	/* Reverse -> fall through */
3279 	switch (myargcount) {
3280 		case 7:
3281 			_php_ldap_controls_to_array(ld->link, lserverctrls, serverctrls, 0);
3282 			ZEND_FALLTHROUGH;
3283 		case 6:
3284 			referrals = zend_try_array_init(referrals);
3285 			if (!referrals) {
3286 				RETURN_THROWS();
3287 			}
3288 			if (lreferrals != NULL) {
3289 				refp = lreferrals;
3290 				while (*refp) {
3291 					add_next_index_string(referrals, *refp);
3292 					refp++;
3293 				}
3294 				ldap_memvfree((void**)lreferrals);
3295 			}
3296 			ZEND_FALLTHROUGH;
3297 		case 5:
3298 			if (lerrmsg == NULL) {
3299 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(errmsg);
3300 			} else {
3301 				ZEND_TRY_ASSIGN_REF_STRING(errmsg, lerrmsg);
3302 				ldap_memfree(lerrmsg);
3303 			}
3304 			ZEND_FALLTHROUGH;
3305 		case 4:
3306 			if (lmatcheddn == NULL) {
3307 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(matcheddn);
3308 			} else {
3309 				ZEND_TRY_ASSIGN_REF_STRING(matcheddn, lmatcheddn);
3310 				ldap_memfree(lmatcheddn);
3311 			}
3312 	}
3313 	RETURN_TRUE;
3314 }
3315 /* }}} */
3316 #endif
3317 
3318 /* {{{ Extended operation response parsing, Pierangelo Masarati */
3319 #ifdef HAVE_LDAP_PARSE_EXTENDED_RESULT
3320 /* {{{ Extract information from extended operation result */
PHP_FUNCTION(ldap_parse_exop)3321 PHP_FUNCTION(ldap_parse_exop)
3322 {
3323 	zval *link, *result, *retdata, *retoid;
3324 	ldap_linkdata *ld;
3325 	ldap_resultdata *ldap_result;
3326 	char *lretoid;
3327 	struct berval *lretdata;
3328 	int rc, myargcount = ZEND_NUM_ARGS();
3329 
3330 	if (zend_parse_parameters(myargcount, "OO|zz", &link, ldap_link_ce, &result, ldap_result_ce, &retdata, &retoid) != SUCCESS) {
3331 		RETURN_THROWS();
3332 	}
3333 
3334 	ld = Z_LDAP_LINK_P(link);
3335 	VERIFY_LDAP_LINK_CONNECTED(ld);
3336 
3337 	ldap_result = Z_LDAP_RESULT_P(result);
3338 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3339 
3340 	rc = ldap_parse_extended_result(ld->link, ldap_result->result,
3341 				myargcount > 3 ? &lretoid: NULL,
3342 				myargcount > 2 ? &lretdata: NULL,
3343 				0);
3344 	if (rc != LDAP_SUCCESS) {
3345 		php_error_docref(NULL, E_WARNING, "Unable to parse extended operation result: %s", ldap_err2string(rc));
3346 		RETURN_FALSE;
3347 	}
3348 
3349 	/* Reverse -> fall through */
3350 	switch (myargcount) {
3351 		case 4:
3352 			if (lretoid == NULL) {
3353 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retoid);
3354 			} else {
3355 				ZEND_TRY_ASSIGN_REF_STRING(retoid, lretoid);
3356 				ldap_memfree(lretoid);
3357 			}
3358 			ZEND_FALLTHROUGH;
3359 		case 3:
3360 			/* use arg #3 as the data returned by the server */
3361 			if (lretdata == NULL) {
3362 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retdata);
3363 			} else {
3364 				ZEND_TRY_ASSIGN_REF_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len);
3365 				ldap_memfree(lretdata->bv_val);
3366 				ldap_memfree(lretdata);
3367 			}
3368 	}
3369 	RETURN_TRUE;
3370 }
3371 /* }}} */
3372 #endif
3373 /* }}} */
3374 
3375 /* {{{ Count the number of references in a search result */
PHP_FUNCTION(ldap_count_references)3376 PHP_FUNCTION(ldap_count_references)
3377 {
3378 	zval *link, *result;
3379 	ldap_linkdata *ld;
3380 	ldap_resultdata *ldap_result;
3381 
3382 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
3383 		RETURN_THROWS();
3384 	}
3385 
3386 	ld = Z_LDAP_LINK_P(link);
3387 	VERIFY_LDAP_LINK_CONNECTED(ld);
3388 
3389 	ldap_result = Z_LDAP_RESULT_P(result);
3390 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3391 
3392 	RETURN_LONG(ldap_count_references(ld->link, ldap_result->result));
3393 }
3394 /* }}} */
3395 
3396 /* {{{ Return first reference */
PHP_FUNCTION(ldap_first_reference)3397 PHP_FUNCTION(ldap_first_reference)
3398 {
3399 	zval *link, *result;
3400 	ldap_linkdata *ld;
3401 	ldap_result_entry *resultentry;
3402 	ldap_resultdata *ldap_result;
3403 	LDAPMessage *entry;
3404 
3405 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result, ldap_result_ce) != SUCCESS) {
3406 		RETURN_THROWS();
3407 	}
3408 
3409 	ld = Z_LDAP_LINK_P(link);
3410 	VERIFY_LDAP_LINK_CONNECTED(ld);
3411 
3412 	ldap_result = Z_LDAP_RESULT_P(result);
3413 	VERIFY_LDAP_RESULT_OPEN(ldap_result);
3414 
3415 	if ((entry = ldap_first_reference(ld->link, ldap_result->result)) == NULL) {
3416 		RETVAL_FALSE;
3417 	} else {
3418 		object_init_ex(return_value, ldap_result_entry_ce);
3419 		resultentry = Z_LDAP_RESULT_ENTRY_P(return_value);
3420 		ZVAL_COPY(&resultentry->res, result);
3421 		resultentry->data = entry;
3422 		resultentry->ber = NULL;
3423 	}
3424 }
3425 /* }}} */
3426 
3427 /* {{{ Get next reference */
PHP_FUNCTION(ldap_next_reference)3428 PHP_FUNCTION(ldap_next_reference)
3429 {
3430 	zval *link, *result_entry;
3431 	ldap_linkdata *ld;
3432 	ldap_result_entry *resultentry, *resultentry_next;
3433 	LDAPMessage *entry_next;
3434 
3435 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OO", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce) != SUCCESS) {
3436 		RETURN_THROWS();
3437 	}
3438 
3439 	ld = Z_LDAP_LINK_P(link);
3440 	VERIFY_LDAP_LINK_CONNECTED(ld);
3441 
3442 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
3443 
3444 	if ((entry_next = ldap_next_reference(ld->link, resultentry->data)) == NULL) {
3445 		RETVAL_FALSE;
3446 	} else {
3447 		object_init_ex(return_value, ldap_result_entry_ce);
3448 		resultentry_next = Z_LDAP_RESULT_ENTRY_P(return_value);
3449 		ZVAL_COPY(&resultentry_next->res, &resultentry->res);
3450 		resultentry_next->data = entry_next;
3451 		resultentry_next->ber = NULL;
3452 	}
3453 }
3454 /* }}} */
3455 
3456 #ifdef HAVE_LDAP_PARSE_REFERENCE
3457 /* {{{ Extract information from reference entry */
PHP_FUNCTION(ldap_parse_reference)3458 PHP_FUNCTION(ldap_parse_reference)
3459 {
3460 	zval *link, *result_entry, *referrals;
3461 	ldap_linkdata *ld;
3462 	ldap_result_entry *resultentry;
3463 	char **lreferrals, **refp;
3464 
3465 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OOz", &link, ldap_link_ce, &result_entry, ldap_result_entry_ce, &referrals) != SUCCESS) {
3466 		RETURN_THROWS();
3467 	}
3468 
3469 	ld = Z_LDAP_LINK_P(link);
3470 	VERIFY_LDAP_LINK_CONNECTED(ld);
3471 
3472 	resultentry = Z_LDAP_RESULT_ENTRY_P(result_entry);
3473 
3474 	if (ldap_parse_reference(ld->link, resultentry->data, &lreferrals, NULL /* &serverctrls */, 0) != LDAP_SUCCESS) {
3475 		RETURN_FALSE;
3476 	}
3477 
3478 	referrals = zend_try_array_init(referrals);
3479 	if (!referrals) {
3480 		RETURN_THROWS();
3481 	}
3482 
3483 	if (lreferrals != NULL) {
3484 		refp = lreferrals;
3485 		while (*refp) {
3486 			add_next_index_string(referrals, *refp);
3487 			refp++;
3488 		}
3489 		ldap_memvfree((void**)lreferrals);
3490 	}
3491 	RETURN_TRUE;
3492 }
3493 /* }}} */
3494 #endif
3495 
3496 /* {{{ php_ldap_do_rename */
php_ldap_do_rename(INTERNAL_FUNCTION_PARAMETERS,int ext)3497 static void php_ldap_do_rename(INTERNAL_FUNCTION_PARAMETERS, int ext)
3498 {
3499 	zval *serverctrls = NULL;
3500 	zval *link;
3501 	ldap_linkdata *ld;
3502 	LDAPControl **lserverctrls = NULL;
3503 	ldap_resultdata *result;
3504 	LDAPMessage *ldap_res;
3505 	int rc, msgid;
3506 	char *dn, *newrdn, *newparent;
3507 	size_t dn_len, newrdn_len, newparent_len;
3508 	bool deleteoldrdn;
3509 
3510 	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) {
3511 		RETURN_THROWS();
3512 	}
3513 
3514 	ld = Z_LDAP_LINK_P(link);
3515 	VERIFY_LDAP_LINK_CONNECTED(ld);
3516 
3517 	if (newparent_len == 0) {
3518 		newparent = NULL;
3519 	}
3520 
3521 #if (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP)
3522 	if (serverctrls) {
3523 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 6);
3524 		if (lserverctrls == NULL) {
3525 			RETVAL_FALSE;
3526 			goto cleanup;
3527 		}
3528 	}
3529 
3530 	if (ext) {
3531 		rc = ldap_rename(ld->link, dn, newrdn, newparent, deleteoldrdn, lserverctrls, NULL, &msgid);
3532 	} else {
3533 		rc = ldap_rename_s(ld->link, dn, newrdn, newparent, deleteoldrdn, lserverctrls, NULL);
3534 	}
3535 #else
3536 	if (newparent_len != 0) {
3537 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, newparent must be the empty string, can only modify RDN");
3538 		RETURN_FALSE;
3539 	}
3540 	if (serverctrls) {
3541 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, controls are not supported");
3542 		RETURN_FALSE;
3543 	}
3544 	if (ext) {
3545 		php_error_docref(NULL, E_WARNING, "You are using old LDAP API, ldap_rename_ext is not supported");
3546 		RETURN_FALSE;
3547 	}
3548 /* could support old APIs but need check for ldap_modrdn2()/ldap_modrdn() */
3549 	rc = ldap_modrdn2_s(ld->link, dn, newrdn, deleteoldrdn);
3550 #endif
3551 
3552 	if (rc != LDAP_SUCCESS) {
3553 		RETVAL_FALSE;
3554 	} else if (ext) {
3555 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3556 		if (rc == -1) {
3557 			php_error_docref(NULL, E_WARNING, "Rename operation failed");
3558 			RETVAL_FALSE;
3559 			goto cleanup;
3560 		}
3561 
3562 		/* return a PHP control object */
3563 		object_init_ex(return_value, ldap_result_ce);
3564 		result = Z_LDAP_RESULT_P(return_value);
3565 		result->result = ldap_res;
3566 	} else {
3567 		RETVAL_TRUE;
3568 	}
3569 
3570 cleanup:
3571 	if (lserverctrls) {
3572 		_php_ldap_controls_free(&lserverctrls);
3573 	}
3574 
3575 	return;
3576 }
3577 /* }}} */
3578 
3579 /* {{{ Modify the name of an entry */
PHP_FUNCTION(ldap_rename)3580 PHP_FUNCTION(ldap_rename)
3581 {
3582 	php_ldap_do_rename(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3583 }
3584 /* }}} */
3585 
3586 /* {{{ Modify the name of an entry */
PHP_FUNCTION(ldap_rename_ext)3587 PHP_FUNCTION(ldap_rename_ext)
3588 {
3589 	php_ldap_do_rename(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3590 }
3591 /* }}} */
3592 
3593 #ifdef HAVE_LDAP_START_TLS_S
3594 /* {{{ Start TLS */
PHP_FUNCTION(ldap_start_tls)3595 PHP_FUNCTION(ldap_start_tls)
3596 {
3597 	zval *link;
3598 	ldap_linkdata *ld;
3599 	int rc, protocol = LDAP_VERSION3;
3600 
3601 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) != SUCCESS) {
3602 		RETURN_THROWS();
3603 	}
3604 
3605 	ld = Z_LDAP_LINK_P(link);
3606 	VERIFY_LDAP_LINK_CONNECTED(ld);
3607 
3608 	if (((rc = ldap_set_option(ld->link, LDAP_OPT_PROTOCOL_VERSION, &protocol)) != LDAP_SUCCESS) ||
3609 		((rc = ldap_start_tls_s(ld->link, NULL, NULL)) != LDAP_SUCCESS)
3610 	) {
3611 		php_error_docref(NULL, E_WARNING,"Unable to start TLS: %s", ldap_err2string(rc));
3612 		RETURN_FALSE;
3613 	} else {
3614 		RETURN_TRUE;
3615 	}
3616 }
3617 /* }}} */
3618 #endif
3619 #endif /* (LDAP_API_VERSION > 2000) || defined(HAVE_ORALDAP) */
3620 
3621 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
3622 /* {{{ _ldap_rebind_proc() */
_ldap_rebind_proc(LDAP * ldap,const char * url,ber_tag_t req,ber_int_t msgid,void * params)3623 int _ldap_rebind_proc(LDAP *ldap, const char *url, ber_tag_t req, ber_int_t msgid, void *params)
3624 {
3625 	ldap_linkdata *ld = NULL;
3626 	int retval;
3627 	zval cb_args[2];
3628 	zval cb_retval;
3629 	zval *cb_link = (zval *) params;
3630 
3631 	ld = Z_LDAP_LINK_P(cb_link);
3632 	if (!ld->link) {
3633 		zend_throw_error(NULL, "LDAP connection has already been closed");
3634 		return LDAP_OTHER;
3635 	}
3636 
3637 	/* link exists and callback set? */
3638 	if (Z_ISUNDEF(ld->rebindproc)) {
3639 		php_error_docref(NULL, E_WARNING, "No callback set");
3640 		return LDAP_OTHER;
3641 	}
3642 
3643 	/* callback */
3644 	ZVAL_COPY_VALUE(&cb_args[0], cb_link);
3645 	ZVAL_STRING(&cb_args[1], url);
3646 	if (call_user_function(EG(function_table), NULL, &ld->rebindproc, &cb_retval, 2, cb_args) == SUCCESS && !Z_ISUNDEF(cb_retval)) {
3647 		retval = zval_get_long(&cb_retval);
3648 		zval_ptr_dtor(&cb_retval);
3649 	} else {
3650 		php_error_docref(NULL, E_WARNING, "rebind_proc PHP callback failed");
3651 		retval = LDAP_OTHER;
3652 	}
3653 	zval_ptr_dtor(&cb_args[1]);
3654 	return retval;
3655 }
3656 /* }}} */
3657 
3658 /* {{{ Set a callback function to do re-binds on referral chasing. */
PHP_FUNCTION(ldap_set_rebind_proc)3659 PHP_FUNCTION(ldap_set_rebind_proc)
3660 {
3661 	zval *link;
3662 	zend_fcall_info fci;
3663 	zend_fcall_info_cache fcc;
3664 	ldap_linkdata *ld;
3665 
3666 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Of!", &link, ldap_link_ce, &fci, &fcc) == FAILURE) {
3667 		RETURN_THROWS();
3668 	}
3669 
3670 	ld = Z_LDAP_LINK_P(link);
3671 	VERIFY_LDAP_LINK_CONNECTED(ld);
3672 
3673 	if (!ZEND_FCI_INITIALIZED(fci)) {
3674 		/* unregister rebind procedure */
3675 		if (!Z_ISUNDEF(ld->rebindproc)) {
3676 			zval_ptr_dtor(&ld->rebindproc);
3677 			ZVAL_UNDEF(&ld->rebindproc);
3678 			ldap_set_rebind_proc(ld->link, NULL, NULL);
3679 		}
3680 		RETURN_TRUE;
3681 	}
3682 
3683 	/* register rebind procedure */
3684 	if (Z_ISUNDEF(ld->rebindproc)) {
3685 		ldap_set_rebind_proc(ld->link, _ldap_rebind_proc, (void *) link);
3686 	} else {
3687 		zval_ptr_dtor(&ld->rebindproc);
3688 	}
3689 
3690 	ZVAL_COPY(&ld->rebindproc, &fci.function_name);
3691 	RETURN_TRUE;
3692 }
3693 /* }}} */
3694 #endif
3695 
php_ldap_do_escape(const bool * map,const char * value,size_t valuelen,zend_long flags)3696 static zend_string* php_ldap_do_escape(const bool *map, const char *value, size_t valuelen, zend_long flags)
3697 {
3698 	char hex[] = "0123456789abcdef";
3699 	size_t i, p = 0;
3700 	size_t len = 0;
3701 	zend_string *ret;
3702 
3703 	for (i = 0; i < valuelen; i++) {
3704 		len += (map[(unsigned char) value[i]]) ? 3 : 1;
3705 	}
3706 	/* Per RFC 4514, a leading and trailing space must be escaped */
3707 	if ((flags & PHP_LDAP_ESCAPE_DN) && (value[0] == ' ')) {
3708 		len += 2;
3709 	}
3710 	if ((flags & PHP_LDAP_ESCAPE_DN) && ((valuelen > 1) && (value[valuelen - 1] == ' '))) {
3711 		len += 2;
3712 	}
3713 
3714 	ret =  zend_string_alloc(len, 0);
3715 
3716 	for (i = 0; i < valuelen; i++) {
3717 		unsigned char v = (unsigned char) value[i];
3718 
3719 		if (map[v] || ((flags & PHP_LDAP_ESCAPE_DN) && ((i == 0) || (i + 1 == valuelen)) && (v == ' '))) {
3720 			ZSTR_VAL(ret)[p++] = '\\';
3721 			ZSTR_VAL(ret)[p++] = hex[v >> 4];
3722 			ZSTR_VAL(ret)[p++] = hex[v & 0x0f];
3723 		} else {
3724 			ZSTR_VAL(ret)[p++] = v;
3725 		}
3726 	}
3727 
3728 	ZSTR_VAL(ret)[p] = '\0';
3729 	ZSTR_LEN(ret) = p;
3730 	return ret;
3731 }
3732 
php_ldap_escape_map_set_chars(bool * map,const char * chars,const size_t charslen,char escape)3733 static void php_ldap_escape_map_set_chars(bool *map, const char *chars, const size_t charslen, char escape)
3734 {
3735 	size_t i = 0;
3736 	while (i < charslen) {
3737 		map[(unsigned char) chars[i++]] = escape;
3738 	}
3739 }
3740 
PHP_FUNCTION(ldap_escape)3741 PHP_FUNCTION(ldap_escape)
3742 {
3743 	char *value, *ignores;
3744 	size_t valuelen = 0, ignoreslen = 0;
3745 	int i;
3746 	zend_long flags = 0;
3747 	bool map[256] = {0}, havecharlist = 0;
3748 
3749 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|sl", &value, &valuelen, &ignores, &ignoreslen, &flags) != SUCCESS) {
3750 		RETURN_THROWS();
3751 	}
3752 
3753 	if (!valuelen) {
3754 		RETURN_EMPTY_STRING();
3755 	}
3756 
3757 	if (flags & PHP_LDAP_ESCAPE_FILTER) {
3758 		havecharlist = 1;
3759 		php_ldap_escape_map_set_chars(map, "\\*()\0", sizeof("\\*()\0") - 1, 1);
3760 	}
3761 
3762 	if (flags & PHP_LDAP_ESCAPE_DN) {
3763 		havecharlist = 1;
3764 		php_ldap_escape_map_set_chars(map, "\\,=+<>;\"#\r", sizeof("\\,=+<>;\"#\r") - 1, 1);
3765 	}
3766 
3767 	if (!havecharlist) {
3768 		for (i = 0; i < 256; i++) {
3769 			map[i] = 1;
3770 		}
3771 	}
3772 
3773 	if (ignoreslen) {
3774 		php_ldap_escape_map_set_chars(map, ignores, ignoreslen, 0);
3775 	}
3776 
3777 	RETURN_NEW_STR(php_ldap_do_escape(map, value, valuelen, flags));
3778 }
3779 
3780 #ifdef STR_TRANSLATION
3781 /* {{{ php_ldap_do_translate */
php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS,int way)3782 static void php_ldap_do_translate(INTERNAL_FUNCTION_PARAMETERS, int way)
3783 {
3784 	char *value;
3785 	size_t value_len;
3786 	int result;
3787 
3788 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &value, &value_len) != SUCCESS) {
3789 		RETURN_THROWS();
3790 	}
3791 
3792 	if (value_len == 0) {
3793 		RETURN_FALSE;
3794 	}
3795 
3796 	if (way == 1) {
3797 		result = ldap_8859_to_t61(&value, &value_len, 0);
3798 	} else {
3799 		result = ldap_t61_to_8859(&value, &value_len, 0);
3800 	}
3801 
3802 	if (result == LDAP_SUCCESS) {
3803 		RETVAL_STRINGL(value, value_len);
3804 		free(value);
3805 	} else {
3806 		php_error_docref(NULL, E_WARNING, "Conversion from ISO-8859-1 to t61 failed: %s", ldap_err2string(result));
3807 		RETVAL_FALSE;
3808 	}
3809 }
3810 /* }}} */
3811 
3812 /* {{{ Translate t61 characters to 8859 characters */
PHP_FUNCTION(ldap_t61_to_8859)3813 PHP_FUNCTION(ldap_t61_to_8859)
3814 {
3815 	php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
3816 }
3817 /* }}} */
3818 
3819 /* {{{ Translate 8859 characters to t61 characters */
PHP_FUNCTION(ldap_8859_to_t61)3820 PHP_FUNCTION(ldap_8859_to_t61)
3821 {
3822 	php_ldap_do_translate(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
3823 }
3824 /* }}} */
3825 #endif
3826 
3827 /* {{{ Extended operations, Pierangelo Masarati */
3828 #ifdef HAVE_LDAP_EXTENDED_OPERATION_S
3829 /* {{{ Extended operation */
PHP_FUNCTION(ldap_exop)3830 PHP_FUNCTION(ldap_exop)
3831 {
3832 	zval *serverctrls = NULL;
3833 	zval *link, *retdata = NULL, *retoid = NULL;
3834 	char *lretoid = NULL;
3835 	zend_string *reqoid, *reqdata = NULL;
3836 	struct berval lreqdata, *lretdata = NULL;
3837 	ldap_linkdata *ld;
3838 	ldap_resultdata *result;
3839 	LDAPMessage *ldap_res;
3840 	LDAPControl **lserverctrls = NULL;
3841 	int rc, msgid;
3842 
3843 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "OS|S!a!zz", &link, ldap_link_ce, &reqoid, &reqdata, &serverctrls, &retdata, &retoid) != SUCCESS) {
3844 		RETURN_THROWS();
3845 	}
3846 
3847 	ld = Z_LDAP_LINK_P(link);
3848 	VERIFY_LDAP_LINK_CONNECTED(ld);
3849 
3850 	if (reqdata) {
3851 		lreqdata.bv_val = ZSTR_VAL(reqdata);
3852 		lreqdata.bv_len = ZSTR_LEN(reqdata);
3853 	} else {
3854 		lreqdata.bv_len = 0;
3855 	}
3856 
3857 	if (serverctrls) {
3858 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls, 4);
3859 		if (lserverctrls == NULL) {
3860 			RETVAL_FALSE;
3861 			goto cleanup;
3862 		}
3863 	}
3864 
3865 	if (retdata) {
3866 		/* synchronous call */
3867 		rc = ldap_extended_operation_s(ld->link, ZSTR_VAL(reqoid),
3868 			lreqdata.bv_len > 0 ? &lreqdata: NULL,
3869 			lserverctrls,
3870 			NULL,
3871 			retoid ? &lretoid : NULL,
3872 			&lretdata );
3873 		if (rc != LDAP_SUCCESS ) {
3874 			php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", ZSTR_VAL(reqoid), ldap_err2string(rc), rc);
3875 			RETVAL_FALSE;
3876 			goto cleanup;
3877 		}
3878 
3879 		if (retoid) {
3880 			if (lretoid) {
3881 				ZEND_TRY_ASSIGN_REF_STRING(retoid, lretoid);
3882 				ldap_memfree(lretoid);
3883 			} else {
3884 				ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retoid);
3885 			}
3886 		}
3887 
3888 		if (lretdata) {
3889 			ZEND_TRY_ASSIGN_REF_STRINGL(retdata, lretdata->bv_val, lretdata->bv_len);
3890 			ldap_memfree(lretdata->bv_val);
3891 			ldap_memfree(lretdata);
3892 		} else {
3893 			ZEND_TRY_ASSIGN_REF_EMPTY_STRING(retdata);
3894 		}
3895 
3896 		RETVAL_TRUE;
3897 		goto cleanup;
3898 	}
3899 
3900 	/* asynchronous call */
3901 	rc = ldap_extended_operation(ld->link, ZSTR_VAL(reqoid),
3902 		lreqdata.bv_len > 0 ? &lreqdata: NULL,
3903 		lserverctrls,
3904 		NULL,
3905 		&msgid);
3906 	if (rc != LDAP_SUCCESS ) {
3907 		php_error_docref(NULL, E_WARNING, "Extended operation %s failed: %s (%d)", ZSTR_VAL(reqoid), ldap_err2string(rc), rc);
3908 		RETVAL_FALSE;
3909 		goto cleanup;
3910 	}
3911 
3912 	rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3913 	if (rc == -1) {
3914 		php_error_docref(NULL, E_WARNING, "Extended operation %s failed", ZSTR_VAL(reqoid));
3915 		RETVAL_FALSE;
3916 		goto cleanup;
3917 	}
3918 
3919 	/* return a PHP control object */
3920 	object_init_ex(return_value, ldap_result_ce);
3921 	result = Z_LDAP_RESULT_P(return_value);
3922 	result->result = ldap_res;
3923 
3924 	cleanup:
3925 	if (lserverctrls) {
3926 		_php_ldap_controls_free(&lserverctrls);
3927 	}
3928 }
3929 /* }}} */
3930 #endif
3931 
3932 #ifdef HAVE_LDAP_PASSWD
3933 /* {{{ Passwd modify extended operation */
PHP_FUNCTION(ldap_exop_passwd)3934 PHP_FUNCTION(ldap_exop_passwd)
3935 {
3936 	zval *link, *serverctrls;
3937 	struct berval luser = { 0L, NULL };
3938 	struct berval loldpw = { 0L, NULL };
3939 	struct berval lnewpw = { 0L, NULL };
3940 	struct berval lgenpasswd = { 0L, NULL };
3941 	LDAPControl *ctrl, **lserverctrls = NULL, *requestctrls[2] = { NULL, NULL };
3942 	LDAPMessage* ldap_res = NULL;
3943 	ldap_linkdata *ld;
3944 	int rc, myargcount = ZEND_NUM_ARGS(), msgid, err;
3945 	char* errmsg = NULL;
3946 
3947 	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) {
3948 		RETURN_THROWS();
3949 	}
3950 
3951 	ld = Z_LDAP_LINK_P(link);
3952 	VERIFY_LDAP_LINK_CONNECTED(ld);
3953 
3954 	switch (myargcount) {
3955 		case 5:
3956 			/* ldap_create_passwordpolicy_control() allocates ctrl */
3957 			if (ldap_create_passwordpolicy_control(ld->link, &ctrl) == LDAP_SUCCESS) {
3958 				requestctrls[0] = ctrl;
3959 			}
3960 	}
3961 
3962 	/* asynchronous call to get result and controls */
3963 	rc = ldap_passwd(ld->link, &luser,
3964 		loldpw.bv_len > 0 ? &loldpw : NULL,
3965 		lnewpw.bv_len > 0 ? &lnewpw : NULL,
3966 		requestctrls,
3967 		NULL, &msgid);
3968 
3969 	if (requestctrls[0] != NULL) {
3970 		ldap_control_free(requestctrls[0]);
3971 	}
3972 
3973 	if (rc != LDAP_SUCCESS ) {
3974 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3975 		RETVAL_FALSE;
3976 		goto cleanup;
3977 	}
3978 
3979 	rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
3980 	if ((rc < 0) || !ldap_res) {
3981 		rc = _get_lderrno(ld->link);
3982 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3983 		RETVAL_FALSE;
3984 		goto cleanup;
3985 	}
3986 
3987 	rc = ldap_parse_passwd(ld->link, ldap_res, &lgenpasswd);
3988 	if( rc != LDAP_SUCCESS ) {
3989 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3990 		RETVAL_FALSE;
3991 		goto cleanup;
3992 	}
3993 
3994 	rc = ldap_parse_result(ld->link, ldap_res, &err, NULL, &errmsg, NULL, (myargcount > 4 ? &lserverctrls : NULL), 0);
3995 	if( rc != LDAP_SUCCESS ) {
3996 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", ldap_err2string(rc), rc);
3997 		RETVAL_FALSE;
3998 		goto cleanup;
3999 	}
4000 
4001 	if (myargcount > 4) {
4002 		_php_ldap_controls_to_array(ld->link, lserverctrls, serverctrls, 0);
4003 	}
4004 
4005 	/* return */
4006 	if (lnewpw.bv_len == 0) {
4007 		if (lgenpasswd.bv_len == 0) {
4008 			RETVAL_EMPTY_STRING();
4009 		} else {
4010 			RETVAL_STRINGL(lgenpasswd.bv_val, lgenpasswd.bv_len);
4011 		}
4012 	} else if (err == LDAP_SUCCESS) {
4013 		RETVAL_TRUE;
4014 	} else {
4015 		php_error_docref(NULL, E_WARNING, "Passwd modify extended operation failed: %s (%d)", (errmsg ? errmsg : ldap_err2string(err)), err);
4016 		RETVAL_FALSE;
4017 	}
4018 
4019 cleanup:
4020 	if (lgenpasswd.bv_val != NULL) {
4021 		ldap_memfree(lgenpasswd.bv_val);
4022 	}
4023 	if (ldap_res != NULL) {
4024 		ldap_msgfree(ldap_res);
4025 	}
4026 	if (errmsg != NULL) {
4027 		ldap_memfree(errmsg);
4028 	}
4029 }
4030 /* }}} */
4031 #endif
4032 
4033 #ifdef HAVE_LDAP_WHOAMI_S
4034 /* {{{ Whoami extended operation */
PHP_FUNCTION(ldap_exop_whoami)4035 PHP_FUNCTION(ldap_exop_whoami)
4036 {
4037 	zval *link;
4038 	struct berval *lauthzid;
4039 	ldap_linkdata *ld;
4040 	int rc;
4041 
4042 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &link, ldap_link_ce) == FAILURE) {
4043 		RETURN_THROWS();
4044 	}
4045 
4046 	ld = Z_LDAP_LINK_P(link);
4047 	VERIFY_LDAP_LINK_CONNECTED(ld);
4048 
4049 	/* synchronous call */
4050 	rc = ldap_whoami_s(ld->link, &lauthzid, NULL, NULL);
4051 	if (rc != LDAP_SUCCESS ) {
4052 		php_error_docref(NULL, E_WARNING, "Whoami extended operation failed: %s (%d)", ldap_err2string(rc), rc);
4053 		RETURN_FALSE;
4054 	}
4055 
4056 	if (lauthzid == NULL) {
4057 		RETVAL_EMPTY_STRING();
4058 	} else {
4059 		RETVAL_STRINGL(lauthzid->bv_val, lauthzid->bv_len);
4060 		ldap_memfree(lauthzid->bv_val);
4061 		ldap_memfree(lauthzid);
4062 	}
4063 }
4064 /* }}} */
4065 #endif
4066 
4067 #ifdef HAVE_LDAP_REFRESH_S
4068 /* {{{ DDS refresh extended operation */
PHP_FUNCTION(ldap_exop_refresh)4069 PHP_FUNCTION(ldap_exop_refresh)
4070 {
4071 	zval *link;
4072 	zend_long ttl;
4073 	struct berval ldn;
4074 	ber_int_t lttl;
4075 	ber_int_t newttl;
4076 	ldap_linkdata *ld;
4077 	int rc;
4078 
4079 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "Osl", &link, ldap_link_ce, &ldn.bv_val, &ldn.bv_len, &ttl) != SUCCESS) {
4080 		RETURN_THROWS();
4081 	}
4082 
4083 	ld = Z_LDAP_LINK_P(link);
4084 	VERIFY_LDAP_LINK_CONNECTED(ld);
4085 
4086 	lttl = (ber_int_t) ttl;
4087 
4088 	rc = ldap_refresh_s(ld->link, &ldn, lttl, &newttl, NULL, NULL);
4089 	if (rc != LDAP_SUCCESS ) {
4090 		php_error_docref(NULL, E_WARNING, "Refresh extended operation failed: %s (%d)", ldap_err2string(rc), rc);
4091 		RETURN_FALSE;
4092 	}
4093 
4094 	RETURN_LONG(newttl);
4095 }
4096 /* }}} */
4097 #endif
4098 
4099 zend_module_entry ldap_module_entry = { /* {{{ */
4100 	STANDARD_MODULE_HEADER,
4101 	"ldap",
4102 	ext_functions,
4103 	PHP_MINIT(ldap),
4104 	PHP_MSHUTDOWN(ldap),
4105 	NULL,
4106 	NULL,
4107 	PHP_MINFO(ldap),
4108 	PHP_LDAP_VERSION,
4109 	PHP_MODULE_GLOBALS(ldap),
4110 	PHP_GINIT(ldap),
4111 	NULL,
4112 	NULL,
4113 	STANDARD_MODULE_PROPERTIES_EX
4114 };
4115 /* }}} */
4116