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