]> git.sur5r.net Git - openldap/blobdiff - servers/slapd/back-meta/conn.c
use result of validation (ITS#4028)
[openldap] / servers / slapd / back-meta / conn.c
index cfabeb17534f1b3dba1618e19cd48b425ae0a1d0..a0ae2801249fe69e0b607e747dff707e43900006 100644 (file)
@@ -24,6 +24,7 @@
 
 #include <stdio.h>
 
+#include <ac/errno.h>
 #include <ac/socket.h>
 #include <ac/string.h>
 
 int
 meta_back_conn_cmp(
        const void *c1,
-       const void *c2
-       )
+       const void *c2 )
 {
-       struct metaconn *lc1 = ( struct metaconn * )c1;
-        struct metaconn *lc2 = ( struct metaconn * )c2;
+       metaconn_t      *mc1 = ( metaconn_t * )c1;
+        metaconn_t     *mc2 = ( metaconn_t * )c2;
        
-       return SLAP_PTRCMP( lc1->mc_conn, lc2->mc_conn );
+       return SLAP_PTRCMP( mc1->mc_conn, mc2->mc_conn );
 }
 
 /*
@@ -65,13 +65,12 @@ meta_back_conn_cmp(
 int
 meta_back_conn_dup(
        void *c1,
-       void *c2
-       )
+       void *c2 )
 {
-       struct metaconn *lc1 = ( struct metaconn * )c1;
-       struct metaconn *lc2 = ( struct metaconn * )c2;
+       metaconn_t      *mc1 = ( metaconn_t * )c1;
+       metaconn_t      *mc2 = ( metaconn_t * )c2;
 
-       return( ( lc1->mc_conn == lc2->mc_conn ) ? -1 : 0 );
+       return( ( mc1->mc_conn == mc2->mc_conn ) ? -1 : 0 );
 }
 
 /*
@@ -93,7 +92,7 @@ ravl_print( Avlnode *root, int depth )
                printf( "    " );
        }
 
-       printf( "c(%d) %d\n", ( ( struct metaconn * )root->avl_data )->mc_conn->c_connid, root->avl_bf );
+       printf( "c(%d) %d\n", ( ( metaconn_t * )root->avl_data )->mc_conn->c_connid, root->avl_bf );
        
        ravl_print( root->avl_left, depth + 1 );
 }
@@ -121,93 +120,101 @@ myprint( Avlnode *root )
  * 
  * Allocates a connection structure, making room for all the referenced targets
  */
-static struct metaconn *
-metaconn_alloc( int ntargets )
+static metaconn_t *
+metaconn_alloc(
+               Operation               *op )
 {
-       struct metaconn *lc;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
+       metaconn_t      *mc;
+       int             i, ntargets = mi->mi_ntargets;
 
        assert( ntargets > 0 );
 
-       lc = ch_calloc( sizeof( struct metaconn ), 1 );
-       if ( lc == NULL ) {
+       /* malloc all in one */
+       mc = ( metaconn_t * )ch_malloc( sizeof( metaconn_t )
+                       + sizeof( metasingleconn_t ) * ntargets );
+       if ( mc == NULL ) {
                return NULL;
        }
-       
-       /*
-        * make it a null-terminated array ...
-        */
-       lc->mc_conns = ch_calloc( sizeof( struct metasingleconn ), ntargets + 1 );
-       if ( lc->mc_conns == NULL ) {
-               free( lc );
-               return NULL;
-       }
-
-       /* FIXME: needed by META_LAST() */
-       lc->mc_conns[ ntargets ].msc_candidate = META_LAST_CONN;
 
-       for ( ; ntargets-- > 0; ) {
-               lc->mc_conns[ ntargets ].msc_ld = NULL;
-               BER_BVZERO( &lc->mc_conns[ ntargets ].msc_bound_ndn );
-               BER_BVZERO( &lc->mc_conns[ ntargets ].msc_cred );
-               lc->mc_conns[ ntargets ].msc_bound = META_UNBOUND;
+       for ( i = 0; i < ntargets; i++ ) {
+               mc->mc_conns[ i ].msc_ld = NULL;
+               BER_BVZERO( &mc->mc_conns[ i ].msc_bound_ndn );
+               BER_BVZERO( &mc->mc_conns[ i ].msc_cred );
+               mc->mc_conns[ i ].msc_bound = META_UNBOUND;
+               mc->mc_conns[ i ].msc_info = mi;
        }
 
-       lc->mc_bound_target = META_BOUND_NONE;
+       mc->mc_auth_target = META_BOUND_NONE;
+       ldap_pvt_thread_mutex_init( &mc->mc_mutex );
+       mc->mc_refcnt = 1;
 
-       return lc;
+       return mc;
 }
 
 /*
- * metaconn_free
+ * meta_back_conn_free
  *
  * clears a metaconn
  */
+
+void
+meta_back_conn_free(
+       metaconn_t      *mc )
+{
+       assert( mc != NULL );
+       assert( mc->mc_refcnt == 0 );
+
+       ldap_pvt_thread_mutex_destroy( &mc->mc_mutex );
+       free( mc );
+}
+
 static void
-metaconn_free(
-               struct metaconn *lc
-)
+meta_back_freeconn(
+       Operation       *op,
+       metaconn_t      *mc )
 {
-       if ( !lc ) {
-               return;
-       }
-       
-       if ( lc->mc_conns ) {
-               ch_free( lc->mc_conns );
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
+
+       assert( mc != NULL );
+
+       ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+
+       if ( --mc->mc_refcnt == 0 ) {
+               meta_back_conn_free( mc );
        }
 
-       free( lc );
+       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
 }
 
 /*
- * init_one_conn
+ * meta_back_init_one_conn
  * 
  * Initializes one connection
  */
-static int
-init_one_conn(
-               Operation               *op,
-               SlapReply               *rs,
-               struct metatarget       *lt, 
-               struct metasingleconn   *lsc,
-               char                    *candidate,
-               ldap_back_send_t        sendok )
+int
+meta_back_init_one_conn(
+       Operation               *op,
+       SlapReply               *rs,
+       metatarget_t            *mt, 
+       metasingleconn_t        *msc,
+       ldap_back_send_t        sendok )
 {
-       struct metainfo *li = ( struct metainfo * )op->o_bd->be_private;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
        int             vers;
        dncookie        dc;
 
        /*
         * Already init'ed
         */
-       if ( lsc->msc_ld != NULL ) {
-               rs->sr_err = LDAP_SUCCESS;
-               goto error_return;
+       if ( msc->msc_ld != NULL ) {
+               return rs->sr_err = LDAP_SUCCESS;
        }
        
        /*
         * Attempts to initialize the connection to the target ds
         */
-       rs->sr_err = ldap_initialize( &lsc->msc_ld, lt->mt_uri );
+       rs->sr_err = ldap_initialize( &msc->msc_ld, mt->mt_uri );
        if ( rs->sr_err != LDAP_SUCCESS ) {
                goto error_return;
        }
@@ -217,39 +224,41 @@ init_one_conn(
         * bound with a particular version, then so can we.
         */
        vers = op->o_conn->c_protocol;
-       ldap_set_option( lsc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &vers );
+       ldap_set_option( msc->msc_ld, LDAP_OPT_PROTOCOL_VERSION, &vers );
 
        /* automatically chase referrals ("chase-referrals"/"dont-chase-referrals" statement) */
-       if ( LDAP_BACK_CHASE_REFERRALS( li ) ) {
-               ldap_set_option( lsc->msc_ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
+       if ( LDAP_BACK_CHASE_REFERRALS( mi ) ) {
+               ldap_set_option( msc->msc_ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
        }
 
 #ifdef HAVE_TLS
-       /* start TLS ("start-tls"/"try-start-tls" statements) */
-       if ( ( LDAP_BACK_USE_TLS( li ) || ( op->o_conn->c_is_tls && LDAP_BACK_PROPAGATE_TLS( li ) ) )
-                       && !ldap_is_ldaps_url( lt->mt_uri ) )
+       /* start TLS ("tls [try-]{start|propagate}" statement) */
+       if ( ( LDAP_BACK_USE_TLS( mi ) || ( op->o_conn->c_is_tls && LDAP_BACK_PROPAGATE_TLS( mi ) ) )
+                       && !ldap_is_ldaps_url( mt->mt_uri ) )
        {
 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
                /*
-                * use asynchronous StartTLS
-                * in case, chase referral (not implemented yet)
+                * use asynchronous StartTLS; in case, chase referral
+                * FIXME: OpenLDAP does not return referral on StartTLS yet
                 */
                int             msgid;
 
-               rs->sr_err = ldap_start_tls( lsc->msc_ld, NULL, NULL, &msgid );
+               rs->sr_err = ldap_start_tls( msc->msc_ld, NULL, NULL, &msgid );
                if ( rs->sr_err == LDAP_SUCCESS ) {
                        LDAPMessage     *res = NULL;
-                       int             rc, retries = 1;
+                       int             rc, nretries = mt->mt_nretries;
                        struct timeval  tv = { 0, 0 };
 
 retry:;
-                       rc = ldap_result( lsc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
+                       rc = ldap_result( msc->msc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
                        if ( rc < 0 ) {
                                rs->sr_err = LDAP_OTHER;
 
                        } else if ( rc == 0 ) {
-                               if ( retries ) {
-                                       retries--;
+                               if ( nretries != 0 ) {
+                                       if ( nretries > 0 ) {
+                                               nretries--;
+                                       }
                                        tv.tv_sec = 0;
                                        tv.tv_usec = 100000;
                                        goto retry;
@@ -259,10 +268,10 @@ retry:;
                        } else if ( rc == LDAP_RES_EXTENDED ) {
                                struct berval   *data = NULL;
 
-                               rs->sr_err = ldap_parse_extended_result( lsc->msc_ld, res,
+                               rs->sr_err = ldap_parse_extended_result( msc->msc_ld, res,
                                                NULL, &data, 0 );
                                if ( rs->sr_err == LDAP_SUCCESS ) {
-                                       rs->sr_err = ldap_result2error( lsc->msc_ld, res, 1 );
+                                       rs->sr_err = ldap_result2error( msc->msc_ld, res, 1 );
                                        res = NULL;
                                        
                                        /* FIXME: in case a referral 
@@ -270,7 +279,7 @@ retry:;
                                         * using it instead of the 
                                         * configured URI? */
                                        if ( rs->sr_err == LDAP_SUCCESS ) {
-                                               ldap_install_tls( lsc->msc_ld );
+                                               ldap_install_tls( msc->msc_ld );
 
                                        } else if ( rs->sr_err == LDAP_REFERRAL ) {
                                                rs->sr_err = LDAP_OTHER;
@@ -297,7 +306,7 @@ retry:;
                /*
                 * use synchronous StartTLS
                 */
-               rs->sr_err = ldap_start_tls_s( lsc->msc_ld, NULL, NULL );
+               rs->sr_err = ldap_start_tls_s( msc->msc_ld, NULL, NULL );
 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
 
                /* if StartTLS is requested, only attempt it if the URL
@@ -305,9 +314,9 @@ retry:;
                 * of misconfiguration, but also when used in the chain 
                 * overlay, where the "uri" can be parsed out of a referral */
                if ( rs->sr_err == LDAP_SERVER_DOWN
-                               || ( rs->sr_err != LDAP_SUCCESS && LDAP_BACK_TLS_CRITICAL( li ) ) )
+                               || ( rs->sr_err != LDAP_SUCCESS && LDAP_BACK_TLS_CRITICAL( mi ) ) )
                {
-                       ldap_unbind_ext_s( lsc->msc_ld, NULL, NULL );
+                       ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
                        goto error_return;
                }
        }
@@ -316,26 +325,21 @@ retry:;
        /*
         * Set the network timeout if set
         */
-       if ( li->mi_network_timeout != 0 ) {
+       if ( mi->mi_network_timeout != 0 ) {
                struct timeval  network_timeout;
 
                network_timeout.tv_usec = 0;
-               network_timeout.tv_sec = li->mi_network_timeout;
+               network_timeout.tv_sec = mi->mi_network_timeout;
 
-               ldap_set_option( lsc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
+               ldap_set_option( msc->msc_ld, LDAP_OPT_NETWORK_TIMEOUT,
                                (void *)&network_timeout );
        }
 
-       /*
-        * Sets a cookie for the rewrite session
-        */
-       ( void )rewrite_session_init( lt->mt_rwmap.rwm_rw, op->o_conn );
-
        /*
         * If the connection DN is not null, an attempt to rewrite it is made
         */
        if ( !BER_BVISEMPTY( &op->o_conn->c_dn ) ) {
-               dc.rwmap = &lt->mt_rwmap;
+               dc.target = mt;
                dc.conn = op->o_conn;
                dc.rs = rs;
                dc.ctx = "bindDN";
@@ -344,41 +348,92 @@ retry:;
                 * Rewrite the bind dn if needed
                 */
                if ( ldap_back_dn_massage( &dc, &op->o_conn->c_dn,
-                                       &lsc->msc_bound_ndn ) )
+                                       &msc->msc_bound_ndn ) )
                {
                        goto error_return;
                }
 
                /* copy the DN idf needed */
-               if ( lsc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
-                       ber_dupbv( &lsc->msc_bound_ndn, &op->o_conn->c_dn );
+               if ( msc->msc_bound_ndn.bv_val == op->o_conn->c_dn.bv_val ) {
+                       ber_dupbv( &msc->msc_bound_ndn, &op->o_conn->c_dn );
                }
 
-               assert( !BER_BVISNULL( &lsc->msc_bound_ndn ) );
+               assert( !BER_BVISNULL( &msc->msc_bound_ndn ) );
 
        } else {
-               ber_str2bv( "", 0, 1, &lsc->msc_bound_ndn );
+               ber_str2bv( "", 0, 1, &msc->msc_bound_ndn );
        }
 
-       lsc->msc_bound = META_UNBOUND;
+       msc->msc_bound = META_UNBOUND;
 
 error_return:;
-       if ( rs->sr_err != LDAP_SUCCESS ) {
+       if ( rs->sr_err == LDAP_SUCCESS ) {
+               /*
+                * Sets a cookie for the rewrite session
+                */
+               ( void )rewrite_session_init( mt->mt_rwmap.rwm_rw, op->o_conn );
+
+       } else {
                rs->sr_err = slap_map_api2result( rs );
                if ( sendok & LDAP_BACK_SENDERR ) {
                        send_ldap_result( op, rs );
                        rs->sr_text = NULL;
                }
+       }
 
-       } else {
+       return rs->sr_err;
+}
 
-               /*
-                * The candidate is activated
-                */
-               *candidate = META_CANDIDATE;
+/*
+ * meta_back_retry
+ * 
+ * Retries one connection
+ */
+int
+meta_back_retry(
+       Operation               *op,
+       SlapReply               *rs,
+       metaconn_t              *mc,
+       int                     candidate,
+       ldap_back_send_t        sendok )
+{
+       metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
+       metatarget_t            *mt = &mi->mi_targets[ candidate ];
+       int                     rc = LDAP_UNAVAILABLE;
+       metasingleconn_t        *msc = &mc->mc_conns[ candidate ];
+
+retry_lock:;
+       ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+
+       assert( mc->mc_refcnt > 0 );
+
+       if ( mc->mc_refcnt == 1 ) {
+               while ( ldap_pvt_thread_mutex_trylock( &mc->mc_mutex ) ) {
+                       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
+                       ldap_pvt_thread_yield();
+                       goto retry_lock;
+               }
+
+               ldap_unbind_ext_s( msc->msc_ld, NULL, NULL );
+               msc->msc_ld = NULL;
+               msc->msc_bound = 0;
+
+               ( void )rewrite_session_delete( mt->mt_rwmap.rwm_rw, op->o_conn );
+
+               /* mc here must be the regular mc, reset and ready for init */
+               rc = meta_back_init_one_conn( op, rs, mt, msc, sendok );
+
+               if ( rc == LDAP_SUCCESS ) {
+                       rc = meta_back_single_dobind( op, rs, mc, candidate,
+                                       sendok, mt->mt_nretries, 0 );
+               }
+
+               ldap_pvt_thread_mutex_unlock( &mc->mc_mutex );
        }
 
-       return rs->sr_err;
+       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
+
+       return rc == LDAP_SUCCESS ? 1 : 0;
 }
 
 /*
@@ -412,14 +467,14 @@ meta_back_get_candidate(
        SlapReply       *rs,
        struct berval   *ndn )
 {
-       struct metainfo *li = ( struct metainfo * )op->o_bd->be_private;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
        int             candidate;
 
        /*
         * tries to get a unique candidate
         * (takes care of default target)
         */
-       candidate = meta_back_select_unique_candidate( li, ndn );
+       candidate = meta_back_select_unique_candidate( mi, ndn );
 
        /*
         * if any is found, inits the connection
@@ -469,10 +524,12 @@ meta_back_get_candidate(
                        /* if multiple candidates can serve the operation,
                         * and a default target is defined, and it is
                         * a candidate, try using it (FIXME: YMMV) */
-                       if ( li->mi_defaulttarget != META_DEFAULT_TARGET_NONE
-                               && meta_back_is_candidate( &li->mi_targets[ li->mi_defaulttarget ]->mt_nsuffix, ndn ) )
+                       if ( mi->mi_defaulttarget != META_DEFAULT_TARGET_NONE
+                               && meta_back_is_candidate( &mi->mi_targets[ mi->mi_defaulttarget ].mt_nsuffix,
+                                               mi->mi_targets[ mi->mi_defaulttarget ].mt_scope,
+                                               ndn, op->o_tag == LDAP_REQ_SEARCH ? op->ors_scope : LDAP_SCOPE_BASE ) )
                        {
-                               candidate = li->mi_defaulttarget;
+                               candidate = mi->mi_defaulttarget;
                                rs->sr_err = LDAP_SUCCESS;
                                rs->sr_text = NULL;
 
@@ -482,43 +539,69 @@ meta_back_get_candidate(
                        }
                        break;
                }
+
+       } else {
+               rs->sr_err = LDAP_SUCCESS;
        }
 
        return candidate;
 }
 
+static void    *meta_back_candidates_dummy;
+
 static void
-meta_back_candidate_keyfree( void *key, void *data )
+meta_back_candidates_keyfree(
+       void            *key,
+       void            *data )
 {
+       metacandidates_t        *mc = (metacandidates_t *)data;
+
+       ber_memfree_x( mc->mc_candidates, NULL );
        ber_memfree_x( data, NULL );
 }
 
-char *
+SlapReply *
 meta_back_candidates_get( Operation *op )
 {
-       struct metainfo *li = ( struct metainfo * )op->o_bd->be_private;
-       void            *data = NULL;
+       metainfo_t              *mi = ( metainfo_t * )op->o_bd->be_private;
+       metacandidates_t        *mc;
 
        if ( op->o_threadctx ) {
+               void            *data = NULL;
+
                ldap_pvt_thread_pool_getkey( op->o_threadctx,
-                               meta_back_candidate_keyfree, &data, NULL );
+                               &meta_back_candidates_dummy, &data, NULL );
+               mc = (metacandidates_t *)data;
+
        } else {
-               data = (void *)li->mi_candidates;
+               mc = mi->mi_candidates;
        }
 
-       if ( data == NULL ) {
-               data = ber_memalloc_x( sizeof( char ) * li->mi_ntargets, NULL );
+       if ( mc == NULL ) {
+               mc = ch_calloc( sizeof( metacandidates_t ), 1 );
+               mc->mc_ntargets = mi->mi_ntargets;
+               mc->mc_candidates = ch_calloc( sizeof( SlapReply ), mc->mc_ntargets );
                if ( op->o_threadctx ) {
+                       void            *data = NULL;
+
+                       data = (void *)mc;
                        ldap_pvt_thread_pool_setkey( op->o_threadctx,
-                                       meta_back_candidate_keyfree, data,
-                                       meta_back_candidate_keyfree );
+                                       &meta_back_candidates_dummy, data,
+                                       meta_back_candidates_keyfree );
 
                } else {
-                       li->mi_candidates = (char *)data;
+                       mi->mi_candidates = mc;
                }
+
+       } else if ( mc->mc_ntargets < mi->mi_ntargets ) {
+               /* NOTE: in the future, may want to allow back-config
+                * to add/remove targets from back-meta... */
+               mc->mc_ntargets = mi->mi_ntargets;
+               mc->mc_candidates = ch_realloc( mc->mc_candidates,
+                               sizeof( SlapReply ) * mc->mc_ntargets );
        }
 
-       return (char *)data;
+       return mc->mc_candidates;
 }
 
 /*
@@ -554,40 +637,47 @@ meta_back_candidates_get( Operation *op )
  *   that exactly none (noSuchObject) or one (TRUE/FALSE/UNDEFINED) is
  *   returned.
  */
-struct metaconn *
+metaconn_t *
 meta_back_getconn(
-               Operation               *op,
-               SlapReply               *rs,
-               int                     *candidate,
-               ldap_back_send_t        sendok )
+               Operation               *op,
+       SlapReply               *rs,
+       int                     *candidate,
+       ldap_back_send_t        sendok )
 {
-       struct metainfo *li = ( struct metainfo * )op->o_bd->be_private;
-       struct metaconn *lc, lc_curr;
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
+       metaconn_t      *mc = NULL,
+                       mc_curr = { 0 };
        int             cached = META_TARGET_NONE,
                        i = META_TARGET_NONE,
                        err = LDAP_SUCCESS,
-                       new_conn = 0;
+                       new_conn = 0,
+                       ncandidates = 0;
+
 
        meta_op_type    op_type = META_OP_REQUIRE_SINGLE;
        int             parent = 0,
                        newparent = 0;
-       struct berval   ndn = op->o_req_ndn;
+       struct berval   ndn = op->o_req_ndn,
+                       pndn;
 
-       char            *candidates = meta_back_candidates_get( op );
+       SlapReply       *candidates = meta_back_candidates_get( op );
 
        /* Searches for a metaconn in the avl tree */
-       lc_curr.mc_conn = op->o_conn;
-       ldap_pvt_thread_mutex_lock( &li->mi_conn_mutex );
-       lc = (struct metaconn *)avl_find( li->mi_conntree, 
-               (caddr_t)&lc_curr, meta_back_conn_cmp );
-       ldap_pvt_thread_mutex_unlock( &li->mi_conn_mutex );
+       mc_curr.mc_conn = op->o_conn;
+       ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+       mc = (metaconn_t *)avl_find( mi->mi_conntree, 
+               (caddr_t)&mc_curr, meta_back_conn_cmp );
+       if ( mc ) {
+               mc->mc_refcnt++;
+       }
+       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
 
        switch ( op->o_tag ) {
        case LDAP_REQ_ADD:
                /* if we go to selection, the entry must not exist,
                 * and we must be able to resolve the parent */
                parent = 1;
-               dnParent( &ndn, &ndn );
+               dnParent( &ndn, &pndn );
                break;
 
        case LDAP_REQ_MODRDN:
@@ -628,49 +718,78 @@ meta_back_getconn(
        if ( op_type == META_OP_REQUIRE_ALL ) {
 
                /* Looks like we didn't get a bind. Open a new session... */
-               if ( !lc ) {
-                       lc = metaconn_alloc( li->mi_ntargets );
-                       lc->mc_conn = op->o_conn;
+               if ( mc == NULL ) {
+                       mc = metaconn_alloc( op );
+                       mc->mc_conn = op->o_conn;
                        new_conn = 1;
                }
 
-               for ( i = 0; i < li->mi_ntargets; i++ ) {
+               for ( i = 0; i < mi->mi_ntargets; i++ ) {
 
                        /*
                         * The target is activated; if needed, it is
                         * also init'd
                         */
-                       int lerr = init_one_conn( op, rs, li->mi_targets[ i ],
-                                       &lc->mc_conns[ i ], &candidates[ i ],
-                                       sendok );
-                       if ( lerr != LDAP_SUCCESS ) {
+                       candidates[ i ].sr_err =
+                               meta_back_init_one_conn( op, rs,
+                                               &mi->mi_targets[ i ],
+                                               &mc->mc_conns[ i ], sendok );
+                       if ( candidates[ i ].sr_err == LDAP_SUCCESS ) {
+                               candidates[ i ].sr_tag = META_CANDIDATE;
+                               ncandidates++;
+                               
+                       } else {
                                
                                /*
                                 * FIXME: in case one target cannot
                                 * be init'd, should the other ones
                                 * be tried?
                                 */
-                               candidates[ i ] = META_NOT_CANDIDATE;
-#if 0
-                               ( void )meta_clear_one_candidate( &lc->mc_conns[ i ] );
-#endif
-                               err = lerr;
+                               candidates[ i ].sr_tag = META_NOT_CANDIDATE;
+                               err = candidates[ i ].sr_err;
                                continue;
                        }
                }
+
+               if ( ncandidates == 0 ) {
+                       if ( new_conn ) {
+                               meta_back_freeconn( op, mc );
+
+                       } else {
+                               meta_back_release_conn( op, mc );
+                       }
+
+                       rs->sr_err = LDAP_NO_SUCH_OBJECT;
+                       rs->sr_text = "Unable to select valid candidates";
+
+                       if ( sendok & LDAP_BACK_SENDERR ) {
+                               if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
+                                       rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
+                               }
+                               send_ldap_result( op, rs );
+                               rs->sr_text = NULL;
+                               rs->sr_matched = NULL;
+                       }
+
+                       return NULL;
+               }
+
                goto done;
        }
        
        /*
         * looks in cache, if any
         */
-       if ( li->mi_cache.ttl != META_DNCACHE_DISABLED ) {
-               cached = i = meta_dncache_get_target( &li->mi_cache, &op->o_req_ndn );
+       if ( mi->mi_cache.ttl != META_DNCACHE_DISABLED ) {
+               cached = i = meta_dncache_get_target( &mi->mi_cache, &op->o_req_ndn );
        }
 
        if ( op_type == META_OP_REQUIRE_SINGLE ) {
+               int     j;
 
-               memset( candidates, META_NOT_CANDIDATE, sizeof( char ) * li->mi_ntargets );
+               for ( j = 0; j < mi->mi_ntargets; j++ ) {
+                       candidates[ j ].sr_tag = META_NOT_CANDIDATE;
+               }
 
                /*
                 * tries to get a unique candidate
@@ -679,72 +798,102 @@ meta_back_getconn(
                if ( i == META_TARGET_NONE ) {
                        i = meta_back_get_candidate( op, rs, &ndn );
 
+                       if ( rs->sr_err == LDAP_NO_SUCH_OBJECT && parent ) {
+                               i = meta_back_get_candidate( op, rs, &pndn );
+                       }
+       
                        if ( rs->sr_err != LDAP_SUCCESS ) {
+                               if ( mc != NULL ) {
+                                       meta_back_release_conn( op, mc );
+                               }
+
                                if ( sendok & LDAP_BACK_SENDERR ) {
+                                       if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
+                                               rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
+                                       }
                                        send_ldap_result( op, rs );
                                        rs->sr_text = NULL;
+                                       rs->sr_matched = NULL;
                                }
+                       
                                return NULL;
                        }
                }
 
                if ( newparent && meta_back_get_candidate( op, rs, op->orr_nnewSup ) != i )
                {
+                       if ( mc != NULL ) {
+                               meta_back_release_conn( op, mc );
+                       }
+
                        rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
                        rs->sr_text = "cross-target rename not supported";
                        if ( sendok & LDAP_BACK_SENDERR ) {
                                send_ldap_result( op, rs );
                                rs->sr_text = NULL;
                        }
+
                        return NULL;
                }
 
-               Debug( LDAP_DEBUG_CACHE,
+               Debug( LDAP_DEBUG_TRACE,
        "==>meta_back_getconn: got target %d for ndn=\"%s\" from cache\n",
                                i, op->o_req_ndn.bv_val, 0 );
 
-               /* Retries searching for a metaconn in the avl tree */
-               lc_curr.mc_conn = op->o_conn;
-               ldap_pvt_thread_mutex_lock( &li->mi_conn_mutex );
-               lc = (struct metaconn *)avl_find( li->mi_conntree, 
-                       (caddr_t)&lc_curr, meta_back_conn_cmp );
-               ldap_pvt_thread_mutex_unlock( &li->mi_conn_mutex );
+               if ( mc == NULL ) {
+                       /* Retries searching for a metaconn in the avl tree
+                        * the reason is that the connection might have been
+                        * created by meta_back_get_candidate() */
+                       mc_curr.mc_conn = op->o_conn;
+                       ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+                       mc = (metaconn_t *)avl_find( mi->mi_conntree, 
+                               (caddr_t)&mc_curr, meta_back_conn_cmp );
+                       if ( mc != NULL ) {
+                               mc->mc_refcnt++;
+                       }
+                       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
 
-               /* Looks like we didn't get a bind. Open a new session... */
-               if ( !lc ) {
-                       lc = metaconn_alloc( li->mi_ntargets );
-                       lc->mc_conn = op->o_conn;
-                       new_conn = 1;
+                       /* Looks like we didn't get a bind. Open a new session... */
+                       if ( mc == NULL ) {
+                               mc = metaconn_alloc( op );
+                               mc->mc_conn = op->o_conn;
+                               new_conn = 1;
+                       }
                }
 
                /*
                 * Clear all other candidates
                 */
-               ( void )meta_clear_unused_candidates( op, lc, i );
+               ( void )meta_clear_unused_candidates( op, i );
 
                /*
                 * The target is activated; if needed, it is
-                * also init'd. In case of error, init_one_conn
+                * also init'd. In case of error, meta_back_init_one_conn
                 * sends the appropriate result.
                 */
-               err = init_one_conn( op, rs, li->mi_targets[ i ],
-                               &lc->mc_conns[ i ], &candidates[ i ],
-                               sendok );
+               err = meta_back_init_one_conn( op, rs, &mi->mi_targets[ i ],
+                               &mc->mc_conns[ i ], sendok );
                if ( err != LDAP_SUCCESS ) {
-               
                        /*
                         * FIXME: in case one target cannot
                         * be init'd, should the other ones
                         * be tried?
                         */
-                       candidates[ i ] = META_NOT_CANDIDATE;
+                       candidates[ i ].sr_tag = META_NOT_CANDIDATE;
                        if ( new_conn ) {
-                               ( void )meta_clear_one_candidate( &lc->mc_conns[ i ] );
-                               metaconn_free( lc );
+                               (void)meta_clear_one_candidate( &mc->mc_conns[ i ] );
+                               meta_back_freeconn( op, mc );
+
+                       } else {
+                               meta_back_release_conn( op, mc );
                        }
                        return NULL;
                }
 
+               candidates[ i ].sr_err = LDAP_SUCCESS;
+               candidates[ i ].sr_tag = META_CANDIDATE;
+               ncandidates++;
+
                if ( candidate ) {
                        *candidate = i;
                }
@@ -755,50 +904,88 @@ meta_back_getconn(
        } else {
 
                /* Looks like we didn't get a bind. Open a new session... */
-               if ( !lc ) {
-                       lc = metaconn_alloc( li->mi_ntargets );
-                       lc->mc_conn = op->o_conn;
+               if ( mc == NULL ) {
+                       mc = metaconn_alloc( op );
+                       mc->mc_conn = op->o_conn;
                        new_conn = 1;
                }
 
-               for ( i = 0; i < li->mi_ntargets; i++ ) {
+               for ( i = 0; i < mi->mi_ntargets; i++ ) {
                        if ( i == cached 
-                               || meta_back_is_candidate( &li->mi_targets[ i ]->mt_nsuffix,
-                                               &op->o_req_ndn ) )
+                               || meta_back_is_candidate( &mi->mi_targets[ i ].mt_nsuffix,
+                                               mi->mi_targets[ i ].mt_scope,
+                                               &op->o_req_ndn, LDAP_SCOPE_SUBTREE ) )
                        {
 
                                /*
                                 * The target is activated; if needed, it is
                                 * also init'd
                                 */
-                               int lerr = init_one_conn( op, rs,
-                                               li->mi_targets[ i ],
-                                               &lc->mc_conns[ i ],
-                                               &candidates[ i ],
-                                               sendok );
-                               if ( lerr != LDAP_SUCCESS ) {
+                               int lerr = meta_back_init_one_conn( op, rs,
+                                               &mi->mi_targets[ i ],
+                                               &mc->mc_conns[ i ], sendok );
+                               if ( lerr == LDAP_SUCCESS ) {
+                                       candidates[ i ].sr_tag = META_CANDIDATE;
+                                       candidates[ i ].sr_err = LDAP_SUCCESS;
+                                       ncandidates++;
+
+                                       Debug( LDAP_DEBUG_TRACE, "%s: meta_back_init_one_conn(%d)\n",
+                                               op->o_log_prefix, i, 0 );
+
+                               } else {
                                
                                        /*
                                         * FIXME: in case one target cannot
                                         * be init'd, should the other ones
                                         * be tried?
                                         */
-                                       candidates[ i ] = META_NOT_CANDIDATE;
-#if 0
-                                       ( void )meta_clear_one_candidate( &lc->mc_conns[ i ] );
-#endif
+                                       if ( new_conn ) {
+                                               ( void )meta_clear_one_candidate( &mc->mc_conns[ i ] );
+                                       }
+                                       /* leave the target candidate, but record the error for later use */
+                                       candidates[ i ].sr_err = lerr;
                                        err = lerr;
+
+                                       Debug( LDAP_DEBUG_ANY, "%s: meta_back_init_one_conn(%d) failed: %d\n",
+                                               op->o_log_prefix, i, lerr );
+
                                        continue;
                                }
 
                        } else {
-                               candidates[ i ] = META_NOT_CANDIDATE;
+                               if ( new_conn ) {
+                                       ( void )meta_clear_one_candidate( &mc->mc_conns[ i ] );
+                               }
+                               candidates[ i ].sr_tag = META_NOT_CANDIDATE;
                        }
                }
+
+               if ( ncandidates == 0 ) {
+                       if ( new_conn ) {
+                               meta_back_freeconn( op, mc );
+
+                       } else {
+                               meta_back_release_conn( op, mc );
+                       }
+
+                       rs->sr_err = LDAP_NO_SUCH_OBJECT;
+                       rs->sr_text = "Unable to select valid candidates";
+
+                       if ( sendok & LDAP_BACK_SENDERR ) {
+                               if ( rs->sr_err == LDAP_NO_SUCH_OBJECT ) {
+                                       rs->sr_matched = op->o_bd->be_suffix[ 0 ].bv_val;
+                               }
+                               send_ldap_result( op, rs );
+                               rs->sr_text = NULL;
+                               rs->sr_matched = NULL;
+                       }
+
+                       return NULL;
+               }
        }
 
 done:;
-       /* clear out init_one_conn non-fatal errors */
+       /* clear out meta_back_init_one_conn non-fatal errors */
        rs->sr_err = LDAP_SUCCESS;
        rs->sr_text = NULL;
 
@@ -807,27 +994,30 @@ done:;
                /*
                 * Inserts the newly created metaconn in the avl tree
                 */
-               ldap_pvt_thread_mutex_lock( &li->mi_conn_mutex );
-               err = avl_insert( &li->mi_conntree, ( caddr_t )lc,
+               ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+               err = avl_insert( &mi->mi_conntree, ( caddr_t )mc,
                                meta_back_conn_cmp, meta_back_conn_dup );
 
 #if PRINT_CONNTREE > 0
-               myprint( li->mi_conntree );
+               myprint( mi->mi_conntree );
 #endif /* PRINT_CONNTREE */
                
-               ldap_pvt_thread_mutex_unlock( &li->mi_conn_mutex );
+               ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
 
-               Debug( LDAP_DEBUG_TRACE,
-                       "=>meta_back_getconn: conn %ld inserted\n",
-                       lc->mc_conn->c_connid, 0, 0 );
-               
                /*
                 * Err could be -1 in case a duplicate metaconn is inserted
+                *
+                * FIXME: what if the same client issues more than one
+                * asynchronous operations?
                 */
                if ( err != 0 ) {
+                       Debug( LDAP_DEBUG_ANY,
+                               "%s meta_back_getconn: candidates=%d conn=%ld insert failed\n",
+                               op->o_log_prefix, ncandidates, mc->mc_conn->c_connid );
+               
                        rs->sr_err = LDAP_OTHER;
                        rs->sr_text = "Internal server error";
-                       metaconn_free( lc );
+                       meta_back_freeconn( op, mc );
                        if ( sendok & LDAP_BACK_SENDERR ) {
                                send_ldap_result( op, rs );
                                rs->sr_text = NULL;
@@ -835,12 +1025,30 @@ done:;
                        return NULL;
                }
 
+               Debug( LDAP_DEBUG_TRACE,
+                       "%s meta_back_getconn: candidates=%d conn=%ld inserted\n",
+                       op->o_log_prefix, ncandidates, mc->mc_conn->c_connid );
+
        } else {
                Debug( LDAP_DEBUG_TRACE,
-                       "=>meta_back_getconn: conn %ld fetched\n",
-                       lc->mc_conn->c_connid, 0, 0 );
+                       "%s meta_back_getconn: candidates=%d conn=%ld fetched\n",
+                       op->o_log_prefix, ncandidates, mc->mc_conn->c_connid );
        }
        
-       return lc;
+       return mc;
 }
 
+void
+meta_back_release_conn(
+               Operation               *op,
+       metaconn_t              *mc )
+{
+       metainfo_t      *mi = ( metainfo_t * )op->o_bd->be_private;
+
+       assert( mc != NULL );
+
+       ldap_pvt_thread_mutex_lock( &mi->mi_conn_mutex );
+       assert( mc->mc_refcnt > 0 );
+       mc->mc_refcnt--;
+       ldap_pvt_thread_mutex_unlock( &mi->mi_conn_mutex );
+}