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