Sat Mar 26 11:08:52 2011

Asterisk developer's documentation


res_config_ldap.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- A telephony toolkit for Linux.
00003  *
00004  * Copyright (C) 2005, Oxymium sarl
00005  * Manuel Guesdon <mguesdon@oxymium.net> - LDAP RealTime Driver Author/Adaptor
00006  *
00007  * Copyright (C) 2007, Digium, Inc.
00008  * Russell Bryant <russell@digium.com>
00009  *
00010  * See http://www.asterisk.org for more information about
00011  * the Asterisk project. Please do not directly contact
00012  * any of the maintainers of this project for assistance;
00013  * the project provides a web site, mailing lists and IRC
00014  * channels for your use.
00015  *
00016  * This program is free software, distributed under the terms of
00017  * the GNU General Public License Version 2. See the LICENSE file
00018  * at the top of the source tree.
00019  *
00020  */
00021 
00022 /*! \file
00023  *
00024  * \brief ldap plugin for portable configuration engine (ARA)
00025  *
00026  * \author Mark Spencer <markster@digium.com>
00027  * \author Manuel Guesdon
00028  * \author Carl-Einar Thorner <cthorner@voicerd.com>
00029  * \author Russell Bryant <russell@digium.com>
00030  *
00031  * \arg http://www.openldap.org
00032  */
00033 
00034 /*** MODULEINFO
00035    <depend>ldap</depend>
00036  ***/
00037 
00038 #include "asterisk.h"
00039 
00040 #include <stdlib.h>
00041 #include <string.h>
00042 #include <ctype.h>
00043 #include <stdio.h>
00044 #include <ldap.h>
00045 
00046 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 289332 $")
00047 
00048 #include "asterisk/channel.h"
00049 #include "asterisk/logger.h"
00050 #include "asterisk/config.h"
00051 #include "asterisk/module.h"
00052 #include "asterisk/lock.h"
00053 #include "asterisk/options.h"
00054 #include "asterisk/cli.h"
00055 #include "asterisk/utils.h"
00056 #include "asterisk/strings.h"
00057 #include "asterisk/pbx.h"
00058 #include "asterisk/linkedlists.h"
00059 
00060 #define RES_CONFIG_LDAP_CONF "res_ldap.conf"
00061 #define RES_CONFIG_LDAP_DEFAULT_BASEDN "asterisk"
00062 
00063 AST_MUTEX_DEFINE_STATIC(ldap_lock);
00064 
00065 static LDAP *ldapConn;
00066 static char url[512];
00067 static char user[512];
00068 static char pass[512];
00069 static char base_distinguished_name[512];
00070 static int version = 3;
00071 static time_t connect_time;
00072 
00073 static int parse_config(void);
00074 static int ldap_reconnect(void);
00075 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
00076 
00077 struct category_and_metric {
00078    const char *name;
00079    int metric;
00080    const char *variable_name;
00081    const char *variable_value;
00082    int var_metric; /*!< For organizing variables (particularly includes and switch statments) within a context */
00083 };
00084 
00085 /*! \brief Table configuration */
00086 struct ldap_table_config {
00087    char *table_name;                 /*!< table name */
00088    char *additional_filter;          /*!< additional filter        */
00089    struct ast_variable *attributes;  /*!< attribute names conversion */
00090    struct ast_variable *delimiters;  /*!< the current delimiter is semicolon, so we are not using this variable */
00091    AST_LIST_ENTRY(ldap_table_config) entry;
00092    /* TODO: Make proxies work */
00093 };
00094 
00095 /*! \brief Should be locked before using it */
00096 static AST_LIST_HEAD_NOLOCK_STATIC(table_configs, ldap_table_config);
00097 static struct ldap_table_config *base_table_config;
00098 static struct ldap_table_config *static_table_config;
00099 
00100 static struct ast_cli_entry ldap_cli[] = {
00101    AST_CLI_DEFINE(realtime_ldap_status, "Shows connection information for the LDAP RealTime driver"),
00102 };
00103 
00104 /*! \brief Create a new table_config */
00105 static struct ldap_table_config *table_config_new(const char *table_name)
00106 {
00107    struct ldap_table_config *p;
00108 
00109    if (!(p = ast_calloc(1, sizeof(*p))))
00110       return NULL;
00111 
00112    if (table_name) {
00113       if (!(p->table_name = ast_strdup(table_name))) {
00114          free(p);
00115          return NULL;
00116       }
00117    }
00118 
00119    return p;
00120 }
00121 
00122 /*! \brief Find a table_config - Should be locked before using it 
00123  *  \note This function assumes ldap_lock to be locked. */
00124 static struct ldap_table_config *table_config_for_table_name(const char *table_name)
00125 {
00126    struct ldap_table_config *c = NULL;
00127 
00128    AST_LIST_TRAVERSE(&table_configs, c, entry) {
00129       if (!strcmp(c->table_name, table_name))
00130          break;
00131    }
00132 
00133    return c;
00134 }
00135 
00136 /*! \brief Find variable by name */
00137 static struct ast_variable *variable_named(struct ast_variable *var, const char *name)
00138 {
00139    for (; var; var = var->next) {
00140       if (!strcasecmp(name, var->name))
00141          break;
00142    }
00143 
00144    return var;
00145 }
00146 
00147 /*! \brief for the semicolon delimiter
00148    \param somestr - pointer to a string
00149 
00150    \return number of occurances of the delimiter(semicolon)
00151  */
00152 static int semicolon_count_str(const char *somestr)
00153 {
00154    int count = 0;
00155 
00156    for (; *somestr; somestr++) {
00157       if (*somestr == ';')
00158          count++;
00159    }
00160 
00161    return count;
00162 } 
00163 
00164 /* takes a linked list of \a ast_variable variables, finds the one with the name variable_value
00165  * and returns the number of semicolons in the value for that \a ast_variable
00166  */
00167 static int semicolon_count_var(struct ast_variable *var)
00168 {
00169    struct ast_variable *var_value = variable_named(var, "variable_value");
00170 
00171    if (!var_value)
00172       return 0;
00173 
00174    ast_debug(1, "LINE(%d) semicolon_count_var: %s\n", __LINE__, var_value->value);
00175 
00176    return semicolon_count_str(var_value->value);
00177 }
00178 
00179 /*! \brief add attribute to table config - Should be locked before using it */
00180 static void ldap_table_config_add_attribute(struct ldap_table_config *table_config,
00181    const char *attribute_name, const char *attribute_value)
00182 {
00183    struct ast_variable *var;
00184 
00185    if (ast_strlen_zero(attribute_name) || ast_strlen_zero(attribute_value))
00186       return;
00187 
00188    if (!(var = ast_variable_new(attribute_name, attribute_value, table_config->table_name)))
00189       return;
00190 
00191    if (table_config->attributes)
00192       var->next = table_config->attributes;
00193    table_config->attributes = var;
00194 }
00195 
00196 /*! \brief Free table_config 
00197  *  \note assumes ldap_lock to be locked */
00198 static void table_configs_free(void)
00199 {
00200    struct ldap_table_config *c;
00201 
00202    while ((c = AST_LIST_REMOVE_HEAD(&table_configs, entry))) {
00203       if (c->table_name)
00204          free(c->table_name);
00205       if (c->additional_filter)
00206          free(c->additional_filter);
00207       if (c->attributes)
00208          ast_variables_destroy(c->attributes);
00209       free(c);
00210    }
00211 
00212    base_table_config = NULL;
00213    static_table_config = NULL;
00214 }
00215 
00216 /*! \brief Convert variable name to ldap attribute name - Should be locked before using it */
00217 static const char *convert_attribute_name_to_ldap(struct ldap_table_config *table_config,
00218    const char *attribute_name)
00219 {
00220    int i = 0;
00221    struct ldap_table_config *configs[] = { table_config, base_table_config };
00222 
00223    for (i = 0; i < ARRAY_LEN(configs); i++) {
00224       struct ast_variable *attribute;
00225 
00226       if (!configs[i])
00227          continue;
00228 
00229       attribute = configs[i]->attributes;
00230       for (; attribute; attribute = attribute->next) {
00231          if (!strcasecmp(attribute_name, attribute->name))
00232             return attribute->value;
00233       }
00234    }
00235 
00236    return attribute_name;
00237 }
00238 
00239 /*! \brief Convert ldap attribute name to variable name - Should be locked before using it */
00240 static const char *convert_attribute_name_from_ldap(struct ldap_table_config *table_config,
00241                       const char *attribute_name)
00242 {
00243    int i = 0;
00244    struct ldap_table_config *configs[] = { table_config, base_table_config };
00245 
00246    for (i = 0; i < ARRAY_LEN(configs); i++) {
00247       struct ast_variable *attribute;
00248 
00249       if (!configs[i])
00250          continue;
00251 
00252       attribute = configs[i]->attributes;
00253       for (; attribute; attribute = attribute->next) {
00254          if (strcasecmp(attribute_name, attribute->value) == 0)
00255             return attribute->name;
00256       }
00257    }
00258 
00259    return attribute_name;
00260 }
00261 
00262 /*! \brief Get variables from ldap entry attributes - Should be locked before using it
00263  * \return a linked list of ast_variable variables.
00264  **/
00265 static struct ast_variable *realtime_ldap_entry_to_var(struct ldap_table_config *table_config,
00266    LDAPMessage *ldap_entry)
00267 {
00268    BerElement *ber = NULL;
00269    struct ast_variable *var = NULL;
00270    struct ast_variable *prev = NULL;
00271    int is_delimited = 0;
00272    int i = 0;
00273    char *ldap_attribute_name;
00274    struct berval *value;
00275    int pos = 0;
00276 
00277    ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
00278 
00279    while (ldap_attribute_name) {
00280       struct berval **values = NULL;
00281       const char *attribute_name = convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
00282       int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
00283 
00284       values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name); /* these are freed at the end */
00285       if (values) {
00286          struct berval **v;
00287          char *valptr;
00288 
00289          for (v = values; *v; v++) {
00290             value = *v;
00291             valptr = value->bv_val;
00292             ast_debug(2, "LINE(%d) attribute_name: %s LDAP value: %s\n", __LINE__, attribute_name, valptr);
00293             if (is_realmed_password_attribute) {
00294                if (!strncasecmp(valptr, "{md5}", 5)) {
00295                   valptr += 5;
00296                }
00297                ast_debug(2, "md5: %s\n", valptr);
00298             }
00299             if (valptr) {
00300                /* ok, so looping through all delimited values except the last one (not, last character is not delimited...) */
00301                if (is_delimited) {
00302                   i = 0;
00303                   pos = 0;
00304                   while (!ast_strlen_zero(valptr + i)) {
00305                      if (valptr[i] == ';'){
00306                         valptr[i] = '\0';
00307                         if (prev) {
00308                            prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
00309                            if (prev->next) {
00310                               prev = prev->next;
00311                            }
00312                         } else {
00313                            prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
00314                         }
00315                         pos = i + 1;
00316                      }
00317                      i++;
00318                   }
00319                }
00320                /* for the last delimited value or if the value is not delimited: */
00321                if (prev) {
00322                   prev->next = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
00323                   if (prev->next) {
00324                      prev = prev->next;
00325                   }
00326                } else {
00327                   prev = var = ast_variable_new(attribute_name, &valptr[pos], table_config->table_name);
00328                }
00329             }
00330          }
00331          ldap_value_free_len(values);
00332       }
00333       ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
00334    }
00335    ber_free(ber, 0);
00336 
00337    return var;
00338 }
00339 
00340 /*! \brief Get variables from ldap entry attributes - Should be locked before using it
00341  *
00342  * The results are freed outside this function so is the \a vars array.
00343  * 
00344  * \return \a vars - an array of ast_variable variables terminated with a null.
00345  **/
00346 static struct ast_variable **realtime_ldap_result_to_vars(struct ldap_table_config *table_config,
00347    LDAPMessage *ldap_result_msg, unsigned int *entries_count_ptr)
00348 {
00349    struct ast_variable **vars;
00350    int i = 0;
00351    int tot_count = 0;
00352    int entry_index = 0;
00353    LDAPMessage *ldap_entry = NULL;
00354    BerElement *ber = NULL;
00355    struct ast_variable *var = NULL;
00356    struct ast_variable *prev = NULL;
00357    int is_delimited = 0;
00358    char *delim_value = NULL;
00359    int delim_tot_count = 0;
00360    int delim_count = 0;
00361 
00362    /* First find the total count */
00363    ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
00364 
00365    for (tot_count = 0; ldap_entry; tot_count++){ 
00366       struct ast_variable *tmp = realtime_ldap_entry_to_var(table_config, ldap_entry);
00367       tot_count += semicolon_count_var(tmp);
00368       ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
00369       ast_variables_destroy(tmp);
00370    }
00371 
00372    if (entries_count_ptr)
00373       *entries_count_ptr = tot_count;
00374    /* Now that we have the total count we allocate space and create the variables
00375     * Remember that each element in vars is a linked list that points to realtime variable.
00376     * If the we are dealing with a static realtime variable we create a new element in the \a vars array for each delimited
00377     * 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.
00378     * This memory must be freed outside of this function. */
00379    vars = ast_calloc(sizeof(struct ast_variable *), tot_count + 1);
00380 
00381    ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
00382 
00383    i = 0;
00384 
00385    /* For each static realtime variable we may create several entries in the \a vars array if it's delimited */
00386    for (entry_index = 0; ldap_entry; ) { 
00387       int pos = 0;
00388       delim_value = NULL;
00389       delim_tot_count = 0;
00390       delim_count = 0;
00391       
00392       do { /* while delim_count */
00393 
00394          /* Starting new static var */
00395          char *ldap_attribute_name = ldap_first_attribute(ldapConn, ldap_entry, &ber);
00396          struct berval *value;
00397          while (ldap_attribute_name) {
00398          
00399             const char *attribute_name =
00400                convert_attribute_name_from_ldap(table_config, ldap_attribute_name);
00401             int is_realmed_password_attribute = strcasecmp(attribute_name, "md5secret") == 0;
00402             struct berval **values = NULL;
00403 
00404             values = ldap_get_values_len(ldapConn, ldap_entry, ldap_attribute_name);
00405             if (values) {
00406                struct berval **v;
00407                char *valptr;
00408 
00409                for (v = values; *v; v++) {
00410                   value = *v;
00411                   valptr = value->bv_val;
00412                   if (is_realmed_password_attribute) {
00413                      if (strncasecmp(valptr, "{md5}", 5) == 0) {
00414                         valptr += 5;
00415                      }
00416                      ast_debug(2, "md5: %s\n", valptr);
00417                   }
00418                   if (valptr) {
00419                      if (delim_value == NULL 
00420                         && !is_realmed_password_attribute 
00421                         && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0)) {
00422 
00423                         delim_value = ast_strdup(valptr);
00424 
00425                         if ((delim_tot_count = semicolon_count_str(delim_value)) > 0) {
00426                            ast_debug(4, "LINE(%d) is delimited %d times: %s\n", __LINE__, delim_tot_count, delim_value);
00427                            is_delimited = 1;
00428                         }
00429                      }
00430 
00431                      if (is_delimited != 0 
00432                         && !is_realmed_password_attribute 
00433                         && (static_table_config != table_config || strcmp(attribute_name, "variable_value") == 0) ) {
00434                         /* for non-Static RealTime, first */
00435 
00436                         for (i = pos; !ast_strlen_zero(valptr + i); i++) {
00437                            ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
00438                            if (delim_value[i] == ';') {
00439                               delim_value[i] = '\0';
00440 
00441                               ast_debug(2, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
00442                      
00443                               if (prev) {
00444                                  prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
00445                                  if (prev->next) {
00446                                     prev = prev->next;
00447                                  }
00448                               } else {
00449                                  prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
00450                               }
00451                               pos = i + 1;
00452 
00453                               if (static_table_config == table_config) {
00454                                  break;
00455                               }
00456                            }
00457                         }
00458                         if (ast_strlen_zero(valptr + i)) {
00459                            ast_debug(4, "LINE(%d) DELIM pos: %d i: %d delim_count: %d\n", __LINE__, pos, i, delim_count);
00460                            /* Last delimited value */
00461                            ast_debug(4, "LINE(%d) DELIM - attribute_name: %s value: %s pos: %d\n", __LINE__, attribute_name, &delim_value[pos], pos);
00462                            if (prev) {
00463                               prev->next = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
00464                               if (prev->next) {
00465                                  prev = prev->next;
00466                               }
00467                            } else {
00468                               prev = var = ast_variable_new(attribute_name, &delim_value[pos], table_config->table_name);
00469                            }
00470                            /* Remembering to free memory */
00471                            is_delimited = 0;
00472                            pos = 0;
00473                         }
00474                         free(delim_value);
00475                         delim_value = NULL;
00476                         
00477                         ast_debug(4, "LINE(%d) DELIM pos: %d i: %d\n", __LINE__, pos, i);
00478                      } else {
00479                         /* not delimited */
00480                         if (delim_value) {
00481                            free(delim_value);
00482                            delim_value = NULL;
00483                         }
00484                         ast_debug(2, "LINE(%d) attribute_name: %s value: %s\n", __LINE__, attribute_name, valptr);
00485 
00486                         if (prev) {
00487                            prev->next = ast_variable_new(attribute_name, valptr, table_config->table_name);
00488                            if (prev->next) {
00489                               prev = prev->next;
00490                            }
00491                         } else {
00492                            prev = var = ast_variable_new(attribute_name, valptr, table_config->table_name);
00493                         }
00494                      }
00495                   }
00496                } /*!< for (v = values; *v; v++) */
00497                ldap_value_free_len(values);
00498             }/*!< if (values) */
00499             ldap_attribute_name = ldap_next_attribute(ldapConn, ldap_entry, ber);
00500          } /*!< while (ldap_attribute_name) */
00501          ber_free(ber, 0);
00502          if (static_table_config == table_config) {
00503             if (option_debug > 2) {
00504                const struct ast_variable *tmpdebug = variable_named(var, "variable_name");
00505                const struct ast_variable *tmpdebug2 = variable_named(var, "variable_value");
00506                if (tmpdebug && tmpdebug2) {
00507                   ast_debug(3, "LINE(%d) Added to vars - %s = %s\n", __LINE__, tmpdebug->value, tmpdebug2->value);
00508                }
00509             }
00510             vars[entry_index++] = var;
00511             prev = NULL;
00512          }
00513 
00514          delim_count++;
00515       } while (delim_count <= delim_tot_count && static_table_config == table_config);
00516 
00517       if (static_table_config != table_config) {
00518          ast_debug(3, "LINE(%d) Added to vars - non static\n", __LINE__);
00519             
00520          vars[entry_index++] = var;
00521          prev = NULL;
00522       }
00523       ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
00524    } /*!< end for loop over ldap_entry */
00525 
00526    return vars;
00527 }
00528 
00529 
00530 static int is_ldap_connect_error(int err)
00531 {
00532    return (err == LDAP_SERVER_DOWN
00533          || err == LDAP_TIMEOUT || err == LDAP_CONNECT_ERROR);
00534 }
00535 
00536 /*! \brief Get LDAP entry by dn and return attributes as variables  - Should be locked before using it 
00537    This is used for setting the default values of an object(i.e., with accountBaseDN)
00538 */
00539 static struct ast_variable *ldap_loadentry(struct ldap_table_config *table_config,
00540                   const char *dn)
00541 {
00542    if (!table_config) {
00543       ast_log(LOG_ERROR, "No table config\n");
00544       return NULL;
00545    } else {
00546       struct ast_variable **vars = NULL;
00547       struct ast_variable *var = NULL;
00548       int result = -1;
00549       LDAPMessage *ldap_result_msg = NULL;
00550       int tries = 0;
00551 
00552       ast_debug(2, "ldap_loadentry dn=%s\n", dn);
00553 
00554       do {
00555          result = ldap_search_ext_s(ldapConn, dn, LDAP_SCOPE_BASE,
00556                   "(objectclass=*)", NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT, &ldap_result_msg);
00557          if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
00558             ast_log(LOG_WARNING,
00559                "Failed to query database. Try %d/3\n",
00560                tries + 1);
00561             tries++;
00562             if (tries < 3) {
00563                usleep(500000L * tries);
00564                if (ldapConn) {
00565                   ldap_unbind_ext_s(ldapConn, NULL, NULL);
00566                   ldapConn = NULL;
00567                }
00568                if (!ldap_reconnect())
00569                   break;
00570             }
00571          }
00572       } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
00573 
00574       if (result != LDAP_SUCCESS) {
00575          ast_log(LOG_WARNING,
00576                "Failed to query database. Check debug for more info.\n");
00577          ast_debug(2, "dn=%s\n", dn);
00578          ast_debug(2, "Query Failed because: %s\n",
00579             ldap_err2string(result));
00580          ast_mutex_unlock(&ldap_lock);
00581          return NULL;
00582       } else {
00583          int num_entry = 0;
00584          unsigned int *entries_count_ptr = NULL; /*!< not using this */
00585          if ((num_entry = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
00586             ast_debug(3, "num_entry: %d\n", num_entry);
00587 
00588             vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
00589             if (num_entry > 1)
00590                ast_log(LOG_NOTICE, "More than one entry for dn=%s. Take only 1st one\n", dn);
00591          } else {
00592             ast_debug(2, "Could not find any entry dn=%s.\n", dn);
00593          }
00594       }
00595       ldap_msgfree(ldap_result_msg);
00596 
00597       /* Chopping \a vars down to one variable */
00598       if (vars != NULL) {
00599          struct ast_variable **p = vars;
00600          p++;
00601          var = *p;
00602          while (var) {
00603             ast_variables_destroy(var);
00604             p++;
00605          }
00606          vars = ast_realloc(vars, sizeof(struct ast_variable *));
00607       }
00608 
00609       var = *vars;
00610 
00611       return var;
00612    }
00613 }
00614 
00615 /*! \brief caller should free returned pointer */
00616 static char *substituted(struct ast_channel *channel, const char *string)
00617 {
00618 #define MAXRESULT 2048
00619    char *ret_string = NULL;
00620 
00621    if (!ast_strlen_zero(string)) {
00622       ret_string = ast_calloc(1, MAXRESULT);
00623       pbx_substitute_variables_helper(channel, string, ret_string, MAXRESULT - 1);
00624    }
00625    ast_debug(2, "substituted: string: '%s' => '%s' \n",
00626       string, ret_string);
00627    return ret_string;
00628 }
00629 
00630 /*! \brief caller should free returned pointer */
00631 static char *cleaned_basedn(struct ast_channel *channel, const char *basedn)
00632 {
00633    char *cbasedn = NULL;
00634    if (basedn) {
00635       char *p = NULL;
00636       cbasedn = substituted(channel, basedn);
00637       if (*cbasedn == '"') {
00638          cbasedn++;
00639          if (!ast_strlen_zero(cbasedn)) {
00640             int len = strlen(cbasedn);
00641             if (cbasedn[len - 1] == '"')
00642                cbasedn[len - 1] = '\0';
00643 
00644          }
00645       }
00646       p = cbasedn;
00647       while (*p) {
00648          if (*p == '|')
00649             *p = ',';
00650          p++;
00651       }
00652    }
00653    ast_debug(2, "basedn: '%s' => '%s' \n", basedn, cbasedn);
00654    return cbasedn;
00655 }
00656 
00657 /*! \brief Replace <search> by <by> in string. No check is done on string allocated size ! */
00658 static int replace_string_in_string(char *string, const char *search, const char *by)
00659 {
00660    int search_len = strlen(search);
00661    int by_len = strlen(by);
00662    int replaced = 0;
00663    char *p = strstr(string, search);
00664    if (p) {
00665       replaced = 1;
00666       while (p) {
00667          if (by_len == search_len)
00668             memcpy(p, by, by_len);
00669          else {
00670             memmove(p + by_len, p + search_len,
00671                   strlen(p + search_len) + 1);
00672             memcpy(p, by, by_len);
00673          }
00674          p = strstr(p + by_len, search);
00675       }
00676    }
00677    return replaced;
00678 }
00679 
00680 /*! \brief Append a name=value filter string. The filter string can grow. */
00681 static void append_var_and_value_to_filter(struct ast_str **filter,
00682    struct ldap_table_config *table_config,
00683    const char *name, const char *value)
00684 {
00685    char *new_name = NULL;
00686    char *new_value = NULL;
00687    char *like_pos = strstr(name, " LIKE");
00688 
00689    ast_debug(2, "name='%s' value='%s'\n", name, value);
00690 
00691    if (like_pos) {
00692       int len = like_pos - name;
00693       name = new_name = ast_strdupa(name);
00694       new_name[len] = '\0';
00695       value = new_value = ast_strdupa(value);
00696       replace_string_in_string(new_value, "\\_", "_");
00697       replace_string_in_string(new_value, "%", "*");
00698    }
00699 
00700    name = convert_attribute_name_to_ldap(table_config, name);
00701 
00702    ast_str_append(filter, 0, "(%s=%s)", name, value);
00703 }
00704 
00705 /*! \brief LDAP base function 
00706  * \return a null terminated array of ast_variable (one per entry) or NULL if no entry is found or if an error occured
00707  * caller should free the returned array and ast_variables
00708  * \param entries_count_ptr is a pointer to found entries count (can be NULL)
00709  * \param basedn is the base DN
00710  * \param table_name is the table_name (used dor attribute convertion and additional filter)
00711  * \param ap contains null terminated list of pairs name/value
00712 */
00713 static struct ast_variable **realtime_ldap_base_ap(unsigned int *entries_count_ptr,
00714    const char *basedn, const char *table_name, va_list ap)
00715 {
00716    struct ast_variable **vars = NULL;
00717    const char *newparam = NULL;
00718    const char *newval = NULL;
00719    struct ldap_table_config *table_config = NULL;
00720    char *clean_basedn = cleaned_basedn(NULL, basedn);
00721    struct ast_str *filter = NULL;
00722    int tries = 0;
00723    int result = 0;
00724    LDAPMessage *ldap_result_msg = NULL;
00725 
00726    if (!table_name) {
00727       ast_log(LOG_WARNING, "No table_name specified.\n");
00728       ast_free(clean_basedn);
00729       return NULL;
00730    } 
00731 
00732    if (!(filter = ast_str_create(80))) {
00733       ast_free(clean_basedn);
00734       return NULL;
00735    }
00736 
00737    /* Get the first parameter and first value in our list of passed paramater/value pairs  */
00738    newparam = va_arg(ap, const char *);
00739    newval = va_arg(ap, const char *);
00740 
00741    if (!newparam || !newval) {
00742       ast_log(LOG_WARNING, "Realtime retrieval requires at least 1 parameter"
00743          " and 1 value to search on.\n");
00744       ast_free(filter);
00745       ast_free(clean_basedn);
00746       return NULL;
00747    }
00748 
00749    ast_mutex_lock(&ldap_lock);
00750 
00751    /* We now have our complete statement; Lets connect to the server and execute it.  */
00752    if (!ldap_reconnect()) {
00753       ast_mutex_unlock(&ldap_lock);
00754       ast_free(filter);
00755       ast_free(clean_basedn);
00756       return NULL;
00757    }
00758 
00759    table_config = table_config_for_table_name(table_name);
00760    if (!table_config) {
00761       ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
00762       ast_mutex_unlock(&ldap_lock);
00763       ast_free(filter);
00764       ast_free(clean_basedn);
00765       return NULL;
00766    }
00767 
00768    ast_str_append(&filter, 0, "(&");
00769 
00770    if (table_config && table_config->additional_filter)
00771       ast_str_append(&filter, 0, "%s", table_config->additional_filter);
00772    if (table_config != base_table_config && base_table_config && 
00773       base_table_config->additional_filter) {
00774       ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
00775    }
00776 
00777    /* Create the first part of the query using the first parameter/value pairs we just extracted */
00778    /*   If there is only 1 set, then we have our query. Otherwise, loop thru the list and concat */
00779 
00780    append_var_and_value_to_filter(&filter, table_config, newparam, newval);
00781    while ((newparam = va_arg(ap, const char *))) {
00782       newval = va_arg(ap, const char *);
00783       append_var_and_value_to_filter(&filter, table_config, newparam, newval);
00784    }
00785    ast_str_append(&filter, 0, ")");
00786 
00787    do {
00788       /* freeing ldap_result further down */
00789       result = ldap_search_ext_s(ldapConn, clean_basedn,
00790               LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
00791               &ldap_result_msg);
00792       if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
00793          ast_log(LOG_DEBUG, "Failed to query database. Try %d/10\n",
00794             tries + 1);
00795          if (++tries < 10) {
00796             usleep(1);
00797             if (ldapConn) {
00798                ldap_unbind_ext_s(ldapConn, NULL, NULL);
00799                ldapConn = NULL;
00800             }
00801             if (!ldap_reconnect())
00802                break;
00803          }
00804       }
00805    } while (result != LDAP_SUCCESS && tries < 10 && is_ldap_connect_error(result));
00806 
00807    if (result != LDAP_SUCCESS) {
00808       ast_log(LOG_WARNING, "Failed to query database. Check debug for more info.\n");
00809       ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
00810       ast_log(LOG_WARNING, "Query Failed because: %s\n", ldap_err2string(result));
00811    } else {
00812       /* this is where we create the variables from the search result 
00813        * freeing this \a vars outside this function */
00814       if (ldap_count_entries(ldapConn, ldap_result_msg) > 0) {
00815          /* is this a static var or some other? they are handled different for delimited values */
00816          vars = realtime_ldap_result_to_vars(table_config, ldap_result_msg, entries_count_ptr);
00817       } else {
00818          ast_debug(1, "Could not find any entry matching %s in base dn %s.\n",
00819             ast_str_buffer(filter), clean_basedn);
00820       }
00821 
00822       ldap_msgfree(ldap_result_msg);
00823 
00824       /* TODO: get the default variables from the accountBaseDN, not implemented with delimited values */
00825       if (vars) {
00826          struct ast_variable **p = vars;
00827          while (*p) {
00828             struct ast_variable *append_var = NULL;
00829             struct ast_variable *tmp = *p;
00830             while (tmp) {
00831                if (strcasecmp(tmp->name, "accountBaseDN") == 0) {
00832                   /* Get the variable to compare with for the defaults */
00833                   struct ast_variable *base_var = ldap_loadentry(table_config, tmp->value);
00834                   
00835                   while (base_var) {
00836                      struct ast_variable *next = base_var->next;
00837                      struct ast_variable *test_var = *p;
00838                      int base_var_found = 0;
00839 
00840                      /* run throught the default values and fill it inn if it is missing */
00841                      while (test_var) {
00842                         if (strcasecmp(test_var->name, base_var->name) == 0) {
00843                            base_var_found = 1;
00844                            break;
00845                         } else
00846                            test_var = test_var->next;
00847                      }
00848                      if (base_var_found) {
00849                         base_var->next = NULL;
00850                         ast_variables_destroy(base_var);
00851                         base_var = next;
00852                      } else {
00853                         if (append_var)
00854                            base_var->next = append_var;
00855                         else
00856                            base_var->next = NULL;
00857                         append_var = base_var;
00858                         base_var = next;
00859                      }
00860                   }
00861                }
00862                if (!tmp->next && append_var) {
00863                   tmp->next = append_var;
00864                   tmp = NULL;
00865                } else
00866                   tmp = tmp->next;
00867             }
00868             p++;
00869          }
00870       }
00871    }
00872 
00873    if (filter)
00874       ast_free(filter);
00875 
00876    if (clean_basedn)
00877       ast_free(clean_basedn);
00878 
00879    ast_mutex_unlock(&ldap_lock);
00880 
00881    return vars;
00882 }
00883 
00884 /*! \brief same as realtime_ldap_base_ap but take variable arguments count list */
00885 static struct ast_variable **realtime_ldap_base(unsigned int *entries_count_ptr,
00886    const char *basedn, const char *table_name, ...)
00887 {
00888    struct ast_variable **vars = NULL;
00889    va_list ap;
00890 
00891    va_start(ap, table_name);
00892    vars = realtime_ldap_base_ap(entries_count_ptr, basedn, table_name, ap);
00893    va_end(ap);
00894 
00895    return vars;
00896 }
00897 
00898 /*! \brief See Asterisk doc
00899 *
00900 * For Realtime Dynamic(i.e., switch, queues, and directory) -- I think
00901 */
00902 static struct ast_variable *realtime_ldap(const char *basedn,
00903                  const char *table_name, va_list ap)
00904 {
00905    struct ast_variable **vars = realtime_ldap_base_ap(NULL, basedn, table_name, ap);
00906    struct ast_variable *var = NULL;
00907 
00908    if (vars) {
00909       struct ast_variable *last_var = NULL;
00910       struct ast_variable **p = vars;
00911       while (*p) {
00912          if (last_var) {
00913             while (last_var->next)
00914                last_var = last_var->next;
00915             last_var->next = *p;
00916          } else {
00917             var = *p;
00918             last_var = var;
00919          }
00920          p++;
00921       }
00922       free(vars);
00923    }
00924    return var;
00925 }
00926 
00927 /*! \brief See Asterisk doc
00928 *
00929 * 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);
00930 * however, the ast_load_realtime wil match on wildcharacters also depending on what the mode is set to
00931 * this is an area of asterisk that could do with a lot of modification
00932 * I think this function returns Realtime dynamic objects
00933 */
00934 static struct ast_config *realtime_multi_ldap(const char *basedn,
00935       const char *table_name, va_list ap)
00936 {
00937         char *op;
00938         const char *initfield = NULL;
00939         const char *newparam, *newval;
00940    struct ast_variable **vars =
00941       realtime_ldap_base_ap(NULL, basedn, table_name, ap);
00942    struct ast_config *cfg = NULL;
00943 
00944         newparam = va_arg(ap, const char *);
00945         newval = va_arg(ap, const char *);
00946         if (!newparam || !newval) {
00947             ast_log(LOG_WARNING, "realtime retrieval requires at least 1 parameter and 1 value to search on.\n");
00948             return NULL;
00949         }
00950         initfield = ast_strdupa(newparam);
00951         if ((op = strchr(initfield, ' '))) {
00952                 *op = '\0';
00953         }
00954 
00955    if (vars) {
00956       cfg = ast_config_new();
00957       if (!cfg) {
00958          ast_log(LOG_ERROR, "Unable to create a config!\n");
00959       } else {
00960          struct ast_variable **p = vars;
00961 
00962          while (*p) {
00963             struct ast_category *cat = NULL;
00964             cat = ast_category_new("", table_name, -1);
00965             if (!cat) {
00966                ast_log(LOG_ERROR, "Unable to create a new category!\n");
00967                break;
00968             } else {
00969                struct ast_variable *var = *p;
00970                while (var) {
00971                   struct ast_variable *next = var->next;
00972                                                 if (initfield && !strcmp(initfield, var->name)) {
00973                                                         ast_category_rename(cat, var->value);
00974                                                 }
00975                   var->next = NULL;
00976                   ast_variable_append(cat, var);
00977                   var = next;
00978                }
00979             }
00980             ast_category_append(cfg, cat);
00981             p++;
00982          }
00983       }
00984       free(vars);
00985    }
00986    return cfg;
00987 
00988 }
00989 
00990 /*! 
00991  * \brief Sorting alogrithm for qsort to find the order of the variables \a a and \a b
00992  * \param a pointer to category_and_metric struct
00993  * \param b pointer to category_and_metric struct
00994  *
00995  * \retval -1 for if b is greater
00996  * \retval 0 zero for equal
00997  * \retval 1 if a is greater
00998  */
00999 static int compare_categories(const void *a, const void *b)
01000 {
01001    const struct category_and_metric *as = a;
01002    const struct category_and_metric *bs = b;
01003 
01004    if (as->metric < bs->metric)
01005       return -1;
01006    else if (as->metric > bs->metric)
01007       return 1;
01008    else if (as->metric == bs->metric && strcmp(as->name, bs->name) != 0)
01009       return strcmp(as->name, bs->name);
01010 
01011    /* if the metric and the category name is the same, we check the variable metric */
01012    if (as->var_metric < bs->var_metric)
01013       return -1;
01014    else if (as->var_metric > bs->var_metric)
01015       return 1;
01016 
01017    return 0;
01018 }
01019 
01020 /*! \brief See Asterisk doc
01021  *
01022 *  This is for Static Realtime (again: I think...)
01023 *  
01024 *  load the configuration stuff for the .conf files
01025 *  called on a reload
01026 */
01027 static struct ast_config *config_ldap(const char *basedn, const char *table_name,
01028    const char *file, struct ast_config *cfg, struct ast_flags config_flags, const char *sugg_incl, const char *who_asked)
01029 {
01030    unsigned int vars_count = 0;
01031    struct ast_variable **vars;
01032    int i = 0;
01033    struct ast_variable *new_v = NULL;
01034    struct ast_category *cur_cat = NULL;
01035    const char *last_category = NULL;
01036    int last_category_metric = 0;
01037    struct category_and_metric *categories;
01038    struct ast_variable **p;
01039 
01040    if (ast_strlen_zero(file) || !strcasecmp(file, RES_CONFIG_LDAP_CONF)) {
01041       ast_log(LOG_ERROR, "Cannot configure myself.\n");
01042       return NULL;
01043    }
01044 
01045    vars = realtime_ldap_base(&vars_count, basedn, table_name, "filename",
01046             file, "commented", "FALSE", NULL);
01047 
01048    if (!vars) {
01049       ast_log(LOG_WARNING, "Could not find config '%s' in database.\n", file);
01050       return NULL;
01051    }
01052 
01053    /*!\note Since the items come back in random order, they need to be sorted
01054     * first, and since the data could easily exceed stack size, this is
01055     * allocated from the heap.
01056     */
01057    if (!(categories = ast_calloc(sizeof(*categories), vars_count)))
01058       return NULL;
01059 
01060    for (vars_count = 0, p = vars; *p; p++) {
01061       struct ast_variable *category = variable_named(*p, "category");
01062       struct ast_variable *cat_metric = variable_named(*p, "cat_metric");
01063       struct ast_variable *var_name = variable_named(*p, "variable_name");
01064       struct ast_variable *var_val = variable_named(*p, "variable_value");
01065       struct ast_variable *var_metric = variable_named(*p, "var_metric");
01066       struct ast_variable *dn = variable_named(*p, "dn");
01067          
01068       ast_debug(1, "category: %s\n", category->value);
01069       ast_debug(1, "var_name: %s\n", var_name->value);
01070       ast_debug(1, "var_val: %s\n", var_val->value);
01071       ast_debug(1, "cat_metric: %s\n", cat_metric->value);
01072 
01073       if (!category) {
01074          ast_log(LOG_ERROR,
01075                "No category name in entry '%s'  for file '%s'.\n",
01076                (dn ? dn->value : "?"), file);
01077       } else if (!cat_metric) {
01078          ast_log(LOG_ERROR,
01079                "No category metric in entry '%s'(category: %s) for file '%s'.\n",
01080                (dn ? dn->value : "?"), category->value, file);
01081       } else if (!var_metric) {
01082          ast_log(LOG_ERROR,
01083                "No variable metric in entry '%s'(category: %s) for file '%s'.\n",
01084                (dn ? dn->value : "?"), category->value, file);
01085       } else if (!var_name) {
01086          ast_log(LOG_ERROR,
01087                "No variable name in entry '%s' (category: %s metric: %s) for file '%s'.\n",
01088                (dn ? dn->value : "?"), category->value,
01089                cat_metric->value, file);
01090       } else if (!var_val) {
01091          ast_log(LOG_ERROR,
01092                "No variable value in entry '%s' (category: %s metric: %s variable: %s) for file '%s'.\n",
01093                (dn ? dn->value : "?"), category->value,
01094                cat_metric->value, var_name->value, file);
01095       } else {
01096          categories[vars_count].name = category->value;
01097          categories[vars_count].metric = atoi(cat_metric->value);
01098          categories[vars_count].variable_name = var_name->value;
01099          categories[vars_count].variable_value = var_val->value;
01100          categories[vars_count].var_metric = atoi(var_metric->value);
01101          vars_count++;
01102       }
01103    }
01104 
01105    qsort(categories, vars_count, sizeof(*categories), compare_categories);
01106 
01107    for (i = 0; i < vars_count; i++) {
01108       if (!strcmp(categories[i].variable_name, "#include")) {
01109          struct ast_flags flags = { 0 };
01110          if (!ast_config_internal_load(categories[i].variable_value, cfg, flags, "", who_asked))
01111             break;
01112          continue;
01113       }
01114 
01115       if (!last_category || strcmp(last_category, categories[i].name) ||
01116          last_category_metric != categories[i].metric) {
01117          cur_cat = ast_category_new(categories[i].name, table_name, -1);
01118          if (!cur_cat)
01119             break;
01120          last_category = categories[i].name;
01121          last_category_metric = categories[i].metric;
01122          ast_category_append(cfg, cur_cat);
01123       }
01124 
01125       if (!(new_v = ast_variable_new(categories[i].variable_name, categories[i].variable_value, table_name)))
01126          break;
01127 
01128       ast_variable_append(cur_cat, new_v);
01129    }
01130 
01131    free(vars);
01132    free(categories);
01133 
01134    return cfg;
01135 }
01136 
01137 /* \brief Function to update a set of values in ldap
01138 static
01139 */
01140 static int update_ldap(const char *basedn, const char *table_name, const char *attribute,
01141    const char *lookup, va_list ap)
01142 {
01143    int error = 0;
01144    LDAPMessage *ldap_entry = NULL;
01145    LDAPMod **ldap_mods;
01146    const char *newparam = NULL;
01147    const char *newval = NULL;
01148    char *dn;
01149    int num_entries = 0;
01150    int i = 0;
01151    int mods_size = 0;
01152    int mod_exists = 0;
01153    struct ldap_table_config *table_config = NULL;
01154    char *clean_basedn = NULL;
01155    struct ast_str *filter = NULL;
01156    int tries = 0;
01157    int result = 0;
01158    LDAPMessage *ldap_result_msg = NULL;
01159 
01160    if (!table_name) {
01161       ast_log(LOG_WARNING, "No table_name specified.\n");
01162       return -1;
01163    } 
01164 
01165    if (!(filter = ast_str_create(80)))
01166       return -1;
01167 
01168    if (!attribute || !lookup) {
01169       ast_log(LOG_WARNING,
01170             "LINE(%d): search parameters are empty.\n", __LINE__);
01171       return -1;
01172    }
01173    ast_mutex_lock(&ldap_lock);
01174 
01175    /* We now have our complete statement; Lets connect to the server and execute it.  */
01176    if (!ldap_reconnect()) {
01177       ast_mutex_unlock(&ldap_lock);
01178       return -1;
01179    }
01180 
01181    table_config = table_config_for_table_name(table_name);
01182    if (!table_config) {
01183       ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
01184       ast_mutex_unlock(&ldap_lock);
01185       return -1;
01186    }
01187 
01188    clean_basedn = cleaned_basedn(NULL, basedn);
01189 
01190    /* Create the filter with the table additional filter and the parameter/value pairs we were given */
01191    ast_str_append(&filter, 0, "(&");
01192    if (table_config && table_config->additional_filter) {
01193       ast_str_append(&filter, 0, "%s", table_config->additional_filter);
01194    }
01195    if (table_config != base_table_config && base_table_config
01196       && base_table_config->additional_filter) {
01197       ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
01198    }
01199    append_var_and_value_to_filter(&filter, table_config, attribute, lookup);
01200    ast_str_append(&filter, 0, ")");
01201 
01202    /* Create the modification array with the parameter/value pairs we were given, 
01203     * if there are several parameters with the same name, we collect them into 
01204     * one parameter/value pair and delimit them with a semicolon */
01205    newparam = va_arg(ap, const char *);
01206    newparam = convert_attribute_name_to_ldap(table_config, newparam);
01207    newval = va_arg(ap, const char *);
01208    if (!newparam || !newval) {
01209       ast_log(LOG_WARNING,
01210             "LINE(%d): need at least one parameter to modify.\n", __LINE__);
01211       return -1;
01212    }
01213 
01214    mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
01215    ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
01216    ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
01217 
01218    ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
01219    ldap_mods[0]->mod_type = ast_strdup(newparam);
01220 
01221    ldap_mods[0]->mod_values = ast_calloc(sizeof(char *), 2);
01222    ldap_mods[0]->mod_values[0] = ast_strdup(newval);
01223 
01224    while ((newparam = va_arg(ap, const char *))) {
01225       newparam = convert_attribute_name_to_ldap(table_config, newparam);
01226       newval = va_arg(ap, const char *);
01227       mod_exists = 0;
01228 
01229       for (i = 0; i < mods_size - 1; i++) {
01230          if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
01231             /* We have the parameter allready, adding the value as a semicolon delimited value */
01232             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));
01233             strcat(ldap_mods[i]->mod_values[0], ";");
01234             strcat(ldap_mods[i]->mod_values[0], newval);
01235             mod_exists = 1;   
01236             break;
01237          }
01238       }
01239 
01240       /* create new mod */
01241       if (!mod_exists) {
01242          mods_size++;
01243          ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
01244          ldap_mods[mods_size - 1] = NULL;
01245          
01246          ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
01247 
01248          ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
01249          strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
01250 
01251          if (strlen(newval) == 0) {
01252             ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_DELETE;
01253          } else {
01254             ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
01255 
01256             ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
01257             ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
01258             strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
01259          }
01260       }
01261    }
01262    /* freeing ldap_mods further down */
01263 
01264    do {
01265       /* freeing ldap_result further down */
01266       result = ldap_search_ext_s(ldapConn, clean_basedn,
01267               LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
01268               &ldap_result_msg);
01269       if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
01270          ast_log(LOG_WARNING, "Failed to query database. Try %d/3\n",
01271             tries + 1);
01272          tries++;
01273          if (tries < 3) {
01274             usleep(500000L * tries);
01275             if (ldapConn) {
01276                ldap_unbind_ext_s(ldapConn, NULL, NULL);
01277                ldapConn = NULL;
01278             }
01279             if (!ldap_reconnect())
01280                break;
01281          }
01282       }
01283    } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
01284 
01285    if (result != LDAP_SUCCESS) {
01286       ast_log(LOG_WARNING, "Failed to query directory. Check debug for more info.\n");
01287       ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
01288       ast_log(LOG_WARNING, "Query Failed because: %s\n",
01289          ldap_err2string(result));
01290 
01291       ast_mutex_unlock(&ldap_lock);
01292       free(filter);
01293       free(clean_basedn);
01294       ldap_msgfree(ldap_result_msg);
01295       ldap_mods_free(ldap_mods, 0);
01296       return -1;
01297    }
01298    /* Ready to update */
01299    if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
01300       ast_debug(3, "LINE(%d) Modifying %s=%s hits: %d\n", __LINE__, attribute, lookup, num_entries);
01301       for (i = 0; option_debug > 2 && i < mods_size - 1; i++) {
01302          if (ldap_mods[i]->mod_op != LDAP_MOD_DELETE) {
01303             ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
01304          } else {
01305             ast_debug(3, "LINE(%d) deleting %s \n", __LINE__, ldap_mods[i]->mod_type);
01306          }
01307       }
01308       ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
01309 
01310       for (i = 0; ldap_entry; i++) { 
01311          dn = ldap_get_dn(ldapConn, ldap_entry);
01312          if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) 
01313             ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
01314 
01315          ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
01316       }
01317    }
01318 
01319    ast_mutex_unlock(&ldap_lock);
01320    free(filter);
01321    free(clean_basedn);
01322    ldap_msgfree(ldap_result_msg);
01323    ldap_mods_free(ldap_mods, 0);
01324    return num_entries;
01325 }
01326 
01327 static int update2_ldap(const char *basedn, const char *table_name, va_list ap)
01328 {
01329    int error = 0;
01330    LDAPMessage *ldap_entry = NULL;
01331    LDAPMod **ldap_mods;
01332    const char *newparam = NULL;
01333    const char *newval = NULL;
01334    char *dn;
01335    int num_entries = 0;
01336    int i = 0;
01337    int mods_size = 0;
01338    int mod_exists = 0;
01339    struct ldap_table_config *table_config = NULL;
01340    char *clean_basedn = NULL;
01341    struct ast_str *filter = NULL;
01342    int tries = 0;
01343    int result = 0;
01344    LDAPMessage *ldap_result_msg = NULL;
01345 
01346    if (!table_name) {
01347       ast_log(LOG_WARNING, "No table_name specified.\n");
01348       return -1;
01349    } 
01350 
01351    if (!(filter = ast_str_create(80)))
01352       return -1;
01353 
01354    ast_mutex_lock(&ldap_lock);
01355 
01356    /* We now have our complete statement; Lets connect to the server and execute it.  */
01357    if (!ldap_reconnect()) {
01358       ast_mutex_unlock(&ldap_lock);
01359       ast_free(filter);
01360       return -1;
01361    }
01362 
01363    table_config = table_config_for_table_name(table_name);
01364    if (!table_config) {
01365       ast_log(LOG_WARNING, "No table named '%s'.\n", table_name);
01366       ast_mutex_unlock(&ldap_lock);
01367       ast_free(filter);
01368       return -1;
01369    }
01370 
01371    clean_basedn = cleaned_basedn(NULL, basedn);
01372 
01373    /* Create the filter with the table additional filter and the parameter/value pairs we were given */
01374    ast_str_append(&filter, 0, "(&");
01375    if (table_config && table_config->additional_filter) {
01376       ast_str_append(&filter, 0, "%s", table_config->additional_filter);
01377    }
01378    if (table_config != base_table_config && base_table_config
01379       && base_table_config->additional_filter) {
01380       ast_str_append(&filter, 0, "%s", base_table_config->additional_filter);
01381    }
01382 
01383    /* Get multiple lookup keyfields and values */
01384    while ((newparam = va_arg(ap, const char *))) {
01385       newval = va_arg(ap, const char *);
01386       append_var_and_value_to_filter(&filter, table_config, newparam, newval);
01387    }
01388    ast_str_append(&filter, 0, ")");
01389 
01390    /* Create the modification array with the parameter/value pairs we were given, 
01391     * if there are several parameters with the same name, we collect them into 
01392     * one parameter/value pair and delimit them with a semicolon */
01393    newparam = va_arg(ap, const char *);
01394    newparam = convert_attribute_name_to_ldap(table_config, newparam);
01395    newval = va_arg(ap, const char *);
01396    if (!newparam || !newval) {
01397       ast_log(LOG_WARNING,
01398             "LINE(%d): need at least one parameter to modify.\n", __LINE__);
01399       ast_free(filter);
01400       ast_free(clean_basedn);
01401       return -1;
01402    }
01403 
01404    mods_size = 2; /* one for the first param/value pair and one for the the terminating NULL */
01405    ldap_mods = ast_calloc(sizeof(LDAPMod *), mods_size);
01406    ldap_mods[0] = ast_calloc(1, sizeof(LDAPMod));
01407 
01408    ldap_mods[0]->mod_op = LDAP_MOD_REPLACE;
01409    ldap_mods[0]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
01410    strcpy(ldap_mods[0]->mod_type, newparam);
01411 
01412    ldap_mods[0]->mod_values = ast_calloc(sizeof(char), 2);
01413    ldap_mods[0]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
01414    strcpy(ldap_mods[0]->mod_values[0], newval);
01415 
01416    while ((newparam = va_arg(ap, const char *))) {
01417       newparam = convert_attribute_name_to_ldap(table_config, newparam);
01418       newval = va_arg(ap, const char *);
01419       mod_exists = 0;
01420 
01421       for (i = 0; i < mods_size - 1; i++) {
01422          if (ldap_mods[i]&& !strcmp(ldap_mods[i]->mod_type, newparam)) {
01423             /* We have the parameter allready, adding the value as a semicolon delimited value */
01424             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));
01425             strcat(ldap_mods[i]->mod_values[0], ";");
01426             strcat(ldap_mods[i]->mod_values[0], newval);
01427             mod_exists = 1;   
01428             break;
01429          }
01430       }
01431 
01432       /* create new mod */
01433       if (!mod_exists) {
01434          mods_size++;
01435          ldap_mods = ast_realloc(ldap_mods, sizeof(LDAPMod *) * mods_size);
01436          ldap_mods[mods_size - 1] = NULL;
01437          ldap_mods[mods_size - 2] = ast_calloc(1, sizeof(LDAPMod));
01438 
01439          ldap_mods[mods_size - 2]->mod_op = LDAP_MOD_REPLACE;
01440 
01441          ldap_mods[mods_size - 2]->mod_type = ast_calloc(sizeof(char), strlen(newparam) + 1);
01442          strcpy(ldap_mods[mods_size - 2]->mod_type, newparam);
01443 
01444          ldap_mods[mods_size - 2]->mod_values = ast_calloc(sizeof(char *), 2);
01445          ldap_mods[mods_size - 2]->mod_values[0] = ast_calloc(sizeof(char), strlen(newval) + 1);
01446          strcpy(ldap_mods[mods_size - 2]->mod_values[0], newval);
01447       }
01448    }
01449    /* freeing ldap_mods further down */
01450 
01451    do {
01452       /* freeing ldap_result further down */
01453       result = ldap_search_ext_s(ldapConn, clean_basedn,
01454               LDAP_SCOPE_SUBTREE, ast_str_buffer(filter), NULL, 0, NULL, NULL, NULL, LDAP_NO_LIMIT,
01455               &ldap_result_msg);
01456       if (result != LDAP_SUCCESS && is_ldap_connect_error(result)) {
01457          ast_log(LOG_WARNING, "Failed to query database. Try %d/3\n",
01458             tries + 1);
01459          tries++;
01460          if (tries < 3) {
01461             usleep(500000L * tries);
01462             if (ldapConn) {
01463                ldap_unbind_ext_s(ldapConn, NULL, NULL);
01464                ldapConn = NULL;
01465             }
01466             if (!ldap_reconnect())
01467                break;
01468          }
01469       }
01470    } while (result != LDAP_SUCCESS && tries < 3 && is_ldap_connect_error(result));
01471 
01472    if (result != LDAP_SUCCESS) {
01473       ast_log(LOG_WARNING, "Failed to query directory. Check debug for more info.\n");
01474       ast_log(LOG_WARNING, "Query: %s\n", ast_str_buffer(filter));
01475       ast_log(LOG_WARNING, "Query Failed because: %s\n",
01476          ldap_err2string(result));
01477 
01478       ast_mutex_unlock(&ldap_lock);
01479       free(filter);
01480       free(clean_basedn);
01481       ldap_msgfree(ldap_result_msg);
01482       ldap_mods_free(ldap_mods, 0);
01483       return -1;
01484    }
01485    /* Ready to update */
01486    if ((num_entries = ldap_count_entries(ldapConn, ldap_result_msg)) > 0) {
01487       for (i = 0; option_debug > 2 && i < mods_size - 1; i++)
01488          ast_debug(3, "LINE(%d) %s=%s \n", __LINE__, ldap_mods[i]->mod_type, ldap_mods[i]->mod_values[0]);
01489 
01490       ldap_entry = ldap_first_entry(ldapConn, ldap_result_msg);
01491 
01492       for (i = 0; ldap_entry; i++) { 
01493          dn = ldap_get_dn(ldapConn, ldap_entry);
01494          if ((error = ldap_modify_ext_s(ldapConn, dn, ldap_mods, NULL, NULL)) != LDAP_SUCCESS) 
01495             ast_log(LOG_ERROR, "Couldn't modify dn:%s because %s", dn, ldap_err2string(error));
01496 
01497          ldap_entry = ldap_next_entry(ldapConn, ldap_entry);
01498       }
01499    }
01500 
01501    ast_mutex_unlock(&ldap_lock);
01502    if (filter)
01503       free(filter);
01504    if (clean_basedn)
01505       free(clean_basedn);
01506    ldap_msgfree(ldap_result_msg);
01507    ldap_mods_free(ldap_mods, 0);
01508    return num_entries;
01509 }
01510 
01511 static struct ast_config_engine ldap_engine = {
01512    .name = "ldap",
01513    .load_func = config_ldap,
01514    .realtime_func = realtime_ldap,
01515    .realtime_multi_func = realtime_multi_ldap,
01516    .update_func = update_ldap,
01517    .update2_func = update2_ldap,
01518 };
01519 
01520 static int load_module(void)
01521 {
01522    if (parse_config() < 0) {
01523       ast_log(LOG_NOTICE, "Cannot load LDAP RealTime driver.\n");
01524       return 0;
01525    }
01526 
01527    ast_mutex_lock(&ldap_lock);
01528 
01529    if (!ldap_reconnect()) 
01530       ast_log(LOG_WARNING, "Couldn't establish connection. Check debug.\n");
01531 
01532    ast_config_engine_register(&ldap_engine);
01533    ast_verb(1, "LDAP RealTime driver loaded.\n");
01534    ast_cli_register_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
01535 
01536    ast_mutex_unlock(&ldap_lock);
01537 
01538    return 0;
01539 }
01540 
01541 static int unload_module(void)
01542 {
01543    /* Aquire control before doing anything to the module itself. */
01544    ast_mutex_lock(&ldap_lock);
01545 
01546    table_configs_free();
01547 
01548    if (ldapConn) {
01549       ldap_unbind_ext_s(ldapConn, NULL, NULL);
01550       ldapConn = NULL;
01551    }
01552    ast_cli_unregister_multiple(ldap_cli, ARRAY_LEN(ldap_cli));
01553    ast_config_engine_deregister(&ldap_engine);
01554    ast_verb(1, "LDAP RealTime unloaded.\n");
01555 
01556    /* Unlock so something else can destroy the lock. */
01557    ast_mutex_unlock(&ldap_lock);
01558 
01559    return 0;
01560 }
01561 
01562 static int reload(void)
01563 {
01564    /* Aquire control before doing anything to the module itself. */
01565    ast_mutex_lock(&ldap_lock);
01566 
01567    if (ldapConn) {
01568       ldap_unbind_ext_s(ldapConn, NULL, NULL);
01569       ldapConn = NULL;
01570    }
01571 
01572    if (parse_config() < 0) {
01573       ast_log(LOG_NOTICE, "Cannot reload LDAP RealTime driver.\n");
01574       ast_mutex_unlock(&ldap_lock);
01575       return 0;
01576    }     
01577 
01578    if (!ldap_reconnect()) 
01579       ast_log(LOG_WARNING, "Couldn't establish connection. Check debug.\n");
01580 
01581    ast_verb(2, "LDAP RealTime reloaded.\n");
01582 
01583    /* Done reloading. Release lock so others can now use driver. */
01584    ast_mutex_unlock(&ldap_lock);
01585 
01586    return 0;
01587 }
01588 
01589 int parse_config(void)
01590 {
01591    struct ast_config *config;
01592    struct ast_flags config_flags = {0};
01593    const char *s, *host;
01594    int port;
01595    char *category_name = NULL;
01596 
01597    config = ast_config_load(RES_CONFIG_LDAP_CONF, config_flags);
01598    if (config == CONFIG_STATUS_FILEMISSING || config == CONFIG_STATUS_FILEINVALID) {
01599       ast_log(LOG_WARNING, "Cannot load configuration %s\n", RES_CONFIG_LDAP_CONF);
01600       return -1;
01601    }
01602 
01603    if (!(s = ast_variable_retrieve(config, "_general", "user"))) {
01604       ast_log(LOG_WARNING, "No directory user found, anonymous binding as default.\n");
01605       user[0] = '\0';
01606    } else 
01607       ast_copy_string(user, s, sizeof(user));
01608 
01609    if (!ast_strlen_zero(user)) {
01610       if (!(s = ast_variable_retrieve(config, "_general", "pass"))) {
01611          ast_log(LOG_WARNING, "No directory password found, using 'asterisk' as default.\n");
01612          ast_copy_string(pass, "asterisk", sizeof(pass));
01613       } else {
01614          ast_copy_string(pass, s, sizeof(pass));
01615       }
01616    }
01617 
01618    /* URL is preferred, use host and port if not found */
01619    if ((s = ast_variable_retrieve(config, "_general", "url"))) {
01620       ast_copy_string(url, s, sizeof(url));
01621    } else if ((host = ast_variable_retrieve(config, "_general", "host"))) {
01622       if (!(s = ast_variable_retrieve(config, "_general", "port")) || sscanf(s, "%5d", &port) != 1 || port > 65535) {
01623          ast_log(LOG_NOTICE, "No directory port found, using 389 as default.\n");
01624          port = 389;
01625       }
01626 
01627       snprintf(url, sizeof(url), "ldap://%s:%d", host, port);
01628    } else {
01629       ast_log(LOG_ERROR, "No directory URL or host found.\n");
01630       ast_config_destroy(config);
01631       return -1;
01632    }
01633 
01634    if (!(s = ast_variable_retrieve(config, "_general", "basedn"))) {
01635       ast_log(LOG_ERROR, "No LDAP base dn found, using '%s' as default.\n", RES_CONFIG_LDAP_DEFAULT_BASEDN);
01636       ast_copy_string(base_distinguished_name, RES_CONFIG_LDAP_DEFAULT_BASEDN, sizeof(base_distinguished_name));
01637    } else 
01638       ast_copy_string(base_distinguished_name, s, sizeof(base_distinguished_name));
01639 
01640    if (!(s = ast_variable_retrieve(config, "_general", "version")) && !(s = ast_variable_retrieve(config, "_general", "protocol"))) {
01641       ast_log(LOG_NOTICE, "No explicit LDAP version found, using 3 as default.\n");
01642       version = 3;
01643    } else if (sscanf(s, "%30d", &version) != 1 || version < 1 || version > 6) {
01644       ast_log(LOG_WARNING, "Invalid LDAP version '%s', using 3 as default.\n", s);
01645       version = 3;
01646    }
01647 
01648    table_configs_free();
01649 
01650    while ((category_name = ast_category_browse(config, category_name))) {
01651       int is_general = (strcasecmp(category_name, "_general") == 0);
01652       int is_config = (strcasecmp(category_name, "config") == 0); /*!< using the [config] context for Static RealTime */
01653       struct ast_variable *var = ast_variable_browse(config, category_name);
01654       
01655       if (var) {
01656          struct ldap_table_config *table_config =
01657             table_config_for_table_name(category_name);
01658          if (!table_config) {
01659             table_config = table_config_new(category_name);
01660             AST_LIST_INSERT_HEAD(&table_configs, table_config, entry);
01661             if (is_general)
01662                base_table_config = table_config;
01663             if (is_config)
01664                static_table_config = table_config;
01665          }
01666          for (; var; var = var->next) {
01667             if (!strcasecmp(var->name, "additionalFilter")) {
01668                table_config->additional_filter = ast_strdup(var->value);
01669             } else {
01670                ldap_table_config_add_attribute(table_config, var->name, var->value);
01671             }
01672          }
01673       }
01674    }
01675 
01676    ast_config_destroy(config);
01677 
01678    return 1;
01679 }
01680 
01681 /*! \note ldap_lock should have been locked before calling this function. */
01682 static int ldap_reconnect(void)
01683 {
01684    int bind_result = 0;
01685    struct berval cred;
01686 
01687    if (ldapConn) {
01688       ast_debug(2, "Everything seems fine.\n");
01689       return 1;
01690    }
01691 
01692    if (ast_strlen_zero(url)) {
01693       ast_log(LOG_ERROR, "Not enough parameters to connect to ldap database\n");
01694       return 0;
01695    }
01696 
01697    if (LDAP_SUCCESS != ldap_initialize(&ldapConn, url)) {
01698       ast_log(LOG_ERROR, "Failed to init ldap connection to '%s'. Check debug for more info.\n", url);
01699       return 0;
01700    }
01701 
01702    if (LDAP_OPT_SUCCESS != ldap_set_option(ldapConn, LDAP_OPT_PROTOCOL_VERSION, &version)) {
01703       ast_log(LOG_WARNING, "Unable to set LDAP protocol version to %d, falling back to default.\n", version);
01704    }
01705 
01706    if (!ast_strlen_zero(user)) {
01707       ast_debug(2, "bind to '%s' as user '%s'\n", url, user);
01708       cred.bv_val = (char *) pass;
01709       cred.bv_len = strlen(pass);
01710       bind_result = ldap_sasl_bind_s(ldapConn, user, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
01711    } else {
01712       ast_debug(2, "bind %s anonymously\n", url);
01713       cred.bv_val = NULL;
01714       cred.bv_len = 0;
01715       bind_result = ldap_sasl_bind_s(ldapConn, NULL, LDAP_SASL_SIMPLE, &cred, NULL, NULL, NULL);
01716    }
01717    if (bind_result == LDAP_SUCCESS) {
01718       ast_debug(2, "Successfully connected to database.\n");
01719       connect_time = time(NULL);
01720       return 1;
01721    } else {
01722       ast_log(LOG_WARNING, "bind failed: %s\n", ldap_err2string(bind_result));
01723       ldap_unbind_ext_s(ldapConn, NULL, NULL);
01724       ldapConn = NULL;
01725       return 0;
01726    }
01727 }
01728 
01729 static char *realtime_ldap_status(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
01730 {
01731    char status[256], credentials[100] = "";
01732    int ctimesec = time(NULL) - connect_time;
01733 
01734    switch (cmd) {
01735    case CLI_INIT:
01736       e->command = "realtime show ldap status";
01737       e->usage =
01738          "Usage: realtime show ldap status\n"
01739          "               Shows connection information for the LDAP RealTime driver\n";
01740       return NULL;
01741    case CLI_GENERATE:
01742       return NULL;
01743    }
01744 
01745    if (!ldapConn)
01746       return CLI_FAILURE;
01747 
01748    if (!ast_strlen_zero(url)) 
01749       snprintf(status, sizeof(status), "Connected to '%s', baseDN %s", url, base_distinguished_name);
01750 
01751    if (!ast_strlen_zero(user))
01752       snprintf(credentials, sizeof(credentials), " with username %s", user);
01753 
01754    if (ctimesec > 31536000) {
01755       ast_cli(a->fd, "%s%s for %d years, %d days, %d hours, %d minutes, %d seconds.\n",
01756             status, credentials, ctimesec / 31536000,
01757             (ctimesec % 31536000) / 86400, (ctimesec % 86400) / 3600,
01758             (ctimesec % 3600) / 60, ctimesec % 60);
01759    } else if (ctimesec > 86400) {
01760       ast_cli(a->fd, "%s%s for %d days, %d hours, %d minutes, %d seconds.\n",
01761             status, credentials, ctimesec / 86400, (ctimesec % 86400) / 3600,
01762             (ctimesec % 3600) / 60, ctimesec % 60);
01763    } else if (ctimesec > 3600) {
01764       ast_cli(a->fd, "%s%s for %d hours, %d minutes, %d seconds.\n",
01765             status, credentials, ctimesec / 3600, (ctimesec % 3600) / 60,
01766             ctimesec % 60);
01767    } else if (ctimesec > 60) {
01768       ast_cli(a->fd, "%s%s for %d minutes, %d seconds.\n", status, credentials,
01769                ctimesec / 60, ctimesec % 60);
01770    } else {
01771       ast_cli(a->fd, "%s%s for %d seconds.\n", status, credentials, ctimesec);
01772    }
01773 
01774    return CLI_SUCCESS;
01775 }
01776 
01777 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "LDAP realtime interface",
01778    .load = load_module,
01779    .unload = unload_module,
01780    .reload = reload,
01781 );

Generated on Sat Mar 26 11:08:53 2011 for Asterisk - the Open Source PBX by  doxygen 1.5.9