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