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