2 * Asterisk -- A telephony toolkit for Linux.
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 * \extref OpenLDAP http://www.openldap.org
46 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
48 #include "asterisk/channel.h"
49 #include "asterisk/logger.h"
50 #include "asterisk/config.h"
51 #include "asterisk/module.h"
52 #include "asterisk/lock.h"
53 #include "asterisk/options.h"
54 #include "asterisk/cli.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/strings.h"
57 #include "asterisk/pbx.h"
58 #include "asterisk/linkedlists.h"
60 #define RES_CONFIG_LDAP_CONF "res_ldap.conf"
61 #define RES_CONFIG_LDAP_DEFAULT_BASEDN "asterisk"
63 AST_MUTEX_DEFINE_STATIC(ldap_lock);
65 static LDAP *ldapConn;
67 static char user[512];
68 static char pass[512];
69 static char base_distinguished_name[512];
71 static time_t connect_time;
73 static int parse_config(void);
74 static int ldap_reconnect(void);
75 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
77 struct category_and_metric {
80 const char *variable_name;
81 const char *variable_value;
82 int var_metric; /*!< For organizing variables (particularly includes and switch statments) within a context */
85 /*! \brief Table configuration */
86 struct ldap_table_config {
87 char *table_name; /*!< table name */
88 char *additional_filter; /*!< additional filter */
89 struct ast_variable *attributes; /*!< attribute names conversion */
90 struct ast_variable *delimiters; /*!< the current delimiter is semicolon, so we are not using this variable */
91 AST_LIST_ENTRY(ldap_table_config) entry;
92 /* TODO: Make proxies work */
95 /*! \brief Should be locked before using it */
96 static AST_LIST_HEAD_NOLOCK_STATIC(table_configs, ldap_table_config);
97 static struct ldap_table_config *base_table_config;
98 static struct ldap_table_config *static_table_config;
100 static struct ast_cli_entry ldap_cli[] = {
101 AST_CLI_DEFINE(realtime_ldap_status, "Shows connection information for the LDAP RealTime driver"),
104 /*! \brief Create a new table_config */
105 static struct ldap_table_config *table_config_new(const char *table_name)
107 struct ldap_table_config *p;
109 if (!(p = ast_calloc(1, sizeof(*p))))
113 if (!(p->table_name = ast_strdup(table_name))) {
122 /*! \brief Find a table_config - Should be locked before using it
123 * \note This function assumes ldap_lock to be locked. */
124 static struct ldap_table_config *table_config_for_table_name(const char *table_name)
126 struct ldap_table_config *c = NULL;
128 AST_LIST_TRAVERSE(&table_configs, c, entry) {
129 if (!strcmp(c->table_name, table_name))
136 /*! \brief Find variable by name */
137 static struct ast_variable *variable_named(struct ast_variable *var, const char *name)
139 for (; var; var = var->next) {
140 if (!strcasecmp(name, var->name))
147 /*! \brief for the semicolon delimiter
148 \param somestr - pointer to a string
150 \return number of occurances of the delimiter(semicolon)
152 static int semicolon_count_str(const char *somestr)
156 for (; *somestr; somestr++) {
164 /* takes a linked list of \a ast_variable variables, finds the one with the name variable_value
165 * and returns the number of semicolons in the value for that \a ast_variable
167 static int semicolon_count_var(struct ast_variable *var)
169 struct ast_variable *var_value = variable_named(var, "variable_value");
175 ast_debug(2, "LINE(%d) semicolon_count_var: %s\n", __LINE__, var_value->value);
177 return semicolon_count_str(var_value->value);
180 /*! \brief add attribute to table config - Should be locked before using it */
181 static void ldap_table_config_add_attribute(struct ldap_table_config *table_config,
182 const char *attribute_name, const char *attribute_value)
184 struct ast_variable *var;
186 if (ast_strlen_zero(attribute_name) || ast_strlen_zero(attribute_value)) {
190 if (!(var = ast_variable_new(attribute_name, attribute_value, table_config->table_name))) {
194 if (table_config->attributes) {
195 var->next = table_config->attributes;
197 table_config->attributes = var;
200 /*! \brief Free table_config
201 * \note assumes ldap_lock to be locked */
202 static void table_configs_free(void)
204 struct ldap_table_config *c;
206 while ((c = AST_LIST_REMOVE_HEAD(&table_configs, entry))) {
208 ast_free(c->table_name);
210 if (c->additional_filter) {
211 ast_free(c->additional_filter);
214 ast_variables_destroy(c->attributes);
219 base_table_config = NULL;
220 static_table_config = NULL;
223 /*! \brief Convert variable name to ldap attribute name - Should be locked before using it */
224 static const char *convert_attribute_name_to_ldap(struct ldap_table_config *table_config,
225 const char *attribute_name)
228 struct ldap_table_config *configs[] = { table_config, base_table_config };
230 for (i = 0; i < ARRAY_LEN(configs); i++) {
231 struct ast_variable *attribute;
237 attribute = configs[i]->attributes;
238 for (; attribute; attribute = attribute->next) {
239 if (!strcasecmp(attribute_name, attribute->name)) {
240 return attribute->value;
245 return attribute_name;
248 /*! \brief Convert ldap attribute name to variable name
249 \note Should be locked before using it */
250 static const char *convert_attribute_name_from_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->value) == 0) {
266 return attribute->name;
271 return attribute_name;
274 /*! \brief Get variables from ldap entry attributes
275 \note Should be locked before using it
276 \return a linked list of ast_variable variables.
278 static struct ast_variable *realtime_ldap_entry_to_var(struct ldap_table_config *table_config,
279 LDAPMessage *ldap_entry)
281 BerElement *ber = NULL;
282 struct ast_variable *var = NULL;
283 struct ast_variable *prev = NULL;
284 int is_delimited = 0;
286 char *ldap_attribute_name;
287 struct berval *value;
290 ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
292 while (ldap_attribute_name) {
293 struct berval **values = NULL;
294 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
295 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
297 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name); /* these are freed at the end */
302 for (v = values; *v; v++) {
304 valptr = value->bv_val;
305 ast_debug(2, "LINE(%d) attribute_name: %s LDAP value: %s\n", __LINE__, attribute_name, valptr);
306 if (is_realmed_password_attribute) {
307 if (!strncasecmp(valptr, "{md5}", 5)) {
310 ast_debug(2, "md5: %s\n", valptr);
313 /* ok, so looping through all delimited values except the last one (not, last character is not delimited...) */
317 while (!ast_strlen_zero(valptr + i)) {
318 if (valptr[i] == ';') {
321 prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
326 prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
333 /* for the last delimited value or if the value is not delimited: */
335 prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
340 prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
344 ldap_value_free_len(values);
346 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
353 /*! \brief Get variables from ldap entry attributes - Should be locked before using it
355 * The results are freed outside this function so is the \a vars array.
357 * \return \a vars - an array of ast_variable variables terminated with a null.
359 static struct ast_variable **realtime_ldap_result_to_vars(struct ldap_table_config *table_config,
360 LDAPMessage *ldap_result_msg, unsigned int *entries_count_ptr)
362 struct ast_variable **vars;
366 LDAPMessage *ldap_entry = NULL;
367 BerElement *ber = NULL;
368 struct ast_variable *var = NULL;
369 struct ast_variable *prev = NULL;
370 int is_delimited = 0;
371 char *delim_value = NULL;
372 int delim_tot_count = 0;
375 /* First find the total count */
376 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
378 for (tot_count = 0; ldap_entry; tot_count++) {
379 struct ast_variable *tmp = realtime_ldap_entry_to_var(table_config, ldap_entry);
380 tot_count += semicolon_count_var(tmp);
381 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
382 ast_variables_destroy(tmp);
385 if (entries_count_ptr) {
386 *entries_count_ptr = tot_count;
389 /* Now that we have the total count we allocate space and create the variables
390 * Remember that each element in vars is a linked list that points to realtime variable.
391 * If the we are dealing with a static realtime variable we create a new element in the \a vars array for each delimited
392 * 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.
393 * This memory must be freed outside of this function. */
394 vars = ast_calloc(sizeof(struct ast_variable *), tot_count + 1);
396 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
400 /* For each static realtime variable we may create several entries in the \a vars array if it's delimited */
401 for (entry_index = 0; ldap_entry; ) {
407 do { /* while delim_count */
409 /* Starting new static var */
410 char *ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
411 struct berval *value;
412 while (ldap_attribute_name) {
414 const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
415 int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
416 struct berval **values = NULL;
418 values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name);
423 for (v = values; *v; v++) {
425 valptr = value->bv_val;
426 if (is_realmed_password_attribute) {
427 if (strncasecmp(valptr, "{md5}", 5) == 0) {
430 ast_debug(2, "md5: %s\n", valptr);
433 if (delim_value == NULL && !is_realmed_password_attribute
434 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0)) {
436 delim_value = ast_strdup(valptr);
438 if ((delim_tot_count = semicolon_count_str(delim_value)) > 0) {
439 ast_debug(4, "LINE(%d) is delimited %d times: %s\n", __LINE__, delim_tot_count, delim_value);
444 if (is_delimited != 0 && !is_realmed_password_attribute
445 && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0) ) {
446 /* for non-Static RealTime, first */
448 for (i = pos; !ast_strlen_zero(valptr + i); i++) {
449 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
450 if (delim_value[i] == ';') {
451 delim_value[i] = '\0';
453 ast_debug(2, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
456 prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
461 prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
465 if (static_table_config == table_config) {
470 if (ast_strlen_zero(valptr + i)) {
471 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d delim_count: %d\n", __LINE__, pos, i, delim_count);
472 /* Last delimited value */
473 ast_debug(4, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
475 prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
480 prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
482 /* Remembering to free memory */
489 ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
496 ast_debug(2, "LINE(%d) attribute_name: %s value: %s\n", __LINE__, attribute_name, valptr);
499 prev->next = ast_variable_new(attribute_name, valptr, table_config->table_name);
504 prev = var = ast_variable_new(attribute_name, valptr, table_config->table_name);
508 } /*!< for (v = values; *v; v++) */
509 ldap_value_free_len(values);
511 ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
512 } /*!< while (ldap_attribute_name) */
514 if (static_table_config == table_config) {
515 if (option_debug > 2) {
516 const struct ast_variable *tmpdebug = variable_named(var, "variable_name");
517 const struct ast_variable *tmpdebug2 = variable_named(var, "variable_value");
518 if (tmpdebug && tmpdebug2) {
519 ast_debug(3, "LINE(%d) Added to vars - %s = %s\n", __LINE__, tmpdebug->value, tmpdebug2->value);
522 vars[entry_index++] = var;
527 } while (delim_count <= delim_tot_count && static_table_config == table_config);
529 if (static_table_config != table_config) {
530 ast_debug(3, "LINE(%d) Added to vars - non static\n", __LINE__);
532 vars[entry_index++] = var;
535 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
536 } /*!< end for loop over ldap_entry */
542 /*! \brief Check if we have a connection error */
543 static int is_ldap_connect_error(int err)
545 return (err == LDAP_SERVER_DOWN || err == LDAP_TIMEOUT || err == LDAP_CONNECT_ERROR);
548 /*! \brief Get LDAP entry by dn and return attributes as variables - Should be locked before using it
549 This is used for setting the default values of an object(i.e., with accountBaseDN)
551 static struct ast_variable *ldap_loadentry(struct ldap_table_config *table_config,
555 ast_log(LOG_ERROR, "No table config\n");
558 struct ast_variable **vars = NULL;
559 struct ast_variable *var = NULL;
561 LDAPMessage *ldap_result_msg = NULL;
564 ast_debug(2, "ldap_loadentry dn=%s\n", dn);
567 result = ldap_search_ext_s(ldapConn, dn, LDAP_SCOPE_BASE,
568 "(objectclass=*)", NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &ldap_result_msg);
569 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
570 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
573 usleep(500000L * tries);
575 ldap_unbind_ext_s(ldapConn, NULL, NULL);
578 if (!ldap_reconnect()) {
583 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
585 if (result != LDAP_SUCCESS) {
586 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
587 ast_debug(2, "dn=%s\n", dn);
588 ast_mutex_unlock(&ldap_lock);
592 unsigned int *entries_count_ptr = NULL; /*!< not using this */
594 if ((num_entry = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
595 ast_debug(3, "num_entry: %d\n", num_entry);
597 vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
599 ast_log(LOG_NOTICE, "More than one entry for dn=%s. Take only 1st one\n", dn);
602 ast_debug(2, "Could not find any entry dn=%s.\n", dn);
605 ldap_msgfree(ldap_result_msg);
607 /* Chopping \a vars down to one variable */
609 struct ast_variable **p = vars;
613 ast_variables_destroy(var);
616 vars = ast_realloc(vars, sizeof(struct ast_variable *));
625 /*! \note caller should free returned pointer */
626 static char *substituted(struct ast_channel *channel, const char *string)
628 #define MAXRESULT 2048
629 char *ret_string = NULL;
631 if (!ast_strlen_zero(string)) {
632 ret_string = ast_calloc(1, MAXRESULT);
633 pbx_substitute_variables_helper(channel, string, ret_string, MAXRESULT - 1);
635 ast_debug(2, "substituted: string: '%s' => '%s' \n", string, ret_string);
639 /*! \note caller should free returned pointer */
640 static char *cleaned_basedn(struct ast_channel *channel, const char *basedn)
642 char *cbasedn = NULL;
645 cbasedn = substituted(channel, basedn);
646 if (*cbasedn == '"') {
648 if (!ast_strlen_zero(cbasedn)) {
649 int len = strlen(cbasedn);
650 if (cbasedn[len - 1] == '"')
651 cbasedn[len - 1] = '\0';
662 ast_debug(2, "basedn: '%s' => '%s' \n", basedn, cbasedn);
666 /*! \brief Replace \<search\> by \<by\> in string.
667 \note No check is done on string allocated size ! */
668 static int replace_string_in_string(char *string, const char *search, const char *by)
670 int search_len = strlen(search);
671 int by_len = strlen(by);
673 char *p = strstr(string, search);
678 if (by_len == search_len) {
679 memcpy(p, by, by_len);
681 memmove(p + by_len, p + search_len, strlen(p + search_len) + 1);
682 memcpy(p, by, by_len);
684 p = strstr(p + by_len, search);
690 /*! \brief Append a name=value filter string. The filter string can grow. */
691 static void append_var_and_value_to_filter(struct ast_str **filter,
692 struct ldap_table_config *table_config,
693 const char *name, const char *value)
695 char *new_name = NULL;
696 char *new_value = NULL;
697 char *like_pos = strstr(name, " LIKE");
699 ast_debug(2, "name='%s' value='%s'\n", name, value);
702 int len = like_pos - name;
704 name = new_name = ast_strdupa(name);
705 new_name[len] = '\0';
706 value = new_value = ast_strdupa(value);
707 replace_string_in_string(new_value, "\\_", "_");
708 replace_string_in_string(new_value, "%", "*");
711 name = convert_attribute_name_to_ldap(table_config, name);
713 ast_str_append(filter, 0, "(%s=%s)", name, value);
716 /*! \brief LDAP base function
717 * \return a null terminated array of ast_variable (one per entry) or NULL if no entry is found or if an error occured
718 * caller should free the returned array and ast_variables
719 * \param entries_count_ptr is a pointer to found entries count (can be NULL)
720 * \param basedn is the base DN
721 * \param table_name is the table_name (used dor attribute convertion and additional filter)
722 * \param ap contains null terminated list of pairs name/value
724 static struct ast_variable **realtime_ldap_base_ap(unsigned int *entries_count_ptr,
725 const char *basedn, const char *table_name, va_list ap)
727 struct ast_variable **vars = NULL;
728 const char *newparam = NULL;
729 const char *newval = NULL;
730 struct ldap_table_config *table_config = NULL;
731 char *clean_basedn = cleaned_basedn(NULL, basedn);
732 struct ast_str *filter = NULL;
735 LDAPMessage *ldap_result_msg = NULL;
738 ast_log(LOG_ERROR, "No table_name specified.\n");
739 ast_free(clean_basedn);
743 if (!(filter = ast_str_create(80))) {
744 ast_log(LOG_ERROR, "Can't initialize data structures.n");
745 ast_free(clean_basedn);
749 /* Get the first parameter and first value in our list of passed paramater/value pairs */
750 newparam = va_arg(ap, const char *);
751 newval = va_arg(ap, const char *);
753 if (!newparam || !newval) {
754 ast_log(LOG_ERROR, "Realtime retrieval requires at least 1 parameter"
755 " and 1 value to search on.\n");
757 ast_free(clean_basedn);
761 ast_mutex_lock(&ldap_lock);
763 /* We now have our complete statement; Lets connect to the server and execute it. */
764 if (!ldap_reconnect()) {
765 ast_mutex_unlock(&ldap_lock);
767 ast_free(clean_basedn);
771 table_config = table_config_for_table_name(table_name);
773 ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
774 ast_mutex_unlock(&ldap_lock);
776 ast_free(clean_basedn);
780 ast_str_append(&filter, 0, "(&");
782 if (table_config && table_config->additional_filter) {
783 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
785 if (table_config != base_table_config && base_table_config &&
786 base_table_config->additional_filter) {
787 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
790 /* Create the first part of the query using the first parameter/value pairs we just extracted */
791 /* If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
793 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
794 while ((newparam = va_arg(ap, const char *))) {
795 newval = va_arg(ap, const char *);
796 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
798 ast_str_append(&filter, 0, ")");
801 /* freeing ldap_result further down */
802 result = ldap_search_ext_s(ldapConn, clean_basedn,
803 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
805 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
806 ast_log(LOG_DEBUG, "Failed to query directory. Try %d/10\n", tries + 1);
810 ldap_unbind_ext_s(ldapConn, NULL, NULL);
813 if (!ldap_reconnect()) {
818 } while (result != LDAP_SUCCESS && tries < 10 && is_ldap_connect_error(result));
820 if (result != LDAP_SUCCESS) {
821 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
822 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
824 /* this is where we create the variables from the search result
825 * freeing this \a vars outside this function */
826 if (ldap_count_entries(ldapConn, ldap_result_msg) > 0) {
827 /* is this a static var or some other? they are handled different for delimited values */
828 vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
830 ast_debug(1, "Could not find any entry matching %s in base dn %s.\n", ast_str_buffer(filter), clean_basedn);
833 ldap_msgfree(ldap_result_msg);
835 /* TODO: get the default variables from the accountBaseDN, not implemented with delimited values */
837 struct ast_variable **p = vars;
839 struct ast_variable *append_var = NULL;
840 struct ast_variable *tmp = *p;
842 if (strcasecmp(tmp->name, "accountBaseDN") == 0) {
843 /* Get the variable to compare with for the defaults */
844 struct ast_variable *base_var = ldap_loadentry(table_config, tmp->value);
847 struct ast_variable *next = base_var->next;
848 struct ast_variable *test_var = *p;
849 int base_var_found = 0;
851 /* run throught the default values and fill it inn if it is missing */
853 if (strcasecmp(test_var->name, base_var->name) == 0) {
857 test_var = test_var->next;
860 if (base_var_found) {
861 base_var->next = NULL;
862 ast_variables_destroy(base_var);
866 base_var->next = append_var;
868 base_var->next = NULL;
870 append_var = base_var;
875 if (!tmp->next && append_var) {
876 tmp->next = append_var;
892 ast_free(clean_basedn);
895 ast_mutex_unlock(&ldap_lock);
900 /*! \brief same as realtime_ldap_base_ap but take variable arguments count list */
901 static struct ast_variable **realtime_ldap_base(unsigned int *entries_count_ptr,
902 const char *basedn, const char *table_name, ...)
904 struct ast_variable **vars = NULL;
907 va_start(ap, table_name);
908 vars = realtime_ldap_base_ap(entries_count_ptr, basedn, table_name, ap);
914 /*! \brief See Asterisk doc
916 * For Realtime Dynamic(i.e., switch, queues, and directory) -- I think
918 static struct ast_variable *realtime_ldap(const char *basedn,
919 const char *table_name, va_list ap)
921 struct ast_variable **vars = realtime_ldap_base_ap(NULL, basedn, table_name, ap);
922 struct ast_variable *var = NULL;
925 struct ast_variable *last_var = NULL;
926 struct ast_variable **p = vars;
929 while (last_var->next) {
930 last_var = last_var->next;
944 /*! \brief See Asterisk doc
946 * 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);
947 * however, the ast_load_realtime wil match on wildcharacters also depending on what the mode is set to
948 * this is an area of asterisk that could do with a lot of modification
949 * I think this function returns Realtime dynamic objects
951 static struct ast_config *realtime_multi_ldap(const char *basedn,
952 const char *table_name, va_list ap)
955 const char *initfield = NULL;
956 const char *newparam, *newval;
957 struct ast_variable **vars =
958 realtime_ldap_base_ap(NULL, basedn, table_name, ap);
959 struct ast_config *cfg = NULL;
961 newparam = va_arg(ap, const char *);
962 newval = va_arg(ap, const char *);
963 if (!newparam || !newval) {
964 ast_log(LOG_WARNING, "realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
967 initfield = ast_strdupa(newparam);
968 if ((op = strchr(initfield, ' '))) {
973 cfg = ast_config_new();
975 ast_log(LOG_ERROR, "Unable to create a config!\n");
977 struct ast_variable **p = vars;
980 struct ast_category *cat = NULL;
981 cat = ast_category_new("", table_name, -1);
983 ast_log(LOG_ERROR, "Unable to create a new category!\n");
986 struct ast_variable *var = *p;
988 struct ast_variable *next = var->next;
989 if (initfield && !strcmp(initfield, var->name)) {
990 ast_category_rename(cat, var->value);
993 ast_variable_append(cat, var);
997 ast_category_append(cfg, cat);
1008 * \brief Sorting alogrithm for qsort to find the order of the variables \a a and \a b
1009 * \param a pointer to category_and_metric struct
1010 * \param b pointer to category_and_metric struct
1012 * \retval -1 for if b is greater
1013 * \retval 0 zero for equal
1014 * \retval 1 if a is greater
1016 static int compare_categories(const void *a, const void *b)
1018 const struct category_and_metric *as = a;
1019 const struct category_and_metric *bs = b;
1021 if (as->metric < bs->metric) {
1023 } else if (as->metric > bs->metric) {
1025 } else if (as->metric == bs->metric && strcmp(as->name, bs->name) != 0) {
1026 return strcmp(as->name, bs->name);
1028 /* if the metric and the category name is the same, we check the variable metric */
1029 if (as->var_metric < bs->var_metric) {
1031 } else if (as->var_metric > bs->var_metric) {
1038 /*! \brief See Asterisk doc
1040 * This is for Static Realtime (again: I think...)
1042 * load the configuration stuff for the .conf files
1043 * called on a reload
1045 static struct ast_config *config_ldap(const char *basedn, const char *table_name,
1046 const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *sugg_incl, const char *who_asked)
1048 unsigned int vars_count = 0;
1049 struct ast_variable **vars;
1051 struct ast_variable *new_v = NULL;
1052 struct ast_category *cur_cat = NULL;
1053 const char *last_category = NULL;
1054 int last_category_metric = 0;
1055 struct category_and_metric *categories;
1056 struct ast_variable **p;
1058 if (ast_strlen_zero(file) || !strcasecmp(file, RES_CONFIG_LDAP_CONF)) {
1059 ast_log(LOG_ERROR, "Missing configuration file: %s. Can't configure myself.\n", RES_CONFIG_LDAP_CONF);
1063 vars = realtime_ldap_base(&vars_count, basedn, table_name, "filename", file, "commented", "FALSE", NULL);
1066 ast_log(LOG_WARNING, "Could not find config '%s' in directory.\n", file);
1070 /*!\note Since the items come back in random order, they need to be sorted
1071 * first, and since the data could easily exceed stack size, this is
1072 * allocated from the heap.
1074 if (!(categories = ast_calloc(sizeof(*categories), vars_count))) {
1078 for (vars_count = 0, p = vars; *p; p++) {
1079 struct ast_variable *category = variable_named(*p, "category");
1080 struct ast_variable *cat_metric = variable_named(*p, "cat_metric");
1081 struct ast_variable *var_name = variable_named(*p, "variable_name");
1082 struct ast_variable *var_val = variable_named(*p, "variable_value");
1083 struct ast_variable *var_metric = variable_named(*p, "var_metric");
1084 struct ast_variable *dn = variable_named(*p, "dn");
1086 ast_debug(3, "category: %s\n", category->value);
1087 ast_debug(3, "var_name: %s\n", var_name->value);
1088 ast_debug(3, "var_val: %s\n", var_val->value);
1089 ast_debug(3, "cat_metric: %s\n", cat_metric->value);
1092 ast_log(LOG_ERROR, "No category name in entry '%s' for file '%s'.\n",
1093 (dn ? dn->value : "?"), file);
1094 } else if (!cat_metric) {
1095 ast_log(LOG_ERROR, "No category metric in entry '%s'(category: %s) for file '%s'.\n",
1096 (dn ? dn->value : "?"), category->value, file);
1097 } else if (!var_metric) {
1098 ast_log(LOG_ERROR, "No variable metric in entry '%s'(category: %s) for file '%s'.\n",
1099 (dn ? dn->value : "?"), category->value, file);
1100 } else if (!var_name) {
1101 ast_log(LOG_ERROR, "No variable name in entry '%s' (category: %s metric: %s) for file '%s'.\n",
1102 (dn ? dn->value : "?"), category->value,
1103 cat_metric->value, file);
1104 } else if (!var_val) {
1105 ast_log(LOG_ERROR, "No variable value in entry '%s' (category: %s metric: %s variable: %s) for file '%s'.\n",
1106 (dn ? dn->value : "?"), category->value,
1107 cat_metric->value, var_name->value, file);
1109 categories[vars_count].name = category->value;
1110 categories[vars_count].metric = atoi(cat_metric->value);
1111 categories[vars_count].variable_name = var_name->value;
1112 categories[vars_count].variable_value = var_val->value;
1113 categories[vars_count].var_metric = atoi(var_metric->value);
1118 qsort(categories, vars_count, sizeof(*categories), compare_categories);
1120 for (i = 0; i < vars_count; i++) {
1121 if (!strcmp(categories[i].variable_name, "#include")) {
1122 struct ast_flags flags = { 0 };
1123 if (!ast_config_internal_load(categories[i].variable_value, cfg, flags, "", who_asked)) {
1129 if (!last_category || strcmp(last_category, categories[i].name) ||
1130 last_category_metric != categories[i].metric) {
1132 cur_cat = ast_category_new(categories[i].name, table_name, -1);
1136 last_category = categories[i].name;
1137 last_category_metric = categories[i].metric;
1138 ast_category_append(cfg, cur_cat);
1141 if (!(new_v = ast_variable_new(categories[i].variable_name, categories[i].variable_value, table_name))) {
1145 ast_variable_append(cur_cat, new_v);
1149 ast_free(categories);
1154 /* \brief Function to update a set of values in ldap static mode
1156 static int update_ldap(const char *basedn, const char *table_name, const char *attribute,
1157 const char *lookup, va_list ap)
1160 LDAPMessage *ldap_entry = NULL;
1161 LDAPMod **ldap_mods;
1162 const char *newparam = NULL;
1163 const char *newval = NULL;
1165 int num_entries = 0;
1169 struct ldap_table_config *table_config = NULL;
1170 char *clean_basedn = NULL;
1171 struct ast_str *filter = NULL;
1174 LDAPMessage *ldap_result_msg = NULL;
1177 ast_log(LOG_ERROR, "No table_name specified.\n");
1181 if (!(filter = ast_str_create(80))) {
1185 if (!attribute || !lookup) {
1186 ast_log(LOG_WARNING, "LINE(%d): search parameters are empty.\n", __LINE__);
1189 ast_mutex_lock(&ldap_lock);
1191 /* We now have our complete statement; Lets connect to the server and execute it. */
1192 if (!ldap_reconnect()) {
1193 ast_mutex_unlock(&ldap_lock);
1197 table_config = table_config_for_table_name(table_name);
1198 if (!table_config) {
1199 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1200 ast_mutex_unlock(&ldap_lock);
1204 clean_basedn = cleaned_basedn(NULL, basedn);
1206 /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1207 ast_str_append(&filter, 0, "(&");
1208 if (table_config && table_config->additional_filter) {
1209 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1211 if (table_config != base_table_config && base_table_config && base_table_config->additional_filter) {
1212 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1214 append_var_and_value_to_filter(&filter, table_config, attribute, lookup);
1215 ast_str_append(&filter, 0, ")");
1217 /* Create the modification array with the parameter/value pairs we were given,
1218 * if there are several parameters with the same name, we collect them into
1219 * one parameter/value pair and delimit them with a semicolon */
1220 newparam = va_arg(ap, const char *);
1221 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1222 newval = va_arg(ap, const char *);
1223 if (!newparam || !newval) {
1224 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1228 mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1229 ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1230 ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1232 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1233 ldap_mods[0]->mod_type = ast_strdup(newparam);
1235 ldap_mods[0]->mod_values = ast_calloc(sizeof(char *), 2);
1236 ldap_mods[0]->mod_values[0] = ast_strdup(newval);
1238 while ((newparam = va_arg(ap, const char *))) {
1239 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1240 newval = va_arg(ap, const char *);
1243 for (i = 0; i < mods_size - 1; i++) {
1244 if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1245 /* We have the parameter allready, adding the value as a semicolon delimited value */
1246 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));
1247 strcat(ldap_mods[i]->mod_values[0], ";");
1248 strcat(ldap_mods[i]->mod_values[0], newval);
1254 /* create new mod */
1257 ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1258 ldap_mods[mods_size - 1] = NULL;
1260 ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1262 ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1263 strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1265 if (strlen(newval) == 0) {
1266 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
1268 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1270 ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1271 ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1272 strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
1276 /* freeing ldap_mods further down */
1279 /* freeing ldap_result further down */
1280 result = ldap_search_ext_s(ldapConn, clean_basedn,
1281 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1283 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1284 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1287 usleep(500000L * tries);
1289 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1292 if (!ldap_reconnect())
1296 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1298 if (result != LDAP_SUCCESS) {
1299 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1300 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1302 ast_mutex_unlock(&ldap_lock);
1305 ldap_msgfree(ldap_result_msg);
1306 ldap_mods_free(ldap_mods, 0);
1309 /* Ready to update */
1310 if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1311 ast_debug(3, "LINE(%d) Modifying %s=%s hits: %d\n", __LINE__, attribute, lookup, num_entries);
1312 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1313 if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
1314 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1316 ast_debug(3, "LINE(%d) deleting %s \n", __LINE__, ldap_mods[i]->mod_type);
1319 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1321 for (i = 0; ldap_entry; i++) {
1322 dn = ldap_get_dn(ldapConn, ldap_entry);
1323 if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1324 ast_log(LOG_ERROR, "Couldn't modify '%s'='%s', dn:%s because %s\n",
1325 attribute, lookup, dn, ldap_err2string(error));
1328 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1332 ast_mutex_unlock(&ldap_lock);
1334 ast_free(clean_basedn);
1335 ldap_msgfree(ldap_result_msg);
1336 ldap_mods_free(ldap_mods, 0);
1340 static int update2_ldap(const char *basedn, const char *table_name, va_list ap)
1343 LDAPMessage *ldap_entry = NULL;
1344 LDAPMod **ldap_mods;
1345 const char *newparam = NULL;
1346 const char *newval = NULL;
1348 int num_entries = 0;
1352 struct ldap_table_config *table_config = NULL;
1353 char *clean_basedn = NULL;
1354 struct ast_str *filter = NULL;
1357 LDAPMessage *ldap_result_msg = NULL;
1360 ast_log(LOG_ERROR, "No table_name specified.\n");
1364 if (!(filter = ast_str_create(80))) {
1368 ast_mutex_lock(&ldap_lock);
1370 /* We now have our complete statement; Lets connect to the server and execute it. */
1371 if (!ldap_reconnect()) {
1372 ast_mutex_unlock(&ldap_lock);
1377 table_config = table_config_for_table_name(table_name);
1378 if (!table_config) {
1379 ast_log(LOG_ERROR, "No table named '%s'.\n", table_name);
1380 ast_mutex_unlock(&ldap_lock);
1385 clean_basedn = cleaned_basedn(NULL, basedn);
1387 /* Create the filter with the table additional filter and the parameter/value pairs we were given */
1388 ast_str_append(&filter, 0, "(&");
1389 if (table_config && table_config->additional_filter) {
1390 ast_str_append(&filter, 0, "%s", table_config->additional_filter);
1392 if (table_config != base_table_config && base_table_config
1393 && base_table_config->additional_filter) {
1394 ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
1397 /* Get multiple lookup keyfields and values */
1398 while ((newparam = va_arg(ap, const char *))) {
1399 newval = va_arg(ap, const char *);
1400 append_var_and_value_to_filter(&filter, table_config, newparam, newval);
1402 ast_str_append(&filter, 0, ")");
1404 /* Create the modification array with the parameter/value pairs we were given,
1405 * if there are several parameters with the same name, we collect them into
1406 * one parameter/value pair and delimit them with a semicolon */
1407 newparam = va_arg(ap, const char *);
1408 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1409 newval = va_arg(ap, const char *);
1410 if (!newparam || !newval) {
1411 ast_log(LOG_WARNING, "LINE(%d): need at least one parameter to modify.\n", __LINE__);
1413 ast_free(clean_basedn);
1417 mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
1418 ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
1419 ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
1421 ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
1422 ldap_mods[0]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1423 strcpy(ldap_mods[0]->mod_type, newparam);
1425 ldap_mods[0]->mod_values = ast_calloc(sizeof(char), 2);
1426 ldap_mods[0]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1427 strcpy(ldap_mods[0]->mod_values[0], newval);
1429 while ((newparam = va_arg(ap, const char *))) {
1430 newparam = convert_attribute_name_to_ldap(table_config, newparam);
1431 newval = va_arg(ap, const char *);
1434 for (i = 0; i < mods_size - 1; i++) {
1435 if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
1436 /* We have the parameter allready, adding the value as a semicolon delimited value */
1437 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));
1438 strcat(ldap_mods[i]->mod_values[0], ";");
1439 strcat(ldap_mods[i]->mod_values[0], newval);
1445 /* create new mod */
1448 ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
1449 ldap_mods[mods_size - 1] = NULL;
1450 ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
1452 ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
1454 ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
1455 strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
1457 ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
1458 ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
1459 strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
1462 /* freeing ldap_mods further down */
1465 /* freeing ldap_result further down */
1466 result = ldap_search_ext_s(ldapConn, clean_basedn,
1467 LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
1469 if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
1470 ast_log(LOG_WARNING, "Failed to query directory. Try %d/3\n", tries + 1);
1473 usleep(500000L * tries);
1475 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1478 if (!ldap_reconnect()) {
1483 } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
1485 if (result != LDAP_SUCCESS) {
1486 ast_log(LOG_WARNING, "Failed to query directory. Error: %s.\n", ldap_err2string(result));
1487 ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
1489 ast_mutex_unlock(&ldap_lock);
1491 ast_free(clean_basedn);
1492 ldap_msgfree(ldap_result_msg);
1493 ldap_mods_free(ldap_mods, 0);
1496 /* Ready to update */
1497 if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
1498 for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
1499 ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
1502 ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
1504 for (i = 0; ldap_entry; i++) {
1505 dn = ldap_get_dn(ldapConn, ldap_entry);
1506 if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) {
1507 ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
1510 ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
1514 ast_mutex_unlock(&ldap_lock);
1519 ast_free(clean_basedn);
1521 ldap_msgfree(ldap_result_msg);
1522 ldap_mods_free(ldap_mods, 0);
1526 static struct ast_config_engine ldap_engine = {
1528 .load_func = config_ldap,
1529 .realtime_func = realtime_ldap,
1530 .realtime_multi_func = realtime_multi_ldap,
1531 .update_func = update_ldap,
1532 .update2_func = update2_ldap,
1535 static int load_module(void)
1537 if (parse_config() < 0) {
1538 ast_log(LOG_ERROR, "Cannot load LDAP RealTime driver.\n");
1542 ast_mutex_lock(&ldap_lock);
1544 if (!ldap_reconnect()) {
1545 ast_log(LOG_WARNING, "Couldn't establish connection to LDAP directory. Check debug.\n");
1548 ast_config_engine_register(&ldap_engine);
1549 ast_verb(1, "LDAP RealTime driver loaded.\n");
1550 ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1552 ast_mutex_unlock(&ldap_lock);
1557 static int unload_module(void)
1559 /* Aquire control before doing anything to the module itself. */
1560 ast_mutex_lock(&ldap_lock);
1562 table_configs_free();
1565 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1568 ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
1569 ast_config_engine_deregister(&ldap_engine);
1570 ast_verb(1, "LDAP RealTime driver unloaded.\n");
1572 /* Unlock so something else can destroy the lock. */
1573 ast_mutex_unlock(&ldap_lock);
1578 static int reload(void)
1580 /* Aquire control before doing anything to the module itself. */
1581 ast_mutex_lock(&ldap_lock);
1584 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1588 if (parse_config() < 0) {
1589 ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
1590 ast_mutex_unlock(&ldap_lock);
1594 if (!ldap_reconnect()) {
1595 ast_log(LOG_WARNING, "Couldn't establish connection to your directory server. Check debug.\n");
1598 ast_verb(2, "LDAP RealTime driver reloaded.\n");
1600 /* Done reloading. Release lock so others can now use driver. */
1601 ast_mutex_unlock(&ldap_lock);
1606 /*! \brief parse the configuration file */
1607 static int parse_config(void)
1609 struct ast_config *config;
1610 struct ast_flags config_flags = {0};
1611 const char *s, *host;
1613 char *category_name = NULL;
1615 /* Make sure that global variables are reset */
1619 base_distinguished_name[0] = '\0';
1622 config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
1623 if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
1624 ast_log(LOG_ERROR, "Cannot load configuration file: %s\n", RES_CONFIG_LDAP_CONF);
1628 if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
1629 ast_log(LOG_NOTICE, "No directory user found, anonymous binding as default.\n");
1632 ast_copy_string(user, s, sizeof(user));
1635 if (!ast_strlen_zero(user)) {
1636 if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
1637 ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
1638 ast_copy_string(pass, "asterisk", sizeof(pass));
1640 ast_copy_string(pass, s, sizeof(pass));
1644 /* URL is preferred, use host and port if not found */
1645 if ((s = ast_variable_retrieve(config, "_general", "url"))) {
1646 ast_copy_string(url, s, sizeof(url));
1647 } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
1648 if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
1649 ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
1653 snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
1655 ast_log(LOG_ERROR, "No directory URL or host found.\n");
1656 ast_config_destroy(config);
1660 if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
1661 ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
1662 ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
1664 ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
1666 if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
1667 ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
1668 } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
1669 ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
1673 table_configs_free();
1675 while ((category_name = ast_category_browse(config, category_name))) {
1676 int is_general = (strcasecmp(category_name, "_general") == 0);
1677 int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
1678 struct ast_variable *var = ast_variable_browse(config, category_name);
1681 struct ldap_table_config *table_config =
1682 table_config_for_table_name(category_name);
1683 if (!table_config) {
1684 table_config = table_config_new(category_name);
1685 AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
1687 base_table_config = table_config;
1689 static_table_config = table_config;
1691 for (; var; var = var->next) {
1692 if (!strcasecmp(var->name, "additionalFilter")) {
1693 table_config->additional_filter = ast_strdup(var->value);
1695 ldap_table_config_add_attribute(table_config, var->name, var->value);
1701 ast_config_destroy(config);
1706 /*! \note ldap_lock should have been locked before calling this function. */
1707 static int ldap_reconnect(void)
1709 int bind_result = 0;
1713 ast_debug(2, "Everything seems fine.\n");
1717 if (ast_strlen_zero(url)) {
1718 ast_log(LOG_ERROR, "Not enough parameters to connect to ldap directory\n");
1722 if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
1723 ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
1727 if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
1728 ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
1731 if (!ast_strlen_zero(user)) {
1732 ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
1733 cred.bv_val = (char *) pass;
1734 cred.bv_len = strlen(pass);
1735 bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1737 ast_debug(2, "bind %s anonymously\n", url);
1740 bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
1742 if (bind_result == LDAP_SUCCESS) {
1743 ast_debug(2, "Successfully connected to directory.\n");
1744 connect_time = time(NULL);
1747 ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
1748 ldap_unbind_ext_s(ldapConn, NULL, NULL);
1754 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1756 char status[256], credentials[100] = "";
1757 int ctimesec = time(NULL) - connect_time;
1761 e->command = "realtime show ldap status";
1763 "Usage: realtime show ldap status\n"
1764 " Shows connection information for the LDAP RealTime driver\n";
1773 if (!ast_strlen_zero(url))
1774 snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
1776 if (!ast_strlen_zero(user))
1777 snprintf(credentials, sizeof(credentials), " with username %s", user);
1779 if (ctimesec > 31536000) {
1780 ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
1781 status, credentials, ctimesec / 31536000,
1782 (ctimesec % 31536000) / 86400, (ctimesec % 86400) / 3600,
1783 (ctimesec % 3600) / 60, ctimesec % 60);
1784 } else if (ctimesec > 86400) {
1785 ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n",
1786 status, credentials, ctimesec / 86400, (ctimesec % 86400) / 3600,
1787 (ctimesec % 3600) / 60, ctimesec % 60);
1788 } else if (ctimesec > 3600) {
1789 ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n",
1790 status, credentials, ctimesec / 3600, (ctimesec % 3600) / 60,
1792 } else if (ctimesec > 60) {
1793 ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials,
1794 ctimesec / 60, ctimesec % 60);
1796 ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
1802 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "LDAP realtime interface",
1803 .load = load_module,
1804 .unload = unload_module,
1806 .load_pri = AST_MODPRI_REALTIME_DRIVER,