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