res_config_ldap: Fix erroneous LDAP_MOD_REPLACE in LDAP modify
[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         ldap_mods[0]->mod_type = ldap_strdup(newparam);
1296
1297         if (strlen(field->value) == 0) {
1298                 ldap_mods[0]->mod_op = LDAP_MOD_DELETE;
1299         } else {
1300                 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1301                 ldap_mods[0]->mod_values = ast_calloc(sizeof(char *), 2);
1302                 ldap_mods[0]->mod_values[0] = ldap_strdup(field->value);
1303         }
1304
1305         while ((field = field->next)) {
1306                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1307                 mod_exists = 0;
1308
1309                 for (i = 0; i < mods_size - 1; i++) {
1310                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1311                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1312                                 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));
1313                                 strcat(ldap_mods[i]->mod_values[0], ";");
1314                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1315                                 mod_exists = 1; 
1316                                 break;
1317                         }
1318                 }
1319
1320                 /* create new mod */
1321                 if (!mod_exists) {
1322                         mods_size++;
1323                         ldap_mods = ldap_memrealloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1324                         ldap_mods[mods_size - 1] = NULL;
1325                         
1326                         ldap_mods[mods_size - 2] = ldap_memcalloc(1, sizeof(LDAPMod));
1327
1328                         ldap_mods[mods_size - 2]->mod_type = ldap_memcalloc(sizeof(char), strlen(newparam) + 1);
1329                         strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1330
1331                         if (strlen(field->value) == 0) {
1332                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
1333                         } else {
1334                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1335
1336                                 ldap_mods[mods_size - 2]->mod_values = ldap_memcalloc(sizeof(char *), 2);
1337                                 ldap_mods[mods_size - 2]->mod_values[0] = ldap_memcalloc(sizeof(char), strlen(field->value) + 1);
1338                                 strcpy(ldap_mods[mods_size - 2]->mod_values[0], field->value);
1339                         }
1340                 }
1341         }
1342         /* freeing ldap_mods further down */
1343
1344         do {
1345                 /* freeing ldap_result further down */
1346                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1347                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1348                                   &ldap_result_msg);
1349                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1350                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1351                         tries++;
1352                         if (tries < 3) {
1353                                 usleep(500000L * tries);
1354                                 if (ldapConn) {
1355                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1356                                         ldapConn = NULL;
1357                                 }
1358                                 if (!ldap_reconnect())
1359                                         break;
1360                         }
1361                 }
1362         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1363
1364         if (result != LDAP_SUCCESS) {
1365                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1366                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1367
1368                 ast_mutex_unlock(&ldap_lock);
1369                 ast_free(filter);
1370                 ast_free(clean_basedn);
1371                 ldap_msgfree(ldap_result_msg);
1372                 ldap_mods_free(ldap_mods, 0);
1373                 return -1;
1374         }
1375         /* Ready to update */
1376         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1377                 ast_debug(3, "LINE(%d) Modifying %s=%s hits: %d\n", __LINE__, attribute, lookup, num_entries);
1378                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1379                         if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
1380                                 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1381                         } else {
1382                                 ast_debug(3, "LINE(%d) deleting %s \n", __LINE__, ldap_mods[i]->mod_type);
1383                         }
1384                 }
1385                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1386
1387                 for (i = 0; ldap_entry; i++) { 
1388                         dn = ldap_get_dn(ldapConn, ldap_entry);
1389                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1390                                 ast_log(LOG_ERROR, "Couldn't modify '%s'='%s', dn:%s because %s\n",
1391                                                 attribute, lookup, dn, ldap_err2string(error));
1392                         }
1393                         ldap_memfree(dn);
1394                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1395                 }
1396         }
1397
1398         ast_mutex_unlock(&ldap_lock);
1399         ast_free(filter);
1400         ast_free(clean_basedn);
1401         ldap_msgfree(ldap_result_msg);
1402         ldap_mods_free(ldap_mods, 0);
1403         return num_entries;
1404 }
1405
1406 static int update2_ldap(const char *basedn, const char *table_name, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
1407 {
1408         int error = 0;
1409         LDAPMessage *ldap_entry = NULL;
1410         LDAPMod **ldap_mods;
1411         const char *newparam;
1412         const struct ast_variable *field;
1413         char *dn;
1414         int num_entries = 0;
1415         int i = 0;
1416         int mods_size = 0;
1417         int mod_exists = 0;
1418         struct ldap_table_config *table_config = NULL;
1419         char *clean_basedn = NULL;
1420         struct ast_str *filter = NULL;
1421         int tries = 0;
1422         int result = 0;
1423         LDAPMessage *ldap_result_msg = NULL;
1424
1425         if (!table_name) {
1426                 ast_log(LOG_ERROR, "No table_name specified.\n");
1427                 return -1;
1428         } 
1429
1430         if (!(filter = ast_str_create(80))) {
1431                 return -1;
1432         }
1433
1434         ast_mutex_lock(&ldap_lock);
1435
1436         /* We now have our complete statement; Lets connect to the server and execute it.  */
1437         if (!ldap_reconnect()) {
1438                 ast_mutex_unlock(&ldap_lock);
1439                 ast_free(filter);
1440                 return -1;
1441         }
1442
1443         table_config = table_config_for_table_name(table_name);
1444         if (!table_config) {
1445                 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1446                 ast_mutex_unlock(&ldap_lock);
1447                 ast_free(filter);
1448                 return -1;
1449         }
1450
1451         clean_basedn = cleaned_basedn(NULL, basedn);
1452
1453         /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1454         ast_str_append(&filter, 0, "(&");
1455         if (table_config && table_config->additional_filter) {
1456                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1457         }
1458         if (table_config != base_table_config && base_table_config
1459                 && base_table_config->additional_filter) {
1460                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1461         }
1462
1463         /* Get multiple lookup keyfields and values */
1464         for (field = lookup_fields; field; field = field->next) {
1465                 append_var_and_value_to_filter(&filter, table_config, field->name, field->value);
1466         }
1467         ast_str_append(&filter, 0, ")");
1468
1469         /* Create the modification array with the parameter/value pairs we were given, 
1470          * if there are several parameters with the same name, we collect them into 
1471          * one parameter/value pair and delimit them with a semicolon */
1472         field = update_fields;
1473         newparam = convert_attribute_name_to_ldap(table_config, field->name);
1474         if (!newparam) {
1475                 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1476                 ast_free(filter);
1477                 ast_free(clean_basedn);
1478                 return -1;
1479         }
1480
1481         mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1482         ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1483         ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1484
1485         ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1486         ldap_mods[0]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1487         strcpy(ldap_mods[0]->mod_type, newparam);
1488
1489         ldap_mods[0]->mod_values = ast_calloc(sizeof(char), 2);
1490         ldap_mods[0]->mod_values[0] = ast_calloc(sizeof(char), strlen(field->value) + 1);
1491         strcpy(ldap_mods[0]->mod_values[0], field->value);
1492
1493         while ((field = field->next)) {
1494                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1495                 mod_exists = 0;
1496
1497                 for (i = 0; i < mods_size - 1; i++) {
1498                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1499                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1500                                 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));
1501                                 strcat(ldap_mods[i]->mod_values[0], ";");
1502                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1503                                 mod_exists = 1; 
1504                                 break;
1505                         }
1506                 }
1507
1508                 /* create new mod */
1509                 if (!mod_exists) {
1510                         mods_size++;
1511                         ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1512                         ldap_mods[mods_size - 1] = NULL;
1513                         ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1514
1515                         ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1516
1517                         ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1518                         strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1519
1520                         ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1521                         ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(field->value) + 1);
1522                         strcpy(ldap_mods[mods_size - 2]->mod_values[0], field->value);
1523                 }
1524         }
1525         /* freeing ldap_mods further down */
1526
1527         do {
1528                 /* freeing ldap_result further down */
1529                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1530                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1531                                   &ldap_result_msg);
1532                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1533                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1534                         tries++;
1535                         if (tries < 3) {
1536                                 usleep(500000L * tries);
1537                                 if (ldapConn) {
1538                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1539                                         ldapConn = NULL;
1540                                 }
1541                                 if (!ldap_reconnect()) {
1542                                         break;
1543                                 }
1544                         }
1545                 }
1546         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1547
1548         if (result != LDAP_SUCCESS) {
1549                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1550                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1551
1552                 ast_mutex_unlock(&ldap_lock);
1553                 ast_free(filter);
1554                 ast_free(clean_basedn);
1555                 ldap_msgfree(ldap_result_msg);
1556                 ldap_mods_free(ldap_mods, 0);
1557                 return -1;
1558         }
1559         /* Ready to update */
1560         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1561                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1562                         ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1563                 }
1564
1565                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1566
1567                 for (i = 0; ldap_entry; i++) {
1568                         dn = ldap_get_dn(ldapConn, ldap_entry);
1569                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1570                                 ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
1571                         }
1572                         ldap_memfree(dn);
1573                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1574                 }
1575         }
1576
1577         ast_mutex_unlock(&ldap_lock);
1578         if (filter) {
1579                 ast_free(filter);
1580         }
1581         if (clean_basedn) {
1582                 ast_free(clean_basedn);
1583         }
1584         ldap_msgfree(ldap_result_msg);
1585         ldap_mods_free(ldap_mods, 0);
1586         return num_entries;
1587 }
1588
1589 static struct ast_config_engine ldap_engine = {
1590         .name = "ldap",
1591         .load_func = config_ldap,
1592         .realtime_func = realtime_ldap,
1593         .realtime_multi_func = realtime_multi_ldap,
1594         .update_func = update_ldap,
1595         .update2_func = update2_ldap,
1596 };
1597
1598 /*!
1599  * \brief Load the module
1600  *
1601  * Module loading including tests for configuration or dependencies.
1602  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1603  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1604  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1605  * configuration file or other non-critical problem return 
1606  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1607  *
1608  * \todo Don't error or warn on a default install. If the config is
1609  * default we should not attempt to connect to a server. -lathama
1610  */
1611 static int load_module(void)
1612 {
1613         if (parse_config() < 0) {
1614                 ast_log(LOG_ERROR, "Cannot load LDAP RealTime driver.\n");
1615                 return 0;
1616         }
1617
1618         ast_mutex_lock(&ldap_lock);
1619
1620         if (!ldap_reconnect())  {
1621                 ast_log(LOG_WARNING, "Couldn't establish connection to LDAP directory. Check debug.\n");
1622         }
1623
1624         ast_config_engine_register(&ldap_engine);
1625         ast_verb(1, "LDAP RealTime driver loaded.\n");
1626         ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1627
1628         ast_mutex_unlock(&ldap_lock);
1629
1630         return 0;
1631 }
1632
1633 /*! \brief Unload Module
1634  *
1635  */
1636 static int unload_module(void)
1637 {
1638         /* Aquire control before doing anything to the module itself. */
1639         ast_mutex_lock(&ldap_lock);
1640
1641         table_configs_free();
1642
1643         if (ldapConn) {
1644                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1645                 ldapConn = NULL;
1646         }
1647         ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1648         ast_config_engine_deregister(&ldap_engine);
1649         ast_verb(1, "LDAP RealTime driver unloaded.\n");
1650
1651         /* Unlock so something else can destroy the lock. */
1652         ast_mutex_unlock(&ldap_lock);
1653
1654         return 0;
1655 }
1656
1657 /*! \breif Relod Module
1658  */
1659 static int reload(void)
1660 {
1661         /* Aquire control before doing anything to the module itself. */
1662         ast_mutex_lock(&ldap_lock);
1663
1664         if (ldapConn) {
1665                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1666                 ldapConn = NULL;
1667         }
1668
1669         if (parse_config() < 0) {
1670                 ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
1671                 ast_mutex_unlock(&ldap_lock);
1672                 return 0;
1673         }               
1674
1675         if (!ldap_reconnect())  {
1676                 ast_log(LOG_WARNING, "Couldn't establish connection to your directory server. Check debug.\n");
1677         }
1678
1679         ast_verb(2, "LDAP RealTime driver reloaded.\n");
1680
1681         /* Done reloading. Release lock so others can now use driver. */
1682         ast_mutex_unlock(&ldap_lock);
1683
1684         return 0;
1685 }
1686
1687 /*! \brief parse the configuration file
1688  */
1689 static int parse_config(void)
1690 {
1691         struct ast_config *config;
1692         struct ast_flags config_flags = {0};
1693         const char *s, *host;
1694         int port;
1695         char *category_name = NULL;
1696
1697         /* Make sure that global variables are reset */
1698         url[0] = '\0';
1699         user[0] = '\0';
1700         pass[0] = '\0';
1701         base_distinguished_name[0] = '\0';
1702         version = 3;
1703
1704         config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
1705         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1706                 ast_log(LOG_ERROR, "Cannot load configuration file: %s\n", RES_CONFIG_LDAP_CONF);
1707                 return -1;
1708         }
1709
1710         if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
1711                 ast_log(LOG_NOTICE, "No directory user found, anonymous binding as default.\n");
1712                 user[0] = '\0';
1713         } else {
1714                 ast_copy_string(user, s, sizeof(user));
1715         }
1716
1717         if (!ast_strlen_zero(user)) {
1718                 if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
1719                         ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
1720                         ast_copy_string(pass, "asterisk", sizeof(pass));
1721                 } else {
1722                         ast_copy_string(pass, s, sizeof(pass));
1723                 }
1724         }
1725
1726         /* URL is preferred, use host and port if not found */
1727         if ((s = ast_variable_retrieve(config, "_general", "url"))) {
1728                 ast_copy_string(url, s, sizeof(url));
1729         } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
1730                 if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
1731                         ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
1732                         port = 389;
1733                 }
1734
1735                 snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
1736         } else {
1737                 ast_log(LOG_ERROR, "No directory URL or host found.\n");
1738                 ast_config_destroy(config);
1739                 return -1;
1740         }
1741
1742         if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
1743                 ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
1744                 ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
1745         } else 
1746                 ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
1747
1748         if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
1749                 ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
1750         } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
1751                 ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
1752                 version = 3;
1753         }
1754
1755         table_configs_free();
1756
1757         while ((category_name = ast_category_browse(config, category_name))) {
1758                 int is_general = (strcasecmp(category_name, "_general") == 0);
1759                 int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
1760                 struct ast_variable *var = ast_variable_browse(config, category_name);
1761                 
1762                 if (var) {
1763                         struct ldap_table_config *table_config =
1764                                 table_config_for_table_name(category_name);
1765                         if (!table_config) {
1766                                 table_config = table_config_new(category_name);
1767                                 AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
1768                                 if (is_general)
1769                                         base_table_config = table_config;
1770                                 if (is_config)
1771                                         static_table_config = table_config;
1772                         }
1773                         for (; var; var = var->next) {
1774                                 if (!strcasecmp(var->name, "additionalFilter")) {
1775                                         table_config->additional_filter = ast_strdup(var->value);
1776                                 } else {
1777                                         ldap_table_config_add_attribute(table_config, var->name, var->value);
1778                                 }
1779                         }
1780                 }
1781         }
1782
1783         ast_config_destroy(config);
1784
1785         return 1;
1786 }
1787
1788 /*! \note ldap_lock should have been locked before calling this function. */
1789 static int ldap_reconnect(void)
1790 {
1791         int bind_result = 0;
1792         struct berval cred;
1793
1794         if (ldapConn) {
1795                 ast_debug(2, "Everything seems fine.\n");
1796                 return 1;
1797         }
1798
1799         if (ast_strlen_zero(url)) {
1800                 ast_log(LOG_ERROR, "Not enough parameters to connect to ldap directory\n");
1801                 return 0;
1802         }
1803
1804         if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
1805                 ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
1806                 return 0;
1807         }
1808
1809         if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
1810                 ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
1811         }
1812
1813         if (!ast_strlen_zero(user)) {
1814                 ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
1815                 cred.bv_val = (char *) pass;
1816                 cred.bv_len = strlen(pass);
1817                 bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1818         } else {
1819                 ast_debug(2, "bind %s anonymously\n", url);
1820                 cred.bv_val = NULL;
1821                 cred.bv_len = 0;
1822                 bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1823         }
1824         if (bind_result == LDAP_SUCCESS) {
1825                 ast_debug(2, "Successfully connected to directory.\n");
1826                 connect_time = time(NULL);
1827                 return 1;
1828         } else {
1829                 ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
1830                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1831                 ldapConn = NULL;
1832                 return 0;
1833         }
1834 }
1835
1836 /*! \brief Realtime Status
1837  *
1838  */
1839 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1840 {
1841         char status[256];
1842         char credentials[100] = "";
1843         char buf[362]; /* 256+100+" for "+NULL */
1844         int ctimesec = time(NULL) - connect_time;
1845
1846         switch (cmd) {
1847         case CLI_INIT:
1848                 e->command = "realtime show ldap status";
1849                 e->usage =
1850                         "Usage: realtime show ldap status\n"
1851                         "              Shows connection information for the LDAP RealTime driver\n";
1852                 return NULL;
1853         case CLI_GENERATE:
1854                 return NULL;
1855         }
1856
1857         if (!ldapConn)
1858                 return CLI_FAILURE;
1859
1860         if (!ast_strlen_zero(url)) 
1861                 snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
1862
1863         if (!ast_strlen_zero(user))
1864                 snprintf(credentials, sizeof(credentials), " with username %s", user);
1865
1866         snprintf(buf, sizeof(buf), "%s%s for ", status, credentials);
1867         ast_cli_print_timestr_fromseconds(a->fd, ctimesec, buf);
1868
1869         return CLI_SUCCESS;
1870 }
1871
1872 /*! \brief Module Information
1873  *
1874  */
1875 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "LDAP realtime interface",
1876         .support_level = AST_MODULE_SUPPORT_EXTENDED,
1877         .load = load_module,
1878         .unload = unload_module,
1879         .reload = reload,
1880         .load_pri = AST_MODPRI_REALTIME_DRIVER,
1881 );