5e95853d462def6eef468ed05c77b857e16dc960
[asterisk/asterisk.git] / res / res_config_ldap.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2005, Oxymium sarl
5  * Manuel Guesdon <mguesdon@oxymium.net> - LDAP RealTime Driver Author/Adaptor
6  *
7  * Copyright (C) 2007, Digium, Inc.
8  * Russell Bryant <russell@digium.com>
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  *
20  */
21
22 /*! \file
23  *
24  * \brief LDAP plugin for portable configuration engine (ARA)
25  *
26  * \author Mark Spencer <markster@digium.com>
27  * \author Manuel Guesdon
28  * \author Carl-Einar Thorner <cthorner@voicerd.com>
29  * \author Russell Bryant <russell@digium.com>
30  *
31  * OpenLDAP http://www.openldap.org
32  */
33
34 /*! \li \ref res_config_ldap.c uses the configuration file \ref res_ldap.conf
35  * \addtogroup configuration_file Configuration Files
36  */
37
38 /*! 
39  * \page res_ldap.conf res_ldap.conf
40  * \verbinclude res_ldap.conf.sample
41  */
42
43 /*** MODULEINFO
44         <depend>ldap</depend>
45         <support_level>extended</support_level>
46  ***/
47
48 #include "asterisk.h"
49
50 #include <stdlib.h>
51 #include <string.h>
52 #include <ctype.h>
53 #include <stdio.h>
54 #include <ldap.h>
55
56 #include "asterisk/channel.h"
57 #include "asterisk/logger.h"
58 #include "asterisk/config.h"
59 #include "asterisk/module.h"
60 #include "asterisk/lock.h"
61 #include "asterisk/options.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/utils.h"
64 #include "asterisk/strings.h"
65 #include "asterisk/pbx.h"
66 #include "asterisk/linkedlists.h"
67
68 #define RES_CONFIG_LDAP_CONF "res_ldap.conf"
69 #define RES_CONFIG_LDAP_DEFAULT_BASEDN "asterisk"
70
71 AST_MUTEX_DEFINE_STATIC(ldap_lock);
72
73 static LDAP *ldapConn;
74 static char url[512];
75 static char user[512];
76 static char pass[512];
77 static char base_distinguished_name[512];
78 static int version;
79 static time_t connect_time;
80
81 static int parse_config(void);
82 static int ldap_reconnect(void);
83 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
84
85 struct category_and_metric {
86         const char *name;
87         int metric;
88         const char *variable_name;
89         const char *variable_value;
90         int var_metric; /*!< For organizing variables (particularly includes and switch statments) within a context */
91 };
92
93 /*! \brief Table configuration 
94  */
95 struct ldap_table_config {
96         char *table_name;                /*!< table name */
97         char *additional_filter;          /*!< additional filter        */
98         struct ast_variable *attributes;  /*!< attribute names conversion */
99         struct ast_variable *delimiters;  /*!< the current delimiter is semicolon, so we are not using this variable */
100         AST_LIST_ENTRY(ldap_table_config) entry;
101         /* TODO: Make proxies work */
102 };
103
104 /*! \brief Should be locked before using it 
105  */
106 static AST_LIST_HEAD_NOLOCK_STATIC(table_configs, ldap_table_config);
107 static struct ldap_table_config *base_table_config;
108 static struct ldap_table_config *static_table_config;
109
110 static struct ast_cli_entry ldap_cli[] = {
111         AST_CLI_DEFINE(realtime_ldap_status, "Shows connection information for the LDAP RealTime driver"),
112 };
113
114 /*! \brief Create a new table_config
115  */
116 static struct ldap_table_config *table_config_new(const char *table_name)
117 {
118         struct ldap_table_config *p;
119
120         if (!(p = ast_calloc(1, sizeof(*p))))
121                 return NULL;
122
123         if (table_name) {
124                 if (!(p->table_name = ast_strdup(table_name))) {
125                         ast_free(p);
126                         return NULL;
127                 }
128         }
129
130         return p;
131 }
132
133 /*! \brief Find a table_config
134  *
135  * Should be locked before using it 
136  *
137  *  \note This function assumes ldap_lock to be locked.
138  */
139 static struct ldap_table_config *table_config_for_table_name(const char *table_name)
140 {
141         struct ldap_table_config *c = NULL;
142
143         AST_LIST_TRAVERSE(&table_configs, c, entry) {
144                 if (!strcmp(c->table_name, table_name))
145                         break;
146         }
147
148         return c;
149 }
150
151 /*! \brief Find variable by name
152  */
153 static struct ast_variable *variable_named(struct ast_variable *var, const char *name)
154 {
155         for (; var; var = var->next) {
156                 if (!strcasecmp(name, var->name))
157                         break;
158         }
159
160         return var;
161 }
162
163 /*! \brief Count  semicolons in string
164  * \param somestr - pointer to a string
165  *
166  * \return number of occurances of the delimiter(semicolon)
167  */
168 static int semicolon_count_str(const char *somestr)
169 {
170         int count = 0;
171
172         for (; *somestr; somestr++) {
173                 if (*somestr == ';')
174                         count++;
175         }
176
177         return count;
178 }
179
180 /* \brief Count semicolons in variables
181  *  
182  * takes a linked list of \a ast_variable variables, finds the one with the name variable_value
183  * and returns the number of semicolons in the value for that \a ast_variable
184  */
185 static int semicolon_count_var(struct ast_variable *var)
186 {
187         struct ast_variable *var_value = variable_named(var, "variable_value");
188
189         if (!var_value) {
190                 return 0;
191         }
192
193         ast_debug(2, "LINE(%d) semicolon_count_var: %s\n", __LINE__, var_value->value);
194
195         return semicolon_count_str(var_value->value);
196 }
197
198 /*! \brief add attribute to table config
199  *
200  * Should be locked before using it
201  */
202 static void ldap_table_config_add_attribute(struct ldap_table_config *table_config,
203         const char *attribute_name, const char *attribute_value)
204 {
205         struct ast_variable *var;
206
207         if (ast_strlen_zero(attribute_name) || ast_strlen_zero(attribute_value)) {
208                 return;
209         }
210
211         if (!(var = ast_variable_new(attribute_name, attribute_value, table_config->table_name))) {
212                 return;
213         }
214
215         if (table_config->attributes) {
216                 var->next = table_config->attributes;
217         }
218         table_config->attributes = var;
219 }
220
221 /*! \brief Free table_config
222  *
223  * \note assumes ldap_lock to be locked
224  */
225 static void table_configs_free(void)
226 {
227         struct ldap_table_config *c;
228
229         while ((c = AST_LIST_REMOVE_HEAD(&table_configs, entry))) {
230                 if (c->table_name) {
231                         ast_free(c->table_name);
232                 }
233                 if (c->additional_filter) {
234                         ast_free(c->additional_filter);
235                 }
236                 if (c->attributes) {
237                         ast_variables_destroy(c->attributes);
238                 }
239                 ast_free(c);
240         }
241
242         base_table_config = NULL;
243         static_table_config = NULL;
244 }
245
246 /*! \brief Convert variable name to ldap attribute name
247  *
248  * \note Should be locked before using it
249  */
250 static const char *convert_attribute_name_to_ldap(struct ldap_table_config *table_config,
251         const char *attribute_name)
252 {
253         int i = 0;
254         struct ldap_table_config *configs[] = { table_config, base_table_config };
255
256         for (i = 0; i < ARRAY_LEN(configs); i++) {
257                 struct ast_variable *attribute;
258
259                 if (!configs[i]) {
260                         continue;
261                 }
262
263                 attribute = configs[i]->attributes;
264                 for (; attribute; attribute = attribute->next) {
265                         if (!strcasecmp(attribute_name, attribute->name)) {
266                                 return attribute->value;
267                         }
268                 }
269         }
270
271         return attribute_name;
272 }
273
274 /*! \brief Convert ldap attribute name to variable name 
275  *
276  * \note Should be locked before using it
277  */
278 static const char *convert_attribute_name_from_ldap(struct ldap_table_config *table_config,
279                                                     const char *attribute_name)
280 {
281         int i = 0;
282         struct ldap_table_config *configs[] = { table_config, base_table_config };
283
284         for (i = 0; i < ARRAY_LEN(configs); i++) {
285                 struct ast_variable *attribute;
286
287                 if (!configs[i]) {
288                         continue;
289                 }
290
291                 attribute = configs[i]->attributes;
292                 for (; attribute; attribute = attribute->next) {
293                         if (strcasecmp(attribute_name, attribute->value) == 0) {
294                                 return attribute->name;
295                         }
296                 }
297         }
298
299         return attribute_name;
300 }
301
302 /*! \brief Get variables from ldap entry attributes 
303  * \note Should be locked before using it
304  * \return a linked list of ast_variable variables.
305  */
306 static struct ast_variable *realtime_ldap_entry_to_var(struct ldap_table_config *table_config,
307         LDAPMessage *ldap_entry)
308 {
309         BerElement *ber = NULL;
310         struct ast_variable *var = NULL;
311         struct ast_variable *prev = NULL;
312         int is_delimited = 0;
313         int i = 0;
314         char *ldap_attribute_name;
315         struct berval *value;
316         int pos = 0;
317
318         ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
319
320         while (ldap_attribute_name) {
321                 struct berval **values = NULL;
322                 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
323                 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
324
325                 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name); /* these are freed at the end */
326                 if (values) {
327                         struct berval **v;
328                         char *valptr;
329
330                         for (v = values; *v; v++) {
331                                 value = *v;
332                                 valptr = value->bv_val;
333                                 ast_debug(2, "LINE(%d) attribute_name: %s LDAP value: %s\n", __LINE__, attribute_name, valptr);
334                                 if (is_realmed_password_attribute) {
335                                         if (!strncasecmp(valptr, "{md5}", 5)) {
336                                                 valptr += 5;
337                                         }
338                                         ast_debug(2, "md5: %s\n", valptr);
339                                 }
340                                 if (valptr) {
341                                         /* ok, so looping through all delimited values except the last one (not, last character is not delimited...) */
342                                         if (is_delimited) {
343                                                 i = 0;
344                                                 pos = 0;
345                                                 while (!ast_strlen_zero(valptr + i)) {
346                                                         if (valptr[i] == ';') {
347                                                                 valptr[i] = '\0';
348                                                                 if (prev) {
349                                                                         prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
350                                                                         if (prev->next) {
351                                                                                 prev = prev->next;
352                                                                         }
353                                                                 } else {
354                                                                         prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
355                                                                 }
356                                                                 pos = i + 1;
357                                                         }
358                                                         i++;
359                                                 }
360                                         }
361                                         /* for the last delimited value or if the value is not delimited: */
362                                         if (prev) {
363                                                 prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
364                                                 if (prev->next) {
365                                                         prev = prev->next;
366                                                 }
367                                         } else {
368                                                 prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
369                                         }
370                                 }
371                         }
372                         ldap_value_free_len(values);
373                 }
374                 ldap_memfree(ldap_attribute_name);
375                 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
376         }
377         ber_free(ber, 0);
378
379         return var;
380 }
381
382 /*! \brief Get variables from ldap entry attributes - Should be locked before using it
383  *
384  * The results are freed outside this function so is the \a vars array.
385  *      
386  * \return \a vars - an array of ast_variable variables terminated with a null.
387  */
388 static struct ast_variable **realtime_ldap_result_to_vars(struct ldap_table_config *table_config,
389         LDAPMessage *ldap_result_msg, unsigned int *entries_count_ptr)
390 {
391         struct ast_variable **vars;
392         int i = 0;
393         int tot_count = 0;
394         int entry_index = 0;
395         LDAPMessage *ldap_entry = NULL;
396         BerElement *ber = NULL;
397         struct ast_variable *var = NULL;
398         struct ast_variable *prev = NULL;
399         int is_delimited = 0;
400         char *delim_value = NULL;
401         int delim_tot_count = 0;
402         int delim_count = 0;
403
404         /* \breif First find the total count
405          */
406         ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
407
408         for (tot_count = 0; ldap_entry; tot_count++) { 
409                 struct ast_variable *tmp = realtime_ldap_entry_to_var(table_config, ldap_entry);
410                 tot_count += semicolon_count_var(tmp);
411                 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
412                 ast_variables_destroy(tmp);
413         }
414
415         if (entries_count_ptr) {
416                 *entries_count_ptr = tot_count;
417         }
418
419         /*! \note Now that we have the total count we allocate space and create the variables
420          * Remember that each element in vars is a linked list that points to realtime variable.
421          * If the we are dealing with a static realtime variable we create a new element in the \a vars array for each delimited
422          * value in \a variable_value; otherwise, we keep \a vars static and increase the length of the linked list of variables in the array element.
423          * This memory must be freed outside of this function.
424          */
425         vars = ast_calloc(sizeof(struct ast_variable *), tot_count + 1);
426
427         ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
428
429         i = 0;
430
431         /* \brief For each static realtime variable we may create several entries in the \a vars array if it's delimited
432          */
433         for (entry_index = 0; ldap_entry; ) {
434                 int pos = 0;
435                 delim_value = NULL;
436                 delim_tot_count = 0;
437                 delim_count = 0;
438
439                 do { /* while delim_count */
440
441                         /* Starting new static var */
442                         char *ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
443                         struct berval *value;
444                         while (ldap_attribute_name) {
445                                 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
446                                 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
447                                 struct berval **values = NULL;
448
449                                 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name);
450                                 if (values) {
451                                         struct berval **v;
452                                         char *valptr;
453
454                                         for (v = values; *v; v++) {
455                                                 value = *v;
456                                                 valptr = value->bv_val;
457                                                 if (is_realmed_password_attribute) {
458                                                         if (strncasecmp(valptr, "{md5}", 5) == 0) {
459                                                                 valptr += 5;
460                                                         }
461                                                         ast_debug(2, "md5: %s\n", valptr);
462                                                 }
463                                                 if (valptr) {
464                                                         if (delim_value == NULL && !is_realmed_password_attribute
465                                                                 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0)) {
466
467                                                                 delim_value = ast_strdup(valptr);
468
469                                                                 if ((delim_tot_count = semicolon_count_str(delim_value)) > 0) {
470                                                                         ast_debug(4, "LINE(%d) is delimited %d times: %s\n", __LINE__, delim_tot_count, delim_value);
471                                                                         is_delimited = 1;
472                                                                 }
473                                                         }
474
475                                                         if (is_delimited != 0 && !is_realmed_password_attribute
476                                                                 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0) ) {
477                                                                 /* for non-Static RealTime, first */
478
479                                                                 for (i = pos; !ast_strlen_zero(valptr + i); i++) {
480                                                                         ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
481                                                                         if (delim_value[i] == ';') {
482                                                                                 delim_value[i] = '\0';
483
484                                                                                 ast_debug(2, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
485
486                                                                                 if (prev) {
487                                                                                         prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
488                                                                                         if (prev->next) {
489                                                                                                 prev = prev->next;
490                                                                                         }
491                                                                                 } else {
492                                                                                         prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
493                                                                                 }
494                                                                                 pos = i + 1;
495
496                                                                                 if (static_table_config == table_config) {
497                                                                                         break;
498                                                                                 }
499                                                                         }
500                                                                 }
501                                                                 if (ast_strlen_zero(valptr + i)) {
502                                                                         ast_debug(4, "LINE(%d) DELIM pos: %d i: %d delim_count: %d\n", __LINE__, pos, i, delim_count);
503                                                                         /* Last delimited value */
504                                                                         ast_debug(4, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
505                                                                         if (prev) {
506                                                                                 prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
507                                                                                 if (prev->next) {
508                                                                                         prev = prev->next;
509                                                                                 }
510                                                                         } else {
511                                                                                 prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
512                                                                         }
513                                                                         /* Remembering to free memory */
514                                                                         is_delimited = 0;
515                                                                         pos = 0;
516                                                                 }
517                                                                 ast_free(delim_value);
518                                                                 delim_value = NULL;
519
520                                                                 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
521                                                         } else {
522                                                                 /* not delimited */
523                                                                 if (delim_value) {
524                                                                         ast_free(delim_value);
525                                                                         delim_value = NULL;
526                                                                 }
527                                                                 ast_debug(2, "LINE(%d) attribute_name: %s value: %s\n", __LINE__, attribute_name, valptr);
528
529                                                                 if (prev) {
530                                                                         prev->next = ast_variable_new(attribute_name, valptr, table_config->table_name);
531                                                                         if (prev->next) {
532                                                                                 prev = prev->next;
533                                                                         }
534                                                                 } else {
535                                                                         prev = var = ast_variable_new(attribute_name, valptr, table_config->table_name);
536                                                                 }
537                                                         }
538                                                 }
539                                         } /*!< for (v = values; *v; v++) */
540                                         ldap_value_free_len(values);
541                                 }/*!< if (values) */
542                                 ldap_memfree(ldap_attribute_name);
543                                 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
544                         } /*!< while (ldap_attribute_name) */
545                         ber_free(ber, 0);
546                         if (static_table_config == table_config) {
547                                 if (option_debug > 2) {
548                                         const struct ast_variable *tmpdebug = variable_named(var, "variable_name");
549                                         const struct ast_variable *tmpdebug2 = variable_named(var, "variable_value");
550                                         if (tmpdebug && tmpdebug2) {
551                                                 ast_debug(3, "LINE(%d) Added to vars - %s = %s\n", __LINE__, tmpdebug->value, tmpdebug2->value);
552                                         }
553                                 }
554                                 vars[entry_index++] = var;
555                                 prev = NULL;
556                         }
557
558                         delim_count++;
559                 } while (delim_count <= delim_tot_count && static_table_config == table_config);
560
561                 if (static_table_config != table_config) {
562                         ast_debug(3, "LINE(%d) Added to vars - non static\n", __LINE__);
563
564                         vars[entry_index++] = var;
565                         prev = NULL;
566                 }
567                 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
568         } /*!< end for loop over ldap_entry */
569
570         return vars;
571 }
572
573
574 /*! \brief Check if we have a connection error
575  */
576 static int is_ldap_connect_error(int err)
577 {
578         return (err == LDAP_SERVER_DOWN || err == LDAP_TIMEOUT || err == LDAP_CONNECT_ERROR);
579 }
580
581 /*! \brief Get LDAP entry by dn and return attributes as variables
582  *
583  * Should be locked before using it 
584  *
585  * This is used for setting the default values of an object
586  * i.e., with accountBaseDN
587 */
588 static struct ast_variable *ldap_loadentry(struct ldap_table_config *table_config,
589                                            const char *dn)
590 {
591         if (!table_config) {
592                 ast_log(LOG_ERROR, "No table config\n");
593                 return NULL;
594         } else {
595                 struct ast_variable **vars = NULL;
596                 struct ast_variable *var = NULL;
597                 int result = -1;
598                 LDAPMessage *ldap_result_msg = NULL;
599                 int tries = 0;
600
601                 ast_debug(2, "ldap_loadentry dn=%s\n", dn);
602
603                 do {
604                         result = ldap_search_ext_s(ldapConn, dn, LDAP_SCOPE_BASE,
605                                            "(objectclass=*)", NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &ldap_result_msg);
606                         if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
607                                 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
608                                 tries++;
609                                 if (tries < 3) {
610                                         usleep(500000L * tries);
611                                         if (ldapConn) {
612                                                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
613                                                 ldapConn = NULL;
614                                         }
615                                         if (!ldap_reconnect()) {
616                                                 break;
617                                         }
618                                 }
619                         }
620                 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
621
622                 if (result != LDAP_SUCCESS) {
623                         ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
624                         ast_debug(2, "dn=%s\n", dn);
625                         ast_mutex_unlock(&ldap_lock);
626                         return NULL;
627                 } else {
628                         int num_entry = 0;
629                         unsigned int *entries_count_ptr = NULL; /*!< not using this */
630
631                         if ((num_entry = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
632                                 ast_debug(3, "num_entry: %d\n", num_entry);
633
634                                 vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
635                                 if (num_entry > 1) {
636                                         ast_log(LOG_NOTICE, "More than one entry for dn=%s. Take only 1st one\n", dn);
637                                 }
638                         } else {
639                                 ast_debug(2, "Could not find any entry dn=%s.\n", dn);
640                         }
641                 }
642                 ldap_msgfree(ldap_result_msg);
643
644                 /* Chopping \a vars down to one variable */
645                 if (vars != NULL) {
646                         struct ast_variable **p = vars;
647
648                         /* Only take the first one. */
649                         var = *vars;
650
651                         /* Destroy the rest. */
652                         while (*++p) {
653                                 ast_variables_destroy(*p);
654                         }
655                         ast_free(vars);
656                 }
657
658                 return var;
659         }
660 }
661
662 /*! \note caller should free returned pointer
663  */
664 static char *substituted(struct ast_channel *channel, const char *string)
665 {
666 #define MAXRESULT       2048
667         char *ret_string = NULL;
668
669         if (!ast_strlen_zero(string)) {
670                 ret_string = ast_calloc(1, MAXRESULT);
671                 pbx_substitute_variables_helper(channel, string, ret_string, MAXRESULT - 1);
672         }
673         ast_debug(2, "substituted: string: '%s' => '%s' \n", string, ret_string);
674         return ret_string;
675 }
676
677 /*! \note caller should free returned pointer
678  */
679 static char *cleaned_basedn(struct ast_channel *channel, const char *basedn)
680 {
681         char *cbasedn = NULL;
682         if (basedn) {
683                 char *p = NULL;
684                 cbasedn = substituted(channel, basedn);
685                 if (*cbasedn == '"') {
686                         cbasedn++;
687                         if (!ast_strlen_zero(cbasedn)) {
688                                 int len = strlen(cbasedn);
689                                 if (cbasedn[len - 1] == '"')
690                                         cbasedn[len - 1] = '\0';
691
692                         }
693                 }
694                 p = cbasedn;
695                 while (*p) {
696                         if (*p == '|')
697                                 *p = ',';
698                         p++;
699                 }
700         }
701         ast_debug(2, "basedn: '%s' => '%s' \n", basedn, cbasedn);
702         return cbasedn;
703 }
704
705 /*! \brief Replace \<search\> by \<by\> in string. 
706  * \note No check is done on string allocated size !
707  */
708 static int replace_string_in_string(char *string, const char *search, const char *by)
709 {
710         int search_len = strlen(search);
711         int by_len = strlen(by);
712         int replaced = 0;
713         char *p = strstr(string, search);
714
715         if (p) {
716                 replaced = 1;
717                 while (p) {
718                         if (by_len == search_len) {
719                                 memcpy(p, by, by_len);
720                         } else {
721                                 memmove(p + by_len, p + search_len, strlen(p + search_len) + 1);
722                                 memcpy(p, by, by_len);
723                         }
724                         p = strstr(p + by_len, search);
725                 }
726         }
727         return replaced;
728 }
729
730 /*! \brief Append a name=value filter string. The filter string can grow. 
731  */
732 static void append_var_and_value_to_filter(struct ast_str **filter,
733         struct ldap_table_config *table_config,
734         const char *name, const char *value)
735 {
736         char *new_name = NULL;
737         char *new_value = NULL;
738         char *like_pos = strstr(name, " LIKE");
739
740         ast_debug(2, "name='%s' value='%s'\n", name, value);
741
742         if (like_pos) {
743                 int len = like_pos - name;
744
745                 name = new_name = ast_strdupa(name);
746                 new_name[len] = '\0';
747                 value = new_value = ast_strdupa(value);
748                 replace_string_in_string(new_value, "\\_", "_");
749                 replace_string_in_string(new_value, "%", "*");
750         }
751
752         name = convert_attribute_name_to_ldap(table_config, name);
753
754         ast_str_append(filter, 0, "(%s=%s)", name, value);
755 }
756
757 /*! \brief LDAP base function 
758  * \return a null terminated array of ast_variable (one per entry) or NULL if no entry is found or if an error occured
759  * caller should free the returned array and ast_variables
760  * \param entries_count_ptr is a pointer to found entries count (can be NULL)
761  * \param basedn is the base DN
762  * \param table_name is the table_name (used dor attribute convertion and additional filter)
763  * \param fields contains list of pairs name/value
764 */
765 static struct ast_variable **realtime_ldap_base_ap(unsigned int *entries_count_ptr,
766         const char *basedn, const char *table_name, const struct ast_variable *fields)
767 {
768         struct ast_variable **vars = NULL;
769         const struct ast_variable *field = fields;
770         struct ldap_table_config *table_config = NULL;
771         char *clean_basedn = cleaned_basedn(NULL, basedn);
772         struct ast_str *filter = NULL;
773         int tries = 0;
774         int result = 0;
775         LDAPMessage *ldap_result_msg = NULL;
776
777         if (!table_name) {
778                 ast_log(LOG_ERROR, "No table_name specified.\n");
779                 ast_free(clean_basedn);
780                 return NULL;
781         } 
782
783         if (!(filter = ast_str_create(80))) {
784                 ast_log(LOG_ERROR, "Can't initialize data structures.n");
785                 ast_free(clean_basedn);
786                 return NULL;
787         }
788
789         if (!field) {
790                 ast_log(LOG_ERROR, "Realtime retrieval requires at least 1 parameter"
791                         " and 1 value to search on.\n");
792                 ast_free(filter);
793                 ast_free(clean_basedn);
794                 return NULL;
795         }
796
797         ast_mutex_lock(&ldap_lock);
798
799         /* We now have our complete statement; Lets connect to the server and execute it.  */
800         if (!ldap_reconnect()) {
801                 ast_mutex_unlock(&ldap_lock);
802                 ast_free(filter);
803                 ast_free(clean_basedn);
804                 return NULL;
805         }
806
807         table_config = table_config_for_table_name(table_name);
808         if (!table_config) {
809                 ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
810                 ast_mutex_unlock(&ldap_lock);
811                 ast_free(filter);
812                 ast_free(clean_basedn);
813                 return NULL;
814         }
815
816         ast_str_append(&filter, 0, "(&");
817
818         if (table_config && table_config->additional_filter) {
819                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
820         }
821         if (table_config != base_table_config && base_table_config && 
822                 base_table_config->additional_filter) {
823                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
824         }
825
826         /* Create the first part of the query using the first parameter/value pairs we just extracted.
827          * If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat
828          */
829
830         append_var_and_value_to_filter(&filter, table_config, field->name, field->value);
831         while ((field = field->next)) {
832                 append_var_and_value_to_filter(&filter, table_config, field->name, field->value);
833         }
834         ast_str_append(&filter, 0, ")");
835
836         do {
837                 /* freeing ldap_result further down */
838                 result = ldap_search_ext_s(ldapConn, clean_basedn,
839                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
840                                   &ldap_result_msg);
841                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
842                         ast_debug(1, "Failed to query directory. Try %d/10\n", tries + 1);
843                         if (++tries < 10) {
844                                 usleep(1);
845                                 if (ldapConn) {
846                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
847                                         ldapConn = NULL;
848                                 }
849                                 if (!ldap_reconnect()) {
850                                         break;
851                                 }
852                         }
853                 }
854         } while (result != LDAP_SUCCESS && tries < 10 && is_ldap_connect_error(result));
855
856         if (result != LDAP_SUCCESS) {
857                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
858                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
859         } else {
860                 /* this is where we create the variables from the search result 
861                  * freeing this \a vars outside this function */
862                 if (ldap_count_entries(ldapConn, ldap_result_msg) > 0) {
863                         /* is this a static var or some other? they are handled different for delimited values */
864                         vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
865                 } else {
866                         ast_debug(1, "Could not find any entry matching %s in base dn %s.\n", ast_str_buffer(filter), clean_basedn);
867                 }
868
869                 ldap_msgfree(ldap_result_msg);
870
871                 /*! \TODO get the default variables from the accountBaseDN, not implemented with delimited values
872                  */
873                 if (vars) {
874                         struct ast_variable **p = vars;
875                         while (*p) {
876                                 struct ast_variable *append_var = NULL;
877                                 struct ast_variable *tmp = *p;
878                                 while (tmp) {
879                                         if (strcasecmp(tmp->name, "accountBaseDN") == 0) {
880                                                 /* Get the variable to compare with for the defaults */
881                                                 struct ast_variable *base_var = ldap_loadentry(table_config, tmp->value);
882                                                 
883                                                 while (base_var) {
884                                                         struct ast_variable *next = base_var->next;
885                                                         struct ast_variable *test_var = *p;
886                                                         int base_var_found = 0;
887
888                                                         /* run throught the default values and fill it inn if it is missing */
889                                                         while (test_var) {
890                                                                 if (strcasecmp(test_var->name, base_var->name) == 0) {
891                                                                         base_var_found = 1;
892                                                                         break;
893                                                                 } else {
894                                                                         test_var = test_var->next;
895                                                                 }
896                                                         }
897                                                         if (base_var_found) {
898                                                                 base_var->next = NULL;
899                                                                 ast_variables_destroy(base_var);
900                                                                 base_var = next;
901                                                         } else {
902                                                                 /*!
903                                                                  * \todo XXX The interactions with base_var and append_var may
904                                                                  * cause a memory leak of base_var nodes.  Also the append_var
905                                                                  * list and base_var list may get cross linked.
906                                                                  */
907                                                                 if (append_var) {
908                                                                         base_var->next = append_var;
909                                                                 } else {
910                                                                         base_var->next = NULL;
911                                                                 }
912                                                                 append_var = base_var;
913                                                                 base_var = next;
914                                                         }
915                                                 }
916                                         }
917                                         if (!tmp->next && append_var) {
918                                                 tmp->next = append_var;
919                                                 tmp = NULL;
920                                         } else {
921                                                 tmp = tmp->next;
922                                         }
923                                 }
924                                 p++;
925                         }
926                 }
927         }
928
929         if (filter) {
930                 ast_free(filter);
931         }
932
933         if (clean_basedn) {
934                 ast_free(clean_basedn);
935         }
936
937         ast_mutex_unlock(&ldap_lock);
938
939         return vars;
940 }
941
942 static struct ast_variable *realtime_arguments_to_fields(va_list ap)
943 {
944         struct ast_variable *fields = NULL;
945         const char *newparam, *newval;
946
947         while ((newparam = va_arg(ap, const char *))) {
948                 struct ast_variable *field;
949
950                 newval = va_arg(ap, const char *);
951                 if (!(field = ast_variable_new(newparam, newval, ""))) {
952                         ast_variables_destroy(fields);
953                         return NULL;
954                 }
955
956                 field->next = fields;
957                 fields = field;
958         }
959
960         return fields;
961 }
962
963 /*! \brief same as realtime_ldap_base_ap but take variable arguments count list
964  */
965 static struct ast_variable **realtime_ldap_base(unsigned int *entries_count_ptr,
966         const char *basedn, const char *table_name, ...)
967 {
968         RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
969         struct ast_variable **vars = NULL;
970         va_list ap;
971
972         va_start(ap, table_name);
973         fields = realtime_arguments_to_fields(ap);
974         va_end(ap);
975
976         vars = realtime_ldap_base_ap(entries_count_ptr, basedn, table_name, fields);
977
978         return vars;
979 }
980
981 /*! \brief See Asterisk doc
982  *
983  * For Realtime Dynamic(i.e., switch, queues, and directory)
984  */
985 static struct ast_variable *realtime_ldap(const char *basedn,
986                                           const char *table_name, const struct ast_variable *fields)
987 {
988         struct ast_variable **vars = realtime_ldap_base_ap(NULL, basedn, table_name, fields);
989         struct ast_variable *var = NULL;
990
991         if (vars) {
992                 struct ast_variable *last_var = NULL;
993                 struct ast_variable **p = vars;
994
995                 /* Chain the vars array of lists into one list to return. */
996                 while (*p) {
997                         if (last_var) {
998                                 while (last_var->next) {
999                                         last_var = last_var->next;
1000                                 }
1001                                 last_var->next = *p;
1002                         } else {
1003                                 var = *p;
1004                                 last_var = var;
1005                         }
1006                         p++;
1007                 }
1008                 ast_free(vars);
1009         }
1010         return var;
1011 }
1012
1013 /*! \brief See Asterisk doc
1014  *
1015  * this function will be called for the switch statment if no match is found with the realtime_ldap function(i.e. it is a failover);
1016  * however, the ast_load_realtime wil match on wildcharacters also depending on what the mode is set to
1017  * this is an area of asterisk that could do with a lot of modification
1018  * I think this function returns Realtime dynamic objects
1019  */
1020 static struct ast_config *realtime_multi_ldap(const char *basedn,
1021       const char *table_name, const struct ast_variable *fields)
1022 {
1023         char *op;
1024         const char *initfield = NULL;
1025         struct ast_variable **vars =
1026                 realtime_ldap_base_ap(NULL, basedn, table_name, fields);
1027         struct ast_config *cfg = NULL;
1028
1029         if (!fields) {
1030             ast_log(LOG_WARNING, "realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
1031             return NULL;
1032         }
1033         initfield = ast_strdupa(fields->name);
1034         if ((op = strchr(initfield, ' '))) {
1035                 *op = '\0';
1036         }
1037
1038         if (vars) {
1039                 cfg = ast_config_new();
1040                 if (!cfg) {
1041                         ast_log(LOG_ERROR, "Unable to create a config!\n");
1042                 } else {
1043                         struct ast_variable **p = vars;
1044
1045                         while (*p) {
1046                                 struct ast_category *cat = NULL;
1047                                 cat = ast_category_new("", table_name, -1);
1048                                 if (!cat) {
1049                                         ast_log(LOG_ERROR, "Unable to create a new category!\n");
1050                                         break;
1051                                 } else {
1052                                         struct ast_variable *var = *p;
1053                                         while (var) {
1054                                                 struct ast_variable *next = var->next;
1055                                                 if (initfield && !strcmp(initfield, var->name)) {
1056                                                         ast_category_rename(cat, var->value);
1057                                                 }
1058                                                 var->next = NULL;
1059                                                 ast_variable_append(cat, var);
1060                                                 var = next;
1061                                         }
1062                                 }
1063                                 ast_category_append(cfg, cat);
1064                                 p++;
1065                         }
1066                 }
1067                 ast_free(vars);
1068         }
1069         return cfg;
1070
1071 }
1072
1073 /*! \brief Sorting alogrithm for qsort to find the order of the variables \a a and \a b
1074  * \param a pointer to category_and_metric struct
1075  * \param b pointer to category_and_metric struct
1076  *
1077  * \retval -1 for if b is greater
1078  * \retval 0 zero for equal
1079  * \retval 1 if a is greater
1080  */
1081 static int compare_categories(const void *a, const void *b)
1082 {
1083         const struct category_and_metric *as = a;
1084         const struct category_and_metric *bs = b;
1085
1086         if (as->metric < bs->metric) {
1087                 return -1;
1088         } else if (as->metric > bs->metric) {
1089                 return 1;
1090         } else if (as->metric == bs->metric && strcmp(as->name, bs->name) != 0) {
1091                 return strcmp(as->name, bs->name);
1092         } 
1093         /* if the metric and the category name is the same, we check the variable metric */
1094         if (as->var_metric < bs->var_metric) {
1095                 return -1;
1096         } else if (as->var_metric > bs->var_metric) {
1097                 return 1;
1098         }
1099
1100         return 0;
1101 }
1102
1103 /*! \brief See Asterisk Realtime Documentation
1104  *
1105  * This is for Static Realtime
1106  *      
1107  * load the configuration stuff for the .conf files
1108  * called on a reload
1109  */
1110 static struct ast_config *config_ldap(const char *basedn, const char *table_name,
1111         const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *sugg_incl, const char *who_asked)
1112 {
1113         unsigned int vars_count = 0;
1114         struct ast_variable **vars;
1115         int i = 0;
1116         struct ast_variable *new_v = NULL;
1117         struct ast_category *cur_cat = NULL;
1118         const char *last_category = NULL;
1119         int last_category_metric = 0;
1120         struct category_and_metric *categories;
1121         struct ast_variable **p;
1122
1123         if (ast_strlen_zero(file) || !strcasecmp(file, RES_CONFIG_LDAP_CONF)) {
1124                 ast_log(LOG_ERROR, "Missing configuration file: %s. Can't configure myself.\n", RES_CONFIG_LDAP_CONF);
1125                 return NULL;
1126         }
1127
1128         vars = realtime_ldap_base(&vars_count, basedn, table_name, "filename", file, "commented", "FALSE", NULL);
1129
1130         if (!vars) {
1131                 ast_log(LOG_WARNING, "Could not find config '%s' in directory.\n", file);
1132                 return NULL;
1133         }
1134
1135         /*! \note Since the items come back in random order, they need to be sorted
1136          * first, and since the data could easily exceed stack size, this is
1137          * allocated from the heap.
1138          */
1139         if (!(categories = ast_calloc(sizeof(*categories), vars_count))) {
1140                 return NULL;
1141         }
1142
1143         for (vars_count = 0, p = vars; *p; p++) {
1144                 struct ast_variable *category = variable_named(*p, "category");
1145                 struct ast_variable *cat_metric = variable_named(*p, "cat_metric");
1146                 struct ast_variable *var_name = variable_named(*p, "variable_name");
1147                 struct ast_variable *var_val = variable_named(*p, "variable_value");
1148                 struct ast_variable *var_metric = variable_named(*p, "var_metric");
1149                 struct ast_variable *dn = variable_named(*p, "dn");
1150
1151                 if (!category) {
1152                         ast_log(LOG_ERROR, "No category name in entry '%s'  for file '%s'.\n",
1153                                         (dn ? dn->value : "?"), file);
1154                 } else if (!cat_metric) {
1155                         ast_log(LOG_ERROR, "No category metric in entry '%s'(category: %s) for file '%s'.\n",
1156                                         (dn ? dn->value : "?"), category->value, file);
1157                 } else if (!var_metric) {
1158                         ast_log(LOG_ERROR, "No variable metric in entry '%s'(category: %s) for file '%s'.\n",
1159                                         (dn ? dn->value : "?"), category->value, file);
1160                 } else if (!var_name) {
1161                         ast_log(LOG_ERROR, "No variable name in entry '%s' (category: %s metric: %s) for file '%s'.\n",
1162                                         (dn ? dn->value : "?"), category->value,
1163                                         cat_metric->value, file);
1164                 } else if (!var_val) {
1165                         ast_log(LOG_ERROR, "No variable value in entry '%s' (category: %s metric: %s variable: %s) for file '%s'.\n",
1166                                         (dn ? dn->value : "?"), category->value,
1167                                         cat_metric->value, var_name->value, file);
1168                 } else {
1169                         categories[vars_count].name = category->value;
1170                         categories[vars_count].metric = atoi(cat_metric->value);
1171                         categories[vars_count].variable_name = var_name->value;
1172                         categories[vars_count].variable_value = var_val->value;
1173                         categories[vars_count].var_metric = atoi(var_metric->value);
1174                         vars_count++;
1175                 }
1176
1177                 ast_debug(3, "category: %s\n", category->value);
1178                 ast_debug(3, "var_name: %s\n", var_name->value);
1179                 ast_debug(3, "var_val: %s\n", var_val->value);
1180                 ast_debug(3, "cat_metric: %s\n", cat_metric->value);
1181
1182         }
1183
1184         qsort(categories, vars_count, sizeof(*categories), compare_categories);
1185
1186         for (i = 0; i < vars_count; i++) {
1187                 if (!strcmp(categories[i].variable_name, "#include")) {
1188                         struct ast_flags flags = { 0 };
1189                         if (!ast_config_internal_load(categories[i].variable_value, cfg, flags, "", who_asked)) {
1190                                 break;
1191                         }
1192                         continue;
1193                 }
1194
1195                 if (!last_category || strcmp(last_category, categories[i].name) ||
1196                         last_category_metric != categories[i].metric) {
1197
1198                         cur_cat = ast_category_new(categories[i].name, table_name, -1);
1199                         if (!cur_cat) {
1200                                 break;
1201                         }
1202                         last_category = categories[i].name;
1203                         last_category_metric = categories[i].metric;
1204                         ast_category_append(cfg, cur_cat);
1205                 }
1206
1207                 if (!(new_v = ast_variable_new(categories[i].variable_name, categories[i].variable_value, table_name))) {
1208                         break;
1209                 }
1210
1211                 ast_variable_append(cur_cat, new_v);
1212         }
1213
1214         ast_free(vars);
1215         ast_free(categories);
1216
1217         return cfg;
1218 }
1219
1220 /* \brief Function to update a set of values in ldap static mode
1221  */
1222 static int update_ldap(const char *basedn, const char *table_name, const char *attribute,
1223         const char *lookup, const struct ast_variable *fields)
1224 {
1225         int error = 0;
1226         LDAPMessage *ldap_entry = NULL;
1227         LDAPMod **ldap_mods;
1228         const char *newparam;
1229         const struct ast_variable *field = fields;
1230         char *dn;
1231         int num_entries = 0;
1232         int i = 0;
1233         int mods_size = 0;
1234         int mod_exists = 0;
1235         struct ldap_table_config *table_config = NULL;
1236         char *clean_basedn = NULL;
1237         struct ast_str *filter = NULL;
1238         int tries = 0;
1239         int result = 0;
1240         LDAPMessage *ldap_result_msg = NULL;
1241
1242         if (!table_name) {
1243                 ast_log(LOG_ERROR, "No table_name specified.\n");
1244                 return -1;
1245         } 
1246
1247         if (!(filter = ast_str_create(80))) {
1248                 return -1;
1249         }
1250
1251         if (!attribute || !lookup) {
1252                 ast_log(LOG_WARNING, "LINE(%d): search parameters are empty.\n", __LINE__);
1253                 return -1;
1254         }
1255         ast_mutex_lock(&ldap_lock);
1256
1257         /* We now have our complete statement; Lets connect to the server and execute it.  */
1258         if (!ldap_reconnect()) {
1259                 ast_mutex_unlock(&ldap_lock);
1260                 return -1;
1261         }
1262
1263         table_config = table_config_for_table_name(table_name);
1264         if (!table_config) {
1265                 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1266                 ast_mutex_unlock(&ldap_lock);
1267                 return -1;
1268         }
1269
1270         clean_basedn = cleaned_basedn(NULL, basedn);
1271
1272         /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1273         ast_str_append(&filter, 0, "(&");
1274         if (table_config && table_config->additional_filter) {
1275                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1276         }
1277         if (table_config != base_table_config && base_table_config && base_table_config->additional_filter) {
1278                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1279         }
1280         append_var_and_value_to_filter(&filter, table_config, attribute, lookup);
1281         ast_str_append(&filter, 0, ")");
1282
1283         /* Create the modification array with the parameter/value pairs we were given, 
1284          * if there are several parameters with the same name, we collect them into 
1285          * one parameter/value pair and delimit them with a semicolon */
1286         newparam = convert_attribute_name_to_ldap(table_config, field->name);
1287         if (!newparam) {
1288                 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1289                 return -1;
1290         }
1291
1292         mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1293         ldap_mods = ldap_memcalloc(sizeof(LDAPMod *), mods_size);
1294         ldap_mods[0] = ldap_memcalloc(1, sizeof(LDAPMod));
1295
1296         ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1297         ldap_mods[0]->mod_type = ldap_strdup(newparam);
1298
1299         ldap_mods[0]->mod_values = ast_calloc(sizeof(char *), 2);
1300         ldap_mods[0]->mod_values[0] = ldap_strdup(field->value);
1301
1302         while ((field = field->next)) {
1303                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1304                 mod_exists = 0;
1305
1306                 for (i = 0; i < mods_size - 1; i++) {
1307                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1308                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1309                                 ldap_mods[i]->mod_values[0] = ldap_memrealloc(ldap_mods[i]->mod_values[0], sizeof(char) * (strlen(ldap_mods[i]->mod_values[0]) + strlen(field->value) + 2));
1310                                 strcat(ldap_mods[i]->mod_values[0], ";");
1311                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1312                                 mod_exists = 1; 
1313                                 break;
1314                         }
1315                 }
1316
1317                 /* create new mod */
1318                 if (!mod_exists) {
1319                         mods_size++;
1320                         ldap_mods = ldap_memrealloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1321                         ldap_mods[mods_size - 1] = NULL;
1322                         
1323                         ldap_mods[mods_size - 2] = ldap_memcalloc(1, sizeof(LDAPMod));
1324
1325                         ldap_mods[mods_size - 2]->mod_type = ldap_memcalloc(sizeof(char), strlen(newparam) + 1);
1326                         strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1327
1328                         if (strlen(field->value) == 0) {
1329                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
1330                         } else {
1331                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1332
1333                                 ldap_mods[mods_size - 2]->mod_values = ldap_memcalloc(sizeof(char *), 2);
1334                                 ldap_mods[mods_size - 2]->mod_values[0] = ldap_memcalloc(sizeof(char), strlen(field->value) + 1);
1335                                 strcpy(ldap_mods[mods_size - 2]->mod_values[0], field->value);
1336                         }
1337                 }
1338         }
1339         /* freeing ldap_mods further down */
1340
1341         do {
1342                 /* freeing ldap_result further down */
1343                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1344                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1345                                   &ldap_result_msg);
1346                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1347                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1348                         tries++;
1349                         if (tries < 3) {
1350                                 usleep(500000L * tries);
1351                                 if (ldapConn) {
1352                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1353                                         ldapConn = NULL;
1354                                 }
1355                                 if (!ldap_reconnect())
1356                                         break;
1357                         }
1358                 }
1359         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1360
1361         if (result != LDAP_SUCCESS) {
1362                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1363                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1364
1365                 ast_mutex_unlock(&ldap_lock);
1366                 ast_free(filter);
1367                 ast_free(clean_basedn);
1368                 ldap_msgfree(ldap_result_msg);
1369                 ldap_mods_free(ldap_mods, 0);
1370                 return -1;
1371         }
1372         /* Ready to update */
1373         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1374                 ast_debug(3, "LINE(%d) Modifying %s=%s hits: %d\n", __LINE__, attribute, lookup, num_entries);
1375                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1376                         if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
1377                                 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1378                         } else {
1379                                 ast_debug(3, "LINE(%d) deleting %s \n", __LINE__, ldap_mods[i]->mod_type);
1380                         }
1381                 }
1382                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1383
1384                 for (i = 0; ldap_entry; i++) { 
1385                         dn = ldap_get_dn(ldapConn, ldap_entry);
1386                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1387                                 ast_log(LOG_ERROR, "Couldn't modify '%s'='%s', dn:%s because %s\n",
1388                                                 attribute, lookup, dn, ldap_err2string(error));
1389                         }
1390                         ldap_memfree(dn);
1391                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1392                 }
1393         }
1394
1395         ast_mutex_unlock(&ldap_lock);
1396         ast_free(filter);
1397         ast_free(clean_basedn);
1398         ldap_msgfree(ldap_result_msg);
1399         ldap_mods_free(ldap_mods, 0);
1400         return num_entries;
1401 }
1402
1403 static int update2_ldap(const char *basedn, const char *table_name, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
1404 {
1405         int error = 0;
1406         LDAPMessage *ldap_entry = NULL;
1407         LDAPMod **ldap_mods;
1408         const char *newparam;
1409         const struct ast_variable *field;
1410         char *dn;
1411         int num_entries = 0;
1412         int i = 0;
1413         int mods_size = 0;
1414         int mod_exists = 0;
1415         struct ldap_table_config *table_config = NULL;
1416         char *clean_basedn = NULL;
1417         struct ast_str *filter = NULL;
1418         int tries = 0;
1419         int result = 0;
1420         LDAPMessage *ldap_result_msg = NULL;
1421
1422         if (!table_name) {
1423                 ast_log(LOG_ERROR, "No table_name specified.\n");
1424                 return -1;
1425         } 
1426
1427         if (!(filter = ast_str_create(80))) {
1428                 return -1;
1429         }
1430
1431         ast_mutex_lock(&ldap_lock);
1432
1433         /* We now have our complete statement; Lets connect to the server and execute it.  */
1434         if (!ldap_reconnect()) {
1435                 ast_mutex_unlock(&ldap_lock);
1436                 ast_free(filter);
1437                 return -1;
1438         }
1439
1440         table_config = table_config_for_table_name(table_name);
1441         if (!table_config) {
1442                 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1443                 ast_mutex_unlock(&ldap_lock);
1444                 ast_free(filter);
1445                 return -1;
1446         }
1447
1448         clean_basedn = cleaned_basedn(NULL, basedn);
1449
1450         /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1451         ast_str_append(&filter, 0, "(&");
1452         if (table_config && table_config->additional_filter) {
1453                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1454         }
1455         if (table_config != base_table_config && base_table_config
1456                 && base_table_config->additional_filter) {
1457                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1458         }
1459
1460         /* Get multiple lookup keyfields and values */
1461         for (field = lookup_fields; field; field = field->next) {
1462                 append_var_and_value_to_filter(&filter, table_config, field->name, field->value);
1463         }
1464         ast_str_append(&filter, 0, ")");
1465
1466         /* Create the modification array with the parameter/value pairs we were given, 
1467          * if there are several parameters with the same name, we collect them into 
1468          * one parameter/value pair and delimit them with a semicolon */
1469         field = update_fields;
1470         newparam = convert_attribute_name_to_ldap(table_config, field->name);
1471         if (!newparam) {
1472                 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1473                 ast_free(filter);
1474                 ast_free(clean_basedn);
1475                 return -1;
1476         }
1477
1478         mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1479         ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1480         ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1481
1482         ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1483         ldap_mods[0]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1484         strcpy(ldap_mods[0]->mod_type, newparam);
1485
1486         ldap_mods[0]->mod_values = ast_calloc(sizeof(char), 2);
1487         ldap_mods[0]->mod_values[0] = ast_calloc(sizeof(char), strlen(field->value) + 1);
1488         strcpy(ldap_mods[0]->mod_values[0], field->value);
1489
1490         while ((field = field->next)) {
1491                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1492                 mod_exists = 0;
1493
1494                 for (i = 0; i < mods_size - 1; i++) {
1495                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1496                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1497                                 ldap_mods[i]->mod_values[0] = ast_realloc(ldap_mods[i]->mod_values[0], sizeof(char) * (strlen(ldap_mods[i]->mod_values[0]) + strlen(field->value) + 2));
1498                                 strcat(ldap_mods[i]->mod_values[0], ";");
1499                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1500                                 mod_exists = 1; 
1501                                 break;
1502                         }
1503                 }
1504
1505                 /* create new mod */
1506                 if (!mod_exists) {
1507                         mods_size++;
1508                         ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1509                         ldap_mods[mods_size - 1] = NULL;
1510                         ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1511
1512                         ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1513
1514                         ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1515                         strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1516
1517                         ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1518                         ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(field->value) + 1);
1519                         strcpy(ldap_mods[mods_size - 2]->mod_values[0], field->value);
1520                 }
1521         }
1522         /* freeing ldap_mods further down */
1523
1524         do {
1525                 /* freeing ldap_result further down */
1526                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1527                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1528                                   &ldap_result_msg);
1529                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1530                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1531                         tries++;
1532                         if (tries < 3) {
1533                                 usleep(500000L * tries);
1534                                 if (ldapConn) {
1535                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1536                                         ldapConn = NULL;
1537                                 }
1538                                 if (!ldap_reconnect()) {
1539                                         break;
1540                                 }
1541                         }
1542                 }
1543         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1544
1545         if (result != LDAP_SUCCESS) {
1546                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1547                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1548
1549                 ast_mutex_unlock(&ldap_lock);
1550                 ast_free(filter);
1551                 ast_free(clean_basedn);
1552                 ldap_msgfree(ldap_result_msg);
1553                 ldap_mods_free(ldap_mods, 0);
1554                 return -1;
1555         }
1556         /* Ready to update */
1557         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1558                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1559                         ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1560                 }
1561
1562                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1563
1564                 for (i = 0; ldap_entry; i++) {
1565                         dn = ldap_get_dn(ldapConn, ldap_entry);
1566                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1567                                 ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
1568                         }
1569                         ldap_memfree(dn);
1570                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1571                 }
1572         }
1573
1574         ast_mutex_unlock(&ldap_lock);
1575         if (filter) {
1576                 ast_free(filter);
1577         }
1578         if (clean_basedn) {
1579                 ast_free(clean_basedn);
1580         }
1581         ldap_msgfree(ldap_result_msg);
1582         ldap_mods_free(ldap_mods, 0);
1583         return num_entries;
1584 }
1585
1586 static struct ast_config_engine ldap_engine = {
1587         .name = "ldap",
1588         .load_func = config_ldap,
1589         .realtime_func = realtime_ldap,
1590         .realtime_multi_func = realtime_multi_ldap,
1591         .update_func = update_ldap,
1592         .update2_func = update2_ldap,
1593 };
1594
1595 /*!
1596  * \brief Load the module
1597  *
1598  * Module loading including tests for configuration or dependencies.
1599  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1600  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1601  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1602  * configuration file or other non-critical problem return 
1603  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1604  *
1605  * \todo Don't error or warn on a default install. If the config is
1606  * default we should not attempt to connect to a server. -lathama
1607  */
1608 static int load_module(void)
1609 {
1610         if (parse_config() < 0) {
1611                 ast_log(LOG_ERROR, "Cannot load LDAP RealTime driver.\n");
1612                 return 0;
1613         }
1614
1615         ast_mutex_lock(&ldap_lock);
1616
1617         if (!ldap_reconnect())  {
1618                 ast_log(LOG_WARNING, "Couldn't establish connection to LDAP directory. Check debug.\n");
1619         }
1620
1621         ast_config_engine_register(&ldap_engine);
1622         ast_verb(1, "LDAP RealTime driver loaded.\n");
1623         ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1624
1625         ast_mutex_unlock(&ldap_lock);
1626
1627         return 0;
1628 }
1629
1630 /*! \brief Unload Module
1631  *
1632  */
1633 static int unload_module(void)
1634 {
1635         /* Aquire control before doing anything to the module itself. */
1636         ast_mutex_lock(&ldap_lock);
1637
1638         table_configs_free();
1639
1640         if (ldapConn) {
1641                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1642                 ldapConn = NULL;
1643         }
1644         ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1645         ast_config_engine_deregister(&ldap_engine);
1646         ast_verb(1, "LDAP RealTime driver unloaded.\n");
1647
1648         /* Unlock so something else can destroy the lock. */
1649         ast_mutex_unlock(&ldap_lock);
1650
1651         return 0;
1652 }
1653
1654 /*! \breif Relod Module
1655  */
1656 static int reload(void)
1657 {
1658         /* Aquire control before doing anything to the module itself. */
1659         ast_mutex_lock(&ldap_lock);
1660
1661         if (ldapConn) {
1662                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1663                 ldapConn = NULL;
1664         }
1665
1666         if (parse_config() < 0) {
1667                 ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
1668                 ast_mutex_unlock(&ldap_lock);
1669                 return 0;
1670         }               
1671
1672         if (!ldap_reconnect())  {
1673                 ast_log(LOG_WARNING, "Couldn't establish connection to your directory server. Check debug.\n");
1674         }
1675
1676         ast_verb(2, "LDAP RealTime driver reloaded.\n");
1677
1678         /* Done reloading. Release lock so others can now use driver. */
1679         ast_mutex_unlock(&ldap_lock);
1680
1681         return 0;
1682 }
1683
1684 /*! \brief parse the configuration file
1685  */
1686 static int parse_config(void)
1687 {
1688         struct ast_config *config;
1689         struct ast_flags config_flags = {0};
1690         const char *s, *host;
1691         int port;
1692         char *category_name = NULL;
1693
1694         /* Make sure that global variables are reset */
1695         url[0] = '\0';
1696         user[0] = '\0';
1697         pass[0] = '\0';
1698         base_distinguished_name[0] = '\0';
1699         version = 3;
1700
1701         config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
1702         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1703                 ast_log(LOG_ERROR, "Cannot load configuration file: %s\n", RES_CONFIG_LDAP_CONF);
1704                 return -1;
1705         }
1706
1707         if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
1708                 ast_log(LOG_NOTICE, "No directory user found, anonymous binding as default.\n");
1709                 user[0] = '\0';
1710         } else {
1711                 ast_copy_string(user, s, sizeof(user));
1712         }
1713
1714         if (!ast_strlen_zero(user)) {
1715                 if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
1716                         ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
1717                         ast_copy_string(pass, "asterisk", sizeof(pass));
1718                 } else {
1719                         ast_copy_string(pass, s, sizeof(pass));
1720                 }
1721         }
1722
1723         /* URL is preferred, use host and port if not found */
1724         if ((s = ast_variable_retrieve(config, "_general", "url"))) {
1725                 ast_copy_string(url, s, sizeof(url));
1726         } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
1727                 if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
1728                         ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
1729                         port = 389;
1730                 }
1731
1732                 snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
1733         } else {
1734                 ast_log(LOG_ERROR, "No directory URL or host found.\n");
1735                 ast_config_destroy(config);
1736                 return -1;
1737         }
1738
1739         if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
1740                 ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
1741                 ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
1742         } else 
1743                 ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
1744
1745         if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
1746                 ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
1747         } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
1748                 ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
1749                 version = 3;
1750         }
1751
1752         table_configs_free();
1753
1754         while ((category_name = ast_category_browse(config, category_name))) {
1755                 int is_general = (strcasecmp(category_name, "_general") == 0);
1756                 int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
1757                 struct ast_variable *var = ast_variable_browse(config, category_name);
1758                 
1759                 if (var) {
1760                         struct ldap_table_config *table_config =
1761                                 table_config_for_table_name(category_name);
1762                         if (!table_config) {
1763                                 table_config = table_config_new(category_name);
1764                                 AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
1765                                 if (is_general)
1766                                         base_table_config = table_config;
1767                                 if (is_config)
1768                                         static_table_config = table_config;
1769                         }
1770                         for (; var; var = var->next) {
1771                                 if (!strcasecmp(var->name, "additionalFilter")) {
1772                                         table_config->additional_filter = ast_strdup(var->value);
1773                                 } else {
1774                                         ldap_table_config_add_attribute(table_config, var->name, var->value);
1775                                 }
1776                         }
1777                 }
1778         }
1779
1780         ast_config_destroy(config);
1781
1782         return 1;
1783 }
1784
1785 /*! \note ldap_lock should have been locked before calling this function. */
1786 static int ldap_reconnect(void)
1787 {
1788         int bind_result = 0;
1789         struct berval cred;
1790
1791         if (ldapConn) {
1792                 ast_debug(2, "Everything seems fine.\n");
1793                 return 1;
1794         }
1795
1796         if (ast_strlen_zero(url)) {
1797                 ast_log(LOG_ERROR, "Not enough parameters to connect to ldap directory\n");
1798                 return 0;
1799         }
1800
1801         if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
1802                 ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
1803                 return 0;
1804         }
1805
1806         if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
1807                 ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
1808         }
1809
1810         if (!ast_strlen_zero(user)) {
1811                 ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
1812                 cred.bv_val = (char *) pass;
1813                 cred.bv_len = strlen(pass);
1814                 bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1815         } else {
1816                 ast_debug(2, "bind %s anonymously\n", url);
1817                 cred.bv_val = NULL;
1818                 cred.bv_len = 0;
1819                 bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1820         }
1821         if (bind_result == LDAP_SUCCESS) {
1822                 ast_debug(2, "Successfully connected to directory.\n");
1823                 connect_time = time(NULL);
1824                 return 1;
1825         } else {
1826                 ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
1827                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1828                 ldapConn = NULL;
1829                 return 0;
1830         }
1831 }
1832
1833 /*! \brief Realtime Status
1834  *
1835  */
1836 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1837 {
1838         char status[256];
1839         char credentials[100] = "";
1840         char buf[362]; /* 256+100+" for "+NULL */
1841         int ctimesec = time(NULL) - connect_time;
1842
1843         switch (cmd) {
1844         case CLI_INIT:
1845                 e->command = "realtime show ldap status";
1846                 e->usage =
1847                         "Usage: realtime show ldap status\n"
1848                         "              Shows connection information for the LDAP RealTime driver\n";
1849                 return NULL;
1850         case CLI_GENERATE:
1851                 return NULL;
1852         }
1853
1854         if (!ldapConn)
1855                 return CLI_FAILURE;
1856
1857         if (!ast_strlen_zero(url)) 
1858                 snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
1859
1860         if (!ast_strlen_zero(user))
1861                 snprintf(credentials, sizeof(credentials), " with username %s", user);
1862
1863         snprintf(buf, sizeof(buf), "%s%s for ", status, credentials);
1864         ast_cli_print_timestr_fromseconds(a->fd, ctimesec, buf);
1865
1866         return CLI_SUCCESS;
1867 }
1868
1869 /*! \brief Module Information
1870  *
1871  */
1872 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "LDAP realtime interface",
1873         .support_level = AST_MODULE_SUPPORT_EXTENDED,
1874         .load = load_module,
1875         .unload = unload_module,
1876         .reload = reload,
1877         .load_pri = AST_MODPRI_REALTIME_DRIVER,
1878 );