2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2005, Oxymium sarl
5 * Manuel Guesdon <mguesdon@oxymium.net> - LDAP RealTime Driver Author/Adaptor
7 * Copyright (C) 2007, Digium, Inc.
8 * Russell Bryant <russell@digium.com>
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.
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.
24 * \brief LDAP plugin for portable configuration engine (ARA)
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>
31 * OpenLDAP http://www.openldap.org
34 /*! \li \ref res_config_ldap.c uses the configuration file \ref res_ldap.conf
35 * \addtogroup configuration_file Configuration Files
39 * \page res_ldap.conf res_ldap.conf
40 * \verbinclude res_ldap.conf.sample
45 <support_level>extended</support_level>
56 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
58 #include "asterisk/channel.h"
59 #include "asterisk/logger.h"
60 #include "asterisk/config.h"
61 #include "asterisk/module.h"
62 #include "asterisk/lock.h"
63 #include "asterisk/options.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/utils.h"
66 #include "asterisk/strings.h"
67 #include "asterisk/pbx.h"
68 #include "asterisk/linkedlists.h"
70 #define RES_CONFIG_LDAP_CONF "res_ldap.conf"
71 #define RES_CONFIG_LDAP_DEFAULT_BASEDN "asterisk"
73 AST_MUTEX_DEFINE_STATIC(ldap_lock);
75 static LDAP *ldapConn;
77 static char user[512];
78 static char pass[512];
79 static char base_distinguished_name[512];
81 static time_t connect_time;
83 static int parse_config(void);
84 static int ldap_reconnect(void);
85 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
87 struct category_and_metric {
90 const char *variable_name;
91 const char *variable_value;
92 int var_metric; /*!< For organizing variables (particularly includes and switch statments) within a context */
95 /*! \brief Table configuration
97 struct ldap_table_config {
98 char *table_name; /*!< table name */
99 char *additional_filter; /*!< additional filter */
100 struct ast_variable *attributes; /*!< attribute names conversion */
101 struct ast_variable *delimiters; /*!< the current delimiter is semicolon, so we are not using this variable */
102 AST_LIST_ENTRY(ldap_table_config) entry;
103 /* TODO: Make proxies work */
106 /*! \brief Should be locked before using it
108 static AST_LIST_HEAD_NOLOCK_STATIC(table_configs, ldap_table_config);
109 static struct ldap_table_config *base_table_config;
110 static struct ldap_table_config *static_table_config;
112 static struct ast_cli_entry ldap_cli[] = {
113 AST_CLI_DEFINE(realtime_ldap_status, "Shows connection information for the LDAP RealTime driver"),
116 /*! \brief Create a new table_config
118 static struct ldap_table_config *table_config_new(const char *table_name)
120 struct ldap_table_config *p;
122 if (!(p = ast_calloc(1, sizeof(*p))))
126 if (!(p->table_name = ast_strdup(table_name))) {
135 /*! \brief Find a table_config
137 * Should be locked before using it
138 * \note This function assumes ldap_lock to be locked.
140 static struct ldap_table_config *table_config_for_table_name(const char *table_name)
142 struct ldap_table_config *c = NULL;
144 AST_LIST_TRAVERSE(&table_configs, c, entry) {
145 if (!strcmp(c->table_name, table_name))
152 /*! \brief Find variable by name
154 static struct ast_variable *variable_named(struct ast_variable *var, const char *name)
156 for (; var; var = var->next) {
157 if (!strcasecmp(name, var->name))
164 /*! \brief Count semicolons in string
165 * \param somestr - pointer to a string
167 * \return number of occurances of the delimiter(semicolon)
169 static int semicolon_count_str(const char *somestr)
173 for (; *somestr; somestr++) {
181 /* \brief Count semicolons in variables
183 * takes a linked list of \a ast_variable variables, finds the one with the name variable_value
184 * and returns the number of semicolons in the value for that \a ast_variable
186 static int semicolon_count_var(struct ast_variable *var)
188 struct ast_variable *var_value = variable_named(var, "variable_value");
194 ast_debug(2, "LINE(%d) semicolon_count_var: %s\n", __LINE__, var_value->value);
196 return semicolon_count_str(var_value->value);
199 /*! \brief add attribute to table config
201 * Should be locked before using it
203 static void ldap_table_config_add_attribute(struct ldap_table_config *table_config,
204 const char *attribute_name, const char *attribute_value)
206 struct ast_variable *var;
208 if (ast_strlen_zero(attribute_name) || ast_strlen_zero(attribute_value)) {
212 if (!(var = ast_variable_new(attribute_name, attribute_value, table_config->table_name))) {
216 if (table_config->attributes) {
217 var->next = table_config->attributes;
219 table_config->attributes = var;
222 /*! \brief Free table_config
223 * \note assumes ldap_lock to be locked
225 static void table_configs_free(void)
227 struct ldap_table_config *c;
229 while ((c = AST_LIST_REMOVE_HEAD(&table_configs, entry))) {
231 ast_free(c->table_name);
233 if (c->additional_filter) {
234 ast_free(c->additional_filter);
237 ast_variables_destroy(c->attributes);
242 base_table_config = NULL;
243 static_table_config = NULL;
246 /*! \brief Convert variable name to ldap attribute name
248 * Should be locked before using it
250 static const char *convert_attribute_name_to_ldap(struct ldap_table_config *table_config,
251 const char *attribute_name)
254 struct ldap_table_config *configs[] = { table_config, base_table_config };
256 for (i = 0; i < ARRAY_LEN(configs); i++) {
257 struct ast_variable *attribute;
263 attribute = configs[i]->attributes;
264 for (; attribute; attribute = attribute->next) {
265 if (!strcasecmp(attribute_name, attribute->name)) {
266 return attribute->value;
271 return attribute_name;
274 /*! \brief Convert ldap attribute name to variable name
275 * \note Should be locked before using it
277 static const char *convert_attribute_name_from_ldap(struct ldap_table_config *table_config,
278 const char *attribute_name)
281 struct ldap_table_config *configs[] = { table_config, base_table_config };
283 for (i = 0; i < ARRAY_LEN(configs); i++) {
284 struct ast_variable *attribute;
290 attribute = configs[i]->attributes;
291 for (; attribute; attribute = attribute->next) {
292 if (strcasecmp(attribute_name, attribute->value) == 0) {
293 return attribute->name;
298 return attribute_name;
301 /*! \brief Get variables from ldap entry attributes
302 * \note Should be locked before using it
303 * \return a linked list of ast_variable variables.
305 static struct ast_variable *realtime_ldap_entry_to_var(struct ldap_table_config *table_config,
306 LDAPMessage *ldap_entry)
308 BerElement *ber = NULL;
309 struct ast_variable *var = NULL;
310 struct ast_variable *prev = NULL;
311 int is_delimited = 0;
313 char *ldap_attribute_name;
314 struct berval *value;
317 ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
319 while (ldap_attribute_name) {
320 struct berval **values = NULL;
321 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
322 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
324 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name); /* these are freed at the end */
329 for (v = values; *v; v++) {
331 valptr = value->bv_val;
332 ast_debug(2, "LINE(%d) attribute_name: %s LDAP value: %s\n", __LINE__, attribute_name, valptr);
333 if (is_realmed_password_attribute) {
334 if (!strncasecmp(valptr, "{md5}", 5)) {
337 ast_debug(2, "md5: %s\n", valptr);
340 /* ok, so looping through all delimited values except the last one (not, last character is not delimited...) */
344 while (!ast_strlen_zero(valptr + i)) {
345 if (valptr[i] == ';') {
348 prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
353 prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
360 /* for the last delimited value or if the value is not delimited: */
362 prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
367 prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
371 ldap_value_free_len(values);
373 ldap_memfree(ldap_attribute_name);
374 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
381 /*! \brief Get variables from ldap entry attributes - Should be locked before using it
383 * The results are freed outside this function so is the \a vars array.
385 * \return \a vars - an array of ast_variable variables terminated with a null.
387 static struct ast_variable **realtime_ldap_result_to_vars(struct ldap_table_config *table_config,
388 LDAPMessage *ldap_result_msg, unsigned int *entries_count_ptr)
390 struct ast_variable **vars;
394 LDAPMessage *ldap_entry = NULL;
395 BerElement *ber = NULL;
396 struct ast_variable *var = NULL;
397 struct ast_variable *prev = NULL;
398 int is_delimited = 0;
399 char *delim_value = NULL;
400 int delim_tot_count = 0;
403 /* First find the total count */
404 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
406 for (tot_count = 0; ldap_entry; tot_count++) {
407 struct ast_variable *tmp = realtime_ldap_entry_to_var(table_config, ldap_entry);
408 tot_count += semicolon_count_var(tmp);
409 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
410 ast_variables_destroy(tmp);
413 if (entries_count_ptr) {
414 *entries_count_ptr = tot_count;
417 /* Now that we have the total count we allocate space and create the variables
418 * Remember that each element in vars is a linked list that points to realtime variable.
419 * If the we are dealing with a static realtime variable we create a new element in the \a vars array for each delimited
420 * 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.
421 * This memory must be freed outside of this function.
423 vars = ast_calloc(sizeof(struct ast_variable *), tot_count + 1);
425 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
429 /* For each static realtime variable we may create several entries in the \a vars array if it's delimited */
430 for (entry_index = 0; ldap_entry; ) {
436 do { /* while delim_count */
438 /* Starting new static var */
439 char *ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
440 struct berval *value;
441 while (ldap_attribute_name) {
442 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
443 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
444 struct berval **values = NULL;
446 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name);
451 for (v = values; *v; v++) {
453 valptr = value->bv_val;
454 if (is_realmed_password_attribute) {
455 if (strncasecmp(valptr, "{md5}", 5) == 0) {
458 ast_debug(2, "md5: %s\n", valptr);
461 if (delim_value == NULL && !is_realmed_password_attribute
462 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0)) {
464 delim_value = ast_strdup(valptr);
466 if ((delim_tot_count = semicolon_count_str(delim_value)) > 0) {
467 ast_debug(4, "LINE(%d) is delimited %d times: %s\n", __LINE__, delim_tot_count, delim_value);
472 if (is_delimited != 0 && !is_realmed_password_attribute
473 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0) ) {
474 /* for non-Static RealTime, first */
476 for (i = pos; !ast_strlen_zero(valptr + i); i++) {
477 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
478 if (delim_value[i] == ';') {
479 delim_value[i] = '\0';
481 ast_debug(2, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
484 prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
489 prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
493 if (static_table_config == table_config) {
498 if (ast_strlen_zero(valptr + i)) {
499 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d delim_count: %d\n", __LINE__, pos, i, delim_count);
500 /* Last delimited value */
501 ast_debug(4, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
503 prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
508 prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
510 /* Remembering to free memory */
517 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
524 ast_debug(2, "LINE(%d) attribute_name: %s value: %s\n", __LINE__, attribute_name, valptr);
527 prev->next = ast_variable_new(attribute_name, valptr, table_config->table_name);
532 prev = var = ast_variable_new(attribute_name, valptr, table_config->table_name);
536 } /*!< for (v = values; *v; v++) */
537 ldap_value_free_len(values);
539 ldap_memfree(ldap_attribute_name);
540 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
541 } /*!< while (ldap_attribute_name) */
543 if (static_table_config == table_config) {
544 if (option_debug > 2) {
545 const struct ast_variable *tmpdebug = variable_named(var, "variable_name");
546 const struct ast_variable *tmpdebug2 = variable_named(var, "variable_value");
547 if (tmpdebug && tmpdebug2) {
548 ast_debug(3, "LINE(%d) Added to vars - %s = %s\n", __LINE__, tmpdebug->value, tmpdebug2->value);
551 vars[entry_index++] = var;
556 } while (delim_count <= delim_tot_count && static_table_config == table_config);
558 if (static_table_config != table_config) {
559 ast_debug(3, "LINE(%d) Added to vars - non static\n", __LINE__);
561 vars[entry_index++] = var;
564 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
565 } /*!< end for loop over ldap_entry */
571 /*! \brief Check if we have a connection error
573 static int is_ldap_connect_error(int err)
575 return (err == LDAP_SERVER_DOWN || err == LDAP_TIMEOUT || err == LDAP_CONNECT_ERROR);
578 /*! \brief Get LDAP entry by dn and return attributes as variables
580 * Should be locked before using it
582 * This is used for setting the default values of an object
583 * i.e., with accountBaseDN
585 static struct ast_variable *ldap_loadentry(struct ldap_table_config *table_config,
589 ast_log(LOG_ERROR, "No table config\n");
592 struct ast_variable **vars = NULL;
593 struct ast_variable *var = NULL;
595 LDAPMessage *ldap_result_msg = NULL;
598 ast_debug(2, "ldap_loadentry dn=%s\n", dn);
601 result = ldap_search_ext_s(ldapConn, dn, LDAP_SCOPE_BASE,
602 "(objectclass=*)", NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &ldap_result_msg);
603 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
604 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
607 usleep(500000L * tries);
609 ldap_unbind_ext_s(ldapConn, NULL, NULL);
612 if (!ldap_reconnect()) {
617 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
619 if (result != LDAP_SUCCESS) {
620 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
621 ast_debug(2, "dn=%s\n", dn);
622 ast_mutex_unlock(&ldap_lock);
626 unsigned int *entries_count_ptr = NULL; /*!< not using this */
628 if ((num_entry = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
629 ast_debug(3, "num_entry: %d\n", num_entry);
631 vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
633 ast_log(LOG_NOTICE, "More than one entry for dn=%s. Take only 1st one\n", dn);
636 ast_debug(2, "Could not find any entry dn=%s.\n", dn);
639 ldap_msgfree(ldap_result_msg);
641 /* Chopping \a vars down to one variable */
643 struct ast_variable **p = vars;
645 /* Only take the first one. */
648 /* Destroy the rest. */
650 ast_variables_destroy(*p);
659 /*! \note caller should free returned pointer
661 static char *substituted(struct ast_channel *channel, const char *string)
663 #define MAXRESULT 2048
664 char *ret_string = NULL;
666 if (!ast_strlen_zero(string)) {
667 ret_string = ast_calloc(1, MAXRESULT);
668 pbx_substitute_variables_helper(channel, string, ret_string, MAXRESULT - 1);
670 ast_debug(2, "substituted: string: '%s' => '%s' \n", string, ret_string);
674 /*! \note caller should free returned pointer
676 static char *cleaned_basedn(struct ast_channel *channel, const char *basedn)
678 char *cbasedn = NULL;
681 cbasedn = substituted(channel, basedn);
682 if (*cbasedn == '"') {
684 if (!ast_strlen_zero(cbasedn)) {
685 int len = strlen(cbasedn);
686 if (cbasedn[len - 1] == '"')
687 cbasedn[len - 1] = '\0';
698 ast_debug(2, "basedn: '%s' => '%s' \n", basedn, cbasedn);
702 /*! \brief Replace \<search\> by \<by\> in string.
703 * \note No check is done on string allocated size !
705 static int replace_string_in_string(char *string, const char *search, const char *by)
707 int search_len = strlen(search);
708 int by_len = strlen(by);
710 char *p = strstr(string, search);
715 if (by_len == search_len) {
716 memcpy(p, by, by_len);
718 memmove(p + by_len, p + search_len, strlen(p + search_len) + 1);
719 memcpy(p, by, by_len);
721 p = strstr(p + by_len, search);
727 /*! \brief Append a name=value filter string. The filter string can grow.
729 static void append_var_and_value_to_filter(struct ast_str **filter,
730 struct ldap_table_config *table_config,
731 const char *name, const char *value)
733 char *new_name = NULL;
734 char *new_value = NULL;
735 char *like_pos = strstr(name, " LIKE");
737 ast_debug(2, "name='%s' value='%s'\n", name, value);
740 int len = like_pos - name;
742 name = new_name = ast_strdupa(name);
743 new_name[len] = '\0';
744 value = new_value = ast_strdupa(value);
745 replace_string_in_string(new_value, "\\_", "_");
746 replace_string_in_string(new_value, "%", "*");
749 name = convert_attribute_name_to_ldap(table_config, name);
751 ast_str_append(filter, 0, "(%s=%s)", name, value);
754 /*! \brief LDAP base function
755 * \return a null terminated array of ast_variable (one per entry) or NULL if no entry is found or if an error occured
756 * caller should free the returned array and ast_variables
757 * \param entries_count_ptr is a pointer to found entries count (can be NULL)
758 * \param basedn is the base DN
759 * \param table_name is the table_name (used dor attribute convertion and additional filter)
760 * \param ap contains null terminated list of pairs name/value
762 static struct ast_variable **realtime_ldap_base_ap(unsigned int *entries_count_ptr,
763 const char *basedn, const char *table_name, va_list ap)
765 struct ast_variable **vars = NULL;
766 const char *newparam = NULL;
767 const char *newval = NULL;
768 struct ldap_table_config *table_config = NULL;
769 char *clean_basedn = cleaned_basedn(NULL, basedn);
770 struct ast_str *filter = NULL;
773 LDAPMessage *ldap_result_msg = NULL;
776 ast_log(LOG_ERROR, "No table_name specified.\n");
777 ast_free(clean_basedn);
781 if (!(filter = ast_str_create(80))) {
782 ast_log(LOG_ERROR, "Can't initialize data structures.n");
783 ast_free(clean_basedn);
787 /* Get the first parameter and first value in our list of passed paramater/value pairs */
788 newparam = va_arg(ap, const char *);
789 newval = va_arg(ap, const char *);
791 if (!newparam || !newval) {
792 ast_log(LOG_ERROR, "Realtime retrieval requires at least 1 parameter"
793 " and 1 value to search on.\n");
795 ast_free(clean_basedn);
799 ast_mutex_lock(&ldap_lock);
801 /* We now have our complete statement; Lets connect to the server and execute it. */
802 if (!ldap_reconnect()) {
803 ast_mutex_unlock(&ldap_lock);
805 ast_free(clean_basedn);
809 table_config = table_config_for_table_name(table_name);
811 ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
812 ast_mutex_unlock(&ldap_lock);
814 ast_free(clean_basedn);
818 ast_str_append(&filter, 0, "(&");
820 if (table_config && table_config->additional_filter) {
821 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
823 if (table_config != base_table_config && base_table_config &&
824 base_table_config->additional_filter) {
825 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
828 /* Create the first part of the query using the first parameter/value pairs we just extracted.
829 * If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat
832 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
833 while ((newparam = va_arg(ap, const char *))) {
834 newval = va_arg(ap, const char *);
835 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
837 ast_str_append(&filter, 0, ")");
840 /* freeing ldap_result further down */
841 result = ldap_search_ext_s(ldapConn, clean_basedn,
842 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
844 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
845 ast_debug(1, "Failed to query directory. Try %d/10\n", tries + 1);
849 ldap_unbind_ext_s(ldapConn, NULL, NULL);
852 if (!ldap_reconnect()) {
857 } while (result != LDAP_SUCCESS && tries < 10 && is_ldap_connect_error(result));
859 if (result != LDAP_SUCCESS) {
860 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
861 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
863 /* this is where we create the variables from the search result
864 * freeing this \a vars outside this function */
865 if (ldap_count_entries(ldapConn, ldap_result_msg) > 0) {
866 /* is this a static var or some other? they are handled different for delimited values */
867 vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
869 ast_debug(1, "Could not find any entry matching %s in base dn %s.\n", ast_str_buffer(filter), clean_basedn);
872 ldap_msgfree(ldap_result_msg);
874 /*! \TODO get the default variables from the accountBaseDN, not implemented with delimited values
877 struct ast_variable **p = vars;
879 struct ast_variable *append_var = NULL;
880 struct ast_variable *tmp = *p;
882 if (strcasecmp(tmp->name, "accountBaseDN") == 0) {
883 /* Get the variable to compare with for the defaults */
884 struct ast_variable *base_var = ldap_loadentry(table_config, tmp->value);
887 struct ast_variable *next = base_var->next;
888 struct ast_variable *test_var = *p;
889 int base_var_found = 0;
891 /* run throught the default values and fill it inn if it is missing */
893 if (strcasecmp(test_var->name, base_var->name) == 0) {
897 test_var = test_var->next;
900 if (base_var_found) {
901 base_var->next = NULL;
902 ast_variables_destroy(base_var);
906 * \todo XXX The interactions with base_var and append_var may
907 * cause a memory leak of base_var nodes. Also the append_var
908 * list and base_var list may get cross linked.
911 base_var->next = append_var;
913 base_var->next = NULL;
915 append_var = base_var;
920 if (!tmp->next && append_var) {
921 tmp->next = append_var;
937 ast_free(clean_basedn);
940 ast_mutex_unlock(&ldap_lock);
945 /*! \brief same as realtime_ldap_base_ap but take variable arguments count list
947 static struct ast_variable **realtime_ldap_base(unsigned int *entries_count_ptr,
948 const char *basedn, const char *table_name, ...)
950 struct ast_variable **vars = NULL;
953 va_start(ap, table_name);
954 vars = realtime_ldap_base_ap(entries_count_ptr, basedn, table_name, ap);
960 /*! \brief See Asterisk doc
962 * For Realtime Dynamic(i.e., switch, queues, and directory) -- I think
964 static struct ast_variable *realtime_ldap(const char *basedn,
965 const char *table_name, va_list ap)
967 struct ast_variable **vars = realtime_ldap_base_ap(NULL, basedn, table_name, ap);
968 struct ast_variable *var = NULL;
971 struct ast_variable *last_var = NULL;
972 struct ast_variable **p = vars;
974 /* Chain the vars array of lists into one list to return. */
977 while (last_var->next) {
978 last_var = last_var->next;
992 /*! \brief See Asterisk doc
994 * 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);
995 * however, the ast_load_realtime wil match on wildcharacters also depending on what the mode is set to
996 * this is an area of asterisk that could do with a lot of modification
997 * I think this function returns Realtime dynamic objects
999 static struct ast_config *realtime_multi_ldap(const char *basedn,
1000 const char *table_name, va_list ap)
1003 const char *initfield = NULL;
1004 const char *newparam, *newval;
1005 struct ast_variable **vars =
1006 realtime_ldap_base_ap(NULL, basedn, table_name, ap);
1007 struct ast_config *cfg = NULL;
1009 newparam = va_arg(ap, const char *);
1010 newval = va_arg(ap, const char *);
1011 if (!newparam || !newval) {
1012 ast_log(LOG_WARNING, "realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
1015 initfield = ast_strdupa(newparam);
1016 if ((op = strchr(initfield, ' '))) {
1021 cfg = ast_config_new();
1023 ast_log(LOG_ERROR, "Unable to create a config!\n");
1025 struct ast_variable **p = vars;
1028 struct ast_category *cat = NULL;
1029 cat = ast_category_new("", table_name, -1);
1031 ast_log(LOG_ERROR, "Unable to create a new category!\n");
1034 struct ast_variable *var = *p;
1036 struct ast_variable *next = var->next;
1037 if (initfield && !strcmp(initfield, var->name)) {
1038 ast_category_rename(cat, var->value);
1041 ast_variable_append(cat, var);
1045 ast_category_append(cfg, cat);
1055 /*! \brief Sorting alogrithm for qsort to find the order of the variables \a a and \a b
1056 * \param a pointer to category_and_metric struct
1057 * \param b pointer to category_and_metric struct
1059 * \retval -1 for if b is greater
1060 * \retval 0 zero for equal
1061 * \retval 1 if a is greater
1063 static int compare_categories(const void *a, const void *b)
1065 const struct category_and_metric *as = a;
1066 const struct category_and_metric *bs = b;
1068 if (as->metric < bs->metric) {
1070 } else if (as->metric > bs->metric) {
1072 } else if (as->metric == bs->metric && strcmp(as->name, bs->name) != 0) {
1073 return strcmp(as->name, bs->name);
1075 /* if the metric and the category name is the same, we check the variable metric */
1076 if (as->var_metric < bs->var_metric) {
1078 } else if (as->var_metric > bs->var_metric) {
1085 /*! \brief See Asterisk doc
1087 * This is for Static Realtime (again: I think...)
1089 * load the configuration stuff for the .conf files
1090 * called on a reload
1092 static struct ast_config *config_ldap(const char *basedn, const char *table_name,
1093 const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *sugg_incl, const char *who_asked)
1095 unsigned int vars_count = 0;
1096 struct ast_variable **vars;
1098 struct ast_variable *new_v = NULL;
1099 struct ast_category *cur_cat = NULL;
1100 const char *last_category = NULL;
1101 int last_category_metric = 0;
1102 struct category_and_metric *categories;
1103 struct ast_variable **p;
1105 if (ast_strlen_zero(file) || !strcasecmp(file, RES_CONFIG_LDAP_CONF)) {
1106 ast_log(LOG_ERROR, "Missing configuration file: %s. Can't configure myself.\n", RES_CONFIG_LDAP_CONF);
1110 vars = realtime_ldap_base(&vars_count, basedn, table_name, "filename", file, "commented", "FALSE", NULL);
1113 ast_log(LOG_WARNING, "Could not find config '%s' in directory.\n", file);
1117 /*! \note Since the items come back in random order, they need to be sorted
1118 * first, and since the data could easily exceed stack size, this is
1119 * allocated from the heap.
1121 if (!(categories = ast_calloc(sizeof(*categories), vars_count))) {
1125 for (vars_count = 0, p = vars; *p; p++) {
1126 struct ast_variable *category = variable_named(*p, "category");
1127 struct ast_variable *cat_metric = variable_named(*p, "cat_metric");
1128 struct ast_variable *var_name = variable_named(*p, "variable_name");
1129 struct ast_variable *var_val = variable_named(*p, "variable_value");
1130 struct ast_variable *var_metric = variable_named(*p, "var_metric");
1131 struct ast_variable *dn = variable_named(*p, "dn");
1134 ast_log(LOG_ERROR, "No category name in entry '%s' for file '%s'.\n",
1135 (dn ? dn->value : "?"), file);
1136 } else if (!cat_metric) {
1137 ast_log(LOG_ERROR, "No category metric in entry '%s'(category: %s) for file '%s'.\n",
1138 (dn ? dn->value : "?"), category->value, file);
1139 } else if (!var_metric) {
1140 ast_log(LOG_ERROR, "No variable metric in entry '%s'(category: %s) for file '%s'.\n",
1141 (dn ? dn->value : "?"), category->value, file);
1142 } else if (!var_name) {
1143 ast_log(LOG_ERROR, "No variable name in entry '%s' (category: %s metric: %s) for file '%s'.\n",
1144 (dn ? dn->value : "?"), category->value,
1145 cat_metric->value, file);
1146 } else if (!var_val) {
1147 ast_log(LOG_ERROR, "No variable value in entry '%s' (category: %s metric: %s variable: %s) for file '%s'.\n",
1148 (dn ? dn->value : "?"), category->value,
1149 cat_metric->value, var_name->value, file);
1151 categories[vars_count].name = category->value;
1152 categories[vars_count].metric = atoi(cat_metric->value);
1153 categories[vars_count].variable_name = var_name->value;
1154 categories[vars_count].variable_value = var_val->value;
1155 categories[vars_count].var_metric = atoi(var_metric->value);
1159 ast_debug(3, "category: %s\n", category->value);
1160 ast_debug(3, "var_name: %s\n", var_name->value);
1161 ast_debug(3, "var_val: %s\n", var_val->value);
1162 ast_debug(3, "cat_metric: %s\n", cat_metric->value);
1166 qsort(categories, vars_count, sizeof(*categories), compare_categories);
1168 for (i = 0; i < vars_count; i++) {
1169 if (!strcmp(categories[i].variable_name, "#include")) {
1170 struct ast_flags flags = { 0 };
1171 if (!ast_config_internal_load(categories[i].variable_value, cfg, flags, "", who_asked)) {
1177 if (!last_category || strcmp(last_category, categories[i].name) ||
1178 last_category_metric != categories[i].metric) {
1180 cur_cat = ast_category_new(categories[i].name, table_name, -1);
1184 last_category = categories[i].name;
1185 last_category_metric = categories[i].metric;
1186 ast_category_append(cfg, cur_cat);
1189 if (!(new_v = ast_variable_new(categories[i].variable_name, categories[i].variable_value, table_name))) {
1193 ast_variable_append(cur_cat, new_v);
1197 ast_free(categories);
1202 /* \brief Function to update a set of values in ldap static mode
1204 static int update_ldap(const char *basedn, const char *table_name, const char *attribute,
1205 const char *lookup, va_list ap)
1208 LDAPMessage *ldap_entry = NULL;
1209 LDAPMod **ldap_mods;
1210 const char *newparam = NULL;
1211 const char *newval = NULL;
1213 int num_entries = 0;
1217 struct ldap_table_config *table_config = NULL;
1218 char *clean_basedn = NULL;
1219 struct ast_str *filter = NULL;
1222 LDAPMessage *ldap_result_msg = NULL;
1225 ast_log(LOG_ERROR, "No table_name specified.\n");
1229 if (!(filter = ast_str_create(80))) {
1233 if (!attribute || !lookup) {
1234 ast_log(LOG_WARNING, "LINE(%d): search parameters are empty.\n", __LINE__);
1237 ast_mutex_lock(&ldap_lock);
1239 /* We now have our complete statement; Lets connect to the server and execute it. */
1240 if (!ldap_reconnect()) {
1241 ast_mutex_unlock(&ldap_lock);
1245 table_config = table_config_for_table_name(table_name);
1246 if (!table_config) {
1247 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1248 ast_mutex_unlock(&ldap_lock);
1252 clean_basedn = cleaned_basedn(NULL, basedn);
1254 /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1255 ast_str_append(&filter, 0, "(&");
1256 if (table_config && table_config->additional_filter) {
1257 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1259 if (table_config != base_table_config && base_table_config && base_table_config->additional_filter) {
1260 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1262 append_var_and_value_to_filter(&filter, table_config, attribute, lookup);
1263 ast_str_append(&filter, 0, ")");
1265 /* Create the modification array with the parameter/value pairs we were given,
1266 * if there are several parameters with the same name, we collect them into
1267 * one parameter/value pair and delimit them with a semicolon */
1268 newparam = va_arg(ap, const char *);
1269 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1270 newval = va_arg(ap, const char *);
1271 if (!newparam || !newval) {
1272 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1276 mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1277 ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1278 ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1280 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1281 ldap_mods[0]->mod_type = ast_strdup(newparam);
1283 ldap_mods[0]->mod_values = ast_calloc(sizeof(char *), 2);
1284 ldap_mods[0]->mod_values[0] = ast_strdup(newval);
1286 while ((newparam = va_arg(ap, const char *))) {
1287 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1288 newval = va_arg(ap, const char *);
1291 for (i = 0; i < mods_size - 1; i++) {
1292 if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1293 /* We have the parameter allready, adding the value as a semicolon delimited value */
1294 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));
1295 strcat(ldap_mods[i]->mod_values[0], ";");
1296 strcat(ldap_mods[i]->mod_values[0], newval);
1302 /* create new mod */
1305 ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1306 ldap_mods[mods_size - 1] = NULL;
1308 ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1310 ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1311 strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1313 if (strlen(newval) == 0) {
1314 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
1316 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1318 ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1319 ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1320 strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
1324 /* freeing ldap_mods further down */
1327 /* freeing ldap_result further down */
1328 result = ldap_search_ext_s(ldapConn, clean_basedn,
1329 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1331 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1332 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1335 usleep(500000L * tries);
1337 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1340 if (!ldap_reconnect())
1344 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1346 if (result != LDAP_SUCCESS) {
1347 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1348 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1350 ast_mutex_unlock(&ldap_lock);
1353 ldap_msgfree(ldap_result_msg);
1354 ldap_mods_free(ldap_mods, 0);
1357 /* Ready to update */
1358 if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1359 ast_debug(3, "LINE(%d) Modifying %s=%s hits: %d\n", __LINE__, attribute, lookup, num_entries);
1360 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1361 if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
1362 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1364 ast_debug(3, "LINE(%d) deleting %s \n", __LINE__, ldap_mods[i]->mod_type);
1367 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1369 for (i = 0; ldap_entry; i++) {
1370 dn = ldap_get_dn(ldapConn, ldap_entry);
1371 if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1372 ast_log(LOG_ERROR, "Couldn't modify '%s'='%s', dn:%s because %s\n",
1373 attribute, lookup, dn, ldap_err2string(error));
1376 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1380 ast_mutex_unlock(&ldap_lock);
1382 ast_free(clean_basedn);
1383 ldap_msgfree(ldap_result_msg);
1384 ldap_mods_free(ldap_mods, 0);
1388 static int update2_ldap(const char *basedn, const char *table_name, va_list ap)
1391 LDAPMessage *ldap_entry = NULL;
1392 LDAPMod **ldap_mods;
1393 const char *newparam = NULL;
1394 const char *newval = NULL;
1396 int num_entries = 0;
1400 struct ldap_table_config *table_config = NULL;
1401 char *clean_basedn = NULL;
1402 struct ast_str *filter = NULL;
1405 LDAPMessage *ldap_result_msg = NULL;
1408 ast_log(LOG_ERROR, "No table_name specified.\n");
1412 if (!(filter = ast_str_create(80))) {
1416 ast_mutex_lock(&ldap_lock);
1418 /* We now have our complete statement; Lets connect to the server and execute it. */
1419 if (!ldap_reconnect()) {
1420 ast_mutex_unlock(&ldap_lock);
1425 table_config = table_config_for_table_name(table_name);
1426 if (!table_config) {
1427 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1428 ast_mutex_unlock(&ldap_lock);
1433 clean_basedn = cleaned_basedn(NULL, basedn);
1435 /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1436 ast_str_append(&filter, 0, "(&");
1437 if (table_config && table_config->additional_filter) {
1438 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1440 if (table_config != base_table_config && base_table_config
1441 && base_table_config->additional_filter) {
1442 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1445 /* Get multiple lookup keyfields and values */
1446 while ((newparam = va_arg(ap, const char *))) {
1447 newval = va_arg(ap, const char *);
1448 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
1450 ast_str_append(&filter, 0, ")");
1452 /* Create the modification array with the parameter/value pairs we were given,
1453 * if there are several parameters with the same name, we collect them into
1454 * one parameter/value pair and delimit them with a semicolon */
1455 newparam = va_arg(ap, const char *);
1456 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1457 newval = va_arg(ap, const char *);
1458 if (!newparam || !newval) {
1459 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1461 ast_free(clean_basedn);
1465 mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1466 ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1467 ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1469 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1470 ldap_mods[0]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1471 strcpy(ldap_mods[0]->mod_type, newparam);
1473 ldap_mods[0]->mod_values = ast_calloc(sizeof(char), 2);
1474 ldap_mods[0]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1475 strcpy(ldap_mods[0]->mod_values[0], newval);
1477 while ((newparam = va_arg(ap, const char *))) {
1478 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1479 newval = va_arg(ap, const char *);
1482 for (i = 0; i < mods_size - 1; i++) {
1483 if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1484 /* We have the parameter allready, adding the value as a semicolon delimited value */
1485 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));
1486 strcat(ldap_mods[i]->mod_values[0], ";");
1487 strcat(ldap_mods[i]->mod_values[0], newval);
1493 /* create new mod */
1496 ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1497 ldap_mods[mods_size - 1] = NULL;
1498 ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1500 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1502 ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1503 strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1505 ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1506 ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1507 strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
1510 /* freeing ldap_mods further down */
1513 /* freeing ldap_result further down */
1514 result = ldap_search_ext_s(ldapConn, clean_basedn,
1515 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1517 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1518 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1521 usleep(500000L * tries);
1523 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1526 if (!ldap_reconnect()) {
1531 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1533 if (result != LDAP_SUCCESS) {
1534 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1535 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1537 ast_mutex_unlock(&ldap_lock);
1539 ast_free(clean_basedn);
1540 ldap_msgfree(ldap_result_msg);
1541 ldap_mods_free(ldap_mods, 0);
1544 /* Ready to update */
1545 if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1546 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1547 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1550 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1552 for (i = 0; ldap_entry; i++) {
1553 dn = ldap_get_dn(ldapConn, ldap_entry);
1554 if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1555 ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
1558 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1562 ast_mutex_unlock(&ldap_lock);
1567 ast_free(clean_basedn);
1569 ldap_msgfree(ldap_result_msg);
1570 ldap_mods_free(ldap_mods, 0);
1574 static struct ast_config_engine ldap_engine = {
1576 .load_func = config_ldap,
1577 .realtime_func = realtime_ldap,
1578 .realtime_multi_func = realtime_multi_ldap,
1579 .update_func = update_ldap,
1580 .update2_func = update2_ldap,
1584 * \brief Load the module
1586 * Module loading including tests for configuration or dependencies.
1587 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
1588 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
1589 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
1590 * configuration file or other non-critical problem return
1591 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
1593 * \todo Don't error or warn on a default install. If the config is
1594 * default we should not attempt to connect to a server. -lathama
1596 static int load_module(void)
1598 if (parse_config() < 0) {
1599 ast_log(LOG_ERROR, "Cannot load LDAP RealTime driver.\n");
1603 ast_mutex_lock(&ldap_lock);
1605 if (!ldap_reconnect()) {
1606 ast_log(LOG_WARNING, "Couldn't establish connection to LDAP directory. Check debug.\n");
1609 ast_config_engine_register(&ldap_engine);
1610 ast_verb(1, "LDAP RealTime driver loaded.\n");
1611 ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1613 ast_mutex_unlock(&ldap_lock);
1618 static int unload_module(void)
1620 /* Aquire control before doing anything to the module itself. */
1621 ast_mutex_lock(&ldap_lock);
1623 table_configs_free();
1626 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1629 ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1630 ast_config_engine_deregister(&ldap_engine);
1631 ast_verb(1, "LDAP RealTime driver unloaded.\n");
1633 /* Unlock so something else can destroy the lock. */
1634 ast_mutex_unlock(&ldap_lock);
1639 static int reload(void)
1641 /* Aquire control before doing anything to the module itself. */
1642 ast_mutex_lock(&ldap_lock);
1645 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1649 if (parse_config() < 0) {
1650 ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
1651 ast_mutex_unlock(&ldap_lock);
1655 if (!ldap_reconnect()) {
1656 ast_log(LOG_WARNING, "Couldn't establish connection to your directory server. Check debug.\n");
1659 ast_verb(2, "LDAP RealTime driver reloaded.\n");
1661 /* Done reloading. Release lock so others can now use driver. */
1662 ast_mutex_unlock(&ldap_lock);
1667 /*! \brief parse the configuration file */
1668 static int parse_config(void)
1670 struct ast_config *config;
1671 struct ast_flags config_flags = {0};
1672 const char *s, *host;
1674 char *category_name = NULL;
1676 /* Make sure that global variables are reset */
1680 base_distinguished_name[0] = '\0';
1683 config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
1684 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1685 ast_log(LOG_ERROR, "Cannot load configuration file: %s\n", RES_CONFIG_LDAP_CONF);
1689 if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
1690 ast_log(LOG_NOTICE, "No directory user found, anonymous binding as default.\n");
1693 ast_copy_string(user, s, sizeof(user));
1696 if (!ast_strlen_zero(user)) {
1697 if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
1698 ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
1699 ast_copy_string(pass, "asterisk", sizeof(pass));
1701 ast_copy_string(pass, s, sizeof(pass));
1705 /* URL is preferred, use host and port if not found */
1706 if ((s = ast_variable_retrieve(config, "_general", "url"))) {
1707 ast_copy_string(url, s, sizeof(url));
1708 } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
1709 if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
1710 ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
1714 snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
1716 ast_log(LOG_ERROR, "No directory URL or host found.\n");
1717 ast_config_destroy(config);
1721 if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
1722 ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
1723 ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
1725 ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
1727 if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
1728 ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
1729 } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
1730 ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
1734 table_configs_free();
1736 while ((category_name = ast_category_browse(config, category_name))) {
1737 int is_general = (strcasecmp(category_name, "_general") == 0);
1738 int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
1739 struct ast_variable *var = ast_variable_browse(config, category_name);
1742 struct ldap_table_config *table_config =
1743 table_config_for_table_name(category_name);
1744 if (!table_config) {
1745 table_config = table_config_new(category_name);
1746 AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
1748 base_table_config = table_config;
1750 static_table_config = table_config;
1752 for (; var; var = var->next) {
1753 if (!strcasecmp(var->name, "additionalFilter")) {
1754 table_config->additional_filter = ast_strdup(var->value);
1756 ldap_table_config_add_attribute(table_config, var->name, var->value);
1762 ast_config_destroy(config);
1767 /*! \note ldap_lock should have been locked before calling this function. */
1768 static int ldap_reconnect(void)
1770 int bind_result = 0;
1774 ast_debug(2, "Everything seems fine.\n");
1778 if (ast_strlen_zero(url)) {
1779 ast_log(LOG_ERROR, "Not enough parameters to connect to ldap directory\n");
1783 if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
1784 ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
1788 if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
1789 ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
1792 if (!ast_strlen_zero(user)) {
1793 ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
1794 cred.bv_val = (char *) pass;
1795 cred.bv_len = strlen(pass);
1796 bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1798 ast_debug(2, "bind %s anonymously\n", url);
1801 bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1803 if (bind_result == LDAP_SUCCESS) {
1804 ast_debug(2, "Successfully connected to directory.\n");
1805 connect_time = time(NULL);
1808 ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
1809 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1815 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1817 char status[256], credentials[100] = "";
1818 int ctimesec = time(NULL) - connect_time;
1822 e->command = "realtime show ldap status";
1824 "Usage: realtime show ldap status\n"
1825 " Shows connection information for the LDAP RealTime driver\n";
1834 if (!ast_strlen_zero(url))
1835 snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
1837 if (!ast_strlen_zero(user))
1838 snprintf(credentials, sizeof(credentials), " with username %s", user);
1840 if (ctimesec > 31536000) {
1841 ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1842 status, credentials, ctimesec / 31536000,
1843 (ctimesec % 31536000) / 86400, (ctimesec % 86400) / 3600,
1844 (ctimesec % 3600) / 60, ctimesec % 60);
1845 } else if (ctimesec > 86400) {
1846 ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n",
1847 status, credentials, ctimesec / 86400, (ctimesec % 86400) / 3600,
1848 (ctimesec % 3600) / 60, ctimesec % 60);
1849 } else if (ctimesec > 3600) {
1850 ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n",
1851 status, credentials, ctimesec / 3600, (ctimesec % 3600) / 60,
1853 } else if (ctimesec > 60) {
1854 ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials,
1855 ctimesec / 60, ctimesec % 60);
1857 ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1863 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "LDAP realtime interface",
1864 .load = load_module,
1865 .unload = unload_module,
1867 .load_pri = AST_MODPRI_REALTIME_DRIVER,