res_config_ldap: Remove extraneous line numbers from log messages
[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, "semicolon_count_var: %s\n", 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, "attribute_name: %s LDAP value: %s\n", 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(tot_count + 1, sizeof(struct ast_variable *));
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, "is delimited %d times: %s\n", 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, "DELIM pos: %d i: %d\n", pos, i);
481                                                                         if (delim_value[i] == ';') {
482                                                                                 delim_value[i] = '\0';
483
484                                                                                 ast_debug(2, "DELIM - attribute_name: %s value: %s pos: %d\n", 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, "DELIM pos: %d i: %d delim_count: %d\n", pos, i, delim_count);
503                                                                         /* Last delimited value */
504                                                                         ast_debug(4, "DELIM - attribute_name: %s value: %s pos: %d\n", 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, "DELIM pos: %d i: %d\n", 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, "attribute_name: %s value: %s\n", 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, "Added to vars - %s = %s\n", 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, "Added to vars - non static\n");
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         ast_free(filter);
930         ast_free(clean_basedn);
931
932         ast_mutex_unlock(&ldap_lock);
933
934         return vars;
935 }
936
937 static struct ast_variable *realtime_arguments_to_fields(va_list ap)
938 {
939         struct ast_variable *fields = NULL;
940         const char *newparam, *newval;
941
942         while ((newparam = va_arg(ap, const char *))) {
943                 struct ast_variable *field;
944
945                 newval = va_arg(ap, const char *);
946                 if (!(field = ast_variable_new(newparam, newval, ""))) {
947                         ast_variables_destroy(fields);
948                         return NULL;
949                 }
950
951                 field->next = fields;
952                 fields = field;
953         }
954
955         return fields;
956 }
957
958 /*! \brief same as realtime_ldap_base_ap but take variable arguments count list
959  */
960 static struct ast_variable **realtime_ldap_base(unsigned int *entries_count_ptr,
961         const char *basedn, const char *table_name, ...)
962 {
963         RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
964         struct ast_variable **vars = NULL;
965         va_list ap;
966
967         va_start(ap, table_name);
968         fields = realtime_arguments_to_fields(ap);
969         va_end(ap);
970
971         vars = realtime_ldap_base_ap(entries_count_ptr, basedn, table_name, fields);
972
973         return vars;
974 }
975
976 /*! \brief See Asterisk doc
977  *
978  * For Realtime Dynamic(i.e., switch, queues, and directory)
979  */
980 static struct ast_variable *realtime_ldap(const char *basedn,
981                                           const char *table_name, const struct ast_variable *fields)
982 {
983         struct ast_variable **vars = realtime_ldap_base_ap(NULL, basedn, table_name, fields);
984         struct ast_variable *var = NULL;
985
986         if (vars) {
987                 struct ast_variable *last_var = NULL;
988                 struct ast_variable **p = vars;
989
990                 /* Chain the vars array of lists into one list to return. */
991                 while (*p) {
992                         if (last_var) {
993                                 while (last_var->next) {
994                                         last_var = last_var->next;
995                                 }
996                                 last_var->next = *p;
997                         } else {
998                                 var = *p;
999                                 last_var = var;
1000                         }
1001                         p++;
1002                 }
1003                 ast_free(vars);
1004         }
1005         return var;
1006 }
1007
1008 /*! \brief See Asterisk doc
1009  *
1010  * 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);
1011  * however, the ast_load_realtime wil match on wildcharacters also depending on what the mode is set to
1012  * this is an area of asterisk that could do with a lot of modification
1013  * I think this function returns Realtime dynamic objects
1014  */
1015 static struct ast_config *realtime_multi_ldap(const char *basedn,
1016       const char *table_name, const struct ast_variable *fields)
1017 {
1018         char *op;
1019         const char *initfield = NULL;
1020         struct ast_variable **vars =
1021                 realtime_ldap_base_ap(NULL, basedn, table_name, fields);
1022         struct ast_config *cfg = NULL;
1023
1024         if (!fields) {
1025             ast_log(LOG_WARNING, "realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
1026             return NULL;
1027         }
1028         initfield = ast_strdupa(fields->name);
1029         if ((op = strchr(initfield, ' '))) {
1030                 *op = '\0';
1031         }
1032
1033         if (vars) {
1034                 cfg = ast_config_new();
1035                 if (!cfg) {
1036                         ast_log(LOG_ERROR, "Unable to create a config!\n");
1037                 } else {
1038                         struct ast_variable **p = vars;
1039
1040                         while (*p) {
1041                                 struct ast_category *cat = NULL;
1042                                 cat = ast_category_new("", table_name, -1);
1043                                 if (!cat) {
1044                                         ast_log(LOG_ERROR, "Unable to create a new category!\n");
1045                                         break;
1046                                 } else {
1047                                         struct ast_variable *var = *p;
1048                                         while (var) {
1049                                                 struct ast_variable *next = var->next;
1050                                                 if (initfield && !strcmp(initfield, var->name)) {
1051                                                         ast_category_rename(cat, var->value);
1052                                                 }
1053                                                 var->next = NULL;
1054                                                 ast_variable_append(cat, var);
1055                                                 var = next;
1056                                         }
1057                                 }
1058                                 ast_category_append(cfg, cat);
1059                                 p++;
1060                         }
1061                 }
1062                 ast_free(vars);
1063         }
1064         return cfg;
1065
1066 }
1067
1068 /*! \brief Sorting alogrithm for qsort to find the order of the variables \a a and \a b
1069  * \param a pointer to category_and_metric struct
1070  * \param b pointer to category_and_metric struct
1071  *
1072  * \retval -1 for if b is greater
1073  * \retval 0 zero for equal
1074  * \retval 1 if a is greater
1075  */
1076 static int compare_categories(const void *a, const void *b)
1077 {
1078         const struct category_and_metric *as = a;
1079         const struct category_and_metric *bs = b;
1080
1081         if (as->metric < bs->metric) {
1082                 return -1;
1083         } else if (as->metric > bs->metric) {
1084                 return 1;
1085         } else if (as->metric == bs->metric && strcmp(as->name, bs->name) != 0) {
1086                 return strcmp(as->name, bs->name);
1087         } 
1088         /* if the metric and the category name is the same, we check the variable metric */
1089         if (as->var_metric < bs->var_metric) {
1090                 return -1;
1091         } else if (as->var_metric > bs->var_metric) {
1092                 return 1;
1093         }
1094
1095         return 0;
1096 }
1097
1098 /*! \brief See Asterisk Realtime Documentation
1099  *
1100  * This is for Static Realtime
1101  *      
1102  * load the configuration stuff for the .conf files
1103  * called on a reload
1104  */
1105 static struct ast_config *config_ldap(const char *basedn, const char *table_name,
1106         const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *sugg_incl, const char *who_asked)
1107 {
1108         unsigned int vars_count = 0;
1109         struct ast_variable **vars;
1110         int i = 0;
1111         struct ast_variable *new_v = NULL;
1112         struct ast_category *cur_cat = NULL;
1113         const char *last_category = NULL;
1114         int last_category_metric = 0;
1115         struct category_and_metric *categories;
1116         struct ast_variable **p;
1117
1118         if (ast_strlen_zero(file) || !strcasecmp(file, RES_CONFIG_LDAP_CONF)) {
1119                 ast_log(LOG_ERROR, "Missing configuration file: %s. Can't configure myself.\n", RES_CONFIG_LDAP_CONF);
1120                 return NULL;
1121         }
1122
1123         vars = realtime_ldap_base(&vars_count, basedn, table_name, "filename", file, "commented", "FALSE", NULL);
1124
1125         if (!vars) {
1126                 ast_log(LOG_WARNING, "Could not find config '%s' in directory.\n", file);
1127                 return NULL;
1128         }
1129
1130         /*! \note Since the items come back in random order, they need to be sorted
1131          * first, and since the data could easily exceed stack size, this is
1132          * allocated from the heap.
1133          */
1134         if (!(categories = ast_calloc(vars_count, sizeof(*categories)))) {
1135                 return NULL;
1136         }
1137
1138         for (vars_count = 0, p = vars; *p; p++) {
1139                 struct ast_variable *category = variable_named(*p, "category");
1140                 struct ast_variable *cat_metric = variable_named(*p, "cat_metric");
1141                 struct ast_variable *var_name = variable_named(*p, "variable_name");
1142                 struct ast_variable *var_val = variable_named(*p, "variable_value");
1143                 struct ast_variable *var_metric = variable_named(*p, "var_metric");
1144                 struct ast_variable *dn = variable_named(*p, "dn");
1145
1146                 if (!category) {
1147                         ast_log(LOG_ERROR, "No category name in entry '%s'  for file '%s'.\n",
1148                                         (dn ? dn->value : "?"), file);
1149                 } else if (!cat_metric) {
1150                         ast_log(LOG_ERROR, "No category metric in entry '%s'(category: %s) for file '%s'.\n",
1151                                         (dn ? dn->value : "?"), category->value, file);
1152                 } else if (!var_metric) {
1153                         ast_log(LOG_ERROR, "No variable metric in entry '%s'(category: %s) for file '%s'.\n",
1154                                         (dn ? dn->value : "?"), category->value, file);
1155                 } else if (!var_name) {
1156                         ast_log(LOG_ERROR, "No variable name in entry '%s' (category: %s metric: %s) for file '%s'.\n",
1157                                         (dn ? dn->value : "?"), category->value,
1158                                         cat_metric->value, file);
1159                 } else if (!var_val) {
1160                         ast_log(LOG_ERROR, "No variable value in entry '%s' (category: %s metric: %s variable: %s) for file '%s'.\n",
1161                                         (dn ? dn->value : "?"), category->value,
1162                                         cat_metric->value, var_name->value, file);
1163                 } else {
1164                         categories[vars_count].name = category->value;
1165                         categories[vars_count].metric = atoi(cat_metric->value);
1166                         categories[vars_count].variable_name = var_name->value;
1167                         categories[vars_count].variable_value = var_val->value;
1168                         categories[vars_count].var_metric = atoi(var_metric->value);
1169                         vars_count++;
1170                 }
1171
1172                 ast_debug(3, "category: %s\n", category->value);
1173                 ast_debug(3, "var_name: %s\n", var_name->value);
1174                 ast_debug(3, "var_val: %s\n", var_val->value);
1175                 ast_debug(3, "cat_metric: %s\n", cat_metric->value);
1176
1177         }
1178
1179         qsort(categories, vars_count, sizeof(*categories), compare_categories);
1180
1181         for (i = 0; i < vars_count; i++) {
1182                 if (!strcmp(categories[i].variable_name, "#include")) {
1183                         struct ast_flags flags = { 0 };
1184                         if (!ast_config_internal_load(categories[i].variable_value, cfg, flags, "", who_asked)) {
1185                                 break;
1186                         }
1187                         continue;
1188                 }
1189
1190                 if (!last_category || strcmp(last_category, categories[i].name) ||
1191                         last_category_metric != categories[i].metric) {
1192
1193                         cur_cat = ast_category_new(categories[i].name, table_name, -1);
1194                         if (!cur_cat) {
1195                                 break;
1196                         }
1197                         last_category = categories[i].name;
1198                         last_category_metric = categories[i].metric;
1199                         ast_category_append(cfg, cur_cat);
1200                 }
1201
1202                 if (!(new_v = ast_variable_new(categories[i].variable_name, categories[i].variable_value, table_name))) {
1203                         break;
1204                 }
1205
1206                 ast_variable_append(cur_cat, new_v);
1207         }
1208
1209         ast_free(vars);
1210         ast_free(categories);
1211
1212         return cfg;
1213 }
1214
1215 /* \brief Function to update a set of values in ldap static mode
1216  */
1217 static int update_ldap(const char *basedn, const char *table_name, const char *attribute,
1218         const char *lookup, const struct ast_variable *fields)
1219 {
1220         int error = 0;
1221         LDAPMessage *ldap_entry = NULL;
1222         LDAPMod **ldap_mods;
1223         const char *newparam;
1224         const struct ast_variable *field = fields;
1225         char *dn;
1226         int num_entries = 0;
1227         int i = 0;
1228         int mods_size = 0;
1229         int mod_exists = 0;
1230         struct ldap_table_config *table_config = NULL;
1231         char *clean_basedn = NULL;
1232         struct ast_str *filter = NULL;
1233         int tries = 0;
1234         int result = 0;
1235         LDAPMessage *ldap_result_msg = NULL;
1236
1237         if (!table_name) {
1238                 ast_log(LOG_ERROR, "No table_name specified.\n");
1239                 return -1;
1240         } 
1241
1242         if (!(filter = ast_str_create(80))) {
1243                 return -1;
1244         }
1245
1246         if (!attribute || !lookup) {
1247                 ast_log(LOG_WARNING, "Search parameters are empty.\n");
1248                 return -1;
1249         }
1250         ast_mutex_lock(&ldap_lock);
1251
1252         /* We now have our complete statement; Lets connect to the server and execute it.  */
1253         if (!ldap_reconnect()) {
1254                 ast_mutex_unlock(&ldap_lock);
1255                 return -1;
1256         }
1257
1258         table_config = table_config_for_table_name(table_name);
1259         if (!table_config) {
1260                 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1261                 ast_mutex_unlock(&ldap_lock);
1262                 return -1;
1263         }
1264
1265         clean_basedn = cleaned_basedn(NULL, basedn);
1266
1267         /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1268         ast_str_append(&filter, 0, "(&");
1269         if (table_config && table_config->additional_filter) {
1270                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1271         }
1272         if (table_config != base_table_config && base_table_config && base_table_config->additional_filter) {
1273                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1274         }
1275         append_var_and_value_to_filter(&filter, table_config, attribute, lookup);
1276         ast_str_append(&filter, 0, ")");
1277
1278         /* Create the modification array with the parameter/value pairs we were given, 
1279          * if there are several parameters with the same name, we collect them into 
1280          * one parameter/value pair and delimit them with a semicolon */
1281         newparam = convert_attribute_name_to_ldap(table_config, field->name);
1282         if (!newparam) {
1283                 ast_log(LOG_WARNING, "Need at least one parameter to modify.\n");
1284                 return -1;
1285         }
1286
1287         mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1288         ldap_mods = ldap_memcalloc(mods_size, sizeof(LDAPMod *));
1289         ldap_mods[0] = ldap_memcalloc(1, sizeof(LDAPMod));
1290         ldap_mods[0]->mod_type = ldap_strdup(newparam);
1291
1292         if (strlen(field->value) == 0) {
1293                 ldap_mods[0]->mod_op = LDAP_MOD_DELETE;
1294         } else {
1295                 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1296                 ldap_mods[0]->mod_values = ldap_memcalloc(2, sizeof(char *));
1297                 ldap_mods[0]->mod_values[0] = ldap_strdup(field->value);
1298         }
1299
1300         while ((field = field->next)) {
1301                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1302                 mod_exists = 0;
1303
1304                 for (i = 0; i < mods_size - 1; i++) {
1305                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1306                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1307                                 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));
1308                                 strcat(ldap_mods[i]->mod_values[0], ";");
1309                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1310                                 mod_exists = 1;
1311                                 break;
1312                         }
1313                 }
1314
1315                 /* create new mod */
1316                 if (!mod_exists) {
1317                         mods_size++;
1318                         ldap_mods = ldap_memrealloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1319                         ldap_mods[mods_size - 2] = ldap_memcalloc(1, sizeof(LDAPMod));
1320                         ldap_mods[mods_size - 2]->mod_type = ldap_strdup(newparam);
1321
1322                         if (strlen(field->value) == 0) {
1323                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
1324                         } else {
1325                                 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1326                                 ldap_mods[mods_size - 2]->mod_values = ldap_memcalloc(2, sizeof(char *));
1327                                 ldap_mods[mods_size - 2]->mod_values[0] = ldap_strdup(field->value);
1328                         }
1329
1330                         /* NULL terminate */
1331                         ldap_mods[mods_size - 1] = NULL;
1332                 }
1333         }
1334         /* freeing ldap_mods further down */
1335
1336         do {
1337                 /* freeing ldap_result further down */
1338                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1339                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1340                                   &ldap_result_msg);
1341                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1342                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1343                         tries++;
1344                         if (tries < 3) {
1345                                 usleep(500000L * tries);
1346                                 if (ldapConn) {
1347                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1348                                         ldapConn = NULL;
1349                                 }
1350                                 if (!ldap_reconnect())
1351                                         break;
1352                         }
1353                 }
1354         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1355
1356         if (result != LDAP_SUCCESS) {
1357                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1358                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1359
1360                 ast_mutex_unlock(&ldap_lock);
1361                 ast_free(filter);
1362                 ast_free(clean_basedn);
1363                 ldap_msgfree(ldap_result_msg);
1364                 ldap_mods_free(ldap_mods, 1);
1365                 return -1;
1366         }
1367         /* Ready to update */
1368         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1369                 ast_debug(3, "Modifying %s=%s hits: %d\n", attribute, lookup, num_entries);
1370                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1371                         if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
1372                                 ast_debug(3, "%s=%s\n", ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1373                         } else {
1374                                 ast_debug(3, "deleting %s\n", ldap_mods[i]->mod_type);
1375                         }
1376                 }
1377                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1378
1379                 for (i = 0; ldap_entry; i++) { 
1380                         dn = ldap_get_dn(ldapConn, ldap_entry);
1381                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1382                                 ast_log(LOG_ERROR, "Couldn't modify '%s'='%s', dn:%s because %s\n",
1383                                                 attribute, lookup, dn, ldap_err2string(error));
1384                         }
1385                         ldap_memfree(dn);
1386                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1387                 }
1388         }
1389
1390         ast_mutex_unlock(&ldap_lock);
1391         ast_free(filter);
1392         ast_free(clean_basedn);
1393         ldap_msgfree(ldap_result_msg);
1394         ldap_mods_free(ldap_mods, 1);
1395         return num_entries;
1396 }
1397
1398 static int update2_ldap(const char *basedn, const char *table_name, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
1399 {
1400         int error = 0;
1401         LDAPMessage *ldap_entry = NULL;
1402         LDAPMod **ldap_mods;
1403         const char *newparam;
1404         const struct ast_variable *field;
1405         char *dn;
1406         int num_entries = 0;
1407         int i = 0;
1408         int mods_size = 0;
1409         int mod_exists = 0;
1410         struct ldap_table_config *table_config = NULL;
1411         char *clean_basedn = NULL;
1412         struct ast_str *filter = NULL;
1413         int tries = 0;
1414         int result = 0;
1415         LDAPMessage *ldap_result_msg = NULL;
1416
1417         if (!table_name) {
1418                 ast_log(LOG_ERROR, "No table_name specified.\n");
1419                 return -1;
1420         } 
1421
1422         if (!(filter = ast_str_create(80))) {
1423                 return -1;
1424         }
1425
1426         ast_mutex_lock(&ldap_lock);
1427
1428         /* We now have our complete statement; Lets connect to the server and execute it.  */
1429         if (!ldap_reconnect()) {
1430                 ast_mutex_unlock(&ldap_lock);
1431                 ast_free(filter);
1432                 return -1;
1433         }
1434
1435         table_config = table_config_for_table_name(table_name);
1436         if (!table_config) {
1437                 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1438                 ast_mutex_unlock(&ldap_lock);
1439                 ast_free(filter);
1440                 return -1;
1441         }
1442
1443         clean_basedn = cleaned_basedn(NULL, basedn);
1444
1445         /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1446         ast_str_append(&filter, 0, "(&");
1447         if (table_config && table_config->additional_filter) {
1448                 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1449         }
1450         if (table_config != base_table_config && base_table_config
1451                 && base_table_config->additional_filter) {
1452                 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1453         }
1454
1455         /* Get multiple lookup keyfields and values */
1456         for (field = lookup_fields; field; field = field->next) {
1457                 append_var_and_value_to_filter(&filter, table_config, field->name, field->value);
1458         }
1459         ast_str_append(&filter, 0, ")");
1460
1461         /* Create the modification array with the parameter/value pairs we were given, 
1462          * if there are several parameters with the same name, we collect them into 
1463          * one parameter/value pair and delimit them with a semicolon */
1464         field = update_fields;
1465         newparam = convert_attribute_name_to_ldap(table_config, field->name);
1466         if (!newparam) {
1467                 ast_log(LOG_WARNING, "Need at least one parameter to modify.\n");
1468                 ast_free(filter);
1469                 ast_free(clean_basedn);
1470                 return -1;
1471         }
1472
1473         mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1474         ldap_mods = ldap_memcalloc(mods_size, sizeof(LDAPMod *));
1475         ldap_mods[0] = ldap_memcalloc(1, sizeof(LDAPMod));
1476         ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1477         ldap_mods[0]->mod_type = ldap_strdup(newparam);
1478         ldap_mods[0]->mod_values = ldap_memcalloc(2, sizeof(char *));
1479         ldap_mods[0]->mod_values[0] = ldap_strdup(field->value);
1480
1481         while ((field = field->next)) {
1482                 newparam = convert_attribute_name_to_ldap(table_config, field->name);
1483                 mod_exists = 0;
1484
1485                 for (i = 0; i < mods_size - 1; i++) {
1486                         if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1487                                 /* We have the parameter allready, adding the value as a semicolon delimited value */
1488                                 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));
1489                                 strcat(ldap_mods[i]->mod_values[0], ";");
1490                                 strcat(ldap_mods[i]->mod_values[0], field->value);
1491                                 mod_exists = 1; 
1492                                 break;
1493                         }
1494                 }
1495
1496                 /* create new mod */
1497                 if (!mod_exists) {
1498                         mods_size++;
1499                         ldap_mods = ldap_memrealloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1500                         ldap_mods[mods_size - 2] = ldap_memcalloc(1, sizeof(LDAPMod));
1501                         ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1502                         ldap_mods[mods_size - 2]->mod_type = ldap_strdup(newparam);
1503                         ldap_mods[mods_size - 2]->mod_values = ldap_memcalloc(2, sizeof(char *));
1504                         ldap_mods[mods_size - 2]->mod_values[0] = ldap_strdup(field->value);
1505
1506                         /* NULL terminate */
1507                         ldap_mods[mods_size - 1] = NULL;
1508                 }
1509         }
1510         /* freeing ldap_mods further down */
1511
1512         do {
1513                 /* freeing ldap_result further down */
1514                 result = ldap_search_ext_s(ldapConn, clean_basedn,
1515                                   LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1516                                   &ldap_result_msg);
1517                 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1518                         ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1519                         tries++;
1520                         if (tries < 3) {
1521                                 usleep(500000L * tries);
1522                                 if (ldapConn) {
1523                                         ldap_unbind_ext_s(ldapConn, NULL, NULL);
1524                                         ldapConn = NULL;
1525                                 }
1526                                 if (!ldap_reconnect()) {
1527                                         break;
1528                                 }
1529                         }
1530                 }
1531         } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1532
1533         if (result != LDAP_SUCCESS) {
1534                 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1535                 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1536
1537                 ast_mutex_unlock(&ldap_lock);
1538                 ast_free(filter);
1539                 ast_free(clean_basedn);
1540                 ldap_msgfree(ldap_result_msg);
1541                 ldap_mods_free(ldap_mods, 1);
1542                 return -1;
1543         }
1544         /* Ready to update */
1545         if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1546                 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1547                         ast_debug(3, "%s=%s\n", ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1548                 }
1549
1550                 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1551
1552                 for (i = 0; ldap_entry; i++) {
1553                         dn = ldap_get_dn(ldapConn, ldap_entry);
1554                         if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS)  {
1555                                 ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
1556                         }
1557                         ldap_memfree(dn);
1558                         ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1559                 }
1560         }
1561
1562         ast_mutex_unlock(&ldap_lock);
1563         ast_free(filter);
1564         ast_free(clean_basedn);
1565         ldap_msgfree(ldap_result_msg);
1566         ldap_mods_free(ldap_mods, 1);
1567         return num_entries;
1568 }
1569
1570 static struct ast_config_engine ldap_engine = {
1571         .name = "ldap",
1572         .load_func = config_ldap,
1573         .realtime_func = realtime_ldap,
1574         .realtime_multi_func = realtime_multi_ldap,
1575         .update_func = update_ldap,
1576         .update2_func = update2_ldap,
1577 };
1578
1579 /*!
1580  * \brief Load the module
1581  *
1582  * Module loading including tests for configuration or dependencies.
1583  * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1584  * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1585  * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the 
1586  * configuration file or other non-critical problem return 
1587  * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1588  *
1589  * \todo Don't error or warn on a default install. If the config is
1590  * default we should not attempt to connect to a server. -lathama
1591  */
1592 static int load_module(void)
1593 {
1594         if (parse_config() < 0) {
1595                 ast_log(LOG_ERROR, "Cannot load LDAP RealTime driver.\n");
1596                 return 0;
1597         }
1598
1599         ast_mutex_lock(&ldap_lock);
1600
1601         if (!ldap_reconnect())  {
1602                 ast_log(LOG_WARNING, "Couldn't establish connection to LDAP directory. Check debug.\n");
1603         }
1604
1605         ast_config_engine_register(&ldap_engine);
1606         ast_verb(1, "LDAP RealTime driver loaded.\n");
1607         ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1608
1609         ast_mutex_unlock(&ldap_lock);
1610
1611         return 0;
1612 }
1613
1614 /*! \brief Unload Module
1615  *
1616  */
1617 static int unload_module(void)
1618 {
1619         /* Aquire control before doing anything to the module itself. */
1620         ast_mutex_lock(&ldap_lock);
1621
1622         table_configs_free();
1623
1624         if (ldapConn) {
1625                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1626                 ldapConn = NULL;
1627         }
1628         ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1629         ast_config_engine_deregister(&ldap_engine);
1630         ast_verb(1, "LDAP RealTime driver unloaded.\n");
1631
1632         /* Unlock so something else can destroy the lock. */
1633         ast_mutex_unlock(&ldap_lock);
1634
1635         return 0;
1636 }
1637
1638 /*! \breif Relod Module
1639  */
1640 static int reload(void)
1641 {
1642         /* Aquire control before doing anything to the module itself. */
1643         ast_mutex_lock(&ldap_lock);
1644
1645         if (ldapConn) {
1646                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1647                 ldapConn = NULL;
1648         }
1649
1650         if (parse_config() < 0) {
1651                 ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
1652                 ast_mutex_unlock(&ldap_lock);
1653                 return 0;
1654         }               
1655
1656         if (!ldap_reconnect())  {
1657                 ast_log(LOG_WARNING, "Couldn't establish connection to your directory server. Check debug.\n");
1658         }
1659
1660         ast_verb(2, "LDAP RealTime driver reloaded.\n");
1661
1662         /* Done reloading. Release lock so others can now use driver. */
1663         ast_mutex_unlock(&ldap_lock);
1664
1665         return 0;
1666 }
1667
1668 static int config_can_be_inherited(const char *key)
1669 {
1670         int i;
1671         static const char * const config[] = {
1672                 "basedn", "host", "pass", "port", "protocol", "url", "user", "version", NULL
1673         };
1674
1675         for (i = 0; config[i]; i++) {
1676                 if (!strcasecmp(key, config[i])) {
1677                         return 0;
1678                 }
1679         }
1680         return 1;
1681 }
1682
1683 /*! \brief parse the configuration file
1684  */
1685 static int parse_config(void)
1686 {
1687         struct ast_config *config;
1688         struct ast_flags config_flags = {0};
1689         const char *s, *host;
1690         int port;
1691         char *category_name = NULL;
1692
1693         /* Make sure that global variables are reset */
1694         url[0] = '\0';
1695         user[0] = '\0';
1696         pass[0] = '\0';
1697         base_distinguished_name[0] = '\0';
1698         version = 3;
1699
1700         config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
1701         if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1702                 ast_log(LOG_ERROR, "Cannot load configuration file: %s\n", RES_CONFIG_LDAP_CONF);
1703                 return -1;
1704         }
1705
1706         if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
1707                 ast_log(LOG_NOTICE, "No directory user found, anonymous binding as default.\n");
1708                 user[0] = '\0';
1709         } else {
1710                 ast_copy_string(user, s, sizeof(user));
1711         }
1712
1713         if (!ast_strlen_zero(user)) {
1714                 if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
1715                         ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
1716                         ast_copy_string(pass, "asterisk", sizeof(pass));
1717                 } else {
1718                         ast_copy_string(pass, s, sizeof(pass));
1719                 }
1720         }
1721
1722         /* URL is preferred, use host and port if not found */
1723         if ((s = ast_variable_retrieve(config, "_general", "url"))) {
1724                 ast_copy_string(url, s, sizeof(url));
1725         } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
1726                 if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
1727                         ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
1728                         port = 389;
1729                 }
1730
1731                 snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
1732         } else {
1733                 ast_log(LOG_ERROR, "No directory URL or host found.\n");
1734                 ast_config_destroy(config);
1735                 return -1;
1736         }
1737
1738         if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
1739                 ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
1740                 ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
1741         } else 
1742                 ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
1743
1744         if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
1745                 ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
1746         } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
1747                 ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
1748                 version = 3;
1749         }
1750
1751         table_configs_free();
1752
1753         while ((category_name = ast_category_browse(config, category_name))) {
1754                 int is_general = (strcasecmp(category_name, "_general") == 0);
1755                 int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
1756                 struct ast_variable *var = ast_variable_browse(config, category_name);
1757                 
1758                 if (var) {
1759                         struct ldap_table_config *table_config =
1760                                 table_config_for_table_name(category_name);
1761                         if (!table_config) {
1762                                 table_config = table_config_new(category_name);
1763                                 AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
1764                                 if (is_general)
1765                                         base_table_config = table_config;
1766                                 if (is_config)
1767                                         static_table_config = table_config;
1768                         }
1769                         for (; var; var = var->next) {
1770                                 if (!strcasecmp(var->name, "additionalFilter")) {
1771                                         table_config->additional_filter = ast_strdup(var->value);
1772                                 } else {
1773                                         if (!is_general || config_can_be_inherited(var->name)) {
1774                                                 ldap_table_config_add_attribute(table_config, var->name, var->value);
1775                                         }
1776                                 }
1777                         }
1778                 }
1779         }
1780
1781         ast_config_destroy(config);
1782
1783         return 1;
1784 }
1785
1786 /*! \note ldap_lock should have been locked before calling this function. */
1787 static int ldap_reconnect(void)
1788 {
1789         int bind_result = 0;
1790         struct berval cred;
1791
1792         if (ldapConn) {
1793                 ast_debug(2, "Everything seems fine.\n");
1794                 return 1;
1795         }
1796
1797         if (ast_strlen_zero(url)) {
1798                 ast_log(LOG_ERROR, "Not enough parameters to connect to ldap directory\n");
1799                 return 0;
1800         }
1801
1802         if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
1803                 ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
1804                 return 0;
1805         }
1806
1807         if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
1808                 ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
1809         }
1810
1811         if (!ast_strlen_zero(user)) {
1812                 ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
1813                 cred.bv_val = (char *) pass;
1814                 cred.bv_len = strlen(pass);
1815                 bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1816         } else {
1817                 ast_debug(2, "bind %s anonymously\n", url);
1818                 cred.bv_val = NULL;
1819                 cred.bv_len = 0;
1820                 bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1821         }
1822         if (bind_result == LDAP_SUCCESS) {
1823                 ast_debug(2, "Successfully connected to directory.\n");
1824                 connect_time = time(NULL);
1825                 return 1;
1826         } else {
1827                 ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
1828                 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1829                 ldapConn = NULL;
1830                 return 0;
1831         }
1832 }
1833
1834 /*! \brief Realtime Status
1835  *
1836  */
1837 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1838 {
1839         char status[256];
1840         char credentials[100] = "";
1841         char buf[362]; /* 256+100+" for "+NULL */
1842         int ctimesec = time(NULL) - connect_time;
1843
1844         switch (cmd) {
1845         case CLI_INIT:
1846                 e->command = "realtime show ldap status";
1847                 e->usage =
1848                         "Usage: realtime show ldap status\n"
1849                         "              Shows connection information for the LDAP RealTime driver\n";
1850                 return NULL;
1851         case CLI_GENERATE:
1852                 return NULL;
1853         }
1854
1855         if (!ldapConn)
1856                 return CLI_FAILURE;
1857
1858         if (!ast_strlen_zero(url)) 
1859                 snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
1860
1861         if (!ast_strlen_zero(user))
1862                 snprintf(credentials, sizeof(credentials), " with username %s", user);
1863
1864         snprintf(buf, sizeof(buf), "%s%s for ", status, credentials);
1865         ast_cli_print_timestr_fromseconds(a->fd, ctimesec, buf);
1866
1867         return CLI_SUCCESS;
1868 }
1869
1870 /*! \brief Module Information
1871  *
1872  */
1873 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "LDAP realtime interface",
1874         .support_level = AST_MODULE_SUPPORT_EXTENDED,
1875         .load = load_module,
1876         .unload = unload_module,
1877         .reload = reload,
1878         .load_pri = AST_MODPRI_REALTIME_DRIVER,
1879 );