If we don't re-connect, it's an error.
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
index 40422df..d3fddbf 100644 (file)
@@ -1,10 +1,7 @@
 /*
- * rlm_ldap.c  LDAP authorization and authentication module.
- *
- *   This program is free software; you can redistribute it and/or modify
- *   it under the terms of the GNU General Public License as published by
- *   the Free Software Foundation; either version 2 of the License, or
- *   (at your option) any later version.
+ *   This program is is free software; you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License, version 2 if the
+ *   License as published by the Free Software Foundation.
  *
  *   This program is distributed in the hope that it will be useful,
  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
  *   You should have received a copy of the GNU General Public License
  *   along with this program; if not, write to the Free Software
  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
+ */
+/**
+ * $Id$
+ * @file rlm_ldap.c
+ * @brief LDAP authorization and authentication module.
  *
- *   Copyright 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,
- *            2009,2010,2011,1012 The FreeRADIUS Server Project.
- *
- *   Copyright 2012 Alan DeKok <aland@freeradius.org>
+ * @copyright 1999-2013 The FreeRADIUS Server Project.
+ * @copyright 2012 Alan DeKok <aland@freeradius.org>
+ * @copyright 2012-2013 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
  */
-
 #include <freeradius-devel/ident.h>
 RCSID("$Id$")
 
@@ -38,6 +39,18 @@ RCSID("$Id$")
 #define MAX_ATTR_STR_LEN       256
 #define MAX_FILTER_STR_LEN     1024
 
+#ifdef WITH_EDIR
+extern int nmasldap_get_password(LDAP *ld,char *objectDN, char *pwd, size_t *pwdSize);
+
+#endif
+
+typedef struct ldap_acct_section {
+       CONF_SECTION    *cs;
+       
+       const char *reference;
+} ldap_acct_section_t;
+
+
 typedef struct {
        CONF_SECTION    *cs;
        fr_connection_pool_t *pool;
@@ -54,19 +67,18 @@ typedef struct {
        int             chase_referrals;
        int             rebind;
 
-       int             ldap_debug; /* Debug flag for LDAP SDK */
+       int             ldap_debug; //!< Debug flag for the SDK.
 
-       const char      *xlat_name; /* name used to xlat */
+       const char      *xlat_name; //!< Instance name.
 
        int             expect_password;
        
        /*
         *      RADIUS attribute to LDAP attribute maps
         */
-       VALUE_PAIR_MAP  *user_map;      /* Applied to user object, and profiles */
-
-       int             do_xlat;
-
+       value_pair_map_t *user_map; //!< Attribute map applied to users and
+                                   //!< profiles.
+       
        /*
         *      Access related configuration
         */
@@ -83,9 +95,15 @@ typedef struct {
        /*
         *      Group checking.
         */
-       char           *groupname_attr;
-       char           *groupmemb_filt;
+       char            *groupname_attr;
+       char            *groupmemb_filter;
        char            *groupmemb_attr;
+       
+       /*
+        *      Accounting
+        */
+       ldap_acct_section_t *postauth;
+       ldap_acct_section_t *accounting;
 
        /*
         *      TLS items.  We should really normalize these with the
@@ -108,6 +126,13 @@ typedef struct {
        int             timeout;
        int             is_url;
 
+#ifdef WITH_EDIR
+       /*
+        *      eDir support
+        */
+       int             edir;
+       int             edir_autz;
+#endif
        /*
         *      For keep-alives.
         */
@@ -159,7 +184,8 @@ static CONF_PARSER attr_config[] = {
         offsetof(ldap_instance,positive_access_attr), NULL, "yes"},
 
        {"base_filter", PW_TYPE_STRING_PTR,
-        offsetof(ldap_instance,base_filter), NULL, "(objectclass=radiusprofile)"},
+        offsetof(ldap_instance,base_filter), NULL,
+        "(objectclass=radiusprofile)"},
        {"default_profile", PW_TYPE_STRING_PTR,
         offsetof(ldap_instance,default_profile), NULL, NULL},
        {"profile_attribute", PW_TYPE_STRING_PTR,
@@ -180,7 +206,9 @@ static CONF_PARSER group_config[] = {
        {"name_attribute", PW_TYPE_STRING_PTR,
         offsetof(ldap_instance,groupname_attr), NULL, "cn"},
        {"membership_filter", PW_TYPE_STRING_PTR,
-        offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
+        offsetof(ldap_instance,groupmemb_filter), NULL,
+        "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))"
+        "(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
        {"membership_attribute", PW_TYPE_STRING_PTR,
         offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
 
@@ -189,6 +217,15 @@ static CONF_PARSER group_config[] = {
 };
 
 /*
+ *     Reference for accounting updates
+ */
+static const CONF_PARSER acct_section_config[] = {
+       {"reference", PW_TYPE_STRING_PTR,
+         offsetof(ldap_acct_section_t, reference), NULL, "."},
+       {NULL, -1, 0, NULL, NULL}
+};
+
+/*
  *     Various options that don't belong in the main configuration.
  *
  *     Note that these overlap a bit with the connection pool code!
@@ -219,13 +256,16 @@ static CONF_PARSER option_config[] = {
         offsetof(ldap_instance,timelimit), NULL, "20"},
 
 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
-       {"idle", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_idle), NULL, "60"},
+       {"idle", PW_TYPE_INTEGER,
+        offsetof(ldap_instance,keepalive_idle), NULL, "60"},
 #endif
 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
-       {"probes", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_probes), NULL, "3"},
+       {"probes", PW_TYPE_INTEGER,
+        offsetof(ldap_instance,keepalive_probes), NULL, "3"},
 #endif
 #ifdef LDAP_OPT_ERROR_NUMBER
-       {"interval", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_interval), NULL, "30"},
+       {"interval", PW_TYPE_INTEGER, 
+        offsetof(ldap_instance,keepalive_interval), NULL, "30"},
 #endif
        { NULL, -1, 0, NULL, NULL }
 };
@@ -255,22 +295,31 @@ static const CONF_PARSER module_config[] = {
        {"expect_password", PW_TYPE_BOOLEAN,
         offsetof(ldap_instance,expect_password), NULL, "yes"},
         
+#ifdef WITH_EDIR
+       /* support for eDirectory Universal Password */
+       {"edir", PW_TYPE_BOOLEAN,
+        offsetof(ldap_instance,edir), NULL, NULL}, /* NULL defaults to "no" */
+
        /*
-        *      Terrible things which should be deleted.
+        * Attempt to bind with the Cleartext password we got from eDirectory
+        * Universal password for additional authorization checks.
         */
-       {"do_xlat", PW_TYPE_BOOLEAN,
-        offsetof(ldap_instance,do_xlat), NULL, "yes"},
+       {"edir_autz", PW_TYPE_BOOLEAN,
+        offsetof(ldap_instance,edir_autz), NULL, NULL}, /* NULL defaults to "no" */
+#endif
 
+       /*
+        *      Terrible things which should be deleted.
+        */
        { "profiles", PW_TYPE_SUBSECTION, 0, NULL, (const void *) attr_config },
 
        { "group", PW_TYPE_SUBSECTION, 0, NULL, (const void *) group_config },
 
-       { "options", PW_TYPE_SUBSECTION, 0, NULL, (const void *) option_config },
+       { "options", PW_TYPE_SUBSECTION, 0, NULL,
+        (const void *) option_config },
 
        { "tls", PW_TYPE_SUBSECTION, 0, NULL, (const void *) tls_config },
 
-       { "profiles", PW_TYPE_SUBSECTION, 0, NULL, (const void *) attr_config },
-
        {NULL, -1, 0, NULL, NULL}
 };
 
@@ -282,7 +331,7 @@ typedef struct ldap_conn {
 } LDAP_CONN;
 
 typedef struct xlat_attrs {
-       const VALUE_PAIR_MAP *maps;
+       const value_pair_map_t *maps;
        const char *attrs[MAX_ATTRMAP];
 } xlat_attrs_t;
 
@@ -291,112 +340,174 @@ typedef struct rlm_ldap_result {
        int     count;
 } rlm_ldap_result_t;
 
+typedef enum {
+       LDAP_PROC_SUCCESS = 0,
+       LDAP_PROC_ERROR = -1,
+       LDAP_PROC_RETRY = -2,
+       LDAP_PROC_REJECT = -3
+} ldap_rcode_t;
 
-#if LDAP_SET_REBIND_PROC_ARGS == 3
-/*
- *     Rebind && chase referral stuff
- */
-static int ldap_rebind(LDAP *handle, LDAP_CONST char *url,
-                      UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
-                      void *ctx )
+static ldap_rcode_t process_ldap_errno(ldap_instance *inst, LDAP_CONN **pconn,
+                             const char *operation)
 {
-       LDAP_CONN *conn = ctx;
+       int ldap_errno;
+       
+       ldap_get_option((*pconn)->handle, LDAP_OPT_ERROR_NUMBER,
+                       &ldap_errno);
+       switch (ldap_errno) {
+       case LDAP_SUCCESS:
+       case LDAP_NO_SUCH_OBJECT:
+               return LDAP_PROC_SUCCESS;
 
-       conn->referred = TRUE;
-       conn->rebound = TRUE;   /* not really, but oh well... */
-       rad_assert(handle == conn->handle);
+       case LDAP_INSUFFICIENT_ACCESS:
+               radlog(L_ERR, "rlm_ldap (%s): %s failed: Insufficient access. "
+                      "Check the identity and password configuration "
+                      "directives", inst->xlat_name, operation);
+               return LDAP_PROC_ERROR;
+               
+       case LDAP_TIMEOUT:
+               exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
+               radlog(L_ERR, "rlm_ldap (%s): %s failed: Timed out "
+                      "while waiting for server to respond", inst->xlat_name,
+                      operation);
+               return LDAP_PROC_ERROR;
+
+       case LDAP_FILTER_ERROR:
+               radlog(L_ERR, "rlm_ldap (%s): %s failed: Bad search "
+                      "filter", inst->xlat_name, operation);
+               return LDAP_PROC_ERROR;
+
+       case LDAP_TIMELIMIT_EXCEEDED:
+               exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
+               /* FALL-THROUGH */
+
+       case LDAP_BUSY:
+       case LDAP_UNAVAILABLE:
+               /*
+                *      Reconnect.  There's an issue with the socket
+                *      or LDAP server.
+                */
+               radlog(L_ERR, "rlm_ldap (%s): %s failed: %s",
+                      inst->xlat_name, operation, ldap_err2string(ldap_errno));
+       case LDAP_SERVER_DOWN:
+               return LDAP_PROC_RETRY;
+               
+       case LDAP_INVALID_CREDENTIALS:
+       case LDAP_CONSTRAINT_VIOLATION:
+               return LDAP_PROC_REJECT;
 
-       DEBUG("  [%s] rebind to URL %s", conn->inst->xlat_name, url);
-       return ldap_bind_s(handle, conn->inst->login, conn->inst->password,
-                          LDAP_AUTH_SIMPLE);
+       case LDAP_OPERATIONS_ERROR:
+               DEBUGW("Please set 'chase_referrals=yes' and 'rebind=yes'");
+               DEBUGW("See the ldap module configuration for details");
+               /* FALL-THROUGH */
+
+       default:
+               radlog(L_ERR, "rlm_ldap (%s): %s failed: %s",
+                      inst->xlat_name, operation, ldap_err2string(ldap_errno));
+               return LDAP_PROC_ERROR;
+       }
 }
-#endif
+
 
 static int ldap_bind_wrapper(LDAP_CONN **pconn, const char *user,
-                            const char *password,
-                            const char **perror_str, int do_rebind)
+                            const char *password, int retry)
 {
-       int             rcode, ldap_errno;
-       int             module_rcode = RLM_MODULE_FAIL;
-       int             reconnect = FALSE;
-       const char      *error_string;
+       int             rcode, msg_id;
+       int             module_rcode = RLM_MODULE_OK;
        LDAP_CONN       *conn = *pconn;
        ldap_instance   *inst = conn->inst;
        LDAPMessage     *result = NULL;
        struct timeval tv;
 
-redo:
-       ldap_errno = ldap_bind(conn->handle, user, password, LDAP_AUTH_SIMPLE);
-       if (ldap_errno < 0) {
-       get_error:
-               ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
-                               &ldap_errno);
-               error_string = ldap_err2string(ldap_errno);
+retry:
+       msg_id = ldap_bind(conn->handle, user, password, LDAP_AUTH_SIMPLE);
+       if (msg_id < 0) goto get_error;
 
-               if (do_rebind && !reconnect) {
-                       conn = fr_connection_reconnect(inst->pool, conn);
-                       *pconn = conn;
-                       if (!conn) return RLM_MODULE_FAIL;
-                       goto redo;
-               }
+       DEBUG3("rlm_ldap (%s): Waiting for bind result...", inst->xlat_name);
 
-       print_error:
-               if (perror_str) *perror_str = error_string;
+       tv.tv_sec = inst->timeout;
+       tv.tv_usec = 0;
 
+       rcode = ldap_result(conn->handle, msg_id, 1, &tv, &result);
+       ldap_msgfree(result);
+       if (rcode <= 0) {
+get_error:
+               switch (process_ldap_errno(inst, &conn, "Bind"))
+               {
+                       case LDAP_PROC_SUCCESS:
+                               break;
+                       case LDAP_PROC_REJECT:
+                               module_rcode = RLM_MODULE_REJECT;
+                               goto error;
+                       case LDAP_PROC_ERROR:
+                               module_rcode = RLM_MODULE_FAIL;
+error:
 #ifdef HAVE_LDAP_INITIALIZE
-               if (inst->is_url) {
-                       radlog(L_ERR, "  [%s] %s bind to %s failed: %s",
-                              inst->xlat_name, user,
-                              inst->server, error_string);
-               } else
+                               if (inst->is_url) {
+                                       radlog(L_ERR, "rlm_ldap (%s): bind "
+                                              "with %s to %s failed",
+                                              inst->xlat_name, user,
+                                              inst->server);
+                               } else
 #endif
-               {
-                       radlog(L_ERR, "  [%s] %s bind to %s:%d failed: %s",
-                              inst->xlat_name, user,
-                              inst->server, inst->port,
-                              error_string);
-               }
-
-               return module_rcode; /* caller closes the connection */
+                               {
+                                       radlog(L_ERR, "rlm_ldap (%s): bind "
+                                              "with %s to %s:%d failed",
+                                              inst->xlat_name, user,
+                                              inst->server, inst->port);
+                               }
+       
+                               break;
+                       case LDAP_PROC_RETRY:
+                               if (retry) {
+                                       *pconn = fr_connection_reconnect(inst->pool, *pconn);
+                                       if (*pconn) goto retry;
+                               }
+                               
+                               module_rcode = RLM_MODULE_FAIL;
+                               break;
+                       default:
+                               rad_assert(0);
+               }       
        }
 
-       DEBUG3("  [%s] waiting for bind result ...", inst->xlat_name);
-
-       tv.tv_sec = inst->timeout;
-       tv.tv_usec = 0;
-       rcode = ldap_result(conn->handle, ldap_errno, 1, &tv, &result);
-       if (rcode < 0) goto get_error;
+       return module_rcode; /* caller closes the connection */
+}
 
-       if (rcode == 0) {
-               error_string = "timeout";
-               goto print_error;
-       }
+#if LDAP_SET_REBIND_PROC_ARGS == 3
+/*
+ *     Rebind && chase referral stuff
+ */
+static int ldap_rebind(LDAP *handle, LDAP_CONST char *url,
+                      UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
+                      void *ctx )
+{
+       int rcode, ldap_errno;
+       LDAP_CONN *conn = ctx;
 
-       ldap_errno = ldap_result2error(conn->handle, result, 1);
-       switch (ldap_errno) {
-       case LDAP_SUCCESS:
-               break;
+       conn->referred = TRUE;
+       conn->rebound = TRUE;   /* not really, but oh well... */
+       rad_assert(handle == conn->handle);
 
-       case LDAP_INVALID_CREDENTIALS:
-       case LDAP_CONSTRAINT_VIOLATION:
-               rcode = RLM_MODULE_REJECT;
-               /* FALL-THROUGH */
+       DEBUG("rlm_ldap (%s): Rebinding to URL %s", conn->inst->xlat_name, url);
+       
 
-       default:
-               goto get_error;
+       rcode = ldap_bind_wrapper(&conn, conn->inst->login,
+                                 conn->inst->password, FALSE);
+       
+       if (rcode == RLM_MODULE_OK) {
+               return LDAP_SUCCESS;
        }
-
-       return RLM_MODULE_OK;
+       
+       ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
+                       
+       return ldap_errno;
 }
+#endif
 
-/*************************************************************************
- *
- *     Function: ldap_conn_create
- *
- *     Purpose: Create and return a new connection
- *     This function is probably too big.
- *
- *************************************************************************/
+/** Create and return a new connection
+ * This function is probably too big.
+ */
 static void *ldap_conn_create(void *ctx)
 {
        int module_rcode;
@@ -405,28 +516,29 @@ static void *ldap_conn_create(void *ctx)
        ldap_instance *inst = ctx;
        LDAP *handle = NULL;
        LDAP_CONN *conn = NULL;
-       const char *error;
 
 #ifdef HAVE_LDAP_INITIALIZE
        if (inst->is_url) {
-               DEBUG("  [%s] Connect to %s", inst->xlat_name, inst->server);
+               DEBUG("rlm_ldap (%s): Connecting to %s", inst->xlat_name,
+                     inst->server);
 
                ldap_errno = ldap_initialize(&handle, inst->server);
-
                if (ldap_errno != LDAP_SUCCESS) {
-                       radlog(L_ERR, "  [%s] ldap_initialize() failed: %s",
+                       radlog(L_ERR, "rlm_ldap (%s): ldap_initialize() "
+                              "failed: %s",
                               inst->xlat_name, ldap_err2string(ldap_errno));
                        goto conn_fail;
                }
        } else
 #endif
        {
-               DEBUG("  [%s] Connect to %s:%d", inst->xlat_name,
+               DEBUG("rlm_ldap (%s): Connecting to %s:%d", inst->xlat_name,
                      inst->server, inst->port);
 
                handle = ldap_init(inst->server, inst->port);
                if (!handle) {
-                       radlog(L_ERR, "  [%s] ldap_init() failed", inst->xlat_name);
+                       radlog(L_ERR, "rlm_ldap (%s): ldap_init() failed",
+                              inst->xlat_name);
                conn_fail:
                        if (handle) ldap_unbind_s(handle);
                        return NULL;
@@ -438,14 +550,16 @@ static void *ldap_conn_create(void *ctx)
         *
         *      Set a bunch of LDAP options, using common code.
         */
-
-#define do_ldap_option(_option, _name, _value) if (ldap_set_option(handle, _option, _value) != LDAP_OPT_SUCCESS) { \
+#define do_ldap_option(_option, _name, _value) \
+       if (ldap_set_option(handle, _option, _value) != LDAP_OPT_SUCCESS) { \
                ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno); \
-               radlog(L_ERR, "  [%s] Could not set %s: %s", inst->xlat_name, _name, ldap_err2string(ldap_errno)); \
+               radlog(L_ERR, "rlm_ldap (%s): Could not set %s: %s", \
+                      inst->xlat_name, _name, ldap_err2string(ldap_errno)); \
        }
                
        if (inst->ldap_debug) {
-               do_ldap_option(LDAP_OPT_DEBUG_LEVEL, "ldap_debug", &(inst->ldap_debug));
+               do_ldap_option(LDAP_OPT_DEBUG_LEVEL, "ldap_debug",
+                              &(inst->ldap_debug));
        }
 
        /*
@@ -454,15 +568,19 @@ static void *ldap_conn_create(void *ctx)
         */
        if (inst->chase_referrals != 2) {
                if (inst->chase_referrals) {
-                       do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_ON);
+                       do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals",
+                                      LDAP_OPT_ON);
                        
-#if LDAP_SET_REBIND_PROC_ARGS == 3
                        if (inst->rebind == 1) {
+#if LDAP_SET_REBIND_PROC_ARGS == 3
                                ldap_set_rebind_proc(handle, ldap_rebind, inst);
-                       }
+#else
+                               DEBUGW("The flag 'rebind = yes' is not supported by the system LDAP library.  Ignoring.");
 #endif
+                       }
                } else {
-                       do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals", LDAP_OPT_OFF);
+                       do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals",
+                                      LDAP_OPT_OFF);
                }
        }
 
@@ -473,18 +591,22 @@ static void *ldap_conn_create(void *ctx)
        do_ldap_option(LDAP_OPT_TIMELIMIT, "timelimit", &(inst->timelimit));
 
        ldap_version = LDAP_VERSION3;
-       do_ldap_option(LDAP_OPT_PROTOCOL_VERSION, "ldap_version", &ldap_version);
+       do_ldap_option(LDAP_OPT_PROTOCOL_VERSION, "ldap_version",
+                      &ldap_version);
 
 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
-       do_ldap_option(LDAP_OPT_X_KEEPALIVE_IDLE, "keepalive idle", &(inst->keepalive_idle));
+       do_ldap_option(LDAP_OPT_X_KEEPALIVE_IDLE, "keepalive idle",
+                      &(inst->keepalive_idle));
 #endif
 
 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
-       do_ldap_option(LDAP_OPT_X_KEEPALIVE_PROBES, "keepalive probes", &(inst->keepalive_probes));
+       do_ldap_option(LDAP_OPT_X_KEEPALIVE_PROBES, "keepalive probes",
+                      &(inst->keepalive_probes));
 #endif
 
 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
-       do_ldap_option(LDAP_OPT_X_KEEPALIVE_INTERVAL, "keepalive interval", &(inst->keepalive_interval));
+       do_ldap_option(LDAP_OPT_X_KEEPALIVE_INTERVAL, "keepalive interval",
+                      &(inst->keepalive_interval));
 #endif
 
 #ifdef HAVE_LDAP_START_TLS
@@ -495,7 +617,8 @@ static void *ldap_conn_create(void *ctx)
                do_ldap_option(LDAP_OPT_X_TLS, "tls_mode", &(inst->tls_mode));
        }
 
-#define maybe_ldap_option(_option, _name, _value) if (_value) do_ldap_option(_option, _name, _value)
+#define maybe_ldap_option(_option, _name, _value) \
+       if (_value) do_ldap_option(_option, _name, _value)
 
        maybe_ldap_option(LDAP_OPT_X_TLS_CACERTFILE,
                          "cacertfile", inst->tls_cacertfile);
@@ -506,7 +629,7 @@ static void *ldap_conn_create(void *ctx)
        if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
                                (inst->tls_require_cert)) != LDAP_OPT_SUCCESS) {
                ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
-               radlog(L_ERR, "  [%s] could not set ", 
+               radlog(L_ERR, "rlm_ldap (%s): could not set "
                       "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s: %s",
                       inst->xlat_name, 
                       inst->tls_require_cert,
@@ -529,7 +652,7 @@ static void *ldap_conn_create(void *ctx)
                if (ldap_errno != LDAP_SUCCESS) {
                        ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER,
                                        &ldap_errno);
-                       radlog(L_ERR, "  [%s] could not start TLS: %s",
+                       radlog(L_ERR, "rlm_ldap (%s): could not start TLS: %s",
                               inst->xlat_name,
                               ldap_err2string(ldap_errno));
                        goto conn_fail;
@@ -537,21 +660,15 @@ static void *ldap_conn_create(void *ctx)
        }
 #endif /* HAVE_LDAP_START_TLS */
 
-       conn = rad_malloc(sizeof(*conn));
+       conn = talloc(NULL, LDAP_CONN);
        conn->inst = inst;
        conn->handle = handle;
        conn->rebound = FALSE;
        conn->referred = FALSE;
 
        module_rcode = ldap_bind_wrapper(&conn, inst->login, inst->password,
-                                        &error, FALSE);
+                                        FALSE);
        if (module_rcode != RLM_MODULE_OK) {
-               radlog(L_ERR, "  [%s] Failed binding to LDAP server: %s",
-                      inst->xlat_name, error);
-
-               /*
-                *      FIXME: print "check config, morians!
-                */
                goto conn_fail;
        }
 
@@ -559,38 +676,30 @@ static void *ldap_conn_create(void *ctx)
 }
 
 
-/*************************************************************************
- *
- *     Function: ldap_conn_delete
+/** Close and delete a connection
  *
- *     Purpose: Close and delete a connection
- *
- *************************************************************************/
+ */
 static int ldap_conn_delete(UNUSED void *ctx, void *connection)
 {
        LDAP_CONN *conn = connection;
 
        ldap_unbind_s(conn->handle);
-       free(conn);
+       talloc_free(conn);
 
        return 0;
 }
 
 
-/*************************************************************************
- *
- *     Function: ldap_get_socket
- *
- *     Purpose: Gets an LDAP socket from the connection pool
+/** Gets an LDAP socket from the connection pool
  *
- *************************************************************************/
+ */
 static LDAP_CONN *ldap_get_socket(ldap_instance *inst)
 {
        LDAP_CONN *conn;
 
        conn = fr_connection_get(inst->pool);
        if (!conn) {
-               radlog(L_ERR, "  [%s] All ldap connections are in use",
+               radlog(L_ERR, "rlm_ldap (%s): all ldap connections are in use",
                       inst->xlat_name);
                return NULL;
        }
@@ -598,13 +707,9 @@ static LDAP_CONN *ldap_get_socket(ldap_instance *inst)
        return conn;
 }
 
-/*************************************************************************
- *
- *     Function: ldap_release_socket
+/** Frees an LDAP socket back to the connection pool
  *
- *     Purpose: Frees an LDAP socket back to the connection pool
- *
- *************************************************************************/
+ */
 static void ldap_release_socket(ldap_instance *inst, LDAP_CONN *conn)
 {
        /*
@@ -633,13 +738,9 @@ static void ldap_release_socket(ldap_instance *inst, LDAP_CONN *conn)
 }
 
 
-/*************************************************************************
+/* Converts "bad" strings into ones which are safe for LDAP
  *
- *     Function: ldap_escape_func
- *
- *     Purpose: Converts "bad" strings into ones which are safe for LDAP
- *
- *************************************************************************/
+ */
 static size_t ldap_escape_func(UNUSED REQUEST *request, char *out,
                               size_t outlen, const char *in, UNUSED void *arg)
 {
@@ -688,21 +789,16 @@ static size_t ldap_escape_func(UNUSED REQUEST *request, char *out,
        return len;
 }
 
-/*************************************************************************
- *
- *     Function: perform_search
+/** Do a search and get a response
  *
- *     Purpose: Do a search and get a response
- *
- *************************************************************************/
-static int perform_search(ldap_instance *inst, LDAP_CONN **pconn,
-                         const char *search_basedn, int scope,
-                         const char *filter, const char * const *attrs,
-                         LDAPMessage **presult)
+ */
+static int perform_search(ldap_instance *inst, REQUEST *request,
+                         LDAP_CONN **pconn, const char *search_basedn,
+                         int scope, const char *filter, 
+                         const char * const *attrs, LDAPMessage **presult)
 {
        int             ldap_errno;
-       int             reconnect = FALSE;
-       LDAP_CONN       *conn = *pconn;
+       int             count = 0;
        struct timeval  tv;
 
        /*
@@ -717,110 +813,66 @@ static int perform_search(ldap_instance *inst, LDAP_CONN **pconn,
        /*
         *      Do all searches as the default admin user.
         */
-       if (conn->rebound) {
-               ldap_errno = ldap_bind_wrapper(pconn,
-                                              inst->login, inst->password,
-                                              NULL, TRUE);
+       if ((*pconn)->rebound) {
+               ldap_errno = ldap_bind_wrapper(pconn, inst->login,
+                                              inst->password, TRUE);
                if (ldap_errno != RLM_MODULE_OK) {
                        return -1;
                }
 
-               rad_assert(*pconn != NULL);
-               conn = *pconn;
-               conn->rebound = FALSE;
+               rad_assert(*pconn);
+               (*pconn)->rebound = FALSE;
        }
 
        tv.tv_sec = inst->timeout;
        tv.tv_usec = 0;
-       DEBUG2("  [%s] Performing search in '%s' with filter '%s'", inst->xlat_name, 
-              search_basedn ? search_basedn : "(null)" , filter);
+       RDEBUG2("Performing search in '%s' with filter '%s'",
+               search_basedn ? search_basedn : "(null)" ,
+               filter);
 
 retry:
-       ldap_errno = ldap_search_ext_s(conn->handle, search_basedn, scope,
+       ldap_errno = ldap_search_ext_s((*pconn)->handle, search_basedn, scope,
                                       filter, search_attrs, 0, NULL, NULL,
                                       &tv, 0, presult);
-       switch (ldap_errno) {
-       case LDAP_SUCCESS:
-       case LDAP_NO_SUCH_OBJECT:
-               break;
-
-       case LDAP_SERVER_DOWN:
-       do_reconnect:
-               ldap_msgfree(*presult);
-
-               if (reconnect) return -1;
-               reconnect = TRUE;
-
-               conn = fr_connection_reconnect(inst->pool, conn);
-               *pconn = conn;  /* tell the caller we have a new connection */
-               if (!conn) return -1;
-               goto retry;
-
-       case LDAP_INSUFFICIENT_ACCESS:
-               radlog(L_ERR, "  [%s] ldap_search() failed: Insufficient access. Check the identity and password configuration directives.", inst->xlat_name);
-               ldap_msgfree(*presult);
-               return -1;
-
-       case LDAP_TIMEOUT:
-               exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
-               radlog(L_ERR, "  [%s] ldap_search() failed: Timed out while waiting for server to respond. Please increase the timeout.", inst->xlat_name);
-               ldap_msgfree(*presult);
-               return -1;
-
-       case LDAP_FILTER_ERROR:
-               radlog(L_ERR, "  [%s] ldap_search() failed: Bad search filter: %s", inst->xlat_name,filter);
-               ldap_msgfree(*presult);
-               return -1;
-
-       case LDAP_TIMELIMIT_EXCEEDED:
-               exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
-
-       case LDAP_BUSY:
-       case LDAP_UNAVAILABLE:
-               /*
-                *      Reconnect.  There's an issue with the socket
-                *      or LDAP server.
-                */
-               ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
-                               &ldap_errno);
-               radlog(L_ERR, "  [%s] ldap_search() failed: %s",
-                      inst->xlat_name, ldap_err2string(ldap_errno));
-               goto do_reconnect;
-
-       default:
-               ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
-                               &ldap_errno);
-               radlog(L_ERR, "  [%s] ldap_search() failed: %s",
-                      inst->xlat_name, ldap_err2string(ldap_errno));
+       if (ldap_errno != LDAP_SUCCESS) {
                ldap_msgfree(*presult);
-               return -1;
+               switch (process_ldap_errno(inst, pconn, "Search"))
+               {
+                       case LDAP_PROC_SUCCESS:
+                               break;
+                       case LDAP_PROC_REJECT:
+                       case LDAP_PROC_ERROR:
+                               return -1;
+                       case LDAP_PROC_RETRY:
+                               *pconn = fr_connection_reconnect(inst->pool, *pconn);
+                               if (*pconn) goto retry;
+                               return -1;
+                       default:
+                               rad_assert(0);
+               }
        }
-
-       ldap_errno = ldap_count_entries(conn->handle, *presult);
-       if (ldap_errno == 0) {
+               
+       count = ldap_count_entries((*pconn)->handle, *presult);
+       if (count == 0) {
                ldap_msgfree(*presult);
-               DEBUG("  [%s] object not found", inst->xlat_name);
+               RDEBUG("Search returned no results");
+               
                return -2;
        }
 
-       if (ldap_errno != 1) {
+       if (count != 1) {
                ldap_msgfree(*presult);
-               DEBUG("  [%s] got ambiguous search result (%d results)",
-                     inst->xlat_name, ldap_errno);
+               RDEBUG("Got ambiguous search result (%d results)", count);
+                     
                return -2;
        }
 
        return 0;
 }
 
-/*************************************************************************
- *
- *     Function: ldap_xlat
- *
- *     Purpose: Expand an LDAP URL into a query, and return a string
- *             result from that query.
+/** Expand an LDAP URL into a query, and return a string result from that query.
  *
- *************************************************************************/
+ */
 static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
                        char *out, size_t freespace)
 {
@@ -832,13 +884,17 @@ static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
        LDAPMessage *entry = NULL;
        char **vals;
        LDAP_CONN *conn;
+       int ldap_errno;
        const char *url;
        const char **attrs;
        char buffer[MAX_FILTER_STR_LEN];
 
        if (strchr(fmt, '%') != NULL) {
-               if (!radius_xlat(buffer, sizeof(buffer), fmt, request, ldap_escape_func, NULL)) {
-                       radlog (L_ERR, "  [%s] Unable to create LDAP URL.", inst->xlat_name);
+               if (!radius_xlat(buffer, sizeof(buffer), fmt, request,
+                                ldap_escape_func, NULL)) {
+                       radlog(L_ERR,
+                              "rlm_ldap (%s): Unable to create LDAP URL", 
+                              inst->xlat_name);
                        return 0;
                }
                url = buffer;
@@ -847,13 +903,14 @@ static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
        }
 
        if (!ldap_is_ldap_url(url)) {
-               radlog (L_ERR, "  [%s] String passed does not look like an LDAP URL.",
-                       inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): String passed does not look "
+                      "like an LDAP URL", inst->xlat_name);
                return 0;
        }
 
        if (ldap_url_parse(url, &ldap_url)){
-               radlog (L_ERR, "  [%s] LDAP URL parse failed.", inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Parsing LDAP URL failed",
+                      inst->xlat_name);
                return 0;
        }
 
@@ -861,17 +918,24 @@ static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
         *      Nothing, empty string, "*" string, or got 2 things, die.
         */
        if (!ldap_url->lud_attrs || !ldap_url->lud_attrs[0] ||
-           !*ldap_url->lud_attrs[0] || (strcmp(ldap_url->lud_attrs[0], "*") == 0) ||
+           !*ldap_url->lud_attrs[0] ||
+           (strcmp(ldap_url->lud_attrs[0], "*") == 0) ||
            ldap_url->lud_attrs[1]) {
-               radlog (L_ERR, "  [%s] Invalid Attribute(s) request.",
-                       inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Bad attributes list in LDAP "
+                      "URL. URL must specify exactly one attribute to "
+                      "retrieve",
+                      inst->xlat_name);
+                      
                goto free_urldesc;
        }
 
        if (ldap_url->lud_host &&
-           ((strncmp(inst->server, ldap_url->lud_host, strlen(inst->server)) != 0) ||
+           ((strncmp(inst->server, ldap_url->lud_host,
+                     strlen(inst->server)) != 0) ||
             (ldap_url->lud_port != inst->port))) {
-               DEBUG("  [%s] Requested server/port is .", inst->xlat_name);
+               RDEBUG("Requested server/port is \"%s:%i\"", ldap_url->lud_host,
+                      inst->port);
+               
                goto free_urldesc;
        }
 
@@ -880,26 +944,32 @@ static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
 
        memcpy(&attrs, &ldap_url->lud_attrs, sizeof(attrs));
        
-       rcode = perform_search(inst, &conn, ldap_url->lud_dn, ldap_url->lud_scope,
-                              ldap_url->lud_filter, attrs, &result);
+       rcode = perform_search(inst, request, &conn, ldap_url->lud_dn, 
+                              ldap_url->lud_scope, ldap_url->lud_filter, attrs,
+                              &result);
        if (rcode < 0) {
                if (rcode == -2) {
-                       DEBUG("  [%s] Search returned not found", inst->xlat_name);
+                       RDEBUG("Search returned not found", inst->xlat_name);
                        goto free_socket;
                }
-               DEBUG("  [%s] Search returned error", inst->xlat_name);
+
                goto free_socket;
        }
 
        entry = ldap_first_entry(conn->handle, result);
        if (!entry) {
-               DEBUG("  [%s] ldap_first_entry() failed", inst->xlat_name);
+               ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
                goto free_result;
        }
 
        vals = ldap_get_values(conn->handle, entry, ldap_url->lud_attrs[0]);
        if (!vals) {
-               DEBUG("  [%s] ldap_get_values failed", inst->xlat_name);
+               RDEBUG("No \"%s\" attributes found in specified object",
+                      inst->xlat_name, ldap_url->lud_attrs[0]);
                goto free_result;
        }
 
@@ -924,38 +994,45 @@ free_urldesc:
 }
 
 
-static char *get_userdn(LDAP_CONN **pconn, REQUEST *request, int *module_rcode)
+static char *get_userdn(LDAP_CONN **pconn, REQUEST *request,
+                       rlm_rcode_t *module_rcode)
 {
        int             rcode;
        VALUE_PAIR      *vp;
        ldap_instance   *inst = (*pconn)->inst;
        LDAPMessage     *result, *entry;
+       int             ldap_errno;
        static char     firstattr[] = "uid";
        char            *user_dn;
        const char      *attrs[] = {firstattr, NULL};
-       char        filter[MAX_FILTER_STR_LEN]; 
-       char        basedn[MAX_FILTER_STR_LEN]; 
+       char            filter[MAX_FILTER_STR_LEN];     
+       char            basedn[MAX_FILTER_STR_LEN];     
 
        *module_rcode = RLM_MODULE_FAIL;
 
-       vp = pairfind(request->config_items, PW_LDAP_USERDN, 0);
-       if (vp) return vp->vp_strvalue;
-
+       vp = pairfind(request->config_items, PW_LDAP_USERDN, 0, TAG_ANY);
+       if (vp) {
+               *module_rcode = RLM_MODULE_OK;
+               return vp->vp_strvalue;
+       }
+       
        if (!radius_xlat(filter, sizeof(filter), inst->filter,
                         request, ldap_escape_func, NULL)) {
-               radlog(L_ERR, "  [%s] unable to create filter.", inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Unable to create filter",
+                      inst->xlat_name);
                *module_rcode = RLM_MODULE_INVALID;
                return NULL;
        }
 
        if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
                         request, ldap_escape_func, NULL)) {
-               radlog(L_ERR, "  [%s] unable to create basedn.", inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Unable to create basedn",
+                      inst->xlat_name);
                *module_rcode = RLM_MODULE_INVALID;
                return NULL;
        }
 
-       rcode = perform_search(inst, pconn, basedn, LDAP_SCOPE_SUBTREE,
+       rcode = perform_search(inst, request, pconn, basedn, LDAP_SCOPE_SUBTREE,
                               filter, attrs, &result);
        if (rcode < 0) {
                if (rcode == -2) {
@@ -966,11 +1043,22 @@ static char *get_userdn(LDAP_CONN **pconn, REQUEST *request, int *module_rcode)
        }
 
        if ((entry = ldap_first_entry((*pconn)->handle, result)) == NULL) {
+               ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
                ldap_msgfree(result);
                return NULL;
        }
 
        if ((user_dn = ldap_get_dn((*pconn)->handle, entry)) == NULL) {
+               ldap_get_option((*pconn)->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): ldap_get_dn() failed: %s",
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
+                      
                ldap_msgfree(result);
                return NULL;
        }
@@ -982,6 +1070,8 @@ static char *get_userdn(LDAP_CONN **pconn, REQUEST *request, int *module_rcode)
                return NULL;
        }
        
+       *module_rcode = RLM_MODULE_OK;
+       
        pairadd(&request->config_items, vp);
        ldap_memfree(user_dn);
        ldap_msgfree(result);
@@ -990,33 +1080,36 @@ static char *get_userdn(LDAP_CONN **pconn, REQUEST *request, int *module_rcode)
 }
 
 
-/*****************************************************************************
- *
- *     Perform LDAP-Group comparison checking
+/** Perform LDAP-Group comparison checking
  *
- *****************************************************************************/
+ */
 static int ldap_groupcmp(void *instance, REQUEST *request,
                         UNUSED VALUE_PAIR *thing, VALUE_PAIR *check,
                         UNUSED VALUE_PAIR *check_pairs,
                         UNUSED VALUE_PAIR **reply_pairs)
 {
        ldap_instance   *inst = instance;
-       int          i, rcode, found;
+       int             i, rcode, found;
+       rlm_rcode_t     module_rcode;
        LDAPMessage     *result = NULL;
        LDAPMessage     *entry = NULL;
+       int             ldap_errno;
+       int             check_is_dn = FALSE, value_is_dn = FALSE;
        static char     firstattr[] = "dn";
        const char      *attrs[] = {firstattr, NULL};
        char            **vals;
        const char      *group_attrs[] = {inst->groupmemb_attr, NULL};
        LDAP_CONN       *conn;
        char            *user_dn;
-       int             module_rcode;
+
        char            gr_filter[MAX_FILTER_STR_LEN];
        char            filter[MAX_FILTER_STR_LEN];
        char            basedn[MAX_FILTER_STR_LEN];
 
+       RDEBUG("Searching for user in group \"%s\"", check->vp_strvalue);
+
        if (check->length == 0) {
-               RDEBUG("Cannot do comparison: group name is empty");
+               RDEBUG("Cannot do comparison (group name is empty)");
                return 1;
        }
 
@@ -1032,21 +1125,24 @@ static int ldap_groupcmp(void *instance, REQUEST *request,
                return 1;
        }
 
-       if (!inst->groupmemb_filt) goto check_attr;
+       if (!inst->groupmemb_filter) goto check_attr;
 
-       if (!radius_xlat(filter, sizeof(filter),
-                        inst->groupmemb_filt, request, ldap_escape_func, NULL)) {
-               RDEBUG("Failed creating group filter");
+       if (!radius_xlat(gr_filter, sizeof(gr_filter),
+                        inst->groupmemb_filter, request, ldap_escape_func,
+                        NULL)) {
+               radlog(L_ERR, "rlm_ldap (%s): Failed creating group filter",
+                      inst->xlat_name);
                return 1;
        }
 
        /*
         *      If it's a DN, use that.
         */
-       if (strchr(check->vp_strvalue,',') != NULL) {
+       check_is_dn = strchr(check->vp_strvalue,',') == NULL ? FALSE : TRUE;
+       
+       if (check_is_dn) {
                strlcpy(filter, gr_filter, sizeof(filter));
-               strlcpy(basedn, check->vp_strvalue, sizeof(basedn));
-               
+               strlcpy(basedn, check->vp_strvalue, sizeof(basedn));    
        } else {
                snprintf(filter, sizeof(filter), "(&(%s=%s)%s)",
                         inst->groupname_attr,
@@ -1057,24 +1153,25 @@ static int ldap_groupcmp(void *instance, REQUEST *request,
                 */
                if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
                                 request, ldap_escape_func, NULL)) {
-                       radlog(L_ERR, "  [%s] unable to create basedn.\n",
+                       radlog(L_ERR, "rlm_ldap (%s): Failed creating basedn",
                               inst->xlat_name);
                        return 1;
                }
        }
 
-       rcode = perform_search(inst, &conn, basedn, LDAP_SCOPE_SUBTREE,
+       rcode = perform_search(inst, request, &conn, basedn, LDAP_SCOPE_SUBTREE,
                               filter, attrs, &result);
        if (rcode == 0) {
                ldap_release_socket(inst, conn);
                ldap_msgfree(result);
-               RDEBUG("User found in group %s", check->vp_strvalue);
+                       
+               RDEBUG("User found in group object");
+               
                return 0;
        }
 
        if (rcode == -1) {
                ldap_release_socket(inst, conn);
-               RDEBUG("Failed performing search");
                return 1;
        }
 
@@ -1087,25 +1184,36 @@ static int ldap_groupcmp(void *instance, REQUEST *request,
         */
        if (!inst->groupmemb_attr) {
                ldap_release_socket(inst, conn);
-               RDEBUG("Group %s was not found, or user is not a member",
+               RDEBUG("Group object \"%s\" not found, or user is not a member",
                       check->vp_strvalue);
                return 1;
        }
 
 check_attr:
+       RDEBUG2("Checking user object membership (%s) attributes",
+               inst->groupmemb_attr);
+
        snprintf(filter ,sizeof(filter), "(objectclass=*)");
 
-       rcode = perform_search(inst, &conn, user_dn, LDAP_SCOPE_BASE,
+       rcode = perform_search(inst, request, &conn, user_dn, LDAP_SCOPE_BASE,
                               filter, group_attrs, &result);
        if (rcode < 0) {
-               RDEBUG("Search failed for group attrs");
+               if (rcode == -2) {
+                       RDEBUG("Can't check membership attributes, user object "
+                              "not found");
+               }
                ldap_release_socket(inst, conn);
                return 1;
        }
 
        entry = ldap_first_entry(conn->handle, result);
        if (!entry) {
-               RDEBUG("First entry failed for group attrs");
+               ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
+                              
                ldap_release_socket(inst, conn);
                ldap_msgfree(result);
                return 1;
@@ -1113,7 +1221,7 @@ check_attr:
 
        vals = ldap_get_values(conn->handle, entry, inst->groupmemb_attr);
        if (!vals) {
-               RDEBUG("Get values failed for group attrs");
+               RDEBUG("No group membership attribute(s) found in user object");
                ldap_release_socket(inst, conn);
                ldap_msgfree(result);
                return 1;
@@ -1124,171 +1232,248 @@ check_attr:
         *      looking for a match.
         */
        found = FALSE;
-       for (i = 0; i < ldap_count_values(vals); i++){
+       for (i = 0; i < ldap_count_values(vals); i++) {
                LDAPMessage *gr_result = NULL;
+               
+               value_is_dn = strchr(vals[i], ',') == NULL ? FALSE : TRUE;
+               
+               RDEBUG2("Processing group membership value \"%s\"", vals[i]);
 
-               if (strcmp(vals[i], check->vp_strvalue) == 0){
-                       found = TRUE;
-                       break;
+               /*
+                *      Both literal group names, do case sensitive comparison
+                */
+               if (!check_is_dn && !value_is_dn) {
+                       if (strcmp(vals[i], check->vp_strvalue) == 0){
+                               RDEBUG("User found (membership value matches "
+                                      "check value)");
+                              
+                               found = TRUE;
+                               break;
+                       }
+                       
+                       continue;
+               }
+
+               /*
+                *      Both DNs, do case insensitive comparison
+                */
+               if (check_is_dn && value_is_dn) {
+                       if (strcasecmp(vals[i], check->vp_strvalue) == 0){
+                               RDEBUG("User found (membership DN matches "
+                                      "check DN)");
+                              
+                               found = TRUE;
+                               break;
+                       }
+                       
+                       continue;
                }
+               
+               /*
+                *      If the value is not a DN, or the check item is a DN
+                *      there's nothing more we can do.
+                */
+               if (!value_is_dn && check_is_dn) continue;
 
                /*
-                *      The group isn't a DN: ignore it.
+                *      We have a value which is a DN, and a check item which
+                *      specifies the name of a group, search using the value
+                *      DN for the group, and see if it has a groupname_attr
+                *      which matches our check val.
                 */
-               if (strchr(vals[i], ',') == NULL) continue;
+               RDEBUG2("Searching with membership DN and group name");
 
-               /* This looks like a DN.  Do tons more work. */
                snprintf(filter,sizeof(filter), "(%s=%s)",
                         inst->groupname_attr, check->vp_strvalue);
 
-               rcode = perform_search(inst, &conn, vals[i], LDAP_SCOPE_BASE,
-                                      filter, attrs, &gr_result);
-               if (rcode == -1) {
-                       RDEBUG("Failed doing group search");
-                       ldap_value_free(vals);
+               rcode = perform_search(inst, request, &conn, vals[i],
+                                      LDAP_SCOPE_BASE, filter, attrs,
+                                      &gr_result);
+                                      
+               ldap_msgfree(gr_result);
+
+               /* Error occurred */
+               if (rcode == -1) {
+                       ldap_value_free(vals);
                        ldap_msgfree(result);
                        ldap_release_socket(inst, conn);
                        return 1;
                }
+               
+               /*
+                *      Either the group DN wasn't found, or it didn't have the
+                *      correct name. Continue looping over the attributes.
+                */
+               if (rcode == -2) {
+                       ldap_msgfree(gr_result);
+                       continue;
+               }
 
-               ldap_msgfree(gr_result);
                found = TRUE;
+
+               RDEBUG("User found (group name in membership DN matches check "
+                      "value)");
+
                break;
        }
+
        ldap_value_free(vals);
        ldap_msgfree(result);
        ldap_release_socket(inst, conn);
 
-       if (!found){
-               RDEBUG("groupcmp: Group %s not found, or user is not a member",
-                      check->vp_strvalue);
+       if (!found) {
+               RDEBUG("User is not a member of specified group");
                return 1;
        }
 
        return 0;
 }
 
-/*
- *     Verify that the ldap update section makes sense, and add attribute names
- *     to array of attributes for efficient querying later.
+/** Detach from the LDAP server and cleanup internal state.
+ *
  */
-static VALUE_PAIR_MAP *build_attrmap(CONF_SECTION *cs)
+static int ldap_detach(void *instance)
 {
-       const char *cs_list, *p;
+       ldap_instance *inst = instance;
+       
+       fr_connection_pool_delete(inst->pool);
 
-       request_refs_t request_def = REQUEST_CURRENT;
-       pair_lists_t list_def = PAIR_LIST_REQUEST;
+       if (inst->user_map) {
+               radius_mapfree(&inst->user_map);
+       }
 
-       CONF_ITEM *ci = cf_sectiontoitem(cs);
-       CONF_PAIR *cp;
+       return 0;
+}
 
-       unsigned int total = 0;
-       VALUE_PAIR_MAP **tail, *map, *head;
-       head = NULL;
-       tail = &head;
-       
-       if (!cs) return NULL;
+static int parse_sub_section(CONF_SECTION *parent, 
+                            ldap_instance *inst,
+                            ldap_acct_section_t **config,
+                            rlm_components_t comp)
+{
+       CONF_SECTION *cs;
+
+       const char *name = section_type_value[comp].section;
        
-       cs_list = p = cf_section_name2(cs);
-       if (cs_list) {
-               request_def = radius_request_name(&p, REQUEST_UNKNOWN);
-               if (request_def == REQUEST_UNKNOWN) {
-                       cf_log_err(ci, "rlm_ldap: Default request specified "
-                                  "in mapping section is invalid");
-                       return NULL;
-               }
+       cs = cf_section_sub_find(parent, name);
+       if (!cs) {
+               radlog(L_INFO, "rlm_ldap (%s): Couldn't find configuration for "
+                      "%s, will return NOOP for calls from this section",
+                      inst->xlat_name, name);
                
-               list_def = fr_str2int(pair_lists, p, PAIR_LIST_UNKNOWN);
-               if (list_def == PAIR_LIST_UNKNOWN) {
-                       cf_log_err(ci, "rlm_ldap: Default list specified "
-                                  "in mapping section is invalid");
-                       return NULL;
-               }
+               return 0;
        }
-
-       for (ci = cf_item_find_next(cs, NULL);
-            ci != NULL;
-            ci = cf_item_find_next(cs, ci)) {
-               if (total++ == MAX_ATTRMAP) {
-                       cf_log_err(ci, "rlm_ldap: Attribute map size exceeded");
-                       goto error;
-               }
-               
-               if (!cf_item_is_pair(ci)) {
-                       cf_log_err(ci, "rlm_ldap: Entry is not in \"attribute ="
-                                      " ldap-attribute\" format");
-                       goto error;
-               }
        
-               cp = cf_itemtopair(ci);
-               map = radius_cp2map(cp, REQUEST_CURRENT, list_def);
-               if (!map) {
-                       goto error;
-               }
-               
-               *tail = map;
-               tail = &(map->next);
+       *config = talloc_zero(inst, ldap_acct_section_t);
+       if (cf_section_parse(cs, *config, acct_section_config) < 0) {
+               radlog(L_ERR, "rlm_ldap (%s): Failed parsing configuration for "
+                      "section %s", inst->xlat_name, name);
+               return -1;
        }
+               
+       (*config)->cs = cs;
 
-       return head;
-       
-       error:
-               radius_mapfree(&head);
-               return NULL;
+       return 0;
 }
 
-/*****************************************************************************
- *
- *     Detach from the LDAP server and cleanup internal state.
- *
- *****************************************************************************/
-static int ldap_detach(void *instance)
+static int ldap_map_verify(ldap_instance *inst, value_pair_map_t **head)
 {
-       ldap_instance *inst = instance;
-
-       fr_connection_pool_delete(inst->pool);
+       value_pair_map_t *map;
        
-       if (inst->user_map) {
-               radius_mapfree(&inst->user_map);
+       if (radius_attrmap(inst->cs, head, PAIR_LIST_REPLY,
+                          PAIR_LIST_REQUEST, MAX_ATTRMAP) < 0) {
+               return -1;
+       }
+       /*
+        *      Attrmap only performs some basic validation checks, we need
+        *      to do rlm_ldap specific checks here.
+        */
+       for (map = *head; map != NULL; map = map->next) {
+               if (map->dst->type != VPT_TYPE_ATTR) {
+                       cf_log_err(map->ci, "Left operand must be an "
+                                    "attribute ref");
+                       
+                       return -1;
+               }
+               
+               if (map->src->type == VPT_TYPE_LIST) {
+                       cf_log_err(map->ci, "Right operand must not be "
+                                    "a list");
+                       
+                       return -1;
+               }
+               
+               switch (map->src->type) 
+               {
+               /*
+                *      Only =, :=, += and -= operators are supported for
+                *      cache entries.
+                */
+               case VPT_TYPE_LITERAL:
+               case VPT_TYPE_XLAT:
+               case VPT_TYPE_ATTR:
+                       switch (map->op) {
+                       case T_OP_SET:
+                       case T_OP_EQ:
+                       case T_OP_SUB:
+                       case T_OP_ADD:
+                               break;
+               
+                       default:
+                               cf_log_err(map->ci, "Operator \"%s\" not "
+                                          "allowed for %s values",
+                                          fr_int2str(fr_tokens, map->op,
+                                                     "¿unknown?"),
+                                          fr_int2str(vpt_types, map->src->type,
+                                                     "¿unknown?"));
+                               return -1;
+                       }
+               default:
+                       break;
+               }
        }
-
-       free(inst);
-
        return 0;
 }
 
-/*************************************************************************
- *
- *     Function: rlm_ldap_instantiate
- *
- *     Purpose: Uses section of radiusd config file passed as parameter
- *              to create an instance of the module.
- *
- *************************************************************************/
+/** Parses config
+ * Uses section of radiusd config file passed as parameter to create an
+ * instance of the module.
+ */
 static int ldap_instantiate(CONF_SECTION * conf, void **instance)
 {
        ldap_instance *inst;
-       CONF_SECTION *cs;
 
-       inst = rad_malloc(sizeof *inst);
-       if (!inst) {
-               return -1;
-       }
-       memset(inst, 0, sizeof(*inst));
+       *instance = inst = talloc_zero(conf, ldap_instance);
+       if (!inst) return -1;
+
        inst->cs = conf;
 
        inst->chase_referrals = 2; /* use OpenLDAP defaults */
        inst->rebind = 2;
+       
+       inst->xlat_name = cf_section_name2(conf);
+       if (!inst->xlat_name) {
+               inst->xlat_name = cf_section_name1(conf);
+       }
 
-       if (cf_section_parse(conf, inst, module_config) < 0) {
-               free(inst);
-               return -1;
+       /*
+        *      If the configuration parameters can't be parsed, then fail.
+        */
+       if ((cf_section_parse(conf, inst, module_config) < 0) ||
+           (parse_sub_section(conf, inst,
+                              &inst->accounting,
+                              RLM_COMPONENT_ACCT) < 0) ||
+           (parse_sub_section(conf, inst,
+                              &inst->postauth,
+                              RLM_COMPONENT_POST_AUTH) < 0)) {
+               radlog(L_ERR, "rlm_ldap (%s): Failed parsing configuration",
+                      inst->xlat_name);
+               goto error;
        }
 
        if (inst->server == NULL) {
-               radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
-               ldap_detach(inst);
-               return -1;
+               radlog(L_ERR, "rlm_ldap (%s): Missing 'server' directive",
+                      inst->xlat_name);
+               goto error;
        }
 
        /*
@@ -1301,10 +1486,10 @@ static int ldap_instantiate(CONF_SECTION * conf, void **instance)
                inst->is_url = 1;
                inst->port = 0;
 #else
-               radlog(L_ERR, "rlm_ldap: 'server' directive is in URL form but "
-                      "ldap_initialize() is not available.");
-               ldap_detach(inst);
-               return -1;
+               radlog(L_ERR, "rlm_ldap (%s): 'server' directive is in URL "
+                      "form but ldap_initialize() is not available",
+                      inst->xlat_name);
+               goto error;
 #endif
        }
 
@@ -1315,9 +1500,6 @@ static int ldap_instantiate(CONF_SECTION * conf, void **instance)
                inst->tls_mode = 0;
        }
 
-       inst->xlat_name = cf_section_name2(conf);
-       if (!inst->xlat_name) inst->xlat_name = cf_section_name1(conf);
-
 #if LDAP_SET_REBIND_PROC_ARGS != 3
        /*
         *      The 2-argument rebind doesn't take an instance
@@ -1325,24 +1507,18 @@ static int ldap_instantiate(CONF_SECTION * conf, void **instance)
         *      variable for the username, password, etc.
         */
        if (inst->rebind == 1) {
-               radlog(L_ERR, "%s: Cannot use 'rebind' directive as this "
-                      "version of libldap does not support the API that "
-                      "we need.", inst->xlat-name);
-               ldap_detach(inst);
-               return -1;
+               radlog(L_ERR, "rlm_ldap (%s): Cannot use 'rebind' directive "
+                      "as this version of libldap does not support the API "
+                      "that we need", inst->xlat-name);
+               goto error;
        }
 #endif
 
        /*
         *      Build the attribute map
         */
-       cs = cf_section_sub_find(conf, "update");
-       if (cs) {       
-               inst->user_map = build_attrmap(cs);
-               if (!inst->user_map) {
-                       ldap_detach(inst);
-                       return -1;
-               }
+       if (ldap_map_verify(inst, &(inst->user_map)) < 0) {
+               goto error;
        }
 
        /*
@@ -1350,23 +1526,24 @@ static int ldap_instantiate(CONF_SECTION * conf, void **instance)
         */
        paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst); 
        if (cf_section_name2(conf)) {
-               DICT_ATTR *da;
+               const DICT_ATTR *da;
                ATTR_FLAGS flags;
                char buffer[256];
 
-               snprintf(buffer, sizeof(buffer), "%s-Ldap-Group", inst->xlat_name);
+               snprintf(buffer, sizeof(buffer), "%s-Ldap-Group",
+                        inst->xlat_name);
                memset(&flags, 0, sizeof(flags));
 
                dict_addattr(buffer, -1, 0, PW_TYPE_STRING, flags);
                da = dict_attrbyname(buffer);
                if (!da) {
-                       radlog(L_ERR, "%s: Failed creating attribute %s",
-                              inst->xlat_name, buffer);
-                       ldap_detach(inst);
-                       return -1;
+                       radlog(L_ERR, "rlm_ldap (%s): Failed creating "
+                              "attribute %s", inst->xlat_name, buffer);
+                       goto error;
                }
 
-               paircompare_register(da->attr, PW_USER_NAME, ldap_groupcmp, inst);
+               paircompare_register(da->attr, PW_USER_NAME, ldap_groupcmp,
+                                    inst);
        }
 
        xlat_register(inst->xlat_name, ldap_xlat, inst);
@@ -1383,30 +1560,15 @@ static int ldap_instantiate(CONF_SECTION * conf, void **instance)
                return -1;
        }
        
-       *instance = inst;
        return 0;
-}
-
-
-static void module_failure_msg(VALUE_PAIR **vps, const char *fmt, ...)
-{
-       va_list ap;
-       VALUE_PAIR *vp;
-
-       va_start(ap, fmt);
-       vp = paircreate(PW_MODULE_FAILURE_MESSAGE, 0, PW_TYPE_STRING);
-       if (!vp) {
-               va_end(ap);
-               return;
-       }
-
-       vsnprintf(vp->vp_strvalue, sizeof(vp->vp_strvalue), fmt, ap);
 
-       pairadd(vps, vp);
+error:
+       ldap_detach(inst);
+       return -1;
 }
 
-
-static int check_access(ldap_instance *inst, LDAP_CONN *conn, LDAPMessage *entry)
+static int check_access(ldap_instance *inst, REQUEST* request, LDAP_CONN *conn,
+                       LDAPMessage *entry)
 {
        int rcode = -1;
        char **vals = NULL;
@@ -1415,21 +1577,22 @@ static int check_access(ldap_instance *inst, LDAP_CONN *conn, LDAPMessage *entry
        if (vals) {
                if (inst->positive_access_attr) {
                        if (strncmp(vals[0], "FALSE", 5) == 0) {
-                               DEBUG("dialup access disabled");
+                               RDEBUG("Dialup access disabled");
 
                        } else {
                                rcode = 0;
                        }
 
                } else {
-                       DEBUG("%s attribute exists - access denied by default",
-                               inst->access_attr);
+                       RDEBUG("\"%s\" attribute exists - access denied by"
+                              " default", inst->access_attr);
                }
 
                ldap_value_free(vals);
 
        } else if (inst->positive_access_attr) {
-               DEBUG("No %s attribute - access denied by default", inst->access_attr);
+               RDEBUG("No %s attribute - access denied by default",
+                      inst->access_attr);
 
        } else {
                rcode = 0;
@@ -1439,7 +1602,7 @@ static int check_access(ldap_instance *inst, LDAP_CONN *conn, LDAPMessage *entry
 }
 
 
-static VALUE_PAIR *ldap_getvalue(REQUEST *request, VALUE_PAIR_TMPL *dst,
+static VALUE_PAIR *ldap_getvalue(REQUEST *request, const value_pair_map_t *map,
                                 void *ctx)
 {
        rlm_ldap_result_t *self = ctx;
@@ -1457,7 +1620,7 @@ static VALUE_PAIR *ldap_getvalue(REQUEST *request, VALUE_PAIR_TMPL *dst,
         *      just use whatever was set in the attribute map. 
         */
        for (i = 0; i < self->count; i++) {
-               vp = pairalloc(dst->da);
+               vp = pairalloc(NULL, map->dst->da);
                rad_assert(vp);
 
                pairparsevalue(vp, self->values[i]);
@@ -1472,55 +1635,91 @@ static VALUE_PAIR *ldap_getvalue(REQUEST *request, VALUE_PAIR_TMPL *dst,
 
 static void xlat_attrsfree(const xlat_attrs_t *expanded)
 {
-       const VALUE_PAIR_MAP *map;
+       const value_pair_map_t *map;
        unsigned int total = 0;
        
-       char *name;
+       const char *name;
        
        for (map = expanded->maps; map != NULL; map = map->next)
        {
-               memcpy(&name, &(expanded->attrs[total++]), sizeof(name));
-               
+               name = expanded->attrs[total++];
                if (!name) return;
                
-               if (map->src.do_xlat) {
-                       free(name);
+               switch (map->src->type)
+               {
+               case VPT_TYPE_XLAT:             
+               case VPT_TYPE_ATTR:
+                       rad_cfree(name);
+                       break;
+               default:
+                       break;
                }
        }
 }
 
 
-static int xlat_attrs(REQUEST *request, const VALUE_PAIR_MAP *maps,
+static int xlat_attrs(REQUEST *request, const value_pair_map_t *maps,
                      xlat_attrs_t *expanded)
 {
-       const VALUE_PAIR_MAP *map;
+       const value_pair_map_t *map;
        unsigned int total = 0;
        
        size_t len;
        char *buffer;
 
+       VALUE_PAIR *found, **from = NULL;
+       REQUEST *context;
+
        for (map = maps; map != NULL; map = map->next)
        {
-               if (map->src.do_xlat) {
+               switch (map->src->type)
+               {
+               case VPT_TYPE_XLAT:
                        buffer = rad_malloc(MAX_ATTR_STR_LEN);
                        len = radius_xlat(buffer, MAX_ATTR_STR_LEN,
-                                         map->src.name, request, NULL, NULL);
+                                         map->src->name, request, NULL, NULL);
                                          
-                       if (!len) {
-                               DEBUG2("WARNING: Expansion of LDAP attribute "
-                                      "\"%s\" failed", map->src.name);
+                       if (len <= 0) {
+                               RDEBUG("Expansion of LDAP attribute "
+                                      "\"%s\" failed", map->src->name);
                                       
-                               expanded->attrs[total] = NULL;
-                               
-                               xlat_attrsfree(expanded);
-                               
-                               return -1;
+                               goto error;
                        }
                        
                        expanded->attrs[total++] = buffer;
-               } else {
-                       expanded->attrs[total++] = map->src.name;
+                       break;
+
+               case VPT_TYPE_ATTR:
+                       context = request;
+                       
+                       if (radius_request(&context, map->src->request) == 0) {
+                               from = radius_list(context, map->src->list);
+                       }
+                       if (!from) continue;
+                       
+                       found = pairfind(*from, map->src->da->attr,
+                                        map->src->da->vendor, TAG_ANY);
+                       if (!found) continue;
+                       
+                       buffer = rad_malloc(MAX_ATTR_STR_LEN);
+                       strlcpy(buffer, found->vp_strvalue, MAX_ATTR_STR_LEN);
+                       
+                       expanded->attrs[total++] = buffer;
+                       break;
+                       
+               case VPT_TYPE_LITERAL:
+                       expanded->attrs[total++] = map->src->name;
+                       break;
+               default:
+                       rad_assert(0);
+               error:
+                       expanded->attrs[total] = NULL;
+                       
+                       xlat_attrsfree(expanded);
+                       
+                       return -1;
                }
+                       
        }
        
        expanded->attrs[total] = NULL;
@@ -1542,7 +1741,7 @@ static void do_attrmap(UNUSED ldap_instance *inst, REQUEST *request,
                       LDAP *handle, const xlat_attrs_t *expanded,
                       LDAPMessage *entry)
 {
-       const VALUE_PAIR_MAP    *map;
+       const value_pair_map_t  *map;
        unsigned int            total = 0;
        
        rlm_ldap_result_t       result;
@@ -1554,8 +1753,8 @@ static void do_attrmap(UNUSED ldap_instance *inst, REQUEST *request,
                
                result.values = ldap_get_values(handle, entry, name);
                if (!result.values) {
-                       DEBUG2("WARNING: Attribute \"%s\" not found in LDAP "
-                              "object", name);
+                       RDEBUG2("Attribute \"%s\" not found in LDAP object",
+                               name);
                                
                        goto next;
                }
@@ -1589,14 +1788,16 @@ static void do_check_reply(ldap_instance *inst, REQUEST *request)
        *       More warning messages for people who can't be bothered
        *       to read the documentation.
        */
-       if (inst->expect_password && (debug_flag > 1)) {
-              if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0) &&
-                  !pairfind(request->config_items, PW_NT_PASSWORD, 0) &&
-                  !pairfind(request->config_items, PW_USER_PASSWORD, 0) &&
-                  !pairfind(request->config_items, PW_PASSWORD_WITH_HEADER, 0) &&
-                  !pairfind(request->config_items, PW_CRYPT_PASSWORD, 0)) {
-                      DEBUG("WARNING: No \"known good\" password was found in LDAP.  Are you sure that the user is configured correctly?");
-              }
+       if (inst->expect_password && (debug_flag > 1)) {
+               if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY) &&
+                   !pairfind(request->config_items, PW_NT_PASSWORD, 0, TAG_ANY) &&
+                   !pairfind(request->config_items, PW_USER_PASSWORD, 0, TAG_ANY) &&
+                   !pairfind(request->config_items, PW_PASSWORD_WITH_HEADER, 0, TAG_ANY) &&
+                   !pairfind(request->config_items, PW_CRYPT_PASSWORD, 0, TAG_ANY)) {
+                       RDEBUGW("No \"known good\" password "
+                              "was found in LDAP.  Are you sure that "
+                               "the user is configured correctly?");
+               }
        }
 }
 
@@ -1607,53 +1808,63 @@ static void apply_profile(ldap_instance *inst, REQUEST *request,
 {
        int rcode;
        LDAPMessage     *result, *entry;
+       int             ldap_errno;
+       LDAP            *handle = (*pconn)->handle;
        char            filter[MAX_FILTER_STR_LEN];
 
        if (!profile || !*profile) return;
 
        strlcpy(filter, inst->base_filter, sizeof(filter));
 
-       rcode = perform_search(inst, pconn, profile, LDAP_SCOPE_BASE,
+       rcode = perform_search(inst, request, pconn, profile, LDAP_SCOPE_BASE,
                               filter, expanded->attrs, &result);
                
        if (rcode < 0) {
-               RDEBUG("FAILED Searching profile %s", profile);
+               if (rcode == -2) {
+                       RDEBUG("Profile \"%s\" not found", profile);
+               }
                goto free_result;
        }
 
-       entry = ldap_first_entry((*pconn)->handle, result);
-       if (!entry) goto free_result;
-
-       do_attrmap(inst, request, (*pconn)->handle, expanded, entry);
+       entry = ldap_first_entry(handle, result);
+       if (!entry) {
+               ldap_get_option(handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
+                      
+               goto free_result;
+       }
+       
+       do_attrmap(inst, request, handle, expanded, entry);
 
 free_result:
        ldap_msgfree(result);
 }
 
 
-/******************************************************************************
- *
- *      Function: ldap_authorize
- *
- *      Purpose: Check if user is authorized for remote access
+/** Check if user is authorized for remote access
  *
- ******************************************************************************/
-static int ldap_authorize(void *instance, REQUEST * request)
+ */
+static rlm_rcode_t ldap_authorize(void *instance, REQUEST * request)
 {
        int rcode;
        int module_rcode = RLM_MODULE_OK;
        ldap_instance   *inst = instance;
-       char            *user_dn;
+       char            *user_dn = NULL;
        char            **vals;
        VALUE_PAIR      *vp;
        LDAP_CONN       *conn;
        LDAPMessage     *result, *entry;
+       int             ldap_errno;
        char            filter[MAX_FILTER_STR_LEN];
        char            basedn[MAX_FILTER_STR_LEN];
        xlat_attrs_t    expanded; /* faster that mallocing every time */
        
        if (!request->username) {
-               RDEBUG2("attribute \"User-Name\" is required for authorization.\n");
+               RDEBUG2("Attribute \"User-Name\" is required for "
+                       "authorization.");
                return RLM_MODULE_NOOP;
        }
 
@@ -1661,69 +1872,143 @@ static int ldap_authorize(void *instance, REQUEST * request)
         *      Check for valid input, zero length names not permitted
         */
        if (request->username->length == 0) {
-               RDEBUG2("zero length username not permitted\n");
+               RDEBUG2("Zero length username not permitted");
                return RLM_MODULE_INVALID;
        }
 
        if (!radius_xlat(filter, sizeof(filter), inst->filter,
                         request, ldap_escape_func, NULL)) {
-               radlog(L_ERR, "  [%s] Failed creating filter.\n", inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Failed creating filter",
+                      inst->xlat_name);
                return RLM_MODULE_INVALID;
        }
 
        if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
                         request, ldap_escape_func, NULL)) {
-               radlog(L_ERR, "  [%s] Failed creating basedn.\n", inst->xlat_name);
+               radlog(L_ERR, "rlm_ldap (%s): Failed creating basedn",
+                      inst->xlat_name);
                return RLM_MODULE_INVALID;
        }
-
-       conn = ldap_get_socket(inst);
-       if (!conn) return RLM_MODULE_FAIL;
        
        if (xlat_attrs(request, inst->user_map, &expanded) < 0) {
                return RLM_MODULE_FAIL;
        }
        
-       rcode = perform_search(inst, &conn, basedn, LDAP_SCOPE_SUBTREE, filter,
-                              expanded.attrs, &result);
+
+       conn = ldap_get_socket(inst);
+       if (!conn) return RLM_MODULE_FAIL;
+       
+       rcode = perform_search(inst, request, &conn, basedn,
+                              LDAP_SCOPE_SUBTREE, filter, expanded.attrs,
+                              &result);
        
        if (rcode < 0) {
                if (rcode == -2) {
-                       module_failure_msg(&request->packet->vps,
-                                          "[%s] Search returned not found",
+                       module_failure_msg(request,
+                                          "rlm_ldap (%s): User object not "
+                                          " found",
                                           inst->xlat_name);
-                       DEBUG("  [%s] Search returned not found", inst->xlat_name);
+                                          
+                       RDEBUG("User object not found", inst->xlat_name);
+                              
                        module_rcode = RLM_MODULE_NOTFOUND;
                        goto free_socket;
                }
-               DEBUG("  [%s] Search returned error", inst->xlat_name);
+
                goto free_socket;
        }
 
        entry = ldap_first_entry(conn->handle, result);
        if (!entry) {
-               RDEBUG2("ldap_first_entry() failed");
+               ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
+                      
                goto free_result;
        }
 
        user_dn = ldap_get_dn(conn->handle, entry);
        if (!user_dn) {
-               RDEBUG2("ldap_get_dn() failed");
+               ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
+                               &ldap_errno);
+               radlog(L_ERR, "rlm_ldap (%s): ldap_get_dn() failed: %s",
+                      inst->xlat_name,
+                      ldap_err2string(ldap_errno));
                goto free_result;
        }
        
-       RDEBUG2("User found, dn is \"%s\"", user_dn);
+       RDEBUG2("User found at DN \"%s\"", user_dn);
        /*
         *      Adding attribute containing the Users' DN.
         */
-       pairadd(&request->config_items, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
-       ldap_memfree(user_dn);
+       pairadd(&request->config_items,
+               pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
+
+#ifdef WITH_EDIR
+       /*
+        *      We already have a Cleartext-Password.  Skip edir.
+        */
+       if (inst->edir && pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY)) {
+               goto skip_edir;
+       }
+
+       /*
+        *      Retrieve Universal Password if we use eDirectory
+        */
+       if (inst->edir) {
+               int res = 0;
+               size_t bufsize;
+               char buffer[256];
+
+               bufsize = sizeof(buffer);
+
+               /* retrive universal password */
+               res = nmasldap_get_password(conn->handle, user_dn,
+                                           buffer, &bufsize);
+               if (res != 0) {
+                       RDEBUG2("Failed to retrieve eDirectory password. Check "
+                               "your configuration !");
+                       module_rcode = RLM_MODULE_NOOP;
+                       goto free_result;
+               }
+
+               /* Add Cleartext-Password attribute to the request */
+               vp = radius_paircreate(request, &request->config_items,
+                                      PW_CLEARTEXT_PASSWORD, 0);
+               strlcpy(vp->vp_strvalue, buffer, sizeof(vp->vp_strvalue));
+               vp->length = strlen(vp->vp_strvalue);
+               
+               RDEBUG2("Added eDirectory password in check items as %s = %s",
+                       vp->da->name, vp->vp_strvalue);
+                       
+               if (inst->edir_autz) {
+                       RDEBUG2("Binding as user for eDirectory authorization "
+                               "checks");
+                       /*
+                        *      Bind as the user
+                        */
+                       conn->rebound = TRUE;
+                       module_rcode = ldap_bind_wrapper(&conn, user_dn,
+                                                        vp->vp_strvalue,
+                                                        TRUE);
+                       if (module_rcode != RLM_MODULE_OK) {
+                               goto free_result;
+                       }
+                       
+                       RDEBUG("Bind as user \"%s\" was successful", user_dn);
+               }
+       }
+
+skip_edir:
+#endif
 
        /*
         *      Check for access.
         */
        if (inst->access_attr) {
-               if (check_access(inst, conn, entry) < 0) {
+               if (check_access(inst, request, conn, entry) < 0) {
                        module_rcode = RLM_MODULE_USERLOCK;
                        goto free_result;
                }
@@ -1732,7 +2017,7 @@ static int ldap_authorize(void *instance, REQUEST * request)
        /*
         *      Apply ONE user profile, or a default user profile.
         */
-       vp = pairfind(request->config_items, PW_USER_PROFILE, 0);
+       vp = pairfind(request->config_items, PW_USER_PROFILE, 0, TAG_ANY);
        if (vp || inst->default_profile) {
                char *profile = inst->default_profile;
 
@@ -1744,16 +2029,19 @@ static int ldap_authorize(void *instance, REQUEST * request)
        /*
         *      Apply a SET of user profiles.
         */
-       if (inst->profile_attr &&
-           (vals = ldap_get_values(conn->handle, entry, inst->profile_attr)) != NULL) {
-
-               int i;
-
-               for (i = 0; (vals[i] != NULL) && (*vals[i] != '\0'); i++) {
-                       apply_profile(inst, request, &conn, vals[i], &expanded);
+       if (inst->profile_attr) {
+               vals = ldap_get_values(conn->handle, entry, inst->profile_attr);
+               if (vals != NULL) {
+                       int i;
+       
+                       for (i = 0; (vals[i] != NULL) && (*vals[i] != '\0');
+                            i++) {
+                               apply_profile(inst, request, &conn, vals[i],
+                                             &expanded);
+                       }
+       
+                       ldap_value_free(vals);
                }
-
-               ldap_value_free(vals);
        }
 
        if (inst->user_map) {
@@ -1762,6 +2050,7 @@ static int ldap_authorize(void *instance, REQUEST * request)
        }
        
 free_result:
+       if (user_dn) ldap_memfree(user_dn);
        xlat_attrsfree(&expanded);
        ldap_msgfree(result);
 free_socket:
@@ -1771,16 +2060,12 @@ free_socket:
 }
 
 
-/*****************************************************************************
- *
- *     Function: ldap_authenticate
+/** Check the user's password against ldap database
  *
- *     Purpose: Check the user's password against ldap database
- *
- *****************************************************************************/
-static int ldap_authenticate(void *instance, REQUEST * request)
+ */
+static rlm_rcode_t ldap_authenticate(void *instance, REQUEST * request)
 {
-       int             module_rcode;
+       rlm_rcode_t     module_rcode;
        const char      *user_dn;
        ldap_instance   *inst = instance;
        LDAP_CONN       *conn;
@@ -1791,37 +2076,42 @@ static int ldap_authenticate(void *instance, REQUEST * request)
         */
 
        if (!request->username) {
-               radlog(L_AUTH, "  [%s] Attribute \"User-Name\" is required for authentication.", inst->xlat_name);
+               radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Name\" is "
+                      "required for authentication", inst->xlat_name);
                return RLM_MODULE_INVALID;
        }
 
        if (!request->password) {
-               radlog(L_AUTH, "  [%s] Attribute \"User-Password\" is required for authentication.", inst->xlat_name);
-               RDEBUG2("  You seem to have set \"Auth-Type := LDAP\" somewhere.");
-               RDEBUG2("  *******************************************************");
-               RDEBUG2("  * THAT CONFIGURATION IS WRONG.  DELETE IT.");
-               RDEBUG2("  * YOU ARE PREVENTING THE SERVER FROM WORKING PROPERLY.");
-               RDEBUG2("  *******************************************************");
+               radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Password\" "
+                      "is required for authentication.", inst->xlat_name);
+               RDEBUG2("  You have set \"Auth-Type := LDAP\" somewhere.");
+               RDEBUG2("  *********************************************");
+               RDEBUG2("  * THAT CONFIGURATION IS WRONG.  DELETE IT.   ");
+               RDEBUG2("  * YOU ARE PREVENTING THE SERVER FROM WORKING.");
+               RDEBUG2("  *********************************************");
                return RLM_MODULE_INVALID;
        }
 
-       if (request->password->attribute != PW_USER_PASSWORD) {
-               radlog(L_AUTH, "  [%s] Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", inst->xlat_name, request->password->name);
+       if (request->password->da->attr != PW_USER_PASSWORD) {
+               radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Password\" "
+                      "is required for authentication. Cannot use \"%s\".",
+                      inst->xlat_name, request->password->da->name);
                return RLM_MODULE_INVALID;
        }
 
        if (request->password->length == 0) {
-               module_failure_msg(&request->packet->vps,
-                                  "[%s] empty password supplied", inst->xlat_name);
+               module_failure_msg(request,
+                                  "rlm_ldap (%s): Empty password supplied",
+                                  inst->xlat_name);
                return RLM_MODULE_INVALID;
        }
 
+       RDEBUG("Login attempt by \"%s\" with password \"%s\"",
+              request->username->vp_strvalue, request->password->vp_strvalue);
+
        conn = ldap_get_socket(inst);
        if (!conn) return RLM_MODULE_FAIL;
 
-       RDEBUG("login attempt by \"%s\" with password \"%s\"",
-              request->username->vp_strvalue, request->password->vp_strvalue);
-
        /*
         *      Get the DN by doing a search.
         */
@@ -1837,17 +2127,332 @@ static int ldap_authenticate(void *instance, REQUEST * request)
        conn->rebound = TRUE;
        module_rcode = ldap_bind_wrapper(&conn, user_dn,
                                         request->password->vp_strvalue,
-                                        NULL, TRUE);
+                                        TRUE);
        if (module_rcode == RLM_MODULE_OK) {
-               RDEBUG("  [%s] Bind as user '%s' was successful", inst->xlat_name,
-                       user_dn);
+               RDEBUG("Bind as user \"%s\" was successful", user_dn);
+       }
+
+       ldap_release_socket(inst, conn);
+       return module_rcode;
+}
+
+/** Modify user's object in LDAP
+ *
+ */
+static rlm_rcode_t user_modify(ldap_instance *inst, REQUEST *request,
+                              ldap_acct_section_t *section)
+{
+       rlm_rcode_t     module_rcode = RLM_MODULE_OK;
+       int             ldap_errno, rcode, msg_id;
+       LDAPMessage     *result = NULL;
+       
+       LDAP_CONN       *conn = NULL;
+       
+       LDAPMod         *mod_p[MAX_ATTRMAP + 1], mod_s[MAX_ATTRMAP];
+       LDAPMod         **modify = mod_p;
+       
+       char            *passed[MAX_ATTRMAP * 2];
+       int             i, total = 0, last_pass = 0;
+       
+       char            *expanded[MAX_ATTRMAP];
+       int             last_exp = 0;
+       
+       struct timeval  tv;
+       
+       const char      *attr;
+       const char      *value;
+       
+       const char      *user_dn;
+
+       /*
+        *      Build our set of modifications using the update sections in
+        *      the config.
+        */
+       CONF_ITEM       *ci;
+       CONF_PAIR       *cp;
+       CONF_SECTION    *cs;
+       FR_TOKEN        op;
+       char            path[MAX_STRING_LEN];
+       
+       char            *p = path;
+
+       rad_assert(section);
+       
+       /*
+        *      Locate the update section were going to be using
+        */
+       if (section->reference[0] != '.') {
+               *p++ = '.';
+       }
+       
+       if (!radius_xlat(p, (sizeof(path) - (p - path)) - 1,
+                        section->reference, request, NULL, NULL)) {
+               goto error;     
+       }
+
+       ci = cf_reference_item(NULL, section->cs, path);
+       if (!ci) {
+               goto error;     
+       }
+       
+       if (!cf_item_is_section(ci)){
+               radlog(L_ERR, "rlm_ldap (%s): Reference must resolve to a "
+                      "section", inst->xlat_name);
+               
+               goto error;     
+       }
+       
+       cs = cf_section_sub_find(cf_itemtosection(ci), "update");
+       if (!cs) {
+               radlog(L_ERR, "rlm_ldap (%s): Section must contain 'update' "
+                      "subsection",
+                      inst->xlat_name);
+               
+               goto error;
+       }
+       
+       /*
+        *      Iterate over all the pairs, building our mods array
+        */
+       for (ci = cf_item_find_next(cs, NULL);
+            ci != NULL;
+            ci = cf_item_find_next(cs, ci)) {
+               int do_xlat = FALSE;
+               
+               if (total == MAX_ATTRMAP) {
+                       radlog(L_ERR, "rlm_ldap (%s): Modify map size exceeded",
+                              inst->xlat_name);
+       
+                       goto error;
+               }
+               
+               if (!cf_item_is_pair(ci)) {
+                       radlog(L_ERR, "rlm_ldap (%s): Entry is not in "
+                              "\"ldap-attribute = value\" format",
+                              inst->xlat_name);
+                              
+                       goto error;
+               }
+       
+               /*
+                *      Retrieve all the information we need about the pair
+                */
+               cp = cf_itemtopair(ci);
+               value = cf_pair_value(cp);
+               attr = cf_pair_attr(cp);
+               op = cf_pair_operator(cp);
+               
+               if ((value == NULL) || (*value == '\0')) {
+                       RDEBUG("empty value string, "
+                              "skipping attribute \"%s\"", attr);
+                       
+                       continue;
+               }
+
+               switch (cf_pair_value_type(cp))
+               {
+                       case T_BARE_WORD:
+                       case T_SINGLE_QUOTED_STRING:
+                       break;
+                       case T_BACK_QUOTED_STRING:
+                       case T_DOUBLE_QUOTED_STRING:
+                               do_xlat = TRUE;         
+                       break;
+                       default:
+                               rad_assert(0);
+                               goto error;
+               }
+               
+               if (op == T_OP_CMP_FALSE) {
+                       passed[last_pass] = NULL;
+               } else if (do_xlat) {
+                       p = rad_malloc(1024);
+                       if (radius_xlat(p, 1024, value, request, NULL, NULL) <= 0) {
+                               RDEBUG("xlat failed or empty value string, "
+                                      "skipping attribute \"%s\"", attr);
+                                      
+                               free(p);
+                               
+                               continue;
+                       }
+                       
+                       expanded[last_exp++] = p;
+                       passed[last_pass] = p;
+               /* 
+                *      Static strings
+                */
+               } else {
+                       memcpy(&(passed[last_pass]), &value,
+                              sizeof(passed[last_pass]));
+               }
+               
+               passed[last_pass + 1] = NULL;
+               
+               mod_s[total].mod_values = &(passed[last_pass]);
+                                       
+               last_pass += 2;
+               
+               switch (op)
+               {
+               /*
+                *  T_OP_EQ is *NOT* supported, it is impossible to
+                *  support because of the lack of transactions in LDAP
+                */
+               case T_OP_ADD:
+                       mod_s[total].mod_op = LDAP_MOD_ADD;
+                       break;
+
+               case T_OP_SET:
+                       mod_s[total].mod_op = LDAP_MOD_REPLACE;
+                       break;
+
+               case T_OP_SUB:
+               case T_OP_CMP_FALSE:
+                       mod_s[total].mod_op = LDAP_MOD_DELETE;
+                       break;
+
+#ifdef LDAP_MOD_INCREMENT
+               case T_OP_INCRM:
+                       mod_s[total].mod_op = LDAP_MOD_INCREMENT;
+                       break;
+#endif
+               default:
+                       radlog(L_ERR, "rlm_ldap (%s): Operator '%s' "
+                              "is not supported for LDAP modify "
+                              "operations", inst->xlat_name,
+                              fr_int2str(fr_tokens, op, "¿unknown?"));
+                              
+                       goto error;
+               }
+               
+               /*
+                *      Now we know the value is ok, copy the pointers into
+                *      the ldapmod struct.
+                */
+               memcpy(&(mod_s[total].mod_type), &(attr), 
+                      sizeof(mod_s[total].mod_type));
+               
+               mod_p[total] = &(mod_s[total]);
+               total++;
+       }
+       
+       if (total == 0) {
+               module_rcode = RLM_MODULE_NOOP;
+               goto release;
        }
+       
+       mod_p[total] = NULL;
+       
+       conn = ldap_get_socket(inst);
+       if (!conn) return RLM_MODULE_FAIL;
+       
+       /*
+        *      Perform all modifications as the default admin user.
+        */
+       if (conn->rebound) {
+               ldap_errno = ldap_bind_wrapper(&conn, inst->login,
+                                              inst->password, TRUE);
+               if (ldap_errno != RLM_MODULE_OK) {
+                       goto error;
+               }
+
+               rad_assert(conn != NULL);
+               conn->rebound = FALSE;
+       }
+
+       user_dn = get_userdn(&conn, request, &module_rcode);
+       if (!user_dn) {
+               module_rcode = RLM_MODULE_NOTFOUND;
+               goto release;
+       }
+       
+       RDEBUG2("Modifying user object with DN \"%s\"", user_dn);
+       retry:
+       ldap_errno = ldap_modify_ext(conn->handle, user_dn, modify, NULL, NULL,
+                                    &msg_id);
+       if (ldap_errno != LDAP_SUCCESS) {
+               switch (process_ldap_errno(inst, &conn, "Modify"))
+               {
+                       case LDAP_PROC_SUCCESS:
+                               break;
+                       case LDAP_PROC_REJECT:
+                       case LDAP_PROC_ERROR:
+                               goto error;
+                       case LDAP_PROC_RETRY:
+                               goto retry;
+                       default:
+                               rad_assert(0);
+               }
+       }
+                                            
+       DEBUG3("rlm_ldap (%s): Waiting for modify result...", inst->xlat_name);
+
+       tv.tv_sec = inst->timeout;
+       tv.tv_usec = 0;
+       
+       result:
+       rcode = ldap_result(conn->handle, msg_id, 1, &tv, &result);
+       ldap_msgfree(result);
+       if (rcode <= 0) {
+               switch (process_ldap_errno(inst, &conn, "Modify"))
+               {
+                       case LDAP_PROC_SUCCESS:
+                               break;
+                       case LDAP_PROC_REJECT:
+                       case LDAP_PROC_ERROR:
+                               error:
+                               module_rcode = RLM_MODULE_FAIL;
+                               goto release;
+                       case LDAP_PROC_RETRY:
+                               goto result;
+                       default:
+                               rad_assert(0);
+               }
+       }
+               
+       RDEBUG2("Modification successful!");
+       
+       release:
+       /*
+        *      Free up any buffers we allocated for xlat expansion
+        */     
+       for (i = 0; i < last_exp; i++) {
+               free(expanded[i]);
+       }
+       
 
        ldap_release_socket(inst, conn);
+       
        return module_rcode;
 }
 
 
+static rlm_rcode_t ldap_accounting(void *instance, REQUEST * request) {
+       ldap_instance *inst = instance;         
+
+       if (inst->accounting) {
+               return user_modify(inst, request, inst->accounting); 
+       }
+       
+       return RLM_MODULE_NOOP;
+}
+
+
+/** Check the user's password against ldap database
+ *
+ */
+static rlm_rcode_t ldap_postauth(void *instance, REQUEST * request)
+{
+       ldap_instance   *inst = instance;
+
+       if (inst->postauth) {
+               return user_modify(inst, request, inst->postauth); 
+       }
+
+       return RLM_MODULE_NOOP;
+}
+
+
 /* globally exported name */
 module_t rlm_ldap = {
        RLM_MODULE_INIT,
@@ -1859,10 +2464,10 @@ module_t rlm_ldap = {
                ldap_authenticate,      /* authentication        */
                ldap_authorize,         /* authorization         */
                NULL,                   /* preaccounting         */
-               NULL,                   /* accounting            */
+               ldap_accounting,        /* accounting            */
                NULL,                   /* checksimul            */
                NULL,                   /* pre-proxy             */
                NULL,                   /* post-proxy            */
-               NULL
+               ldap_postauth           /* post-auth */
        },
 };