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