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