1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Amitay Isaacs  <amitay@w-o-i.com>                           |
16    |          Eric Warnke    <ericw@albany.edu>                           |
17    |          Rasmus Lerdorf <rasmus@php.net>                             |
18    |          Gerrit Thomson <334647@swin.edu.au>                         |
19    |          Jani Taskinen  <sniper@iki.fi>                              |
20    |          Stig Venaas    <venaas@uninett.no>                          |
21    |          Doug Goldstein <cardoe@cardoe.com>                          |
22    |          Côme Chilliet  <mcmic@php.net>                              |
23    | PHP 4.0 updates:  Zeev Suraski <zeev@php.net>                        |
24    +----------------------------------------------------------------------+
25  */
26 
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30 
31 #include "php.h"
32 #include "php_ini.h"
33 
34 #include <stddef.h>
35 
36 #include "ext/standard/dl.h"
37 #include "php_ldap.h"
38 
39 #ifdef PHP_WIN32
40 #include <string.h>
41 #include "config.w32.h"
42 #define strdup _strdup
43 #undef WINDOWS
44 #undef strcasecmp
45 #undef strncasecmp
46 #define WINSOCK 1
47 #define __STDC__ 1
48 #endif
49 
50 #include "ext/standard/php_string.h"
51 #include "ext/standard/info.h"
52 
53 #ifdef HAVE_LDAP_SASL
54 #include <sasl/sasl.h>
55 #endif
56 
57 #define PHP_LDAP_ESCAPE_FILTER 0x01
58 #define PHP_LDAP_ESCAPE_DN     0x02
59 
60 #if defined(LDAP_CONTROL_PAGEDRESULTS) && !defined(HAVE_LDAP_CONTROL_FIND)
ldap_control_find( const char *oid, LDAPControl **ctrls, LDAPControl ***nextctrlp)61 LDAPControl *ldap_control_find( const char *oid, LDAPControl **ctrls, LDAPControl ***nextctrlp)
62 {
63 	assert(nextctrlp == NULL);
64 	return ldap_find_control(oid, ctrls);
65 }
66 #endif
67 
68 #if !defined(LDAP_API_FEATURE_X_OPENLDAP)
ldap_memvfree(void **v)69 void ldap_memvfree(void **v)
70 {
71 	ldap_value_free((char **)v);
72 }
73 #endif
74 
75 typedef struct {
76 	LDAP *link;
77 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
78 	zval rebindproc;
79 #endif
80 } ldap_linkdata;
81 
82 typedef struct {
83 	LDAPMessage *data;
84 	BerElement  *ber;
85 	zval         res;
86 } ldap_resultentry;
87 
88 ZEND_DECLARE_MODULE_GLOBALS(ldap)
89 static PHP_GINIT_FUNCTION(ldap);
90 
91 static int le_link, le_result, le_result_entry;
92 
93 #ifdef COMPILE_DL_LDAP
94 #ifdef ZTS
95 ZEND_TSRMLS_CACHE_DEFINE()
96 #endif
97 ZEND_GET_MODULE(ldap)
98 #endif
99 
_close_ldap_link(zend_resource *rsrc)100 static void _close_ldap_link(zend_resource *rsrc) /* {{{ */
101 {
102 	ldap_linkdata *ld = (ldap_linkdata *)rsrc->ptr;
103 
104 	/* We use ldap_destroy rather than ldap_unbind here, because ldap_unbind
105 	 * will skip the destructor entirely if a critical client control is set. */
106 	ldap_destroy(ld->link);
107 
108 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && defined(HAVE_3ARG_SETREBINDPROC)
109 	zval_ptr_dtor(&ld->rebindproc);
110 #endif
111 
112 	efree(ld);
113 	LDAPG(num_links)--;
114 }
115 /* }}} */
116 
_free_ldap_result(zend_resource *rsrc)117 static void _free_ldap_result(zend_resource *rsrc) /* {{{ */
118 {
119 	LDAPMessage *result = (LDAPMessage *)rsrc->ptr;
120 	ldap_msgfree(result);
121 }
122 /* }}} */
123 
_free_ldap_result_entry(zend_resource *rsrc)124 static void _free_ldap_result_entry(zend_resource *rsrc) /* {{{ */
125 {
126 	ldap_resultentry *entry = (ldap_resultentry *)rsrc->ptr;
127 
128 	if (entry->ber != NULL) {
129 		ber_free(entry->ber, 0);
130 		entry->ber = NULL;
131 	}
132 	zval_ptr_dtor(&entry->res);
133 	efree(entry);
134 }
135 /* }}} */
136 
137 /* {{{ Parse controls from and to arrays */
_php_ldap_control_to_array(LDAP *ld, LDAPControl* ctrl, zval* array, int request)138 static void _php_ldap_control_to_array(LDAP *ld, LDAPControl* ctrl, zval* array, int request)
139 {
140 	array_init(array);
141 
142 	add_assoc_string(array, "oid", ctrl->ldctl_oid);
143 	if (request) {
144 		/* iscritical field only makes sense in request controls (which may be obtained by ldap_get_option) */
145 		add_assoc_bool(array, "iscritical", (ctrl->ldctl_iscritical != 0));
146 	}
147 
148 	/* If it is a known oid, parse to values */
149 	if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PASSWORDPOLICYRESPONSE) == 0) {
150 		int expire = 0, grace = 0, rc;
151 		LDAPPasswordPolicyError pperr;
152 		zval value;
153 
154 		rc = ldap_parse_passwordpolicy_control(ld, ctrl, &expire, &grace, &pperr);
155 		if ( rc == LDAP_SUCCESS ) {
156 			array_init(&value);
157 			add_assoc_long(&value, "expire", expire);
158 			add_assoc_long(&value, "grace", grace);
159 
160 			if ( pperr != PP_noError ) {
161 				add_assoc_long(&value, "error", pperr);
162 			}
163 			add_assoc_zval(array, "value", &value);
164 		} else {
165 			add_assoc_null(array, "value");
166 		}
167 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PAGEDRESULTS) == 0) {
168 		int lestimated, rc;
169 		struct berval lcookie;
170 		zval value;
171 
172 		if (ctrl->ldctl_value.bv_len) {
173 			rc = ldap_parse_pageresponse_control(ld, ctrl, &lestimated, &lcookie);
174 		} else {
175 			/* ldap_parse_pageresponse_control will crash if value is empty */
176 			rc = -1;
177 		}
178 		if ( rc == LDAP_SUCCESS ) {
179 			array_init(&value);
180 			add_assoc_long(&value, "size", lestimated);
181 			add_assoc_stringl(&value, "cookie", lcookie.bv_val, lcookie.bv_len);
182 			add_assoc_zval(array, "value", &value);
183 		} else {
184 			add_assoc_null(array, "value");
185 		}
186 	} else if ((strcmp(ctrl->ldctl_oid, LDAP_CONTROL_PRE_READ) == 0) || (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_POST_READ) == 0)) {
187 		BerElement *ber;
188 		struct berval bv;
189 
190 		ber = ber_init(&ctrl->ldctl_value);
191 		if (ber == NULL) {
192 			add_assoc_null(array, "value");
193 		} else if (ber_scanf(ber, "{m{" /*}}*/, &bv) == LBER_ERROR) {
194 			add_assoc_null(array, "value");
195 		} else {
196 			zval value;
197 
198 			array_init(&value);
199 			add_assoc_stringl(&value, "dn", bv.bv_val, bv.bv_len);
200 
201 			while (ber_scanf(ber, "{m" /*}*/, &bv) != LBER_ERROR) {
202 				int	 i;
203 				BerVarray vals = NULL;
204 				zval tmp;
205 
206 				if (ber_scanf(ber, "[W]", &vals) == LBER_ERROR || vals == NULL)
207 				{
208 					break;
209 				}
210 
211 				array_init(&tmp);
212 				for (i = 0; vals[i].bv_val != NULL; i++) {
213 					add_next_index_stringl(&tmp, vals[i].bv_val, vals[i].bv_len);
214 				}
215 				add_assoc_zval(&value, bv.bv_val, &tmp);
216 
217 				ber_bvarray_free(vals);
218 			}
219 			add_assoc_zval(array, "value", &value);
220 		}
221 
222 		if (ber != NULL) {
223 			ber_free(ber, 1);
224 		}
225 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_SORTRESPONSE) == 0) {
226 		zval value;
227 		int errcode, rc;
228 		char* attribute;
229 
230 		if (ctrl->ldctl_value.bv_len) {
231 			rc = ldap_parse_sortresponse_control(ld, ctrl, &errcode, &attribute);
232 		} else {
233 			rc = -1;
234 		}
235 		if ( rc == LDAP_SUCCESS ) {
236 			array_init(&value);
237 			add_assoc_long(&value, "errcode", errcode);
238 			if (attribute) {
239 				add_assoc_string(&value, "attribute", attribute);
240 				ldap_memfree(attribute);
241 			}
242 			add_assoc_zval(array, "value", &value);
243 		} else {
244 			add_assoc_null(array, "value");
245 		}
246 	} else if (strcmp(ctrl->ldctl_oid, LDAP_CONTROL_VLVRESPONSE) == 0) {
247 		int target, count, errcode, rc;
248 		struct berval *context;
249 		zval value;
250 
251 		if (ctrl->ldctl_value.bv_len) {
252 			rc = ldap_parse_vlvresponse_control(ld, ctrl, &target, &count, &context, &errcode);
253 		} else {
254 			rc = -1;
255 		}
256 		if ( rc == LDAP_SUCCESS ) {
257 			array_init(&value);
258 			add_assoc_long(&value, "target", target);
259 			add_assoc_long(&value, "count", count);
260 			add_assoc_long(&value, "errcode", errcode);
261 			if ( context && (context->bv_len >= 0) ) {
262 				add_assoc_stringl(&value, "context", context->bv_val, context->bv_len);
263 			}
264 			add_assoc_zval(array, "value", &value);
265 			ber_bvfree(context);
266 		} else {
267 			add_assoc_null(array, "value");
268 		}
269 	} else {
270 		if (ctrl->ldctl_value.bv_len) {
271 			add_assoc_stringl(array, "value", ctrl->ldctl_value.bv_val, ctrl->ldctl_value.bv_len);
272 		} else {
273 			add_assoc_null(array, "value");
274 		}
275 	}
276 }
277 
_php_ldap_control_from_array(LDAP *ld, LDAPControl** ctrl, zval* array)278 static int _php_ldap_control_from_array(LDAP *ld, LDAPControl** ctrl, zval* array)
279 {
280 	zval* val;
281 	zend_string *control_oid;
282 	int control_iscritical = 0, rc = LDAP_SUCCESS;
283 	char** ldap_attrs = NULL;
284 	LDAPSortKey** sort_keys = NULL;
285 	zend_string *tmpstring = NULL;
286 
287 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "oid", sizeof("oid") - 1)) == NULL) {
288 		php_error_docref(NULL, E_WARNING, "Control must have an oid key");
289 		return -1;
290 	}
291 
292 	control_oid = zval_get_string(val);
293 	if (EG(exception)) {
294 		return -1;
295 	}
296 
297 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "iscritical", sizeof("iscritical") - 1)) != NULL) {
298 		control_iscritical = zend_is_true(val);
299 	} else {
300 		control_iscritical = 0;
301 	}
302 
303 	struct berval *control_value = NULL;
304 
305 	if ((val = zend_hash_str_find(Z_ARRVAL_P(array), "value", sizeof("value") - 1)) != NULL) {
306 		if (Z_TYPE_P(val) != IS_ARRAY) {
307 			control_value = ber_memalloc(sizeof * control_value);
308 			if (control_value == NULL) {
309 				rc = -1;
310 				php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
311 			} else {
312 				tmpstring = zval_get_string(val);
313 				if (EG(exception)) {
314 					rc = -1;
315 					goto failure;
316 				}
317 				control_value->bv_val = ZSTR_VAL(tmpstring);
318 				control_value->bv_len = ZSTR_LEN(tmpstring);
319 			}
320 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_PAGEDRESULTS) == 0) {
321 			zval* tmp;
322 			int pagesize = 1;
323 			struct berval cookie = { 0, NULL };
324 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "size", sizeof("size") - 1)) != NULL) {
325 				pagesize = zval_get_long(tmp);
326 			}
327 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "cookie", sizeof("cookie") - 1)) != NULL) {
328 				tmpstring = zval_get_string(tmp);
329 				if (EG(exception)) {
330 					rc = -1;
331 					goto failure;
332 				}
333 				cookie.bv_val = ZSTR_VAL(tmpstring);
334 				cookie.bv_len = ZSTR_LEN(tmpstring);
335 			}
336 			control_value = ber_memalloc(sizeof * control_value);
337 			if (control_value == NULL) {
338 				rc = -1;
339 				php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
340 			} else {
341 				rc = ldap_create_page_control_value(ld, pagesize, &cookie, control_value);
342 				if (rc != LDAP_SUCCESS) {
343 					php_error_docref(NULL, E_WARNING, "Failed to create paged result control value: %s (%d)", ldap_err2string(rc), rc);
344 				}
345 			}
346 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_ASSERT) == 0) {
347 			zval* tmp;
348 			zend_string* assert;
349 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "filter", sizeof("filter") - 1)) == NULL) {
350 				rc = -1;
351 				php_error_docref(NULL, E_WARNING, "Filter missing from assert control value array");
352 			} else {
353 				assert = zval_get_string(tmp);
354 				if (EG(exception)) {
355 					rc = -1;
356 					goto failure;
357 				}
358 				control_value = ber_memalloc(sizeof * control_value);
359 				if (control_value == NULL) {
360 					rc = -1;
361 					php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
362 				} else {
363 					/* ldap_create_assertion_control_value does not reset ld_errno, we need to do it ourselves
364 					   See http://www.openldap.org/its/index.cgi/Incoming?id=8674 */
365 					int success = LDAP_SUCCESS;
366 					ldap_set_option(ld, LDAP_OPT_RESULT_CODE, &success);
367 					rc = ldap_create_assertion_control_value(ld, ZSTR_VAL(assert), control_value);
368 					if (rc != LDAP_SUCCESS) {
369 						php_error_docref(NULL, E_WARNING, "Failed to create assert control value: %s (%d)", ldap_err2string(rc), rc);
370 					}
371 				}
372 				zend_string_release(assert);
373 			}
374 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_VALUESRETURNFILTER) == 0) {
375 			zval* tmp;
376 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "filter", sizeof("filter") - 1)) == NULL) {
377 				rc = -1;
378 				php_error_docref(NULL, E_WARNING, "Filter missing from control value array");
379 			} else {
380 				BerElement *vrber = ber_alloc_t(LBER_USE_DER);
381 				control_value = ber_memalloc(sizeof * control_value);
382 				if ((control_value == NULL) || (vrber == NULL)) {
383 					rc = -1;
384 					php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
385 				} else {
386 					tmpstring = zval_get_string(tmp);
387 					if (EG(exception)) {
388 						rc = -1;
389 						goto failure;
390 					}
391 					if (ldap_put_vrFilter(vrber, ZSTR_VAL(tmpstring)) == -1) {
392 						ber_free(vrber, 1);
393 						rc = -1;
394 						php_error_docref(NULL, E_WARNING, "Failed to create control value: Bad ValuesReturnFilter: %s", ZSTR_VAL(tmpstring));
395 					} else {
396 						if (ber_flatten2(vrber, control_value, 0) == -1) {
397 							rc = -1;
398 						}
399 						ber_free(vrber, 1);
400 					}
401 				}
402 			}
403 		} else if ((strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_PRE_READ) == 0) || (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_POST_READ) == 0)) {
404 			zval* tmp;
405 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "attrs", sizeof("attrs") - 1)) == NULL) {
406 				rc = -1;
407 				php_error_docref(NULL, E_WARNING, "Attributes list missing from control value array");
408 			} else {
409 				BerElement *ber = ber_alloc_t(LBER_USE_DER);
410 
411 				control_value = ber_memalloc(sizeof * control_value);
412 				if ((control_value == NULL) || (ber == NULL)) {
413 					rc = -1;
414 					php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
415 				} else {
416 					int num_attribs, i;
417 					zval* attr;
418 
419 					num_attribs = zend_hash_num_elements(Z_ARRVAL_P(tmp));
420 					ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
421 
422 					for (i = 0; i<num_attribs; i++) {
423 						if ((attr = zend_hash_index_find(Z_ARRVAL_P(tmp), i)) == NULL) {
424 							rc = -1;
425 							php_error_docref(NULL, E_WARNING, "Failed to encode attribute list");
426 							goto failure;
427 						}
428 
429 						tmpstring = zval_get_string(attr);
430 						if (EG(exception)) {
431 							rc = -1;
432 							goto failure;
433 						}
434 						ldap_attrs[i] = ZSTR_VAL(tmpstring);
435 					}
436 					ldap_attrs[num_attribs] = NULL;
437 
438 					ber_init2( ber, NULL, LBER_USE_DER );
439 
440 					if (ber_printf(ber, "{v}", ldap_attrs) == -1) {
441 						rc = -1;
442 						php_error_docref(NULL, E_WARNING, "Failed to encode attribute list");
443 					} else {
444 						int err;
445 						err = ber_flatten2(ber, control_value, 0);
446 						if (err < 0) {
447 							rc = -1;
448 							php_error_docref(NULL, E_WARNING, "Failed to encode control value (%d)", err);
449 						}
450 					}
451 				}
452 			}
453 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_SORTREQUEST) == 0) {
454 			int num_keys, i;
455 			zval *sortkey, *tmp;
456 
457 			num_keys = zend_hash_num_elements(Z_ARRVAL_P(val));
458 			sort_keys = safe_emalloc((num_keys+1), sizeof(LDAPSortKey*), 0);
459 
460 			for (i = 0; i<num_keys; i++) {
461 				if ((sortkey = zend_hash_index_find(Z_ARRVAL_P(val), i)) == NULL) {
462 					rc = -1;
463 					php_error_docref(NULL, E_WARNING, "Failed to encode sort keys list");
464 					goto failure;
465 				}
466 
467 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "attr", sizeof("attr") - 1)) == NULL) {
468 					rc = -1;
469 					php_error_docref(NULL, E_WARNING, "Sort key list missing field");
470 					goto failure;
471 				}
472 				sort_keys[i] = emalloc(sizeof(LDAPSortKey));
473 				tmpstring = zval_get_string(tmp);
474 				if (EG(exception)) {
475 					rc = -1;
476 					goto failure;
477 				}
478 				sort_keys[i]->attributeType = ZSTR_VAL(tmpstring);
479 
480 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "oid", sizeof("oid") - 1)) != NULL) {
481 					tmpstring = zval_get_string(tmp);
482 					if (EG(exception)) {
483 						rc = -1;
484 						goto failure;
485 					}
486 					sort_keys[i]->orderingRule = ZSTR_VAL(tmpstring);
487 				} else {
488 					sort_keys[i]->orderingRule = NULL;
489 				}
490 
491 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(sortkey), "reverse", sizeof("reverse") - 1)) != NULL) {
492 					sort_keys[i]->reverseOrder = zend_is_true(tmp);
493 				} else {
494 					sort_keys[i]->reverseOrder = 0;
495 				}
496 			}
497 			sort_keys[num_keys] = NULL;
498 			control_value = ber_memalloc(sizeof * control_value);
499 			if (control_value == NULL) {
500 				rc = -1;
501 				php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
502 			} else {
503 				rc = ldap_create_sort_control_value(ld, sort_keys, control_value);
504 				if (rc != LDAP_SUCCESS) {
505 					php_error_docref(NULL, E_WARNING, "Failed to create sort control value: %s (%d)", ldap_err2string(rc), rc);
506 				}
507 			}
508 		} else if (strcmp(ZSTR_VAL(control_oid), LDAP_CONTROL_VLVREQUEST) == 0) {
509 			zval* tmp;
510 			LDAPVLVInfo vlvInfo;
511 			struct berval attrValue;
512 			struct berval context;
513 
514 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "before", sizeof("before") - 1)) != NULL) {
515 				vlvInfo.ldvlv_before_count = zval_get_long(tmp);
516 			} else {
517 				rc = -1;
518 				php_error_docref(NULL, E_WARNING, "Before key missing from array value for VLV control");
519 				goto failure;
520 			}
521 
522 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "after", sizeof("after") - 1)) != NULL) {
523 				vlvInfo.ldvlv_after_count = zval_get_long(tmp);
524 			} else {
525 				rc = -1;
526 				php_error_docref(NULL, E_WARNING, "After key missing from array value for VLV control");
527 				goto failure;
528 			}
529 
530 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "attrvalue", sizeof("attrvalue") - 1)) != NULL) {
531 				tmpstring = zval_get_string(tmp);
532 				if (EG(exception)) {
533 					rc = -1;
534 					goto failure;
535 				}
536 				attrValue.bv_val = ZSTR_VAL(tmpstring);
537 				attrValue.bv_len = ZSTR_LEN(tmpstring);
538 				vlvInfo.ldvlv_attrvalue = &attrValue;
539 			} else if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "offset", sizeof("offset") - 1)) != NULL) {
540 				vlvInfo.ldvlv_attrvalue = NULL;
541 				vlvInfo.ldvlv_offset = zval_get_long(tmp);
542 				if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "count", sizeof("count") - 1)) != NULL) {
543 					vlvInfo.ldvlv_count = zval_get_long(tmp);
544 				} else {
545 					rc = -1;
546 					php_error_docref(NULL, E_WARNING, "Count key missing from array value for VLV control");
547 					goto failure;
548 				}
549 			} else {
550 				rc = -1;
551 				php_error_docref(NULL, E_WARNING, "Missing either attrvalue or offset key from array value for VLV control");
552 				goto failure;
553 			}
554 
555 			if ((tmp = zend_hash_str_find(Z_ARRVAL_P(val), "context", sizeof("context") - 1)) != NULL) {
556 				tmpstring = zval_get_string(tmp);
557 				if (EG(exception)) {
558 					rc = -1;
559 					goto failure;
560 				}
561 				context.bv_val = ZSTR_VAL(tmpstring);
562 				context.bv_len = ZSTR_LEN(tmpstring);
563 				vlvInfo.ldvlv_context = &context;
564 			} else {
565 				vlvInfo.ldvlv_context = NULL;
566 			}
567 
568 			control_value = ber_memalloc(sizeof * control_value);
569 			if (control_value == NULL) {
570 				rc = -1;
571 				php_error_docref(NULL, E_WARNING, "Failed to allocate control value");
572 			} else {
573 				rc = ldap_create_vlv_control_value(ld, &vlvInfo, control_value);
574 				if (rc != LDAP_SUCCESS) {
575 					php_error_docref(NULL, E_WARNING, "Failed to create VLV control value: %s (%d)", ldap_err2string(rc), rc);
576 				}
577 			}
578 		} else {
579 			php_error_docref(NULL, E_WARNING, "Control OID %s does not expect an array as value", ZSTR_VAL(control_oid));
580 			rc = -1;
581 		}
582 	}
583 
584 	if (rc == LDAP_SUCCESS) {
585 		rc = ldap_control_create(ZSTR_VAL(control_oid), control_iscritical, control_value, 1, ctrl);
586 	}
587 
588 failure:
589 	zend_string_release(control_oid);
590 	if (tmpstring != NULL) {
591 		zend_string_release(tmpstring);
592 	}
593 	if (control_value != NULL) {
594 		ber_memfree(control_value);
595 		control_value = NULL;
596 	}
597 	if (ldap_attrs != NULL) {
598 		efree(ldap_attrs);
599 	}
600 	if (sort_keys != NULL) {
601 		LDAPSortKey** sortp = sort_keys;
602 		while (*sortp) {
603 			efree(*sortp);
604 			sortp++;
605 		}
606 		efree(sort_keys);
607 		sort_keys = NULL;
608 	}
609 
610 	if (rc == LDAP_SUCCESS) {
611 		return LDAP_SUCCESS;
612 	}
613 
614 	/* Failed */
615 	*ctrl = NULL;
616 	return -1;
617 }
618 
_php_ldap_controls_to_array(LDAP *ld, LDAPControl** ctrls, zval* array, int request)619 static void _php_ldap_controls_to_array(LDAP *ld, LDAPControl** ctrls, zval* array, int request)
620 {
621 	zval tmp1;
622 	LDAPControl **ctrlp;
623 
624 	array = zend_try_array_init(array);
625 	if (!array) {
626 		return;
627 	}
628 
629 	if (ctrls == NULL) {
630 		return;
631 	}
632 	ctrlp = ctrls;
633 	while (*ctrlp != NULL) {
634 		_php_ldap_control_to_array(ld, *ctrlp, &tmp1, request);
635 		add_assoc_zval(array, (*ctrlp)->ldctl_oid, &tmp1);
636 		ctrlp++;
637 	}
638 	ldap_controls_free(ctrls);
639 }
640 
_php_ldap_controls_from_array(LDAP *ld, zval* array)641 static LDAPControl** _php_ldap_controls_from_array(LDAP *ld, zval* array)
642 {
643 	int ncontrols;
644 	LDAPControl** ctrlp, **ctrls = NULL;
645 	zval* ctrlarray;
646 	int error = 0;
647 
648 	ncontrols = zend_hash_num_elements(Z_ARRVAL_P(array));
649 	ctrls = safe_emalloc((1 + ncontrols), sizeof(*ctrls), 0);
650 	*ctrls = NULL;
651 	ctrlp = ctrls;
652 	ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(array), ctrlarray) {
653 		if (Z_TYPE_P(ctrlarray) != IS_ARRAY) {
654 			php_error_docref(NULL, E_WARNING, "The array value must contain only arrays, where each array is a control");
655 			error = 1;
656 			break;
657 		}
658 
659 		if (_php_ldap_control_from_array(ld, ctrlp, ctrlarray) == LDAP_SUCCESS) {
660 			++ctrlp;
661 		} else {
662 			error = 1;
663 			break;
664 		}
665 
666 		*ctrlp = NULL;
667 	} ZEND_HASH_FOREACH_END();
668 
669 	if (error) {
670 		ctrlp = ctrls;
671 		while (*ctrlp) {
672 			ldap_control_free(*ctrlp);
673 			ctrlp++;
674 		}
675 		efree(ctrls);
676 		ctrls = NULL;
677 	}
678 
679 	return ctrls;
680 }
681 
_php_ldap_controls_free(LDAPControl*** ctrls)682 static void _php_ldap_controls_free (LDAPControl*** ctrls)
683 {
684 	LDAPControl **ctrlp;
685 
686 	if (*ctrls) {
687 		ctrlp = *ctrls;
688 		while (*ctrlp) {
689 			ldap_control_free(*ctrlp);
690 			ctrlp++;
691 		}
692 		efree(*ctrls);
693 		*ctrls = NULL;
694 	}
695 }
696 /* }}} */
697 
698 /* {{{ PHP_INI_BEGIN
699  */
700 PHP_INI_BEGIN()
701 	STD_PHP_INI_ENTRY_EX("ldap.max_links", "-1", PHP_INI_SYSTEM, OnUpdateLong, max_links, zend_ldap_globals, ldap_globals, display_link_numbers)
702 PHP_INI_END()
703 /* }}} */
704 
705 /* {{{ PHP_GINIT_FUNCTION
706  */
PHP_GINIT_FUNCTIONnull707 static PHP_GINIT_FUNCTION(ldap)
708 {
709 #if defined(COMPILE_DL_LDAP) && defined(ZTS)
710 	ZEND_TSRMLS_CACHE_UPDATE();
711 #endif
712 	ldap_globals->num_links = 0;
713 }
714 /* }}} */
715 
716 /* {{{ PHP_MINIT_FUNCTION
717  */
PHP_MINIT_FUNCTIONnull718 PHP_MINIT_FUNCTION(ldap)
719 {
720 	REGISTER_INI_ENTRIES();
721 
722 	/* Constants to be used with deref-parameter in php_ldap_do_search() */
723 	REGISTER_LONG_CONSTANT("LDAP_DEREF_NEVER", LDAP_DEREF_NEVER, CONST_PERSISTENT | CONST_CS);
724 	REGISTER_LONG_CONSTANT("LDAP_DEREF_SEARCHING", LDAP_DEREF_SEARCHING, CONST_PERSISTENT | CONST_CS);
725 	REGISTER_LONG_CONSTANT("LDAP_DEREF_FINDING", LDAP_DEREF_FINDING, CONST_PERSISTENT | CONST_CS);
726 	REGISTER_LONG_CONSTANT("LDAP_DEREF_ALWAYS", LDAP_DEREF_ALWAYS, CONST_PERSISTENT | CONST_CS);
727 
728 	/* Constants to be used with ldap_modify_batch() */
729 	REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_ADD", LDAP_MODIFY_BATCH_ADD, CONST_PERSISTENT | CONST_CS);
730 	REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE", LDAP_MODIFY_BATCH_REMOVE, CONST_PERSISTENT | CONST_CS);
731 	REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REMOVE_ALL", LDAP_MODIFY_BATCH_REMOVE_ALL, CONST_PERSISTENT | CONST_CS);
732 	REGISTER_LONG_CONSTANT("LDAP_MODIFY_BATCH_REPLACE", LDAP_MODIFY_BATCH_REPLACE, CONST_PERSISTENT | CONST_CS);
733 	REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_ATTRIB", LDAP_MODIFY_BATCH_ATTRIB, CONST_PERSISTENT | CONST_CS);
734 	REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_MODTYPE", LDAP_MODIFY_BATCH_MODTYPE, CONST_PERSISTENT | CONST_CS);
735 	REGISTER_STRING_CONSTANT("LDAP_MODIFY_BATCH_VALUES", LDAP_MODIFY_BATCH_VALUES, CONST_PERSISTENT | CONST_CS);
736 
737 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP
738 	/* LDAP options */
739 	REGISTER_LONG_CONSTANT("LDAP_OPT_DEREF", LDAP_OPT_DEREF, CONST_PERSISTENT | CONST_CS);
740 	REGISTER_LONG_CONSTANT("LDAP_OPT_SIZELIMIT", LDAP_OPT_SIZELIMIT, CONST_PERSISTENT | CONST_CS);
741 	REGISTER_LONG_CONSTANT("LDAP_OPT_TIMELIMIT", LDAP_OPT_TIMELIMIT, CONST_PERSISTENT | CONST_CS);
742 #ifdef LDAP_OPT_NETWORK_TIMEOUT
743 	REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_OPT_NETWORK_TIMEOUT, CONST_PERSISTENT | CONST_CS);
744 #elif defined (LDAP_X_OPT_CONNECT_TIMEOUT)
745 	REGISTER_LONG_CONSTANT("LDAP_OPT_NETWORK_TIMEOUT", LDAP_X_OPT_CONNECT_TIMEOUT, CONST_PERSISTENT | CONST_CS);
746 #endif
747 #ifdef LDAP_OPT_TIMEOUT
748 	REGISTER_LONG_CONSTANT("LDAP_OPT_TIMEOUT", LDAP_OPT_TIMEOUT, CONST_PERSISTENT | CONST_CS);
749 #endif
750 	REGISTER_LONG_CONSTANT("LDAP_OPT_PROTOCOL_VERSION", LDAP_OPT_PROTOCOL_VERSION, CONST_PERSISTENT | CONST_CS);
751 	REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_NUMBER", LDAP_OPT_ERROR_NUMBER, CONST_PERSISTENT | CONST_CS);
752 	REGISTER_LONG_CONSTANT("LDAP_OPT_REFERRALS", LDAP_OPT_REFERRALS, CONST_PERSISTENT | CONST_CS);
753 #ifdef LDAP_OPT_RESTART
754 	REGISTER_LONG_CONSTANT("LDAP_OPT_RESTART", LDAP_OPT_RESTART, CONST_PERSISTENT | CONST_CS);
755 #endif
756 #ifdef LDAP_OPT_HOST_NAME
757 	REGISTER_LONG_CONSTANT("LDAP_OPT_HOST_NAME", LDAP_OPT_HOST_NAME, CONST_PERSISTENT | CONST_CS);
758 #endif
759 	REGISTER_LONG_CONSTANT("LDAP_OPT_ERROR_STRING", LDAP_OPT_ERROR_STRING, CONST_PERSISTENT | CONST_CS);
760 #ifdef LDAP_OPT_MATCHED_DN
761 	REGISTER_LONG_CONSTANT("LDAP_OPT_MATCHED_DN", LDAP_OPT_MATCHED_DN, CONST_PERSISTENT | CONST_CS);
762 #endif
763 	REGISTER_LONG_CONSTANT("LDAP_OPT_SERVER_CONTROLS", LDAP_OPT_SERVER_CONTROLS, CONST_PERSISTENT | CONST_CS);
764 	REGISTER_LONG_CONSTANT("LDAP_OPT_CLIENT_CONTROLS", LDAP_OPT_CLIENT_CONTROLS, CONST_PERSISTENT | CONST_CS);
765 #endif
766 #ifdef LDAP_OPT_DEBUG_LEVEL
767 	REGISTER_LONG_CONSTANT("LDAP_OPT_DEBUG_LEVEL", LDAP_OPT_DEBUG_LEVEL, CONST_PERSISTENT | CONST_CS);
768 #endif
769 
770 #ifdef LDAP_OPT_DIAGNOSTIC_MESSAGE
771 	REGISTER_LONG_CONSTANT("LDAP_OPT_DIAGNOSTIC_MESSAGE", LDAP_OPT_DIAGNOSTIC_MESSAGE, CONST_PERSISTENT | CONST_CS);
772 #endif
773 
774 #ifdef HAVE_LDAP_SASL
775 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_MECH", LDAP_OPT_X_SASL_MECH, CONST_PERSISTENT | CONST_CS);
776 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_REALM", LDAP_OPT_X_SASL_REALM, CONST_PERSISTENT | CONST_CS);
777 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHCID", LDAP_OPT_X_SASL_AUTHCID, CONST_PERSISTENT | CONST_CS);
778 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_AUTHZID", LDAP_OPT_X_SASL_AUTHZID, CONST_PERSISTENT | CONST_CS);
779 #endif
780 #ifdef LDAP_OPT_X_SASL_NOCANON
781 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_NOCANON", LDAP_OPT_X_SASL_NOCANON, CONST_PERSISTENT | CONST_CS);
782 #endif
783 #ifdef LDAP_OPT_X_SASL_USERNAME
784 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_SASL_USERNAME", LDAP_OPT_X_SASL_USERNAME, CONST_PERSISTENT | CONST_CS);
785 #endif
786 
787 #ifdef ORALDAP
788 	REGISTER_LONG_CONSTANT("GSLC_SSL_NO_AUTH", GSLC_SSL_NO_AUTH, CONST_PERSISTENT | CONST_CS);
789 	REGISTER_LONG_CONSTANT("GSLC_SSL_ONEWAY_AUTH", GSLC_SSL_ONEWAY_AUTH, CONST_PERSISTENT | CONST_CS);
790 	REGISTER_LONG_CONSTANT("GSLC_SSL_TWOWAY_AUTH", GSLC_SSL_TWOWAY_AUTH, CONST_PERSISTENT | CONST_CS);
791 #endif
792 
793 #if (LDAP_API_VERSION > 2000)
794 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_REQUIRE_CERT", LDAP_OPT_X_TLS_REQUIRE_CERT, CONST_PERSISTENT | CONST_CS);
795 
796 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_NEVER", LDAP_OPT_X_TLS_NEVER, CONST_PERSISTENT | CONST_CS);
797 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_HARD", LDAP_OPT_X_TLS_HARD, CONST_PERSISTENT | CONST_CS);
798 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_DEMAND", LDAP_OPT_X_TLS_DEMAND, CONST_PERSISTENT | CONST_CS);
799 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_ALLOW", LDAP_OPT_X_TLS_ALLOW, CONST_PERSISTENT | CONST_CS);
800 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_TRY", LDAP_OPT_X_TLS_TRY, CONST_PERSISTENT | CONST_CS);
801 
802 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CACERTDIR", LDAP_OPT_X_TLS_CACERTDIR, CONST_PERSISTENT | CONST_CS);
803 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CACERTFILE", LDAP_OPT_X_TLS_CACERTFILE, CONST_PERSISTENT | CONST_CS);
804 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CERTFILE", LDAP_OPT_X_TLS_CERTFILE, CONST_PERSISTENT | CONST_CS);
805 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CIPHER_SUITE", LDAP_OPT_X_TLS_CIPHER_SUITE, CONST_PERSISTENT | CONST_CS);
806 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_KEYFILE", LDAP_OPT_X_TLS_KEYFILE, CONST_PERSISTENT | CONST_CS);
807 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_RANDOM_FILE", LDAP_OPT_X_TLS_RANDOM_FILE, CONST_PERSISTENT | CONST_CS);
808 #endif
809 
810 #ifdef LDAP_OPT_X_TLS_CRLCHECK
811 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRLCHECK", LDAP_OPT_X_TLS_CRLCHECK, CONST_PERSISTENT | CONST_CS);
812 
813 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_NONE", LDAP_OPT_X_TLS_CRL_NONE, CONST_PERSISTENT | CONST_CS);
814 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_PEER", LDAP_OPT_X_TLS_CRL_PEER, CONST_PERSISTENT | CONST_CS);
815 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRL_ALL", LDAP_OPT_X_TLS_CRL_ALL, CONST_PERSISTENT | CONST_CS);
816 #endif
817 
818 #ifdef LDAP_OPT_X_TLS_DHFILE
819 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_DHFILE", LDAP_OPT_X_TLS_DHFILE, CONST_PERSISTENT | CONST_CS);
820 #endif
821 
822 #ifdef LDAP_OPT_X_TLS_CRLFILE
823 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_CRLFILE", LDAP_OPT_X_TLS_CRLFILE, CONST_PERSISTENT | CONST_CS);
824 #endif
825 
826 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
827 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_MIN", LDAP_OPT_X_TLS_PROTOCOL_MIN, CONST_PERSISTENT | CONST_CS);
828 
829 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_SSL2", LDAP_OPT_X_TLS_PROTOCOL_SSL2, CONST_PERSISTENT | CONST_CS);
830 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_SSL3", LDAP_OPT_X_TLS_PROTOCOL_SSL3, CONST_PERSISTENT | CONST_CS);
831 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_0", LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, CONST_PERSISTENT | CONST_CS);
832 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_1", LDAP_OPT_X_TLS_PROTOCOL_TLS1_1, CONST_PERSISTENT | CONST_CS);
833 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PROTOCOL_TLS1_2", LDAP_OPT_X_TLS_PROTOCOL_TLS1_2, CONST_PERSISTENT | CONST_CS);
834 #endif
835 
836 #ifdef LDAP_OPT_X_TLS_PACKAGE
837 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_TLS_PACKAGE", LDAP_OPT_X_TLS_PACKAGE, CONST_PERSISTENT | CONST_CS);
838 #endif
839 
840 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
841 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_IDLE", LDAP_OPT_X_KEEPALIVE_IDLE, CONST_PERSISTENT | CONST_CS);
842 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_PROBES", LDAP_OPT_X_KEEPALIVE_PROBES, CONST_PERSISTENT | CONST_CS);
843 	REGISTER_LONG_CONSTANT("LDAP_OPT_X_KEEPALIVE_INTERVAL", LDAP_OPT_X_KEEPALIVE_INTERVAL, CONST_PERSISTENT | CONST_CS);
844 #endif
845 
846 	REGISTER_LONG_CONSTANT("LDAP_ESCAPE_FILTER", PHP_LDAP_ESCAPE_FILTER, CONST_PERSISTENT | CONST_CS);
847 	REGISTER_LONG_CONSTANT("LDAP_ESCAPE_DN", PHP_LDAP_ESCAPE_DN, CONST_PERSISTENT | CONST_CS);
848 
849 #ifdef HAVE_LDAP_EXTENDED_OPERATION_S
850 	REGISTER_STRING_CONSTANT("LDAP_EXOP_START_TLS", LDAP_EXOP_START_TLS, CONST_PERSISTENT | CONST_CS);
851 	REGISTER_STRING_CONSTANT("LDAP_EXOP_MODIFY_PASSWD", LDAP_EXOP_MODIFY_PASSWD, CONST_PERSISTENT | CONST_CS);
852 	REGISTER_STRING_CONSTANT("LDAP_EXOP_REFRESH", LDAP_EXOP_REFRESH, CONST_PERSISTENT | CONST_CS);
853 	REGISTER_STRING_CONSTANT("LDAP_EXOP_WHO_AM_I", LDAP_EXOP_WHO_AM_I, CONST_PERSISTENT | CONST_CS);
854 	REGISTER_STRING_CONSTANT("LDAP_EXOP_TURN", LDAP_EXOP_TURN, CONST_PERSISTENT | CONST_CS);
855 #endif
856 
857 /* LDAP Controls */
858 /*	standard track controls */
859 #ifdef LDAP_CONTROL_MANAGEDSAIT
860 	/* RFC 3296 */
861 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_MANAGEDSAIT", LDAP_CONTROL_MANAGEDSAIT, CONST_PERSISTENT | CONST_CS);
862 #endif
863 #ifdef LDAP_CONTROL_PROXY_AUTHZ
864 	/* RFC 4370 */
865 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_PROXY_AUTHZ", LDAP_CONTROL_PROXY_AUTHZ, CONST_PERSISTENT | CONST_CS);
866 #endif
867 #ifdef LDAP_CONTROL_SUBENTRIES
868 	/* RFC 3672 */
869 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SUBENTRIES", LDAP_CONTROL_SUBENTRIES, CONST_PERSISTENT | CONST_CS);
870 #endif
871 #ifdef LDAP_CONTROL_VALUESRETURNFILTER
872 	/* RFC 3876 */
873 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_VALUESRETURNFILTER", LDAP_CONTROL_VALUESRETURNFILTER, CONST_PERSISTENT | CONST_CS);
874 #endif
875 #ifdef LDAP_CONTROL_ASSERT
876 	/* RFC 4528 */
877 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_ASSERT", LDAP_CONTROL_ASSERT, CONST_PERSISTENT | CONST_CS);
878 	/* RFC 4527 */
879 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_PRE_READ", LDAP_CONTROL_PRE_READ, CONST_PERSISTENT | CONST_CS);
880 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_POST_READ", LDAP_CONTROL_POST_READ, CONST_PERSISTENT | CONST_CS);
881 #endif
882 #ifdef LDAP_CONTROL_SORTREQUEST
883 	/* RFC 2891 */
884 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SORTREQUEST", LDAP_CONTROL_SORTREQUEST, CONST_PERSISTENT | CONST_CS);
885 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SORTRESPONSE", LDAP_CONTROL_SORTRESPONSE, CONST_PERSISTENT | CONST_CS);
886 #endif
887 /*	non-standard track controls */
888 #ifdef LDAP_CONTROL_PAGEDRESULTS
889 	/* RFC 2696 */
890 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_PAGEDRESULTS", LDAP_CONTROL_PAGEDRESULTS, CONST_PERSISTENT | CONST_CS);
891 #endif
892 #ifdef LDAP_CONTROL_AUTHZID_REQUEST
893 	/* RFC 3829 */
894 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_AUTHZID_REQUEST", LDAP_CONTROL_AUTHZID_REQUEST, CONST_PERSISTENT | CONST_CS);
895 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_AUTHZID_RESPONSE", LDAP_CONTROL_AUTHZID_RESPONSE, CONST_PERSISTENT | CONST_CS);
896 #endif
897 #ifdef LDAP_CONTROL_SYNC
898 	/* LDAP Content Synchronization Operation -- RFC 4533 */
899 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC", LDAP_CONTROL_SYNC, CONST_PERSISTENT | CONST_CS);
900 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC_STATE", LDAP_CONTROL_SYNC_STATE, CONST_PERSISTENT | CONST_CS);
901 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_SYNC_DONE", LDAP_CONTROL_SYNC_DONE, CONST_PERSISTENT | CONST_CS);
902 #endif
903 #ifdef LDAP_CONTROL_DONTUSECOPY
904 	/* LDAP Don't Use Copy Control (RFC 6171) */
905 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_DONTUSECOPY", LDAP_CONTROL_DONTUSECOPY, CONST_PERSISTENT | CONST_CS);
906 #endif
907 #ifdef LDAP_CONTROL_PASSWORDPOLICYREQUEST
908 	/* Password policy Controls */
909 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_PASSWORDPOLICYREQUEST", LDAP_CONTROL_PASSWORDPOLICYREQUEST, CONST_PERSISTENT | CONST_CS);
910 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_PASSWORDPOLICYRESPONSE", LDAP_CONTROL_PASSWORDPOLICYRESPONSE, CONST_PERSISTENT | CONST_CS);
911 #endif
912 #ifdef LDAP_CONTROL_X_INCREMENTAL_VALUES
913 	/* MS Active Directory controls */
914 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_INCREMENTAL_VALUES", LDAP_CONTROL_X_INCREMENTAL_VALUES, CONST_PERSISTENT | CONST_CS);
915 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_DOMAIN_SCOPE", LDAP_CONTROL_X_DOMAIN_SCOPE, CONST_PERSISTENT | CONST_CS);
916 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_PERMISSIVE_MODIFY", LDAP_CONTROL_X_PERMISSIVE_MODIFY, CONST_PERSISTENT | CONST_CS);
917 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_SEARCH_OPTIONS", LDAP_CONTROL_X_SEARCH_OPTIONS, CONST_PERSISTENT | CONST_CS);
918 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_TREE_DELETE", LDAP_CONTROL_X_TREE_DELETE, CONST_PERSISTENT | CONST_CS);
919 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_X_EXTENDED_DN", LDAP_CONTROL_X_EXTENDED_DN, CONST_PERSISTENT | CONST_CS);
920 #endif
921 #ifdef LDAP_CONTROL_VLVREQUEST
922 	/* LDAP VLV */
923 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_VLVREQUEST", LDAP_CONTROL_VLVREQUEST, CONST_PERSISTENT | CONST_CS);
924 	REGISTER_STRING_CONSTANT("LDAP_CONTROL_VLVRESPONSE", LDAP_CONTROL_VLVRESPONSE, CONST_PERSISTENT | CONST_CS);
925 #endif
926 
927 	le_link = zend_register_list_destructors_ex(_close_ldap_link, NULL, "ldap link", module_number);
928 	le_result = zend_register_list_destructors_ex(_free_ldap_result, NULL, "ldap result", module_number);
929 	le_result_entry = zend_register_list_destructors_ex(_free_ldap_result_entry, NULL, "ldap result entry", module_number);
930 
931 	ldap_module_entry.type = type;
932 
933 	return SUCCESS;
934 }
935 /* }}} */
936 
937 /* {{{ PHP_MSHUTDOWN_FUNCTION
938  */
PHP_MSHUTDOWN_FUNCTIONnull939 PHP_MSHUTDOWN_FUNCTION(ldap)
940 {
941 	UNREGISTER_INI_ENTRIES();
942 	return SUCCESS;
943 }
944 /* }}} */
945 
946 /* {{{ PHP_MINFO_FUNCTION
947  */
PHP_MINFO_FUNCTIONnull948 PHP_MINFO_FUNCTION(ldap)
949 {
950 	char tmp[32];
951 
952 	php_info_print_table_start();
953 	php_info_print_table_row(2, "LDAP Support", "enabled");
954 
955 	if (LDAPG(max_links) == -1) {
956 		snprintf(tmp, 31, ZEND_LONG_FMT "/unlimited", LDAPG(num_links));
957 	} else {
958 		snprintf(tmp, 31, ZEND_LONG_FMT "/" ZEND_LONG_FMT, LDAPG(num_links), LDAPG(max_links));
959 	}
960 	php_info_print_table_row(2, "Total Links", tmp);
961 
962 #ifdef LDAP_API_VERSION
963 	snprintf(tmp, 31, "%d", LDAP_API_VERSION);
964 	php_info_print_table_row(2, "API Version", tmp);
965 #endif
966 
967 #ifdef LDAP_VENDOR_NAME
968 	php_info_print_table_row(2, "Vendor Name", LDAP_VENDOR_NAME);
969 #endif
970 
971 #ifdef LDAP_VENDOR_VERSION
972 	snprintf(tmp, 31, "%d", LDAP_VENDOR_VERSION);
973 	php_info_print_table_row(2, "Vendor Version", tmp);
974 #endif
975 
976 #ifdef HAVE_LDAP_SASL
977 	php_info_print_table_row(2, "SASL Support", "Enabled");
978 #endif
979 
980 	php_info_print_table_end();
981 	DISPLAY_INI_ENTRIES();
982 }
983 /* }}} */
984 
985 /* {{{ proto resource ldap_connect([string host [, int port [, string wallet [, string wallet_passwd [, int authmode]]]]])
986    Connect to an LDAP server */
PHP_FUNCTIONnull987 PHP_FUNCTION(ldap_connect)
988 {
989 	char *host = NULL;
990 	size_t hostlen = 0;
991 	zend_long port = LDAP_PORT;
992 #ifdef HAVE_ORALDAP
993 	char *wallet = NULL, *walletpasswd = NULL;
994 	size_t walletlen = 0, walletpasswdlen = 0;
995 	zend_long authmode = GSLC_SSL_NO_AUTH;
996 	int ssl=0;
997 #endif
998 	ldap_linkdata *ld;
999 	LDAP *ldap = NULL;
1000 
1001 #ifdef HAVE_ORALDAP
1002 	if (ZEND_NUM_ARGS() == 3 || ZEND_NUM_ARGS() == 4) {
1003 		WRONG_PARAM_COUNT;
1004 	}
1005 
1006 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|slssl", &host, &hostlen, &port, &wallet, &walletlen, &walletpasswd, &walletpasswdlen, &authmode) != SUCCESS) {
1007 		RETURN_FALSE;
1008 	}
1009 
1010 	if (ZEND_NUM_ARGS() == 5) {
1011 		ssl = 1;
1012 	}
1013 #else
1014 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|sl", &host, &hostlen, &port) != SUCCESS) {
1015 		RETURN_FALSE;
1016 	}
1017 #endif
1018 
1019 	if (LDAPG(max_links) != -1 && LDAPG(num_links) >= LDAPG(max_links)) {
1020 		php_error_docref(NULL, E_WARNING, "Too many open links (" ZEND_LONG_FMT ")", LDAPG(num_links));
1021 		RETURN_FALSE;
1022 	}
1023 
1024 	ld = ecalloc(1, sizeof(ldap_linkdata));
1025 
1026 	{
1027 		int rc = LDAP_SUCCESS;
1028 		char	*url = host;
1029 		if (url && !ldap_is_ldap_url(url)) {
1030 			size_t urllen = hostlen + sizeof( "ldap://:65535" );
1031 
1032 			if (port <= 0 || port > 65535) {
1033 				efree(ld);
1034 				php_error_docref(NULL, E_WARNING, "invalid port number: " ZEND_LONG_FMT, port);
1035 				RETURN_FALSE;
1036 			}
1037 
1038 			url = emalloc(urllen);
1039 			snprintf( url, urllen, "ldap://%s:" ZEND_LONG_FMT, host, port );
1040 		}
1041 
1042 #ifdef LDAP_API_FEATURE_X_OPENLDAP
1043 		/* ldap_init() is deprecated, use ldap_initialize() instead.
1044 		 */
1045 		rc = ldap_initialize(&ldap, url);
1046 #else /* ! LDAP_API_FEATURE_X_OPENLDAP */
1047 		/* ldap_init does not support URLs.
1048 		 * We must try the original host and port information.
1049 		 */
1050 		ldap = ldap_init(host, port);
1051 		if (ldap == NULL) {
1052 			efree(ld);
1053 			php_error_docref(NULL, E_WARNING, "Could not create session handle");
1054 			RETURN_FALSE;
1055 		}
1056 #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */
1057 		if (url != host) {
1058 			efree(url);
1059 		}
1060 		if (rc != LDAP_SUCCESS) {
1061 			efree(ld);
1062 			php_error_docref(NULL, E_WARNING, "Could not create session handle: %s", ldap_err2string(rc));
1063 			RETURN_FALSE;
1064 		}
1065 	}
1066 
1067 	if (ldap == NULL) {
1068 		efree(ld);
1069 		RETURN_FALSE;
1070 	} else {
1071 #ifdef HAVE_ORALDAP
1072 		if (ssl) {
1073 			if (ldap_init_SSL(&ldap->ld_sb, wallet, walletpasswd, authmode)) {
1074 				efree(ld);
1075 				php_error_docref(NULL, E_WARNING, "SSL init failed");
1076 				RETURN_FALSE;
1077 			}
1078 		}
1079 #endif
1080 		LDAPG(num_links)++;
1081 		ld->link = ldap;
1082 		RETURN_RES(zend_register_resource(ld, le_link));
1083 	}
1084 
1085 }
1086 /* }}} */
1087 
1088 /* {{{ _get_lderrno
1089  */
_get_lderrno(LDAP *ldap)1090 static int _get_lderrno(LDAP *ldap)
1091 {
1092 #if LDAP_API_VERSION > 2000 || HAVE_ORALDAP
1093 	int lderr;
1094 
1095 	/* New versions of OpenLDAP do it this way */
1096 	ldap_get_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
1097 	return lderr;
1098 #else
1099 	return ldap->ld_errno;
1100 #endif
1101 }
1102 /* }}} */
1103 
1104 /* {{{ _set_lderrno
1105  */
_set_lderrno(LDAP *ldap, int lderr)1106 static void _set_lderrno(LDAP *ldap, int lderr)
1107 {
1108 #if LDAP_API_VERSION > 2000 || HAVE_ORALDAP
1109 	/* New versions of OpenLDAP do it this way */
1110 	ldap_set_option(ldap, LDAP_OPT_ERROR_NUMBER, &lderr);
1111 #else
1112 	ldap->ld_errno = lderr;
1113 #endif
1114 }
1115 /* }}} */
1116 
1117 /* {{{ proto bool ldap_bind(resource link [, string dn [, string password]])
1118    Bind to LDAP directory */
PHP_FUNCTIONnull1119 PHP_FUNCTION(ldap_bind)
1120 {
1121 	zval *link;
1122 	char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
1123 	size_t ldap_bind_dnlen, ldap_bind_pwlen;
1124 	ldap_linkdata *ld;
1125 	int rc;
1126 
1127 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|ss", &link, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen) != SUCCESS) {
1128 		RETURN_FALSE;
1129 	}
1130 
1131 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1132 		RETURN_FALSE;
1133 	}
1134 
1135 	if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
1136 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1137 		php_error_docref(NULL, E_WARNING, "DN contains a null byte");
1138 		RETURN_FALSE;
1139 	}
1140 
1141 	if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
1142 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1143 		php_error_docref(NULL, E_WARNING, "Password contains a null byte");
1144 		RETURN_FALSE;
1145 	}
1146 
1147 	{
1148 #ifdef LDAP_API_FEATURE_X_OPENLDAP
1149 		/* ldap_simple_bind_s() is deprecated, use ldap_sasl_bind_s() instead.
1150 		 */
1151 		struct berval   cred;
1152 
1153 		cred.bv_val = ldap_bind_pw;
1154 		cred.bv_len = ldap_bind_pw ? ldap_bind_pwlen : 0;
1155 		rc = ldap_sasl_bind_s(ld->link, ldap_bind_dn, LDAP_SASL_SIMPLE, &cred,
1156 				NULL, NULL,     /* no controls right now */
1157 				NULL);	  /* we don't care about the server's credentials */
1158 #else /* ! LDAP_API_FEATURE_X_OPENLDAP */
1159 		rc = ldap_simple_bind_s(ld->link, ldap_bind_dn, ldap_bind_pw);
1160 #endif /* ! LDAP_API_FEATURE_X_OPENLDAP */
1161 	}
1162 	if ( rc != LDAP_SUCCESS) {
1163 		php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
1164 		RETURN_FALSE;
1165 	} else {
1166 		RETURN_TRUE;
1167 	}
1168 }
1169 /* }}} */
1170 
1171 /* {{{ proto resource ldap_bind_ext(resource link [, string dn [, string password [, serverctrls]]])
1172    Bind to LDAP directory */
PHP_FUNCTIONnull1173 PHP_FUNCTION(ldap_bind_ext)
1174 {
1175 	zval *serverctrls = NULL;
1176 	zval *link;
1177 	char *ldap_bind_dn = NULL, *ldap_bind_pw = NULL;
1178 	size_t ldap_bind_dnlen, ldap_bind_pwlen;
1179 	ldap_linkdata *ld;
1180 	LDAPControl **lserverctrls = NULL;
1181 	LDAPMessage *ldap_res;
1182 	int rc;
1183 
1184 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|ssa", &link, &ldap_bind_dn, &ldap_bind_dnlen, &ldap_bind_pw, &ldap_bind_pwlen, &serverctrls) != SUCCESS) {
1185 		RETURN_FALSE;
1186 	}
1187 
1188 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1189 		RETURN_FALSE;
1190 	}
1191 
1192 	if (ldap_bind_dn != NULL && memchr(ldap_bind_dn, '\0', ldap_bind_dnlen) != NULL) {
1193 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1194 		php_error_docref(NULL, E_WARNING, "DN contains a null byte");
1195 		RETURN_FALSE;
1196 	}
1197 
1198 	if (ldap_bind_pw != NULL && memchr(ldap_bind_pw, '\0', ldap_bind_pwlen) != NULL) {
1199 		_set_lderrno(ld->link, LDAP_INVALID_CREDENTIALS);
1200 		php_error_docref(NULL, E_WARNING, "Password contains a null byte");
1201 		RETURN_FALSE;
1202 	}
1203 
1204 	if (serverctrls) {
1205 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
1206 		if (lserverctrls == NULL) {
1207 			RETVAL_FALSE;
1208 			goto cleanup;
1209 		}
1210 	}
1211 
1212 	{
1213 		/* ldap_simple_bind() is deprecated, use ldap_sasl_bind() instead */
1214 		struct berval   cred;
1215 		int msgid;
1216 
1217 		cred.bv_val = ldap_bind_pw;
1218 		cred.bv_len = ldap_bind_pw ? ldap_bind_pwlen : 0;
1219 		/* asynchronous call */
1220 		rc = ldap_sasl_bind(ld->link, ldap_bind_dn, LDAP_SASL_SIMPLE, &cred,
1221 				lserverctrls, NULL, &msgid);
1222 		if (rc != LDAP_SUCCESS ) {
1223 			php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s (%d)", ldap_err2string(rc), rc);
1224 			RETVAL_FALSE;
1225 			goto cleanup;
1226 		}
1227 
1228 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
1229 		if (rc == -1) {
1230 			php_error_docref(NULL, E_WARNING, "Bind operation failed");
1231 			RETVAL_FALSE;
1232 			goto cleanup;
1233 		}
1234 
1235 		/* return a PHP control object */
1236 		RETVAL_RES(zend_register_resource(ldap_res, le_result));
1237 	}
1238 
1239 cleanup:
1240 	if (lserverctrls) {
1241 		_php_ldap_controls_free(&lserverctrls);
1242 	}
1243 
1244 	return;
1245 }
1246 /* }}} */
1247 
1248 #ifdef HAVE_LDAP_SASL
1249 typedef struct {
1250 	char *mech;
1251 	char *realm;
1252 	char *authcid;
1253 	char *passwd;
1254 	char *authzid;
1255 } php_ldap_bictx;
1256 
1257 /* {{{ _php_sasl_setdefs
1258  */
_php_sasl_setdefs(LDAP *ld, char *sasl_mech, char *sasl_realm, char *sasl_authc_id, char *passwd, char *sasl_authz_id)1259 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)
1260 {
1261 	php_ldap_bictx *ctx;
1262 
1263 	ctx = ber_memalloc(sizeof(php_ldap_bictx));
1264 	ctx->mech    = (sasl_mech) ? ber_strdup(sasl_mech) : NULL;
1265 	ctx->realm   = (sasl_realm) ? ber_strdup(sasl_realm) : NULL;
1266 	ctx->authcid = (sasl_authc_id) ? ber_strdup(sasl_authc_id) : NULL;
1267 	ctx->passwd  = (passwd) ? ber_strdup(passwd) : NULL;
1268 	ctx->authzid = (sasl_authz_id) ? ber_strdup(sasl_authz_id) : NULL;
1269 
1270 	if (ctx->mech == NULL) {
1271 		ldap_get_option(ld, LDAP_OPT_X_SASL_MECH, &ctx->mech);
1272 	}
1273 	if (ctx->realm == NULL) {
1274 		ldap_get_option(ld, LDAP_OPT_X_SASL_REALM, &ctx->realm);
1275 	}
1276 	if (ctx->authcid == NULL) {
1277 		ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHCID, &ctx->authcid);
1278 	}
1279 	if (ctx->authzid == NULL) {
1280 		ldap_get_option(ld, LDAP_OPT_X_SASL_AUTHZID, &ctx->authzid);
1281 	}
1282 
1283 	return ctx;
1284 }
1285 /* }}} */
1286 
1287 /* {{{ _php_sasl_freedefs
1288  */
_php_sasl_freedefs(php_ldap_bictx *ctx)1289 static void _php_sasl_freedefs(php_ldap_bictx *ctx)
1290 {
1291 	if (ctx->mech) ber_memfree(ctx->mech);
1292 	if (ctx->realm) ber_memfree(ctx->realm);
1293 	if (ctx->authcid) ber_memfree(ctx->authcid);
1294 	if (ctx->passwd) ber_memfree(ctx->passwd);
1295 	if (ctx->authzid) ber_memfree(ctx->authzid);
1296 	ber_memfree(ctx);
1297 }
1298 /* }}} */
1299 
1300 /* {{{ _php_sasl_interact
1301    Internal interact function for SASL */
_php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)1302 static int _php_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)
1303 {
1304 	sasl_interact_t *interact = in;
1305 	const char *p;
1306 	php_ldap_bictx *ctx = defaults;
1307 
1308 	for (;interact->id != SASL_CB_LIST_END;interact++) {
1309 		p = NULL;
1310 		switch(interact->id) {
1311 			case SASL_CB_GETREALM:
1312 				p = ctx->realm;
1313 				break;
1314 			case SASL_CB_AUTHNAME:
1315 				p = ctx->authcid;
1316 				break;
1317 			case SASL_CB_USER:
1318 				p = ctx->authzid;
1319 				break;
1320 			case SASL_CB_PASS:
1321 				p = ctx->passwd;
1322 				break;
1323 		}
1324 		if (p) {
1325 			interact->result = p;
1326 			interact->len = strlen(interact->result);
1327 		}
1328 	}
1329 	return LDAP_SUCCESS;
1330 }
1331 /* }}} */
1332 
1333 /* {{{ proto bool ldap_sasl_bind(resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authc_id [, string sasl_authz_id [, string props]]]]]]])
1334    Bind to LDAP directory using SASL */
PHP_FUNCTIONnull1335 PHP_FUNCTION(ldap_sasl_bind)
1336 {
1337 	zval *link;
1338 	ldap_linkdata *ld;
1339 	char *binddn = NULL;
1340 	char *passwd = NULL;
1341 	char *sasl_mech = NULL;
1342 	char *sasl_realm = NULL;
1343 	char *sasl_authz_id = NULL;
1344 	char *sasl_authc_id = NULL;
1345 	char *props = NULL;
1346 	size_t rc, dn_len, passwd_len, mech_len, realm_len, authc_id_len, authz_id_len, props_len;
1347 	php_ldap_bictx *ctx;
1348 
1349 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|sssssss", &link, &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) {
1350 		RETURN_FALSE;
1351 	}
1352 
1353 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1354 		RETURN_FALSE;
1355 	}
1356 
1357 	ctx = _php_sasl_setdefs(ld->link, sasl_mech, sasl_realm, sasl_authc_id, passwd, sasl_authz_id);
1358 
1359 	if (props) {
1360 		ldap_set_option(ld->link, LDAP_OPT_X_SASL_SECPROPS, props);
1361 	}
1362 
1363 	rc = ldap_sasl_interactive_bind_s(ld->link, binddn, ctx->mech, NULL, NULL, LDAP_SASL_QUIET, _php_sasl_interact, ctx);
1364 	if (rc != LDAP_SUCCESS) {
1365 		php_error_docref(NULL, E_WARNING, "Unable to bind to server: %s", ldap_err2string(rc));
1366 		RETVAL_FALSE;
1367 	} else {
1368 		RETVAL_TRUE;
1369 	}
1370 	_php_sasl_freedefs(ctx);
1371 }
1372 /* }}} */
1373 #endif /* HAVE_LDAP_SASL */
1374 
1375 /* {{{ proto bool ldap_unbind(resource link)
1376    Unbind from LDAP directory */
PHP_FUNCTIONnull1377 PHP_FUNCTION(ldap_unbind)
1378 {
1379 	zval *link;
1380 	ldap_linkdata *ld;
1381 
1382 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
1383 		RETURN_FALSE;
1384 	}
1385 
1386 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1387 		RETURN_FALSE;
1388 	}
1389 
1390 	zend_list_close(Z_RES_P(link));
1391 	RETURN_TRUE;
1392 }
1393 /* }}} */
1394 
1395 /* {{{ php_set_opts
1396  */
php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref)1397 static void php_set_opts(LDAP *ldap, int sizelimit, int timelimit, int deref, int *old_sizelimit, int *old_timelimit, int *old_deref)
1398 {
1399 	/* sizelimit */
1400 	if (sizelimit > -1) {
1401 #if (LDAP_API_VERSION >= 2004) || HAVE_ORALDAP
1402 		ldap_get_option(ldap, LDAP_OPT_SIZELIMIT, old_sizelimit);
1403 		ldap_set_option(ldap, LDAP_OPT_SIZELIMIT, &sizelimit);
1404 #else
1405 		*old_sizelimit = ldap->ld_sizelimit;
1406 		ldap->ld_sizelimit = sizelimit;
1407 #endif
1408 	}
1409 
1410 	/* timelimit */
1411 	if (timelimit > -1) {
1412 #if (LDAP_API_VERSION >= 2004) || HAVE_ORALDAP
1413 		ldap_get_option(ldap, LDAP_OPT_TIMELIMIT, old_timelimit);
1414 		ldap_set_option(ldap, LDAP_OPT_TIMELIMIT, &timelimit);
1415 #else
1416 		*old_timelimit = ldap->ld_timelimit;
1417 		ldap->ld_timelimit = timelimit;
1418 #endif
1419 	}
1420 
1421 	/* deref */
1422 	if (deref > -1) {
1423 #if (LDAP_API_VERSION >= 2004) || HAVE_ORALDAP
1424 		ldap_get_option(ldap, LDAP_OPT_DEREF, old_deref);
1425 		ldap_set_option(ldap, LDAP_OPT_DEREF, &deref);
1426 #else
1427 		*old_deref = ldap->ld_deref;
1428 		ldap->ld_deref = deref;
1429 #endif
1430 	}
1431 }
1432 /* }}} */
1433 
1434 /* {{{ php_ldap_do_search
1435  */
php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope)1436 static void php_ldap_do_search(INTERNAL_FUNCTION_PARAMETERS, int scope)
1437 {
1438 	zval *link, *base_dn, *filter, *attrs = NULL, *attr, *serverctrls = NULL;
1439 	zend_long attrsonly, sizelimit, timelimit, deref;
1440 	zend_string *ldap_filter = NULL, *ldap_base_dn = NULL;
1441 	char **ldap_attrs = NULL;
1442 	ldap_linkdata *ld = NULL;
1443 	LDAPMessage *ldap_res;
1444 	LDAPControl **lserverctrls = NULL;
1445 	int ldap_attrsonly = 0, ldap_sizelimit = -1, ldap_timelimit = -1, ldap_deref = -1;
1446 	int old_ldap_sizelimit = -1, old_ldap_timelimit = -1, old_ldap_deref = -1;
1447 	int num_attribs = 0, ret = 1, i, errno, argcount = ZEND_NUM_ARGS();
1448 
1449 	if (zend_parse_parameters(argcount, "zzz|a/lllla/", &link, &base_dn, &filter, &attrs, &attrsonly,
1450 		&sizelimit, &timelimit, &deref, &serverctrls) == FAILURE) {
1451 		return;
1452 	}
1453 
1454 	/* Reverse -> fall through */
1455 	switch (argcount) {
1456 		case 9:
1457 		case 8:
1458 			ldap_deref = deref;
1459 		case 7:
1460 			ldap_timelimit = timelimit;
1461 		case 6:
1462 			ldap_sizelimit = sizelimit;
1463 		case 5:
1464 			ldap_attrsonly = attrsonly;
1465 		case 4:
1466 			num_attribs = zend_hash_num_elements(Z_ARRVAL_P(attrs));
1467 			ldap_attrs = safe_emalloc((num_attribs+1), sizeof(char *), 0);
1468 
1469 			for (i = 0; i<num_attribs; i++) {
1470 				if ((attr = zend_hash_index_find(Z_ARRVAL_P(attrs), i)) == NULL) {
1471 					php_error_docref(NULL, E_WARNING, "Array initialization wrong");
1472 					ret = 0;
1473 					goto cleanup;
1474 				}
1475 
1476 				convert_to_string(attr);
1477 				if (EG(exception)) {
1478 					ret = 0;
1479 					goto cleanup;
1480 				}
1481 				ldap_attrs[i] = Z_STRVAL_P(attr);
1482 			}
1483 			ldap_attrs[num_attribs] = NULL;
1484 		default:
1485 			break;
1486 	}
1487 
1488 	/* parallel search? */
1489 	if (Z_TYPE_P(link) == IS_ARRAY) {
1490 		int i, nlinks, nbases, nfilters, *rcs;
1491 		ldap_linkdata **lds;
1492 		zval *entry, resource;
1493 
1494 		nlinks = zend_hash_num_elements(Z_ARRVAL_P(link));
1495 		if (nlinks == 0) {
1496 			php_error_docref(NULL, E_WARNING, "No links in link array");
1497 			ret = 0;
1498 			goto cleanup;
1499 		}
1500 
1501 		if (Z_TYPE_P(base_dn) == IS_ARRAY) {
1502 			nbases = zend_hash_num_elements(Z_ARRVAL_P(base_dn));
1503 			if (nbases != nlinks) {
1504 				php_error_docref(NULL, E_WARNING, "Base must either be a string, or an array with the same number of elements as the links array");
1505 				ret = 0;
1506 				goto cleanup;
1507 			}
1508 			zend_hash_internal_pointer_reset(Z_ARRVAL_P(base_dn));
1509 		} else {
1510 			nbases = 0; /* this means string, not array */
1511 			ldap_base_dn = zval_get_string(base_dn);
1512 			if (EG(exception)) {
1513 				ret = 0;
1514 				goto cleanup;
1515 			}
1516 		}
1517 
1518 		if (Z_TYPE_P(filter) == IS_ARRAY) {
1519 			nfilters = zend_hash_num_elements(Z_ARRVAL_P(filter));
1520 			if (nfilters != nlinks) {
1521 				php_error_docref(NULL, E_WARNING, "Filter must either be a string, or an array with the same number of elements as the links array");
1522 				ret = 0;
1523 				goto cleanup;
1524 			}
1525 			zend_hash_internal_pointer_reset(Z_ARRVAL_P(filter));
1526 		} else {
1527 			nfilters = 0; /* this means string, not array */
1528 			ldap_filter = zval_get_string(filter);
1529 			if (EG(exception)) {
1530 				ret = 0;
1531 				goto cleanup;
1532 			}
1533 		}
1534 
1535 		lds = safe_emalloc(nlinks, sizeof(ldap_linkdata), 0);
1536 		rcs = safe_emalloc(nlinks, sizeof(*rcs), 0);
1537 
1538 		zend_hash_internal_pointer_reset(Z_ARRVAL_P(link));
1539 		for (i=0; i<nlinks; i++) {
1540 			entry = zend_hash_get_current_data(Z_ARRVAL_P(link));
1541 
1542 			ld = (ldap_linkdata *) zend_fetch_resource_ex(entry, "ldap link", le_link);
1543 			if (ld == NULL) {
1544 				ret = 0;
1545 				goto cleanup_parallel;
1546 			}
1547 			if (nbases != 0) { /* base_dn an array? */
1548 				entry = zend_hash_get_current_data(Z_ARRVAL_P(base_dn));
1549 				zend_hash_move_forward(Z_ARRVAL_P(base_dn));
1550 				ldap_base_dn = zval_get_string(entry);
1551 				if (EG(exception)) {
1552 					ret = 0;
1553 					goto cleanup_parallel;
1554 				}
1555 			}
1556 			if (nfilters != 0) { /* filter an array? */
1557 				entry = zend_hash_get_current_data(Z_ARRVAL_P(filter));
1558 				zend_hash_move_forward(Z_ARRVAL_P(filter));
1559 				ldap_filter = zval_get_string(entry);
1560 				if (EG(exception)) {
1561 					ret = 0;
1562 					goto cleanup_parallel;
1563 				}
1564 			}
1565 
1566 			if (argcount > 8) {
1567 				/* We have to parse controls again for each link as they use it */
1568 				_php_ldap_controls_free(&lserverctrls);
1569 				lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
1570 				if (lserverctrls == NULL) {
1571 					rcs[i] = -1;
1572 					continue;
1573 				}
1574 			}
1575 
1576 			php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
1577 
1578 			/* Run the actual search */
1579 			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]);
1580 			lds[i] = ld;
1581 			zend_hash_move_forward(Z_ARRVAL_P(link));
1582 		}
1583 
1584 		array_init(return_value);
1585 
1586 		/* Collect results from the searches */
1587 		for (i=0; i<nlinks; i++) {
1588 			if (rcs[i] != -1) {
1589 				rcs[i] = ldap_result(lds[i]->link, LDAP_RES_ANY, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
1590 			}
1591 			if (rcs[i] != -1) {
1592 				ZVAL_RES(&resource, zend_register_resource(ldap_res, le_result));
1593 				add_next_index_zval(return_value, &resource);
1594 			} else {
1595 				add_next_index_bool(return_value, 0);
1596 			}
1597 		}
1598 
1599 cleanup_parallel:
1600 		efree(lds);
1601 		efree(rcs);
1602 	} else {
1603 		ldap_filter = zval_get_string(filter);
1604 		if (EG(exception)) {
1605 			ret = 0;
1606 			goto cleanup;
1607 		}
1608 
1609 		ldap_base_dn = zval_get_string(base_dn);
1610 		if (EG(exception)) {
1611 			ret = 0;
1612 			goto cleanup;
1613 		}
1614 
1615 		ld = (ldap_linkdata *) zend_fetch_resource_ex(link, "ldap link", le_link);
1616 		if (ld == NULL) {
1617 			ret = 0;
1618 			goto cleanup;
1619 		}
1620 
1621 		if (argcount > 8) {
1622 			lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
1623 			if (lserverctrls == NULL) {
1624 				ret = 0;
1625 				goto cleanup;
1626 			}
1627 		}
1628 
1629 		php_set_opts(ld->link, ldap_sizelimit, ldap_timelimit, ldap_deref, &old_ldap_sizelimit, &old_ldap_timelimit, &old_ldap_deref);
1630 
1631 		/* Run the actual search */
1632 		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);
1633 
1634 		if (errno != LDAP_SUCCESS
1635 			&& errno != LDAP_SIZELIMIT_EXCEEDED
1636 #ifdef LDAP_ADMINLIMIT_EXCEEDED
1637 			&& errno != LDAP_ADMINLIMIT_EXCEEDED
1638 #endif
1639 #ifdef LDAP_REFERRAL
1640 			&& errno != LDAP_REFERRAL
1641 #endif
1642 		) {
1643 			php_error_docref(NULL, E_WARNING, "Search: %s", ldap_err2string(errno));
1644 			ret = 0;
1645 		} else {
1646 			if (errno == LDAP_SIZELIMIT_EXCEEDED) {
1647 				php_error_docref(NULL, E_WARNING, "Partial search results returned: Sizelimit exceeded");
1648 			}
1649 #ifdef LDAP_ADMINLIMIT_EXCEEDED
1650 			else if (errno == LDAP_ADMINLIMIT_EXCEEDED) {
1651 				php_error_docref(NULL, E_WARNING, "Partial search results returned: Adminlimit exceeded");
1652 			}
1653 #endif
1654 
1655 			RETVAL_RES(zend_register_resource(ldap_res, le_result));
1656 		}
1657 	}
1658 
1659 cleanup:
1660 	if (ld) {
1661 		/* Restoring previous options */
1662 		php_set_opts(ld->link, old_ldap_sizelimit, old_ldap_timelimit, old_ldap_deref, &ldap_sizelimit, &ldap_timelimit, &ldap_deref);
1663 	}
1664 	if (ldap_filter) {
1665 		zend_string_release(ldap_filter);
1666 	}
1667 	if (ldap_base_dn) {
1668 		zend_string_release(ldap_base_dn);
1669 	}
1670 	if (ldap_attrs != NULL) {
1671 		efree(ldap_attrs);
1672 	}
1673 	if (!ret) {
1674 		RETVAL_BOOL(ret);
1675 	}
1676 	if (lserverctrls) {
1677 		_php_ldap_controls_free(&lserverctrls);
1678 	}
1679 }
1680 /* }}} */
1681 
1682 /* {{{ proto resource ldap_read(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref [, array servercontrols]]]]]])
1683    Read an entry */
PHP_FUNCTIONnull1684 PHP_FUNCTION(ldap_read)
1685 {
1686 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_BASE);
1687 }
1688 /* }}} */
1689 
1690 /* {{{ proto resource ldap_list(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref [, array servercontrols]]]]]])
1691    Single-level search */
PHP_FUNCTIONnull1692 PHP_FUNCTION(ldap_list)
1693 {
1694 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_ONELEVEL);
1695 }
1696 /* }}} */
1697 
1698 /* {{{ proto resource ldap_search(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref [, array servercontrols]]]]]])
1699    Search LDAP tree under base_dn */
PHP_FUNCTIONnull1700 PHP_FUNCTION(ldap_search)
1701 {
1702 	php_ldap_do_search(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_SCOPE_SUBTREE);
1703 }
1704 /* }}} */
1705 
1706 /* {{{ proto bool ldap_free_result(resource result)
1707    Free result memory */
PHP_FUNCTIONnull1708 PHP_FUNCTION(ldap_free_result)
1709 {
1710 	zval *result;
1711 	LDAPMessage *ldap_result;
1712 
1713 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &result) != SUCCESS) {
1714 		return;
1715 	}
1716 
1717 	if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
1718 		RETURN_FALSE;
1719 	}
1720 
1721 	zend_list_close(Z_RES_P(result));  /* Delete list entry */
1722 	RETVAL_TRUE;
1723 }
1724 /* }}} */
1725 
1726 /* {{{ proto int ldap_count_entries(resource link, resource result)
1727    Count the number of entries in a search result */
PHP_FUNCTIONnull1728 PHP_FUNCTION(ldap_count_entries)
1729 {
1730 	zval *link, *result;
1731 	ldap_linkdata *ld;
1732 	LDAPMessage *ldap_result;
1733 
1734 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
1735 		return;
1736 	}
1737 
1738 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1739 		RETURN_FALSE;
1740 	}
1741 
1742 	if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
1743 		RETURN_FALSE;
1744 	}
1745 
1746 	RETURN_LONG(ldap_count_entries(ld->link, ldap_result));
1747 }
1748 /* }}} */
1749 
1750 /* {{{ proto resource ldap_first_entry(resource link, resource result)
1751    Return first result id */
PHP_FUNCTIONnull1752 PHP_FUNCTION(ldap_first_entry)
1753 {
1754 	zval *link, *result;
1755 	ldap_linkdata *ld;
1756 	ldap_resultentry *resultentry;
1757 	LDAPMessage *ldap_result, *entry;
1758 
1759 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
1760 		return;
1761 	}
1762 
1763 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1764 		RETURN_FALSE;
1765 	}
1766 
1767 	if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
1768 		RETURN_FALSE;
1769 	}
1770 
1771 	if ((entry = ldap_first_entry(ld->link, ldap_result)) == NULL) {
1772 		RETVAL_FALSE;
1773 	} else {
1774 		resultentry = emalloc(sizeof(ldap_resultentry));
1775 		RETVAL_RES(zend_register_resource(resultentry, le_result_entry));
1776 		ZVAL_COPY(&resultentry->res, result);
1777 		resultentry->data = entry;
1778 		resultentry->ber = NULL;
1779 	}
1780 }
1781 /* }}} */
1782 
1783 /* {{{ proto resource ldap_next_entry(resource link, resource result_entry)
1784    Get next result entry */
PHP_FUNCTIONnull1785 PHP_FUNCTION(ldap_next_entry)
1786 {
1787 	zval *link, *result_entry;
1788 	ldap_linkdata *ld;
1789 	ldap_resultentry *resultentry, *resultentry_next;
1790 	LDAPMessage *entry_next;
1791 
1792 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
1793 		return;
1794 	}
1795 
1796 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1797 		RETURN_FALSE;
1798 	}
1799 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1800 		RETURN_FALSE;
1801 	}
1802 
1803 	if ((entry_next = ldap_next_entry(ld->link, resultentry->data)) == NULL) {
1804 		RETVAL_FALSE;
1805 	} else {
1806 		resultentry_next = emalloc(sizeof(ldap_resultentry));
1807 		RETVAL_RES(zend_register_resource(resultentry_next, le_result_entry));
1808 		ZVAL_COPY(&resultentry_next->res, &resultentry->res);
1809 		resultentry_next->data = entry_next;
1810 		resultentry_next->ber = NULL;
1811 	}
1812 }
1813 /* }}} */
1814 
1815 /* {{{ proto array ldap_get_entries(resource link, resource result)
1816    Get all result entries */
PHP_FUNCTIONnull1817 PHP_FUNCTION(ldap_get_entries)
1818 {
1819 	zval *link, *result;
1820 	LDAPMessage *ldap_result, *ldap_result_entry;
1821 	zval tmp1, tmp2;
1822 	ldap_linkdata *ld;
1823 	LDAP *ldap;
1824 	int num_entries, num_attrib, num_values, i;
1825 	BerElement *ber;
1826 	char *attribute;
1827 	size_t attr_len;
1828 	struct berval **ldap_value;
1829 	char *dn;
1830 
1831 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result) != SUCCESS) {
1832 		return;
1833 	}
1834 
1835 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1836 		RETURN_FALSE;
1837 	}
1838 	if ((ldap_result = (LDAPMessage *)zend_fetch_resource(Z_RES_P(result), "ldap result", le_result)) == NULL) {
1839 		RETURN_FALSE;
1840 	}
1841 
1842 	ldap = ld->link;
1843 	num_entries = ldap_count_entries(ldap, ldap_result);
1844 
1845 	array_init(return_value);
1846 	add_assoc_long(return_value, "count", num_entries);
1847 
1848 	if (num_entries == 0) {
1849 		return;
1850 	}
1851 
1852 	ldap_result_entry = ldap_first_entry(ldap, ldap_result);
1853 	if (ldap_result_entry == NULL) {
1854 		zend_array_destroy(Z_ARR_P(return_value));
1855 		RETURN_FALSE;
1856 	}
1857 
1858 	num_entries = 0;
1859 	while (ldap_result_entry != NULL) {
1860 		array_init(&tmp1);
1861 
1862 		num_attrib = 0;
1863 		attribute = ldap_first_attribute(ldap, ldap_result_entry, &ber);
1864 
1865 		while (attribute != NULL) {
1866 			ldap_value = ldap_get_values_len(ldap, ldap_result_entry, attribute);
1867 			num_values = ldap_count_values_len(ldap_value);
1868 
1869 			array_init(&tmp2);
1870 			add_assoc_long(&tmp2, "count", num_values);
1871 			for (i = 0; i < num_values; i++) {
1872 				add_index_stringl(&tmp2, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
1873 			}
1874 			ldap_value_free_len(ldap_value);
1875 
1876 			attr_len = strlen(attribute);
1877 			zend_hash_str_update(Z_ARRVAL(tmp1), php_strtolower(attribute, attr_len), attr_len, &tmp2);
1878 			add_index_string(&tmp1, num_attrib, attribute);
1879 
1880 			num_attrib++;
1881 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1882 			ldap_memfree(attribute);
1883 #endif
1884 			attribute = ldap_next_attribute(ldap, ldap_result_entry, ber);
1885 		}
1886 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1887 		if (ber != NULL) {
1888 			ber_free(ber, 0);
1889 		}
1890 #endif
1891 
1892 		add_assoc_long(&tmp1, "count", num_attrib);
1893 		dn = ldap_get_dn(ldap, ldap_result_entry);
1894 		if (dn) {
1895 			add_assoc_string(&tmp1, "dn", dn);
1896 		} else {
1897 			add_assoc_null(&tmp1, "dn");
1898 		}
1899 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1900 		ldap_memfree(dn);
1901 #else
1902 		free(dn);
1903 #endif
1904 
1905 		zend_hash_index_update(Z_ARRVAL_P(return_value), num_entries, &tmp1);
1906 
1907 		num_entries++;
1908 		ldap_result_entry = ldap_next_entry(ldap, ldap_result_entry);
1909 	}
1910 
1911 	add_assoc_long(return_value, "count", num_entries);
1912 
1913 }
1914 /* }}} */
1915 
1916 /* {{{ proto string ldap_first_attribute(resource link, resource result_entry)
1917    Return first attribute */
PHP_FUNCTIONnull1918 PHP_FUNCTION(ldap_first_attribute)
1919 {
1920 	zval *link, *result_entry;
1921 	ldap_linkdata *ld;
1922 	ldap_resultentry *resultentry;
1923 	char *attribute;
1924 	zend_long dummy_ber;
1925 
1926 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1927 		return;
1928 	}
1929 
1930 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1931 		RETURN_FALSE;
1932 	}
1933 
1934 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1935 		RETURN_FALSE;
1936 	}
1937 
1938 	if ((attribute = ldap_first_attribute(ld->link, resultentry->data, &resultentry->ber)) == NULL) {
1939 		RETURN_FALSE;
1940 	} else {
1941 		RETVAL_STRING(attribute);
1942 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1943 		ldap_memfree(attribute);
1944 #endif
1945 	}
1946 }
1947 /* }}} */
1948 
1949 /* {{{ proto string ldap_next_attribute(resource link, resource result_entry)
1950    Get the next attribute in result */
PHP_FUNCTIONnull1951 PHP_FUNCTION(ldap_next_attribute)
1952 {
1953 	zval *link, *result_entry;
1954 	ldap_linkdata *ld;
1955 	ldap_resultentry *resultentry;
1956 	char *attribute;
1957 	zend_long dummy_ber;
1958 
1959 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|l", &link, &result_entry, &dummy_ber) != SUCCESS) {
1960 		return;
1961 	}
1962 
1963 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
1964 		RETURN_FALSE;
1965 	}
1966 
1967 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
1968 		RETURN_FALSE;
1969 	}
1970 
1971 	if (resultentry->ber == NULL) {
1972 		php_error_docref(NULL, E_WARNING, "called before calling ldap_first_attribute() or no attributes found in result entry");
1973 		RETURN_FALSE;
1974 	}
1975 
1976 	if ((attribute = ldap_next_attribute(ld->link, resultentry->data, resultentry->ber)) == NULL) {
1977 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1978 		if (resultentry->ber != NULL) {
1979 			ber_free(resultentry->ber, 0);
1980 			resultentry->ber = NULL;
1981 		}
1982 #endif
1983 		RETURN_FALSE;
1984 	} else {
1985 		RETVAL_STRING(attribute);
1986 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
1987 		ldap_memfree(attribute);
1988 #endif
1989 	}
1990 }
1991 /* }}} */
1992 
1993 /* {{{ proto array ldap_get_attributes(resource link, resource result_entry)
1994    Get attributes from a search result entry */
PHP_FUNCTIONnull1995 PHP_FUNCTION(ldap_get_attributes)
1996 {
1997 	zval *link, *result_entry;
1998 	zval tmp;
1999 	ldap_linkdata *ld;
2000 	ldap_resultentry *resultentry;
2001 	char *attribute;
2002 	struct berval **ldap_value;
2003 	int i, num_values, num_attrib;
2004 	BerElement *ber;
2005 
2006 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
2007 		return;
2008 	}
2009 
2010 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2011 		RETURN_FALSE;
2012 	}
2013 
2014 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
2015 		RETURN_FALSE;
2016 	}
2017 
2018 	array_init(return_value);
2019 	num_attrib = 0;
2020 
2021 	attribute = ldap_first_attribute(ld->link, resultentry->data, &ber);
2022 	while (attribute != NULL) {
2023 		ldap_value = ldap_get_values_len(ld->link, resultentry->data, attribute);
2024 		num_values = ldap_count_values_len(ldap_value);
2025 
2026 		array_init(&tmp);
2027 		add_assoc_long(&tmp, "count", num_values);
2028 		for (i = 0; i < num_values; i++) {
2029 			add_index_stringl(&tmp, i, ldap_value[i]->bv_val, ldap_value[i]->bv_len);
2030 		}
2031 		ldap_value_free_len(ldap_value);
2032 
2033 		zend_hash_str_update(Z_ARRVAL_P(return_value), attribute, strlen(attribute), &tmp);
2034 		add_index_string(return_value, num_attrib, attribute);
2035 
2036 		num_attrib++;
2037 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
2038 		ldap_memfree(attribute);
2039 #endif
2040 		attribute = ldap_next_attribute(ld->link, resultentry->data, ber);
2041 	}
2042 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
2043 	if (ber != NULL) {
2044 		ber_free(ber, 0);
2045 	}
2046 #endif
2047 
2048 	add_assoc_long(return_value, "count", num_attrib);
2049 }
2050 /* }}} */
2051 
2052 /* {{{ proto array ldap_get_values_len(resource link, resource result_entry, string attribute)
2053    Get all values with lengths from a result entry */
PHP_FUNCTIONnull2054 PHP_FUNCTION(ldap_get_values_len)
2055 {
2056 	zval *link, *result_entry;
2057 	ldap_linkdata *ld;
2058 	ldap_resultentry *resultentry;
2059 	char *attr;
2060 	struct berval **ldap_value_len;
2061 	int i, num_values;
2062 	size_t attr_len;
2063 
2064 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result_entry, &attr, &attr_len) != SUCCESS) {
2065 		return;
2066 	}
2067 
2068 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2069 		RETURN_FALSE;
2070 	}
2071 
2072 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
2073 		RETURN_FALSE;
2074 	}
2075 
2076 	if ((ldap_value_len = ldap_get_values_len(ld->link, resultentry->data, attr)) == NULL) {
2077 		php_error_docref(NULL, E_WARNING, "Cannot get the value(s) of attribute %s", ldap_err2string(_get_lderrno(ld->link)));
2078 		RETURN_FALSE;
2079 	}
2080 
2081 	num_values = ldap_count_values_len(ldap_value_len);
2082 	array_init(return_value);
2083 
2084 	for (i=0; i<num_values; i++) {
2085 		add_next_index_stringl(return_value, ldap_value_len[i]->bv_val, ldap_value_len[i]->bv_len);
2086 	}
2087 
2088 	add_assoc_long(return_value, "count", num_values);
2089 	ldap_value_free_len(ldap_value_len);
2090 
2091 }
2092 /* }}} */
2093 
2094 /* {{{ proto string ldap_get_dn(resource link, resource result_entry)
2095    Get the DN of a result entry */
PHP_FUNCTIONnull2096 PHP_FUNCTION(ldap_get_dn)
2097 {
2098 	zval *link, *result_entry;
2099 	ldap_linkdata *ld;
2100 	ldap_resultentry *resultentry;
2101 	char *text;
2102 
2103 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr", &link, &result_entry) != SUCCESS) {
2104 		return;
2105 	}
2106 
2107 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2108 		RETURN_FALSE;
2109 	}
2110 
2111 	if ((resultentry = (ldap_resultentry *)zend_fetch_resource(Z_RES_P(result_entry), "ldap result entry", le_result_entry)) == NULL) {
2112 		RETURN_FALSE;
2113 	}
2114 
2115 	text = ldap_get_dn(ld->link, resultentry->data);
2116 	if (text != NULL) {
2117 		RETVAL_STRING(text);
2118 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
2119 		ldap_memfree(text);
2120 #else
2121 		free(text);
2122 #endif
2123 	} else {
2124 		RETURN_FALSE;
2125 	}
2126 }
2127 /* }}} */
2128 
2129 /* {{{ proto array ldap_explode_dn(string dn, int with_attrib)
2130    Splits DN into its component parts */
PHP_FUNCTIONnull2131 PHP_FUNCTION(ldap_explode_dn)
2132 {
2133 	zend_long with_attrib;
2134 	char *dn, **ldap_value;
2135 	int i, count;
2136 	size_t dn_len;
2137 
2138 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &dn, &dn_len, &with_attrib) != SUCCESS) {
2139 		return;
2140 	}
2141 
2142 	if (!(ldap_value = ldap_explode_dn(dn, with_attrib))) {
2143 		/* Invalid parameters were passed to ldap_explode_dn */
2144 		RETURN_FALSE;
2145 	}
2146 
2147 	i=0;
2148 	while (ldap_value[i] != NULL) i++;
2149 	count = i;
2150 
2151 	array_init(return_value);
2152 
2153 	add_assoc_long(return_value, "count", count);
2154 	for (i = 0; i<count; i++) {
2155 		add_index_string(return_value, i, ldap_value[i]);
2156 	}
2157 
2158 	ldap_memvfree((void **)ldap_value);
2159 }
2160 /* }}} */
2161 
2162 /* {{{ proto string ldap_dn2ufn(string dn)
2163    Convert DN to User Friendly Naming format */
PHP_FUNCTIONnull2164 PHP_FUNCTION(ldap_dn2ufn)
2165 {
2166 	char *dn, *ufn;
2167 	size_t dn_len;
2168 
2169 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dn, &dn_len) != SUCCESS) {
2170 		return;
2171 	}
2172 
2173 	ufn = ldap_dn2ufn(dn);
2174 
2175 	if (ufn != NULL) {
2176 		RETVAL_STRING(ufn);
2177 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP || WINDOWS
2178 		ldap_memfree(ufn);
2179 #endif
2180 	} else {
2181 		RETURN_FALSE;
2182 	}
2183 }
2184 /* }}} */
2185 
2186 
2187 /* added to fix use of ldap_modify_add for doing an ldap_add, gerrit thomson. */
2188 #define PHP_LD_FULL_ADD 0xff
2189 /* {{{ php_ldap_do_modify
2190  */
php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper, int ext)2191 static void php_ldap_do_modify(INTERNAL_FUNCTION_PARAMETERS, int oper, int ext)
2192 {
2193 	zval *serverctrls = NULL;
2194 	zval *link, *entry, *value, *ivalue;
2195 	ldap_linkdata *ld;
2196 	char *dn;
2197 	LDAPMod **ldap_mods;
2198 	LDAPControl **lserverctrls = NULL;
2199 	LDAPMessage *ldap_res;
2200 	int i, j, num_attribs, num_values, msgid;
2201 	size_t dn_len;
2202 	int *num_berval;
2203 	zend_string *attribute;
2204 	zend_ulong index;
2205 	int is_full_add=0; /* flag for full add operation so ldap_mod_add can be put back into oper, gerrit THomson */
2206 
2207 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa/|a", &link, &dn, &dn_len, &entry, &serverctrls) != SUCCESS) {
2208 		return;
2209 	}
2210 
2211 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2212 		RETURN_FALSE;
2213 	}
2214 
2215 	num_attribs = zend_hash_num_elements(Z_ARRVAL_P(entry));
2216 	ldap_mods = safe_emalloc((num_attribs+1), sizeof(LDAPMod *), 0);
2217 	num_berval = safe_emalloc(num_attribs, sizeof(int), 0);
2218 	zend_hash_internal_pointer_reset(Z_ARRVAL_P(entry));
2219 
2220 	/* added by gerrit thomson to fix ldap_add using ldap_mod_add */
2221 	if (oper == PHP_LD_FULL_ADD) {
2222 		oper = LDAP_MOD_ADD;
2223 		is_full_add = 1;
2224 	}
2225 	/* end additional , gerrit thomson */
2226 
2227 	for (i = 0; i < num_attribs; i++) {
2228 		ldap_mods[i] = emalloc(sizeof(LDAPMod));
2229 		ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
2230 		ldap_mods[i]->mod_type = NULL;
2231 
2232 		if (zend_hash_get_current_key(Z_ARRVAL_P(entry), &attribute, &index) == HASH_KEY_IS_STRING) {
2233 			ldap_mods[i]->mod_type = estrndup(ZSTR_VAL(attribute), ZSTR_LEN(attribute));
2234 		} else {
2235 			php_error_docref(NULL, E_WARNING, "Unknown attribute in the data");
2236 			/* Free allocated memory */
2237 			while (i >= 0) {
2238 				if (ldap_mods[i]->mod_type) {
2239 					efree(ldap_mods[i]->mod_type);
2240 				}
2241 				efree(ldap_mods[i]);
2242 				i--;
2243 			}
2244 			efree(num_berval);
2245 			efree(ldap_mods);
2246 			RETURN_FALSE;
2247 		}
2248 
2249 		value = zend_hash_get_current_data(Z_ARRVAL_P(entry));
2250 
2251 		ZVAL_DEREF(value);
2252 		if (Z_TYPE_P(value) != IS_ARRAY) {
2253 			num_values = 1;
2254 		} else {
2255 			SEPARATE_ARRAY(value);
2256 			num_values = zend_hash_num_elements(Z_ARRVAL_P(value));
2257 		}
2258 
2259 		num_berval[i] = num_values;
2260 		ldap_mods[i]->mod_bvalues = safe_emalloc((num_values + 1), sizeof(struct berval *), 0);
2261 
2262 /* allow for arrays with one element, no allowance for arrays with none but probably not required, gerrit thomson. */
2263 		if ((num_values == 1) && (Z_TYPE_P(value) != IS_ARRAY)) {
2264 			convert_to_string(value);
2265 			if (EG(exception)) {
2266 				RETVAL_FALSE;
2267 				goto cleanup;
2268 			}
2269 			ldap_mods[i]->mod_bvalues[0] = (struct berval *) emalloc (sizeof(struct berval));
2270 			ldap_mods[i]->mod_bvalues[0]->bv_val = Z_STRVAL_P(value);
2271 			ldap_mods[i]->mod_bvalues[0]->bv_len = Z_STRLEN_P(value);
2272 		} else {
2273 			for (j = 0; j < num_values; j++) {
2274 				if ((ivalue = zend_hash_index_find(Z_ARRVAL_P(value), j)) == NULL) {
2275 					php_error_docref(NULL, E_WARNING, "Value array must have consecutive indices 0, 1, ...");
2276 					num_berval[i] = j;
2277 					num_attribs = i + 1;
2278 					RETVAL_FALSE;
2279 					goto cleanup;
2280 				}
2281 				convert_to_string(ivalue);
2282 				if (EG(exception)) {
2283 					RETVAL_FALSE;
2284 					goto cleanup;
2285 				}
2286 				ldap_mods[i]->mod_bvalues[j] = (struct berval *) emalloc (sizeof(struct berval));
2287 				ldap_mods[i]->mod_bvalues[j]->bv_val = Z_STRVAL_P(ivalue);
2288 				ldap_mods[i]->mod_bvalues[j]->bv_len = Z_STRLEN_P(ivalue);
2289 			}
2290 		}
2291 		ldap_mods[i]->mod_bvalues[num_values] = NULL;
2292 		zend_hash_move_forward(Z_ARRVAL_P(entry));
2293 	}
2294 	ldap_mods[num_attribs] = NULL;
2295 
2296 	if (serverctrls) {
2297 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
2298 		if (lserverctrls == NULL) {
2299 			RETVAL_FALSE;
2300 			goto cleanup;
2301 		}
2302 	}
2303 
2304 /* check flag to see if do_mod was called to perform full add , gerrit thomson */
2305 	if (is_full_add == 1) {
2306 		if (ext) {
2307 			i = ldap_add_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2308 		} else {
2309 			i = ldap_add_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2310 		}
2311 		if (i != LDAP_SUCCESS) {
2312 			php_error_docref(NULL, E_WARNING, "Add: %s", ldap_err2string(i));
2313 			RETVAL_FALSE;
2314 		} else if (ext) {
2315 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2316 			if (i == -1) {
2317 				php_error_docref(NULL, E_WARNING, "Add operation failed");
2318 				RETVAL_FALSE;
2319 				goto cleanup;
2320 			}
2321 
2322 			/* return a PHP control object */
2323 			RETVAL_RES(zend_register_resource(ldap_res, le_result));
2324 		} else RETVAL_TRUE;
2325 	} else {
2326 		if (ext) {
2327 			i = ldap_modify_ext(ld->link, dn, ldap_mods, lserverctrls, NULL, &msgid);
2328 		} else {
2329 			i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL);
2330 		}
2331 		if (i != LDAP_SUCCESS) {
2332 			php_error_docref(NULL, E_WARNING, "Modify: %s", ldap_err2string(i));
2333 			RETVAL_FALSE;
2334 		} else if (ext) {
2335 			i = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2336 			if (i == -1) {
2337 				php_error_docref(NULL, E_WARNING, "Modify operation failed");
2338 				RETVAL_FALSE;
2339 				goto cleanup;
2340 			}
2341 
2342 			/* return a PHP control object */
2343 			RETVAL_RES(zend_register_resource(ldap_res, le_result));
2344 		} else RETVAL_TRUE;
2345 	}
2346 
2347 cleanup:
2348 	for (i = 0; i < num_attribs; i++) {
2349 		efree(ldap_mods[i]->mod_type);
2350 		for (j = 0; j < num_berval[i]; j++) {
2351 			efree(ldap_mods[i]->mod_bvalues[j]);
2352 		}
2353 		efree(ldap_mods[i]->mod_bvalues);
2354 		efree(ldap_mods[i]);
2355 	}
2356 	efree(num_berval);
2357 	efree(ldap_mods);
2358 
2359 	if (lserverctrls) {
2360 		_php_ldap_controls_free(&lserverctrls);
2361 	}
2362 
2363 	return;
2364 }
2365 /* }}} */
2366 
2367 /* {{{ proto bool ldap_add(resource link, string dn, array entry [, array servercontrols])
2368    Add entries to LDAP directory */
PHP_FUNCTIONnull2369 PHP_FUNCTION(ldap_add)
2370 {
2371 	/* 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 */
2372 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 0);
2373 }
2374 /* }}} */
2375 
2376 /* {{{ proto resource ldap_add_ext(resource link, string dn, array entry [, array servercontrols])
2377    Add entries to LDAP directory */
PHP_FUNCTIONnull2378 PHP_FUNCTION(ldap_add_ext)
2379 {
2380 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_LD_FULL_ADD, 1);
2381 }
2382 /* }}} */
2383 
2384 /* three functions for attribute base modifications, gerrit Thomson */
2385 
2386 /* {{{ proto bool ldap_mod_replace(resource link, string dn, array entry [, array servercontrols])
2387    Replace attribute values with new ones */
PHP_FUNCTIONnull2388 PHP_FUNCTION(ldap_mod_replace)
2389 {
2390 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 0);
2391 }
2392 /* }}} */
2393 
2394 /* {{{ proto resource ldap_mod_replace_ext(resource link, string dn, array entry [, array servercontrols])
2395    Replace attribute values with new ones */
PHP_FUNCTIONnull2396 PHP_FUNCTION(ldap_mod_replace_ext)
2397 {
2398 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_REPLACE, 1);
2399 }
2400 /* }}} */
2401 
2402 /* {{{ proto bool ldap_mod_add(resource link, string dn, array entry [, array servercontrols])
2403    Add attribute values to current */
PHP_FUNCTIONnull2404 PHP_FUNCTION(ldap_mod_add)
2405 {
2406 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 0);
2407 }
2408 /* }}} */
2409 
2410 /* {{{ proto resource ldap_mod_add(resource link, string dn, array entry [, array servercontrols])
2411    Add attribute values to current */
PHP_FUNCTIONnull2412 PHP_FUNCTION(ldap_mod_add_ext)
2413 {
2414 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_ADD, 1);
2415 }
2416 /* }}} */
2417 
2418 /* {{{ proto bool ldap_mod_del(resource link, string dn, array entry [, array servercontrols])
2419    Delete attribute values */
PHP_FUNCTIONnull2420 PHP_FUNCTION(ldap_mod_del)
2421 {
2422 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 0);
2423 }
2424 /* }}} */
2425 
2426 /* {{{ proto resource ldap_mod_del_ext(resource link, string dn, array entry [, array servercontrols])
2427    Delete attribute values */
PHP_FUNCTIONnull2428 PHP_FUNCTION(ldap_mod_del_ext)
2429 {
2430 	php_ldap_do_modify(INTERNAL_FUNCTION_PARAM_PASSTHRU, LDAP_MOD_DELETE, 1);
2431 }
2432 /* }}} */
2433 
2434 /* {{{ php_ldap_do_delete
2435  */
php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS, int ext)2436 static void php_ldap_do_delete(INTERNAL_FUNCTION_PARAMETERS, int ext)
2437 {
2438 	zval *serverctrls = NULL;
2439 	zval *link;
2440 	ldap_linkdata *ld;
2441 	LDAPControl **lserverctrls = NULL;
2442 	LDAPMessage *ldap_res;
2443 	char *dn;
2444 	int rc, msgid;
2445 	size_t dn_len;
2446 
2447 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs|a", &link, &dn, &dn_len, &serverctrls) != SUCCESS) {
2448 		return;
2449 	}
2450 
2451 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2452 		RETURN_FALSE;
2453 	}
2454 
2455 	if (serverctrls) {
2456 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
2457 		if (lserverctrls == NULL) {
2458 			RETVAL_FALSE;
2459 			goto cleanup;
2460 		}
2461 	}
2462 
2463 	if (ext) {
2464 		rc = ldap_delete_ext(ld->link, dn, lserverctrls, NULL, &msgid);
2465 	} else {
2466 		rc = ldap_delete_ext_s(ld->link, dn, lserverctrls, NULL);
2467 	}
2468 	if (rc != LDAP_SUCCESS) {
2469 		php_error_docref(NULL, E_WARNING, "Delete: %s", ldap_err2string(rc));
2470 		RETVAL_FALSE;
2471 		goto cleanup;
2472 	} else if (ext) {
2473 		rc = ldap_result(ld->link, msgid, 1 /* LDAP_MSG_ALL */, NULL, &ldap_res);
2474 		if (rc == -1) {
2475 			php_error_docref(NULL, E_WARNING, "Delete operation failed");
2476 			RETVAL_FALSE;
2477 			goto cleanup;
2478 		}
2479 
2480 		/* return a PHP control object */
2481 		RETVAL_RES(zend_register_resource(ldap_res, le_result));
2482 	} else {
2483 		RETVAL_TRUE;
2484 	}
2485 
2486 cleanup:
2487 	if (lserverctrls) {
2488 		_php_ldap_controls_free(&lserverctrls);
2489 	}
2490 
2491 	return;
2492 }
2493 /* }}} */
2494 
2495 /* {{{ proto bool ldap_delete(resource link, string dn [, array servercontrols])
2496    Delete an entry from a directory */
PHP_FUNCTIONnull2497 PHP_FUNCTION(ldap_delete)
2498 {
2499 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0);
2500 }
2501 /* }}} */
2502 
2503 /* {{{ proto resource ldap_delete_ext(resource link, string dn [, array servercontrols])
2504    Delete an entry from a directory */
PHP_FUNCTIONnull2505 PHP_FUNCTION(ldap_delete_ext)
2506 {
2507 	php_ldap_do_delete(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1);
2508 }
2509 /* }}} */
2510 
2511 /* {{{ _ldap_str_equal_to_const
2512  */
_ldap_str_equal_to_const(const char *str, size_t str_len, const char *cstr)2513 static size_t _ldap_str_equal_to_const(const char *str, size_t str_len, const char *cstr)
2514 {
2515 	size_t i;
2516 
2517 	if (strlen(cstr) != str_len)
2518 		return 0;
2519 
2520 	for (i = 0; i < str_len; ++i) {
2521 		if (str[i] != cstr[i]) {
2522 			return 0;
2523 		}
2524 	}
2525 
2526 	return 1;
2527 }
2528 /* }}} */
2529 
2530 /* {{{ _ldap_strlen_max
2531  */
_ldap_strlen_max(const char *str, size_t max_len)2532 static size_t _ldap_strlen_max(const char *str, size_t max_len)
2533 {
2534 	size_t i;
2535 
2536 	for (i = 0; i < max_len; ++i) {
2537 		if (str[i] == '\0') {
2538 			return i;
2539 		}
2540 	}
2541 
2542 	return max_len;
2543 }
2544 /* }}} */
2545 
2546 /* {{{ _ldap_hash_fetch
2547  */
_ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)2548 static void _ldap_hash_fetch(zval *hashTbl, const char *key, zval **out)
2549 {
2550 	*out = zend_hash_str_find(Z_ARRVAL_P(hashTbl), key, strlen(key));
2551 }
2552 /* }}} */
2553 
2554 /* {{{ proto bool ldap_modify_batch(resource link, string dn, array modifs [, array servercontrols])
2555    Perform multiple modifications as part of one operation */
PHP_FUNCTIONnull2556 PHP_FUNCTION(ldap_modify_batch)
2557 {
2558 	zval *serverctrls = NULL;
2559 	ldap_linkdata *ld;
2560 	zval *link, *mods, *mod, *modinfo;
2561 	zend_string *modval;
2562 	zval *attrib, *modtype, *vals;
2563 	zval *fetched;
2564 	char *dn;
2565 	size_t dn_len;
2566 	int i, j, k;
2567 	int num_mods, num_modprops, num_modvals;
2568 	LDAPMod **ldap_mods;
2569 	LDAPControl **lserverctrls = NULL;
2570 	uint32_t oper;
2571 
2572 	/*
2573 	$mods = array(
2574 		array(
2575 			"attrib" => "unicodePwd",
2576 			"modtype" => LDAP_MODIFY_BATCH_REMOVE,
2577 			"values" => array($oldpw)
2578 		),
2579 		array(
2580 			"attrib" => "unicodePwd",
2581 			"modtype" => LDAP_MODIFY_BATCH_ADD,
2582 			"values" => array($newpw)
2583 		),
2584 		array(
2585 			"attrib" => "userPrincipalName",
2586 			"modtype" => LDAP_MODIFY_BATCH_REPLACE,
2587 			"values" => array("janitor@corp.contoso.com")
2588 		),
2589 		array(
2590 			"attrib" => "userCert",
2591 			"modtype" => LDAP_MODIFY_BATCH_REMOVE_ALL
2592 		)
2593 	);
2594 	*/
2595 
2596 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsa/|a", &link, &dn, &dn_len, &mods, &serverctrls) != SUCCESS) {
2597 		return;
2598 	}
2599 
2600 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2601 		RETURN_FALSE;
2602 	}
2603 
2604 	/* perform validation */
2605 	{
2606 		zend_string *modkey;
2607 		zend_long modtype;
2608 
2609 		/* to store the wrongly-typed keys */
2610 		zend_ulong tmpUlong;
2611 
2612 		/* make sure the DN contains no NUL bytes */
2613 		if (_ldap_strlen_max(dn, dn_len) != dn_len) {
2614 			php_error_docref(NULL, E_WARNING, "DN must not contain NUL bytes");
2615 			RETURN_FALSE;
2616 		}
2617 
2618 		/* make sure the top level is a normal array */
2619 		zend_hash_internal_pointer_reset(Z_ARRVAL_P(mods));
2620 		if (zend_hash_get_current_key_type(Z_ARRVAL_P(mods)) != HASH_KEY_IS_LONG) {
2621 			php_error_docref(NULL, E_WARNING, "Modifications array must not be string-indexed");
2622 			RETURN_FALSE;
2623 		}
2624 
2625 		num_mods = zend_hash_num_elements(Z_ARRVAL_P(mods));
2626 
2627 		for (i = 0; i < num_mods; i++) {
2628 			/* is the numbering consecutive? */
2629 			if ((fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i)) == NULL) {
2630 				php_error_docref(NULL, E_WARNING, "Modifications array must have consecutive indices 0, 1, ...");
2631 				RETURN_FALSE;
2632 			}
2633 			mod = fetched;
2634 
2635 			/* is it an array? */
2636 			if (Z_TYPE_P(mod) != IS_ARRAY) {
2637 				php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be an array itself");
2638 				RETURN_FALSE;
2639 			}
2640 
2641 			SEPARATE_ARRAY(mod);
2642 			/* for the modification hashtable... */
2643 			zend_hash_internal_pointer_reset(Z_ARRVAL_P(mod));
2644 			num_modprops = zend_hash_num_elements(Z_ARRVAL_P(mod));
2645 
2646 			for (j = 0; j < num_modprops; j++) {
2647 				/* are the keys strings? */
2648 				if (zend_hash_get_current_key(Z_ARRVAL_P(mod), &modkey, &tmpUlong) != HASH_KEY_IS_STRING) {
2649 					php_error_docref(NULL, E_WARNING, "Each entry of modifications array must be string-indexed");
2650 					RETURN_FALSE;
2651 				}
2652 
2653 				/* is this a valid entry? */
2654 				if (
2655 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB) &&
2656 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE) &&
2657 					!_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)
2658 				) {
2659 					php_error_docref(NULL, E_WARNING, "The only allowed keys in entries of the modifications array are '" LDAP_MODIFY_BATCH_ATTRIB "', '" LDAP_MODIFY_BATCH_MODTYPE "' and '" LDAP_MODIFY_BATCH_VALUES "'");
2660 					RETURN_FALSE;
2661 				}
2662 
2663 				fetched = zend_hash_get_current_data(Z_ARRVAL_P(mod));
2664 				modinfo = fetched;
2665 
2666 				/* does the value type match the key? */
2667 				if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_ATTRIB)) {
2668 					if (Z_TYPE_P(modinfo) != IS_STRING) {
2669 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must be a string");
2670 						RETURN_FALSE;
2671 					}
2672 
2673 					if (Z_STRLEN_P(modinfo) != _ldap_strlen_max(Z_STRVAL_P(modinfo), Z_STRLEN_P(modinfo))) {
2674 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_ATTRIB "' value must not contain NUL bytes");
2675 						RETURN_FALSE;
2676 					}
2677 				}
2678 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_MODTYPE)) {
2679 					if (Z_TYPE_P(modinfo) != IS_LONG) {
2680 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_MODTYPE "' value must be a long");
2681 						RETURN_FALSE;
2682 					}
2683 
2684 					/* is the value in range? */
2685 					modtype = Z_LVAL_P(modinfo);
2686 					if (
2687 						modtype != LDAP_MODIFY_BATCH_ADD &&
2688 						modtype != LDAP_MODIFY_BATCH_REMOVE &&
2689 						modtype != LDAP_MODIFY_BATCH_REPLACE &&
2690 						modtype != LDAP_MODIFY_BATCH_REMOVE_ALL
2691 					) {
2692 						php_error_docref(NULL, E_WARNING, "The '" LDAP_MODIFY_BATCH_MODTYPE "' value must match one of the LDAP_MODIFY_BATCH_* constants");
2693 						RETURN_FALSE;
2694 					}
2695 
2696 					/* if it's REMOVE_ALL, there must not be a values array; otherwise, there must */
2697 					if (modtype == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2698 						if (zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2699 							php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must not be provided");
2700 							RETURN_FALSE;
2701 						}
2702 					}
2703 					else {
2704 						if (!zend_hash_str_exists(Z_ARRVAL_P(mod), LDAP_MODIFY_BATCH_VALUES, strlen(LDAP_MODIFY_BATCH_VALUES))) {
2705 							php_error_docref(NULL, E_WARNING, "If '" LDAP_MODIFY_BATCH_MODTYPE "' is not LDAP_MODIFY_BATCH_REMOVE_ALL, a '" LDAP_MODIFY_BATCH_VALUES "' array must be provided");
2706 							RETURN_FALSE;
2707 						}
2708 					}
2709 				}
2710 				else if (_ldap_str_equal_to_const(ZSTR_VAL(modkey), ZSTR_LEN(modkey), LDAP_MODIFY_BATCH_VALUES)) {
2711 					if (Z_TYPE_P(modinfo) != IS_ARRAY) {
2712 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' value must be an array");
2713 						RETURN_FALSE;
2714 					}
2715 
2716 					SEPARATE_ARRAY(modinfo);
2717 					/* is the array not empty? */
2718 					zend_hash_internal_pointer_reset(Z_ARRVAL_P(modinfo));
2719 					num_modvals = zend_hash_num_elements(Z_ARRVAL_P(modinfo));
2720 					if (num_modvals == 0) {
2721 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have at least one element");
2722 						RETURN_FALSE;
2723 					}
2724 
2725 					/* are its keys integers? */
2726 					if (zend_hash_get_current_key_type(Z_ARRVAL_P(modinfo)) != HASH_KEY_IS_LONG) {
2727 						php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must not be string-indexed");
2728 						RETURN_FALSE;
2729 					}
2730 
2731 					/* are the keys consecutive? */
2732 					for (k = 0; k < num_modvals; k++) {
2733 						if ((fetched = zend_hash_index_find(Z_ARRVAL_P(modinfo), k)) == NULL) {
2734 							php_error_docref(NULL, E_WARNING, "A '" LDAP_MODIFY_BATCH_VALUES "' array must have consecutive indices 0, 1, ...");
2735 							RETURN_FALSE;
2736 						}
2737 					}
2738 				}
2739 
2740 				zend_hash_move_forward(Z_ARRVAL_P(mod));
2741 			}
2742 		}
2743 	}
2744 	/* validation was successful */
2745 
2746 	/* allocate array of modifications */
2747 	ldap_mods = safe_emalloc((num_mods+1), sizeof(LDAPMod *), 0);
2748 
2749 	/* for each modification */
2750 	for (i = 0; i < num_mods; i++) {
2751 		/* allocate the modification struct */
2752 		ldap_mods[i] = safe_emalloc(1, sizeof(LDAPMod), 0);
2753 
2754 		/* fetch the relevant data */
2755 		fetched = zend_hash_index_find(Z_ARRVAL_P(mods), i);
2756 		mod = fetched;
2757 
2758 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_ATTRIB, &attrib);
2759 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_MODTYPE, &modtype);
2760 		_ldap_hash_fetch(mod, LDAP_MODIFY_BATCH_VALUES, &vals);
2761 
2762 		/* map the modification type */
2763 		switch (Z_LVAL_P(modtype)) {
2764 			case LDAP_MODIFY_BATCH_ADD:
2765 				oper = LDAP_MOD_ADD;
2766 				break;
2767 			case LDAP_MODIFY_BATCH_REMOVE:
2768 			case LDAP_MODIFY_BATCH_REMOVE_ALL:
2769 				oper = LDAP_MOD_DELETE;
2770 				break;
2771 			case LDAP_MODIFY_BATCH_REPLACE:
2772 				oper = LDAP_MOD_REPLACE;
2773 				break;
2774 			default:
2775 				zend_throw_error(NULL, "Unknown and uncaught modification type.");
2776 				RETVAL_FALSE;
2777 				efree(ldap_mods[i]);
2778 				num_mods = i;
2779 				goto cleanup;
2780 		}
2781 
2782 		/* fill in the basic info */
2783 		ldap_mods[i]->mod_op = oper | LDAP_MOD_BVALUES;
2784 		ldap_mods[i]->mod_type = estrndup(Z_STRVAL_P(attrib), Z_STRLEN_P(attrib));
2785 
2786 		if (Z_LVAL_P(modtype) == LDAP_MODIFY_BATCH_REMOVE_ALL) {
2787 			/* no values */
2788 			ldap_mods[i]->mod_bvalues = NULL;
2789 		}
2790 		else {
2791 			/* allocate space for the values as part of this modification */
2792 			num_modvals = zend_hash_num_elements(Z_ARRVAL_P(vals));
2793 			ldap_mods[i]->mod_bvalues = safe_emalloc((num_modvals+1), sizeof(struct berval *), 0);
2794 
2795 			/* for each value */
2796 			for (j = 0; j < num_modvals; j++) {
2797 				/* fetch it */
2798 				fetched = zend_hash_index_find(Z_ARRVAL_P(vals), j);
2799 				modval = zval_get_string(fetched);
2800 				if (EG(exception)) {
2801 					RETVAL_FALSE;
2802 					ldap_mods[i]->mod_bvalues[j] = NULL;
2803 					num_mods = i + 1;
2804 					goto cleanup;
2805 				}
2806 
2807 				/* allocate the data struct */
2808 				ldap_mods[i]->mod_bvalues[j] = safe_emalloc(1, sizeof(struct berval), 0);
2809 
2810 				/* fill it */
2811 				ldap_mods[i]->mod_bvalues[j]->bv_len = ZSTR_LEN(modval);
2812 				ldap_mods[i]->mod_bvalues[j]->bv_val = estrndup(ZSTR_VAL(modval), ZSTR_LEN(modval));
2813 				zend_string_release(modval);
2814 			}
2815 
2816 			/* NULL-terminate values */
2817 			ldap_mods[i]->mod_bvalues[num_modvals] = NULL;
2818 		}
2819 	}
2820 
2821 	/* NULL-terminate modifications */
2822 	ldap_mods[num_mods] = NULL;
2823 
2824 	if (serverctrls) {
2825 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
2826 		if (lserverctrls == NULL) {
2827 			RETVAL_FALSE;
2828 			goto cleanup;
2829 		}
2830 	}
2831 
2832 	/* perform (finally) */
2833 	if ((i = ldap_modify_ext_s(ld->link, dn, ldap_mods, lserverctrls, NULL)) != LDAP_SUCCESS) {
2834 		php_error_docref(NULL, E_WARNING, "Batch Modify: %s", ldap_err2string(i));
2835 		RETVAL_FALSE;
2836 	} else RETVAL_TRUE;
2837 
2838 	/* clean up */
2839 	cleanup: {
2840 		for (i = 0; i < num_mods; i++) {
2841 			/* attribute */
2842 			efree(ldap_mods[i]->mod_type);
2843 
2844 			if (ldap_mods[i]->mod_bvalues != NULL) {
2845 				/* each BER value */
2846 				for (j = 0; ldap_mods[i]->mod_bvalues[j] != NULL; j++) {
2847 					/* free the data bytes */
2848 					efree(ldap_mods[i]->mod_bvalues[j]->bv_val);
2849 
2850 					/* free the bvalue struct */
2851 					efree(ldap_mods[i]->mod_bvalues[j]);
2852 				}
2853 
2854 				/* the BER value array */
2855 				efree(ldap_mods[i]->mod_bvalues);
2856 			}
2857 
2858 			/* the modification */
2859 			efree(ldap_mods[i]);
2860 		}
2861 
2862 		/* the modifications array */
2863 		efree(ldap_mods);
2864 
2865 		if (lserverctrls) {
2866 			_php_ldap_controls_free(&lserverctrls);
2867 		}
2868 	}
2869 }
2870 /* }}} */
2871 
2872 /* {{{ proto int ldap_errno(resource link)
2873    Get the current ldap error number */
PHP_FUNCTIONnull2874 PHP_FUNCTION(ldap_errno)
2875 {
2876 	zval *link;
2877 	ldap_linkdata *ld;
2878 
2879 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
2880 		return;
2881 	}
2882 
2883 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2884 		RETURN_FALSE;
2885 	}
2886 
2887 	RETURN_LONG(_get_lderrno(ld->link));
2888 }
2889 /* }}} */
2890 
2891 /* {{{ proto string ldap_err2str(int errno)
2892    Convert error number to error string */
PHP_FUNCTIONnull2893 PHP_FUNCTION(ldap_err2str)
2894 {
2895 	zend_long perrno;
2896 
2897 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &perrno) != SUCCESS) {
2898 		return;
2899 	}
2900 
2901 	RETURN_STRING(ldap_err2string(perrno));
2902 }
2903 /* }}} */
2904 
2905 /* {{{ proto string ldap_error(resource link)
2906    Get the current ldap error string */
PHP_FUNCTIONnull2907 PHP_FUNCTION(ldap_error)
2908 {
2909 	zval *link;
2910 	ldap_linkdata *ld;
2911 	int ld_errno;
2912 
2913 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &link) != SUCCESS) {
2914 		return;
2915 	}
2916 
2917 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2918 		RETURN_FALSE;
2919 	}
2920 
2921 	ld_errno = _get_lderrno(ld->link);
2922 
2923 	RETURN_STRING(ldap_err2string(ld_errno));
2924 }
2925 /* }}} */
2926 
2927 /* {{{ proto bool ldap_compare(resource link, string dn, string attr, string value)
2928    Determine if an entry has a specific value for one of its attributes */
PHP_FUNCTIONnull2929 PHP_FUNCTION(ldap_compare)
2930 {
2931 	zval *serverctrls = NULL;
2932 	zval *link;
2933 	char *dn, *attr, *value;
2934 	size_t dn_len, attr_len, value_len;
2935 	ldap_linkdata *ld;
2936 	LDAPControl **lserverctrls = NULL;
2937 	int errno;
2938 	struct berval lvalue;
2939 
2940 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rsss|a", &link, &dn, &dn_len, &attr, &attr_len, &value, &value_len, &serverctrls) != SUCCESS) {
2941 		return;
2942 	}
2943 
2944 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2945 		RETURN_FALSE;
2946 	}
2947 
2948 	if (serverctrls) {
2949 		lserverctrls = _php_ldap_controls_from_array(ld->link, serverctrls);
2950 		if (lserverctrls == NULL) {
2951 			RETVAL_FALSE;
2952 			goto cleanup;
2953 		}
2954 	}
2955 
2956 	lvalue.bv_val = value;
2957 	lvalue.bv_len = value_len;
2958 
2959 	errno = ldap_compare_ext_s(ld->link, dn, attr, &lvalue, lserverctrls, NULL);
2960 
2961 	switch (errno) {
2962 		case LDAP_COMPARE_TRUE:
2963 			RETVAL_TRUE;
2964 			break;
2965 
2966 		case LDAP_COMPARE_FALSE:
2967 			RETVAL_FALSE;
2968 			break;
2969 
2970 		default:
2971 			php_error_docref(NULL, E_WARNING, "Compare: %s", ldap_err2string(errno));
2972 			RETVAL_LONG(-1);
2973 	}
2974 
2975 cleanup:
2976 	if (lserverctrls) {
2977 		_php_ldap_controls_free(&lserverctrls);
2978 	}
2979 
2980 	return;
2981 }
2982 /* }}} */
2983 
2984 /* {{{ proto bool ldap_sort(resource link, resource result, string sortfilter)
2985    Sort LDAP result entries */
PHP_FUNCTIONnull2986 PHP_FUNCTION(ldap_sort)
2987 {
2988 	zval *link, *result;
2989 	ldap_linkdata *ld;
2990 	char *sortfilter;
2991 	size_t sflen;
2992 	zend_resource *le;
2993 
2994 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rrs", &link, &result, &sortfilter, &sflen) != SUCCESS) {
2995 		RETURN_FALSE;
2996 	}
2997 
2998 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
2999 		RETURN_FALSE;
3000 	}
3001 
3002 	le = Z_RES_P(result);
3003 	if (le->type != le_result) {
3004 		php_error_docref(NULL, E_WARNING, "Supplied resource is not a valid ldap result resource");
3005 		RETURN_FALSE;
3006 	}
3007 
3008 	if (ldap_sort_entries(ld->link, (LDAPMessage **) &le->ptr, sflen ? sortfilter : NULL, strcmp) != LDAP_SUCCESS) {
3009 		php_error_docref(NULL, E_WARNING, "%s", ldap_err2string(errno));
3010 		RETURN_FALSE;
3011 	}
3012 
3013 	RETURN_TRUE;
3014 }
3015 /* }}} */
3016 
3017 #if (LDAP_API_VERSION > 2000) || HAVE_ORALDAP
3018 /* {{{ proto bool ldap_get_option(resource link, int option, mixed retval)
3019    Get the current value of various session-wide parameters */
PHP_FUNCTIONnull3020 PHP_FUNCTION(ldap_get_option)
3021 {
3022 	zval *link, *retval;
3023 	ldap_linkdata *ld;
3024 	zend_long option;
3025 
3026 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "rlz", &link, &option, &retval) != SUCCESS) {
3027 		return;
3028 	}
3029 
3030 	if ((ld = (ldap_linkdata *)zend_fetch_resource(Z_RES_P(link), "ldap link", le_link)) == NULL) {
3031 		RETURN_FALSE;
3032 	}
3033 
3034 	switch (option) {
3035 	/* options with int value */
3036 	case LDAP_OPT_DEREF:
3037 	case LDAP_OPT_SIZELIMIT:
3038 	case LDAP_OPT_TIMELIMIT:
3039 	case LDAP_OPT_PROTOCOL_VERSION:
3040 	case LDAP_OPT_ERROR_NUMBER:
3041 	case LDAP_OPT_REFERRALS:
3042 #ifdef LDAP_OPT_RESTART
3043 	case LDAP_OPT_RESTART:
3044 #endif
3045 #ifdef LDAP_OPT_X_SASL_NOCANON
3046 	case LDAP_OPT_X_SASL_NOCANON:
3047 #endif
3048 #ifdef LDAP_OPT_X_TLS_REQUIRE_CERT
3049 	case LDAP_OPT_X_TLS_REQUIRE_CERT:
3050 #endif
3051 #ifdef LDAP_OPT_X_TLS_CRLCHECK
3052 	case LDAP_OPT_X_TLS_CRLCHECK:
3053 #endif
3054 #ifdef LDAP_OPT_X_TLS_PROTOCOL_MIN
3055 	case LDAP_OPT_X_TLS_PROTOCOL_MIN:
3056 #endif
3057 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
3058 	case LDAP_OPT_X_KEEPALIVE_IDLE:
3059 	case LDAP_OPT_X_KEEPALIVE_PROBES:
3060 	case LDAP_OPT_X_KEEPALIVE_INTERVAL:
3061 #endif
3062 		{
3063 			int val;
3064 
3065 			if (ldap_get_option(ld->link, option, &val)) {
3066 				RETURN_FALSE;
3067 			}
3068 			ZEND_TRY_ASSIGN_REF_LONG(retval, val);
3069 		} break;
3070 #ifdef LDAP_OPT_NETWORK_TIMEOUT
3071 	case LDAP_OPT_NETWORK_TIMEOUT:
3072 		{
3073 			struct timeval *timeout = NULL;
3074 
3075 			if (ldap_get_option(ld->link, LDAP_OPT_NETWORK_TIMEOUT, (void *) &timeout)) {
3076 				if (timeout) {
3077 					ldap_memfree(timeout);
3078 				}
3079 				RETURN_FALSE;
3080 			}
3081 			if (!timeout) {
3082 				RETURN_FALSE;
3083 			}
3084 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
3085 			ldap_memfree(timeout);
3086 		} break;
3087 #elif defined(LDAP_X_OPT_CONNECT_TIMEOUT)
3088 	case LDAP_X_OPT_CONNECT_TIMEOUT:
3089 		{
3090 			int timeout;
3091 
3092 			if (ldap_get_option(ld->link, LDAP_X_OPT_CONNECT_TIMEOUT, &timeout)) {
3093 				RETURN_FALSE;
3094 			}
3095 			ZEND_TRY_ASSIGN_REF_LONG(retval, (timeout / 1000));
3096 		} break;
3097 #endif
3098 #ifdef LDAP_OPT_TIMEOUT
3099 	case LDAP_OPT_TIMEOUT:
3100 		{
3101 			struct timeval *timeout = NULL;
3102 
3103 			if (ldap_get_option(ld->link, LDAP_OPT_TIMEOUT, (void *) &timeout)) {
3104 				if (timeout) {
3105 					ldap_memfree(timeout);
3106 				}
3107 				RETURN_FALSE;
3108 			}
3109 			if (!timeout) {
3110 				RETURN_FALSE;
3111 			}
3112 			ZEND_TRY_ASSIGN_REF_LONG(retval, timeout->tv_sec);
3113 			ldap_memfree(timeout);
3114 		} break;
3115 #endif
3116 	/* options with string value */
3117 	case LDAP_OPT_ERROR_STRING:
3118 #ifdef LDAP_OPT_HOST_NAME
3119 	case LDAP_OPT_HOST_NAME:
3120 #endif
3121 #ifdef HAVE_LDAP_SASL
3122 	case LDAP_OPT_X_SASL_MECH:
3123 	case LDAP_OPT_X_SASL_REALM:
3124 	case LDAP_OPT_X_SASL_AUTHCID:
3125 	case LDAP_OPT_X_SASL_AUTHZID:
3126 #endif
3127 #ifdef LDAP_OPT_X_SASL_USERNAME
3128 	case LDAP_OPT_X_SASL_USERNAME:
3129 #endif
3130 #if (LDAP_API_VERSION > 2000)
3131 	case LDAP_OPT_X_TLS_CACERTDIR:
3132 	case LDAP_OPT_X_TLS_CACERTFILE:
3133 	case LDAP_OPT_X_TLS_CERTFILE:
3134 	case LDAP_OPT_X_TLS_CIPHER_SUITE:
3135 	case LDAP_OPT_X_TLS_KEYFILE:
3136 	case LDAP_OPT_X_TLS_RANDOM_FILE:
3137 #endif
3138 #ifdef LDAP_OPT_X_TLS_PACKAGE
3139 	case LDAP_OPT_X_TLS_PACKAGE:
3140 #endif
3141 #ifdef LDAP_OPT_X_TLS_CRLFILE
3142 	case LDAP_OPT_X_TLS_CRLFILE:
3143 #endif
3144 #ifdef LDAP_OPT_X_TLS_DHFILE
3145 	case LDAP_OPT_X_TLS_DHFILE:
3146 #endif
3147 #ifdef LDAP_OPT_MATCHED_DN
3148 	case LDAP_OPT_MATCHED_DN:
3149 #endif
3150 		{
3151 			char *val = NULL;
3152 
3153 			if (ldap_get_option(ld->link, option, &val) || val == NULL || *val == '\0') {
3154 				if (val) {
3155 					ldap_memfree(val);
3156 				}
3157 				RETURN_FALSE;
3158 			}
3159 			ZEND_TRY_ASSIGN_REF_STRING(retval, val);
3160 			ldap_memfree(val);
3161 		} break;
3162 	case LDAP_OPT_SERVER_CONTROLS:
3163 	case LDAP_OPT_CLIENT_CONTROLS:
3164 		{
3165 			LDAPControl **ctrls = NULL;
3166 
3167 			if (ldap_get_option(ld->link, option, &ctrls) || ctrls == NULL) {
3168 				if (ctrls) {
3169 					ldap_memfree(ctrls);
3170 				}
3171 				RETURN_FALSE;
3172 			}
3173 			_php_ldap_controls_to_array(ld->link, ctrls, retval, 1);
3174 		} break;
3175 /* options not implemented
3176 	case LDAP_OPT_API_INFO:
3177 	case LDAP_OPT_API_FEATURE_INFO:
3178 */
3179 	default:
3180 		RETURN_FALSE;
3181 	}
3182 	RETURN_TRUE;
3183 }
3184 /* }}} */
3185 
3186 /* {{{ proto bool ldap_set_option(resource link, int option, mixed newval)
3187    Set the value of various session-wide parameters */
PHP_FUNCTIONnull3188 PHP_FUNCTION(ldap_set_option)
3189 {
3190 	zval *link, *newval;
3191 	ldap_linkdata *ld;
3192 	LDAP *ldap;
3193 	zend_long option;
3194 
3195 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "zlz", &link, &option, &newval) != SUCCESS) {
3196 		return;
3197 	}
3198 
3199 	if (Z_TYPE_P(link) ==