]> git.sur5r.net Git - openldap/blobdiff - servers/slapd/back-ldap/chain.c
RFC 4511 calls for unavailableCriticalExtension to returned when
[openldap] / servers / slapd / back-ldap / chain.c
index d06fe256658ec7db474b8b69a83556bd04c21599..b81de4fb8750a6ce31d1e958fef727b55264f273 100644 (file)
@@ -2,7 +2,7 @@
 /* $OpenLDAP$ */
 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  *
- * Copyright 2003-2005 The OpenLDAP Foundation.
+ * Copyright 2003-2006 The OpenLDAP Foundation.
  * Portions Copyright 2003 Howard Chu.
  * All rights reserved.
  *
@@ -27,9 +27,9 @@
 #include <ac/string.h>
 #include <ac/socket.h>
 
+#include "lutil.h"
 #include "slap.h"
 #include "back-ldap.h"
-
 #include "config.h"
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
 static int             sc_chainingBehavior;
 #endif /*  LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
-#define        LDAP_CH_NONE                    ((void *)(0))
-#define        LDAP_CH_RES                     ((void *)(1))
-#define LDAP_CH_ERR                    ((void *)(2))
-
+typedef enum {
+       LDAP_CH_NONE = 0,
+       LDAP_CH_RES,
+       LDAP_CH_ERR
+} ldap_chain_status_t;
 static BackendInfo     *lback;
 
 typedef struct ldap_chain_t {
@@ -78,7 +79,7 @@ typedef struct ldap_chain_t {
         * the tree?  Should be all configurable.
         */
 
-       /* "common" configuration info (all occurring before an "uri") */
+       /* "common" configuration info (anything occurring before an "uri") */
        ldapinfo_t              *lc_common_li;
 
        /* current configuration info */
@@ -87,13 +88,19 @@ typedef struct ldap_chain_t {
        /* tree of configured[/generated?] "uri" info */
        ldap_avl_info_t         lc_lai;
 
+       /* max depth in nested referrals chaining */
+       int                     lc_max_depth;
+
        unsigned                lc_flags;
 #define LDAP_CHAIN_F_NONE              (0x00U)
 #define        LDAP_CHAIN_F_CHAINING           (0x01U)
-#define        LDAP_CHAIN_F_CACHE_URI          (0x10U)
+#define        LDAP_CHAIN_F_CACHE_URI          (0x02U)
+#define        LDAP_CHAIN_F_RETURN_ERR         (0x04U)
 
-#define        LDAP_CHAIN_CHAINING( lc )       ( ( (lc)->lc_flags & LDAP_CHAIN_F_CHAINING ) == LDAP_CHAIN_F_CHAINING )
-#define        LDAP_CHAIN_CACHE_URI( lc )      ( ( (lc)->lc_flags & LDAP_CHAIN_F_CACHE_URI ) == LDAP_CHAIN_F_CACHE_URI )
+#define LDAP_CHAIN_ISSET(lc, f)                ( ( (lc)->lc_flags & (f) ) == (f) )
+#define        LDAP_CHAIN_CHAINING( lc )       LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_CHAINING )
+#define        LDAP_CHAIN_CACHE_URI( lc )      LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_CACHE_URI )
+#define        LDAP_CHAIN_RETURN_ERR( lc )     LDAP_CHAIN_ISSET( (lc), LDAP_CHAIN_F_RETURN_ERR )
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        LDAPControl             lc_chaining_ctrl;
@@ -101,11 +108,36 @@ typedef struct ldap_chain_t {
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 } ldap_chain_t;
 
+static int ldap_chain_db_init_common( BackendDB        *be );
 static int ldap_chain_db_init_one( BackendDB *be );
-#define        ldap_chain_db_open_one(be)      (lback)->bi_db_open( (be) )
+static int ldap_chain_db_open_one( BackendDB *be );
 #define        ldap_chain_db_close_one(be)     (0)
 #define        ldap_chain_db_destroy_one(be)   (lback)->bi_db_destroy( (be) )
 
+typedef struct ldap_chain_cb_t {
+       ldap_chain_status_t     lb_status;
+       ldap_chain_t            *lb_lc;
+       BI_op_func              *lb_op_f;
+       int                     lb_depth;
+} ldap_chain_cb_t;
+
+static int
+ldap_chain_op(
+       Operation       *op,
+       SlapReply       *rs,
+       BI_op_func      *op_f,
+       BerVarray       ref,
+       int             depth );
+
+static int
+ldap_chain_search(
+       Operation       *op,
+       SlapReply       *rs,
+       BerVarray       ref,
+       int             depth );
+
+static slap_overinst ldapchain;
+
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
 static int
 chaining_control_add(
@@ -218,35 +250,18 @@ ldap_chain_uri_dup( void *c1, void *c2 )
        return 0;
 }
 
-static int
-ldap_chain_operational( Operation *op, SlapReply *rs )
-{
-       /* Trap entries generated by back-ldap.
-        * 
-        * FIXME: we need a better way to recognize them; a cleaner
-        * solution would be to be able to intercept the response
-        * of be_operational(), so that we can divert only those
-        * calls that fail because operational attributes were
-        * requested for entries that do not belong to the underlying
-        * database.  This fix is likely to intercept also entries
-        * generated by back-perl and so. */
-       if ( rs->sr_entry->e_private == NULL ) {
-               return 0;
-       }
-
-       return SLAP_CB_CONTINUE;
-}
-
 /*
  * Search specific response that strips entryDN from entries
  */
 static int
 ldap_chain_cb_search_response( Operation *op, SlapReply *rs )
 {
+       ldap_chain_cb_t *lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
+
        assert( op->o_tag == LDAP_REQ_SEARCH );
 
        /* if in error, don't proceed any further */
-       if ( op->o_callback->sc_private == LDAP_CH_ERR ) {
+       if ( lb->lb_status == LDAP_CH_ERR ) {
                return 0;
        }
 
@@ -268,18 +283,25 @@ ldap_chain_cb_search_response( Operation *op, SlapReply *rs )
                                break;
                        }
                }
+
+               /* tell the frontend not to add generated
+                * operational attributes */
+               rs->sr_flags |= REP_NO_OPERATIONALS;
                
                return SLAP_CB_CONTINUE;
 
        } else if ( rs->sr_type == REP_SEARCHREF ) {
                /* if we get it here, it means the library was unable
                 * to chase the referral... */
+               if ( lb->lb_depth < lb->lb_lc->lc_max_depth && rs->sr_ref != NULL ) {
+                       rs->sr_err = ldap_chain_search( op, rs, rs->sr_ref, lb->lb_depth );
+               }
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-               if ( get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
+               if ( rs->sr_err == LDAP_REFERRAL && get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
                        switch ( get_continuationBehavior( op ) ) {
                        case SLAP_CH_RESOLVE_CHAINING_REQUIRED:
-                               op->o_callback->sc_private = LDAP_CH_ERR;
+                               lb->lb_status = LDAP_CH_ERR;
                                return rs->sr_err = LDAP_X_CANNOT_CHAIN;
 
                        default:
@@ -290,8 +312,15 @@ ldap_chain_cb_search_response( Operation *op, SlapReply *rs )
                return SLAP_CB_CONTINUE;
 
        } else if ( rs->sr_type == REP_RESULT ) {
+               if ( rs->sr_err == LDAP_REFERRAL
+                       && lb->lb_depth < lb->lb_lc->lc_max_depth
+                       && rs->sr_ref != NULL )
+               {
+                       rs->sr_err = ldap_chain_op( op, rs, lb->lb_op_f, rs->sr_ref, lb->lb_depth );
+               }
+
                /* back-ldap tried to send result */
-               op->o_callback->sc_private = LDAP_CH_RES;
+               lb->lb_status = LDAP_CH_RES;
        }
 
        return 0;
@@ -304,12 +333,15 @@ ldap_chain_cb_search_response( Operation *op, SlapReply *rs )
 static int
 ldap_chain_cb_response( Operation *op, SlapReply *rs )
 {
+       ldap_chain_cb_t *lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
+
        /* if in error, don't proceed any further */
-       if ( op->o_callback->sc_private == LDAP_CH_ERR ) {
+       if ( lb->lb_status == LDAP_CH_ERR ) {
                return 0;
        }
 
        if ( rs->sr_type == REP_RESULT ) {
+retry:;
                switch ( rs->sr_err ) {
                case LDAP_COMPARE_TRUE:
                case LDAP_COMPARE_FALSE:
@@ -319,15 +351,20 @@ ldap_chain_cb_response( Operation *op, SlapReply *rs )
                        /* fallthru */
 
                case LDAP_SUCCESS:
-                       op->o_callback->sc_private = LDAP_CH_RES;
+                       lb->lb_status = LDAP_CH_RES;
                        break;
 
                case LDAP_REFERRAL:
+                       if ( lb->lb_depth < lb->lb_lc->lc_max_depth && rs->sr_ref != NULL ) {
+                               rs->sr_err = ldap_chain_op( op, rs, lb->lb_op_f, rs->sr_ref, lb->lb_depth );
+                               goto retry;
+                       }
+
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                        if ( get_chaining( op ) > SLAP_CONTROL_IGNORED ) {
                                switch ( get_continuationBehavior( op ) ) {
                                case SLAP_CH_RESOLVE_CHAINING_REQUIRED:
-                                       op->o_callback->sc_private = LDAP_CH_ERR;
+                                       lb->lb_status = LDAP_CH_ERR;
                                        return rs->sr_err = LDAP_X_CANNOT_CHAIN;
 
                                default:
@@ -354,16 +391,19 @@ static int
 ldap_chain_op(
        Operation       *op,
        SlapReply       *rs,
-       int             ( *op_f )( Operation *op, SlapReply *rs ), 
-       BerVarray       ref )
+       BI_op_func      *op_f,
+       BerVarray       ref,
+       int             depth )
 {
        slap_overinst   *on = (slap_overinst *) op->o_bd->bd_info;
+       ldap_chain_cb_t *lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
        ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
-       ldapinfo_t      li = *lc->lc_common_li, *lip = NULL;
+       ldapinfo_t      li = { 0 }, *lip = NULL;
        struct berval   bvuri[ 2 ] = { { 0 } };
 
        /* NOTE: returned if ref is empty... */
-       int             rc = LDAP_OTHER;
+       int             rc = LDAP_OTHER,
+                       first_rc;
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        LDAPControl     **ctrls = NULL;
@@ -372,6 +412,7 @@ ldap_chain_op(
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
        li.li_bvuri = bvuri;
+       first_rc = -1;
        for ( ; !BER_BVISNULL( ref ); ref++ ) {
                LDAPURLDesc     *srv;
                char            *save_dn;
@@ -395,7 +436,7 @@ Document: draft-ietf-ldapbis-protocol-27.txt
        
                /* parse reference and use 
                 * proto://[host][:port]/ only */
-               rc = ldap_url_parse_ext( ref->bv_val, &srv );
+               rc = ldap_url_parse_ext( ref->bv_val, &srv, LDAP_PVT_URL_PARSE_NONE );
                if ( rc != LDAP_URL_SUCCESS ) {
                        /* try next */
                        rc = LDAP_OTHER;
@@ -439,6 +480,8 @@ Document: draft-ietf-ldapbis-protocol-27.txt
                        lip->li_bvuri = bvuri;
                        rc = ldap_chain_db_open_one( op->o_bd );
                        if ( rc != 0 ) {
+                               lip->li_uri = NULL;
+                               lip->li_bvuri = NULL;
                                (void)ldap_chain_db_destroy_one( op->o_bd );
                                goto cleanup;
                        }
@@ -460,7 +503,15 @@ Document: draft-ietf-ldapbis-protocol-27.txt
                        }
                }
 
-               rc = ( *op_f )( op, rs );
+               lb->lb_op_f = op_f;
+               lb->lb_depth = depth + 1;
+
+               rc = op_f( op, rs );
+
+               /* note the first error */
+               if ( first_rc == -1 ) {
+                       first_rc = rc;
+               }
 
 cleanup:;
                ldap_memfree( li.li_uri );
@@ -482,6 +533,183 @@ cleanup:;
        (void)chaining_control_remove( op, &ctrls );
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
+       if ( rc != LDAP_SUCCESS && first_rc > 0 ) {
+               rc = first_rc;
+       }
+
+       return rc;
+}
+
+static int
+ldap_chain_search(
+       Operation       *op,
+       SlapReply       *rs,
+       BerVarray       ref,
+       int             depth )
+
+{
+       slap_overinst   *on = (slap_overinst *) op->o_bd->bd_info;
+       ldap_chain_cb_t *lb = (ldap_chain_cb_t *)op->o_callback->sc_private;
+       ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
+       ldapinfo_t      li = { 0 }, *lip = NULL;
+       struct berval   bvuri[ 2 ] = { { 0 } };
+
+       struct berval   odn = op->o_req_dn,
+                       ondn = op->o_req_ndn;
+       slap_response   *save_response = op->o_callback->sc_response;
+
+       int             rc = LDAP_OTHER,
+                       first_rc = -1;
+
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+       LDAPControl     **ctrls = NULL;
+       
+       (void)chaining_control_add( lc, op, &ctrls );
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+
+       rs->sr_type = REP_SEARCH;
+
+       op->o_callback->sc_response = ldap_chain_cb_search_response;
+
+       /* if we parse the URI then by no means 
+        * we can cache stuff or reuse connections, 
+        * because in back-ldap there's no caching
+        * based on the URI value, which is supposed
+        * to be set once for all (correct?) */
+       li.li_bvuri = bvuri;
+       for ( ; !BER_BVISNULL( &ref[0] ); ref++ ) {
+               LDAPURLDesc     *srv;
+               char            *save_dn;
+               int             temporary = 0;
+
+               /* parse reference and use
+                * proto://[host][:port]/ only */
+               rc = ldap_url_parse_ext( ref[0].bv_val, &srv, LDAP_PVT_URL_PARSE_NONE );
+               if ( rc != LDAP_URL_SUCCESS ) {
+                       /* try next */
+                       rs->sr_err = LDAP_OTHER;
+                       continue;
+               }
+
+               /* remove DN essentially because later on 
+                * ldap_initialize() will parse the URL 
+                * as a comma-separated URL list */
+               save_dn = srv->lud_dn;
+               srv->lud_dn = "";
+               srv->lud_scope = LDAP_SCOPE_DEFAULT;
+               li.li_uri = ldap_url_desc2str( srv );
+               if ( li.li_uri != NULL ) {
+                       ber_str2bv_x( save_dn, 0, 1, &op->o_req_dn,
+                                       op->o_tmpmemctx );
+                       ber_dupbv_x( &op->o_req_ndn, &op->o_req_dn,
+                                       op->o_tmpmemctx );
+               }
+
+               srv->lud_dn = save_dn;
+               ldap_free_urldesc( srv );
+
+               if ( li.li_uri == NULL ) {
+                       /* try next */
+                       rs->sr_err = LDAP_OTHER;
+                       continue;
+               }
+
+               ber_str2bv( li.li_uri, 0, 0, &li.li_bvuri[ 0 ] );
+
+               /* Searches for a ldapinfo in the avl tree */
+               ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
+               lip = (ldapinfo_t *)avl_find( lc->lc_lai.lai_tree, 
+                       (caddr_t)&li, ldap_chain_uri_cmp );
+               ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );
+
+               if ( lip != NULL ) {
+                       op->o_bd->be_private = (void *)lip;
+
+               } else {
+                       /* if none is found, create a temporary... */
+                       rc = ldap_chain_db_init_one( op->o_bd );
+                       if ( rc != 0 ) {
+                               goto cleanup;
+                       }
+                       lip = (ldapinfo_t *)op->o_bd->be_private;
+                       lip->li_uri = li.li_uri;
+                       lip->li_bvuri = bvuri;
+                       rc = ldap_chain_db_open_one( op->o_bd );
+                       if ( rc != 0 ) {
+                               lip->li_uri = NULL;
+                               lip->li_bvuri = NULL;
+                               (void)ldap_chain_db_destroy_one( op->o_bd );
+                               goto cleanup;
+                       }
+
+                       if ( LDAP_CHAIN_CACHE_URI( lc ) ) {
+                               ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
+                               if ( avl_insert( &lc->lc_lai.lai_tree,
+                                       (caddr_t)lip, ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
+                               {
+                                       /* someone just inserted another;
+                                        * don't bother, use this and then
+                                        * just free it */
+                                       temporary = 1;
+                               }
+                               ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );
+
+                       } else {
+                               temporary = 1;
+                       }
+               }
+
+               lb->lb_op_f = lback->bi_op_search;
+               lb->lb_depth = depth + 1;
+
+               /* FIXME: should we also copy filter and scope?
+                * according to RFC3296, no */
+               rc = lback->bi_op_search( op, rs );
+               if ( first_rc == -1 ) {
+                       first_rc = rc;
+               }
+
+cleanup:;
+               ldap_memfree( li.li_uri );
+               li.li_uri = NULL;
+
+               op->o_tmpfree( op->o_req_dn.bv_val, op->o_tmpmemctx );
+               op->o_tmpfree( op->o_req_ndn.bv_val, op->o_tmpmemctx );
+
+               if ( temporary ) {
+                       lip->li_uri = NULL;
+                       lip->li_bvuri = NULL;
+                       (void)ldap_chain_db_close_one( op->o_bd );
+                       (void)ldap_chain_db_destroy_one( op->o_bd );
+               }
+               
+               if ( rc == LDAP_SUCCESS && rs->sr_err == LDAP_SUCCESS ) {
+                       break;
+               }
+
+               rc = rs->sr_err;
+       }
+
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+       (void)chaining_control_remove( op, &ctrls );
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+
+       op->o_req_dn = odn;
+       op->o_req_ndn = ondn;
+       op->o_callback->sc_response = save_response;
+       rs->sr_type = REP_SEARCHREF;
+       rs->sr_entry = NULL;
+
+       if ( rc != LDAP_SUCCESS ) {
+               /* couldn't chase any of the referrals */
+               if ( first_rc != -1 ) {
+                       rc = first_rc;
+
+               } else {
+                       rc = SLAP_CB_CONTINUE;
+               }
+       }
+
        return rc;
 }
 
@@ -489,7 +717,9 @@ static int
 ldap_chain_response( Operation *op, SlapReply *rs )
 {
        slap_overinst   *on = (slap_overinst *)op->o_bd->bd_info;
-       void            *private = op->o_bd->be_private;
+       ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
+       BackendDB       db, *bd = op->o_bd;
+       ldap_chain_cb_t lb = { 0 };
        slap_callback   *sc = op->o_callback,
                        sc2 = { 0 };
        int             rc = 0;
@@ -497,9 +727,9 @@ ldap_chain_response( Operation *op, SlapReply *rs )
        BerVarray       ref;
        struct berval   ndn = op->o_ndn;
 
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        int             sr_err = rs->sr_err;
        slap_reply_t    sr_type = rs->sr_type;
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        slap_mask_t     chain_mask = 0;
        ber_len_t       chain_shift = 0;
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
@@ -544,12 +774,18 @@ ldap_chain_response( Operation *op, SlapReply *rs )
         *   e) what ssf
         */
 
+       db = *op->o_bd;
+       SLAP_DBFLAGS( &db ) &= ~SLAP_DBFLAG_MONITORING;
+       op->o_bd = &db;
+
        matched = rs->sr_matched;
        rs->sr_matched = NULL;
        ref = rs->sr_ref;
        rs->sr_ref = NULL;
 
        /* we need this to know if back-ldap returned any result */
+       lb.lb_lc = lc;
+       sc2.sc_private = &lb;
        sc2.sc_response = ldap_chain_cb_response;
        op->o_callback = &sc2;
 
@@ -570,30 +806,30 @@ ldap_chain_response( Operation *op, SlapReply *rs )
                /* FIXME: can we really get a referral for binds? */
                op->o_req_ndn = slap_empty_bv;
                op->o_conn = NULL;
-               rc = ldap_chain_op( op, rs, lback->bi_op_bind, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_bind, ref, 0 );
                op->o_req_ndn = rndn;
                op->o_conn = conn;
                }
                break;
 
        case LDAP_REQ_ADD:
-               rc = ldap_chain_op( op, rs, lback->bi_op_add, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_add, ref, 0 );
                break;
 
        case LDAP_REQ_DELETE:
-               rc = ldap_chain_op( op, rs, lback->bi_op_delete, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_delete, ref, 0 );
                break;
 
        case LDAP_REQ_MODRDN:
-               rc = ldap_chain_op( op, rs, lback->bi_op_modrdn, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_modrdn, ref, 0 );
                break;
 
        case LDAP_REQ_MODIFY:
-               rc = ldap_chain_op( op, rs, lback->bi_op_modify, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_modify, ref, 0 );
                break;
 
        case LDAP_REQ_COMPARE:
-               rc = ldap_chain_op( op, rs, lback->bi_op_compare, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_op_compare, ref, 0 );
                if ( rs->sr_err == LDAP_COMPARE_TRUE || rs->sr_err == LDAP_COMPARE_FALSE ) {
                        rc = LDAP_SUCCESS;
                }
@@ -601,167 +837,33 @@ ldap_chain_response( Operation *op, SlapReply *rs )
 
        case LDAP_REQ_SEARCH:
                if ( rs->sr_type == REP_SEARCHREF ) {
-                       ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
-                       ldapinfo_t      li = *lc->lc_common_li, *lip = NULL;
-                       struct berval   bvuri[ 2 ] = { { 0 } };
-
-                       struct berval   *curr = ref,
-                                       odn = op->o_req_dn,
-                                       ondn = op->o_req_ndn;
-
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-                       LDAPControl     **ctrls = NULL;
-       
-                       (void)chaining_control_add( lc, op, &ctrls );
-#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-
-                       rs->sr_type = REP_SEARCH;
-
-                       sc2.sc_response = ldap_chain_cb_search_response;
-
-                       /* if we parse the URI then by no means 
-                        * we can cache stuff or reuse connections, 
-                        * because in back-ldap there's no caching
-                        * based on the URI value, which is supposed
-                        * to be set once for all (correct?) */
-                       li.li_bvuri = bvuri;
-                       for ( ; !BER_BVISNULL( &curr[0] ); curr++ ) {
-                               LDAPURLDesc     *srv;
-                               char            *save_dn;
-                               int             temporary = 0;
-
-                               /* parse reference and use
-                                * proto://[host][:port]/ only */
-                               rc = ldap_url_parse_ext( curr[0].bv_val, &srv );
-                               if ( rc != LDAP_URL_SUCCESS ) {
-                                       /* try next */
-                                       rs->sr_err = LDAP_OTHER;
-                                       continue;
-                               }
-
-                               /* remove DN essentially because later on 
-                                * ldap_initialize() will parse the URL 
-                                * as a comma-separated URL list */
-                               save_dn = srv->lud_dn;
-                               srv->lud_dn = "";
-                               srv->lud_scope = LDAP_SCOPE_DEFAULT;
-                               li.li_uri = ldap_url_desc2str( srv );
-                               if ( li.li_uri != NULL ) {
-                                       ber_str2bv_x( save_dn, 0, 1, &op->o_req_dn,
-                                                       op->o_tmpmemctx );
-                                       ber_dupbv_x( &op->o_req_ndn, &op->o_req_dn,
-                                                       op->o_tmpmemctx );
-                               }
-
-                               srv->lud_dn = save_dn;
-                               ldap_free_urldesc( srv );
-
-                               if ( li.li_uri == NULL ) {
-                                       /* try next */
-                                       rs->sr_err = LDAP_OTHER;
-                                       continue;
-                               }
-
-                               ber_str2bv( li.li_uri, 0, 0, &li.li_bvuri[ 0 ] );
-
-                               /* Searches for a ldapinfo in the avl tree */
-                               ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
-                               lip = (ldapinfo_t *)avl_find( lc->lc_lai.lai_tree, 
-                                       (caddr_t)&li, ldap_chain_uri_cmp );
-                               ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );
-
-                               if ( lip != NULL ) {
-                                       op->o_bd->be_private = (void *)lip;
-
-                               } else {
-                                       /* if none is found, create a temporary... */
-                                       rc = ldap_chain_db_init_one( op->o_bd );
-                                       if ( rc != 0 ) {
-                                               goto cleanup;
-                                       }
-                                       lip = (ldapinfo_t *)op->o_bd->be_private;
-                                       lip->li_uri = li.li_uri;
-                                       lip->li_bvuri = bvuri;
-                                       rc = ldap_chain_db_open_one( op->o_bd );
-                                       if ( rc != 0 ) {
-                                               (void)ldap_chain_db_destroy_one( op->o_bd );
-                                               goto cleanup;
-                                       }
-
-                                       if ( LDAP_CHAIN_CACHE_URI( lc ) ) {
-                                               ldap_pvt_thread_mutex_lock( &lc->lc_lai.lai_mutex );
-                                               if ( avl_insert( &lc->lc_lai.lai_tree,
-                                                       (caddr_t)lip, ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
-                                               {
-                                                       /* someone just inserted another;
-                                                        * don't bother, use this and then
-                                                        * just free it */
-                                                       temporary = 1;
-                                               }
-                                               ldap_pvt_thread_mutex_unlock( &lc->lc_lai.lai_mutex );
-               
-                                       } else {
-                                               temporary = 1;
-                                       }
-                               }
-
-                               /* FIXME: should we also copy filter and scope?
-                                * according to RFC3296, no */
-                               rc = lback->bi_op_search( op, rs );
-
-cleanup:;
-                               ldap_memfree( li.li_uri );
-                               li.li_uri = NULL;
-
-                               op->o_tmpfree( op->o_req_dn.bv_val,
-                                               op->o_tmpmemctx );
-                               op->o_tmpfree( op->o_req_ndn.bv_val,
-                                               op->o_tmpmemctx );
-
-                               if ( temporary ) {
-                                       lip->li_uri = NULL;
-                                       lip->li_bvuri = NULL;
-                                       (void)ldap_chain_db_close_one( op->o_bd );
-                                       (void)ldap_chain_db_destroy_one( op->o_bd );
-                               }
-               
-                               if ( rc == LDAP_SUCCESS && rs->sr_err == LDAP_SUCCESS ) {
-                                       break;
-                               }
-
-                               rc = rs->sr_err;
-                       }
-
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-                       (void)chaining_control_remove( op, &ctrls );
-#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-
-                       op->o_req_dn = odn;
-                       op->o_req_ndn = ondn;
-                       rs->sr_type = REP_SEARCHREF;
-                       rs->sr_entry = NULL;
+                       rc = ldap_chain_search( op, rs, ref, 0 );
+                       
+               } else {
+                       /* we might get here before any database actually 
+                        * performed a search; in those cases, we need
+                        * to check limits, to make sure safe defaults
+                        * are in place */
+                       if ( op->ors_limit != NULL || limits_check( op, rs ) == 0 ) {
+                               rc = ldap_chain_op( op, rs, lback->bi_op_search, ref, 0 );
 
-                       if ( rc != LDAP_SUCCESS ) {
-                               /* couldn't chase any of the referrals */
+                       } else {
                                rc = SLAP_CB_CONTINUE;
                        }
-                       
-               } else {
-                       rc = ldap_chain_op( op, rs, lback->bi_op_search, ref );
                }
                break;
 
        case LDAP_REQ_EXTENDED:
-               rc = ldap_chain_op( op, rs, lback->bi_extended, ref );
+               rc = ldap_chain_op( op, rs, lback->bi_extended, ref, 0 );
                /* FIXME: ldap_back_extended() by design 
                 * doesn't send result; frontend is expected
                 * to send it... */
-               /* FIXME: what aboit chaining? */
+               /* FIXME: what about chaining? */
                if ( rc != SLAPD_ABANDON ) {
                        send_ldap_extended( op, rs );
                        rc = LDAP_SUCCESS;
                }
-               sc2.sc_private = LDAP_CH_RES;
+               lb.lb_status = LDAP_CH_RES;
                break;
 
        default:
@@ -776,12 +878,18 @@ cleanup:;
        case LDAP_SUCCESS:
        case LDAP_REFERRAL:
                /* slapd-ldap sent response */
-               assert( sc2.sc_private == LDAP_CH_RES );
+               if ( !op->o_abandon && lb.lb_status != LDAP_CH_RES ) {
+                       /* FIXME: should we send response? */
+                       Debug( LDAP_DEBUG_ANY,
+                               "%s: ldap_chain_response: "
+                               "overlay should have sent result.\n",
+                               op->o_log_prefix, 0, 0 );
+               }
                break;
 
        default:
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-               if ( sc2.sc_private == LDAP_CH_ERR && rs->sr_err == LDAP_X_CANNOT_CHAIN ) {
+               if ( lb.lb_status == LDAP_CH_ERR && rs->sr_err == LDAP_X_CANNOT_CHAIN ) {
                        goto cannot_chain;
                }
 
@@ -795,31 +903,35 @@ cannot_chain:;
 
                default:
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-                       rc = SLAP_CB_CONTINUE;
-                       rs->sr_err = sr_err;
-                       rs->sr_type = sr_type;
-                       rs->sr_matched = matched;
-                       rs->sr_ref = ref;
+                       if ( LDAP_CHAIN_RETURN_ERR( lc ) ) {
+                               rs->sr_err = rc;
+                               rs->sr_type = sr_type;
+
+                       } else {
+                               rc = SLAP_CB_CONTINUE;
+                               rs->sr_err = sr_err;
+                               rs->sr_type = sr_type;
+                               rs->sr_matched = matched;
+                               rs->sr_ref = ref;
+                       }
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                        break;
                }
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
        }
 
-       if ( sc2.sc_private == LDAP_CH_NONE && rc != SLAPD_ABANDON ) {
+       if ( lb.lb_status == LDAP_CH_NONE && rc != SLAPD_ABANDON ) {
                op->o_callback = NULL;
                rc = rs->sr_err = slap_map_api2result( rs );
                send_ldap_result( op, rs );
        }
 
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
 dont_chain:;
-#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
        rs->sr_err = sr_err;
        rs->sr_type = sr_type;
        rs->sr_matched = matched;
        rs->sr_ref = ref;
-       op->o_bd->be_private = private;
+       op->o_bd = bd;
        op->o_callback = sc;
        op->o_ndn = ndn;
 
@@ -859,14 +971,14 @@ str2chain( const char *s )
 
 enum {
        CH_CHAINING = 1,
-       CH_CACHE_URI = 2,
+       CH_CACHE_URI,
+       CH_MAX_DEPTH,
+       CH_RETURN_ERR,
 
        CH_LAST
 };
 
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
 static ConfigDriver chain_cf_gen;
-#endif
 static ConfigCfAdd chain_cfadd;
 static ConfigLDAPadd chain_ldadd;
 
@@ -878,25 +990,40 @@ static ConfigTable chaincfg[] = {
                        "DESC 'Chaining behavior control parameters (draft-sermersheim-ldap-chaining)' "
                        "SYNTAX OMsDirectoryString SINGLE-VALUE )", NULL, NULL },
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-       { "chain-cache-uris", "TRUE/FALSE",
+       { "chain-cache-uri", "TRUE/FALSE",
                2, 2, 0, ARG_MAGIC|ARG_ON_OFF|CH_CACHE_URI, chain_cf_gen,
-               "( OLcfgOvAt:3.2 NAME 'olcCacheURIs' "
+               "( OLcfgOvAt:3.2 NAME 'olcChainCacheURI' "
                        "DESC 'Enables caching of URIs not present in configuration' "
                        "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
+       { "chain-max-depth", "args",
+               2, 2, 0, ARG_MAGIC|ARG_INT|CH_MAX_DEPTH, chain_cf_gen,
+               "( OLcfgOvAt:3.3 NAME 'olcChainMaxReferralDepth' "
+                       "DESC 'max referral depth' "
+                       "SYNTAX OMsInteger "
+                       "EQUALITY integerMatch "
+                       "SINGLE-VALUE )", NULL, NULL },
+       { "chain-return-error", "TRUE/FALSE",
+               2, 2, 0, ARG_MAGIC|ARG_ON_OFF|CH_RETURN_ERR, chain_cf_gen,
+               "( OLcfgOvAt:3.4 NAME 'olcChainReturnError' "
+                       "DESC 'Errors are returned instead of the original referral' "
+                       "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
        { NULL, NULL, 0, 0, 0, ARG_IGNORED }
 };
 
 static ConfigOCs chainocs[] = {
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        { "( OLcfgOvOc:3.1 "
                "NAME 'olcChainConfig' "
                "DESC 'Chain configuration' "
                "SUP olcOverlayConfig "
-               "MAY ( olcChainingBehavior "
-                       "$ olcCacheURIs "
+               "MAY ( "
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
+                       "olcChainingBehavior $ "
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+                       "olcChainCacheURI $ "
+                       "olcChainMaxReferralDepth $ "
+                       "olcChainReturnError "
                        ") )",
                Cft_Overlay, chaincfg, NULL, chain_cfadd },
-#endif
        { "( OLcfgOvOc:3.2 "
                "NAME 'olcChainDatabase' "
                "DESC 'Chain remote server configuration' "
@@ -908,6 +1035,17 @@ static ConfigOCs chainocs[] = {
 static int
 chain_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
 {
+       slap_overinst           *on;
+       ldap_chain_t            *lc;
+
+       ldapinfo_t              *li;
+
+       AttributeDescription    *ad = NULL;
+       Attribute               *at;
+       const char              *text;
+
+       int                     rc;
+
        if ( p->ce_type != Cft_Overlay
                || !p->ce_bi
                || p->ce_bi->bi_cf_ocs != chainocs )
@@ -915,7 +1053,80 @@ chain_ldadd( CfEntryInfo *p, Entry *e, ConfigArgs *ca )
                return LDAP_CONSTRAINT_VIOLATION;
        }
 
-       return LDAP_SUCCESS;
+       on = (slap_overinst *)p->ce_bi;
+       lc = (ldap_chain_t *)on->on_bi.bi_private;
+
+       assert( ca->be == NULL );
+       ca->be = (BackendDB *)ch_calloc( 1, sizeof( BackendDB ) );
+
+       ca->be->bd_info = (BackendInfo *)on;
+
+       rc = slap_str2ad( "olcDbURI", &ad, &text );
+       assert( rc == LDAP_SUCCESS );
+
+       at = attr_find( e->e_attrs, ad );
+       if ( lc->lc_common_li == NULL && at != NULL ) {
+               /* FIXME: we should generate an empty default entry
+                * if none is supplied */
+               Debug( LDAP_DEBUG_ANY, "slapd-chain: "
+                       "first underlying database \"%s\" "
+                       "cannot contain attribute \"%s\".\n",
+                       e->e_name.bv_val, ad->ad_cname.bv_val, 0 );
+               rc = LDAP_CONSTRAINT_VIOLATION;
+               goto done;
+
+       } else if ( lc->lc_common_li != NULL && at == NULL ) {
+               /* FIXME: we should generate an empty default entry
+                * if none is supplied */
+               Debug( LDAP_DEBUG_ANY, "slapd-chain: "
+                       "subsequent underlying database \"%s\" "
+                       "must contain attribute \"%s\".\n",
+                       e->e_name.bv_val, ad->ad_cname.bv_val, 0 );
+               rc = LDAP_CONSTRAINT_VIOLATION;
+               goto done;
+       }
+
+       if ( lc->lc_common_li == NULL ) {
+               rc = ldap_chain_db_init_common( ca->be );
+
+       } else {
+               rc = ldap_chain_db_init_one( ca->be );
+       }
+
+       if ( rc != 0 ) {
+               Debug( LDAP_DEBUG_ANY, "slapd-chain: "
+                       "unable to init %sunderlying database \"%s\".\n",
+                       lc->lc_common_li == NULL ? "common " : "", e->e_name.bv_val, 0 );
+               return LDAP_CONSTRAINT_VIOLATION;
+       }
+
+       li = ca->be->be_private;
+
+       if ( lc->lc_common_li == NULL ) {
+               lc->lc_common_li = li;
+
+       } else {
+               li->li_uri = ch_strdup( at->a_vals[ 0 ].bv_val );
+               value_add_one( &li->li_bvuri, &at->a_vals[ 0 ] );
+               if ( avl_insert( &lc->lc_lai.lai_tree, (caddr_t)li,
+                       ldap_chain_uri_cmp, ldap_chain_uri_dup ) )
+               {
+                       Debug( LDAP_DEBUG_ANY, "slapd-chain: "
+                               "database \"%s\" insert failed.\n",
+                               e->e_name.bv_val, 0, 0 );
+                       rc = LDAP_CONSTRAINT_VIOLATION;
+                       goto done;
+               }
+       }
+
+done:;
+       if ( rc != LDAP_SUCCESS ) {
+               (void)ldap_chain_db_destroy_one( ca->be );
+               ch_free( ca->be );
+               ca->be = NULL;
+       }
+
+       return rc;
 }
 
 typedef struct ldap_chain_cfadd_apply_t {
@@ -963,7 +1174,7 @@ chain_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
                lca.rs = rs;
                lca.p = p;
                lca.ca = ca;
-               lca.count = -1;
+               lca.count = 0;
 
                (void)ldap_chain_cfadd_apply( (void *)lc->lc_common_li, (void *)&lca );
 
@@ -977,7 +1188,6 @@ chain_cfadd( Operation *op, SlapReply *rs, Entry *p, ConfigArgs *ca )
 }
 
 #ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-
 static slap_verbmasks chaining_mode[] = {
        { BER_BVC("referralsRequired"),         LDAP_REFERRALS_REQUIRED },
        { BER_BVC("referralsPreferred"),        LDAP_REFERRALS_PREFERRED },
@@ -985,14 +1195,13 @@ static slap_verbmasks chaining_mode[] = {
        { BER_BVC("chainingPreferred"),         LDAP_CHAINING_PREFERRED },
        { BER_BVNULL,                           0 }
 };
+#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
 static int
 chain_cf_gen( ConfigArgs *c )
 {
        slap_overinst   *on = (slap_overinst *)c->bi;
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
-#endif
 
        int             rc = 0;
 
@@ -1034,6 +1243,14 @@ chain_cf_gen( ConfigArgs *c )
                        c->value_int = LDAP_CHAIN_CACHE_URI( lc );
                        break;
 
+               case CH_MAX_DEPTH:
+                       c->value_int = lc->lc_max_depth;
+                       break;
+
+               case CH_RETURN_ERR:
+                       c->value_int = LDAP_CHAIN_RETURN_ERR( lc );
+                       break;
+
                default:
                        assert( 0 );
                        rc = 1;
@@ -1049,6 +1266,14 @@ chain_cf_gen( ConfigArgs *c )
                        lc->lc_flags &= ~LDAP_CHAIN_F_CACHE_URI;
                        break;
 
+               case CH_MAX_DEPTH:
+                       c->value_int = 0;
+                       break;
+
+               case CH_RETURN_ERR:
+                       lc->lc_flags &= ~LDAP_CHAIN_F_RETURN_ERR;
+                       break;
+
                default:
                        return 1;
                }
@@ -1056,8 +1281,8 @@ chain_cf_gen( ConfigArgs *c )
        }
 
        switch( c->type ) {
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        case CH_CHAINING: {
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
                char                    **argv = c->argv;
                int                     argc = c->argc;
                BerElementBuffer        berbuf;
@@ -1074,20 +1299,20 @@ chain_cf_gen( ConfigArgs *c )
                        if ( strncasecmp( argv[ 0 ], "resolve=", STRLENOF( "resolve=" ) ) == 0 ) {
                                resolve = str2chain( argv[ 0 ] + STRLENOF( "resolve=" ) );
                                if ( resolve == -1 ) {
-                                       fprintf( stderr, "%s line %d: "
+                                       Debug( LDAP_DEBUG_ANY, "%s: "
                                                "illegal <resolve> value %s "
-                                               "in \"chain-chaining>\"\n",
-                                               c->fname, c->lineno, argv[ 0 ] );
+                                               "in \"chain-chaining>\".\n",
+                                               c->log, argv[ 0 ], 0 );
                                        return 1;
                                }
 
                        } else if ( strncasecmp( argv[ 0 ], "continuation=", STRLENOF( "continuation=" ) ) == 0 ) {
                                continuation = str2chain( argv[ 0 ] + STRLENOF( "continuation=" ) );
                                if ( continuation == -1 ) {
-                                       fprintf( stderr, "%s line %d: "
+                                       Debug( LDAP_DEBUG_ANY, "%s: "
                                                "illegal <continuation> value %s "
-                                               "in \"chain-chaining\"\n",
-                                               c->fname, c->lineno, argv[ 0 ] );
+                                               "in \"chain-chaining\".\n",
+                                               c->log, argv[ 0 ], 0 );
                                        return 1;
                                }
 
@@ -1095,9 +1320,9 @@ chain_cf_gen( ConfigArgs *c )
                                iscritical = 1;
 
                        } else {
-                               fprintf( stderr, "%s line %d: "
-                                       "unknown option in \"chain-chaining\"\n",
-                                       c->fname, c->lineno );
+                               Debug( LDAP_DEBUG_ANY, "%s: "
+                                       "unknown option in \"chain-chaining\".\n",
+                                       c->log, 0, 0 );
                                return 1;
                        }
                }
@@ -1115,9 +1340,9 @@ chain_cf_gen( ConfigArgs *c )
                        err = ber_printf( ber, "{e" /* } */, resolve );
                        if ( err == -1 ) {
                                ber_free( ber, 1 );
-                               fprintf( stderr, "%s line %d: "
+                               Debug( LDAP_DEBUG_ANY, "%s: "
                                        "chaining behavior control encoding error!\n",
-                                       c->fname, c->lineno );
+                                       c->log, 0, 0 );
                                return 1;
                        }
 
@@ -1125,9 +1350,9 @@ chain_cf_gen( ConfigArgs *c )
                                err = ber_printf( ber, "e", continuation );
                                if ( err == -1 ) {
                                        ber_free( ber, 1 );
-                                       fprintf( stderr, "%s line %d: "
+                                       Debug( LDAP_DEBUG_ANY, "%s: "
                                                "chaining behavior control encoding error!\n",
-                                               c->fname, c->lineno );
+                                               c->log, 0, 0 );
                                        return 1;
                                }
                        }
@@ -1135,9 +1360,9 @@ chain_cf_gen( ConfigArgs *c )
                        err = ber_printf( ber, /* { */ "N}" );
                        if ( err == -1 ) {
                                ber_free( ber, 1 );
-                               fprintf( stderr, "%s line %d: "
+                               Debug( LDAP_DEBUG_ANY, "%s: "
                                        "chaining behavior control encoding error!\n",
-                                       c->fname, c->lineno );
+                                       c->log, 0, 0 );
                                return 1;
                        }
 
@@ -1154,10 +1379,9 @@ chain_cf_gen( ConfigArgs *c )
 
                if ( ldap_chain_parse_ctrl( &op, &rs, &lc->lc_chaining_ctrl ) != LDAP_SUCCESS )
                {
-                       fprintf( stderr, "%s line %d: "
-                               "unable to parse chaining control%s%s\n",
-                               c->fname, c->lineno,
-                               rs.sr_text ? ": " : "",
+                       Debug( LDAP_DEBUG_ANY, "%s: "
+                               "unable to parse chaining control%s%s.\n",
+                               c->log, rs.sr_text ? ": " : "",
                                rs.sr_text ? rs.sr_text : "" );
                        return 1;
                }
@@ -1167,10 +1391,12 @@ chain_cf_gen( ConfigArgs *c )
                lc->lc_flags |= LDAP_CHAIN_F_CHAINING;
 
                rc = 0;
-
-               break;
-       }
+#else /* ! LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+               Debug( LDAP_DEBUG_ANY, "%s: "
+                       "\"chaining\" control unsupported (ignored).\n",
+                       c->log, 0, 0 );
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
+               } break;
 
        case CH_CACHE_URI:
                if ( c->value_int ) {
@@ -1180,6 +1406,26 @@ chain_cf_gen( ConfigArgs *c )
                }
                break;
 
+       case CH_MAX_DEPTH:
+               if ( c->value_int < 0 ) {
+                       snprintf( c->msg, sizeof( c->msg ),
+                               "<%s> invalid max referral depth %d",
+                               c->argv[0], c->value_int );
+                       Debug( LDAP_DEBUG_ANY, "%s: %s.\n",
+                               c->log, c->msg, 0 );
+                       rc = 1;
+                       break;
+               }
+               lc->lc_max_depth = c->value_int;
+
+       case CH_RETURN_ERR:
+               if ( c->value_int ) {
+                       lc->lc_flags |= LDAP_CHAIN_F_RETURN_ERR;
+               } else {
+                       lc->lc_flags &= ~LDAP_CHAIN_F_RETURN_ERR;
+               }
+               break;
+
        default:
                assert( 0 );
                return 1;
@@ -1187,34 +1433,38 @@ chain_cf_gen( ConfigArgs *c )
        return rc;
 }
 
-#endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
-
 static int
 ldap_chain_db_init(
        BackendDB *be )
 {
        slap_overinst   *on = (slap_overinst *)be->bd_info;
        ldap_chain_t    *lc = NULL;
-       int             rc;
-       BackendDB       bd = *be;
 
        if ( lback == NULL ) {
+               static BackendInfo      lback2;
+
                lback = backend_info( "ldap" );
 
                if ( lback == NULL ) {
-                       return -1;
+                       return 1;
                }
+
+               lback2 = *lback;
+               lback2.bi_type = ldapchain.on_bi.bi_type;
+               lback = &lback2;
        }
 
        lc = ch_malloc( sizeof( ldap_chain_t ) );
+       if ( lc == NULL ) {
+               return 1;
+       }
        memset( lc, 0, sizeof( ldap_chain_t ) );
+       lc->lc_max_depth = 1;
+       ldap_pvt_thread_mutex_init( &lc->lc_lai.lai_mutex );
 
-       bd.be_private = NULL;
-       rc = lback->bi_db_init( &bd );
-       lc->lc_cfg_li = lc->lc_common_li = (ldapinfo_t *)bd.be_private;
        on->on_bi.bi_private = (void *)lc;
 
-       return rc;
+       return 0;
 }
 
 static int
@@ -1230,30 +1480,74 @@ ldap_chain_db_config(
 
        int             rc = SLAP_CONF_UNKNOWN;
                
-       /* Something for the cache database? */
+       if ( lc->lc_common_li == NULL ) {
+               void    *be_private = be->be_private;
+               ldap_chain_db_init_common( be );
+               lc->lc_common_li = lc->lc_cfg_li = (ldapinfo_t *)be->be_private;
+               be->be_private = be_private;
+       }
+
+       /* Something for the chain database? */
        if ( strncasecmp( argv[ 0 ], "chain-", STRLENOF( "chain-" ) ) == 0 ) {
                char            *save_argv0 = argv[ 0 ];
-               BackendInfo     *bd_info = bd_info;
+               BackendInfo     *bd_info = be->bd_info;
                void            *be_private = be->be_private;
                ConfigOCs       *be_cf_ocs = be->be_cf_ocs;
-               int             is_uri = 0;
+               static char     *allowed_argv[] = {
+                       /* special: put URI here, so in the meanwhile
+                        * it detects whether a new URI is being provided */
+                       "uri",
+                       "nretries",
+                       "timeout",
+                       /* flags */
+                       "tls",
+                       /* FIXME: maybe rebind-as-user should be allowed
+                        * only within known URIs... */
+                       "rebind-as-user",
+                       "chase-referrals",
+                       "t-f-support",
+                       "proxy-whoami",
+                       NULL
+               };
+               int             which_argv = -1;
 
                argv[ 0 ] += STRLENOF( "chain-" );
 
-               /* TODO: create a new structure and, after parsing the URI,
-                * put it in the lc->lc_lai tree */
-               if ( strcasecmp( argv[ 0 ], "uri" ) == 0 ) {
+               for ( which_argv = 0; allowed_argv[ which_argv ]; which_argv++ ) {
+                       if ( strcasecmp( argv[ 0 ], allowed_argv[ which_argv ] ) == 0 ) {
+                               break;
+                       }
+               }
+
+               if ( allowed_argv[ which_argv ] == NULL ) {
+                       which_argv = -1;
+
+                       if ( lc->lc_cfg_li == lc->lc_common_li ) {
+                               Debug( LDAP_DEBUG_ANY, "%s: line %d: "
+                                       "\"%s\" only allowed within a URI directive.\n.",
+                                       fname, lineno, argv[ 0 ] );
+                               return 1;
+                       }
+               }
+
+               if ( which_argv == 0 ) {
                        rc = ldap_chain_db_init_one( be );
                        if ( rc != 0 ) {
                                Debug( LDAP_DEBUG_ANY, "%s: line %d: "
-                                       "underlying slapd-ldap initialization failed\n.",
+                                       "underlying slapd-ldap initialization failed.\n.",
                                        fname, lineno, 0 );
                                return 1;
                        }
                        lc->lc_cfg_li = be->be_private;
-                       is_uri = 1;
                }
 
+               /* TODO: add checks on what other slapd-ldap(5) args
+                * should be put in the template; this is not quite
+                * harmful, because attributes that shouldn't don't
+                * get actually used, but the user should at least
+                * be warned.
+                */
+
                be->bd_info = lback;
                be->be_private = (void *)lc->lc_cfg_li;
                be->be_cf_ocs = lback->bi_cf_ocs;
@@ -1265,7 +1559,7 @@ ldap_chain_db_config(
                be->be_private = be_private;
                be->bd_info = bd_info;
 
-               if ( is_uri ) {
+               if ( which_argv == 0 ) {
 private_destroy:;
                        if ( rc != 0 ) {
                                BackendDB               db = *be;
@@ -1342,7 +1636,7 @@ ldap_chain_db_func(
        if ( lc ) {
                BI_db_func      *func = (&lback->bi_db_open)[ which ];
 
-               if ( func != NULL ) {
+               if ( func != NULL && lc->lc_common_li != NULL ) {
                        BackendDB               db = *be;
 
                        db.bd_info = lback;
@@ -1374,19 +1668,32 @@ static int
 ldap_chain_db_open(
        BackendDB       *be )
 {
-#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
-       int     rc = 0;
+       slap_overinst   *on = (slap_overinst *) be->bd_info;
+       ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
+       slap_mask_t     monitoring;
+       int             rc = 0;
 
+#ifdef LDAP_CONTROL_X_CHAINING_BEHAVIOR
        rc = overlay_register_control( be, LDAP_CONTROL_X_CHAINING_BEHAVIOR );
        if ( rc != 0 ) {
                return rc;
        }
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
-       /* FIXME: right now slapd-ldap has no open function;
-        * in case one is introduced, this needs be fixed */
+       if ( lc->lc_common_li == NULL ) {
+               void    *be_private = be->be_private;
+               ldap_chain_db_init_common( be );
+               lc->lc_common_li = lc->lc_cfg_li = (ldapinfo_t *)be->be_private;
+               be->be_private = be_private;
+       }
+
+       /* filter out and restore monitoring */
+       monitoring = ( SLAP_DBFLAGS( be ) & SLAP_DBFLAG_MONITORING );
+       SLAP_DBFLAGS( be ) &= ~SLAP_DBFLAG_MONITORING;
+       rc = ldap_chain_db_func( be, db_open );
+       SLAP_DBFLAGS( be ) |= monitoring;
 
-       return ldap_chain_db_func( be, db_open );
+       return rc;
 }
 
 static int
@@ -1408,12 +1715,49 @@ ldap_chain_db_destroy(
        rc = ldap_chain_db_func( be, db_destroy );
 
        if ( lc ) {
+               avl_free( lc->lc_lai.lai_tree, NULL );
+               ldap_pvt_thread_mutex_destroy( &lc->lc_lai.lai_mutex );
                ch_free( lc );
        }
 
        return rc;
 }
 
+/*
+ * inits one instance of the slapd-ldap backend, and stores
+ * the private info in be_private of the arg
+ */
+static int
+ldap_chain_db_init_common(
+       BackendDB       *be )
+{
+       BackendInfo     *bi = be->bd_info;
+       ldapinfo_t      *li;
+       int             rc;
+
+       be->bd_info = lback;
+       be->be_private = NULL;
+       rc = lback->bi_db_init( be );
+       if ( rc != 0 ) {
+               return rc;
+       }
+       li = (ldapinfo_t *)be->be_private;
+       li->li_urllist_f = NULL;
+       li->li_urllist_p = NULL;
+
+       be->bd_info = bi;
+
+       return 0;
+}
+
+/*
+ * inits one instance of the slapd-ldap backend, stores
+ * the private info in be_private of the arg and fills
+ * selected fields with data from the template.
+ *
+ * NOTE: add checks about the other fields of the template,
+ * which are ignored and SHOULD NOT be configured by the user.
+ */
 static int
 ldap_chain_db_init_one(
        BackendDB       *be )
@@ -1421,31 +1765,60 @@ ldap_chain_db_init_one(
        slap_overinst   *on = (slap_overinst *)be->bd_info;
        ldap_chain_t    *lc = (ldap_chain_t *)on->on_bi.bi_private;
 
-       BackendDB       db = *be;
-       int             t;
+       BackendInfo     *bi = be->bd_info;
        ldapinfo_t      *li;
 
-       db.bd_info = lback;
-       db.be_private = NULL;
-       t = lback->bi_db_init( &db );
+       slap_op_t       t;
+
+       be->bd_info = lback;
+       be->be_private = NULL;
+       t = lback->bi_db_init( be );
        if ( t != 0 ) {
                return t;
        }
-       li = (ldapinfo_t *)db.be_private;
+       li = (ldapinfo_t *)be->be_private;
+       li->li_urllist_f = NULL;
+       li->li_urllist_p = NULL;
 
        /* copy common data */
        li->li_nretries = lc->lc_common_li->li_nretries;
        li->li_flags = lc->lc_common_li->li_flags;
        li->li_version = lc->lc_common_li->li_version;
-       for ( t = 0; t < LDAP_BACK_OP_LAST; t++ ) {
+       for ( t = 0; t < SLAP_OP_LAST; t++ ) {
                li->li_timeout[ t ] = lc->lc_common_li->li_timeout[ t ];
        }
-
-       be->be_private = li;
+       be->bd_info = bi;
 
        return 0;
 }
 
+static int
+ldap_chain_db_open_one(
+       BackendDB       *be )
+{
+       if ( SLAP_DBMONITORING( be ) ) {
+               ldapinfo_t      *li = (ldapinfo_t *)be->be_private;
+
+               if ( li->li_uri == NULL ) {
+                       ber_str2bv( "cn=Common Connections", 0, 1,
+                               &li->li_monitor_info.lmi_rdn );
+
+               } else {
+                       char            *ptr;
+
+                       li->li_monitor_info.lmi_rdn.bv_len
+                               = STRLENOF( "cn=" ) + strlen( li->li_uri );
+                       ptr = li->li_monitor_info.lmi_rdn.bv_val
+                               = ch_malloc( li->li_monitor_info.lmi_rdn.bv_len + 1 );
+                       ptr = lutil_strcopy( ptr, "cn=" );
+                       ptr = lutil_strcopy( ptr, li->li_uri );
+                       ptr[ 0 ] = '\0';
+               }
+       }
+
+       return lback->bi_db_open( be );
+}
+
 typedef struct ldap_chain_conn_apply_t {
        BackendDB       *be;
        Connection      *conn;
@@ -1614,10 +1987,8 @@ ldap_chain_parse_ctrl(
 }
 #endif /* LDAP_CONTROL_X_CHAINING_BEHAVIOR */
 
-static slap_overinst ldapchain;
-
 int
-chain_init( void )
+chain_initialize( void )
 {
        int     rc;
 
@@ -1630,7 +2001,7 @@ chain_init( void )
                        ldap_chain_parse_ctrl, &sc_chainingBehavior );
        if ( rc != LDAP_SUCCESS ) {
                Debug( LDAP_DEBUG_ANY, "slapd-chain: "
-                       "unable to register chaining behavior control: %d\n",
+                       "unable to register chaining behavior control: %d.\n",
                        rc, 0, 0 );
                return rc;
        }
@@ -1643,17 +2014,6 @@ chain_init( void )
        ldapchain.on_bi.bi_db_close = ldap_chain_db_close;
        ldapchain.on_bi.bi_db_destroy = ldap_chain_db_destroy;
 
-       /* ... otherwise the underlying backend's function would be called,
-        * likely passing an invalid entry; on the contrary, the requested
-        * operational attributes should have been returned while chasing
-        * the referrals.  This all in all is a bit messy, because part
-        * of the operational attributes are generated by the backend;
-        * part by the frontend; back-ldap should receive all the available
-        * ones from the remote server, but then, on its own, it strips those
-        * it assumes will be (re)generated by the frontend (e.g.
-        * subschemaSubentry.) */
-       ldapchain.on_bi.bi_operational = ldap_chain_operational;
-       
        ldapchain.on_bi.bi_connection_destroy = ldap_chain_connection_destroy;
 
        ldapchain.on_response = ldap_chain_response;